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.

432 lines
13 KiB

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