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.

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