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.

337 lines
9.8 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  1. /*
  2. WEBSERVER MODULE
  3. Copyright (C) 2016-2017 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 (!_authenticate(request)) return request->requestAuthentication(getSetting("hostname").c_str());
  34. AsyncJsonResponse * response = new AsyncJsonResponse();
  35. JsonObject& root = response->getRoot();
  36. root["app"] = APP_NAME;
  37. root["version"] = APP_VERSION;
  38. unsigned int size = settingsKeyCount();
  39. for (unsigned int i=0; i<size; i++) {
  40. String key = settingsKeyName(i);
  41. String value = getSetting(key);
  42. root[key] = value;
  43. }
  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. response->setLength();
  48. request->send(response);
  49. }
  50. void _onPostConfig(AsyncWebServerRequest *request) {
  51. webLog(request);
  52. if (!_authenticate(request)) return request->requestAuthentication(getSetting("hostname").c_str());
  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 = settingsRestore(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 = settingsRestore(root);
  82. delete _webConfigBuffer;
  83. }
  84. }
  85. #if WEB_EMBEDDED
  86. void _onHome(AsyncWebServerRequest *request) {
  87. webLog(request);
  88. if (!_authenticate(request)) return request->requestAuthentication(getSetting("hostname").c_str());
  89. if (request->header("If-Modified-Since").equals(_last_modified)) {
  90. request->send(304);
  91. } else {
  92. #if ASYNC_TCP_SSL_ENABLED
  93. // Chunked response, we calculate the chunks based on free heap (in multiples of 32)
  94. // This is necessary when a TLS connection is open since it sucks too much memory
  95. DEBUG_MSG_P(PSTR("[MAIN] Free heap: %d bytes\n"), getFreeHeap());
  96. size_t max = (getFreeHeap() / 3) & 0xFFE0;
  97. AsyncWebServerResponse *response = request->beginChunkedResponse("text/html", [max](uint8_t *buffer, size_t maxLen, size_t index) -> size_t {
  98. // Get the chunk based on the index and maxLen
  99. size_t len = index_html_gz_len - index;
  100. if (len > maxLen) len = maxLen;
  101. if (len > max) len = max;
  102. if (len > 0) memcpy_P(buffer, index_html_gz + index, len);
  103. DEBUG_MSG_P(PSTR("[WEB] Sending %d%%%% (max chunk size: %4d)\r"), int(100 * index / index_html_gz_len), max);
  104. if (len == 0) DEBUG_MSG_P(PSTR("\n"));
  105. // Return the actual length of the chunk (0 for end of file)
  106. return len;
  107. });
  108. #else
  109. AsyncWebServerResponse *response = request->beginResponse_P(200, "text/html", index_html_gz, index_html_gz_len);
  110. #endif
  111. response->addHeader("Content-Encoding", "gzip");
  112. response->addHeader("Last-Modified", _last_modified);
  113. request->send(response);
  114. }
  115. }
  116. #endif
  117. #if ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  118. int _onCertificate(void * arg, const char *filename, uint8_t **buf) {
  119. #if WEB_EMBEDDED
  120. if (strcmp(filename, "server.cer") == 0) {
  121. uint8_t * nbuf = (uint8_t*) malloc(server_cer_len);
  122. memcpy_P(nbuf, server_cer, server_cer_len);
  123. *buf = nbuf;
  124. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - OK\n"), filename);
  125. return server_cer_len;
  126. }
  127. if (strcmp(filename, "server.key") == 0) {
  128. uint8_t * nbuf = (uint8_t*) malloc(server_key_len);
  129. memcpy_P(nbuf, server_key, server_key_len);
  130. *buf = nbuf;
  131. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - OK\n"), filename);
  132. return server_key_len;
  133. }
  134. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - ERROR\n"), filename);
  135. *buf = 0;
  136. return 0;
  137. #else
  138. File file = SPIFFS.open(filename, "r");
  139. if (file) {
  140. size_t size = file.size();
  141. uint8_t * nbuf = (uint8_t*) malloc(size);
  142. if (nbuf) {
  143. size = file.read(nbuf, size);
  144. file.close();
  145. *buf = nbuf;
  146. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - OK\n"), filename);
  147. return size;
  148. }
  149. file.close();
  150. }
  151. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - ERROR\n"), filename);
  152. *buf = 0;
  153. return 0;
  154. #endif
  155. }
  156. #endif
  157. void _onUpgrade(AsyncWebServerRequest *request) {
  158. webLog(request);
  159. if (!_authenticate(request)) return request->requestAuthentication(getSetting("hostname").c_str());
  160. char buffer[10];
  161. if (!Update.hasError()) {
  162. sprintf_P(buffer, PSTR("OK"));
  163. } else {
  164. sprintf_P(buffer, PSTR("ERROR %d"), Update.getError());
  165. }
  166. AsyncWebServerResponse *response = request->beginResponse(200, "text/plain", buffer);
  167. response->addHeader("Connection", "close");
  168. if (!Update.hasError()) {
  169. deferredReset(100, CUSTOM_RESET_UPGRADE);
  170. }
  171. request->send(response);
  172. }
  173. void _onUpgradeData(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) {
  174. if (!index) {
  175. DEBUG_MSG_P(PSTR("[UPGRADE] Start: %s\n"), filename.c_str());
  176. Update.runAsync(true);
  177. if (!Update.begin((ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000)) {
  178. #ifdef DEBUG_PORT
  179. Update.printError(DEBUG_PORT);
  180. #endif
  181. }
  182. }
  183. if (!Update.hasError()) {
  184. if (Update.write(data, len) != len) {
  185. #ifdef DEBUG_PORT
  186. Update.printError(DEBUG_PORT);
  187. #endif
  188. }
  189. }
  190. if (final) {
  191. if (Update.end(true)){
  192. DEBUG_MSG_P(PSTR("[UPGRADE] Success: %u bytes\n"), index + len);
  193. } else {
  194. #ifdef DEBUG_PORT
  195. Update.printError(DEBUG_PORT);
  196. #endif
  197. }
  198. } else {
  199. DEBUG_MSG_P(PSTR("[UPGRADE] Progress: %u bytes\r"), index + len);
  200. }
  201. }
  202. // -----------------------------------------------------------------------------
  203. bool _authenticate(AsyncWebServerRequest *request) {
  204. String password = getSetting("adminPass", ADMIN_PASS);
  205. char httpPassword[password.length() + 1];
  206. password.toCharArray(httpPassword, password.length() + 1);
  207. return request->authenticate(WEB_USERNAME, httpPassword);
  208. }
  209. // -----------------------------------------------------------------------------
  210. AsyncWebServer * webServer() {
  211. return _server;
  212. }
  213. void webLog(AsyncWebServerRequest *request) {
  214. DEBUG_MSG_P(PSTR("[WEBSERVER] Request: %s %s\n"), request->methodToString(), request->url().c_str());
  215. }
  216. void webSetup() {
  217. // Cache the Last-Modifier header value
  218. snprintf_P(_last_modified, sizeof(_last_modified), PSTR("%s %s GMT"), __DATE__, __TIME__);
  219. // Create server
  220. #if ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  221. unsigned int port = 443;
  222. #else
  223. unsigned int port = getSetting("webPort", WEB_PORT).toInt();
  224. #endif
  225. _server = new AsyncWebServer(port);
  226. // Rewrites
  227. _server->rewrite("/", "/index.html");
  228. // Serve home (basic authentication protection)
  229. #if WEB_EMBEDDED
  230. _server->on("/index.html", HTTP_GET, _onHome);
  231. #endif
  232. _server->on("/reset", HTTP_GET, _onReset);
  233. _server->on("/config", HTTP_GET, _onGetConfig);
  234. _server->on("/config", HTTP_POST | HTTP_PUT, _onPostConfig, _onPostConfigData);
  235. _server->on("/upgrade", HTTP_POST, _onUpgrade, _onUpgradeData);
  236. // Serve static files
  237. #if SPIFFS_SUPPORT
  238. _server->serveStatic("/", SPIFFS, "/")
  239. .setLastModified(_last_modified)
  240. .setFilter([](AsyncWebServerRequest *request) -> bool {
  241. webLog(request);
  242. return true;
  243. });
  244. #endif
  245. // 404
  246. _server->onNotFound([](AsyncWebServerRequest *request){
  247. request->send(404);
  248. });
  249. // Run server
  250. #if ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  251. _server->onSslFileRequest(_onCertificate, NULL);
  252. _server->beginSecure("server.cer", "server.key", NULL);
  253. #else
  254. _server->begin();
  255. #endif
  256. DEBUG_MSG_P(PSTR("[WEBSERVER] Webserver running on port %d\n"), port);
  257. }
  258. #endif // WEB_SUPPORT