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.

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