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.

324 lines
9.7 KiB

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
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
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
7 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. */
  7. #if TELNET_SUPPORT
  8. #define TELNET_IAC 0xFF
  9. #define TELNET_XEOF 0xEC
  10. #if TELNET_SERVER == TELNET_SERVER_WIFISERVER
  11. #include <ESP8266WiFi.h>
  12. WiFiServer _telnetServer = WiFiServer(TELNET_PORT);
  13. std::unique_ptr<WiFiClient> _telnetClients[TELNET_MAX_CLIENTS];
  14. #else
  15. #include <ESPAsyncTCP.h>
  16. AsyncServer _telnetServer = AsyncServer(TELNET_PORT);
  17. std::unique_ptr<AsyncClient> _telnetClients[TELNET_MAX_CLIENTS];
  18. #endif
  19. bool _telnetAuth = TELNET_AUTHENTICATION;
  20. bool _telnetClientsAuth[TELNET_MAX_CLIENTS];
  21. // -----------------------------------------------------------------------------
  22. // Private methods
  23. // -----------------------------------------------------------------------------
  24. #if WEB_SUPPORT
  25. bool _telnetWebSocketOnKeyCheck(const char * key, JsonVariant& value) {
  26. return (strncmp(key, "telnet", 6) == 0);
  27. }
  28. void _telnetWebSocketOnConnected(JsonObject& root) {
  29. root["telnetSTA"] = getSetting("telnetSTA", TELNET_STA).toInt() == 1;
  30. root["telnetAuth"] = getSetting("telnetAuth", TELNET_AUTHENTICATION).toInt() == 1;
  31. }
  32. #endif
  33. void _telnetDisconnect(unsigned char clientId) {
  34. // ref: we are called from onDisconnect, async is already stopped
  35. #if TELNET_SERVER == TELNET_SERVER_WIFISERVER
  36. _telnetClients[clientId]->stop();
  37. #endif
  38. _telnetClients[clientId] = nullptr;
  39. wifiReconnectCheck();
  40. DEBUG_MSG_P(PSTR("[TELNET] Client #%d disconnected\n"), clientId);
  41. }
  42. bool _telnetWrite(unsigned char clientId, const char *data, size_t len) {
  43. if (_telnetClients[clientId] && _telnetClients[clientId]->connected()) {
  44. return (_telnetClients[clientId]->write(data, len) > 0);
  45. }
  46. return false;
  47. }
  48. unsigned char _telnetWrite(const char *data, size_t len) {
  49. unsigned char count = 0;
  50. for (unsigned char i = 0; i < TELNET_MAX_CLIENTS; i++) {
  51. // Do not send broadcast messages to unauthenticated clients
  52. if (_telnetAuth && !_telnetClientsAuth[i]) {
  53. continue;
  54. }
  55. if (_telnetWrite(i, data, len)) ++count;
  56. }
  57. return count;
  58. }
  59. unsigned char _telnetWrite(const char *data) {
  60. return _telnetWrite(data, strlen(data));
  61. }
  62. bool _telnetWrite(unsigned char clientId, const char * message) {
  63. return _telnetWrite(clientId, message, strlen(message));
  64. }
  65. void _telnetData(unsigned char clientId, void *data, size_t len) {
  66. // Capture close connection
  67. char * p = (char *) data;
  68. if ((len >= 2) && (p[0] == TELNET_IAC)) {
  69. // C-d is sent as two bytes (sometimes repeating)
  70. if (p[1] == TELNET_XEOF) {
  71. _telnetDisconnect(clientId);
  72. }
  73. return; // Ignore telnet negotiation
  74. }
  75. if ((strncmp(p, "close", 5) == 0) || (strncmp(p, "quit", 4) == 0)) {
  76. _telnetDisconnect(clientId);
  77. return;
  78. }
  79. // Password prompt (disable on CORE variant)
  80. #ifdef ESPURNA_CORE
  81. const bool authenticated = true;
  82. #else
  83. const bool authenticated = _telnetClientsAuth[clientId];
  84. #endif
  85. if (_telnetAuth && !authenticated) {
  86. String password = getAdminPass();
  87. if (strncmp(p, password.c_str(), password.length()) == 0) {
  88. DEBUG_MSG_P(PSTR("[TELNET] Client #%d authenticated\n"), clientId);
  89. _telnetWrite(clientId, "Password correct, welcome!\n");
  90. _telnetClientsAuth[clientId] = true;
  91. } else {
  92. _telnetWrite(clientId, "Password (try again): ");
  93. }
  94. return;
  95. }
  96. // Inject command
  97. #if TERMINAL_SUPPORT
  98. terminalInject(data, len);
  99. #endif
  100. }
  101. void _telnetNotifyConnected(unsigned char i) {
  102. DEBUG_MSG_P(PSTR("[TELNET] Client #%u connected\n"), i);
  103. // If there is no terminal support automatically dump info and crash data
  104. #if TERMINAL_SUPPORT == 0
  105. info();
  106. wifiDebug();
  107. crashDump();
  108. crashClear();
  109. #endif
  110. #ifdef ESPURNA_CORE
  111. _telnetClientsAuth[i] = true;
  112. #else
  113. _telnetClientsAuth[i] = !_telnetAuth;
  114. if (_telnetAuth) {
  115. if (getAdminPass().length()) {
  116. _telnetWrite(i, "Password: ");
  117. } else {
  118. _telnetClientsAuth[i] = true;
  119. }
  120. }
  121. #endif
  122. wifiReconnectCheck();
  123. }
  124. #if TELNET_SERVER == TELNET_SERVER_WIFISERVER
  125. void _telnetLoop() {
  126. if (_telnetServer.hasClient()) {
  127. int i;
  128. for (i = 0; i < TELNET_MAX_CLIENTS; i++) {
  129. if (!_telnetClients[i] || !_telnetClients[i]->connected()) {
  130. _telnetClients[i] = std::unique_ptr<WiFiClient>(new WiFiClient(_telnetServer.available()));
  131. if (_telnetClients[i]->localIP() != WiFi.softAPIP()) {
  132. // Telnet is always available for the ESPurna Core image
  133. #ifdef ESPURNA_CORE
  134. bool telnetSTA = true;
  135. #else
  136. bool telnetSTA = getSetting("telnetSTA", TELNET_STA).toInt() == 1;
  137. #endif
  138. if (!telnetSTA) {
  139. DEBUG_MSG_P(PSTR("[TELNET] Rejecting - Only local connections\n"));
  140. _telnetDisconnect(i);
  141. return;
  142. }
  143. }
  144. _telnetNotifyConnected(i);
  145. break;
  146. }
  147. }
  148. //no free/disconnected spot so reject
  149. if (i == TELNET_MAX_CLIENTS) {
  150. DEBUG_MSG_P(PSTR("[TELNET] Rejecting - Too many connections\n"));
  151. _telnetServer.available().stop();
  152. return;
  153. }
  154. }
  155. for (int i = 0; i < TELNET_MAX_CLIENTS; i++) {
  156. if (_telnetClients[i]) {
  157. // Handle client timeouts
  158. if (!_telnetClients[i]->connected()) {
  159. _telnetDisconnect(i);
  160. } else {
  161. // Read data from clients
  162. while (_telnetClients[i] && _telnetClients[i]->available()) {
  163. char data[TERMINAL_BUFFER_SIZE];
  164. size_t len = _telnetClients[i]->available();
  165. unsigned int r = _telnetClients[i]->readBytes(data, min(sizeof(data), len));
  166. _telnetData(i, data, r);
  167. }
  168. }
  169. }
  170. }
  171. }
  172. #else // TELNET_SERVER_ASYNC
  173. void _telnetNewClient(AsyncClient* client) {
  174. if (client->localIP() != WiFi.softAPIP()) {
  175. // Telnet is always available for the ESPurna Core image
  176. #ifdef ESPURNA_CORE
  177. bool telnetSTA = true;
  178. #else
  179. bool telnetSTA = getSetting("telnetSTA", TELNET_STA).toInt() == 1;
  180. #endif
  181. if (!telnetSTA) {
  182. DEBUG_MSG_P(PSTR("[TELNET] Rejecting - Only local connections\n"));
  183. client->onDisconnect([](void *s, AsyncClient *c) {
  184. delete c;
  185. });
  186. client->close(true);
  187. return;
  188. }
  189. }
  190. for (unsigned char i = 0; i < TELNET_MAX_CLIENTS; i++) {
  191. if (!_telnetClients[i] || !_telnetClients[i]->connected()) {
  192. _telnetClients[i] = std::unique_ptr<AsyncClient>(client);
  193. _telnetClients[i]->onAck([i](void *s, AsyncClient *c, size_t len, uint32_t time) {
  194. }, 0);
  195. _telnetClients[i]->onData([i](void *s, AsyncClient *c, void *data, size_t len) {
  196. _telnetData(i, data, len);
  197. }, 0);
  198. _telnetClients[i]->onDisconnect([i](void *s, AsyncClient *c) {
  199. _telnetDisconnect(i);
  200. }, 0);
  201. _telnetClients[i]->onError([i](void *s, AsyncClient *c, int8_t error) {
  202. DEBUG_MSG_P(PSTR("[TELNET] Error %s (%d) on client #%u\n"), c->errorToString(error), error, i);
  203. }, 0);
  204. _telnetClients[i]->onTimeout([i](void *s, AsyncClient *c, uint32_t time) {
  205. DEBUG_MSG_P(PSTR("[TELNET] Timeout on client #%u at %lu\n"), i, time);
  206. c->close();
  207. }, 0);
  208. _telnetNotifyConnected(i);
  209. return;
  210. }
  211. }
  212. DEBUG_MSG_P(PSTR("[TELNET] Rejecting - Too many connections\n"));
  213. client->onDisconnect([](void *s, AsyncClient *c) {
  214. delete c;
  215. });
  216. client->close(true);
  217. }
  218. #endif // TELNET_SERVER == TELNET_SERVER_WIFISERVER
  219. // -----------------------------------------------------------------------------
  220. // Public API
  221. // -----------------------------------------------------------------------------
  222. bool telnetConnected() {
  223. for (unsigned char i = 0; i < TELNET_MAX_CLIENTS; i++) {
  224. if (_telnetClients[i] && _telnetClients[i]->connected()) return true;
  225. }
  226. return false;
  227. }
  228. unsigned char telnetWrite(unsigned char ch) {
  229. char data[1] = {ch};
  230. return _telnetWrite(data, 1);
  231. }
  232. void _telnetConfigure() {
  233. _telnetAuth = getSetting("telnetAuth", TELNET_AUTHENTICATION).toInt() == 1;
  234. }
  235. void telnetSetup() {
  236. #if TELNET_SERVER == TELNET_SERVER_WIFISERVER
  237. espurnaRegisterLoop(_telnetLoop);
  238. _telnetServer.setNoDelay(true);
  239. _telnetServer.begin();
  240. #else
  241. _telnetServer.onClient([](void *s, AsyncClient* c) {
  242. _telnetNewClient(c);
  243. }, 0);
  244. _telnetServer.begin();
  245. #endif
  246. #if WEB_SUPPORT
  247. wsRegister()
  248. .onVisible([](JsonObject& root) { root["telnetVisible"] = 1; })
  249. .onConnected(_telnetWebSocketOnConnected)
  250. .onKeyCheck(_telnetWebSocketOnKeyCheck);
  251. #endif
  252. espurnaRegisterReload(_telnetConfigure);
  253. _telnetConfigure();
  254. DEBUG_MSG_P(PSTR("[TELNET] %s server, Listening on port %d\n"),
  255. (TELNET_SERVER == TELNET_SERVER_WIFISERVER) ? "Sync" : "Async",
  256. TELNET_PORT);
  257. }
  258. #endif // TELNET_SUPPORT