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.

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