telnet.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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 "trace.h"
  43. /************************************
  44. * Globals
  45. */
  46. #define TELNET_STACK_SIZE 8048
  47. #define TELNET_RX_BUF 1024
  48. const static char TAG[] = "telnet";
  49. static int uart_fd=0;
  50. static RingbufHandle_t buf_handle;
  51. static size_t send_chunk=300;
  52. static size_t log_buf_size=2000; //32-bit aligned size
  53. static bool bIsEnabled=false;
  54. static int partnerSocket=0;
  55. static telnet_t *tnHandle;
  56. extern bool bypass_wifi_manager;
  57. /************************************
  58. * Forward declarations
  59. */
  60. static void telnet_task(void *data);
  61. static int stdio_open(const char * path, int flags, int mode);
  62. static int stdout_fstat(int fd, struct stat * st);
  63. static ssize_t stdout_write(int fd, const void * data, size_t size);
  64. static char *eventToString(telnet_event_type_t type);
  65. static void handle_telnet_conn();
  66. static void process_logs( UBaseType_t bytes, bool is_write_op);
  67. static bool bMirrorToUART=false;
  68. struct telnetUserData {
  69. int sockfd;
  70. telnet_t *tnHandle;
  71. char * rxbuf;
  72. };
  73. void init_telnet(){
  74. char *val= get_nvs_value_alloc(NVS_TYPE_STR, "telnet_enable");
  75. if (!val || strlen(val) == 0 || !strcasestr("YXD",val) ) {
  76. ESP_LOGI(TAG,"Telnet support disabled");
  77. if(val) free(val);
  78. return;
  79. }
  80. // if wifi manager is bypassed, there will possibly be no wifi available
  81. //
  82. bMirrorToUART = (strcasestr("D",val)!=NULL);
  83. if(!bMirrorToUART && bypass_wifi_manager){
  84. // This isn't supposed to happen, as telnet won't start if wifi manager isn't
  85. // started. So this is a safeguard only.
  86. ESP_LOGW(TAG,"Wifi manager is not active. Forcing console on Serial output.");
  87. }
  88. FREE_AND_NULL(val);
  89. val=get_nvs_value_alloc(NVS_TYPE_STR, "telnet_block");
  90. if(val){
  91. send_chunk=atol(val);
  92. free(val);
  93. send_chunk=send_chunk>0?send_chunk:500;
  94. }
  95. val=get_nvs_value_alloc(NVS_TYPE_STR, "telnet_buffer");
  96. if(val){
  97. log_buf_size=atol(val);
  98. free(val);
  99. log_buf_size=log_buf_size>0?log_buf_size:4000;
  100. }
  101. // Redirect the output to our telnet handler as soon as possible
  102. StaticRingbuffer_t *buffer_struct = (StaticRingbuffer_t *) heap_caps_malloc(sizeof(StaticRingbuffer_t), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
  103. // All non-split ring buffer must have their memory alignment set to 32 bits.
  104. uint8_t *buffer_storage = (uint8_t *)heap_caps_malloc(sizeof(uint8_t)*log_buf_size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT );
  105. buf_handle = xRingbufferCreateStatic(log_buf_size, RINGBUF_TYPE_BYTEBUF, buffer_storage, buffer_struct);
  106. if (buf_handle == NULL) {
  107. ESP_LOGE(TAG,"Failed to create ring buffer for telnet!");
  108. messaging_post_message(MESSAGING_ERROR,MESSAGING_CLASS_SYSTEM,"Failed to allocate memory for telnet buffer");
  109. return;
  110. }
  111. ESP_LOGI(TAG, "***Redirecting log output to telnet");
  112. const esp_vfs_t vfs = {
  113. .flags = ESP_VFS_FLAG_DEFAULT,
  114. .write = &stdout_write,
  115. .open = &stdio_open,
  116. .fstat = &stdout_fstat,
  117. };
  118. if(bMirrorToUART){
  119. uart_fd=open("/dev/uart/0", O_RDWR);
  120. }
  121. ESP_ERROR_CHECK(esp_vfs_register("/dev/pkspstdout", &vfs, NULL));
  122. freopen("/dev/pkspstdout", "w", stdout);
  123. freopen("/dev/pkspstdout", "w", stderr);
  124. bIsEnabled=true;
  125. }
  126. void start_telnet(void * pvParameter){
  127. static bool isStarted=false;
  128. StaticTask_t *xTaskBuffer = (StaticTask_t*) heap_caps_malloc(sizeof(StaticTask_t), MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
  129. StackType_t *xStack = heap_caps_malloc(TELNET_STACK_SIZE, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
  130. if(!isStarted && bIsEnabled) {
  131. xTaskCreateStatic( (TaskFunction_t) &telnet_task, "telnet", TELNET_STACK_SIZE, NULL, ESP_TASK_PRIO_MIN, xStack, xTaskBuffer);
  132. isStarted=true;
  133. }
  134. }
  135. static void telnet_task(void *data) {
  136. int serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  137. struct sockaddr_in serverAddr;
  138. serverAddr.sin_family = AF_INET;
  139. serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
  140. serverAddr.sin_port = htons(23);
  141. int rc = bind(serverSocket, (struct sockaddr *)&serverAddr, sizeof(serverAddr));
  142. if (rc < 0) {
  143. ESP_LOGE(TAG, "bind: %d (%s)", errno, strerror(errno));
  144. close(serverSocket);
  145. return;
  146. }
  147. rc = listen(serverSocket, 5);
  148. if (rc < 0) {
  149. ESP_LOGE(TAG, "listen: %d (%s)", errno, strerror(errno));
  150. close(serverSocket);
  151. return;
  152. }
  153. while(1) {
  154. socklen_t len = sizeof(serverAddr);
  155. rc = accept(serverSocket, (struct sockaddr *)&serverAddr, &len);
  156. if (rc < 0 ){
  157. ESP_LOGE(TAG, "accept: %d (%s)", errno, strerror(errno));
  158. return;
  159. }
  160. else {
  161. partnerSocket = rc;
  162. ESP_LOGD(TAG, "We have a new client connection!");
  163. handle_telnet_conn();
  164. ESP_LOGD(TAG, "Telnet connection terminated");
  165. }
  166. }
  167. close(serverSocket);
  168. vTaskDelete(NULL);
  169. }
  170. /**
  171. * Convert a telnet event type to its string representation.
  172. */
  173. static char *eventToString(telnet_event_type_t type) {
  174. switch(type) {
  175. case TELNET_EV_COMPRESS:
  176. return "TELNET_EV_COMPRESS";
  177. case TELNET_EV_DATA:
  178. return "TELNET_EV_DATA";
  179. case TELNET_EV_DO:
  180. return "TELNET_EV_DO";
  181. case TELNET_EV_DONT:
  182. return "TELNET_EV_DONT";
  183. case TELNET_EV_ENVIRON:
  184. return "TELNET_EV_ENVIRON";
  185. case TELNET_EV_ERROR:
  186. return "TELNET_EV_ERROR";
  187. case TELNET_EV_IAC:
  188. return "TELNET_EV_IAC";
  189. case TELNET_EV_MSSP:
  190. return "TELNET_EV_MSSP";
  191. case TELNET_EV_SEND:
  192. return "TELNET_EV_SEND";
  193. case TELNET_EV_SUBNEGOTIATION:
  194. return "TELNET_EV_SUBNEGOTIATION";
  195. case TELNET_EV_TTYPE:
  196. return "TELNET_EV_TTYPE";
  197. case TELNET_EV_WARNING:
  198. return "TELNET_EV_WARNING";
  199. case TELNET_EV_WILL:
  200. return "TELNET_EV_WILL";
  201. case TELNET_EV_WONT:
  202. return "TELNET_EV_WONT";
  203. case TELNET_EV_ZMP:
  204. return "TELNET_EV_ZMP";
  205. }
  206. return "Unknown type";
  207. } // eventToString
  208. /**
  209. * Telnet handler.
  210. */
  211. static void handle_telnet_events(
  212. telnet_t *thisTelnet,
  213. telnet_event_t *event,
  214. void *userData) {
  215. int rc;
  216. struct telnetUserData *telnetUserData = (struct telnetUserData *)userData;
  217. switch(event->type) {
  218. case TELNET_EV_SEND:
  219. rc = send(telnetUserData->sockfd, event->data.buffer, event->data.size, 0);
  220. if (rc < 0) {
  221. //printf("ERROR: (telnet) send: %d (%s)", errno, strerror(errno));
  222. }
  223. break;
  224. case TELNET_EV_DATA:
  225. console_push(event->data.buffer, event->data.size);
  226. break;
  227. case TELNET_EV_TTYPE:
  228. printf("telnet event: %s\n", eventToString(event->type));
  229. telnet_ttype_send(telnetUserData->tnHandle);
  230. break;
  231. default:
  232. printf("telnet event: %s\n", eventToString(event->type));
  233. break;
  234. } // End of switch event type
  235. } // myhandle_telnet_events
  236. static void process_logs( UBaseType_t bytes, bool is_write_op){
  237. //Receive an item from no-split ring buffer
  238. size_t item_size;
  239. UBaseType_t uxItemsWaiting;
  240. UBaseType_t uxBytesToSend=bytes;
  241. vRingbufferGetInfo(buf_handle, NULL, NULL, NULL, NULL, &uxItemsWaiting);
  242. bool is_space_available = ((log_buf_size-uxItemsWaiting)>=bytes && log_buf_size>uxItemsWaiting);
  243. if( is_space_available && (is_write_op || partnerSocket == 0) ){
  244. // there's still some room left in the buffer, and we're either
  245. // processing a write operation or telnet isn't connected yet.
  246. return;
  247. }
  248. if(is_write_op && !is_space_available && uxBytesToSend==0){
  249. // flush at least the size of a full chunk
  250. uxBytesToSend = send_chunk;
  251. }
  252. while(uxBytesToSend>0){
  253. char *item = (char *)xRingbufferReceiveUpTo(buf_handle, &item_size, pdMS_TO_TICKS(50), uxBytesToSend);
  254. //Check received data
  255. if (item != NULL) {
  256. uxBytesToSend-=item_size;
  257. if(partnerSocket!=0){
  258. telnet_send_text(tnHandle, item, item_size);
  259. }
  260. //Return Item
  261. vRingbufferReturnItem(buf_handle, (void *)item);
  262. }
  263. else{
  264. break;
  265. }
  266. }
  267. }
  268. static void handle_telnet_conn() {
  269. static const telnet_telopt_t my_telopts[] = {
  270. { TELNET_TELOPT_ECHO, TELNET_WONT, TELNET_DO },
  271. { TELNET_TELOPT_TTYPE, TELNET_WILL, TELNET_DONT },
  272. { TELNET_TELOPT_COMPRESS2, TELNET_WONT, TELNET_DO },
  273. { TELNET_TELOPT_ZMP, TELNET_WONT, TELNET_DO },
  274. { TELNET_TELOPT_MSSP, TELNET_WONT, TELNET_DO },
  275. { TELNET_TELOPT_BINARY, TELNET_WILL, TELNET_DO },
  276. { TELNET_TELOPT_NAWS, TELNET_WILL, TELNET_DONT },
  277. {TELNET_TELOPT_LINEMODE, TELNET_WONT, TELNET_DO },
  278. { -1, 0, 0 }
  279. };
  280. struct telnetUserData *pTelnetUserData = (struct telnetUserData *)heap_caps_malloc(sizeof(struct telnetUserData), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
  281. tnHandle = telnet_init(my_telopts, handle_telnet_events, 0, pTelnetUserData);
  282. pTelnetUserData->rxbuf = (char *) heap_caps_malloc(TELNET_RX_BUF, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
  283. pTelnetUserData->tnHandle = tnHandle;
  284. pTelnetUserData->sockfd = partnerSocket;
  285. // flush all the log buffer on connect
  286. process_logs(log_buf_size, false);
  287. while(1) {
  288. //ESP_LOGD(tag, "waiting for data");
  289. ssize_t len = recv(partnerSocket, pTelnetUserData->rxbuf, TELNET_RX_BUF, MSG_DONTWAIT);
  290. if (len >0 ) {
  291. telnet_recv(tnHandle, pTelnetUserData->rxbuf, len);
  292. }
  293. else if (errno != EAGAIN && errno !=EWOULDBLOCK ){
  294. telnet_free(tnHandle);
  295. tnHandle = NULL;
  296. free(pTelnetUserData->rxbuf);
  297. pTelnetUserData->rxbuf=NULL;
  298. free(pTelnetUserData);
  299. partnerSocket = 0;
  300. return;
  301. }
  302. process_logs(send_chunk, false);
  303. taskYIELD();
  304. }
  305. } // handle_telnet_conn
  306. // ******************* stdout/stderr Redirection to ringbuffer
  307. static ssize_t stdout_write(int fd, const void * data, size_t size) {
  308. // #1 Write to ringbuffer
  309. if (buf_handle == NULL) {
  310. printf("%s() ABORT. file handle _log_remote_fp is NULL\n",
  311. __FUNCTION__);
  312. } else {
  313. // flush the buffer if needed
  314. process_logs(size, true);
  315. //Send an item
  316. UBaseType_t res = xRingbufferSend(buf_handle, data, size, pdMS_TO_TICKS(10));
  317. assert(res == pdTRUE);
  318. }
  319. return bMirrorToUART?write(uart_fd, data, size):size;
  320. }
  321. static int stdio_open(const char * path, int flags, int mode) {
  322. return 0;
  323. }
  324. static int stdout_fstat(int fd, struct stat * st) {
  325. st->st_mode = S_IFCHR;
  326. return 0;
  327. }