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.

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