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.

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