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.

440 lines
12 KiB

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