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.

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