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.

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