telnet.c 11 KB

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