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.

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