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.

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