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.

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