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.

341 lines
9.8 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. request->send(response);
  45. }
  46. void _onPostConfig(AsyncWebServerRequest *request) {
  47. webLog(request);
  48. if (!_authenticate(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 (!_authenticate(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 (!_authenticate(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. deferredReset(100, CUSTOM_RESET_UPGRADE);
  166. }
  167. request->send(response);
  168. }
  169. void _onUpgradeData(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) {
  170. if (!index) {
  171. DEBUG_MSG_P(PSTR("[UPGRADE] Start: %s\n"), filename.c_str());
  172. Update.runAsync(true);
  173. if (!Update.begin((ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000)) {
  174. #ifdef DEBUG_PORT
  175. Update.printError(DEBUG_PORT);
  176. #endif
  177. }
  178. }
  179. if (!Update.hasError()) {
  180. if (Update.write(data, len) != len) {
  181. #ifdef DEBUG_PORT
  182. Update.printError(DEBUG_PORT);
  183. #endif
  184. }
  185. }
  186. if (final) {
  187. if (Update.end(true)){
  188. DEBUG_MSG_P(PSTR("[UPGRADE] Success: %u bytes\n"), index + len);
  189. } else {
  190. #ifdef DEBUG_PORT
  191. Update.printError(DEBUG_PORT);
  192. #endif
  193. }
  194. } else {
  195. DEBUG_MSG_P(PSTR("[UPGRADE] Progress: %u bytes\r"), index + len);
  196. }
  197. }
  198. // -----------------------------------------------------------------------------
  199. bool _authenticate(AsyncWebServerRequest *request) {
  200. #if USE_PASSWORD
  201. String password = getSetting("adminPass", ADMIN_PASS);
  202. char httpPassword[password.length() + 1];
  203. password.toCharArray(httpPassword, password.length() + 1);
  204. return request->authenticate(WEB_USERNAME, httpPassword);
  205. #else
  206. return true;
  207. #endif
  208. }
  209. // -----------------------------------------------------------------------------
  210. AsyncWebServer * webServer() {
  211. return _server;
  212. }
  213. unsigned int webPort() {
  214. #if ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  215. return 443;
  216. #else
  217. return getSetting("webPort", WEB_PORT).toInt();
  218. #endif
  219. }
  220. void webLog(AsyncWebServerRequest *request) {
  221. DEBUG_MSG_P(PSTR("[WEBSERVER] Request: %s %s\n"), request->methodToString(), request->url().c_str());
  222. }
  223. void webSetup() {
  224. // Cache the Last-Modifier header value
  225. snprintf_P(_last_modified, sizeof(_last_modified), PSTR("%s %s GMT"), __DATE__, __TIME__);
  226. // Create server
  227. unsigned int port = webPort();
  228. _server = new AsyncWebServer(port);
  229. // Rewrites
  230. _server->rewrite("/", "/index.html");
  231. // Serve home (basic authentication protection)
  232. #if WEB_EMBEDDED
  233. _server->on("/index.html", HTTP_GET, _onHome);
  234. #endif
  235. _server->on("/reset", HTTP_GET, _onReset);
  236. _server->on("/config", HTTP_GET, _onGetConfig);
  237. _server->on("/config", HTTP_POST | HTTP_PUT, _onPostConfig, _onPostConfigData);
  238. _server->on("/upgrade", HTTP_POST, _onUpgrade, _onUpgradeData);
  239. // Serve static files
  240. #if SPIFFS_SUPPORT
  241. _server->serveStatic("/", SPIFFS, "/")
  242. .setLastModified(_last_modified)
  243. .setFilter([](AsyncWebServerRequest *request) -> bool {
  244. webLog(request);
  245. return true;
  246. });
  247. #endif
  248. // 404
  249. _server->onNotFound([](AsyncWebServerRequest *request){
  250. request->send(404);
  251. });
  252. // Run server
  253. #if ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  254. _server->onSslFileRequest(_onCertificate, NULL);
  255. _server->beginSecure("server.cer", "server.key", NULL);
  256. #else
  257. _server->begin();
  258. #endif
  259. DEBUG_MSG_P(PSTR("[WEBSERVER] Webserver running on port %u\n"), port);
  260. }
  261. #endif // WEB_SUPPORT