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
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"] = getBoardName();
  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. #ifdef DEBUG_PORT
  227. Update.printError(DEBUG_PORT);
  228. #endif
  229. }
  230. }
  231. if (!Update.hasError()) {
  232. if (Update.write(data, len) != len) {
  233. #ifdef DEBUG_PORT
  234. Update.printError(DEBUG_PORT);
  235. #endif
  236. }
  237. }
  238. if (final) {
  239. if (Update.end(true)){
  240. DEBUG_MSG_P(PSTR("[UPGRADE] Success: %u bytes\n"), index + len);
  241. } else {
  242. #ifdef DEBUG_PORT
  243. Update.printError(DEBUG_PORT);
  244. #endif
  245. }
  246. } else {
  247. DEBUG_MSG_P(PSTR("[UPGRADE] Progress: %u bytes\r"), index + len);
  248. }
  249. }
  250. void _webWebSocketOnSend(JsonObject& root) {
  251. root["webPort"] = webPort();
  252. }
  253. bool _webKeyCheck(const char * key) {
  254. return (strncmp(key, "web", 3) == 0);
  255. }
  256. // -----------------------------------------------------------------------------
  257. bool webAuthenticate(AsyncWebServerRequest *request) {
  258. #if USE_PASSWORD
  259. String password = getPassword();
  260. char httpPassword[password.length() + 1];
  261. password.toCharArray(httpPassword, password.length() + 1);
  262. return request->authenticate(WEB_USERNAME, httpPassword);
  263. #else
  264. return true;
  265. #endif
  266. }
  267. // -----------------------------------------------------------------------------
  268. AsyncWebServer * webServer() {
  269. return _server;
  270. }
  271. unsigned int webPort() {
  272. #if ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  273. return 443;
  274. #else
  275. return getSetting("webPort", WEB_PORT).toInt();
  276. #endif
  277. }
  278. unsigned char webMode() {
  279. #if USE_PASSWORD && WEB_FORCE_PASS_CHANGE
  280. return getPassword().equals(ADMIN_PASS) ? WEB_MODE_PASSWORD : WEB_MODE_NORMAL;
  281. #else
  282. return WEB_MODE_NORMAL;
  283. #endif
  284. }
  285. void webLog(AsyncWebServerRequest *request) {
  286. DEBUG_MSG_P(PSTR("[WEBSERVER] Request: %s %s\n"), request->methodToString(), request->url().c_str());
  287. }
  288. void webSetup() {
  289. // Cache the Last-Modifier header value
  290. snprintf_P(_last_modified, sizeof(_last_modified), PSTR("%s %s GMT"), __DATE__, __TIME__);
  291. // Create server
  292. unsigned int port = webPort();
  293. _server = new AsyncWebServer(port);
  294. // Rewrites
  295. _server->rewrite("/", "/index.html");
  296. // Serve home (basic authentication protection)
  297. #if WEB_EMBEDDED
  298. _server->on("/index.html", HTTP_GET, _onHome);
  299. #endif
  300. _server->on("/reset", HTTP_GET, _onReset);
  301. _server->on("/config", HTTP_GET, _onGetConfig);
  302. _server->on("/config", HTTP_POST | HTTP_PUT, _onPostConfig, _onPostConfigData);
  303. _server->on("/upgrade", HTTP_POST, _onUpgrade, _onUpgradeData);
  304. _server->on("/discover", HTTP_GET, _onDiscover);
  305. // Serve static files
  306. #if SPIFFS_SUPPORT
  307. _server->serveStatic("/", SPIFFS, "/")
  308. .setLastModified(_last_modified)
  309. .setFilter([](AsyncWebServerRequest *request) -> bool {
  310. webLog(request);
  311. return true;
  312. });
  313. #endif
  314. // 404
  315. _server->onNotFound([](AsyncWebServerRequest *request){
  316. request->send(404);
  317. });
  318. // Run server
  319. #if ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  320. _server->onSslFileRequest(_onCertificate, NULL);
  321. _server->beginSecure("server.cer", "server.key", NULL);
  322. #else
  323. _server->begin();
  324. #endif
  325. DEBUG_MSG_P(PSTR("[WEBSERVER] Webserver running on port %u\n"), port);
  326. // Websocket Callbacks
  327. wsOnSendRegister(_webWebSocketOnSend);
  328. // Settings key check register
  329. settingsRegisterKeyCheck(_webKeyCheck);
  330. }
  331. #endif // WEB_SUPPORT