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