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.

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