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