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.

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