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.

451 lines
13 KiB

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