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.

443 lines
13 KiB

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