http_server.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  1. /*
  2. Copyright (c) 2017-2019 Tony Pottier
  3. Permission is hereby granted, free of charge, to any person obtaining a copy
  4. of this software and associated documentation files (the "Software"), to deal
  5. in the Software without restriction, including without limitation the rights
  6. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. copies of the Software, and to permit persons to whom the Software is
  8. furnished to do so, subject to the following conditions:
  9. The above copyright notice and this permission notice shall be included in all
  10. copies or substantial portions of the Software.
  11. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  12. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  13. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  14. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  15. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  17. SOFTWARE.
  18. @file http_server.c
  19. @author Tony Pottier
  20. @brief Defines all functions necessary for the HTTP server to run.
  21. Contains the freeRTOS task for the HTTP listener and all necessary support
  22. function to process requests, decode URLs, serve files, etc. etc.
  23. @note http_server task cannot run without the wifi_manager task!
  24. @see https://idyl.io
  25. @see https://github.com/tonyp7/esp32-wifi-manager
  26. */
  27. #include "http_server.h"
  28. #include "cmd_system.h"
  29. #include <inttypes.h>
  30. #include "squeezelite-ota.h"
  31. #include "nvs_utilities.h"
  32. #include <stdio.h>
  33. #include <stdlib.h>
  34. #include "cJSON.h"
  35. #include "esp_system.h"
  36. #include "freertos/FreeRTOS.h"
  37. #include "freertos/task.h"
  38. #include "config.h"
  39. #define HTTP_STACK_SIZE (5*1024)
  40. /* @brief tag used for ESP serial console messages */
  41. static const char TAG[] = "http_server";
  42. /* @brief task handle for the http server */
  43. static TaskHandle_t task_http_server = NULL;
  44. static StaticTask_t task_http_buffer;
  45. #if RECOVERY_APPLICATION
  46. static StackType_t task_http_stack[HTTP_STACK_SIZE];
  47. #else
  48. static StackType_t EXT_RAM_ATTR task_http_stack[HTTP_STACK_SIZE];
  49. #endif
  50. SemaphoreHandle_t http_server_config_mutex = NULL;
  51. /**
  52. * @brief embedded binary data.
  53. * @see file "component.mk"
  54. * @see https://docs.espressif.com/projects/esp-idf/en/latest/api-guides/build-system.html#embedding-binary-data
  55. */
  56. extern const uint8_t style_css_start[] asm("_binary_style_css_start");
  57. extern const uint8_t style_css_end[] asm("_binary_style_css_end");
  58. extern const uint8_t jquery_gz_start[] asm("_binary_jquery_min_js_gz_start");
  59. extern const uint8_t jquery_gz_end[] asm("_binary_jquery_min_js_gz_end");
  60. extern const uint8_t popper_gz_start[] asm("_binary_popper_min_js_gz_start");
  61. extern const uint8_t popper_gz_end[] asm("_binary_popper_min_js_gz_end");
  62. extern const uint8_t bootstrap_js_gz_start[] asm("_binary_bootstrap_min_js_gz_start");
  63. extern const uint8_t bootstrap_js_gz_end[] asm("_binary_bootstrap_min_js_gz_end");
  64. extern const uint8_t bootstrap_css_gz_start[] asm("_binary_bootstrap_min_css_gz_start");
  65. extern const uint8_t bootstrap_css_gz_end[] asm("_binary_bootstrap_min_css_gz_end");
  66. extern const uint8_t code_js_start[] asm("_binary_code_js_start");
  67. extern const uint8_t code_js_end[] asm("_binary_code_js_end");
  68. extern const uint8_t index_html_start[] asm("_binary_index_html_start");
  69. extern const uint8_t index_html_end[] asm("_binary_index_html_end");
  70. /* const http headers stored in ROM */
  71. const static char http_hdr_template[] = "HTTP/1.1 200 OK\nContent-type: %s\nAccept-Ranges: bytes\nContent-Length: %d\nContent-Encoding: %s\nAccess-Control-Allow-Origin: *\n\n";
  72. const static char http_html_hdr[] = "HTTP/1.1 200 OK\nContent-type: text/html\nAccess-Control-Allow-Origin: *\nAccept-Encoding: identity\n\n";
  73. const static char http_css_hdr[] = "HTTP/1.1 200 OK\nContent-type: text/css\nCache-Control: public, max-age=31536000\nAccess-Control-Allow-Origin: *\n\n";
  74. const static char http_js_hdr[] = "HTTP/1.1 200 OK\nContent-type: text/javascript\nAccess-Control-Allow-Origin: *\n\n";
  75. const static char http_400_hdr[] = "HTTP/1.1 400 Bad Request\nContent-Length: 0\n\n";
  76. const static char http_404_hdr[] = "HTTP/1.1 404 Not Found\nContent-Length: 0\n\n";
  77. const static char http_503_hdr[] = "HTTP/1.1 503 Service Unavailable\nContent-Length: 0\n\n";
  78. const static char http_ok_json_no_cache_hdr[] = "HTTP/1.1 200 OK\nContent-type: application/json\nCache-Control: no-store, no-cache, must-revalidate, max-age=0\nPragma: no-cache\nAccess-Control-Allow-Origin: *\nAccept-Encoding: identity\n\n";
  79. const static char http_redirect_hdr_start[] = "HTTP/1.1 302 Found\nLocation: http://";
  80. const static char http_redirect_hdr_end[] = "/\n\n";
  81. void http_server_start() {
  82. ESP_LOGD(TAG, "http_server_start ");
  83. if(task_http_server == NULL) {
  84. task_http_server = xTaskCreateStatic( (TaskFunction_t) &http_server, "http_server", HTTP_STACK_SIZE, NULL,
  85. WIFI_MANAGER_TASK_PRIORITY, task_http_stack, &task_http_buffer);
  86. }
  87. }
  88. void http_server(void *pvParameters) {
  89. http_server_config_mutex = xSemaphoreCreateMutex();
  90. struct netconn *conn, *newconn;
  91. err_t err;
  92. conn = netconn_new(NETCONN_TCP);
  93. netconn_bind(conn, IP_ADDR_ANY, 80);
  94. netconn_listen(conn);
  95. ESP_LOGI(TAG, "HTTP Server listening on 80/tcp");
  96. do {
  97. err = netconn_accept(conn, &newconn);
  98. if(err == ERR_OK) {
  99. http_server_netconn_serve(newconn);
  100. netconn_delete(newconn);
  101. }
  102. else
  103. {
  104. ESP_LOGE(TAG, "Error accepting new connection. Terminating HTTP server");
  105. }
  106. taskYIELD(); /* allows the freeRTOS scheduler to take over if needed. */
  107. } while(err == ERR_OK);
  108. netconn_close(conn);
  109. netconn_delete(conn);
  110. vSemaphoreDelete(http_server_config_mutex);
  111. http_server_config_mutex = NULL;
  112. vTaskDelete( NULL );
  113. }
  114. char* http_server_get_header(char *request, char *header_name, int *len) {
  115. *len = 0;
  116. char *ret = NULL;
  117. char *ptr = NULL;
  118. ptr = strstr(request, header_name);
  119. if(ptr) {
  120. ret = ptr + strlen(header_name);
  121. ptr = ret;
  122. while (*ptr != '\0' && *ptr != '\n' && *ptr != '\r') {
  123. (*len)++;
  124. ptr++;
  125. }
  126. return ret;
  127. }
  128. return NULL;
  129. }
  130. char* http_server_search_header(char *request, char *header_name, int *len, char ** parm_name, char ** next_position, char * bufEnd) {
  131. *len = 0;
  132. char *ret = NULL;
  133. char *ptr = NULL;
  134. int currentLength=0;
  135. ESP_LOGV(TAG, "searching for header name: [%s]", header_name);
  136. ptr = strstr(request, header_name);
  137. if(ptr!=NULL && ptr<bufEnd) {
  138. ret = ptr + strlen(header_name);
  139. ptr = ret;
  140. currentLength=(int)(ptr-request);
  141. ESP_LOGV(TAG, "found string at %d", currentLength);
  142. while (*ptr != '\0' && *ptr != '\n' && *ptr != '\r' && *ptr != ':' && ptr<bufEnd) {
  143. ptr++;
  144. }
  145. if(*ptr==':') {
  146. currentLength=(int)(ptr-ret);
  147. ESP_LOGV(TAG, "Found parameter name end, length : %d", currentLength);
  148. // save the parameter name: the string between header name and ":"
  149. *parm_name=malloc(currentLength+1);
  150. if(*parm_name==NULL) {
  151. ESP_LOGE(TAG, "Unable to allocate memory for new header name");
  152. return NULL;
  153. }
  154. memset(*parm_name, 0x00,currentLength+1);
  155. strncpy(*parm_name,ret,currentLength);
  156. ESP_LOGV(TAG, "Found parameter name : %s ", *parm_name);
  157. ptr++;
  158. while (*ptr == ' ' && ptr<bufEnd) {
  159. ptr++;
  160. }
  161. }
  162. ret=ptr;
  163. while (*ptr != '\0' && *ptr != '\n' && *ptr != '\r'&& ptr<bufEnd) {
  164. (*len)++;
  165. ptr++;
  166. }
  167. // Terminate value inside its actual buffer so we can treat it as individual string
  168. *ptr='\0';
  169. currentLength=(int)(ptr-ret);
  170. ESP_LOGV(TAG, "Found parameter value end, length : %d, value: %s", currentLength,ret );
  171. *next_position=++ptr;
  172. return ret;
  173. }
  174. ESP_LOGD(TAG, "No more match for : %s", header_name);
  175. return NULL;
  176. }
  177. void http_server_send_resource_file(struct netconn *conn,const uint8_t * start, const uint8_t * end, char * content_type,char * encoding) {
  178. uint16_t len=end - start;
  179. size_t buff_length= sizeof(http_hdr_template)+strlen(content_type)+strlen(encoding);
  180. char * http_hdr=malloc(buff_length);
  181. if( http_hdr == NULL) {
  182. ESP_LOGE(TAG, "Cound not allocate %d bytes for headers.",buff_length);
  183. netconn_write(conn, http_503_hdr, sizeof(http_503_hdr) - 1, NETCONN_NOCOPY);
  184. }
  185. else
  186. {
  187. memset(http_hdr,0x00,buff_length);
  188. snprintf(http_hdr, buff_length-1,http_hdr_template,content_type,len,encoding);
  189. netconn_write(conn, http_hdr, strlen(http_hdr), NETCONN_NOCOPY);
  190. ESP_LOGD(TAG, "sending response : %s",http_hdr);
  191. netconn_write(conn, start, end - start, NETCONN_NOCOPY);
  192. free(http_hdr);
  193. }
  194. }
  195. err_t http_server_send_config_json(struct netconn *conn) {
  196. char * json = config_alloc_get_json(false);
  197. if(json!=NULL){
  198. ESP_LOGD(TAG, "config json : %s",json );
  199. netconn_write(conn, http_ok_json_no_cache_hdr, sizeof(http_ok_json_no_cache_hdr) - 1, NETCONN_NOCOPY);
  200. netconn_write(conn, json, strlen(json), NETCONN_NOCOPY);
  201. free(json);
  202. }
  203. else{
  204. ESP_LOGD(TAG, "Error retrieving config json string. ");
  205. netconn_write(conn, http_503_hdr, sizeof(http_503_hdr) - 1, NETCONN_NOCOPY);
  206. }
  207. return ESP_OK;
  208. }
  209. void http_server_process_config(struct netconn *conn, char *inbuf) {
  210. // Here, we are passed a buffer which contains the http request
  211. // netbuf_data(inbuf, (void**)&buf, &buflen);
  212. // err = netconn_recv(conn, &inbuf);
  213. // if(err == ERR_OK) {
  214. //
  215. // /* extract the first line of the request */
  216. // char *save_ptr = buf;
  217. // char *line = strtok_r(save_ptr, new_line, &save_ptr);
  218. // ESP_LOGD(TAG, "Processing line %s",line);
  219. ESP_LOGD(TAG, "Processing request buffer: \n%s",inbuf);
  220. char *last = NULL;
  221. char *ptr = NULL;
  222. last = ptr = inbuf;
  223. bool bHeaders= true;
  224. while(ptr!=NULL && *ptr != '\0') {
  225. // Move to the end of the line, or to the end of the buffer
  226. if(bHeaders) {
  227. while (*ptr != '\0' && *ptr != '\n' && *ptr != '\r') {
  228. ptr++;
  229. }
  230. // terminate the header string
  231. if( *(ptr) == '\0' ) {
  232. ESP_LOGD(TAG, "End of buffer found");
  233. return;
  234. }
  235. *ptr = '\0';
  236. if( *(ptr+1) == '\n' ) {
  237. *(ptr+1)='\0';
  238. ptr+=2;
  239. }
  240. if(ptr==last) {
  241. ESP_LOGD(TAG, "Processing body. ");
  242. break;
  243. }
  244. if(strlen(last)>0) {
  245. ESP_LOGD(TAG, "Found Header Line %s ", last);
  246. //Content-Type: application/json
  247. }
  248. else {
  249. ESP_LOGD(TAG, "Found end of headers");
  250. bHeaders = false;
  251. }
  252. last=ptr;
  253. }
  254. else {
  255. //ESP_LOGD(TAG, "Body content: %s", last);
  256. //cJSON * json = cJSON_Parse(last);
  257. //cJSON_Delete(json);
  258. //todo: implement body json parsing
  259. // right now, body is coming as compressed, so we need some type of decompression to happen.
  260. return;
  261. }
  262. }
  263. return ;
  264. }
  265. void dump_net_buffer(void * buf, u16_t buflen) {
  266. char * curbuf = malloc(buflen+1);
  267. ESP_LOGV(TAG, "netconn buffer, length=%u",buflen);
  268. if(curbuf==NULL) {
  269. ESP_LOGE(TAG, "Unable to show netconn buffer. Malloc failed");
  270. }
  271. memset(curbuf,0x0, buflen+1);
  272. memcpy(curbuf,buf,buflen);
  273. ESP_LOGV(TAG, "netconn buffer content:\n%s",curbuf);
  274. free(curbuf);
  275. }
  276. void http_server_netconn_serve(struct netconn *conn) {
  277. struct netbuf *inbuf;
  278. char *buf = NULL;
  279. u16_t buflen = 0;
  280. err_t err;
  281. ip_addr_t remote_add;
  282. u16_t port;
  283. ESP_LOGV(TAG, "Serving page. Getting device AP address.");
  284. const char new_line[2] = "\n";
  285. char * ap_ip_address= config_alloc_get_default(NVS_TYPE_STR, "ap_ip_address", DEFAULT_AP_IP, 0);
  286. if(ap_ip_address==NULL){
  287. ESP_LOGE(TAG, "Unable to retrieve default AP IP Address");
  288. netconn_write(conn, http_503_hdr, sizeof(http_503_hdr) - 1, NETCONN_NOCOPY);
  289. netconn_close(conn);
  290. return;
  291. }
  292. ESP_LOGV(TAG, "Getting remote device IP address.");
  293. netconn_getaddr(conn, &remote_add, &port, 0);
  294. char * remote_address = strdup(ip4addr_ntoa(ip_2_ip4(&remote_add)));
  295. ESP_LOGD(TAG, "Local Access Point IP address is: %s. Remote device IP address is %s. Receiving request buffer", ap_ip_address, remote_address);
  296. u16_t bufsize = 0;
  297. netconn_set_recvtimeout(conn, 50);
  298. while (netconn_recv(conn, &inbuf) == ERR_OK) {
  299. do {
  300. u8_t *rcvbuf;
  301. u16_t rcvlen;
  302. netbuf_data(inbuf, (void**)&rcvbuf, &rcvlen);
  303. dump_net_buffer(rcvbuf, rcvlen);
  304. if (buflen + rcvlen > bufsize) {
  305. bufsize += rcvlen - bufsize < 2048 ? 2048 : rcvlen - bufsize;
  306. buf = realloc(buf, bufsize);
  307. }
  308. memcpy(buf + buflen, rcvbuf, rcvlen);
  309. buflen += rcvlen;
  310. ESP_LOGI(TAG, "received netbuf of %hu", rcvlen);
  311. } while (netbuf_next(inbuf) != -1);
  312. netbuf_delete(inbuf);
  313. }
  314. if(buflen) {
  315. ESP_LOGV(TAG, "Getting data buffer.");
  316. int lenH = 0;
  317. /* extract the first line of the request */
  318. char *save_ptr = buf;
  319. char *line = strtok_r(save_ptr, new_line, &save_ptr);
  320. char *temphost = http_server_get_header(save_ptr, "Host: ", &lenH);
  321. char * host = malloc(lenH+1);
  322. memset(host,0x00,lenH+1);
  323. if(lenH>0){
  324. strlcpy(host,temphost,lenH+1);
  325. }
  326. ESP_LOGD(TAG, "http_server_netconn_serve Host: [%s], host: [%s], Processing line [%s]",remote_address,host,line);
  327. if(line) {
  328. /* captive portal functionality: redirect to access point IP for HOST that are not the access point IP OR the STA IP */
  329. const char * host_name=NULL;
  330. if((err=tcpip_adapter_get_hostname(TCPIP_ADAPTER_IF_STA, &host_name )) !=ESP_OK) {
  331. ESP_LOGE(TAG, "Unable to get host name. Error: %s",esp_err_to_name(err));
  332. }
  333. else {
  334. ESP_LOGI(TAG,"System host name %s, http requested host: %s.",host_name, host);
  335. }
  336. /* determine if Host is from the STA IP address */
  337. wifi_manager_lock_sta_ip_string(portMAX_DELAY);
  338. bool access_from_sta_ip = lenH > 0?strcasestr(host, wifi_manager_get_sta_ip_string()):false;
  339. wifi_manager_unlock_sta_ip_string();
  340. bool access_from_host_name = (host_name!=NULL) && strcasestr(host,host_name);
  341. if(lenH > 0 && !strcasestr(host, ap_ip_address) && !(access_from_sta_ip || access_from_host_name)) {
  342. ESP_LOGI(TAG, "Redirecting host [%s] to AP IP Address : %s",remote_address, ap_ip_address);
  343. netconn_write(conn, http_redirect_hdr_start, sizeof(http_redirect_hdr_start) - 1, NETCONN_NOCOPY);
  344. netconn_write(conn, ap_ip_address, strlen(ap_ip_address), NETCONN_NOCOPY);
  345. netconn_write(conn, http_redirect_hdr_end, sizeof(http_redirect_hdr_end) - 1, NETCONN_NOCOPY);
  346. }
  347. else {
  348. //static stuff
  349. /* default page */
  350. if(strstr(line, "GET / ")) {
  351. netconn_write(conn, http_html_hdr, sizeof(http_html_hdr) - 1, NETCONN_NOCOPY);
  352. netconn_write(conn, index_html_start, index_html_end- index_html_start, NETCONN_NOCOPY);
  353. }
  354. else if(strstr(line, "GET /code.js ")) {
  355. netconn_write(conn, http_js_hdr, sizeof(http_js_hdr) - 1, NETCONN_NOCOPY);
  356. netconn_write(conn, code_js_start, code_js_end - code_js_start, NETCONN_NOCOPY);
  357. }
  358. else if(strstr(line, "GET /style.css ")) {
  359. netconn_write(conn, http_css_hdr, sizeof(http_css_hdr) - 1, NETCONN_NOCOPY);
  360. netconn_write(conn, style_css_start, style_css_end - style_css_start, NETCONN_NOCOPY);
  361. }
  362. else if(strstr(line, "GET /jquery.js ")) {
  363. http_server_send_resource_file(conn,jquery_gz_start, jquery_gz_end, "text/javascript", "gzip" );
  364. }
  365. else if(strstr(line, "GET /popper.js ")) {
  366. http_server_send_resource_file(conn,popper_gz_start, popper_gz_end, "text/javascript", "gzip" );
  367. }
  368. else if(strstr(line, "GET /bootstrap.js ")) {
  369. http_server_send_resource_file(conn,bootstrap_js_gz_start, bootstrap_js_gz_end, "text/javascript", "gzip" );
  370. }
  371. else if(strstr(line, "GET /bootstrap.css ")) {
  372. http_server_send_resource_file(conn,bootstrap_css_gz_start, bootstrap_css_gz_end, "text/css", "gzip" );
  373. }
  374. //dynamic stuff
  375. else if(strstr(line, "GET /scan.json ")) {
  376. ESP_LOGI(TAG, "Starting wifi scan");
  377. wifi_manager_scan_async();
  378. }
  379. else if(strstr(line, "GET /ap.json ")) {
  380. /* if we can get the mutex, write the last version of the AP list */
  381. ESP_LOGI(TAG, "Processing ap.json request");
  382. if(wifi_manager_lock_json_buffer(( TickType_t ) 10)) {
  383. netconn_write(conn, http_ok_json_no_cache_hdr, sizeof(http_ok_json_no_cache_hdr) - 1, NETCONN_NOCOPY);
  384. char *buff = wifi_manager_alloc_get_ap_list_json();
  385. wifi_manager_unlock_json_buffer();
  386. if(buff!=NULL){
  387. netconn_write(conn, buff, strlen(buff), NETCONN_NOCOPY);
  388. free(buff);
  389. }
  390. else {
  391. ESP_LOGD(TAG, "Error retrieving ap list json string. ");
  392. netconn_write(conn, http_503_hdr, sizeof(http_503_hdr) - 1, NETCONN_NOCOPY);
  393. }
  394. }
  395. else {
  396. netconn_write(conn, http_503_hdr, sizeof(http_503_hdr) - 1, NETCONN_NOCOPY);
  397. ESP_LOGE(TAG, "http_server_netconn_serve: GET /ap.json failed to obtain mutex");
  398. }
  399. /* request a wifi scan */
  400. ESP_LOGI(TAG, "Starting wifi scan");
  401. wifi_manager_scan_async();
  402. ESP_LOGI(TAG, "Done serving ap.json");
  403. }
  404. else if(strstr(line, "GET /config.json ")) {
  405. ESP_LOGI(TAG, "Serving config.json");
  406. ESP_LOGI(TAG, "About to get config from flash");
  407. http_server_send_config_json(conn);
  408. ESP_LOGD(TAG, "Done serving config.json");
  409. }
  410. else if(strstr(line, "POST /config.json ")) {
  411. ESP_LOGI(TAG, "Serving POST config.json");
  412. int lenA=0;
  413. char * last_parm=save_ptr;
  414. char * next_parm=save_ptr;
  415. char * last_parm_name=NULL;
  416. bool bErrorFound=false;
  417. bool bOTA=false;
  418. char * otaURL=NULL;
  419. // todo: implement json body parsing
  420. //http_server_process_config(conn,save_ptr);
  421. while(last_parm!=NULL) {
  422. // Search will return
  423. ESP_LOGD(TAG, "Getting parameters from X-Custom headers");
  424. last_parm = http_server_search_header(next_parm, "X-Custom-", &lenA, &last_parm_name,&next_parm,buf+buflen);
  425. if(last_parm!=NULL && last_parm_name!=NULL) {
  426. ESP_LOGI(TAG, "http_server_netconn_serve: POST config.json, config %s=%s", last_parm_name, last_parm);
  427. if(strcmp(last_parm_name, "fwurl")==0) {
  428. // we're getting a request to do an OTA from that URL
  429. ESP_LOGW(TAG, "Found OTA request!");
  430. otaURL=strdup(last_parm);
  431. bOTA=true;
  432. }
  433. else {
  434. ESP_LOGV(TAG, "http_server_netconn_serve: POST config.json Storing parameter");
  435. if(config_set_value(NVS_TYPE_STR, last_parm_name , last_parm) != ESP_OK){
  436. ESP_LOGE(TAG, "Unable to save nvs value.");
  437. }
  438. }
  439. }
  440. if(last_parm_name!=NULL) {
  441. free(last_parm_name);
  442. last_parm_name=NULL;
  443. }
  444. }
  445. if(bErrorFound) {
  446. netconn_write(conn, http_400_hdr, sizeof(http_400_hdr) - 1, NETCONN_NOCOPY); //400 invalid request
  447. }
  448. else {
  449. netconn_write(conn, http_ok_json_no_cache_hdr, sizeof(http_ok_json_no_cache_hdr) - 1, NETCONN_NOCOPY); //200ok
  450. if(bOTA) {
  451. #if RECOVERY_APPLICATION
  452. ESP_LOGW(TAG, "Starting process OTA for url %s",otaURL);
  453. #else
  454. ESP_LOGW(TAG, "Restarting system to process OTA for url %s",otaURL);
  455. #endif
  456. wifi_manager_reboot_ota(otaURL);
  457. free(otaURL);
  458. }
  459. }
  460. ESP_LOGI(TAG, "Done Serving POST config.json");
  461. }
  462. else if(strstr(line, "POST /connect.json ")) {
  463. ESP_LOGI(TAG, "http_server_netconn_serve: POST /connect.json");
  464. bool found = false;
  465. int lenS = 0, lenP = 0, lenN = 0;
  466. char *ssid = NULL, *password = NULL;
  467. ssid = http_server_get_header(save_ptr, "X-Custom-ssid: ", &lenS);
  468. password = http_server_get_header(save_ptr, "X-Custom-pwd: ", &lenP);
  469. char * new_host_name_b = http_server_get_header(save_ptr, "X-Custom-host_name: ", &lenN);
  470. if(lenN > 0){
  471. lenN++;
  472. char * new_host_name = malloc(lenN);
  473. strlcpy(new_host_name, new_host_name_b, lenN);
  474. if(config_set_value(NVS_TYPE_STR, "host_name", new_host_name) != ESP_OK){
  475. ESP_LOGE(TAG, "Unable to save host name configuration");
  476. }
  477. free(new_host_name);
  478. }
  479. if(ssid && lenS <= MAX_SSID_SIZE && password && lenP <= MAX_PASSWORD_SIZE) {
  480. wifi_config_t* config = wifi_manager_get_wifi_sta_config();
  481. memset(config, 0x00, sizeof(wifi_config_t));
  482. memcpy(config->sta.ssid, ssid, lenS);
  483. memcpy(config->sta.password, password, lenP);
  484. ESP_LOGD(TAG, "http_server_netconn_serve: wifi_manager_connect_async() call, with ssid: %s, password: %s", config->sta.ssid, config->sta.password);
  485. wifi_manager_connect_async();
  486. netconn_write(conn, http_ok_json_no_cache_hdr, sizeof(http_ok_json_no_cache_hdr) - 1, NETCONN_NOCOPY); //200ok
  487. found = true;
  488. }
  489. else{
  490. ESP_LOGE(TAG, "SSID or Password invalid");
  491. }
  492. if(!found) {
  493. /* bad request the authentification header is not complete/not the correct format */
  494. netconn_write(conn, http_400_hdr, sizeof(http_400_hdr) - 1, NETCONN_NOCOPY);
  495. ESP_LOGE(TAG, "bad request the authentification header is not complete/not the correct format");
  496. }
  497. ESP_LOGI(TAG, "http_server_netconn_serve: done serving connect.json");
  498. }
  499. else if(strstr(line, "DELETE /connect.json ")) {
  500. ESP_LOGI(TAG, "http_server_netconn_serve: DELETE /connect.json");
  501. /* request a disconnection from wifi and forget about it */
  502. wifi_manager_disconnect_async();
  503. netconn_write(conn, http_ok_json_no_cache_hdr, sizeof(http_ok_json_no_cache_hdr) - 1, NETCONN_NOCOPY); /* 200 ok */
  504. ESP_LOGI(TAG, "http_server_netconn_serve: done serving DELETE /connect.json");
  505. }
  506. else if(strstr(line, "POST /reboot_ota.json ")) {
  507. ESP_LOGI(TAG, "http_server_netconn_serve: POST reboot_ota.json");
  508. netconn_write(conn, http_ok_json_no_cache_hdr, sizeof(http_ok_json_no_cache_hdr) - 1, NETCONN_NOCOPY); /* 200 ok */
  509. wifi_manager_reboot(OTA);
  510. ESP_LOGI(TAG, "http_server_netconn_serve: done serving POST reboot_ota.json");
  511. }
  512. else if(strstr(line, "POST /reboot.json ")) {
  513. ESP_LOGI(TAG, "http_server_netconn_serve: POST reboot.json");
  514. netconn_write(conn, http_ok_json_no_cache_hdr, sizeof(http_ok_json_no_cache_hdr) - 1, NETCONN_NOCOPY); /* 200 ok */
  515. wifi_manager_reboot(RESTART);
  516. ESP_LOGI(TAG, "http_server_netconn_serve: done serving POST reboot.json");
  517. }
  518. else if(strstr(line, "POST /recovery.json ")) {
  519. ESP_LOGI(TAG, "http_server_netconn_serve: POST recovery.json");
  520. netconn_write(conn, http_ok_json_no_cache_hdr, sizeof(http_ok_json_no_cache_hdr) - 1, NETCONN_NOCOPY); /* 200 ok */
  521. wifi_manager_reboot(RECOVERY);
  522. ESP_LOGI(TAG, "http_server_netconn_serve: done serving POST recovery.json");
  523. }
  524. else if(strstr(line, "GET /status.json ")) {
  525. ESP_LOGI(TAG, "Serving status.json");
  526. if(wifi_manager_lock_json_buffer(( TickType_t ) 10)) {
  527. char *buff = wifi_manager_alloc_get_ip_info_json();
  528. wifi_manager_unlock_json_buffer();
  529. if(buff) {
  530. netconn_write(conn, http_ok_json_no_cache_hdr, sizeof(http_ok_json_no_cache_hdr) - 1, NETCONN_NOCOPY);
  531. netconn_write(conn, buff, strlen(buff), NETCONN_NOCOPY);
  532. free(buff);
  533. }
  534. else {
  535. netconn_write(conn, http_503_hdr, sizeof(http_503_hdr) - 1, NETCONN_NOCOPY);
  536. }
  537. }
  538. else {
  539. netconn_write(conn, http_503_hdr, sizeof(http_503_hdr) - 1, NETCONN_NOCOPY);
  540. ESP_LOGE(TAG, "http_server_netconn_serve: GET /status failed to obtain mutex");
  541. }
  542. ESP_LOGI(TAG, "Done Serving status.json");
  543. }
  544. else {
  545. netconn_write(conn, http_400_hdr, sizeof(http_400_hdr) - 1, NETCONN_NOCOPY);
  546. ESP_LOGE(TAG, "bad request from host: %s, request %s",remote_address, line);
  547. }
  548. }
  549. }
  550. else {
  551. ESP_LOGE(TAG, "URL not found processing for remote host : %s",remote_address);
  552. netconn_write(conn, http_404_hdr, sizeof(http_404_hdr) - 1, NETCONN_NOCOPY);
  553. }
  554. free(host);
  555. free(buf);
  556. }
  557. free(ap_ip_address);
  558. free(remote_address);
  559. netconn_close(conn);
  560. /* free the buffer */
  561. }
  562. bool http_server_lock_json_object(TickType_t xTicksToWait) {
  563. ESP_LOGD(TAG, "Locking config json object");
  564. if(http_server_config_mutex) {
  565. if( xSemaphoreTake( http_server_config_mutex, xTicksToWait ) == pdTRUE ) {
  566. ESP_LOGV(TAG, "config Json object locked!");
  567. return true;
  568. }
  569. else {
  570. ESP_LOGW(TAG, "Semaphore take failed. Unable to lock config Json object mutex");
  571. return false;
  572. }
  573. }
  574. else {
  575. ESP_LOGW(TAG, "Unable to lock config Json object mutex");
  576. return false;
  577. }
  578. }
  579. void http_server_unlock_json_object() {
  580. ESP_LOGD(TAG, "Unlocking json buffer!");
  581. xSemaphoreGive( http_server_config_mutex );
  582. }
  583. void strreplace(char *src, char *str, char *rep)
  584. {
  585. char *p = strstr(src, str);
  586. if(p)
  587. {
  588. int len = strlen(src)+strlen(rep)-strlen(str);
  589. char r[len];
  590. memset(r, 0, len);
  591. if( p >= src ) {
  592. strncpy(r, src, p-src);
  593. r[p-src]='\0';
  594. strncat(r, rep, strlen(rep));
  595. strncat(r, p+strlen(str), p+strlen(str)-src+strlen(src));
  596. strcpy(src, r);
  597. strreplace(p+strlen(rep), str, rep);
  598. }
  599. }
  600. }