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.

509 lines
15 KiB

8 years ago
8 years ago
8 years ago
5 years ago
8 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
8 years ago
  1. /*
  2. WEBSERVER MODULE
  3. Copyright (C) 2016-2019 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #if WEB_SUPPORT
  6. #include <ESPAsyncTCP.h>
  7. #include <ESPAsyncWebServer.h>
  8. #include <Hash.h>
  9. #include <FS.h>
  10. #include <AsyncJson.h>
  11. #include <ArduinoJson.h>
  12. #if WEB_EMBEDDED
  13. #if WEBUI_IMAGE == WEBUI_IMAGE_SMALL
  14. #include "static/index.small.html.gz.h"
  15. #elif WEBUI_IMAGE == WEBUI_IMAGE_LIGHT
  16. #include "static/index.light.html.gz.h"
  17. #elif WEBUI_IMAGE == WEBUI_IMAGE_SENSOR
  18. #include "static/index.sensor.html.gz.h"
  19. #elif WEBUI_IMAGE == WEBUI_IMAGE_RFBRIDGE
  20. #include "static/index.rfbridge.html.gz.h"
  21. #elif WEBUI_IMAGE == WEBUI_IMAGE_RFM69
  22. #include "static/index.rfm69.html.gz.h"
  23. #elif WEBUI_IMAGE == WEBUI_IMAGE_LIGHTFOX
  24. #include "static/index.lightfox.html.gz.h"
  25. #elif WEBUI_IMAGE == WEBUI_IMAGE_THERMOSTAT
  26. #include "static/index.thermostat.html.gz.h"
  27. #elif WEBUI_IMAGE == WEBUI_IMAGE_FULL
  28. #include "static/index.all.html.gz.h"
  29. #endif
  30. #endif // WEB_EMBEDDED
  31. #if ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  32. #include "static/server.cer.h"
  33. #include "static/server.key.h"
  34. #endif // ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  35. // -----------------------------------------------------------------------------
  36. AsyncWebServer * _server;
  37. char _last_modified[50];
  38. std::vector<uint8_t> * _webConfigBuffer;
  39. bool _webConfigSuccess = false;
  40. std::vector<web_request_callback_f> _web_request_callbacks;
  41. std::vector<web_body_callback_f> _web_body_callbacks;
  42. constexpr const size_t WEB_CONFIG_BUFFER_MAX = 4096;
  43. // -----------------------------------------------------------------------------
  44. // HOOKS
  45. // -----------------------------------------------------------------------------
  46. void _onReset(AsyncWebServerRequest *request) {
  47. webLog(request);
  48. if (!webAuthenticate(request)) {
  49. return request->requestAuthentication(getSetting("hostname").c_str());
  50. }
  51. deferredReset(100, CUSTOM_RESET_HTTP);
  52. request->send(200);
  53. }
  54. void _onDiscover(AsyncWebServerRequest *request) {
  55. webLog(request);
  56. AsyncResponseStream *response = request->beginResponseStream("application/json");
  57. const String device = getBoardName();
  58. const String hostname = getSetting("hostname");
  59. StaticJsonBuffer<JSON_OBJECT_SIZE(4)> jsonBuffer;
  60. JsonObject &root = jsonBuffer.createObject();
  61. root["app"] = APP_NAME;
  62. root["version"] = APP_VERSION;
  63. root["device"] = device.c_str();
  64. root["hostname"] = hostname.c_str();
  65. root.printTo(*response);
  66. request->send(response);
  67. }
  68. void _onGetConfig(AsyncWebServerRequest *request) {
  69. webLog(request);
  70. if (!webAuthenticate(request)) {
  71. return request->requestAuthentication(getSetting("hostname").c_str());
  72. }
  73. AsyncResponseStream *response = request->beginResponseStream("text/json");
  74. char buffer[100];
  75. snprintf_P(buffer, sizeof(buffer), PSTR("attachment; filename=\"%s-backup.json\""), (char *) getSetting("hostname").c_str());
  76. response->addHeader("Content-Disposition", buffer);
  77. response->addHeader("X-XSS-Protection", "1; mode=block");
  78. response->addHeader("X-Content-Type-Options", "nosniff");
  79. response->addHeader("X-Frame-Options", "deny");
  80. response->printf("{\n\"app\": \"%s\"", APP_NAME);
  81. response->printf(",\n\"version\": \"%s\"", APP_VERSION);
  82. response->printf(",\n\"backup\": \"1\"");
  83. #if NTP_SUPPORT
  84. response->printf(",\n\"timestamp\": \"%s\"", ntpDateTime().c_str());
  85. #endif
  86. // Write the keys line by line (not sorted)
  87. unsigned long count = settingsKeyCount();
  88. for (unsigned int i=0; i<count; i++) {
  89. String key = settingsKeyName(i);
  90. String value = getSetting(key);
  91. response->printf(",\n\"%s\": \"%s\"", key.c_str(), value.c_str());
  92. }
  93. response->printf("\n}");
  94. request->send(response);
  95. }
  96. void _onPostConfig(AsyncWebServerRequest *request) {
  97. webLog(request);
  98. if (!webAuthenticate(request)) {
  99. return request->requestAuthentication(getSetting("hostname").c_str());
  100. }
  101. request->send(_webConfigSuccess ? 200 : 400);
  102. }
  103. void _onPostConfigData(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) {
  104. if (!webAuthenticate(request)) {
  105. return request->requestAuthentication(getSetting("hostname").c_str());
  106. }
  107. // No buffer
  108. if (final && (index == 0)) {
  109. _webConfigSuccess = settingsRestoreJson((char*) data);
  110. return;
  111. }
  112. // Buffer start => reset
  113. if (index == 0) if (_webConfigBuffer) delete _webConfigBuffer;
  114. // init buffer if it doesn't exist
  115. if (!_webConfigBuffer) {
  116. _webConfigBuffer = new std::vector<uint8_t>();
  117. _webConfigSuccess = false;
  118. }
  119. // Copy
  120. if (len > 0) {
  121. if ((_webConfigBuffer->size() + len) > std::min(WEB_CONFIG_BUFFER_MAX, getFreeHeap() - sizeof(std::vector<uint8_t>))) {
  122. delete _webConfigBuffer;
  123. _webConfigBuffer = nullptr;
  124. request->send(500);
  125. return;
  126. }
  127. _webConfigBuffer->reserve(_webConfigBuffer->size() + len);
  128. _webConfigBuffer->insert(_webConfigBuffer->end(), data, data + len);
  129. }
  130. // Ending
  131. if (final) {
  132. _webConfigBuffer->push_back(0);
  133. _webConfigSuccess = settingsRestoreJson((char*) _webConfigBuffer->data());
  134. delete _webConfigBuffer;
  135. }
  136. }
  137. #if WEB_EMBEDDED
  138. void _onHome(AsyncWebServerRequest *request) {
  139. webLog(request);
  140. if (!webAuthenticate(request)) {
  141. return request->requestAuthentication(getSetting("hostname").c_str());
  142. }
  143. if (request->header("If-Modified-Since").equals(_last_modified)) {
  144. request->send(304);
  145. } else {
  146. #if ASYNC_TCP_SSL_ENABLED
  147. // Chunked response, we calculate the chunks based on free heap (in multiples of 32)
  148. // This is necessary when a TLS connection is open since it sucks too much memory
  149. DEBUG_MSG_P(PSTR("[MAIN] Free heap: %d bytes\n"), getFreeHeap());
  150. size_t max = (getFreeHeap() / 3) & 0xFFE0;
  151. AsyncWebServerResponse *response = request->beginChunkedResponse("text/html", [max](uint8_t *buffer, size_t maxLen, size_t index) -> size_t {
  152. // Get the chunk based on the index and maxLen
  153. size_t len = webui_image_len - index;
  154. if (len > maxLen) len = maxLen;
  155. if (len > max) len = max;
  156. if (len > 0) memcpy_P(buffer, webui_image + index, len);
  157. DEBUG_MSG_P(PSTR("[WEB] Sending %d%%%% (max chunk size: %4d)\r"), int(100 * index / webui_image_len), max);
  158. if (len == 0) DEBUG_MSG_P(PSTR("\n"));
  159. // Return the actual length of the chunk (0 for end of file)
  160. return len;
  161. });
  162. #else
  163. AsyncWebServerResponse *response = request->beginResponse_P(200, "text/html", webui_image, webui_image_len);
  164. #endif
  165. response->addHeader("Content-Encoding", "gzip");
  166. response->addHeader("Last-Modified", _last_modified);
  167. response->addHeader("X-XSS-Protection", "1; mode=block");
  168. response->addHeader("X-Content-Type-Options", "nosniff");
  169. response->addHeader("X-Frame-Options", "deny");
  170. request->send(response);
  171. }
  172. }
  173. #endif
  174. #if ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  175. int _onCertificate(void * arg, const char *filename, uint8_t **buf) {
  176. #if WEB_EMBEDDED
  177. if (strcmp(filename, "server.cer") == 0) {
  178. uint8_t * nbuf = (uint8_t*) malloc(server_cer_len);
  179. memcpy_P(nbuf, server_cer, server_cer_len);
  180. *buf = nbuf;
  181. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - OK\n"), filename);
  182. return server_cer_len;
  183. }
  184. if (strcmp(filename, "server.key") == 0) {
  185. uint8_t * nbuf = (uint8_t*) malloc(server_key_len);
  186. memcpy_P(nbuf, server_key, server_key_len);
  187. *buf = nbuf;
  188. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - OK\n"), filename);
  189. return server_key_len;
  190. }
  191. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - ERROR\n"), filename);
  192. *buf = 0;
  193. return 0;
  194. #else
  195. File file = SPIFFS.open(filename, "r");
  196. if (file) {
  197. size_t size = file.size();
  198. uint8_t * nbuf = (uint8_t*) malloc(size);
  199. if (nbuf) {
  200. size = file.read(nbuf, size);
  201. file.close();
  202. *buf = nbuf;
  203. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - OK\n"), filename);
  204. return size;
  205. }
  206. file.close();
  207. }
  208. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - ERROR\n"), filename);
  209. *buf = 0;
  210. return 0;
  211. #endif
  212. }
  213. #endif
  214. void _onUpgrade(AsyncWebServerRequest *request) {
  215. webLog(request);
  216. if (!webAuthenticate(request)) {
  217. return request->requestAuthentication(getSetting("hostname").c_str());
  218. }
  219. char buffer[10];
  220. if (!Update.hasError()) {
  221. sprintf_P(buffer, PSTR("OK"));
  222. } else {
  223. sprintf_P(buffer, PSTR("ERROR %d"), Update.getError());
  224. }
  225. AsyncWebServerResponse *response = request->beginResponse(200, "text/plain", buffer);
  226. response->addHeader("Connection", "close");
  227. response->addHeader("X-XSS-Protection", "1; mode=block");
  228. response->addHeader("X-Content-Type-Options", "nosniff");
  229. response->addHeader("X-Frame-Options", "deny");
  230. if (Update.hasError()) {
  231. eepromRotate(true);
  232. } else {
  233. deferredReset(100, CUSTOM_RESET_UPGRADE);
  234. }
  235. request->send(response);
  236. }
  237. void _onUpgradeFile(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) {
  238. if (!webAuthenticate(request)) {
  239. return request->requestAuthentication(getSetting("hostname").c_str());
  240. }
  241. if (!index) {
  242. // Disabling EEPROM rotation to prevent writing to EEPROM after the upgrade
  243. eepromRotate(false);
  244. DEBUG_MSG_P(PSTR("[UPGRADE] Start: %s\n"), filename.c_str());
  245. Update.runAsync(true);
  246. if (!Update.begin((ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000)) {
  247. #ifdef DEBUG_PORT
  248. Update.printError(DEBUG_PORT);
  249. #endif
  250. }
  251. }
  252. if (!Update.hasError()) {
  253. if (Update.write(data, len) != len) {
  254. #ifdef DEBUG_PORT
  255. Update.printError(DEBUG_PORT);
  256. #endif
  257. }
  258. }
  259. if (final) {
  260. if (Update.end(true)){
  261. DEBUG_MSG_P(PSTR("[UPGRADE] Success: %u bytes\n"), index + len);
  262. } else {
  263. #ifdef DEBUG_PORT
  264. Update.printError(DEBUG_PORT);
  265. #endif
  266. }
  267. } else {
  268. // Removed to avoid websocket ping back during upgrade (see #1574)
  269. // TODO: implement as separate from debugging message
  270. if (wsConnected()) return;
  271. DEBUG_MSG_P(PSTR("[UPGRADE] Progress: %u bytes\r"), index + len);
  272. }
  273. }
  274. bool _onAPModeRequest(AsyncWebServerRequest *request) {
  275. if ((WiFi.getMode() & WIFI_AP) > 0) {
  276. const String domain = getSetting("hostname") + ".";
  277. const String host = request->header("Host");
  278. const String ip = WiFi.softAPIP().toString();
  279. // Only allow requests that use our hostname or ip
  280. if (host.equals(ip)) return true;
  281. if (host.startsWith(domain)) return true;
  282. // Immediatly close the connection, ref: https://github.com/xoseperez/espurna/issues/1660
  283. // Not doing so will cause memory exhaustion, because the connection will linger
  284. request->send(404);
  285. request->client()->close();
  286. return false;
  287. }
  288. return true;
  289. }
  290. void _onRequest(AsyncWebServerRequest *request){
  291. if (!_onAPModeRequest(request)) return;
  292. // Send request to subscribers
  293. for (unsigned char i = 0; i < _web_request_callbacks.size(); i++) {
  294. bool response = (_web_request_callbacks[i])(request);
  295. if (response) return;
  296. }
  297. // No subscriber handled the request, return a 404 with implicit "Connection: close"
  298. request->send(404);
  299. // And immediatly close the connection, ref: https://github.com/xoseperez/espurna/issues/1660
  300. // Not doing so will cause memory exhaustion, because the connection will linger
  301. request->client()->close();
  302. }
  303. void _onBody(AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total) {
  304. if (!_onAPModeRequest(request)) return;
  305. // Send request to subscribers
  306. for (unsigned char i = 0; i < _web_body_callbacks.size(); i++) {
  307. bool response = (_web_body_callbacks[i])(request, data, len, index, total);
  308. if (response) return;
  309. }
  310. // Same as _onAPModeRequest(...)
  311. request->send(404);
  312. request->client()->close();
  313. }
  314. // -----------------------------------------------------------------------------
  315. bool webAuthenticate(AsyncWebServerRequest *request) {
  316. #if USE_PASSWORD
  317. String password = getAdminPass();
  318. char httpPassword[password.length() + 1];
  319. password.toCharArray(httpPassword, password.length() + 1);
  320. return request->authenticate(WEB_USERNAME, httpPassword);
  321. #else
  322. return true;
  323. #endif
  324. }
  325. // -----------------------------------------------------------------------------
  326. AsyncWebServer * webServer() {
  327. return _server;
  328. }
  329. void webBodyRegister(web_body_callback_f callback) {
  330. _web_body_callbacks.push_back(callback);
  331. }
  332. void webRequestRegister(web_request_callback_f callback) {
  333. _web_request_callbacks.push_back(callback);
  334. }
  335. unsigned int webPort() {
  336. #if ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  337. return 443;
  338. #else
  339. return getSetting("webPort", WEB_PORT).toInt();
  340. #endif
  341. }
  342. void webLog(AsyncWebServerRequest *request) {
  343. DEBUG_MSG_P(PSTR("[WEBSERVER] Request: %s %s\n"), request->methodToString(), request->url().c_str());
  344. }
  345. void webSetup() {
  346. // Cache the Last-Modifier header value
  347. snprintf_P(_last_modified, sizeof(_last_modified), PSTR("%s %s GMT"), __DATE__, __TIME__);
  348. // Create server
  349. unsigned int port = webPort();
  350. _server = new AsyncWebServer(port);
  351. // Rewrites
  352. _server->rewrite("/", "/index.html");
  353. // Serve home (basic authentication protection)
  354. #if WEB_EMBEDDED
  355. _server->on("/index.html", HTTP_GET, _onHome);
  356. #endif
  357. // Other entry points
  358. _server->on("/reset", HTTP_GET, _onReset);
  359. _server->on("/config", HTTP_GET, _onGetConfig);
  360. _server->on("/config", HTTP_POST | HTTP_PUT, _onPostConfig, _onPostConfigData);
  361. _server->on("/upgrade", HTTP_POST, _onUpgrade, _onUpgradeFile);
  362. _server->on("/discover", HTTP_GET, _onDiscover);
  363. // Serve static files
  364. #if SPIFFS_SUPPORT
  365. _server->serveStatic("/", SPIFFS, "/")
  366. .setLastModified(_last_modified)
  367. .setFilter([](AsyncWebServerRequest *request) -> bool {
  368. webLog(request);
  369. return true;
  370. });
  371. #endif
  372. // Handle other requests, including 404
  373. _server->onRequestBody(_onBody);
  374. _server->onNotFound(_onRequest);
  375. // Run server
  376. #if ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  377. _server->onSslFileRequest(_onCertificate, NULL);
  378. _server->beginSecure("server.cer", "server.key", NULL);
  379. #else
  380. _server->begin();
  381. #endif
  382. DEBUG_MSG_P(PSTR("[WEBSERVER] Webserver running on port %u\n"), port);
  383. }
  384. #endif // WEB_SUPPORT