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.

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