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.

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