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.

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