telnet.c 12 KB

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