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.

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