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.

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