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.

503 lines
15 KiB

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