telnet.c 11 KB

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