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.

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