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.

453 lines
13 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. void _onRequest(AsyncWebServerRequest *request){
  259. // Send request to subscribers
  260. for (unsigned char i = 0; i < _web_request_callbacks.size(); i++) {
  261. bool response = (_web_request_callbacks[i])(request);
  262. if (response) return;
  263. }
  264. // No subscriber handled the request, return a 404
  265. request->send(404);
  266. }
  267. void _onBody(AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total) {
  268. // Send request to subscribers
  269. for (unsigned char i = 0; i < _web_body_callbacks.size(); i++) {
  270. bool response = (_web_body_callbacks[i])(request, data, len, index, total);
  271. if (response) return;
  272. }
  273. }
  274. // -----------------------------------------------------------------------------
  275. bool webAuthenticate(AsyncWebServerRequest *request) {
  276. #if USE_PASSWORD
  277. String password = getAdminPass();
  278. char httpPassword[password.length() + 1];
  279. password.toCharArray(httpPassword, password.length() + 1);
  280. return request->authenticate(WEB_USERNAME, httpPassword);
  281. #else
  282. return true;
  283. #endif
  284. }
  285. // -----------------------------------------------------------------------------
  286. AsyncWebServer * webServer() {
  287. return _server;
  288. }
  289. void webBodyRegister(web_body_callback_f callback) {
  290. _web_body_callbacks.push_back(callback);
  291. }
  292. void webRequestRegister(web_request_callback_f callback) {
  293. _web_request_callbacks.push_back(callback);
  294. }
  295. unsigned int webPort() {
  296. #if ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  297. return 443;
  298. #else
  299. return getSetting("webPort", WEB_PORT).toInt();
  300. #endif
  301. }
  302. void webLog(AsyncWebServerRequest *request) {
  303. DEBUG_MSG_P(PSTR("[WEBSERVER] Request: %s %s\n"), request->methodToString(), request->url().c_str());
  304. }
  305. void webSetup() {
  306. // Cache the Last-Modifier header value
  307. snprintf_P(_last_modified, sizeof(_last_modified), PSTR("%s %s GMT"), __DATE__, __TIME__);
  308. // Create server
  309. unsigned int port = webPort();
  310. _server = new AsyncWebServer(port);
  311. // Rewrites
  312. _server->rewrite("/", "/index.html");
  313. // Serve home (basic authentication protection)
  314. #if WEB_EMBEDDED
  315. _server->on("/index.html", HTTP_GET, _onHome);
  316. #endif
  317. // Other entry points
  318. _server->on("/reset", HTTP_GET, _onReset);
  319. _server->on("/config", HTTP_GET, _onGetConfig);
  320. _server->on("/config", HTTP_POST | HTTP_PUT, _onPostConfig, _onPostConfigData);
  321. _server->on("/upgrade", HTTP_POST, _onUpgrade, _onUpgradeData);
  322. _server->on("/discover", HTTP_GET, _onDiscover);
  323. // Serve static files
  324. #if SPIFFS_SUPPORT
  325. _server->serveStatic("/", SPIFFS, "/")
  326. .setLastModified(_last_modified)
  327. .setFilter([](AsyncWebServerRequest *request) -> bool {
  328. webLog(request);
  329. return true;
  330. });
  331. #endif
  332. // Handle other requests, including 404
  333. _server->onRequestBody(_onBody);
  334. _server->onNotFound(_onRequest);
  335. // Run server
  336. #if ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  337. _server->onSslFileRequest(_onCertificate, NULL);
  338. _server->beginSecure("server.cer", "server.key", NULL);
  339. #else
  340. _server->begin();
  341. #endif
  342. DEBUG_MSG_P(PSTR("[WEBSERVER] Webserver running on port %u\n"), port);
  343. }
  344. #endif // WEB_SUPPORT