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.

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