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.

511 lines
15 KiB

8 years ago
8 years ago
8 years ago
6 years ago
8 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 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-2019 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #if WEB_SUPPORT
  6. #include "utils.h"
  7. #include <ESPAsyncTCP.h>
  8. #include <ESPAsyncWebServer.h>
  9. #include <Hash.h>
  10. #include <FS.h>
  11. #include <AsyncJson.h>
  12. #include <ArduinoJson.h>
  13. #if WEB_EMBEDDED
  14. #if WEBUI_IMAGE == WEBUI_IMAGE_SMALL
  15. #include "static/index.small.html.gz.h"
  16. #elif WEBUI_IMAGE == WEBUI_IMAGE_LIGHT
  17. #include "static/index.light.html.gz.h"
  18. #elif WEBUI_IMAGE == WEBUI_IMAGE_SENSOR
  19. #include "static/index.sensor.html.gz.h"
  20. #elif WEBUI_IMAGE == WEBUI_IMAGE_RFBRIDGE
  21. #include "static/index.rfbridge.html.gz.h"
  22. #elif WEBUI_IMAGE == WEBUI_IMAGE_RFM69
  23. #include "static/index.rfm69.html.gz.h"
  24. #elif WEBUI_IMAGE == WEBUI_IMAGE_LIGHTFOX
  25. #include "static/index.lightfox.html.gz.h"
  26. #elif WEBUI_IMAGE == WEBUI_IMAGE_THERMOSTAT
  27. #include "static/index.thermostat.html.gz.h"
  28. #elif WEBUI_IMAGE == WEBUI_IMAGE_FULL
  29. #include "static/index.all.html.gz.h"
  30. #endif
  31. #endif // WEB_EMBEDDED
  32. #if SECURE_CLIENT == SECURE_CLIENT_AXTLS & WEB_SSL_ENABLED
  33. #include "static/server.cer.h"
  34. #include "static/server.key.h"
  35. #endif // SECURE_CLIENT == SECURE_CLIENT_AXTLS & WEB_SSL_ENABLED
  36. // -----------------------------------------------------------------------------
  37. AsyncWebServer * _server;
  38. char _last_modified[50];
  39. std::vector<uint8_t> * _webConfigBuffer;
  40. bool _webConfigSuccess = false;
  41. std::vector<web_request_callback_f> _web_request_callbacks;
  42. std::vector<web_body_callback_f> _web_body_callbacks;
  43. constexpr const size_t WEB_CONFIG_BUFFER_MAX = 4096;
  44. // -----------------------------------------------------------------------------
  45. // HOOKS
  46. // -----------------------------------------------------------------------------
  47. void _onReset(AsyncWebServerRequest *request) {
  48. webLog(request);
  49. if (!webAuthenticate(request)) {
  50. return request->requestAuthentication(getSetting("hostname").c_str());
  51. }
  52. deferredReset(100, CUSTOM_RESET_HTTP);
  53. request->send(200);
  54. }
  55. void _onDiscover(AsyncWebServerRequest *request) {
  56. webLog(request);
  57. AsyncResponseStream *response = request->beginResponseStream("application/json");
  58. const String device = getBoardName();
  59. const String hostname = getSetting("hostname");
  60. StaticJsonBuffer<JSON_OBJECT_SIZE(4)> jsonBuffer;
  61. JsonObject &root = jsonBuffer.createObject();
  62. root["app"] = APP_NAME;
  63. root["version"] = APP_VERSION;
  64. root["device"] = device.c_str();
  65. root["hostname"] = hostname.c_str();
  66. root.printTo(*response);
  67. request->send(response);
  68. }
  69. void _onGetConfig(AsyncWebServerRequest *request) {
  70. webLog(request);
  71. if (!webAuthenticate(request)) {
  72. return request->requestAuthentication(getSetting("hostname").c_str());
  73. }
  74. AsyncResponseStream *response = request->beginResponseStream("text/json");
  75. char buffer[100];
  76. snprintf_P(buffer, sizeof(buffer), PSTR("attachment; filename=\"%s-backup.json\""), (char *) getSetting("hostname").c_str());
  77. response->addHeader("Content-Disposition", buffer);
  78. response->addHeader("X-XSS-Protection", "1; mode=block");
  79. response->addHeader("X-Content-Type-Options", "nosniff");
  80. response->addHeader("X-Frame-Options", "deny");
  81. response->printf("{\n\"app\": \"%s\"", APP_NAME);
  82. response->printf(",\n\"version\": \"%s\"", APP_VERSION);
  83. response->printf(",\n\"backup\": \"1\"");
  84. #if NTP_SUPPORT
  85. response->printf(",\n\"timestamp\": \"%s\"", ntpDateTime().c_str());
  86. #endif
  87. // Write the keys line by line (not sorted)
  88. unsigned long count = settingsKeyCount();
  89. for (unsigned int i=0; i<count; i++) {
  90. String key = settingsKeyName(i);
  91. String value = getSetting(key);
  92. response->printf(",\n\"%s\": \"%s\"", key.c_str(), value.c_str());
  93. }
  94. response->printf("\n}");
  95. request->send(response);
  96. }
  97. void _onPostConfig(AsyncWebServerRequest *request) {
  98. webLog(request);
  99. if (!webAuthenticate(request)) {
  100. return request->requestAuthentication(getSetting("hostname").c_str());
  101. }
  102. request->send(_webConfigSuccess ? 200 : 400);
  103. }
  104. void _onPostConfigData(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) {
  105. if (!webAuthenticate(request)) {
  106. return request->requestAuthentication(getSetting("hostname").c_str());
  107. }
  108. // No buffer
  109. if (final && (index == 0)) {
  110. _webConfigSuccess = settingsRestoreJson((char*) data);
  111. return;
  112. }
  113. // Buffer start => reset
  114. if (index == 0) if (_webConfigBuffer) delete _webConfigBuffer;
  115. // init buffer if it doesn't exist
  116. if (!_webConfigBuffer) {
  117. _webConfigBuffer = new std::vector<uint8_t>();
  118. _webConfigSuccess = false;
  119. }
  120. // Copy
  121. if (len > 0) {
  122. if ((_webConfigBuffer->size() + len) > std::min(WEB_CONFIG_BUFFER_MAX, getFreeHeap() - sizeof(std::vector<uint8_t>))) {
  123. delete _webConfigBuffer;
  124. _webConfigBuffer = nullptr;
  125. request->send(500);
  126. return;
  127. }
  128. _webConfigBuffer->reserve(_webConfigBuffer->size() + len);
  129. _webConfigBuffer->insert(_webConfigBuffer->end(), data, data + len);
  130. }
  131. // Ending
  132. if (final) {
  133. _webConfigBuffer->push_back(0);
  134. _webConfigSuccess = settingsRestoreJson((char*) _webConfigBuffer->data());
  135. delete _webConfigBuffer;
  136. }
  137. }
  138. #if WEB_EMBEDDED
  139. void _onHome(AsyncWebServerRequest *request) {
  140. webLog(request);
  141. if (!webAuthenticate(request)) {
  142. return request->requestAuthentication(getSetting("hostname").c_str());
  143. }
  144. if (request->header("If-Modified-Since").equals(_last_modified)) {
  145. request->send(304);
  146. } else {
  147. #if SECURE_CLIENT == SECURE_CLIENT_AXTLS
  148. // Chunked response, we calculate the chunks based on free heap (in multiples of 32)
  149. // This is necessary when a TLS connection is open since it sucks too much memory
  150. DEBUG_MSG_P(PSTR("[MAIN] Free heap: %d bytes\n"), getFreeHeap());
  151. size_t max = (getFreeHeap() / 3) & 0xFFE0;
  152. AsyncWebServerResponse *response = request->beginChunkedResponse("text/html", [max](uint8_t *buffer, size_t maxLen, size_t index) -> size_t {
  153. // Get the chunk based on the index and maxLen
  154. size_t len = webui_image_len - index;
  155. if (len > maxLen) len = maxLen;
  156. if (len > max) len = max;
  157. if (len > 0) memcpy_P(buffer, webui_image + index, len);
  158. DEBUG_MSG_P(PSTR("[WEB] Sending %d%%%% (max chunk size: %4d)\r"), int(100 * index / webui_image_len), max);
  159. if (len == 0) DEBUG_MSG_P(PSTR("\n"));
  160. // Return the actual length of the chunk (0 for end of file)
  161. return len;
  162. });
  163. #else
  164. AsyncWebServerResponse *response = request->beginResponse_P(200, "text/html", webui_image, webui_image_len);
  165. #endif
  166. response->addHeader("Content-Encoding", "gzip");
  167. response->addHeader("Last-Modified", _last_modified);
  168. response->addHeader("X-XSS-Protection", "1; mode=block");
  169. response->addHeader("X-Content-Type-Options", "nosniff");
  170. response->addHeader("X-Frame-Options", "deny");
  171. request->send(response);
  172. }
  173. }
  174. #endif
  175. #if SECURE_CLIENT == SECURE_CLIENT_AXTLS & WEB_SSL_ENABLED
  176. int _onCertificate(void * arg, const char *filename, uint8_t **buf) {
  177. #if WEB_EMBEDDED
  178. if (strcmp(filename, "server.cer") == 0) {
  179. uint8_t * nbuf = (uint8_t*) malloc(server_cer_len);
  180. memcpy_P(nbuf, server_cer, server_cer_len);
  181. *buf = nbuf;
  182. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - OK\n"), filename);
  183. return server_cer_len;
  184. }
  185. if (strcmp(filename, "server.key") == 0) {
  186. uint8_t * nbuf = (uint8_t*) malloc(server_key_len);
  187. memcpy_P(nbuf, server_key, server_key_len);
  188. *buf = nbuf;
  189. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - OK\n"), filename);
  190. return server_key_len;
  191. }
  192. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - ERROR\n"), filename);
  193. *buf = 0;
  194. return 0;
  195. #else
  196. File file = SPIFFS.open(filename, "r");
  197. if (file) {
  198. size_t size = file.size();
  199. uint8_t * nbuf = (uint8_t*) malloc(size);
  200. if (nbuf) {
  201. size = file.read(nbuf, size);
  202. file.close();
  203. *buf = nbuf;
  204. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - OK\n"), filename);
  205. return size;
  206. }
  207. file.close();
  208. }
  209. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - ERROR\n"), filename);
  210. *buf = 0;
  211. return 0;
  212. #endif
  213. }
  214. #endif
  215. void _onUpgrade(AsyncWebServerRequest *request) {
  216. webLog(request);
  217. if (!webAuthenticate(request)) {
  218. return request->requestAuthentication(getSetting("hostname").c_str());
  219. }
  220. char buffer[10];
  221. if (!Update.hasError()) {
  222. sprintf_P(buffer, PSTR("OK"));
  223. } else {
  224. sprintf_P(buffer, PSTR("ERROR %d"), Update.getError());
  225. }
  226. AsyncWebServerResponse *response = request->beginResponse(200, "text/plain", buffer);
  227. response->addHeader("Connection", "close");
  228. response->addHeader("X-XSS-Protection", "1; mode=block");
  229. response->addHeader("X-Content-Type-Options", "nosniff");
  230. response->addHeader("X-Frame-Options", "deny");
  231. if (Update.hasError()) {
  232. eepromRotate(true);
  233. } else {
  234. deferredReset(100, CUSTOM_RESET_UPGRADE);
  235. }
  236. request->send(response);
  237. }
  238. void _onUpgradeFile(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) {
  239. if (!webAuthenticate(request)) {
  240. return request->requestAuthentication(getSetting("hostname").c_str());
  241. }
  242. if (!index) {
  243. // Disabling EEPROM rotation to prevent writing to EEPROM after the upgrade
  244. eepromRotate(false);
  245. DEBUG_MSG_P(PSTR("[UPGRADE] Start: %s\n"), filename.c_str());
  246. Update.runAsync(true);
  247. if (!Update.begin((ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000)) {
  248. #ifdef DEBUG_PORT
  249. Update.printError(DEBUG_PORT);
  250. #endif
  251. }
  252. }
  253. if (!Update.hasError()) {
  254. if (Update.write(data, len) != len) {
  255. #ifdef DEBUG_PORT
  256. Update.printError(DEBUG_PORT);
  257. #endif
  258. }
  259. }
  260. if (final) {
  261. if (Update.end(true)){
  262. DEBUG_MSG_P(PSTR("[UPGRADE] Success: %u bytes\n"), index + len);
  263. } else {
  264. #ifdef DEBUG_PORT
  265. Update.printError(DEBUG_PORT);
  266. #endif
  267. }
  268. } else {
  269. // Removed to avoid websocket ping back during upgrade (see #1574)
  270. // TODO: implement as separate from debugging message
  271. if (wsConnected()) return;
  272. DEBUG_MSG_P(PSTR("[UPGRADE] Progress: %u bytes\r"), index + len);
  273. }
  274. }
  275. bool _onAPModeRequest(AsyncWebServerRequest *request) {
  276. if ((WiFi.getMode() & WIFI_AP) > 0) {
  277. const String domain = getSetting("hostname") + ".";
  278. const String host = request->header("Host");
  279. const String ip = WiFi.softAPIP().toString();
  280. // Only allow requests that use our hostname or ip
  281. if (host.equals(ip)) return true;
  282. if (host.startsWith(domain)) return true;
  283. // Immediatly close the connection, ref: https://github.com/xoseperez/espurna/issues/1660
  284. // Not doing so will cause memory exhaustion, because the connection will linger
  285. request->send(404);
  286. request->client()->close();
  287. return false;
  288. }
  289. return true;
  290. }
  291. void _onRequest(AsyncWebServerRequest *request){
  292. if (!_onAPModeRequest(request)) return;
  293. // Send request to subscribers
  294. for (unsigned char i = 0; i < _web_request_callbacks.size(); i++) {
  295. bool response = (_web_request_callbacks[i])(request);
  296. if (response) return;
  297. }
  298. // No subscriber handled the request, return a 404 with implicit "Connection: close"
  299. request->send(404);
  300. // And immediatly close the connection, ref: https://github.com/xoseperez/espurna/issues/1660
  301. // Not doing so will cause memory exhaustion, because the connection will linger
  302. request->client()->close();
  303. }
  304. void _onBody(AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total) {
  305. if (!_onAPModeRequest(request)) return;
  306. // Send request to subscribers
  307. for (unsigned char i = 0; i < _web_body_callbacks.size(); i++) {
  308. bool response = (_web_body_callbacks[i])(request, data, len, index, total);
  309. if (response) return;
  310. }
  311. // Same as _onAPModeRequest(...)
  312. request->send(404);
  313. request->client()->close();
  314. }
  315. // -----------------------------------------------------------------------------
  316. bool webAuthenticate(AsyncWebServerRequest *request) {
  317. #if USE_PASSWORD
  318. String password = getAdminPass();
  319. char httpPassword[password.length() + 1];
  320. password.toCharArray(httpPassword, password.length() + 1);
  321. return request->authenticate(WEB_USERNAME, httpPassword);
  322. #else
  323. return true;
  324. #endif
  325. }
  326. // -----------------------------------------------------------------------------
  327. AsyncWebServer * webServer() {
  328. return _server;
  329. }
  330. void webBodyRegister(web_body_callback_f callback) {
  331. _web_body_callbacks.push_back(callback);
  332. }
  333. void webRequestRegister(web_request_callback_f callback) {
  334. _web_request_callbacks.push_back(callback);
  335. }
  336. unsigned int webPort() {
  337. #if SECURE_CLIENT == SECURE_CLIENT_AXTLS & WEB_SSL_ENABLED
  338. return 443;
  339. #else
  340. return getSetting("webPort", WEB_PORT).toInt();
  341. #endif
  342. }
  343. void webLog(AsyncWebServerRequest *request) {
  344. DEBUG_MSG_P(PSTR("[WEBSERVER] Request: %s %s\n"), request->methodToString(), request->url().c_str());
  345. }
  346. void webSetup() {
  347. // Cache the Last-Modifier header value
  348. snprintf_P(_last_modified, sizeof(_last_modified), PSTR("%s %s GMT"), __DATE__, __TIME__);
  349. // Create server
  350. unsigned int port = webPort();
  351. _server = new AsyncWebServer(port);
  352. // Rewrites
  353. _server->rewrite("/", "/index.html");
  354. // Serve home (basic authentication protection)
  355. #if WEB_EMBEDDED
  356. _server->on("/index.html", HTTP_GET, _onHome);
  357. #endif
  358. // Other entry points
  359. _server->on("/reset", HTTP_GET, _onReset);
  360. _server->on("/config", HTTP_GET, _onGetConfig);
  361. _server->on("/config", HTTP_POST | HTTP_PUT, _onPostConfig, _onPostConfigData);
  362. _server->on("/upgrade", HTTP_POST, _onUpgrade, _onUpgradeFile);
  363. _server->on("/discover", HTTP_GET, _onDiscover);
  364. // Serve static files
  365. #if SPIFFS_SUPPORT
  366. _server->serveStatic("/", SPIFFS, "/")
  367. .setLastModified(_last_modified)
  368. .setFilter([](AsyncWebServerRequest *request) -> bool {
  369. webLog(request);
  370. return true;
  371. });
  372. #endif
  373. // Handle other requests, including 404
  374. _server->onRequestBody(_onBody);
  375. _server->onNotFound(_onRequest);
  376. // Run server
  377. #if SECURE_CLIENT == SECURE_CLIENT_AXTLS & WEB_SSL_ENABLED
  378. _server->onSslFileRequest(_onCertificate, NULL);
  379. _server->beginSecure("server.cer", "server.key", NULL);
  380. #else
  381. _server->begin();
  382. #endif
  383. DEBUG_MSG_P(PSTR("[WEBSERVER] Webserver running on port %u\n"), port);
  384. }
  385. #endif // WEB_SUPPORT