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.

575 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
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. DEBUG_MSG_P(PSTR("[TELNET] Client #%d disconnected\n"), clientId);
  125. wifiApCheck();
  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. DEBUG_MSG_P(PSTR("[TELNET] Client #%d disconnected\n"), clientId);
  134. wifiApCheck();
  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. crashDump(terminalDefaultStream());
  281. crashClear();
  282. #endif
  283. #endif
  284. if (!isEspurnaCore()) {
  285. _telnetClientsAuth[i] = !_telnetAuth;
  286. if (_telnetAuth) {
  287. if (getAdminPass().length()) {
  288. _telnetWrite(i, "Password: ");
  289. } else {
  290. _telnetClientsAuth[i] = true;
  291. }
  292. }
  293. } else {
  294. _telnetClientsAuth[i] = true;
  295. }
  296. }
  297. #if TELNET_SERVER == TELNET_SERVER_WIFISERVER
  298. void _telnetLoop() {
  299. if (_telnetServer.hasClient()) {
  300. int i;
  301. for (i = 0; i < TELNET_MAX_CLIENTS; i++) {
  302. if (!_telnetClients[i] || !_telnetClients[i]->connected()) {
  303. _telnetClients[i] = std::make_unique<TTelnetClient>(_telnetServer.available());
  304. if (_telnetClients[i]->localIP() != WiFi.softAPIP()) {
  305. // Telnet is always available for the ESPurna Core image
  306. const bool can_connect = isEspurnaCore() ? true : getSetting("telnetSTA", 1 == TELNET_STA);
  307. if (!can_connect) {
  308. DEBUG_MSG_P(PSTR("[TELNET] Rejecting - Only local connections\n"));
  309. _telnetDisconnect(i);
  310. return;
  311. }
  312. }
  313. _telnetNotifyConnected(i);
  314. break;
  315. }
  316. }
  317. //no free/disconnected spot so reject
  318. if (i == TELNET_MAX_CLIENTS) {
  319. DEBUG_MSG_P(PSTR("[TELNET] Rejecting - Too many connections\n"));
  320. _telnetServer.available().stop();
  321. return;
  322. }
  323. }
  324. for (int i = 0; i < TELNET_MAX_CLIENTS; i++) {
  325. if (_telnetClients[i]) {
  326. // Handle client timeouts
  327. if (!_telnetClients[i]->connected()) {
  328. _telnetDisconnect(i);
  329. } else {
  330. // Read data from clients
  331. while (_telnetClients[i] && _telnetClients[i]->available()) {
  332. size_t len = _telnetClients[i]->available();
  333. unsigned int r = _telnetClients[i]->readBytes(_telnet_data_buffer.data(), min(_telnet_data_buffer.capacity(), len));
  334. _telnetData(i, _telnet_data_buffer.data(), r);
  335. }
  336. }
  337. }
  338. }
  339. }
  340. #elif TELNET_SERVER == TELNET_SERVER_ASYNC
  341. void _telnetSetupClient(unsigned char i, AsyncClient *client) {
  342. client->onError([i](void *s, AsyncClient *client, int8_t error) {
  343. DEBUG_MSG_P(PSTR("[TELNET] Error %s (%d) on client #%u\n"), client->errorToString(error), error, i);
  344. });
  345. client->onData([i](void*, AsyncClient*, void *data, size_t len){
  346. _telnetData(i, reinterpret_cast<char*>(data), len);
  347. });
  348. client->onDisconnect([i](void*, AsyncClient*) {
  349. _telnetCleanUp();
  350. });
  351. // XXX: AsyncClient does not have copy ctor
  352. #if TELNET_SERVER_ASYNC_BUFFERED
  353. _telnetClients[i] = std::make_unique<TTelnetClient>(client);
  354. #else
  355. _telnetClients[i] = std::unique_ptr<TTelnetClient>(client);
  356. #endif // TELNET_SERVER_ASYNC_BUFFERED
  357. }
  358. void _telnetNewClient(AsyncClient* client) {
  359. if (client->localIP() != WiFi.softAPIP()) {
  360. // Telnet is always available for the ESPurna Core image
  361. const bool can_connect = isEspurnaCore() ? true : getSetting("telnetSTA", 1 == TELNET_STA);
  362. if (!can_connect) {
  363. DEBUG_MSG_P(PSTR("[TELNET] Rejecting - Only local connections\n"));
  364. client->onDisconnect([](void *s, AsyncClient *c) {
  365. delete c;
  366. });
  367. client->close(true);
  368. return;
  369. }
  370. }
  371. for (unsigned char i = 0; i < TELNET_MAX_CLIENTS; i++) {
  372. if (!_telnetClients[i] || !_telnetClients[i]->connected()) {
  373. _telnetSetupClient(i, client);
  374. _telnetNotifyConnected(i);
  375. return;
  376. }
  377. }
  378. DEBUG_MSG_P(PSTR("[TELNET] Rejecting - Too many connections\n"));
  379. client->onDisconnect([](void *s, AsyncClient *c) {
  380. delete c;
  381. });
  382. client->close(true);
  383. }
  384. #endif // TELNET_SERVER == TELNET_SERVER_WIFISERVER
  385. // -----------------------------------------------------------------------------
  386. // Public API
  387. // -----------------------------------------------------------------------------
  388. bool telnetConnected() {
  389. for (auto& client : _telnetClients) {
  390. if (client && client->connected()) return true;
  391. }
  392. return false;
  393. }
  394. #if DEBUG_TELNET_SUPPORT
  395. bool telnetDebugSend(const char* prefix, const char* data) {
  396. if (!telnetConnected()) return false;
  397. bool result = false;
  398. if (prefix && (prefix[0] != '\0')) {
  399. result = _telnetWrite(prefix) > 0;
  400. }
  401. return (_telnetWrite(data) > 0) || result;
  402. }
  403. #endif // DEBUG_TELNET_SUPPORT
  404. unsigned char telnetWrite(unsigned char ch) {
  405. char data[1] = {ch};
  406. return _telnetWrite(data, 1);
  407. }
  408. void _telnetConfigure() {
  409. _telnetAuth = getSetting("telnetAuth", 1 == TELNET_AUTHENTICATION);
  410. }
  411. void telnetSetup() {
  412. #if TELNET_SERVER == TELNET_SERVER_WIFISERVER
  413. _telnet_data_buffer.reserve(terminalCapacity());
  414. _telnetServer.setNoDelay(true);
  415. _telnetServer.begin();
  416. espurnaRegisterLoop(_telnetLoop);
  417. #else
  418. _telnetServer.onClient([](void *s, AsyncClient* c) {
  419. _telnetNewClient(c);
  420. }, nullptr);
  421. _telnetServer.begin();
  422. #endif
  423. #if WEB_SUPPORT
  424. wsRegister()
  425. .onVisible([](JsonObject& root) { root["telnetVisible"] = 1; })
  426. .onConnected(_telnetWebSocketOnConnected)
  427. .onKeyCheck(_telnetWebSocketOnKeyCheck);
  428. #endif
  429. #if TELNET_REVERSE_SUPPORT
  430. #if MQTT_SUPPORT
  431. mqttRegister(_telnetReverseMQTTCallback);
  432. #endif
  433. #if TERMINAL_SUPPORT
  434. terminalRegisterCommand(F("TELNET.REVERSE"), [](const terminal::CommandContext& ctx) {
  435. if (ctx.argc < 3) {
  436. terminalError(F("Wrong arguments. Usage: TELNET.REVERSE <host> <port>"));
  437. return;
  438. }
  439. terminalOK();
  440. _telnetReverse(ctx.argv[1].c_str(), ctx.argv[2].toInt());
  441. });
  442. #endif
  443. #endif
  444. espurnaRegisterReload(_telnetConfigure);
  445. _telnetConfigure();
  446. DEBUG_MSG_P(PSTR("[TELNET] Listening on port %d\n"), TELNET_PORT);
  447. }
  448. #endif // TELNET_SUPPORT