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.

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