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.

426 lines
12 KiB

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