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.

359 lines
10 KiB

8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
7 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 _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. char buffer[100];
  44. snprintf_P(buffer, sizeof(buffer), PSTR("attachment; filename=\"%s-backup.json\""), (char *) getSetting("hostname").c_str());
  45. response->addHeader("Content-Disposition", buffer);
  46. request->send(response);
  47. }
  48. void _onPostConfig(AsyncWebServerRequest *request) {
  49. webLog(request);
  50. if (!webAuthenticate(request)) {
  51. return request->requestAuthentication(getSetting("hostname").c_str());
  52. }
  53. request->send(_webConfigSuccess ? 200 : 400);
  54. }
  55. void _onPostConfigData(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) {
  56. // No buffer
  57. if (final && (index == 0)) {
  58. DynamicJsonBuffer jsonBuffer;
  59. JsonObject& root = jsonBuffer.parseObject((char *) data);
  60. if (root.success()) _webConfigSuccess = settingsRestoreJson(root);
  61. return;
  62. }
  63. // Buffer start => reset
  64. if (index == 0) if (_webConfigBuffer) delete _webConfigBuffer;
  65. // init buffer if it doesn't exist
  66. if (!_webConfigBuffer) {
  67. _webConfigBuffer = new std::vector<uint8_t>();
  68. _webConfigSuccess = false;
  69. }
  70. // Copy
  71. if (len > 0) {
  72. _webConfigBuffer->reserve(_webConfigBuffer->size() + len);
  73. _webConfigBuffer->insert(_webConfigBuffer->end(), data, data + len);
  74. }
  75. // Ending
  76. if (final) {
  77. _webConfigBuffer->push_back(0);
  78. // Parse JSON
  79. DynamicJsonBuffer jsonBuffer;
  80. JsonObject& root = jsonBuffer.parseObject((char *) _webConfigBuffer->data());
  81. if (root.success()) _webConfigSuccess = settingsRestoreJson(root);
  82. delete _webConfigBuffer;
  83. }
  84. }
  85. #if WEB_EMBEDDED
  86. void _onHome(AsyncWebServerRequest *request) {
  87. webLog(request);
  88. if (!webAuthenticate(request)) {
  89. return request->requestAuthentication(getSetting("hostname").c_str());
  90. }
  91. if (request->header("If-Modified-Since").equals(_last_modified)) {
  92. request->send(304);
  93. } else {
  94. #if ASYNC_TCP_SSL_ENABLED
  95. // Chunked response, we calculate the chunks based on free heap (in multiples of 32)
  96. // This is necessary when a TLS connection is open since it sucks too much memory
  97. DEBUG_MSG_P(PSTR("[MAIN] Free heap: %d bytes\n"), getFreeHeap());
  98. size_t max = (getFreeHeap() / 3) & 0xFFE0;
  99. AsyncWebServerResponse *response = request->beginChunkedResponse("text/html", [max](uint8_t *buffer, size_t maxLen, size_t index) -> size_t {
  100. // Get the chunk based on the index and maxLen
  101. size_t len = index_html_gz_len - index;
  102. if (len > maxLen) len = maxLen;
  103. if (len > max) len = max;
  104. if (len > 0) memcpy_P(buffer, index_html_gz + index, len);
  105. DEBUG_MSG_P(PSTR("[WEB] Sending %d%%%% (max chunk size: %4d)\r"), int(100 * index / index_html_gz_len), max);
  106. if (len == 0) DEBUG_MSG_P(PSTR("\n"));
  107. // Return the actual length of the chunk (0 for end of file)
  108. return len;
  109. });
  110. #else
  111. AsyncWebServerResponse *response = request->beginResponse_P(200, "text/html", index_html_gz, index_html_gz_len);
  112. #endif
  113. response->addHeader("Content-Encoding", "gzip");
  114. response->addHeader("Last-Modified", _last_modified);
  115. request->send(response);
  116. }
  117. }
  118. #endif
  119. #if ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  120. int _onCertificate(void * arg, const char *filename, uint8_t **buf) {
  121. #if WEB_EMBEDDED
  122. if (strcmp(filename, "server.cer") == 0) {
  123. uint8_t * nbuf = (uint8_t*) malloc(server_cer_len);
  124. memcpy_P(nbuf, server_cer, server_cer_len);
  125. *buf = nbuf;
  126. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - OK\n"), filename);
  127. return server_cer_len;
  128. }
  129. if (strcmp(filename, "server.key") == 0) {
  130. uint8_t * nbuf = (uint8_t*) malloc(server_key_len);
  131. memcpy_P(nbuf, server_key, server_key_len);
  132. *buf = nbuf;
  133. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - OK\n"), filename);
  134. return server_key_len;
  135. }
  136. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - ERROR\n"), filename);
  137. *buf = 0;
  138. return 0;
  139. #else
  140. File file = SPIFFS.open(filename, "r");
  141. if (file) {
  142. size_t size = file.size();
  143. uint8_t * nbuf = (uint8_t*) malloc(size);
  144. if (nbuf) {
  145. size = file.read(nbuf, size);
  146. file.close();
  147. *buf = nbuf;
  148. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - OK\n"), filename);
  149. return size;
  150. }
  151. file.close();
  152. }
  153. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - ERROR\n"), filename);
  154. *buf = 0;
  155. return 0;
  156. #endif
  157. }
  158. #endif
  159. void _onUpgrade(AsyncWebServerRequest *request) {
  160. webLog(request);
  161. if (!webAuthenticate(request)) {
  162. return request->requestAuthentication(getSetting("hostname").c_str());
  163. }
  164. char buffer[10];
  165. if (!Update.hasError()) {
  166. sprintf_P(buffer, PSTR("OK"));
  167. } else {
  168. sprintf_P(buffer, PSTR("ERROR %d"), Update.getError());
  169. }
  170. AsyncWebServerResponse *response = request->beginResponse(200, "text/plain", buffer);
  171. response->addHeader("Connection", "close");
  172. if (Update.hasError()) {
  173. eepromRotate(true);
  174. } else {
  175. deferredReset(100, CUSTOM_RESET_UPGRADE);
  176. }
  177. request->send(response);
  178. }
  179. void _onUpgradeData(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) {
  180. if (!index) {
  181. // Disabling EEPROM rotation to prevent writing to EEPROM after the upgrade
  182. eepromRotate(false);
  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. // Serve static files
  252. #if SPIFFS_SUPPORT
  253. _server->serveStatic("/", SPIFFS, "/")
  254. .setLastModified(_last_modified)
  255. .setFilter([](AsyncWebServerRequest *request) -> bool {
  256. webLog(request);
  257. return true;
  258. });
  259. #endif
  260. // 404
  261. _server->onNotFound([](AsyncWebServerRequest *request){
  262. request->send(404);
  263. });
  264. // Run server
  265. #if ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  266. _server->onSslFileRequest(_onCertificate, NULL);
  267. _server->beginSecure("server.cer", "server.key", NULL);
  268. #else
  269. _server->begin();
  270. #endif
  271. DEBUG_MSG_P(PSTR("[WEBSERVER] Webserver running on port %u\n"), port);
  272. }
  273. #endif // WEB_SUPPORT