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.

368 lines
11 KiB

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