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.

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