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.

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