telnet.c 11 KB

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