Fork of the espurna firmware for `mhsw` switches
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

522 lines
15 KiB

7 years ago
7 years ago
7 years ago
7 years ago
Terminal: change command-line parser (#2247) Change the underlying command line handling: - switch to a custom parser, inspired by redis / sds - update terminalRegisterCommand signature, pass only bare minimum - clean-up `help` & `commands`. update settings `set`, `get` and `del` - allow our custom test suite to run command-line tests - clean-up Stream IO to allow us to print large things into debug stream (for example, `eeprom.dump`) - send parsing errors to the debug log As a proof of concept, introduce `TERMINAL_MQTT_SUPPORT` and `TERMINAL_WEB_API_SUPPORT` - MQTT subscribes to the `<root>/cmd/set` and sends response to the `<root>/cmd`. We can't output too much, as we don't have any large-send API. - Web API listens to the `/api/cmd?apikey=...&line=...` (or PUT, params inside the body). This one is intended as a possible replacement of the `API_SUPPORT`. Internals introduce a 'task' around the AsyncWebServerRequest object that will simulate what WiFiClient does and push data into it continuously, switching between CONT and SYS. Both are experimental. We only accept a single command and not every command is updated to use Print `ctx.output` object. We are also somewhat limited by the Print / Stream overall, perhaps I am overestimating the usefulness of Arduino compatibility to such an extent :) Web API handler can also sometimes show only part of the result, whenever the command tries to yield() by itself waiting for something. Perhaps we would need to create a custom request handler for that specific use-case.
4 years ago
7 years ago
7 years ago
Terminal: change command-line parser (#2247) Change the underlying command line handling: - switch to a custom parser, inspired by redis / sds - update terminalRegisterCommand signature, pass only bare minimum - clean-up `help` & `commands`. update settings `set`, `get` and `del` - allow our custom test suite to run command-line tests - clean-up Stream IO to allow us to print large things into debug stream (for example, `eeprom.dump`) - send parsing errors to the debug log As a proof of concept, introduce `TERMINAL_MQTT_SUPPORT` and `TERMINAL_WEB_API_SUPPORT` - MQTT subscribes to the `<root>/cmd/set` and sends response to the `<root>/cmd`. We can't output too much, as we don't have any large-send API. - Web API listens to the `/api/cmd?apikey=...&line=...` (or PUT, params inside the body). This one is intended as a possible replacement of the `API_SUPPORT`. Internals introduce a 'task' around the AsyncWebServerRequest object that will simulate what WiFiClient does and push data into it continuously, switching between CONT and SYS. Both are experimental. We only accept a single command and not every command is updated to use Print `ctx.output` object. We are also somewhat limited by the Print / Stream overall, perhaps I am overestimating the usefulness of Arduino compatibility to such an extent :) Web API handler can also sometimes show only part of the result, whenever the command tries to yield() by itself waiting for something. Perhaps we would need to create a custom request handler for that specific use-case.
4 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
Terminal: change command-line parser (#2247) Change the underlying command line handling: - switch to a custom parser, inspired by redis / sds - update terminalRegisterCommand signature, pass only bare minimum - clean-up `help` & `commands`. update settings `set`, `get` and `del` - allow our custom test suite to run command-line tests - clean-up Stream IO to allow us to print large things into debug stream (for example, `eeprom.dump`) - send parsing errors to the debug log As a proof of concept, introduce `TERMINAL_MQTT_SUPPORT` and `TERMINAL_WEB_API_SUPPORT` - MQTT subscribes to the `<root>/cmd/set` and sends response to the `<root>/cmd`. We can't output too much, as we don't have any large-send API. - Web API listens to the `/api/cmd?apikey=...&line=...` (or PUT, params inside the body). This one is intended as a possible replacement of the `API_SUPPORT`. Internals introduce a 'task' around the AsyncWebServerRequest object that will simulate what WiFiClient does and push data into it continuously, switching between CONT and SYS. Both are experimental. We only accept a single command and not every command is updated to use Print `ctx.output` object. We are also somewhat limited by the Print / Stream overall, perhaps I am overestimating the usefulness of Arduino compatibility to such an extent :) Web API handler can also sometimes show only part of the result, whenever the command tries to yield() by itself waiting for something. Perhaps we would need to create a custom request handler for that specific use-case.
4 years ago
Terminal: change command-line parser (#2247) Change the underlying command line handling: - switch to a custom parser, inspired by redis / sds - update terminalRegisterCommand signature, pass only bare minimum - clean-up `help` & `commands`. update settings `set`, `get` and `del` - allow our custom test suite to run command-line tests - clean-up Stream IO to allow us to print large things into debug stream (for example, `eeprom.dump`) - send parsing errors to the debug log As a proof of concept, introduce `TERMINAL_MQTT_SUPPORT` and `TERMINAL_WEB_API_SUPPORT` - MQTT subscribes to the `<root>/cmd/set` and sends response to the `<root>/cmd`. We can't output too much, as we don't have any large-send API. - Web API listens to the `/api/cmd?apikey=...&line=...` (or PUT, params inside the body). This one is intended as a possible replacement of the `API_SUPPORT`. Internals introduce a 'task' around the AsyncWebServerRequest object that will simulate what WiFiClient does and push data into it continuously, switching between CONT and SYS. Both are experimental. We only accept a single command and not every command is updated to use Print `ctx.output` object. We are also somewhat limited by the Print / Stream overall, perhaps I am overestimating the usefulness of Arduino compatibility to such an extent :) Web API handler can also sometimes show only part of the result, whenever the command tries to yield() by itself waiting for something. Perhaps we would need to create a custom request handler for that specific use-case.
4 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
Terminal: change command-line parser (#2247) Change the underlying command line handling: - switch to a custom parser, inspired by redis / sds - update terminalRegisterCommand signature, pass only bare minimum - clean-up `help` & `commands`. update settings `set`, `get` and `del` - allow our custom test suite to run command-line tests - clean-up Stream IO to allow us to print large things into debug stream (for example, `eeprom.dump`) - send parsing errors to the debug log As a proof of concept, introduce `TERMINAL_MQTT_SUPPORT` and `TERMINAL_WEB_API_SUPPORT` - MQTT subscribes to the `<root>/cmd/set` and sends response to the `<root>/cmd`. We can't output too much, as we don't have any large-send API. - Web API listens to the `/api/cmd?apikey=...&line=...` (or PUT, params inside the body). This one is intended as a possible replacement of the `API_SUPPORT`. Internals introduce a 'task' around the AsyncWebServerRequest object that will simulate what WiFiClient does and push data into it continuously, switching between CONT and SYS. Both are experimental. We only accept a single command and not every command is updated to use Print `ctx.output` object. We are also somewhat limited by the Print / Stream overall, perhaps I am overestimating the usefulness of Arduino compatibility to such an extent :) Web API handler can also sometimes show only part of the result, whenever the command tries to yield() by itself waiting for something. Perhaps we would need to create a custom request handler for that specific use-case.
4 years ago
Terminal: change command-line parser (#2247) Change the underlying command line handling: - switch to a custom parser, inspired by redis / sds - update terminalRegisterCommand signature, pass only bare minimum - clean-up `help` & `commands`. update settings `set`, `get` and `del` - allow our custom test suite to run command-line tests - clean-up Stream IO to allow us to print large things into debug stream (for example, `eeprom.dump`) - send parsing errors to the debug log As a proof of concept, introduce `TERMINAL_MQTT_SUPPORT` and `TERMINAL_WEB_API_SUPPORT` - MQTT subscribes to the `<root>/cmd/set` and sends response to the `<root>/cmd`. We can't output too much, as we don't have any large-send API. - Web API listens to the `/api/cmd?apikey=...&line=...` (or PUT, params inside the body). This one is intended as a possible replacement of the `API_SUPPORT`. Internals introduce a 'task' around the AsyncWebServerRequest object that will simulate what WiFiClient does and push data into it continuously, switching between CONT and SYS. Both are experimental. We only accept a single command and not every command is updated to use Print `ctx.output` object. We are also somewhat limited by the Print / Stream overall, perhaps I am overestimating the usefulness of Arduino compatibility to such an extent :) Web API handler can also sometimes show only part of the result, whenever the command tries to yield() by itself waiting for something. Perhaps we would need to create a custom request handler for that specific use-case.
4 years ago
7 years ago
Terminal: change command-line parser (#2247) Change the underlying command line handling: - switch to a custom parser, inspired by redis / sds - update terminalRegisterCommand signature, pass only bare minimum - clean-up `help` & `commands`. update settings `set`, `get` and `del` - allow our custom test suite to run command-line tests - clean-up Stream IO to allow us to print large things into debug stream (for example, `eeprom.dump`) - send parsing errors to the debug log As a proof of concept, introduce `TERMINAL_MQTT_SUPPORT` and `TERMINAL_WEB_API_SUPPORT` - MQTT subscribes to the `<root>/cmd/set` and sends response to the `<root>/cmd`. We can't output too much, as we don't have any large-send API. - Web API listens to the `/api/cmd?apikey=...&line=...` (or PUT, params inside the body). This one is intended as a possible replacement of the `API_SUPPORT`. Internals introduce a 'task' around the AsyncWebServerRequest object that will simulate what WiFiClient does and push data into it continuously, switching between CONT and SYS. Both are experimental. We only accept a single command and not every command is updated to use Print `ctx.output` object. We are also somewhat limited by the Print / Stream overall, perhaps I am overestimating the usefulness of Arduino compatibility to such an extent :) Web API handler can also sometimes show only part of the result, whenever the command tries to yield() by itself waiting for something. Perhaps we would need to create a custom request handler for that specific use-case.
4 years ago
Terminal: change command-line parser (#2247) Change the underlying command line handling: - switch to a custom parser, inspired by redis / sds - update terminalRegisterCommand signature, pass only bare minimum - clean-up `help` & `commands`. update settings `set`, `get` and `del` - allow our custom test suite to run command-line tests - clean-up Stream IO to allow us to print large things into debug stream (for example, `eeprom.dump`) - send parsing errors to the debug log As a proof of concept, introduce `TERMINAL_MQTT_SUPPORT` and `TERMINAL_WEB_API_SUPPORT` - MQTT subscribes to the `<root>/cmd/set` and sends response to the `<root>/cmd`. We can't output too much, as we don't have any large-send API. - Web API listens to the `/api/cmd?apikey=...&line=...` (or PUT, params inside the body). This one is intended as a possible replacement of the `API_SUPPORT`. Internals introduce a 'task' around the AsyncWebServerRequest object that will simulate what WiFiClient does and push data into it continuously, switching between CONT and SYS. Both are experimental. We only accept a single command and not every command is updated to use Print `ctx.output` object. We are also somewhat limited by the Print / Stream overall, perhaps I am overestimating the usefulness of Arduino compatibility to such an extent :) Web API handler can also sometimes show only part of the result, whenever the command tries to yield() by itself waiting for something. Perhaps we would need to create a custom request handler for that specific use-case.
4 years ago
7 years ago
  1. /*
  2. TELNET MODULE
  3. Copyright (C) 2017-2019 by Xose Pérez <xose dot perez at gmail dot com>
  4. Parts of the code have been borrowed from Thomas Sarlandie's NetServer
  5. (https://github.com/sarfata/kbox-firmware/tree/master/src/esp)
  6. AsyncBufferedClient based on ESPAsyncTCPbuffer, distributed with the ESPAsyncTCP
  7. (https://github.com/me-no-dev/ESPAsyncTCP/blob/master/src/ESPAsyncTCPbuffer.cpp)
  8. Copyright (C) 2019-2020 by Maxim Prokhorov <prokhorov dot max at outlook dot com>
  9. Updated to use WiFiServer and support reverse connections by Niek van der Maas < mail at niekvandermaas dot nl>
  10. */
  11. #include "telnet.h"
  12. #if TELNET_SUPPORT
  13. #include <memory>
  14. #include <vector>
  15. #include "board.h"
  16. #include "ws.h"
  17. TTelnetServer _telnetServer(TELNET_PORT);
  18. std::unique_ptr<TTelnetClient> _telnetClients[TELNET_MAX_CLIENTS];
  19. bool _telnetAuth = TELNET_AUTHENTICATION;
  20. bool _telnetClientsAuth[TELNET_MAX_CLIENTS];
  21. // -----------------------------------------------------------------------------
  22. // Private methods
  23. // -----------------------------------------------------------------------------
  24. #if WEB_SUPPORT
  25. bool _telnetWebSocketOnKeyCheck(const char * key, JsonVariant& value) {
  26. return (strncmp(key, "telnet", 6) == 0);
  27. }
  28. void _telnetWebSocketOnConnected(JsonObject& root) {
  29. root["telnetSTA"] = getSetting("telnetSTA", 1 == TELNET_STA);
  30. root["telnetAuth"] = getSetting("telnetAuth", 1 == TELNET_AUTHENTICATION);
  31. }
  32. #endif
  33. #if TELNET_REVERSE_SUPPORT
  34. void _telnetReverse(const char * host, uint16_t port) {
  35. DEBUG_MSG_P(PSTR("[TELNET] Connecting to reverse telnet on %s:%d\n"), host, port);
  36. unsigned char i;
  37. for (i = 0; i < TELNET_MAX_CLIENTS; i++) {
  38. if (!_telnetClients[i] || !_telnetClients[i]->connected()) {
  39. #if TELNET_SERVER == TELNET_SERVER_WIFISERVER
  40. _telnetClients[i] = std::make_unique<TTelnetClient>();
  41. #else // TELNET_SERVER == TELNET_SERVER_ASYNC
  42. _telnetSetupClient(i, new AsyncClient());
  43. #endif
  44. if (_telnetClients[i]->connect(host, port)) {
  45. _telnetNotifyConnected(i);
  46. return;
  47. } else {
  48. DEBUG_MSG_P(PSTR("[TELNET] Error connecting reverse telnet\n"));
  49. _telnetDisconnect(i);
  50. return;
  51. }
  52. }
  53. }
  54. //no free/disconnected spot so reject
  55. if (i == TELNET_MAX_CLIENTS) {
  56. DEBUG_MSG_P(PSTR("[TELNET] Failed too connect - too many clients connected\n"));
  57. }
  58. }
  59. #if MQTT_SUPPORT
  60. void _telnetReverseMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  61. if (type == MQTT_CONNECT_EVENT) {
  62. mqttSubscribe(MQTT_TOPIC_TELNET_REVERSE);
  63. } else if (type == MQTT_MESSAGE_EVENT) {
  64. String t = mqttMagnitude((char *) topic);
  65. if (t.equals(MQTT_TOPIC_TELNET_REVERSE)) {
  66. String pl = String(payload);
  67. int col = pl.indexOf(':');
  68. if (col != -1) {
  69. String host = pl.substring(0, col);
  70. uint16_t port = pl.substring(col + 1).toInt();
  71. _telnetReverse(host.c_str(), port);
  72. } else {
  73. DEBUG_MSG_P(PSTR("[TELNET] Incorrect reverse telnet value given, use the form \"host:ip\""));
  74. }
  75. }
  76. }
  77. }
  78. #endif // MQTT_SUPPORT
  79. #endif // TELNET_REVERSE_SUPPORT
  80. #if TELNET_SERVER == TELNET_SERVER_WIFISERVER
  81. static std::vector<char> _telnet_data_buffer;
  82. void _telnetDisconnect(unsigned char clientId) {
  83. _telnetClients[clientId]->stop();
  84. _telnetClients[clientId] = nullptr;
  85. wifiReconnectCheck();
  86. DEBUG_MSG_P(PSTR("[TELNET] Client #%d disconnected\n"), clientId);
  87. }
  88. #elif TELNET_SERVER == TELNET_SERVER_ASYNC
  89. void _telnetCleanUp() {
  90. schedule_function([] () {
  91. for (unsigned char clientId=0; clientId < TELNET_MAX_CLIENTS; ++clientId) {
  92. if (!_telnetClients[clientId]->connected()) {
  93. _telnetClients[clientId] = nullptr;
  94. wifiReconnectCheck();
  95. DEBUG_MSG_P(PSTR("[TELNET] Client #%d disconnected\n"), clientId);
  96. }
  97. }
  98. });
  99. }
  100. // just close, clean-up method above will destroy the object later
  101. void _telnetDisconnect(unsigned char clientId) {
  102. _telnetClients[clientId]->close(true);
  103. }
  104. #if TELNET_SERVER_ASYNC_BUFFERED
  105. AsyncBufferedClient::AsyncBufferedClient(AsyncClient* client) : _client(client) {
  106. _client->onAck(_s_onAck, this);
  107. _client->onPoll(_s_onPoll, this);
  108. }
  109. void AsyncBufferedClient::_trySend(AsyncBufferedClient* client) {
  110. while (!client->_buffers.empty()) {
  111. auto& chunk = client->_buffers.front();
  112. if (client->_client->space() >= chunk.size()) {
  113. client->_client->write((const char*)chunk.data(), chunk.size());
  114. client->_buffers.pop_front();
  115. continue;
  116. }
  117. return;
  118. }
  119. }
  120. void AsyncBufferedClient::_s_onAck(void* client_ptr, AsyncClient*, size_t, uint32_t) {
  121. _trySend(reinterpret_cast<AsyncBufferedClient*>(client_ptr));
  122. }
  123. void AsyncBufferedClient::_s_onPoll(void* client_ptr, AsyncClient* client) {
  124. _trySend(reinterpret_cast<AsyncBufferedClient*>(client_ptr));
  125. }
  126. void AsyncBufferedClient::_addBuffer() {
  127. // Note: c++17 emplace returns created object reference
  128. _buffers.emplace_back();
  129. _buffers.back().reserve(TCP_MSS);
  130. }
  131. size_t AsyncBufferedClient::write(const char* data, size_t size) {
  132. if (_buffers.size() > AsyncBufferedClient::BUFFERS_MAX) return 0;
  133. size_t written = 0;
  134. if (_buffers.empty()) {
  135. written = _client->add(data, size);
  136. if (written == size) return size;
  137. }
  138. const size_t full_size = size;
  139. char* data_ptr = const_cast<char*>(data + written);
  140. size -= written;
  141. while (size) {
  142. if (_buffers.empty()) _addBuffer();
  143. auto& current = _buffers.back();
  144. const auto have = current.capacity() - current.size();
  145. if (have >= size) {
  146. current.insert(current.end(), data_ptr, data_ptr + size);
  147. size = 0;
  148. } else {
  149. current.insert(current.end(), data_ptr, data_ptr + have);
  150. _addBuffer();
  151. data_ptr += have;
  152. size -= have;
  153. }
  154. }
  155. return full_size;
  156. }
  157. size_t AsyncBufferedClient::write(char c) {
  158. char _c[1] {c};
  159. return write(_c, 1);
  160. }
  161. void AsyncBufferedClient::flush() {
  162. _client->send();
  163. }
  164. size_t AsyncBufferedClient::available() {
  165. return _client->space();
  166. }
  167. bool AsyncBufferedClient::connect(const char *host, uint16_t port) {
  168. return _client->connect(host, port);
  169. }
  170. void AsyncBufferedClient::close(bool now) {
  171. _client->close(now);
  172. }
  173. bool AsyncBufferedClient::connected() {
  174. return _client->connected();
  175. }
  176. #endif // TELNET_SERVER_ASYNC_BUFFERED
  177. #endif // TELNET_SERVER == TELNET_SERVER_WIFISERVER
  178. size_t _telnetWrite(unsigned char clientId, const char *data, size_t len) {
  179. if (_telnetClients[clientId] && _telnetClients[clientId]->connected()) {
  180. return _telnetClients[clientId]->write(data, len);
  181. }
  182. return 0;
  183. }
  184. size_t _telnetWrite(const char *data, size_t len) {
  185. unsigned char count = 0;
  186. for (unsigned char i = 0; i < TELNET_MAX_CLIENTS; i++) {
  187. // Do not send broadcast messages to unauthenticated clients
  188. if (_telnetAuth && !_telnetClientsAuth[i]) {
  189. continue;
  190. }
  191. if (_telnetWrite(i, data, len)) ++count;
  192. }
  193. return count;
  194. }
  195. size_t _telnetWrite(const char *data) {
  196. return _telnetWrite(data, strlen(data));
  197. }
  198. size_t _telnetWrite(unsigned char clientId, const char * message) {
  199. return _telnetWrite(clientId, message, strlen(message));
  200. }
  201. void _telnetData(unsigned char clientId, char * data, size_t len) {
  202. if ((len >= 2) && (data[0] == TELNET_IAC)) {
  203. // C-d is sent as two bytes (sometimes repeating)
  204. if (data[1] == TELNET_XEOF) {
  205. _telnetDisconnect(clientId);
  206. }
  207. return; // Ignore telnet negotiation
  208. }
  209. if ((strncmp(data, "close", 5) == 0) || (strncmp(data, "quit", 4) == 0)) {
  210. #if TELNET_SERVER == TELNET_SERVER_WIFISERVER
  211. _telnetDisconnect(clientId);
  212. #else
  213. _telnetClients[clientId]->close();
  214. #endif
  215. return;
  216. }
  217. // Password prompt (disable on CORE variant)
  218. const bool authenticated = isEspurnaCore() ? true : _telnetClientsAuth[clientId];
  219. if (_telnetAuth && !authenticated) {
  220. String password = getAdminPass();
  221. if (strncmp(data, password.c_str(), password.length()) == 0) {
  222. DEBUG_MSG_P(PSTR("[TELNET] Client #%d authenticated\n"), clientId);
  223. _telnetWrite(clientId, "Password correct, welcome!\n");
  224. _telnetClientsAuth[clientId] = true;
  225. } else {
  226. _telnetWrite(clientId, "Password (try again): ");
  227. }
  228. return;
  229. }
  230. // Inject command
  231. #if TERMINAL_SUPPORT
  232. terminalInject((void*)data, len);
  233. #endif
  234. }
  235. void _telnetNotifyConnected(unsigned char i) {
  236. DEBUG_MSG_P(PSTR("[TELNET] Client #%u connected\n"), i);
  237. // If there is no terminal support automatically dump info and crash data
  238. #if DEBUG_SUPPORT
  239. #if not TERMINAL_SUPPORT
  240. info();
  241. wifiDebug();
  242. crashDump();
  243. crashClear();
  244. #endif
  245. #endif
  246. if (!isEspurnaCore()) {
  247. _telnetClientsAuth[i] = !_telnetAuth;
  248. if (_telnetAuth) {
  249. if (getAdminPass().length()) {
  250. _telnetWrite(i, "Password: ");
  251. } else {
  252. _telnetClientsAuth[i] = true;
  253. }
  254. }
  255. } else {
  256. _telnetClientsAuth[i] = true;
  257. }
  258. wifiReconnectCheck();
  259. }
  260. #if TELNET_SERVER == TELNET_SERVER_WIFISERVER
  261. void _telnetLoop() {
  262. if (_telnetServer.hasClient()) {
  263. int i;
  264. for (i = 0; i < TELNET_MAX_CLIENTS; i++) {
  265. if (!_telnetClients[i] || !_telnetClients[i]->connected()) {
  266. _telnetClients[i] = std::make_unique<TTelnetClient>(_telnetServer.available());
  267. if (_telnetClients[i]->localIP() != WiFi.softAPIP()) {
  268. // Telnet is always available for the ESPurna Core image
  269. const bool can_connect = isEspurnaCore() ? true : getSetting("telnetSTA", 1 == TELNET_STA);
  270. if (!can_connect) {
  271. DEBUG_MSG_P(PSTR("[TELNET] Rejecting - Only local connections\n"));
  272. _telnetDisconnect(i);
  273. return;
  274. }
  275. }
  276. _telnetNotifyConnected(i);
  277. break;
  278. }
  279. }
  280. //no free/disconnected spot so reject
  281. if (i == TELNET_MAX_CLIENTS) {
  282. DEBUG_MSG_P(PSTR("[TELNET] Rejecting - Too many connections\n"));
  283. _telnetServer.available().stop();
  284. return;
  285. }
  286. }
  287. for (int i = 0; i < TELNET_MAX_CLIENTS; i++) {
  288. if (_telnetClients[i]) {
  289. // Handle client timeouts
  290. if (!_telnetClients[i]->connected()) {
  291. _telnetDisconnect(i);
  292. } else {
  293. // Read data from clients
  294. while (_telnetClients[i] && _telnetClients[i]->available()) {
  295. size_t len = _telnetClients[i]->available();
  296. unsigned int r = _telnetClients[i]->readBytes(_telnet_data_buffer.data(), min(_telnet_data_buffer.capacity(), len));
  297. _telnetData(i, _telnet_data_buffer.data(), r);
  298. }
  299. }
  300. }
  301. }
  302. }
  303. #elif TELNET_SERVER == TELNET_SERVER_ASYNC
  304. void _telnetSetupClient(unsigned char i, AsyncClient *client) {
  305. client->onError([i](void *s, AsyncClient *client, int8_t error) {
  306. DEBUG_MSG_P(PSTR("[TELNET] Error %s (%d) on client #%u\n"), client->errorToString(error), error, i);
  307. });
  308. client->onData([i](void*, AsyncClient*, void *data, size_t len){
  309. _telnetData(i, reinterpret_cast<char*>(data), len);
  310. });
  311. client->onDisconnect([i](void*, AsyncClient*) {
  312. _telnetCleanUp();
  313. });
  314. // XXX: AsyncClient does not have copy ctor
  315. #if TELNET_SERVER_ASYNC_BUFFERED
  316. _telnetClients[i] = std::make_unique<TTelnetClient>(client);
  317. #else
  318. _telnetClients[i] = std::unique_ptr<TTelnetClient>(client);
  319. #endif // TELNET_SERVER_ASYNC_BUFFERED
  320. }
  321. void _telnetNewClient(AsyncClient* client) {
  322. if (client->localIP() != WiFi.softAPIP()) {
  323. // Telnet is always available for the ESPurna Core image
  324. const bool can_connect = isEspurnaCore() ? true : getSetting("telnetSTA", 1 == TELNET_STA);
  325. if (!can_connect) {
  326. DEBUG_MSG_P(PSTR("[TELNET] Rejecting - Only local connections\n"));
  327. client->onDisconnect([](void *s, AsyncClient *c) {
  328. delete c;
  329. });
  330. client->close(true);
  331. return;
  332. }
  333. }
  334. for (unsigned char i = 0; i < TELNET_MAX_CLIENTS; i++) {
  335. if (!_telnetClients[i] || !_telnetClients[i]->connected()) {
  336. _telnetSetupClient(i, client);
  337. _telnetNotifyConnected(i);
  338. return;
  339. }
  340. }
  341. DEBUG_MSG_P(PSTR("[TELNET] Rejecting - Too many connections\n"));
  342. client->onDisconnect([](void *s, AsyncClient *c) {
  343. delete c;
  344. });
  345. client->close(true);
  346. }
  347. #endif // TELNET_SERVER == TELNET_SERVER_WIFISERVER
  348. // -----------------------------------------------------------------------------
  349. // Public API
  350. // -----------------------------------------------------------------------------
  351. bool telnetConnected() {
  352. for (auto& client : _telnetClients) {
  353. if (client && client->connected()) return true;
  354. }
  355. return false;
  356. }
  357. #if DEBUG_TELNET_SUPPORT
  358. bool telnetDebugSend(const char* prefix, const char* data) {
  359. if (!telnetConnected()) return false;
  360. bool result = false;
  361. if (prefix && (prefix[0] != '\0')) {
  362. result = _telnetWrite(prefix) > 0;
  363. }
  364. return (_telnetWrite(data) > 0) || result;
  365. }
  366. #endif // DEBUG_TELNET_SUPPORT
  367. unsigned char telnetWrite(unsigned char ch) {
  368. char data[1] = {ch};
  369. return _telnetWrite(data, 1);
  370. }
  371. void _telnetConfigure() {
  372. _telnetAuth = getSetting("telnetAuth", 1 == TELNET_AUTHENTICATION);
  373. }
  374. void telnetSetup() {
  375. #if TELNET_SERVER == TELNET_SERVER_WIFISERVER
  376. _telnet_data_buffer.reserve(terminalCapacity());
  377. _telnetServer.setNoDelay(true);
  378. _telnetServer.begin();
  379. espurnaRegisterLoop(_telnetLoop);
  380. #else
  381. _telnetServer.onClient([](void *s, AsyncClient* c) {
  382. _telnetNewClient(c);
  383. }, nullptr);
  384. _telnetServer.begin();
  385. #endif
  386. #if WEB_SUPPORT
  387. wsRegister()
  388. .onVisible([](JsonObject& root) { root["telnetVisible"] = 1; })
  389. .onConnected(_telnetWebSocketOnConnected)
  390. .onKeyCheck(_telnetWebSocketOnKeyCheck);
  391. #endif
  392. #if TELNET_REVERSE_SUPPORT
  393. #if MQTT_SUPPORT
  394. mqttRegister(_telnetReverseMQTTCallback);
  395. #endif
  396. #if TERMINAL_SUPPORT
  397. terminalRegisterCommand(F("TELNET.REVERSE"), [](const terminal::CommandContext& ctx) {
  398. if (ctx.argc < 3) {
  399. terminalError(F("Wrong arguments. Usage: TELNET.REVERSE <host> <port>"));
  400. return;
  401. }
  402. terminalOK();
  403. _telnetReverse(ctx.argv[1].c_str(), ctx.argv[2].toInt());
  404. });
  405. #endif
  406. #endif
  407. espurnaRegisterReload(_telnetConfigure);
  408. _telnetConfigure();
  409. DEBUG_MSG_P(PSTR("[TELNET] Listening on port %d\n"), TELNET_PORT);
  410. }
  411. #endif // TELNET_SUPPORT