telnet.c 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. /**
  2. * Test the telnet functions.
  3. *
  4. * Perform a test using the telnet functions.
  5. * This code exports two new global functions:
  6. *
  7. * void telnet_listenForClients(void (*callback)(uint8_t *buffer, size_t size))
  8. * void telnet_sendData(uint8_t *buffer, size_t size)
  9. *
  10. * For additional details and documentation see:
  11. * * Free book on ESP32 - https://leanpub.com/kolban-ESP32
  12. *
  13. *
  14. * Neil Kolban <kolban1@kolban.com>
  15. *
  16. * ****************************
  17. * Additional portions were taken from
  18. * https://github.com/PocketSprite/8bkc-sdk/blob/master/8bkc-components/8bkc-hal/vfs-stdout.c
  19. *
  20. */
  21. #include "telnet.h"
  22. #include "Config.h"
  23. #include "accessors.h"
  24. #include "config.h"
  25. #include "driver/uart.h"
  26. #include "esp_app_trace.h"
  27. #include "esp_attr.h"
  28. #include "esp_vfs.h"
  29. #include "esp_vfs_dev.h"
  30. #include "freertos/ringbuf.h"
  31. #include "libtelnet.h"
  32. #include "messaging.h"
  33. #include "platform_esp32.h"
  34. #include "sdkconfig.h"
  35. #include "soc/uart_struct.h"
  36. #include "stdbool.h"
  37. #include "tools.h"
  38. #include <errno.h>
  39. #include <esp_log.h>
  40. #include <lwip/def.h>
  41. #include <lwip/sockets.h>
  42. #include <stdlib.h> // Required for libtelnet.h
  43. #include <string.h>
  44. /************************************
  45. * Globals
  46. */
  47. #define TELNET_STACK_SIZE 4096
  48. #define TELNET_RX_BUF 1024
  49. struct telnetUserData {
  50. int sockfd;
  51. telnet_t* tnHandle;
  52. char* rxbuf;
  53. };
  54. const static char TAG[] = "telnet";
  55. static int uart_fd;
  56. static RingbufHandle_t buf_handle;
  57. static size_t send_chunk = 512;
  58. static size_t log_buf_size = 4 * 1024;
  59. static bool bIsEnabled = false;
  60. static int partnerSocket;
  61. static telnet_t* tnHandle;
  62. /************************************
  63. * Forward declarations
  64. */
  65. static void telnet_task(void* data);
  66. static int stdout_open(const char* path, int flags, int mode);
  67. static int stdout_fstat(int fd, struct stat* st);
  68. static ssize_t stdout_write(int fd, const void* data, size_t size);
  69. static void handle_telnet_conn();
  70. static size_t process_logs(UBaseType_t bytes, bool make_room);
  71. static sys_telnet_config* telnet_svc = NULL;
  72. void init_telnet() {
  73. if (!sys_services_config_TELNET(telnet_svc) || telnet_svc->enable == sys_telnet_output_SERIAL_ONLY) {
  74. ESP_LOGI(TAG, "Telnet support disabled");
  75. return;
  76. }
  77. ESP_LOGI(TAG, "Starting Telnet service");
  78. ESP_LOGD(TAG, "Getting values from configuration");
  79. if (telnet_svc->block > 0) send_chunk = telnet_svc->block;
  80. if (telnet_svc->block > 0) log_buf_size = telnet_svc->buffer;
  81. ESP_LOGD(TAG, "Allocating memory for the ring buffer and storage. send_chunk: %d, log_buf_size: %d", send_chunk, log_buf_size);
  82. // Redirect the output to our telnet handler as soon as possible
  83. StaticRingbuffer_t* buffer_struct = (StaticRingbuffer_t*)heap_caps_malloc(sizeof(StaticRingbuffer_t), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
  84. // All non-split ring buffer must have their memory alignment set to 32 bits.
  85. uint8_t* buffer_storage = (uint8_t*)heap_caps_malloc(sizeof(uint8_t) * log_buf_size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
  86. buf_handle = xRingbufferCreateStatic(log_buf_size, RINGBUF_TYPE_BYTEBUF, buffer_storage, buffer_struct);
  87. if (buf_handle == NULL || buffer_struct == NULL) {
  88. ESP_LOGE(TAG, "Failed to create ring buffer for telnet!");
  89. messaging_post_message(MESSAGING_ERROR, MESSAGING_CLASS_SYSTEM, "Failed to allocate memory for telnet buffer");
  90. return;
  91. }
  92. if (telnet_svc->enable == sys_telnet_output_TELNET) {
  93. ESP_LOGI(TAG, "***Redirecting log output to telnet");
  94. } else {
  95. ESP_LOGI(TAG, "Instantiating telnet service");
  96. }
  97. esp_vfs_t vfs = {};
  98. vfs.flags = ESP_VFS_FLAG_DEFAULT;
  99. vfs.write = &stdout_write;
  100. vfs.open = &stdout_open;
  101. vfs.fstat = &stdout_fstat;
  102. if (telnet_svc->enable == sys_telnet_output_TELNET_SERIAL) uart_fd = open("/dev/uart/0", O_RDWR);
  103. ESP_ERROR_CHECK(esp_vfs_register("/dev/pkspstdout", &vfs, NULL));
  104. freopen("/dev/pkspstdout", "w", stdout);
  105. freopen("/dev/pkspstdout", "w", stderr);
  106. bIsEnabled = true;
  107. }
  108. void start_telnet(void* pvParameter) {
  109. static bool isStarted = false;
  110. if (isStarted || !bIsEnabled) return;
  111. isStarted = true;
  112. StaticTask_t* xTaskBuffer = (StaticTask_t*)heap_caps_malloc(sizeof(StaticTask_t), MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
  113. StackType_t* xStack = heap_caps_malloc(TELNET_STACK_SIZE, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
  114. xTaskCreateStatic((TaskFunction_t)&telnet_task, "telnet", TELNET_STACK_SIZE, NULL, ESP_TASK_PRIO_MIN, xStack, xTaskBuffer);
  115. }
  116. static void telnet_task(void* data) {
  117. int serverSocket;
  118. struct sockaddr_in serverAddr;
  119. serverAddr.sin_family = AF_INET;
  120. serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
  121. serverAddr.sin_port = htons(23);
  122. while (1) {
  123. serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  124. if (bind(serverSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) >= 0 && listen(serverSocket, 1) >= 0) break;
  125. close(serverSocket);
  126. ESP_LOGI(TAG, "can't bind Telnet socket");
  127. vTaskDelay(pdMS_TO_TICKS(1000));
  128. }
  129. while (1) {
  130. socklen_t len = sizeof(serverAddr);
  131. int sock = accept(serverSocket, (struct sockaddr*)&serverAddr, &len);
  132. if (sock >= 0) {
  133. partnerSocket = sock;
  134. ESP_LOGI(TAG, "We have a new client connection %d", sock);
  135. handle_telnet_conn();
  136. ESP_LOGI(TAG, "Telnet connection terminated %d", sock);
  137. } else {
  138. ESP_LOGW(TAG, "accept: %d (%s)", errno, strerror(errno));
  139. }
  140. }
  141. // we should not be here
  142. close(serverSocket);
  143. vTaskDelete(NULL);
  144. }
  145. /**
  146. * Telnet handler.
  147. */
  148. static void handle_telnet_events(telnet_t* thisTelnet, telnet_event_t* event, void* userData) {
  149. struct telnetUserData* telnetUserData = (struct telnetUserData*)userData;
  150. switch (event->type) {
  151. case TELNET_EV_SEND:
  152. send(telnetUserData->sockfd, event->data.buffer, event->data.size, 0);
  153. break;
  154. case TELNET_EV_DATA:
  155. console_push(event->data.buffer, event->data.size);
  156. break;
  157. case TELNET_EV_TTYPE:
  158. telnet_ttype_send(telnetUserData->tnHandle);
  159. break;
  160. default:
  161. break;
  162. }
  163. }
  164. static size_t process_logs(UBaseType_t bytes, bool make_room) {
  165. UBaseType_t pending;
  166. vRingbufferGetInfo(buf_handle, NULL, NULL, NULL, NULL, &pending);
  167. // nothing to do or we can do
  168. if (!partnerSocket || (make_room && log_buf_size - pending > bytes)) return pending;
  169. // can't send more than what we have
  170. if (bytes > pending) bytes = pending;
  171. while (bytes > 0) {
  172. size_t size;
  173. char* item = (char*)xRingbufferReceiveUpTo(buf_handle, &size, pdMS_TO_TICKS(50), bytes);
  174. if (!item || !partnerSocket) break;
  175. bytes -= size;
  176. telnet_send_text(tnHandle, item, size);
  177. vRingbufferReturnItem(buf_handle, (void*)item);
  178. }
  179. return pending - bytes;
  180. }
  181. static void handle_telnet_conn() {
  182. static const telnet_telopt_t my_telopts[] = {{TELNET_TELOPT_ECHO, TELNET_WONT, TELNET_DO}, {TELNET_TELOPT_TTYPE, TELNET_WILL, TELNET_DONT},
  183. {TELNET_TELOPT_COMPRESS2, TELNET_WONT, TELNET_DO}, {TELNET_TELOPT_ZMP, TELNET_WONT, TELNET_DO}, {TELNET_TELOPT_MSSP, TELNET_WONT, TELNET_DO},
  184. {TELNET_TELOPT_BINARY, TELNET_WILL, TELNET_DO}, {TELNET_TELOPT_NAWS, TELNET_WILL, TELNET_DONT},
  185. {TELNET_TELOPT_LINEMODE, TELNET_WONT, TELNET_DO}, {-1, 0, 0}};
  186. struct telnetUserData* pTelnetUserData =
  187. (struct telnetUserData*)heap_caps_malloc(sizeof(struct telnetUserData), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
  188. tnHandle = telnet_init(my_telopts, handle_telnet_events, 0, pTelnetUserData);
  189. pTelnetUserData->rxbuf = (char*)heap_caps_malloc(TELNET_RX_BUF, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
  190. pTelnetUserData->tnHandle = tnHandle;
  191. pTelnetUserData->sockfd = partnerSocket;
  192. bool pending = true;
  193. while (1) {
  194. fd_set rfds, wfds;
  195. struct timeval timeout = {0, 200 * 1000};
  196. FD_ZERO(&rfds);
  197. FD_SET(partnerSocket, &rfds);
  198. FD_ZERO(&wfds);
  199. if (pending) FD_SET(partnerSocket, &wfds);
  200. int res = select(partnerSocket + 1, &rfds, &wfds, NULL, &timeout);
  201. if (res < 0) break;
  202. if (FD_ISSET(partnerSocket, &rfds)) {
  203. int len = recv(partnerSocket, pTelnetUserData->rxbuf, TELNET_RX_BUF, 0);
  204. if (!len) break;
  205. telnet_recv(tnHandle, pTelnetUserData->rxbuf, len);
  206. }
  207. if (FD_ISSET(partnerSocket, &wfds)) {
  208. pending = process_logs(send_chunk, false) > 0;
  209. } else {
  210. pending = true;
  211. }
  212. }
  213. telnet_free(tnHandle);
  214. tnHandle = NULL;
  215. free(pTelnetUserData->rxbuf);
  216. free(pTelnetUserData);
  217. close(partnerSocket);
  218. partnerSocket = 0;
  219. }
  220. // ******************* stdout/stderr Redirection to ringbuffer
  221. static ssize_t stdout_write(int fd, const void* data, size_t size) {
  222. // flush the buffer and send item
  223. if (buf_handle) {
  224. process_logs(size, true);
  225. xRingbufferSend(buf_handle, data, size, 0);
  226. }
  227. // mirror to uart if required
  228. return (telnet_svc->enable == sys_telnet_output_TELNET_SERIAL || !buf_handle) ? write(uart_fd, data, size) : size;
  229. }
  230. static int stdout_open(const char* path, int flags, int mode) { return 0; }
  231. static int stdout_fstat(int fd, struct stat* st) {
  232. st->st_mode = S_IFCHR;
  233. return 0;
  234. }