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.

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