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.

449 lines
13 KiB

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