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.

571 lines
16 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. #if TELNET_SERVER == TELNET_SERVER_ASYNC
  18. #include <ESPAsyncTCP.h>
  19. struct AsyncBufferedClient {
  20. public:
  21. constexpr static const size_t BUFFERS_MAX = 5;
  22. using buffer_t = std::vector<uint8_t>;
  23. explicit AsyncBufferedClient(AsyncClient* client);
  24. size_t write(char c);
  25. size_t write(const char* data, size_t size=0);
  26. void flush();
  27. size_t available();
  28. bool connect(const char *host, uint16_t port);
  29. void close(bool now = false);
  30. bool connected();
  31. private:
  32. void _addBuffer();
  33. static void _trySend(AsyncBufferedClient* client);
  34. static void _s_onAck(void* client_ptr, AsyncClient*, size_t, uint32_t);
  35. static void _s_onPoll(void* client_ptr, AsyncClient* client);
  36. std::unique_ptr<AsyncClient> _client;
  37. std::list<buffer_t> _buffers;
  38. };
  39. using TTelnetServer = AsyncServer;
  40. #if TELNET_SERVER_ASYNC_BUFFERED
  41. using TTelnetClient = AsyncBufferedClient;
  42. #else
  43. using TTelnetClient = AsyncClient;
  44. #endif // TELNET_SERVER_ASYNC_BUFFERED
  45. #elif TELNET_SERVER == TELNET_SERVER_WIFISERVER
  46. using TTelnetServer = WiFiServer;
  47. using TTelnetClient = WiFiClient;
  48. #else
  49. #error "TELNET_SERVER value was not properly set"
  50. #endif
  51. TTelnetServer _telnetServer(TELNET_PORT);
  52. std::unique_ptr<TTelnetClient> _telnetClients[TELNET_MAX_CLIENTS];
  53. bool _telnetAuth = TELNET_AUTHENTICATION;
  54. bool _telnetClientsAuth[TELNET_MAX_CLIENTS];
  55. // -----------------------------------------------------------------------------
  56. // Private methods
  57. // -----------------------------------------------------------------------------
  58. #if WEB_SUPPORT
  59. bool _telnetWebSocketOnKeyCheck(const char * key, JsonVariant& value) {
  60. return (strncmp(key, "telnet", 6) == 0);
  61. }
  62. void _telnetWebSocketOnConnected(JsonObject& root) {
  63. root["telnetSTA"] = getSetting("telnetSTA", 1 == TELNET_STA);
  64. root["telnetAuth"] = getSetting("telnetAuth", 1 == TELNET_AUTHENTICATION);
  65. }
  66. #endif
  67. #if TELNET_REVERSE_SUPPORT
  68. void _telnetReverse(const char * host, uint16_t port) {
  69. DEBUG_MSG_P(PSTR("[TELNET] Connecting to reverse telnet on %s:%d\n"), host, port);
  70. unsigned char i;
  71. for (i = 0; i < TELNET_MAX_CLIENTS; i++) {
  72. if (!_telnetClients[i] || !_telnetClients[i]->connected()) {
  73. #if TELNET_SERVER == TELNET_SERVER_WIFISERVER
  74. _telnetClients[i] = std::make_unique<TTelnetClient>();
  75. #else // TELNET_SERVER == TELNET_SERVER_ASYNC
  76. _telnetSetupClient(i, new AsyncClient());
  77. #endif
  78. if (_telnetClients[i]->connect(host, port)) {
  79. _telnetNotifyConnected(i);
  80. return;
  81. } else {
  82. DEBUG_MSG_P(PSTR("[TELNET] Error connecting reverse telnet\n"));
  83. _telnetDisconnect(i);
  84. return;
  85. }
  86. }
  87. }
  88. //no free/disconnected spot so reject
  89. if (i == TELNET_MAX_CLIENTS) {
  90. DEBUG_MSG_P(PSTR("[TELNET] Failed too connect - too many clients connected\n"));
  91. }
  92. }
  93. #if MQTT_SUPPORT
  94. void _telnetReverseMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  95. if (type == MQTT_CONNECT_EVENT) {
  96. mqttSubscribe(MQTT_TOPIC_TELNET_REVERSE);
  97. } else if (type == MQTT_MESSAGE_EVENT) {
  98. String t = mqttMagnitude((char *) topic);
  99. if (t.equals(MQTT_TOPIC_TELNET_REVERSE)) {
  100. String pl = String(payload);
  101. int col = pl.indexOf(':');
  102. if (col != -1) {
  103. String host = pl.substring(0, col);
  104. uint16_t port = pl.substring(col + 1).toInt();
  105. _telnetReverse(host.c_str(), port);
  106. } else {
  107. DEBUG_MSG_P(PSTR("[TELNET] Incorrect reverse telnet value given, use the form \"host:ip\""));
  108. }
  109. }
  110. }
  111. }
  112. #endif // MQTT_SUPPORT
  113. #endif // TELNET_REVERSE_SUPPORT
  114. #if TELNET_SERVER == TELNET_SERVER_WIFISERVER
  115. static std::vector<char> _telnet_data_buffer;
  116. void _telnetDisconnect(unsigned char clientId) {
  117. _telnetClients[clientId]->stop();
  118. _telnetClients[clientId] = nullptr;
  119. wifiReconnectCheck();
  120. DEBUG_MSG_P(PSTR("[TELNET] Client #%d disconnected\n"), clientId);
  121. }
  122. #elif TELNET_SERVER == TELNET_SERVER_ASYNC
  123. void _telnetCleanUp() {
  124. schedule_function([] () {
  125. for (unsigned char clientId=0; clientId < TELNET_MAX_CLIENTS; ++clientId) {
  126. if (!_telnetClients[clientId]->connected()) {
  127. _telnetClients[clientId] = nullptr;
  128. wifiReconnectCheck();
  129. DEBUG_MSG_P(PSTR("[TELNET] Client #%d disconnected\n"), clientId);
  130. }
  131. }
  132. });
  133. }
  134. // just close, clean-up method above will destroy the object later
  135. void _telnetDisconnect(unsigned char clientId) {
  136. _telnetClients[clientId]->close(true);
  137. }
  138. #if TELNET_SERVER_ASYNC_BUFFERED
  139. AsyncBufferedClient::AsyncBufferedClient(AsyncClient* client) : _client(client) {
  140. _client->onAck(_s_onAck, this);
  141. _client->onPoll(_s_onPoll, this);
  142. }
  143. void AsyncBufferedClient::_trySend(AsyncBufferedClient* client) {
  144. while (!client->_buffers.empty()) {
  145. auto& chunk = client->_buffers.front();
  146. if (client->_client->space() >= chunk.size()) {
  147. client->_client->write((const char*)chunk.data(), chunk.size());
  148. client->_buffers.pop_front();
  149. continue;
  150. }
  151. return;
  152. }
  153. }
  154. void AsyncBufferedClient::_s_onAck(void* client_ptr, AsyncClient*, size_t, uint32_t) {
  155. _trySend(reinterpret_cast<AsyncBufferedClient*>(client_ptr));
  156. }
  157. void AsyncBufferedClient::_s_onPoll(void* client_ptr, AsyncClient* client) {
  158. _trySend(reinterpret_cast<AsyncBufferedClient*>(client_ptr));
  159. }
  160. void AsyncBufferedClient::_addBuffer() {
  161. // Note: c++17 emplace returns created object reference
  162. _buffers.emplace_back();
  163. _buffers.back().reserve(TCP_MSS);
  164. }
  165. size_t AsyncBufferedClient::write(const char* data, size_t size) {
  166. if (_buffers.size() > AsyncBufferedClient::BUFFERS_MAX) return 0;
  167. size_t written = 0;
  168. if (_buffers.empty()) {
  169. written = _client->add(data, size);
  170. if (written == size) return size;
  171. }
  172. const size_t full_size = size;
  173. char* data_ptr = const_cast<char*>(data + written);
  174. size -= written;
  175. while (size) {
  176. if (_buffers.empty()) _addBuffer();
  177. auto& current = _buffers.back();
  178. const auto have = current.capacity() - current.size();
  179. if (have >= size) {
  180. current.insert(current.end(), data_ptr, data_ptr + size);
  181. size = 0;
  182. } else {
  183. current.insert(current.end(), data_ptr, data_ptr + have);
  184. _addBuffer();
  185. data_ptr += have;
  186. size -= have;
  187. }
  188. }
  189. return full_size;
  190. }
  191. size_t AsyncBufferedClient::write(char c) {
  192. char _c[1] {c};
  193. return write(_c, 1);
  194. }
  195. void AsyncBufferedClient::flush() {
  196. _client->send();
  197. }
  198. size_t AsyncBufferedClient::available() {
  199. return _client->space();
  200. }
  201. bool AsyncBufferedClient::connect(const char *host, uint16_t port) {
  202. return _client->connect(host, port);
  203. }
  204. void AsyncBufferedClient::close(bool now) {
  205. _client->close(now);
  206. }
  207. bool AsyncBufferedClient::connected() {
  208. return _client->connected();
  209. }
  210. #endif // TELNET_SERVER_ASYNC_BUFFERED
  211. #endif // TELNET_SERVER == TELNET_SERVER_WIFISERVER
  212. size_t _telnetWrite(unsigned char clientId, const char *data, size_t len) {
  213. if (_telnetClients[clientId] && _telnetClients[clientId]->connected()) {
  214. return _telnetClients[clientId]->write(data, len);
  215. }
  216. return 0;
  217. }
  218. size_t _telnetWrite(const char *data, size_t len) {
  219. unsigned char count = 0;
  220. for (unsigned char i = 0; i < TELNET_MAX_CLIENTS; i++) {
  221. // Do not send broadcast messages to unauthenticated clients
  222. if (_telnetAuth && !_telnetClientsAuth[i]) {
  223. continue;
  224. }
  225. if (_telnetWrite(i, data, len)) ++count;
  226. }
  227. return count;
  228. }
  229. size_t _telnetWrite(const char *data) {
  230. return _telnetWrite(data, strlen(data));
  231. }
  232. size_t _telnetWrite(unsigned char clientId, const char * message) {
  233. return _telnetWrite(clientId, message, strlen(message));
  234. }
  235. void _telnetData(unsigned char clientId, char * data, size_t len) {
  236. if ((len >= 2) && (data[0] == TELNET_IAC)) {
  237. // C-d is sent as two bytes (sometimes repeating)
  238. if (data[1] == TELNET_XEOF) {
  239. _telnetDisconnect(clientId);
  240. }
  241. return; // Ignore telnet negotiation
  242. }
  243. if ((strncmp(data, "close", 5) == 0) || (strncmp(data, "quit", 4) == 0)) {
  244. #if TELNET_SERVER == TELNET_SERVER_WIFISERVER
  245. _telnetDisconnect(clientId);
  246. #else
  247. _telnetClients[clientId]->close();
  248. #endif
  249. return;
  250. }
  251. // Password prompt (disable on CORE variant)
  252. const bool authenticated = isEspurnaCore() ? true : _telnetClientsAuth[clientId];
  253. if (_telnetAuth && !authenticated) {
  254. String password = getAdminPass();
  255. if (strncmp(data, password.c_str(), password.length()) == 0) {
  256. DEBUG_MSG_P(PSTR("[TELNET] Client #%d authenticated\n"), clientId);
  257. _telnetWrite(clientId, "Password correct, welcome!\n");
  258. _telnetClientsAuth[clientId] = true;
  259. } else {
  260. _telnetWrite(clientId, "Password (try again): ");
  261. }
  262. return;
  263. }
  264. // Inject command
  265. #if TERMINAL_SUPPORT
  266. terminalInject((void*)data, len);
  267. #endif
  268. }
  269. void _telnetNotifyConnected(unsigned char i) {
  270. DEBUG_MSG_P(PSTR("[TELNET] Client #%u connected\n"), i);
  271. // If there is no terminal support automatically dump info and crash data
  272. #if DEBUG_SUPPORT
  273. #if not TERMINAL_SUPPORT
  274. wifiDebug();
  275. crashDump(terminalDefaultStream());
  276. crashClear();
  277. #endif
  278. #endif
  279. if (!isEspurnaCore()) {
  280. _telnetClientsAuth[i] = !_telnetAuth;
  281. if (_telnetAuth) {
  282. if (getAdminPass().length()) {
  283. _telnetWrite(i, "Password: ");
  284. } else {
  285. _telnetClientsAuth[i] = true;
  286. }
  287. }
  288. } else {
  289. _telnetClientsAuth[i] = true;
  290. }
  291. wifiReconnectCheck();
  292. }
  293. #if TELNET_SERVER == TELNET_SERVER_WIFISERVER
  294. void _telnetLoop() {
  295. if (_telnetServer.hasClient()) {
  296. int i;
  297. for (i = 0; i < TELNET_MAX_CLIENTS; i++) {
  298. if (!_telnetClients[i] || !_telnetClients[i]->connected()) {
  299. _telnetClients[i] = std::make_unique<TTelnetClient>(_telnetServer.available());
  300. if (_telnetClients[i]->localIP() != WiFi.softAPIP()) {
  301. // Telnet is always available for the ESPurna Core image
  302. const bool can_connect = isEspurnaCore() ? true : getSetting("telnetSTA", 1 == TELNET_STA);
  303. if (!can_connect) {
  304. DEBUG_MSG_P(PSTR("[TELNET] Rejecting - Only local connections\n"));
  305. _telnetDisconnect(i);
  306. return;
  307. }
  308. }
  309. _telnetNotifyConnected(i);
  310. break;
  311. }
  312. }
  313. //no free/disconnected spot so reject
  314. if (i == TELNET_MAX_CLIENTS) {
  315. DEBUG_MSG_P(PSTR("[TELNET] Rejecting - Too many connections\n"));
  316. _telnetServer.available().stop();
  317. return;
  318. }
  319. }
  320. for (int i = 0; i < TELNET_MAX_CLIENTS; i++) {
  321. if (_telnetClients[i]) {
  322. // Handle client timeouts
  323. if (!_telnetClients[i]->connected()) {
  324. _telnetDisconnect(i);
  325. } else {
  326. // Read data from clients
  327. while (_telnetClients[i] && _telnetClients[i]->available()) {
  328. size_t len = _telnetClients[i]->available();
  329. unsigned int r = _telnetClients[i]->readBytes(_telnet_data_buffer.data(), min(_telnet_data_buffer.capacity(), len));
  330. _telnetData(i, _telnet_data_buffer.data(), r);
  331. }
  332. }
  333. }
  334. }
  335. }
  336. #elif TELNET_SERVER == TELNET_SERVER_ASYNC
  337. void _telnetSetupClient(unsigned char i, AsyncClient *client) {
  338. client->onError([i](void *s, AsyncClient *client, int8_t error) {
  339. DEBUG_MSG_P(PSTR("[TELNET] Error %s (%d) on client #%u\n"), client->errorToString(error), error, i);
  340. });
  341. client->onData([i](void*, AsyncClient*, void *data, size_t len){
  342. _telnetData(i, reinterpret_cast<char*>(data), len);
  343. });
  344. client->onDisconnect([i](void*, AsyncClient*) {
  345. _telnetCleanUp();
  346. });
  347. // XXX: AsyncClient does not have copy ctor
  348. #if TELNET_SERVER_ASYNC_BUFFERED
  349. _telnetClients[i] = std::make_unique<TTelnetClient>(client);
  350. #else
  351. _telnetClients[i] = std::unique_ptr<TTelnetClient>(client);
  352. #endif // TELNET_SERVER_ASYNC_BUFFERED
  353. }
  354. void _telnetNewClient(AsyncClient* client) {
  355. if (client->localIP() != WiFi.softAPIP()) {
  356. // Telnet is always available for the ESPurna Core image
  357. const bool can_connect = isEspurnaCore() ? true : getSetting("telnetSTA", 1 == TELNET_STA);
  358. if (!can_connect) {
  359. DEBUG_MSG_P(PSTR("[TELNET] Rejecting - Only local connections\n"));
  360. client->onDisconnect([](void *s, AsyncClient *c) {
  361. delete c;
  362. });
  363. client->close(true);
  364. return;
  365. }
  366. }
  367. for (unsigned char i = 0; i < TELNET_MAX_CLIENTS; i++) {
  368. if (!_telnetClients[i] || !_telnetClients[i]->connected()) {
  369. _telnetSetupClient(i, client);
  370. _telnetNotifyConnected(i);
  371. return;
  372. }
  373. }
  374. DEBUG_MSG_P(PSTR("[TELNET] Rejecting - Too many connections\n"));
  375. client->onDisconnect([](void *s, AsyncClient *c) {
  376. delete c;
  377. });
  378. client->close(true);
  379. }
  380. #endif // TELNET_SERVER == TELNET_SERVER_WIFISERVER
  381. // -----------------------------------------------------------------------------
  382. // Public API
  383. // -----------------------------------------------------------------------------
  384. bool telnetConnected() {
  385. for (auto& client : _telnetClients) {
  386. if (client && client->connected()) return true;
  387. }
  388. return false;
  389. }
  390. #if DEBUG_TELNET_SUPPORT
  391. bool telnetDebugSend(const char* prefix, const char* data) {
  392. if (!telnetConnected()) return false;
  393. bool result = false;
  394. if (prefix && (prefix[0] != '\0')) {
  395. result = _telnetWrite(prefix) > 0;
  396. }
  397. return (_telnetWrite(data) > 0) || result;
  398. }
  399. #endif // DEBUG_TELNET_SUPPORT
  400. unsigned char telnetWrite(unsigned char ch) {
  401. char data[1] = {ch};
  402. return _telnetWrite(data, 1);
  403. }
  404. void _telnetConfigure() {
  405. _telnetAuth = getSetting("telnetAuth", 1 == TELNET_AUTHENTICATION);
  406. }
  407. void telnetSetup() {
  408. #if TELNET_SERVER == TELNET_SERVER_WIFISERVER
  409. _telnet_data_buffer.reserve(terminalCapacity());
  410. _telnetServer.setNoDelay(true);
  411. _telnetServer.begin();
  412. espurnaRegisterLoop(_telnetLoop);
  413. #else
  414. _telnetServer.onClient([](void *s, AsyncClient* c) {
  415. _telnetNewClient(c);
  416. }, nullptr);
  417. _telnetServer.begin();
  418. #endif
  419. #if WEB_SUPPORT
  420. wsRegister()
  421. .onVisible([](JsonObject& root) { root["telnetVisible"] = 1; })
  422. .onConnected(_telnetWebSocketOnConnected)
  423. .onKeyCheck(_telnetWebSocketOnKeyCheck);
  424. #endif
  425. #if TELNET_REVERSE_SUPPORT
  426. #if MQTT_SUPPORT
  427. mqttRegister(_telnetReverseMQTTCallback);
  428. #endif
  429. #if TERMINAL_SUPPORT
  430. terminalRegisterCommand(F("TELNET.REVERSE"), [](const terminal::CommandContext& ctx) {
  431. if (ctx.argc < 3) {
  432. terminalError(F("Wrong arguments. Usage: TELNET.REVERSE <host> <port>"));
  433. return;
  434. }
  435. terminalOK();
  436. _telnetReverse(ctx.argv[1].c_str(), ctx.argv[2].toInt());
  437. });
  438. #endif
  439. #endif
  440. espurnaRegisterReload(_telnetConfigure);
  441. _telnetConfigure();
  442. DEBUG_MSG_P(PSTR("[TELNET] Listening on port %d\n"), TELNET_PORT);
  443. }
  444. #endif // TELNET_SUPPORT