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.

521 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
Rework settings (#2282) * wip based on early draft. todo benchmarking * fixup eraser, assume keys are unique * fix cursor copy, test removal at random * small benchmark via permutations. todo lambdas and novirtual * fix empty condition / reset * overwrite optimizations, fix move offsets overflows * ...erase using 0xff instead of 0 * test the theory with code, different length kv were bugged * try to check for out-of-bounds writes / reads * style * trying to fix mover again * clarify length, defend against reading len on edge * fix uncommited rewind change * prove space assumptions * more concise traces, fix move condition (agrh!!!) * slightly more internal knowledge (estimates API?) * make sure cursor is only valid within the range * ensure 0 does not blow things * go back up * cursor comments * comments * rewrite writes through cursor * in del too * estimate kv storage requirements, return available size * move raw erase / move into a method, allow ::set to avoid scanning storage twice * refactor naming, use in code * amend storage slicing test * fix crash handler offsets, cleanup configuration * start -> begin * eeprom readiness * dependencies * unused * SPI_FLASH constants for older Core * vtables -> templates * less include dependencies * gcov help, move estimate outside of the class * writer position can never match, use begin + offset * tweak save_crash to trigger only once in a serious crash * doh, header function should be inline * foreach api, tweak structs for public api * use test helper class * when not using foreach, move cursor reset closer to the loop using read_kv * coverage comments, fix typo in tests decltype * ensure set() does not break with offset * make codacy happy again
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
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. wifiDebug();
  241. crashDump(terminalDefaultStream());
  242. crashClear();
  243. #endif
  244. #endif
  245. if (!isEspurnaCore()) {
  246. _telnetClientsAuth[i] = !_telnetAuth;
  247. if (_telnetAuth) {
  248. if (getAdminPass().length()) {
  249. _telnetWrite(i, "Password: ");
  250. } else {
  251. _telnetClientsAuth[i] = true;
  252. }
  253. }
  254. } else {
  255. _telnetClientsAuth[i] = true;
  256. }
  257. wifiReconnectCheck();
  258. }
  259. #if TELNET_SERVER == TELNET_SERVER_WIFISERVER
  260. void _telnetLoop() {
  261. if (_telnetServer.hasClient()) {
  262. int i;
  263. for (i = 0; i < TELNET_MAX_CLIENTS; i++) {
  264. if (!_telnetClients[i] || !_telnetClients[i]->connected()) {
  265. _telnetClients[i] = std::make_unique<TTelnetClient>(_telnetServer.available());
  266. if (_telnetClients[i]->localIP() != WiFi.softAPIP()) {
  267. // Telnet is always available for the ESPurna Core image
  268. const bool can_connect = isEspurnaCore() ? true : getSetting("telnetSTA", 1 == TELNET_STA);
  269. if (!can_connect) {
  270. DEBUG_MSG_P(PSTR("[TELNET] Rejecting - Only local connections\n"));
  271. _telnetDisconnect(i);
  272. return;
  273. }
  274. }
  275. _telnetNotifyConnected(i);
  276. break;
  277. }
  278. }
  279. //no free/disconnected spot so reject
  280. if (i == TELNET_MAX_CLIENTS) {
  281. DEBUG_MSG_P(PSTR("[TELNET] Rejecting - Too many connections\n"));
  282. _telnetServer.available().stop();
  283. return;
  284. }
  285. }
  286. for (int i = 0; i < TELNET_MAX_CLIENTS; i++) {
  287. if (_telnetClients[i]) {
  288. // Handle client timeouts
  289. if (!_telnetClients[i]->connected()) {
  290. _telnetDisconnect(i);
  291. } else {
  292. // Read data from clients
  293. while (_telnetClients[i] && _telnetClients[i]->available()) {
  294. size_t len = _telnetClients[i]->available();
  295. unsigned int r = _telnetClients[i]->readBytes(_telnet_data_buffer.data(), min(_telnet_data_buffer.capacity(), len));
  296. _telnetData(i, _telnet_data_buffer.data(), r);
  297. }
  298. }
  299. }
  300. }
  301. }
  302. #elif TELNET_SERVER == TELNET_SERVER_ASYNC
  303. void _telnetSetupClient(unsigned char i, AsyncClient *client) {
  304. client->onError([i](void *s, AsyncClient *client, int8_t error) {
  305. DEBUG_MSG_P(PSTR("[TELNET] Error %s (%d) on client #%u\n"), client->errorToString(error), error, i);
  306. });
  307. client->onData([i](void*, AsyncClient*, void *data, size_t len){
  308. _telnetData(i, reinterpret_cast<char*>(data), len);
  309. });
  310. client->onDisconnect([i](void*, AsyncClient*) {
  311. _telnetCleanUp();
  312. });
  313. // XXX: AsyncClient does not have copy ctor
  314. #if TELNET_SERVER_ASYNC_BUFFERED
  315. _telnetClients[i] = std::make_unique<TTelnetClient>(client);
  316. #else
  317. _telnetClients[i] = std::unique_ptr<TTelnetClient>(client);
  318. #endif // TELNET_SERVER_ASYNC_BUFFERED
  319. }
  320. void _telnetNewClient(AsyncClient* client) {
  321. if (client->localIP() != WiFi.softAPIP()) {
  322. // Telnet is always available for the ESPurna Core image
  323. const bool can_connect = isEspurnaCore() ? true : getSetting("telnetSTA", 1 == TELNET_STA);
  324. if (!can_connect) {
  325. DEBUG_MSG_P(PSTR("[TELNET] Rejecting - Only local connections\n"));
  326. client->onDisconnect([](void *s, AsyncClient *c) {
  327. delete c;
  328. });
  329. client->close(true);
  330. return;
  331. }
  332. }
  333. for (unsigned char i = 0; i < TELNET_MAX_CLIENTS; i++) {
  334. if (!_telnetClients[i] || !_telnetClients[i]->connected()) {
  335. _telnetSetupClient(i, client);
  336. _telnetNotifyConnected(i);
  337. return;
  338. }
  339. }
  340. DEBUG_MSG_P(PSTR("[TELNET] Rejecting - Too many connections\n"));
  341. client->onDisconnect([](void *s, AsyncClient *c) {
  342. delete c;
  343. });
  344. client->close(true);
  345. }
  346. #endif // TELNET_SERVER == TELNET_SERVER_WIFISERVER
  347. // -----------------------------------------------------------------------------
  348. // Public API
  349. // -----------------------------------------------------------------------------
  350. bool telnetConnected() {
  351. for (auto& client : _telnetClients) {
  352. if (client && client->connected()) return true;
  353. }
  354. return false;
  355. }
  356. #if DEBUG_TELNET_SUPPORT
  357. bool telnetDebugSend(const char* prefix, const char* data) {
  358. if (!telnetConnected()) return false;
  359. bool result = false;
  360. if (prefix && (prefix[0] != '\0')) {
  361. result = _telnetWrite(prefix) > 0;
  362. }
  363. return (_telnetWrite(data) > 0) || result;
  364. }
  365. #endif // DEBUG_TELNET_SUPPORT
  366. unsigned char telnetWrite(unsigned char ch) {
  367. char data[1] = {ch};
  368. return _telnetWrite(data, 1);
  369. }
  370. void _telnetConfigure() {
  371. _telnetAuth = getSetting("telnetAuth", 1 == TELNET_AUTHENTICATION);
  372. }
  373. void telnetSetup() {
  374. #if TELNET_SERVER == TELNET_SERVER_WIFISERVER
  375. _telnet_data_buffer.reserve(terminalCapacity());
  376. _telnetServer.setNoDelay(true);
  377. _telnetServer.begin();
  378. espurnaRegisterLoop(_telnetLoop);
  379. #else
  380. _telnetServer.onClient([](void *s, AsyncClient* c) {
  381. _telnetNewClient(c);
  382. }, nullptr);
  383. _telnetServer.begin();
  384. #endif
  385. #if WEB_SUPPORT
  386. wsRegister()
  387. .onVisible([](JsonObject& root) { root["telnetVisible"] = 1; })
  388. .onConnected(_telnetWebSocketOnConnected)
  389. .onKeyCheck(_telnetWebSocketOnKeyCheck);
  390. #endif
  391. #if TELNET_REVERSE_SUPPORT
  392. #if MQTT_SUPPORT
  393. mqttRegister(_telnetReverseMQTTCallback);
  394. #endif
  395. #if TERMINAL_SUPPORT
  396. terminalRegisterCommand(F("TELNET.REVERSE"), [](const terminal::CommandContext& ctx) {
  397. if (ctx.argc < 3) {
  398. terminalError(F("Wrong arguments. Usage: TELNET.REVERSE <host> <port>"));
  399. return;
  400. }
  401. terminalOK();
  402. _telnetReverse(ctx.argv[1].c_str(), ctx.argv[2].toInt());
  403. });
  404. #endif
  405. #endif
  406. espurnaRegisterReload(_telnetConfigure);
  407. _telnetConfigure();
  408. DEBUG_MSG_P(PSTR("[TELNET] Listening on port %d\n"), TELNET_PORT);
  409. }
  410. #endif // TELNET_SUPPORT