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.

335 lines
9.7 KiB

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