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.

448 lines
13 KiB

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