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.

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