2
0

wifi_manager_http_server.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. /*
  2. * Squeezelite for esp32
  3. *
  4. * (c) Sebastien 2019
  5. * Philippe G. 2019, philippe_44@outlook.com
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. *
  20. */
  21. #define LOG_LOCAL_LEVEL ESP_LOG_DEBUG
  22. #include "http_server_handlers.h"
  23. #include "esp_log.h"
  24. #include "esp_http_server.h"
  25. #include <inttypes.h>
  26. #include <stdio.h>
  27. #include <stdlib.h>
  28. #include "esp_system.h"
  29. #include "freertos/FreeRTOS.h"
  30. #include "freertos/task.h"
  31. #include "config.h"
  32. static const char TAG[] = "http_server";
  33. static httpd_handle_t server = NULL;
  34. #define FILE_PATH_MAX (ESP_VFS_PATH_MAX + 128)
  35. #define SCRATCH_BUFSIZE (10240)
  36. typedef struct rest_server_context {
  37. char base_path[ESP_VFS_PATH_MAX + 1];
  38. char scratch[SCRATCH_BUFSIZE];
  39. } rest_server_context_t;
  40. #define ESP_LOGE_LOC(t,str, ...) ESP_LOGE(t, "%s(%d): " str, __FUNCTION__, __LINE__, ##__VA_ARGS__)
  41. #define ESP_LOGI_LOC(t,str, ...) ESP_LOGI(t, "%s(%d): " str, __FUNCTION__, __LINE__, ##__VA_ARGS__)
  42. #define ESP_LOGD_LOC(t,str, ...) ESP_LOGD(t, "%s(%d): " str, __FUNCTION__, __LINE__, ##__VA_ARGS__)
  43. void register_common_handlers(httpd_handle_t server){
  44. httpd_uri_t res_get = { .uri = "/res/*", .method = HTTP_GET, .handler = resource_filehandler, .user_ctx = rest_context };
  45. httpd_register_uri_handler(server, &res_get);
  46. }
  47. void register_regular_handlers(httpd_handle_t server){
  48. httpd_uri_t root_get = { .uri = "/", .method = HTTP_GET, .handler = root_get_handler, .user_ctx = rest_context };
  49. httpd_register_uri_handler(server, &root_get);
  50. httpd_uri_t ap_get = { .uri = "/ap.json", .method = HTTP_GET, .handler = ap_get_handler, .user_ctx = rest_context };
  51. httpd_register_uri_handler(server, &ap_get);
  52. httpd_uri_t scan_get = { .uri = "/scan.json", .method = HTTP_GET, .handler = ap_scan_handler, .user_ctx = rest_context };
  53. httpd_register_uri_handler(server, &scan_get);
  54. httpd_uri_t config_get = { .uri = "/config.json", .method = HTTP_GET, .handler = config_get_handler, .user_ctx = rest_context };
  55. httpd_register_uri_handler(server, &config_get);
  56. httpd_uri_t status_get = { .uri = "/status.json", .method = HTTP_GET, .handler = status_get_handler, .user_ctx = rest_context };
  57. httpd_register_uri_handler(server, &status_get);
  58. httpd_uri_t config_post = { .uri = "/config.json", .method = HTTP_POST, .handler = config_post_handler, .user_ctx = rest_context };
  59. httpd_register_uri_handler(server, &config_post);
  60. httpd_uri_t connect_post = { .uri = "/connect.json", .method = HTTP_POST, .handler = connect_post_handler, .user_ctx = rest_context };
  61. httpd_register_uri_handler(server, &connect_post);
  62. httpd_uri_t reboot_ota_post = { .uri = "/reboot_ota.json", .method = HTTP_POST, .handler = reboot_ota_post_handler, .user_ctx = rest_context };
  63. httpd_register_uri_handler(server, &reboot_ota_post);
  64. httpd_uri_t reboot_post = { .uri = "/reboot.json", .method = HTTP_POST, .handler = reboot_post_handler, .user_ctx = rest_context };
  65. httpd_register_uri_handler(server, &reboot_post);
  66. httpd_uri_t recovery_post = { .uri = "/recovery.json", .method = HTTP_POST, .handler = recovery_post_handler, .user_ctx = rest_context };
  67. httpd_register_uri_handler(server, &recovery_post);
  68. httpd_uri_t connect_delete = { .uri = "/connect.json", .method = HTTP_DELETE, .handler = connect_delete_handler, .user_ctx = rest_context };
  69. httpd_register_uri_handler(server, &connect_delete);
  70. }
  71. esp_err_t http_server_start()
  72. {
  73. ESP_LOGI(REST_TAG, "Initializing HTTP Server");
  74. rest_server_context_t *rest_context = calloc(1, sizeof(rest_server_context_t));
  75. if(rest_context==NULL){
  76. ESP_LOGE(TAG,"No memory for http context");
  77. return ESP_FAIL;
  78. }
  79. strlcpy(rest_context->base_path, "/res/", sizeof(rest_context->base_path));
  80. httpd_handle_t server = NULL;
  81. httpd_config_t config = HTTPD_DEFAULT_CONFIG();
  82. config.uri_match_fn = httpd_uri_match_wildcard;
  83. //todo: use this to configure session token?
  84. // config.open_fn
  85. ESP_LOGI(REST_TAG, "Starting HTTP Server");
  86. esp_err_t err= httpd_start(&server, &config);
  87. if(err != ESP_OK){
  88. ESP_LOGE_LOC(TAG,"Start server failed");
  89. }
  90. else {
  91. register_common_handlers(server);
  92. register_regular_handlers(server);
  93. }
  94. register_err_handler(server, HTTPD_404_NOT_FOUND,&err_handler);
  95. return err;
  96. }
  97. /* Function to free context */
  98. void adder_free_func(void *ctx)
  99. {
  100. ESP_LOGI(TAG, "/adder Free Context function called");
  101. free(ctx);
  102. }
  103. /* This handler keeps accumulating data that is posted to it into a per
  104. * socket/session context. And returns the result.
  105. */
  106. esp_err_t adder_post_handler(httpd_req_t *req)
  107. {
  108. /* Log total visitors */
  109. unsigned *visitors = (unsigned *)req->user_ctx;
  110. ESP_LOGI(TAG, "/adder visitor count = %d", ++(*visitors));
  111. char buf[10];
  112. char outbuf[50];
  113. int ret;
  114. /* Read data received in the request */
  115. ret = httpd_req_recv(req, buf, sizeof(buf));
  116. if (ret <= 0) {
  117. if (ret == HTTPD_SOCK_ERR_TIMEOUT) {
  118. httpd_resp_send_408(req);
  119. }
  120. return ESP_FAIL;
  121. }
  122. buf[ret] = '\0';
  123. int val = atoi(buf);
  124. ESP_LOGI(TAG, "/adder handler read %d", val);
  125. /* Create session's context if not already available */
  126. if (! req->sess_ctx) {
  127. ESP_LOGI(TAG, "/adder allocating new session");
  128. req->sess_ctx = malloc(sizeof(int));
  129. req->free_ctx = adder_free_func;
  130. *(int *)req->sess_ctx = 0;
  131. }
  132. /* Add the received data to the context */
  133. int *adder = (int *)req->sess_ctx;
  134. *adder += val;
  135. /* Respond with the accumulated value */
  136. snprintf(outbuf, sizeof(outbuf),"%d", *adder);
  137. httpd_resp_send(req, outbuf, strlen(outbuf));
  138. return ESP_OK;
  139. }
  140. /* This handler gets the present value of the accumulator */
  141. esp_err_t adder_get_handler(httpd_req_t *req)
  142. {
  143. /* Log total visitors */
  144. unsigned *visitors = (unsigned *)req->user_ctx;
  145. ESP_LOGI(TAG, "/adder visitor count = %d", ++(*visitors));
  146. char outbuf[50];
  147. /* Create session's context if not already available */
  148. if (! req->sess_ctx) {
  149. ESP_LOGI(TAG, "/adder GET allocating new session");
  150. req->sess_ctx = malloc(sizeof(int));
  151. req->free_ctx = adder_free_func;
  152. *(int *)req->sess_ctx = 0;
  153. }
  154. ESP_LOGI(TAG, "/adder GET handler send %d", *(int *)req->sess_ctx);
  155. /* Respond with the accumulated value */
  156. snprintf(outbuf, sizeof(outbuf),"%d", *((int *)req->sess_ctx));
  157. httpd_resp_send(req, outbuf, strlen(outbuf));
  158. return ESP_OK;
  159. }
  160. /* This handler resets the value of the accumulator */
  161. esp_err_t adder_put_handler(httpd_req_t *req)
  162. {
  163. /* Log total visitors */
  164. unsigned *visitors = (unsigned *)req->user_ctx;
  165. ESP_LOGI(TAG, "/adder visitor count = %d", ++(*visitors));
  166. char buf[10];
  167. char outbuf[50];
  168. int ret;
  169. /* Read data received in the request */
  170. ret = httpd_req_recv(req, buf, sizeof(buf));
  171. if (ret <= 0) {
  172. if (ret == HTTPD_SOCK_ERR_TIMEOUT) {
  173. httpd_resp_send_408(req);
  174. }
  175. return ESP_FAIL;
  176. }
  177. buf[ret] = '\0';
  178. int val = atoi(buf);
  179. ESP_LOGI(TAG, "/adder PUT handler read %d", val);
  180. /* Create session's context if not already available */
  181. if (! req->sess_ctx) {
  182. ESP_LOGI(TAG, "/adder PUT allocating new session");
  183. req->sess_ctx = malloc(sizeof(int));
  184. req->free_ctx = adder_free_func;
  185. }
  186. *(int *)req->sess_ctx = val;
  187. /* Respond with the reset value */
  188. snprintf(outbuf, sizeof(outbuf),"%d", *((int *)req->sess_ctx));
  189. httpd_resp_send(req, outbuf, strlen(outbuf));
  190. return ESP_OK;
  191. }
  192. /* Maintain a variable which stores the number of times
  193. * the "/adder" URI has been visited */
  194. static unsigned visitors = 0;
  195. httpd_handle_t start_webserver(void)
  196. {
  197. httpd_config_t config = HTTPD_DEFAULT_CONFIG();
  198. // Start the httpd server
  199. ESP_LOGI(TAG, "Starting server on port: '%d'", config.server_port);
  200. if (httpd_start(&server, &config) == ESP_OK) {
  201. // Set URI handlers
  202. ESP_LOGI(TAG, "Registering URI handlers");
  203. httpd_register_uri_handler(server, &adder_get);
  204. httpd_register_uri_handler(server, &adder_put);
  205. httpd_register_uri_handler(server, &adder_post);
  206. return server;
  207. }
  208. ESP_LOGI(TAG, "Error starting server!");
  209. return NULL;
  210. }
  211. void stop_webserver(httpd_handle_t server)
  212. {
  213. // Stop the httpd server
  214. httpd_stop(server);
  215. }
  216. if(strstr(line, "GET / ")) {
  217. netconn_write(conn, http_html_hdr, sizeof(http_html_hdr) - 1, NETCONN_NOCOPY);
  218. netconn_write(conn, index_html_start, index_html_end- index_html_start, NETCONN_NOCOPY);
  219. }
  220. else if(strstr(line, "GET /code.js ")) {
  221. netconn_write(conn, http_js_hdr, sizeof(http_js_hdr) - 1, NETCONN_NOCOPY);
  222. netconn_write(conn, code_js_start, code_js_end - code_js_start, NETCONN_NOCOPY);
  223. }
  224. else if(strstr(line, "GET /style.css ")) {
  225. netconn_write(conn, http_css_hdr, sizeof(http_css_hdr) - 1, NETCONN_NOCOPY);
  226. netconn_write(conn, style_css_start, style_css_end - style_css_start, NETCONN_NOCOPY);
  227. }
  228. else if(strstr(line, "GET /jquery.js ")) {
  229. http_server_send_resource_file(conn,jquery_gz_start, jquery_gz_end, "text/javascript", "gzip" );
  230. }
  231. else if(strstr(line, "GET /popper.js ")) {
  232. http_server_send_resource_file(conn,popper_gz_start, popper_gz_end, "text/javascript", "gzip" );
  233. }
  234. else if(strstr(line, "GET /bootstrap.js ")) {
  235. http_server_send_resource_file(conn,bootstrap_js_gz_start, bootstrap_js_gz_end, "text/javascript", "gzip" );
  236. }
  237. else if(strstr(line, "GET /bootstrap.css ")) {
  238. http_server_send_resource_file(conn,bootstrap_css_gz_start, bootstrap_css_gz_end, "text/css", "gzip" );
  239. }
  240. //dynamic stuff
  241. else if(strstr(line, "GET /scan.json ")) {
  242. ESP_LOGI(TAG, "Starting wifi scan");
  243. wifi_manager_scan_async();
  244. }
  245. else if(strstr(line, "GET /ap.json ")) {
  246. /* if we can get the mutex, write the last version of the AP list */
  247. ESP_LOGI(TAG, "Processing ap.json request");
  248. if(wifi_manager_lock_json_buffer(( TickType_t ) 10)) {
  249. netconn_write(conn, http_ok_json_no_cache_hdr, sizeof(http_ok_json_no_cache_hdr) - 1, NETCONN_NOCOPY);
  250. char *buff = wifi_manager_alloc_get_ap_list_json();
  251. wifi_manager_unlock_json_buffer();
  252. if(buff!=NULL){
  253. netconn_write(conn, buff, strlen(buff), NETCONN_NOCOPY);
  254. free(buff);
  255. }
  256. else {
  257. ESP_LOGD(TAG, "Error retrieving ap list json string. ");
  258. netconn_write(conn, http_503_hdr, sizeof(http_503_hdr) - 1, NETCONN_NOCOPY);
  259. }
  260. }
  261. else {
  262. netconn_write(conn, http_503_hdr, sizeof(http_503_hdr) - 1, NETCONN_NOCOPY);
  263. ESP_LOGE(TAG, "http_server_netconn_serve: GET /ap.json failed to obtain mutex");
  264. }
  265. /* request a wifi scan */
  266. ESP_LOGI(TAG, "Starting wifi scan");
  267. wifi_manager_scan_async();
  268. ESP_LOGI(TAG, "Done serving ap.json");
  269. }
  270. else if(strstr(line, "GET /config.json ")) {
  271. ESP_LOGI(TAG, "Serving config.json");
  272. ESP_LOGI(TAG, "About to get config from flash");
  273. http_server_send_config_json(conn);
  274. ESP_LOGD(TAG, "Done serving config.json");
  275. }
  276. else if(strstr(line, "POST /config.json ")) {
  277. ESP_LOGI(TAG, "Serving POST config.json");
  278. int lenA=0;
  279. char * last_parm=save_ptr;
  280. char * next_parm=save_ptr;
  281. char * last_parm_name=NULL;
  282. bool bErrorFound=false;
  283. bool bOTA=false;
  284. char * otaURL=NULL;
  285. // todo: implement json body parsing
  286. //http_server_process_config(conn,save_ptr);
  287. while(last_parm!=NULL) {
  288. // Search will return
  289. ESP_LOGD(TAG, "Getting parameters from X-Custom headers");
  290. last_parm = http_server_search_header(next_parm, "X-Custom-", &lenA, &last_parm_name,&next_parm,buf+buflen);
  291. if(last_parm!=NULL && last_parm_name!=NULL) {
  292. ESP_LOGI(TAG, "http_server_netconn_serve: POST config.json, config %s=%s", last_parm_name, last_parm);
  293. if(strcmp(last_parm_name, "fwurl")==0) {
  294. // we're getting a request to do an OTA from that URL
  295. ESP_LOGW(TAG, "Found OTA request!");
  296. otaURL=strdup(last_parm);
  297. bOTA=true;
  298. }
  299. else {
  300. ESP_LOGV(TAG, "http_server_netconn_serve: POST config.json Storing parameter");
  301. if(config_set_value(NVS_TYPE_STR, last_parm_name , last_parm) != ESP_OK){
  302. ESP_LOGE(TAG, "Unable to save nvs value.");
  303. }
  304. }
  305. }
  306. if(last_parm_name!=NULL) {
  307. free(last_parm_name);
  308. last_parm_name=NULL;
  309. }
  310. }
  311. if(bErrorFound) {
  312. netconn_write(conn, http_400_hdr, sizeof(http_400_hdr) - 1, NETCONN_NOCOPY); //400 invalid request
  313. }
  314. else {
  315. netconn_write(conn, http_ok_json_no_cache_hdr, sizeof(http_ok_json_no_cache_hdr) - 1, NETCONN_NOCOPY); //200ok
  316. if(bOTA) {
  317. #if RECOVERY_APPLICATION
  318. ESP_LOGW(TAG, "Starting process OTA for url %s",otaURL);
  319. #else
  320. ESP_LOGW(TAG, "Restarting system to process OTA for url %s",otaURL);
  321. #endif
  322. wifi_manager_reboot_ota(otaURL);
  323. free(otaURL);
  324. }
  325. }
  326. ESP_LOGI(TAG, "Done Serving POST config.json");
  327. }
  328. else if(strstr(line, "POST /connect.json ")) {
  329. ESP_LOGI(TAG, "http_server_netconn_serve: POST /connect.json");
  330. bool found = false;
  331. int lenS = 0, lenP = 0, lenN = 0;
  332. char *ssid = NULL, *password = NULL;
  333. ssid = http_server_get_header(save_ptr, "X-Custom-ssid: ", &lenS);
  334. password = http_server_get_header(save_ptr, "X-Custom-pwd: ", &lenP);
  335. char * new_host_name_b = http_server_get_header(save_ptr, "X-Custom-host_name: ", &lenN);
  336. if(lenN > 0){
  337. lenN++;
  338. char * new_host_name = malloc(lenN);
  339. strlcpy(new_host_name, new_host_name_b, lenN);
  340. if(config_set_value(NVS_TYPE_STR, "host_name", new_host_name) != ESP_OK){
  341. ESP_LOGE(TAG, "Unable to save host name configuration");
  342. }
  343. free(new_host_name);
  344. }
  345. if(ssid && lenS <= MAX_SSID_SIZE && password && lenP <= MAX_PASSWORD_SIZE) {
  346. wifi_config_t* config = wifi_manager_get_wifi_sta_config();
  347. memset(config, 0x00, sizeof(wifi_config_t));
  348. memcpy(config->sta.ssid, ssid, lenS);
  349. memcpy(config->sta.password, password, lenP);
  350. ESP_LOGD(TAG, "http_server_netconn_serve: wifi_manager_connect_async() call, with ssid: %s, password: %s", config->sta.ssid, config->sta.password);
  351. wifi_manager_connect_async();
  352. netconn_write(conn, http_ok_json_no_cache_hdr, sizeof(http_ok_json_no_cache_hdr) - 1, NETCONN_NOCOPY); //200ok
  353. found = true;
  354. }
  355. else{
  356. ESP_LOGE(TAG, "SSID or Password invalid");
  357. }
  358. if(!found) {
  359. /* bad request the authentification header is not complete/not the correct format */
  360. netconn_write(conn, http_400_hdr, sizeof(http_400_hdr) - 1, NETCONN_NOCOPY);
  361. ESP_LOGE(TAG, "bad request the authentification header is not complete/not the correct format");
  362. }
  363. ESP_LOGI(TAG, "http_server_netconn_serve: done serving connect.json");
  364. }
  365. else if(strstr(line, "DELETE /connect.json ")) {
  366. ESP_LOGI(TAG, "http_server_netconn_serve: DELETE /connect.json");
  367. /* request a disconnection from wifi and forget about it */
  368. wifi_manager_disconnect_async();
  369. netconn_write(conn, http_ok_json_no_cache_hdr, sizeof(http_ok_json_no_cache_hdr) - 1, NETCONN_NOCOPY); /* 200 ok */
  370. ESP_LOGI(TAG, "http_server_netconn_serve: done serving DELETE /connect.json");
  371. }
  372. else if(strstr(line, "POST /reboot_ota.json ")) {
  373. ESP_LOGI(TAG, "http_server_netconn_serve: POST reboot_ota.json");
  374. netconn_write(conn, http_ok_json_no_cache_hdr, sizeof(http_ok_json_no_cache_hdr) - 1, NETCONN_NOCOPY); /* 200 ok */
  375. wifi_manager_reboot(OTA);
  376. ESP_LOGI(TAG, "http_server_netconn_serve: done serving POST reboot_ota.json");
  377. }
  378. else if(strstr(line, "POST /reboot.json ")) {
  379. ESP_LOGI(TAG, "http_server_netconn_serve: POST reboot.json");
  380. netconn_write(conn, http_ok_json_no_cache_hdr, sizeof(http_ok_json_no_cache_hdr) - 1, NETCONN_NOCOPY); /* 200 ok */
  381. wifi_manager_reboot(RESTART);
  382. ESP_LOGI(TAG, "http_server_netconn_serve: done serving POST reboot.json");
  383. }
  384. else if(strstr(line, "POST /recovery.json ")) {
  385. ESP_LOGI(TAG, "http_server_netconn_serve: POST recovery.json");
  386. netconn_write(conn, http_ok_json_no_cache_hdr, sizeof(http_ok_json_no_cache_hdr) - 1, NETCONN_NOCOPY); /* 200 ok */
  387. wifi_manager_reboot(RECOVERY);
  388. ESP_LOGI(TAG, "http_server_netconn_serve: done serving POST recovery.json");
  389. }
  390. else if(strstr(line, "GET /status.json ")) {
  391. ESP_LOGI(TAG, "Serving status.json");
  392. if(wifi_manager_lock_json_buffer(( TickType_t ) 10)) {
  393. char *buff = wifi_manager_alloc_get_ip_info_json();
  394. wifi_manager_unlock_json_buffer();
  395. if(buff) {
  396. netconn_write(conn, http_ok_json_no_cache_hdr, sizeof(http_ok_json_no_cache_hdr) - 1, NETCONN_NOCOPY);
  397. netconn_write(conn, buff, strlen(buff), NETCONN_NOCOPY);
  398. free(buff);
  399. }
  400. else {
  401. netconn_write(conn, http_503_hdr, sizeof(http_503_hdr) - 1, NETCONN_NOCOPY);
  402. }
  403. }
  404. else {
  405. netconn_write(conn, http_503_hdr, sizeof(http_503_hdr) - 1, NETCONN_NOCOPY);
  406. ESP_LOGE(TAG, "http_server_netconn_serve: GET /status failed to obtain mutex");
  407. }
  408. ESP_LOGI(TAG, "Done Serving status.json");
  409. }
  410. else {
  411. netconn_write(conn, http_400_hdr, sizeof(http_400_hdr) - 1, NETCONN_NOCOPY);
  412. ESP_LOGE(TAG, "bad request from host: %s, request %s",remote_address, line);
  413. }
  414. }
  415. }
  416. else {
  417. ESP_LOGE(TAG, "URL not found processing for remote host : %s",remote_address);
  418. netconn_write(conn, http_404_hdr, sizeof(http_404_hdr) - 1, NETCONN_NOCOPY);
  419. }
  420. free(host);
  421. }