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.

498 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
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. // TODO: implement as separate from debugging message
  262. if (wsConnected()) return;
  263. DEBUG_MSG_P(PSTR("[UPGRADE] Progress: %u bytes\r"), index + len);
  264. }
  265. }
  266. bool _onAPModeRequest(AsyncWebServerRequest *request) {
  267. if ((WiFi.getMode() & WIFI_AP) > 0) {
  268. const String domain = getSetting("hostname") + ".";
  269. const String host = request->header("Host");
  270. const String ip = WiFi.softAPIP().toString();
  271. // Only allow requests that use our hostname or ip
  272. if (host.equals(ip)) return true;
  273. if (host.startsWith(domain)) return true;
  274. // Immediatly close the connection, ref: https://github.com/xoseperez/espurna/issues/1660
  275. // Not doing so will cause memory exhaustion, because the connection will linger
  276. request->send(404);
  277. request->client()->close();
  278. return false;
  279. }
  280. return true;
  281. }
  282. void _onRequest(AsyncWebServerRequest *request){
  283. if (!_onAPModeRequest(request)) return;
  284. // Send request to subscribers
  285. for (unsigned char i = 0; i < _web_request_callbacks.size(); i++) {
  286. bool response = (_web_request_callbacks[i])(request);
  287. if (response) return;
  288. }
  289. // No subscriber handled the request, return a 404 with implicit "Connection: close"
  290. request->send(404);
  291. // And immediatly close the connection, ref: https://github.com/xoseperez/espurna/issues/1660
  292. // Not doing so will cause memory exhaustion, because the connection will linger
  293. request->client()->close();
  294. }
  295. void _onBody(AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total) {
  296. if (!_onAPModeRequest(request)) return;
  297. // Send request to subscribers
  298. for (unsigned char i = 0; i < _web_body_callbacks.size(); i++) {
  299. bool response = (_web_body_callbacks[i])(request, data, len, index, total);
  300. if (response) return;
  301. }
  302. // Same as _onAPModeRequest(...)
  303. request->send(404);
  304. request->client()->close();
  305. }
  306. // -----------------------------------------------------------------------------
  307. bool webAuthenticate(AsyncWebServerRequest *request) {
  308. #if USE_PASSWORD
  309. String password = getAdminPass();
  310. char httpPassword[password.length() + 1];
  311. password.toCharArray(httpPassword, password.length() + 1);
  312. return request->authenticate(WEB_USERNAME, httpPassword);
  313. #else
  314. return true;
  315. #endif
  316. }
  317. // -----------------------------------------------------------------------------
  318. AsyncWebServer * webServer() {
  319. return _server;
  320. }
  321. void webBodyRegister(web_body_callback_f callback) {
  322. _web_body_callbacks.push_back(callback);
  323. }
  324. void webRequestRegister(web_request_callback_f callback) {
  325. _web_request_callbacks.push_back(callback);
  326. }
  327. unsigned int webPort() {
  328. #if ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  329. return 443;
  330. #else
  331. return getSetting("webPort", WEB_PORT).toInt();
  332. #endif
  333. }
  334. void webLog(AsyncWebServerRequest *request) {
  335. DEBUG_MSG_P(PSTR("[WEBSERVER] Request: %s %s\n"), request->methodToString(), request->url().c_str());
  336. }
  337. void webSetup() {
  338. // Cache the Last-Modifier header value
  339. snprintf_P(_last_modified, sizeof(_last_modified), PSTR("%s %s GMT"), __DATE__, __TIME__);
  340. // Create server
  341. unsigned int port = webPort();
  342. _server = new AsyncWebServer(port);
  343. // Rewrites
  344. _server->rewrite("/", "/index.html");
  345. // Serve home (basic authentication protection)
  346. #if WEB_EMBEDDED
  347. _server->on("/index.html", HTTP_GET, _onHome);
  348. #endif
  349. // Other entry points
  350. _server->on("/reset", HTTP_GET, _onReset);
  351. _server->on("/config", HTTP_GET, _onGetConfig);
  352. _server->on("/config", HTTP_POST | HTTP_PUT, _onPostConfig, _onPostConfigData);
  353. _server->on("/upgrade", HTTP_POST, _onUpgrade, _onUpgradeFile);
  354. _server->on("/discover", HTTP_GET, _onDiscover);
  355. // Serve static files
  356. #if SPIFFS_SUPPORT
  357. _server->serveStatic("/", SPIFFS, "/")
  358. .setLastModified(_last_modified)
  359. .setFilter([](AsyncWebServerRequest *request) -> bool {
  360. webLog(request);
  361. return true;
  362. });
  363. #endif
  364. // Handle other requests, including 404
  365. _server->onRequestBody(_onBody);
  366. _server->onNotFound(_onRequest);
  367. // Run server
  368. #if ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  369. _server->onSslFileRequest(_onCertificate, NULL);
  370. _server->beginSecure("server.cer", "server.key", NULL);
  371. #else
  372. _server->begin();
  373. #endif
  374. DEBUG_MSG_P(PSTR("[WEBSERVER] Webserver running on port %u\n"), port);
  375. }
  376. #endif // WEB_SUPPORT