telnet.c 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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 <stdlib.h> // Required for libtelnet.h
  22. #include <esp_log.h>
  23. #include "libtelnet.h"
  24. #include "stdbool.h"
  25. #include <lwip/def.h>
  26. #include <lwip/sockets.h>
  27. #include <errno.h>
  28. #include <string.h>
  29. #include "sdkconfig.h"
  30. #include "freertos/ringbuf.h"
  31. #include "esp_app_trace.h"
  32. #include "telnet.h"
  33. #include "esp_vfs.h"
  34. #include "esp_vfs_dev.h"
  35. #include "esp_attr.h"
  36. #include "soc/uart_struct.h"
  37. #include "driver/uart.h"
  38. #include "config.h"
  39. #include "nvs_utilities.h"
  40. #include "platform_esp32.h"
  41. #include "messaging.h"
  42. #include "tools.h"
  43. /************************************
  44. * Globals
  45. */
  46. #define TELNET_STACK_SIZE 4096
  47. #define TELNET_RX_BUF 1024
  48. extern bool bypass_network_manager;
  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. static bool bMirrorToUART;
  63. /************************************
  64. * Forward declarations
  65. */
  66. static void telnet_task(void *data);
  67. static int stdout_open(const char * path, int flags, int mode);
  68. static int stdout_fstat(int fd, struct stat * st);
  69. static ssize_t stdout_write(int fd, const void * data, size_t size);
  70. static void handle_telnet_conn();
  71. static size_t process_logs( UBaseType_t bytes, bool make_room);
  72. void init_telnet(){
  73. char *val= get_nvs_value_alloc(NVS_TYPE_STR, "telnet_enable");
  74. if (!val || strlen(val) == 0 || !strcasestr("YXD",val) ) {
  75. ESP_LOGI(TAG,"Telnet support disabled");
  76. if(val) free(val);
  77. return;
  78. }
  79. // if wifi manager is bypassed, there will possibly be no wifi available
  80. bMirrorToUART = (strcasestr("D",val)!=NULL);
  81. if (!bMirrorToUART && bypass_network_manager){
  82. // This isn't supposed to happen, as telnet won't start if wifi manager isn't
  83. // started. So this is a safeguard only.
  84. ESP_LOGW(TAG,"Wifi manager is not active. Forcing console on Serial output.");
  85. }
  86. FREE_AND_NULL(val);
  87. val = get_nvs_value_alloc(NVS_TYPE_STR, "telnet_block");
  88. if (val){
  89. int size = atol(val);
  90. if (size > 0) send_chunk = size;
  91. free(val);
  92. }
  93. val = get_nvs_value_alloc(NVS_TYPE_STR, "telnet_buffer");
  94. if (val){
  95. int size = atol(val);
  96. if (size > 0) log_buf_size = size;
  97. free(val);
  98. }
  99. // Redirect the output to our telnet handler as soon as possible
  100. StaticRingbuffer_t *buffer_struct = (StaticRingbuffer_t *) heap_caps_malloc(sizeof(StaticRingbuffer_t), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
  101. // All non-split ring buffer must have their memory alignment set to 32 bits.
  102. uint8_t *buffer_storage = (uint8_t *)heap_caps_malloc(sizeof(uint8_t)*log_buf_size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT );
  103. buf_handle = xRingbufferCreateStatic(log_buf_size, RINGBUF_TYPE_BYTEBUF, buffer_storage, buffer_struct);
  104. if (buf_handle == NULL) {
  105. ESP_LOGE(TAG,"Failed to create ring buffer for telnet!");
  106. messaging_post_message(MESSAGING_ERROR,MESSAGING_CLASS_SYSTEM,"Failed to allocate memory for telnet buffer");
  107. return;
  108. }
  109. ESP_LOGI(TAG, "***Redirecting log output to telnet");
  110. esp_vfs_t vfs = { };
  111. vfs.flags = ESP_VFS_FLAG_DEFAULT;
  112. vfs.write = &stdout_write;
  113. vfs.open = &stdout_open;
  114. vfs.fstat = &stdout_fstat;
  115. if (bMirrorToUART) uart_fd = open("/dev/uart/0", O_RDWR);
  116. ESP_ERROR_CHECK(esp_vfs_register("/dev/pkspstdout", &vfs, NULL));
  117. freopen("/dev/pkspstdout", "wb", stdout);
  118. freopen("/dev/pkspstdout", "wb", stderr);
  119. bIsEnabled=true;
  120. }
  121. void start_telnet(void * pvParameter){
  122. static bool isStarted=false;
  123. if (isStarted || !bIsEnabled) return;
  124. isStarted=true;
  125. StaticTask_t *xTaskBuffer = (StaticTask_t*) heap_caps_malloc(sizeof(StaticTask_t), MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
  126. StackType_t *xStack = heap_caps_malloc(TELNET_STACK_SIZE, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
  127. xTaskCreateStatic( (TaskFunction_t) &telnet_task, "telnet", TELNET_STACK_SIZE, NULL, ESP_TASK_PRIO_MIN, xStack, xTaskBuffer);
  128. }
  129. static void telnet_task(void *data) {
  130. int serverSocket;
  131. struct sockaddr_in serverAddr;
  132. serverAddr.sin_family = AF_INET;
  133. serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
  134. serverAddr.sin_port = htons(23);
  135. while (1) {
  136. serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  137. if (bind(serverSocket, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) >= 0 && listen(serverSocket, 1) >= 0) break;
  138. close(serverSocket);
  139. ESP_LOGI(TAG, "can't bind Telnet socket");
  140. vTaskDelay(pdMS_TO_TICKS(1000));
  141. }
  142. while (1) {
  143. socklen_t len = sizeof(serverAddr);
  144. int sock = accept(serverSocket, (struct sockaddr *)&serverAddr, &len);
  145. if (sock >= 0) {
  146. partnerSocket = sock;
  147. ESP_LOGI(TAG, "We have a new client connection %d", sock);
  148. handle_telnet_conn();
  149. ESP_LOGI(TAG, "Telnet connection terminated %d", sock);
  150. } else {
  151. ESP_LOGW(TAG, "accept: %d (%s)", errno, strerror(errno));
  152. }
  153. }
  154. // we should not be here
  155. close(serverSocket);
  156. vTaskDelete(NULL);
  157. }
  158. /**
  159. * Telnet handler.
  160. */
  161. static void handle_telnet_events(telnet_t *thisTelnet, telnet_event_t *event, void *userData) {
  162. struct telnetUserData *telnetUserData = (struct telnetUserData *)userData;
  163. switch(event->type) {
  164. case TELNET_EV_SEND:
  165. send(telnetUserData->sockfd, event->data.buffer, event->data.size, 0);
  166. break;
  167. case TELNET_EV_DATA:
  168. console_push(event->data.buffer, event->data.size);
  169. break;
  170. case TELNET_EV_TTYPE:
  171. telnet_ttype_send(telnetUserData->tnHandle);
  172. break;
  173. default:
  174. break;
  175. }
  176. }
  177. static size_t process_logs(UBaseType_t bytes, bool make_room){
  178. UBaseType_t pending;
  179. vRingbufferGetInfo(buf_handle, NULL, NULL, NULL, NULL, &pending);
  180. // nothing to do or we can do
  181. if (!partnerSocket || (make_room && log_buf_size - pending > bytes)) return pending;
  182. // can't send more than what we have
  183. if (bytes > pending) bytes = pending;
  184. while (bytes > 0) {
  185. size_t size;
  186. char *item = (char *)xRingbufferReceiveUpTo(buf_handle, &size, pdMS_TO_TICKS(50), bytes);
  187. if (!item || !partnerSocket) break;
  188. bytes -= size;
  189. telnet_send_text(tnHandle, item, size);
  190. vRingbufferReturnItem(buf_handle, (void *)item);
  191. }
  192. return pending - bytes;
  193. }
  194. static void handle_telnet_conn() {
  195. static const telnet_telopt_t my_telopts[] = {
  196. { TELNET_TELOPT_ECHO, TELNET_WONT, TELNET_DO },
  197. { TELNET_TELOPT_TTYPE, TELNET_WILL, TELNET_DONT },
  198. { TELNET_TELOPT_COMPRESS2, TELNET_WONT, TELNET_DO },
  199. { TELNET_TELOPT_ZMP, TELNET_WONT, TELNET_DO },
  200. { TELNET_TELOPT_MSSP, TELNET_WONT, TELNET_DO },
  201. { TELNET_TELOPT_BINARY, TELNET_WILL, TELNET_DO },
  202. { TELNET_TELOPT_NAWS, TELNET_WILL, TELNET_DONT },
  203. {TELNET_TELOPT_LINEMODE, TELNET_WONT, TELNET_DO },
  204. { -1, 0, 0 }
  205. };
  206. struct telnetUserData *pTelnetUserData = (struct telnetUserData *)heap_caps_malloc(sizeof(struct telnetUserData), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
  207. tnHandle = telnet_init(my_telopts, handle_telnet_events, 0, pTelnetUserData);
  208. pTelnetUserData->rxbuf = (char *) heap_caps_malloc(TELNET_RX_BUF, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
  209. pTelnetUserData->tnHandle = tnHandle;
  210. pTelnetUserData->sockfd = partnerSocket;
  211. bool pending = true;
  212. while(1) {
  213. fd_set rfds, wfds;
  214. struct timeval timeout = {0, 200*1000};
  215. FD_ZERO(&rfds);
  216. FD_SET(partnerSocket, &rfds);
  217. FD_ZERO(&wfds);
  218. if (pending) FD_SET(partnerSocket, &wfds);
  219. int res = select(partnerSocket + 1, &rfds, &wfds, NULL, &timeout);
  220. if (res < 0) break;
  221. if (FD_ISSET(partnerSocket, &rfds)) {
  222. int len = recv(partnerSocket, pTelnetUserData->rxbuf, TELNET_RX_BUF, 0);
  223. if (!len) break;
  224. telnet_recv(tnHandle, pTelnetUserData->rxbuf, len);
  225. }
  226. if (FD_ISSET(partnerSocket, &wfds)) {
  227. pending = process_logs(send_chunk, false) > 0;
  228. } else {
  229. pending = true;
  230. }
  231. }
  232. telnet_free(tnHandle);
  233. tnHandle = NULL;
  234. free(pTelnetUserData->rxbuf);
  235. free(pTelnetUserData);
  236. close(partnerSocket);
  237. partnerSocket = 0;
  238. }
  239. // ******************* stdout/stderr Redirection to ringbuffer
  240. static ssize_t stdout_write(int fd, const void * data, size_t size) {
  241. // flush the buffer and send item
  242. if (buf_handle) {
  243. process_logs(size, true);
  244. xRingbufferSend(buf_handle, data, size, 0);
  245. }
  246. // mirror to uart if required
  247. return (bMirrorToUART || !buf_handle) ? write(uart_fd, data, size) : size;
  248. }
  249. static int stdout_open(const char * path, int flags, int mode) {
  250. return 0;
  251. }
  252. static int stdout_fstat(int fd, struct stat * st) {
  253. st->st_mode = S_IFCHR;
  254. return 0;
  255. }