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.

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