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.

387 lines
11 KiB

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