telnet.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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. /************************************
  42. * Globals
  43. */
  44. #define TELNET_STACK_SIZE 8048
  45. #define TELNET_RX_BUF 1024
  46. const static char tag[] = "telnet";
  47. static int uart_fd=0;
  48. RingbufHandle_t buf_handle;
  49. SemaphoreHandle_t xSemaphore = NULL;
  50. static size_t send_chunk=300;
  51. static size_t log_buf_size=2000; //32-bit aligned size
  52. static bool bIsEnabled=false;
  53. static int partnerSocket=0;
  54. static telnet_t *tnHandle;
  55. /************************************
  56. * Forward declarations
  57. */
  58. static void telnet_task(void *data);
  59. static ssize_t stdout_read(int fd, void* data, size_t size);
  60. static int stdout_open(const char * path, int flags, int mode);
  61. static int stdout_close(int fd);
  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);
  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. bMirrorToUART = strcasestr("D",val)!=NULL;
  81. FREE_AND_NULL(val);
  82. val=get_nvs_value_alloc(NVS_TYPE_STR, "telnet_block");
  83. if(val){
  84. send_chunk=atol(val);
  85. free(val);
  86. send_chunk=send_chunk>0?send_chunk:500;
  87. }
  88. val=get_nvs_value_alloc(NVS_TYPE_STR, "telnet_buffer");
  89. if(val){
  90. log_buf_size=atol(val);
  91. free(val);
  92. log_buf_size=log_buf_size>0?log_buf_size:4000;
  93. }
  94. // Create the semaphore to guard a shared resource.
  95. vSemaphoreCreateBinary( xSemaphore );
  96. // Redirect the output to our telnet handler as soon as possible
  97. StaticRingbuffer_t *buffer_struct = (StaticRingbuffer_t *)heap_caps_malloc(sizeof(StaticRingbuffer_t), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
  98. uint8_t *buffer_storage = (uint8_t *)heap_caps_malloc(sizeof(uint8_t)*log_buf_size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
  99. buf_handle = xRingbufferCreateStatic(log_buf_size, RINGBUF_TYPE_BYTEBUF, buffer_storage, buffer_struct);
  100. if (buf_handle == NULL) {
  101. ESP_LOGE(tag,"Failed to create ring buffer for telnet!");
  102. return;
  103. }
  104. ESP_LOGI(tag, "***Redirecting log output to telnet");
  105. const esp_vfs_t vfs = {
  106. .flags = ESP_VFS_FLAG_DEFAULT,
  107. .write = &stdout_write,
  108. .open = &stdout_open,
  109. .fstat = &stdout_fstat,
  110. .close = &stdout_close,
  111. .read = &stdout_read,
  112. };
  113. if(bMirrorToUART){
  114. uart_fd=open("/dev/uart/0", O_RDWR);
  115. }
  116. ESP_ERROR_CHECK(esp_vfs_register("/dev/pkspstdout", &vfs, NULL));
  117. freopen("/dev/pkspstdout", "w", stdout);
  118. freopen("/dev/pkspstdout", "w", stderr);
  119. bIsEnabled=true;
  120. }
  121. void start_telnet(void * pvParameter){
  122. static bool isStarted=false;
  123. StaticTask_t *xTaskBuffer = (StaticTask_t*) heap_caps_malloc(sizeof(StaticTask_t), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
  124. StackType_t *xStack = malloc(TELNET_STACK_SIZE);
  125. if(!isStarted && bIsEnabled) {
  126. xTaskCreateStatic( (TaskFunction_t) &telnet_task, "telnet", TELNET_STACK_SIZE, NULL, ESP_TASK_PRIO_MIN + 1, xStack, xTaskBuffer);
  127. isStarted=true;
  128. }
  129. }
  130. static void telnet_task(void *data) {
  131. int serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  132. struct sockaddr_in serverAddr;
  133. serverAddr.sin_family = AF_INET;
  134. serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
  135. serverAddr.sin_port = htons(23);
  136. int rc = bind(serverSocket, (struct sockaddr *)&serverAddr, sizeof(serverAddr));
  137. if (rc < 0) {
  138. ESP_LOGE(tag, "bind: %d (%s)", errno, strerror(errno));
  139. return;
  140. }
  141. rc = listen(serverSocket, 5);
  142. if (rc < 0) {
  143. ESP_LOGE(tag, "listen: %d (%s)", errno, strerror(errno));
  144. return;
  145. }
  146. while(1) {
  147. socklen_t len = sizeof(serverAddr);
  148. rc = accept(serverSocket, (struct sockaddr *)&serverAddr, &len);
  149. if (rc < 0 ){
  150. ESP_LOGE(tag, "accept: %d (%s)", errno, strerror(errno));
  151. return;
  152. }
  153. else {
  154. partnerSocket = rc;
  155. ESP_LOGD(tag, "We have a new client connection!");
  156. handle_telnet_conn();
  157. ESP_LOGD(tag, "Telnet connection terminated");
  158. }
  159. }
  160. vTaskDelete(NULL);
  161. }
  162. /**
  163. * Convert a telnet event type to its string representation.
  164. */
  165. static char *eventToString(telnet_event_type_t type) {
  166. switch(type) {
  167. case TELNET_EV_COMPRESS:
  168. return "TELNET_EV_COMPRESS";
  169. case TELNET_EV_DATA:
  170. return "TELNET_EV_DATA";
  171. case TELNET_EV_DO:
  172. return "TELNET_EV_DO";
  173. case TELNET_EV_DONT:
  174. return "TELNET_EV_DONT";
  175. case TELNET_EV_ENVIRON:
  176. return "TELNET_EV_ENVIRON";
  177. case TELNET_EV_ERROR:
  178. return "TELNET_EV_ERROR";
  179. case TELNET_EV_IAC:
  180. return "TELNET_EV_IAC";
  181. case TELNET_EV_MSSP:
  182. return "TELNET_EV_MSSP";
  183. case TELNET_EV_SEND:
  184. return "TELNET_EV_SEND";
  185. case TELNET_EV_SUBNEGOTIATION:
  186. return "TELNET_EV_SUBNEGOTIATION";
  187. case TELNET_EV_TTYPE:
  188. return "TELNET_EV_TTYPE";
  189. case TELNET_EV_WARNING:
  190. return "TELNET_EV_WARNING";
  191. case TELNET_EV_WILL:
  192. return "TELNET_EV_WILL";
  193. case TELNET_EV_WONT:
  194. return "TELNET_EV_WONT";
  195. case TELNET_EV_ZMP:
  196. return "TELNET_EV_ZMP";
  197. }
  198. return "Unknown type";
  199. } // eventToString
  200. /**
  201. * Telnet handler.
  202. */
  203. void process_received_data(const char * buffer, size_t size){
  204. //ESP_LOGD(tag, "received data, len=%d", event->data.size);
  205. char * command = malloc(size+1);
  206. const char * c=buffer;
  207. // scrub from any escape command
  208. if(*c == '\e'){
  209. while(*(c++) !='n'){
  210. --size;
  211. };
  212. --size;
  213. }
  214. memcpy(command,c,size);
  215. command[size]='\0';
  216. if(command[0]!='\r' && command[0]!='\n'){
  217. // echo the command buffer out to uart and run
  218. if(bMirrorToUART){
  219. write(uart_fd, command, size);
  220. }
  221. run_command((char *)command);
  222. }
  223. free(command);
  224. }
  225. static void handle_telnet_events(
  226. telnet_t *thisTelnet,
  227. telnet_event_t *event,
  228. void *userData) {
  229. int rc;
  230. struct telnetUserData *telnetUserData = (struct telnetUserData *)userData;
  231. switch(event->type) {
  232. case TELNET_EV_SEND:
  233. rc = send(telnetUserData->sockfd, event->data.buffer, event->data.size, 0);
  234. if (rc < 0) {
  235. //printf("ERROR: (telnet) send: %d (%s)", errno, strerror(errno));
  236. }
  237. break;
  238. case TELNET_EV_DATA:
  239. process_received_data(event->data.buffer, event->data.size);
  240. break;
  241. case TELNET_EV_TTYPE:
  242. printf("telnet event: %s\n", eventToString(event->type));
  243. telnet_ttype_send(telnetUserData->tnHandle);
  244. break;
  245. default:
  246. printf("telnet event: %s\n", eventToString(event->type));
  247. break;
  248. } // End of switch event type
  249. } // myhandle_telnet_events
  250. static void process_logs(UBaseType_t count){
  251. //Receive an item from no-split ring buffer
  252. size_t item_size;
  253. UBaseType_t uxItemsWaiting;
  254. UBaseType_t uxBytesToSend=count;
  255. vRingbufferGetInfo(buf_handle, NULL, NULL, NULL, NULL, &uxItemsWaiting);
  256. if(count == 0){
  257. // this sends the entire buffer to the remote client
  258. uxBytesToSend = uxItemsWaiting;
  259. }
  260. if( partnerSocket ==0 && (uxItemsWaiting*100 / log_buf_size) <75){
  261. // We still have some room in the ringbuffer and there's no telnet
  262. // connection yet, so bail out for now.
  263. //printf("%s() Log buffer used %u of %u bytes used\n", __FUNCTION__, uxItemsWaiting, log_buf_size);
  264. return;
  265. }
  266. while(uxBytesToSend>0){
  267. char *item = (char *)xRingbufferReceiveUpTo(buf_handle, &item_size, pdMS_TO_TICKS(50), uxBytesToSend);
  268. //Check received data
  269. if (item != NULL) {
  270. uxBytesToSend-=item_size;
  271. if(partnerSocket!=0){
  272. telnet_send_text(tnHandle, item, item_size);
  273. }
  274. //Return Item
  275. vRingbufferReturnItem(buf_handle, (void *)item);
  276. }
  277. else{
  278. break;
  279. }
  280. }
  281. }
  282. static void handle_telnet_conn() {
  283. static const telnet_telopt_t my_telopts[] = {
  284. { TELNET_TELOPT_ECHO, TELNET_WONT, TELNET_DO },
  285. { TELNET_TELOPT_TTYPE, TELNET_WILL, TELNET_DONT },
  286. { TELNET_TELOPT_COMPRESS2, TELNET_WONT, TELNET_DO },
  287. { TELNET_TELOPT_ZMP, TELNET_WONT, TELNET_DO },
  288. { TELNET_TELOPT_MSSP, TELNET_WONT, TELNET_DO },
  289. { TELNET_TELOPT_BINARY, TELNET_WILL, TELNET_DO },
  290. { TELNET_TELOPT_NAWS, TELNET_WILL, TELNET_DONT },
  291. {TELNET_TELOPT_LINEMODE, TELNET_WONT, TELNET_DO },
  292. { -1, 0, 0 }
  293. };
  294. struct telnetUserData *pTelnetUserData = (struct telnetUserData *)malloc(sizeof(struct telnetUserData));
  295. tnHandle = telnet_init(my_telopts, handle_telnet_events, 0, pTelnetUserData);
  296. pTelnetUserData->rxbuf = (char *) heap_caps_malloc(TELNET_RX_BUF, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
  297. pTelnetUserData->tnHandle = tnHandle;
  298. pTelnetUserData->sockfd = partnerSocket;
  299. // flush all the log buffer on connect
  300. process_logs(0);
  301. while(1) {
  302. //ESP_LOGD(tag, "waiting for data");
  303. ssize_t len = recv(partnerSocket, pTelnetUserData->rxbuf, TELNET_RX_BUF, MSG_DONTWAIT);
  304. if (len >0 ) {
  305. telnet_recv(tnHandle, pTelnetUserData->rxbuf, len);
  306. }
  307. else if (errno != EAGAIN && errno !=EWOULDBLOCK ){
  308. telnet_free(tnHandle);
  309. tnHandle = NULL;
  310. free(pTelnetUserData->rxbuf);
  311. pTelnetUserData->rxbuf=NULL;
  312. free(pTelnetUserData);
  313. partnerSocket = 0;
  314. return;
  315. }
  316. process_logs(send_chunk);
  317. taskYIELD();
  318. }
  319. } // handle_telnet_conn
  320. // ******************* stdout/stderr Redirection to ringbuffer
  321. static ssize_t stdout_write(int fd, const void * data, size_t size) {
  322. if (xSemaphoreTake(xSemaphore, (TickType_t) 10) == pdTRUE) {
  323. // #1 Write to ringbuffer
  324. if (buf_handle == NULL) {
  325. printf("%s() ABORT. file handle _log_remote_fp is NULL\n",
  326. __FUNCTION__);
  327. } else {
  328. //Send an item
  329. UBaseType_t res = xRingbufferSend(buf_handle, data, size,
  330. pdMS_TO_TICKS(100));
  331. if (res != pdTRUE) {
  332. // flush some entries
  333. process_logs(size);
  334. res = xRingbufferSend(buf_handle, data, size,
  335. pdMS_TO_TICKS(100));
  336. if (res != pdTRUE) {
  337. printf("%s() ABORT. Unable to store log entry in buffer\n",
  338. __FUNCTION__);
  339. }
  340. }
  341. }
  342. xSemaphoreGive(xSemaphore);
  343. } else {
  344. // We could not obtain the semaphore and can therefore not access
  345. // the shared resource safely.
  346. }
  347. return bMirrorToUART?write(uart_fd, data, size):true;
  348. }
  349. static ssize_t stdout_read(int fd, void* data, size_t size) {
  350. return read(fd, data, size);
  351. }
  352. static int stdout_open(const char * path, int flags, int mode) {
  353. return 0;
  354. }
  355. static int stdout_close(int fd) {
  356. return 0;
  357. }
  358. static int stdout_fstat(int fd, struct stat * st) {
  359. st->st_mode = S_IFCHR;
  360. return 0;
  361. }