telnet.c 11 KB

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