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.

282 lines
8.1 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  1. /*
  2. WEBSERVER MODULE
  3. Copyright (C) 2016-2017 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. // -----------------------------------------------------------------------------
  23. // HOOKS
  24. // -----------------------------------------------------------------------------
  25. void _onGetConfig(AsyncWebServerRequest *request) {
  26. webLog(request);
  27. if (!_authenticate(request)) return request->requestAuthentication(getSetting("hostname").c_str());
  28. AsyncJsonResponse * response = new AsyncJsonResponse();
  29. JsonObject& root = response->getRoot();
  30. root["app"] = APP_NAME;
  31. root["version"] = APP_VERSION;
  32. unsigned int size = settingsKeyCount();
  33. for (unsigned int i=0; i<size; i++) {
  34. String key = settingsKeyName(i);
  35. String value = getSetting(key);
  36. root[key] = value;
  37. }
  38. char buffer[100];
  39. snprintf_P(buffer, sizeof(buffer), PSTR("attachment; filename=\"%s-backup.json\""), (char *) getSetting("hostname").c_str());
  40. response->addHeader("Content-Disposition", buffer);
  41. response->setLength();
  42. request->send(response);
  43. }
  44. #if WEB_EMBEDDED
  45. void _onHome(AsyncWebServerRequest *request) {
  46. webLog(request);
  47. if (!_authenticate(request)) return request->requestAuthentication(getSetting("hostname").c_str());
  48. if (request->header("If-Modified-Since").equals(_last_modified)) {
  49. request->send(304);
  50. } else {
  51. #if ASYNC_TCP_SSL_ENABLED
  52. // Chunked response, we calculate the chunks based on free heap (in multiples of 32)
  53. // This is necessary when a TLS connection is open since it sucks too much memory
  54. DEBUG_MSG_P(PSTR("[MAIN] Free heap: %d bytes\n"), getFreeHeap());
  55. size_t max = (getFreeHeap() / 3) & 0xFFE0;
  56. AsyncWebServerResponse *response = request->beginChunkedResponse("text/html", [max](uint8_t *buffer, size_t maxLen, size_t index) -> size_t {
  57. // Get the chunk based on the index and maxLen
  58. size_t len = index_html_gz_len - index;
  59. if (len > maxLen) len = maxLen;
  60. if (len > max) len = max;
  61. if (len > 0) memcpy_P(buffer, index_html_gz + index, len);
  62. DEBUG_MSG_P(PSTR("[WEB] Sending %d%%%% (max chunk size: %4d)\r"), int(100 * index / index_html_gz_len), max);
  63. if (len == 0) DEBUG_MSG_P(PSTR("\n"));
  64. // Return the actual length of the chunk (0 for end of file)
  65. return len;
  66. });
  67. #else
  68. AsyncWebServerResponse *response = request->beginResponse_P(200, "text/html", index_html_gz, index_html_gz_len);
  69. #endif
  70. response->addHeader("Content-Encoding", "gzip");
  71. response->addHeader("Last-Modified", _last_modified);
  72. request->send(response);
  73. }
  74. }
  75. #endif
  76. #if ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  77. int _onCertificate(void * arg, const char *filename, uint8_t **buf) {
  78. #if WEB_EMBEDDED
  79. if (strcmp(filename, "server.cer") == 0) {
  80. uint8_t * nbuf = (uint8_t*) malloc(server_cer_len);
  81. memcpy_P(nbuf, server_cer, server_cer_len);
  82. *buf = nbuf;
  83. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - OK\n"), filename);
  84. return server_cer_len;
  85. }
  86. if (strcmp(filename, "server.key") == 0) {
  87. uint8_t * nbuf = (uint8_t*) malloc(server_key_len);
  88. memcpy_P(nbuf, server_key, server_key_len);
  89. *buf = nbuf;
  90. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - OK\n"), filename);
  91. return server_key_len;
  92. }
  93. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - ERROR\n"), filename);
  94. *buf = 0;
  95. return 0;
  96. #else
  97. File file = SPIFFS.open(filename, "r");
  98. if (file) {
  99. size_t size = file.size();
  100. uint8_t * nbuf = (uint8_t*) malloc(size);
  101. if (nbuf) {
  102. size = file.read(nbuf, size);
  103. file.close();
  104. *buf = nbuf;
  105. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - OK\n"), filename);
  106. return size;
  107. }
  108. file.close();
  109. }
  110. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - ERROR\n"), filename);
  111. *buf = 0;
  112. return 0;
  113. #endif
  114. }
  115. #endif
  116. void _onUpgrade(AsyncWebServerRequest *request) {
  117. webLog(request);
  118. if (!_authenticate(request)) return request->requestAuthentication(getSetting("hostname").c_str());
  119. char buffer[10];
  120. if (!Update.hasError()) {
  121. sprintf_P(buffer, PSTR("OK"));
  122. } else {
  123. sprintf_P(buffer, PSTR("ERROR %d"), Update.getError());
  124. }
  125. AsyncWebServerResponse *response = request->beginResponse(200, "text/plain", buffer);
  126. response->addHeader("Connection", "close");
  127. if (!Update.hasError()) {
  128. deferredReset(100, CUSTOM_RESET_UPGRADE);
  129. }
  130. request->send(response);
  131. }
  132. void _onUpgradeData(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) {
  133. if (!index) {
  134. DEBUG_MSG_P(PSTR("[UPGRADE] Start: %s\n"), filename.c_str());
  135. Update.runAsync(true);
  136. if (!Update.begin((ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000)) {
  137. #ifdef DEBUG_PORT
  138. Update.printError(DEBUG_PORT);
  139. #endif
  140. }
  141. }
  142. if (!Update.hasError()) {
  143. if (Update.write(data, len) != len) {
  144. #ifdef DEBUG_PORT
  145. Update.printError(DEBUG_PORT);
  146. #endif
  147. }
  148. }
  149. if (final) {
  150. if (Update.end(true)){
  151. DEBUG_MSG_P(PSTR("[UPGRADE] Success: %u bytes\n"), index + len);
  152. } else {
  153. #ifdef DEBUG_PORT
  154. Update.printError(DEBUG_PORT);
  155. #endif
  156. }
  157. } else {
  158. DEBUG_MSG_P(PSTR("[UPGRADE] Progress: %u bytes\r"), index + len);
  159. }
  160. }
  161. // -----------------------------------------------------------------------------
  162. bool _authenticate(AsyncWebServerRequest *request) {
  163. String password = getSetting("adminPass", ADMIN_PASS);
  164. char httpPassword[password.length() + 1];
  165. password.toCharArray(httpPassword, password.length() + 1);
  166. return request->authenticate(WEB_USERNAME, httpPassword);
  167. }
  168. // -----------------------------------------------------------------------------
  169. AsyncWebServer * webServer() {
  170. return _server;
  171. }
  172. void webLog(AsyncWebServerRequest *request) {
  173. DEBUG_MSG_P(PSTR("[WEBSERVER] Request: %s %s\n"), request->methodToString(), request->url().c_str());
  174. }
  175. void webSetup() {
  176. // Cache the Last-Modifier header value
  177. snprintf_P(_last_modified, sizeof(_last_modified), PSTR("%s %s GMT"), __DATE__, __TIME__);
  178. // Create server
  179. #if ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  180. unsigned int port = 443;
  181. #else
  182. unsigned int port = getSetting("webPort", WEB_PORT).toInt();
  183. #endif
  184. _server = new AsyncWebServer(port);
  185. // Rewrites
  186. _server->rewrite("/", "/index.html");
  187. // Serve home (basic authentication protection)
  188. #if WEB_EMBEDDED
  189. _server->on("/index.html", HTTP_GET, _onHome);
  190. #endif
  191. _server->on("/config", HTTP_GET, _onGetConfig);
  192. _server->on("/upgrade", HTTP_POST, _onUpgrade, _onUpgradeData);
  193. // Serve static files
  194. #if SPIFFS_SUPPORT
  195. _server->serveStatic("/", SPIFFS, "/")
  196. .setLastModified(_last_modified)
  197. .setFilter([](AsyncWebServerRequest *request) -> bool {
  198. webLog(request);
  199. return true;
  200. });
  201. #endif
  202. // 404
  203. _server->onNotFound([](AsyncWebServerRequest *request){
  204. request->send(404);
  205. });
  206. // Run server
  207. #if ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  208. _server->onSslFileRequest(_onCertificate, NULL);
  209. _server->beginSecure("server.cer", "server.key", NULL);
  210. #else
  211. _server->begin();
  212. #endif
  213. DEBUG_MSG_P(PSTR("[WEBSERVER] Webserver running on port %d\n"), port);
  214. }
  215. #endif // WEB_SUPPORT