http_server_handlers.c 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150
  1. /*
  2. Copyright (c) 2017-2021 Sebastien L
  3. */
  4. #include "http_server_handlers.h"
  5. #include "esp_http_server.h"
  6. #include "cmd_system.h"
  7. #include <inttypes.h>
  8. #include "squeezelite-ota.h"
  9. #include "nvs_utilities.h"
  10. #include <stdio.h>
  11. #include <stdlib.h>
  12. #include "cJSON.h"
  13. #include "esp_system.h"
  14. #include "freertos/FreeRTOS.h"
  15. #include "freertos/task.h"
  16. #include "platform_config.h"
  17. #include "sys/param.h"
  18. #include "esp_vfs.h"
  19. #include "messaging.h"
  20. #include "platform_esp32.h"
  21. #include "esp_console.h"
  22. #include "argtable3/argtable3.h"
  23. #include "platform_console.h"
  24. #include "accessors.h"
  25. #include "webapp/webpack.h"
  26. #include "network_wifi.h"
  27. #include "network_status.h"
  28. #include "tools.h"
  29. #define HTTP_STACK_SIZE (5*1024)
  30. const char str_na[]="N/A";
  31. #define STR_OR_NA(s) s?s:str_na
  32. /* @brief tag used for ESP serial console messages */
  33. static const char TAG[] = "httpd_handlers";
  34. /* @brief task handle for the http server */
  35. SemaphoreHandle_t http_server_config_mutex = NULL;
  36. extern RingbufHandle_t messaging;
  37. #define AUTH_TOKEN_SIZE 50
  38. typedef struct session_context {
  39. char * auth_token;
  40. bool authenticated;
  41. char * sess_ip_address;
  42. u16_t port;
  43. } session_context_t;
  44. union sockaddr_aligned {
  45. struct sockaddr sa;
  46. struct sockaddr_storage st;
  47. struct sockaddr_in sin;
  48. struct sockaddr_in6 sin6;
  49. } aligned_sockaddr_t;
  50. esp_err_t post_handler_buff_receive(httpd_req_t * req);
  51. static const char redirect_payload1[]="<html><head><title>Redirecting to Captive Portal</title><meta http-equiv='refresh' content='0; url=";
  52. static const char redirect_payload2[]="'></head><body><p>Please wait, refreshing. If page does not refresh, click <a href='";
  53. static const char redirect_payload3[]="'>here</a> to login.</p></body></html>";
  54. /**
  55. * @brief embedded binary data.
  56. * @see file "component.mk"
  57. * @see https://docs.espressif.com/projects/esp-idf/en/latest/api-guides/build-system.html#embedding-binary-data
  58. */
  59. esp_err_t redirect_processor(httpd_req_t *req, httpd_err_code_t error);
  60. char * alloc_get_http_header(httpd_req_t * req, const char * key){
  61. char* buf = NULL;
  62. size_t buf_len;
  63. /* Get header value string length and allocate memory for length + 1,
  64. * extra byte for null termination */
  65. buf_len = httpd_req_get_hdr_value_len(req, key) + 1;
  66. if (buf_len > 1) {
  67. buf = malloc_init_external(buf_len);
  68. /* Copy null terminated value string into buffer */
  69. if (httpd_req_get_hdr_value_str(req, "Host", buf, buf_len) == ESP_OK) {
  70. ESP_LOGD_LOC(TAG, "Found header => %s: %s",key, buf);
  71. }
  72. }
  73. return buf;
  74. }
  75. char * http_alloc_get_socket_address(httpd_req_t *req, u8_t local, in_port_t * portl) {
  76. socklen_t len;
  77. union sockaddr_aligned addr;
  78. len = sizeof(addr);
  79. ip_addr_t * ip_addr=NULL;
  80. char * ipstr = malloc_init_external(INET6_ADDRSTRLEN);
  81. typedef int (*getaddrname_fn_t)(int s, struct sockaddr *name, socklen_t *namelen);
  82. getaddrname_fn_t get_addr = NULL;
  83. int s = httpd_req_to_sockfd(req);
  84. if(s == -1) {
  85. free(ipstr);
  86. return strdup_psram("httpd_req_to_sockfd error");
  87. }
  88. ESP_LOGV_LOC(TAG,"httpd socket descriptor: %u", s);
  89. get_addr = local?&lwip_getsockname:&lwip_getpeername;
  90. if(get_addr(s, (struct sockaddr *)&addr, &len) <0){
  91. ESP_LOGE_LOC(TAG,"Failed to retrieve socket address");
  92. sprintf(ipstr,"N/A (0.0.0.%u)",local);
  93. }
  94. else {
  95. if (addr.sin.sin_family!= AF_INET) {
  96. ip_addr = (ip_addr_t *)&(addr.sin6.sin6_addr);
  97. inet_ntop(addr.sa.sa_family, ip_addr, ipstr, INET6_ADDRSTRLEN);
  98. ESP_LOGV_LOC(TAG,"Processing an IPV6 address : %s", ipstr);
  99. *portl = addr.sin6.sin6_port;
  100. unmap_ipv4_mapped_ipv6(ip_2_ip4(ip_addr), ip_2_ip6(ip_addr));
  101. }
  102. else {
  103. ip_addr = (ip_addr_t *)&(addr.sin.sin_addr);
  104. inet_ntop(addr.sa.sa_family, ip_addr, ipstr, INET6_ADDRSTRLEN);
  105. ESP_LOGV_LOC(TAG,"Processing an IPV6 address : %s", ipstr);
  106. *portl = addr.sin.sin_port;
  107. }
  108. inet_ntop(AF_INET, ip_addr, ipstr, INET6_ADDRSTRLEN);
  109. ESP_LOGV_LOC(TAG,"Retrieved ip address:port = %s:%u",ipstr, *portl);
  110. }
  111. return ipstr;
  112. }
  113. bool is_captive_portal_host_name(httpd_req_t *req){
  114. const char * host_name=NULL;
  115. const char * ap_host_name=NULL;
  116. char * ap_ip_address=NULL;
  117. bool request_contains_hostname = false;
  118. esp_err_t hn_err =ESP_OK, err=ESP_OK;
  119. ESP_LOGD_LOC(TAG, "Getting adapter host name");
  120. if((err = tcpip_adapter_get_hostname(TCPIP_ADAPTER_IF_STA, &host_name )) !=ESP_OK) {
  121. ESP_LOGE_LOC(TAG, "Unable to get host name. Error: %s",esp_err_to_name(err));
  122. }
  123. else {
  124. ESP_LOGD_LOC(TAG, "Host name is %s",host_name);
  125. }
  126. ESP_LOGD_LOC(TAG, "Getting host name from request");
  127. char *req_host = alloc_get_http_header(req, "Host");
  128. if(tcpip_adapter_is_netif_up(TCPIP_ADAPTER_IF_AP)){
  129. ESP_LOGD_LOC(TAG, "Soft AP is enabled. getting ip info");
  130. // Access point is up and running. Get the current IP address
  131. tcpip_adapter_ip_info_t ip_info;
  132. esp_err_t ap_ip_err = tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_AP, &ip_info);
  133. if(ap_ip_err != ESP_OK){
  134. ESP_LOGE_LOC(TAG, "Unable to get local AP ip address. Error: %s",esp_err_to_name(ap_ip_err));
  135. }
  136. else {
  137. ESP_LOGD_LOC(TAG, "getting host name for TCPIP_ADAPTER_IF_AP");
  138. if((hn_err = tcpip_adapter_get_hostname(TCPIP_ADAPTER_IF_AP, &ap_host_name )) !=ESP_OK) {
  139. ESP_LOGE_LOC(TAG, "Unable to get host name. Error: %s",esp_err_to_name(hn_err));
  140. err=err==ESP_OK?hn_err:err;
  141. }
  142. else {
  143. ESP_LOGD_LOC(TAG, "Soft AP Host name is %s",ap_host_name);
  144. }
  145. ap_ip_address = malloc_init_external(IP4ADDR_STRLEN_MAX);
  146. memset(ap_ip_address, 0x00, IP4ADDR_STRLEN_MAX);
  147. if(ap_ip_address){
  148. ESP_LOGD_LOC(TAG, "Converting soft ip address to string");
  149. ip4addr_ntoa_r(&ip_info.ip, ap_ip_address, IP4ADDR_STRLEN_MAX);
  150. ESP_LOGD_LOC(TAG,"TCPIP_ADAPTER_IF_AP is up and has ip address %s ", ap_ip_address);
  151. }
  152. }
  153. }
  154. if((request_contains_hostname = (host_name!=NULL) && (req_host!=NULL) && strcasestr(req_host,host_name)) == true){
  155. ESP_LOGD_LOC(TAG,"http request host = system host name %s", req_host);
  156. }
  157. else if((request_contains_hostname = (ap_host_name!=NULL) && (req_host!=NULL) && strcasestr(req_host,ap_host_name)) == true){
  158. ESP_LOGD_LOC(TAG,"http request host = AP system host name %s", req_host);
  159. }
  160. FREE_AND_NULL(ap_ip_address);
  161. FREE_AND_NULL(req_host);
  162. return request_contains_hostname;
  163. }
  164. /* Custom function to free context */
  165. void free_ctx_func(void *ctx)
  166. {
  167. session_context_t * context = (session_context_t *)ctx;
  168. if(context){
  169. ESP_LOGD(TAG, "Freeing up socket context");
  170. FREE_AND_NULL(context->auth_token);
  171. FREE_AND_NULL(context->sess_ip_address);
  172. free(context);
  173. }
  174. }
  175. session_context_t* get_session_context(httpd_req_t *req){
  176. bool newConnection=false;
  177. if (! req->sess_ctx) {
  178. ESP_LOGD(TAG,"New connection context. Allocating session buffer");
  179. req->sess_ctx = malloc_init_external(sizeof(session_context_t));
  180. req->free_ctx = free_ctx_func;
  181. newConnection = true;
  182. // get the remote IP address only once per session
  183. }
  184. session_context_t *ctx_data = (session_context_t*)req->sess_ctx;
  185. FREE_AND_NULL(ctx_data->sess_ip_address);
  186. ctx_data->sess_ip_address = http_alloc_get_socket_address(req, 0, &ctx_data->port);
  187. if(newConnection){
  188. ESP_LOGI(TAG, "serving %s to peer %s port %u", req->uri, ctx_data->sess_ip_address , ctx_data->port);
  189. }
  190. return (session_context_t *)req->sess_ctx;
  191. }
  192. bool is_user_authenticated(httpd_req_t *req){
  193. session_context_t *ctx_data = get_session_context(req);
  194. if(ctx_data->authenticated){
  195. ESP_LOGD_LOC(TAG,"User is authenticated.");
  196. return true;
  197. }
  198. ESP_LOGD(TAG, "Heap internal:%zu (min:%zu) external:%zu (min:%zu) dma:%zu (min:%zu)",
  199. heap_caps_get_free_size(MALLOC_CAP_INTERNAL),
  200. heap_caps_get_minimum_free_size(MALLOC_CAP_INTERNAL),
  201. heap_caps_get_free_size(MALLOC_CAP_SPIRAM),
  202. heap_caps_get_minimum_free_size(MALLOC_CAP_SPIRAM),
  203. heap_caps_get_free_size(MALLOC_CAP_DMA),
  204. heap_caps_get_minimum_free_size(MALLOC_CAP_DMA));
  205. // todo: ask for user to authenticate
  206. return false;
  207. }
  208. /* Copies the full path into destination buffer and returns
  209. * pointer to requested file name */
  210. static const char* get_path_from_uri(char *dest, const char *uri, size_t destsize)
  211. {
  212. size_t pathlen = strlen(uri);
  213. memset(dest,0x0,destsize);
  214. const char *quest = strchr(uri, '?');
  215. if (quest) {
  216. pathlen = MIN(pathlen, quest - uri);
  217. }
  218. const char *hash = strchr(uri, '#');
  219. if (hash) {
  220. pathlen = MIN(pathlen, hash - uri);
  221. }
  222. if ( pathlen + 1 > destsize) {
  223. /* Full path string won't fit into destination buffer */
  224. return NULL;
  225. }
  226. strlcpy(dest , uri, pathlen + 1);
  227. // strip trailing blanks
  228. char * sr = dest+pathlen;
  229. while(*sr== ' ') *sr-- = '\0';
  230. char * last_fs = strchr(dest,'/');
  231. if(!last_fs) ESP_LOGD_LOC(TAG,"no / found in %s", dest);
  232. char * p=last_fs;
  233. while(p && *(++p)!='\0'){
  234. if(*p == '/') {
  235. last_fs=p;
  236. }
  237. }
  238. /* Return pointer to path, skipping the base */
  239. return last_fs? ++last_fs: dest;
  240. }
  241. #define IS_FILE_EXT(filename, ext) \
  242. (strcasecmp(&filename[strlen(filename) - sizeof(ext) + 1], ext) == 0)
  243. /* Set HTTP response content type according to file extension */
  244. static esp_err_t set_content_type_from_file(httpd_req_t *req, const char *filename)
  245. {
  246. if(strlen(filename) ==0){
  247. // for root page, etc.
  248. return httpd_resp_set_type(req, HTTPD_TYPE_TEXT);
  249. } else if (IS_FILE_EXT(filename, ".pdf")) {
  250. return httpd_resp_set_type(req, "application/pdf");
  251. } else if (IS_FILE_EXT(filename, ".html")) {
  252. return httpd_resp_set_type(req, HTTPD_TYPE_TEXT);
  253. } else if (IS_FILE_EXT(filename, ".jpeg")) {
  254. return httpd_resp_set_type(req, "image/jpeg");
  255. } else if (IS_FILE_EXT(filename, ".png")) {
  256. return httpd_resp_set_type(req, "image/png");
  257. } else if (IS_FILE_EXT(filename, ".ico")) {
  258. return httpd_resp_set_type(req, "image/x-icon");
  259. } else if (IS_FILE_EXT(filename, ".css")) {
  260. return httpd_resp_set_type(req, "text/css");
  261. } else if (IS_FILE_EXT(filename, ".js")) {
  262. return httpd_resp_set_type(req, "text/javascript");
  263. } else if (IS_FILE_EXT(filename, ".json")) {
  264. return httpd_resp_set_type(req, HTTPD_TYPE_JSON);
  265. } else if (IS_FILE_EXT(filename, ".map")) {
  266. return httpd_resp_set_type(req, "map");
  267. }
  268. /* This is a limited set only */
  269. /* For any other type always set as plain text */
  270. return httpd_resp_set_type(req, "text/plain");
  271. }
  272. static esp_err_t set_content_type_from_req(httpd_req_t *req)
  273. {
  274. char filepath[FILE_PATH_MAX];
  275. const char *filename = get_path_from_uri(filepath, req->uri, sizeof(filepath));
  276. if (!filename) {
  277. ESP_LOGE_LOC(TAG, "Filename is too long");
  278. /* Respond with 500 Internal Server Error */
  279. httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Filename too long");
  280. return ESP_FAIL;
  281. }
  282. /* If name has trailing '/', respond with directory contents */
  283. if (filename[strlen(filename) - 1] == '/' && strlen(filename)>1) {
  284. httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Browsing files forbidden.");
  285. return ESP_FAIL;
  286. }
  287. set_content_type_from_file(req, filename);
  288. return ESP_OK;
  289. }
  290. int resource_get_index(const char * fileName){
  291. for(int i=0;resource_lookups[i][0]!='\0';i++){
  292. if(strstr(resource_lookups[i], fileName)){
  293. return i;
  294. }
  295. }
  296. return -1;
  297. }
  298. esp_err_t root_get_handler(httpd_req_t *req){
  299. esp_err_t err = ESP_OK;
  300. ESP_LOGD_LOC(TAG, "serving [%s]", req->uri);
  301. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  302. httpd_resp_set_hdr(req, "Accept-Encoding", "identity");
  303. if(!is_user_authenticated(req)){
  304. // todo: send password entry page and return
  305. }
  306. int idx=-1;
  307. if((idx=resource_get_index("index.html"))>=0){
  308. const size_t file_size = (resource_map_end[idx] - resource_map_start[idx]);
  309. httpd_resp_set_hdr(req, "Content-Encoding", "gzip");
  310. err = set_content_type_from_req(req);
  311. if(err == ESP_OK){
  312. httpd_resp_send(req, (const char *)resource_map_start[idx], file_size);
  313. }
  314. }
  315. else{
  316. httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "index.html not found");
  317. return ESP_FAIL;
  318. }
  319. ESP_LOGD_LOC(TAG, "done serving [%s]", req->uri);
  320. return err;
  321. }
  322. esp_err_t resource_filehandler(httpd_req_t *req){
  323. char filepath[FILE_PATH_MAX];
  324. ESP_LOGD_LOC(TAG, "serving [%s]", req->uri);
  325. const char *filename = get_path_from_uri(filepath, req->uri, sizeof(filepath));
  326. if (!filename) {
  327. ESP_LOGE_LOC(TAG, "Filename is too long");
  328. /* Respond with 500 Internal Server Error */
  329. httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Filename too long");
  330. return ESP_FAIL;
  331. }
  332. /* If name has trailing '/', respond with directory contents */
  333. if (filename[strlen(filename) - 1] == '/') {
  334. httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Browsing files forbidden.");
  335. return ESP_FAIL;
  336. }
  337. if(strlen(filename) !=0 && IS_FILE_EXT(filename, ".map")){
  338. return httpd_resp_sendstr(req, "");
  339. }
  340. int idx=-1;
  341. if((idx=resource_get_index(filename))>=0){
  342. set_content_type_from_file(req, filename);
  343. if(strstr(resource_lookups[idx], ".gz")) {
  344. httpd_resp_set_hdr(req, "Content-Encoding", "gzip");
  345. }
  346. const size_t file_size = (resource_map_end[idx] - resource_map_start[idx]);
  347. httpd_resp_send(req, (const char *)resource_map_start[idx], file_size);
  348. }
  349. else {
  350. ESP_LOGE_LOC(TAG, "Unknown resource [%s] from path [%s] ", filename,filepath);
  351. /* Respond with 404 Not Found */
  352. httpd_resp_send_err(req, HTTPD_404_NOT_FOUND, "File does not exist");
  353. return ESP_FAIL;
  354. }
  355. ESP_LOGD_LOC(TAG, "Resource sending complete");
  356. return ESP_OK;
  357. }
  358. esp_err_t ap_scan_handler(httpd_req_t *req){
  359. const char empty[] = "{}";
  360. ESP_LOGD_LOC(TAG, "serving [%s]", req->uri);
  361. if(!is_user_authenticated(req)){
  362. // todo: redirect to login page
  363. // return ESP_OK;
  364. }
  365. network_async_scan();
  366. esp_err_t err = set_content_type_from_req(req);
  367. if(err == ESP_OK){
  368. httpd_resp_send(req, (const char *)empty, HTTPD_RESP_USE_STRLEN);
  369. }
  370. return err;
  371. }
  372. esp_err_t console_cmd_get_handler(httpd_req_t *req){
  373. ESP_LOGD_LOC(TAG, "serving [%s]", req->uri);
  374. if(!is_user_authenticated(req)){
  375. // todo: redirect to login page
  376. // return ESP_OK;
  377. }
  378. /* if we can get the mutex, write the last version of the AP list */
  379. esp_err_t err = set_content_type_from_req(req);
  380. cJSON * cmdlist = get_cmd_list();
  381. char * json_buffer = cJSON_Print(cmdlist);
  382. if(json_buffer){
  383. httpd_resp_send(req, (const char *)json_buffer, HTTPD_RESP_USE_STRLEN);
  384. free(json_buffer);
  385. }
  386. else{
  387. ESP_LOGD_LOC(TAG, "Error retrieving command json string. ");
  388. httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Unable to format command");
  389. }
  390. cJSON_Delete(cmdlist);
  391. ESP_LOGD_LOC(TAG, "done serving [%s]", req->uri);
  392. return err;
  393. }
  394. esp_err_t console_cmd_post_handler(httpd_req_t *req){
  395. char success[]="{\"Result\" : \"Success\" }";
  396. ESP_LOGD_LOC(TAG, "serving [%s]", req->uri);
  397. //bool bOTA=false;
  398. //char * otaURL=NULL;
  399. esp_err_t err = post_handler_buff_receive(req);
  400. if(err!=ESP_OK){
  401. return err;
  402. }
  403. if(!is_user_authenticated(req)){
  404. // todo: redirect to login page
  405. // return ESP_OK;
  406. }
  407. err = set_content_type_from_req(req);
  408. if(err != ESP_OK){
  409. return err;
  410. }
  411. char *command= ((rest_server_context_t *)(req->user_ctx))->scratch;
  412. cJSON *root = cJSON_Parse(command);
  413. if(root == NULL){
  414. ESP_LOGE_LOC(TAG, "Parsing command. Received content was: %s",command);
  415. httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Malformed command json. Unable to parse content.");
  416. return ESP_FAIL;
  417. }
  418. char * root_str = cJSON_Print(root);
  419. if(root_str!=NULL){
  420. ESP_LOGD(TAG, "Processing command item: \n%s", root_str);
  421. free(root_str);
  422. }
  423. cJSON *item=cJSON_GetObjectItemCaseSensitive(root, "command");
  424. if(!item){
  425. ESP_LOGE_LOC(TAG, "Command not found. Received content was: %s",command);
  426. httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Malformed command json. Unable to parse content.");
  427. err = ESP_FAIL;
  428. }
  429. else{
  430. // navigate to the first child of the config structure
  431. char *cmd = cJSON_GetStringValue(item);
  432. if(!console_push(cmd, strlen(cmd) + 1)){
  433. httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Unable to push command for execution");
  434. }
  435. else {
  436. httpd_resp_send(req, (const char *)success, strlen(success));
  437. }
  438. }
  439. ESP_LOGD_LOC(TAG, "done serving [%s]", req->uri);
  440. return err;
  441. }
  442. esp_err_t ap_get_handler(httpd_req_t *req){
  443. ESP_LOGD_LOC(TAG, "serving [%s]", req->uri);
  444. if(!is_user_authenticated(req)){
  445. // todo: redirect to login page
  446. // return ESP_OK;
  447. }
  448. /* if we can get the mutex, write the last version of the AP list */
  449. esp_err_t err = set_content_type_from_req(req);
  450. if( err == ESP_OK && network_status_lock_json_buffer(( TickType_t ) 200/portTICK_PERIOD_MS)){
  451. char *buff = network_status_alloc_get_ap_list_json();
  452. network_status_unlock_json_buffer();
  453. if(buff!=NULL){
  454. httpd_resp_send(req, (const char *)buff, HTTPD_RESP_USE_STRLEN);
  455. free(buff);
  456. }
  457. else {
  458. ESP_LOGD_LOC(TAG, "Error retrieving ap list json string. ");
  459. httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Unable to retrieve AP list");
  460. }
  461. }
  462. else {
  463. httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "AP list unavailable");
  464. ESP_LOGE_LOC(TAG, "GET /ap.json failed to obtain mutex");
  465. }
  466. ESP_LOGD_LOC(TAG, "done serving [%s]", req->uri);
  467. return err;
  468. }
  469. esp_err_t config_get_handler(httpd_req_t *req){
  470. ESP_LOGD_LOC(TAG, "serving [%s]", req->uri);
  471. if(!is_user_authenticated(req)){
  472. // todo: redirect to login page
  473. // return ESP_OK;
  474. }
  475. esp_err_t err = set_content_type_from_req(req);
  476. if(err == ESP_OK){
  477. char * json = config_alloc_get_json(false);
  478. if(json==NULL){
  479. ESP_LOGD_LOC(TAG, "Error retrieving config json string. ");
  480. httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Error retrieving configuration object");
  481. err=ESP_FAIL;
  482. }
  483. else {
  484. ESP_LOGD_LOC(TAG, "config json : %s",json );
  485. cJSON * gplist=get_gpio_list(false);
  486. char * gpliststr=cJSON_PrintUnformatted(gplist);
  487. httpd_resp_sendstr_chunk(req,"{ \"gpio\":");
  488. httpd_resp_sendstr_chunk(req,gpliststr);
  489. httpd_resp_sendstr_chunk(req,", \"config\":");
  490. httpd_resp_sendstr_chunk(req, (const char *)json);
  491. httpd_resp_sendstr_chunk(req,"}");
  492. httpd_resp_sendstr_chunk(req,NULL);
  493. free(gpliststr);
  494. free(json);
  495. }
  496. }
  497. return err;
  498. }
  499. esp_err_t post_handler_buff_receive(httpd_req_t * req){
  500. esp_err_t err = ESP_OK;
  501. int total_len = req->content_len;
  502. int cur_len = 0;
  503. char *buf = ((rest_server_context_t *)(req->user_ctx))->scratch;
  504. int received = 0;
  505. if (total_len >= SCRATCH_BUFSIZE) {
  506. /* Respond with 500 Internal Server Error */
  507. ESP_LOGE_LOC(TAG,"Received content was too long. ");
  508. httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR , "Content too long");
  509. err = ESP_FAIL;
  510. }
  511. while (err == ESP_OK && cur_len < total_len) {
  512. received = httpd_req_recv(req, buf + cur_len, total_len);
  513. if (received <= 0) {
  514. /* Respond with 500 Internal Server Error */
  515. ESP_LOGE_LOC(TAG,"Not all data was received. ");
  516. httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR , "Not all data was received");
  517. err = ESP_FAIL;
  518. }
  519. else {
  520. cur_len += received;
  521. }
  522. }
  523. if(err == ESP_OK) {
  524. buf[total_len] = '\0';
  525. }
  526. return err;
  527. }
  528. esp_err_t config_post_handler(httpd_req_t *req){
  529. ESP_LOGD_LOC(TAG, "serving [%s]", req->uri);
  530. bool bOTA=false;
  531. char * otaURL=NULL;
  532. esp_err_t err = post_handler_buff_receive(req);
  533. if(err!=ESP_OK){
  534. return err;
  535. }
  536. if(!is_user_authenticated(req)){
  537. // todo: redirect to login page
  538. // return ESP_OK;
  539. }
  540. err = set_content_type_from_req(req);
  541. if(err != ESP_OK){
  542. return err;
  543. }
  544. char *buf = ((rest_server_context_t *)(req->user_ctx))->scratch;
  545. cJSON *root = cJSON_Parse(buf);
  546. if(root == NULL){
  547. ESP_LOGE_LOC(TAG, "Parsing config json failed. Received content was: %s",buf);
  548. httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Malformed config json. Unable to parse content.");
  549. return ESP_FAIL;
  550. }
  551. char * root_str = cJSON_Print(root);
  552. if(root_str!=NULL){
  553. ESP_LOGD(TAG, "Processing config item: \n%s", root_str);
  554. free(root_str);
  555. }
  556. cJSON *item=cJSON_GetObjectItemCaseSensitive(root, "config");
  557. if(!item){
  558. ESP_LOGE_LOC(TAG, "Parsing config json failed. Received content was: %s",buf);
  559. httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Malformed config json. Unable to parse content.");
  560. err = ESP_FAIL;
  561. }
  562. else{
  563. // navigate to the first child of the config structure
  564. if(item->child) item=item->child;
  565. }
  566. while (item && err == ESP_OK)
  567. {
  568. cJSON *prev_item = item;
  569. item=item->next;
  570. char * entry_str = cJSON_Print(prev_item);
  571. if(entry_str!=NULL){
  572. ESP_LOGD_LOC(TAG, "Processing config item: \n%s", entry_str);
  573. free(entry_str);
  574. }
  575. if(prev_item->string==NULL) {
  576. ESP_LOGD_LOC(TAG,"Config value does not have a name");
  577. httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Malformed config json. Value does not have a name.");
  578. err = ESP_FAIL;
  579. }
  580. if(err == ESP_OK){
  581. ESP_LOGD_LOC(TAG,"Found config value name [%s]", prev_item->string);
  582. nvs_type_t item_type= config_get_item_type(prev_item);
  583. if(item_type!=0){
  584. void * val = config_safe_alloc_get_entry_value(item_type, prev_item);
  585. if(val!=NULL){
  586. if(strcmp(prev_item->string, "fwurl")==0) {
  587. if(item_type!=NVS_TYPE_STR){
  588. ESP_LOGE_LOC(TAG,"Firmware url should be type %d. Found type %d instead.",NVS_TYPE_STR,item_type );
  589. httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Malformed config json. Wrong type for firmware URL.");
  590. err = ESP_FAIL;
  591. }
  592. else {
  593. // we're getting a request to do an OTA from that URL
  594. ESP_LOGW_LOC(TAG, "Found OTA request!");
  595. otaURL=strdup_psram(val);
  596. bOTA=true;
  597. }
  598. }
  599. else {
  600. if(config_set_value(item_type, prev_item->string , val) != ESP_OK){
  601. ESP_LOGE_LOC(TAG,"Unable to store value for [%s]", prev_item->string);
  602. httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR , "Unable to store config value");
  603. err = ESP_FAIL;
  604. }
  605. else {
  606. ESP_LOGD_LOC(TAG,"Successfully set value for [%s]",prev_item->string);
  607. }
  608. }
  609. free(val);
  610. }
  611. else {
  612. char messageBuffer[101]={};
  613. ESP_LOGE_LOC(TAG,"Value not found for [%s]", prev_item->string);
  614. snprintf(messageBuffer,sizeof(messageBuffer),"Malformed config json. Missing value for entry %s.",prev_item->string);
  615. httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, messageBuffer);
  616. err = ESP_FAIL;
  617. }
  618. }
  619. else {
  620. ESP_LOGE_LOC(TAG,"Unable to determine the type of config value [%s]", prev_item->string);
  621. httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Malformed config json. Missing value for entry.");
  622. err = ESP_FAIL;
  623. }
  624. }
  625. }
  626. if(err==ESP_OK){
  627. httpd_resp_sendstr(req, "{ \"result\" : \"OK\" }");
  628. messaging_post_message(MESSAGING_INFO,MESSAGING_CLASS_SYSTEM,"Save Success");
  629. }
  630. cJSON_Delete(root);
  631. if(bOTA) {
  632. if(is_recovery_running){
  633. ESP_LOGW_LOC(TAG, "Starting process OTA for url %s",otaURL);
  634. }
  635. else {
  636. ESP_LOGW_LOC(TAG, "Restarting system to process OTA for url %s",otaURL);
  637. }
  638. network_reboot_ota(otaURL);
  639. free(otaURL);
  640. }
  641. return err;
  642. }
  643. esp_err_t connect_post_handler(httpd_req_t *req){
  644. ESP_LOGD_LOC(TAG, "serving [%s]", req->uri);
  645. char success[]="{}";
  646. char * ssid=NULL;
  647. char * password=NULL;
  648. char * host_name=NULL;
  649. esp_err_t err = post_handler_buff_receive(req);
  650. if(err!=ESP_OK){
  651. return err;
  652. }
  653. err = set_content_type_from_req(req);
  654. if(err != ESP_OK){
  655. return err;
  656. }
  657. char *buf = ((rest_server_context_t *)(req->user_ctx))->scratch;
  658. if(!is_user_authenticated(req)){
  659. // todo: redirect to login page
  660. // return ESP_OK;
  661. }
  662. cJSON *root = cJSON_Parse(buf);
  663. if(root==NULL){
  664. httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR , "JSON parsing error.");
  665. return ESP_FAIL;
  666. }
  667. cJSON * ssid_object = cJSON_GetObjectItem(root, "ssid");
  668. if(ssid_object !=NULL){
  669. ssid = strdup_psram(ssid_object->valuestring);
  670. }
  671. cJSON * password_object = cJSON_GetObjectItem(root, "pwd");
  672. if(password_object !=NULL){
  673. password = strdup_psram(password_object->valuestring);
  674. }
  675. cJSON * host_name_object = cJSON_GetObjectItem(root, "host_name");
  676. if(host_name_object !=NULL){
  677. host_name = strdup_psram(host_name_object->valuestring);
  678. }
  679. cJSON_Delete(root);
  680. if(host_name!=NULL){
  681. if(config_set_value(NVS_TYPE_STR, "host_name", host_name) != ESP_OK){
  682. ESP_LOGW_LOC(TAG, "Unable to save host name configuration");
  683. }
  684. }
  685. if(ssid !=NULL && strlen(ssid) <= MAX_SSID_SIZE && strlen(password) <= MAX_PASSWORD_SIZE ){
  686. network_async_connect(ssid, password);
  687. httpd_resp_send(req, (const char *)success, strlen(success));
  688. }
  689. else {
  690. httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Malformed json. Missing or invalid ssid/password.");
  691. err = ESP_FAIL;
  692. }
  693. FREE_AND_NULL(ssid);
  694. FREE_AND_NULL(password);
  695. FREE_AND_NULL(host_name);
  696. return err;
  697. }
  698. esp_err_t connect_delete_handler(httpd_req_t *req){
  699. char success[]="{}";
  700. ESP_LOGD_LOC(TAG, "serving [%s]", req->uri);
  701. if(!is_user_authenticated(req)){
  702. // todo: redirect to login page
  703. // return ESP_OK;
  704. }
  705. esp_err_t err = set_content_type_from_req(req);
  706. if(err != ESP_OK){
  707. return err;
  708. }
  709. httpd_resp_send(req, (const char *)success, strlen(success));
  710. network_async_delete();
  711. return ESP_OK;
  712. }
  713. esp_err_t reboot_ota_post_handler(httpd_req_t *req){
  714. char success[]="{}";
  715. ESP_LOGD_LOC(TAG, "serving [%s]", req->uri);
  716. if(!is_user_authenticated(req)){
  717. // todo: redirect to login page
  718. // return ESP_OK;
  719. }
  720. esp_err_t err = set_content_type_from_req(req);
  721. if(err != ESP_OK){
  722. return err;
  723. }
  724. httpd_resp_send(req, (const char *)success, strlen(success));
  725. network_async_reboot(OTA);
  726. return ESP_OK;
  727. }
  728. esp_err_t reboot_post_handler(httpd_req_t *req){
  729. ESP_LOGD_LOC(TAG, "serving [%s]", req->uri);
  730. char success[]="{}";
  731. if(!is_user_authenticated(req)){
  732. // todo: redirect to login page
  733. // return ESP_OK;
  734. }
  735. esp_err_t err = set_content_type_from_req(req);
  736. if(err != ESP_OK){
  737. return err;
  738. }
  739. httpd_resp_send(req, (const char *)success, strlen(success));
  740. network_async_reboot(RESTART);
  741. return ESP_OK;
  742. }
  743. esp_err_t recovery_post_handler(httpd_req_t *req){
  744. ESP_LOGD_LOC(TAG, "serving [%s]", req->uri);
  745. char success[]="{}";
  746. if(!is_user_authenticated(req)){
  747. // todo: redirect to login page
  748. // return ESP_OK;
  749. }
  750. esp_err_t err = set_content_type_from_req(req);
  751. if(err != ESP_OK){
  752. return err;
  753. }
  754. httpd_resp_send(req, (const char *)success, strlen(success));
  755. network_async_reboot(RECOVERY);
  756. return ESP_OK;
  757. }
  758. esp_err_t flash_post_handler(httpd_req_t *req){
  759. esp_err_t err =ESP_OK;
  760. if(is_recovery_running){
  761. ESP_LOGD_LOC(TAG, "serving [%s]", req->uri);
  762. char success[]="File uploaded. Flashing started.";
  763. if(!is_user_authenticated(req)){
  764. // todo: redirect to login page
  765. // return ESP_OK;
  766. }
  767. err = httpd_resp_set_type(req, HTTPD_TYPE_TEXT);
  768. if(err != ESP_OK){
  769. return err;
  770. }
  771. char * binary_buffer = malloc_init_external(req->content_len);
  772. if(binary_buffer == NULL){
  773. ESP_LOGE(TAG, "File too large : %d bytes", req->content_len);
  774. /* Respond with 400 Bad Request */
  775. httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST,
  776. "Binary file too large. Unable to allocate memory!");
  777. return ESP_FAIL;
  778. }
  779. ESP_LOGI(TAG, "Receiving ota binary file");
  780. /* Retrieve the pointer to scratch buffer for temporary storage */
  781. char *buf = ((rest_server_context_t *)(req->user_ctx))->scratch;
  782. char *head=binary_buffer;
  783. int received;
  784. /* Content length of the request gives
  785. * the size of the file being uploaded */
  786. int remaining = req->content_len;
  787. while (remaining > 0) {
  788. ESP_LOGI(TAG, "Remaining size : %d", remaining);
  789. /* Receive the file part by part into a buffer */
  790. if ((received = httpd_req_recv(req, buf, MIN(remaining, SCRATCH_BUFSIZE))) <= 0) {
  791. if (received == HTTPD_SOCK_ERR_TIMEOUT) {
  792. /* Retry if timeout occurred */
  793. continue;
  794. }
  795. FREE_RESET(binary_buffer);
  796. ESP_LOGE(TAG, "File reception failed!");
  797. /* Respond with 500 Internal Server Error */
  798. httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Failed to receive file");
  799. err = ESP_FAIL;
  800. goto bail_out;
  801. }
  802. /* Write buffer content to file on storage */
  803. if (received ) {
  804. memcpy(head,buf,received );
  805. head+=received;
  806. }
  807. /* Keep track of remaining size of
  808. * the file left to be uploaded */
  809. remaining -= received;
  810. }
  811. /* Close file upon upload completion */
  812. ESP_LOGI(TAG, "File reception complete. Invoking OTA process.");
  813. err = start_ota(NULL, binary_buffer, req->content_len);
  814. if(err!=ESP_OK){
  815. httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "OTA processing failed");
  816. goto bail_out;
  817. }
  818. //todo: handle this in ajax. For now, just send the root page
  819. httpd_resp_send(req, (const char *)success, strlen(success));
  820. }
  821. bail_out:
  822. return err;
  823. }
  824. char * get_ap_ip_address(){
  825. static char ap_ip_address[IP4ADDR_STRLEN_MAX]={};
  826. tcpip_adapter_ip_info_t ip_info;
  827. esp_err_t err=ESP_OK;
  828. memset(ap_ip_address, 0x00, sizeof(ap_ip_address));
  829. ESP_LOGD_LOC(TAG, "checking if soft AP is enabled");
  830. if(tcpip_adapter_is_netif_up(TCPIP_ADAPTER_IF_AP)){
  831. ESP_LOGD_LOC(TAG, "Soft AP is enabled. getting ip info");
  832. // Access point is up and running. Get the current IP address
  833. err = tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_AP, &ip_info);
  834. if(err != ESP_OK){
  835. ESP_LOGE_LOC(TAG, "Unable to get local AP ip address. Error: %s",esp_err_to_name(err));
  836. }
  837. else {
  838. ESP_LOGV_LOC(TAG, "Converting soft ip address to string");
  839. ip4addr_ntoa_r(&ip_info.ip, ap_ip_address, IP4ADDR_STRLEN_MAX);
  840. ESP_LOGD_LOC(TAG,"TCPIP_ADAPTER_IF_AP is up and has ip address %s ", ap_ip_address);
  841. }
  842. }
  843. else{
  844. ESP_LOGD_LOC(TAG,"AP Is not enabled. Returning blank string");
  845. }
  846. return ap_ip_address;
  847. }
  848. esp_err_t process_redirect(httpd_req_t *req, const char * status){
  849. const char location_prefix[] = "http://";
  850. char * ap_ip_address=get_ap_ip_address();
  851. char * remote_ip=NULL;
  852. in_port_t port=0;
  853. char *redirect_url = NULL;
  854. ESP_LOGD_LOC(TAG, "Getting remote socket address");
  855. remote_ip = http_alloc_get_socket_address(req,0, &port);
  856. size_t buf_size = strlen(redirect_payload1) +strlen(redirect_payload2) + strlen(redirect_payload3) +2*(strlen(location_prefix)+strlen(ap_ip_address))+1;
  857. char * redirect=malloc_init_external(buf_size);
  858. if(strcasestr(status,"302")){
  859. size_t url_buf_size = strlen(location_prefix) + strlen(ap_ip_address)+1;
  860. redirect_url = malloc_init_external(url_buf_size);
  861. memset(redirect_url,0x00,url_buf_size);
  862. snprintf(redirect_url, buf_size,"%s%s/",location_prefix, ap_ip_address);
  863. ESP_LOGW_LOC(TAG, "Redirecting host [%s] to %s (from uri %s)",remote_ip, redirect_url,req->uri);
  864. httpd_resp_set_hdr(req,"Location",redirect_url);
  865. snprintf(redirect, buf_size,"OK");
  866. }
  867. else {
  868. snprintf(redirect, buf_size,"%s%s%s%s%s%s%s",redirect_payload1, location_prefix, ap_ip_address,redirect_payload2, location_prefix, ap_ip_address,redirect_payload3);
  869. ESP_LOGW_LOC(TAG, "Responding to host [%s] (from uri %s) with redirect html page %s",remote_ip, req->uri,redirect);
  870. }
  871. httpd_resp_set_type(req, HTTPD_TYPE_TEXT);
  872. httpd_resp_set_hdr(req,"Cache-Control","no-cache");
  873. httpd_resp_set_status(req, status);
  874. httpd_resp_send(req, redirect, HTTPD_RESP_USE_STRLEN);
  875. FREE_AND_NULL(redirect);
  876. FREE_AND_NULL(redirect_url);
  877. FREE_AND_NULL(remote_ip);
  878. return ESP_OK;
  879. }
  880. esp_err_t redirect_200_ev_handler(httpd_req_t *req){
  881. ESP_LOGD_LOC(TAG,"Processing known redirect url %s",req->uri);
  882. process_redirect(req,"200 OK");
  883. return ESP_OK;
  884. }
  885. esp_err_t redirect_processor(httpd_req_t *req, httpd_err_code_t error){
  886. esp_err_t err=ESP_OK;
  887. const char * host_name=NULL;
  888. const char * ap_host_name=NULL;
  889. char * user_agent=NULL;
  890. char * remote_ip=NULL;
  891. char * sta_ip_address=NULL;
  892. char * ap_ip_address=get_ap_ip_address();
  893. char * socket_local_address=NULL;
  894. bool request_contains_hostname = false;
  895. bool request_contains_ap_ip_address = false;
  896. bool request_is_sta_ip_address = false;
  897. bool connected_to_ap_ip_interface = false;
  898. bool connected_to_sta_ip_interface = false;
  899. bool useragentiscaptivenetwork = false;
  900. in_port_t port=0;
  901. ESP_LOGV_LOC(TAG, "Getting remote socket address");
  902. remote_ip = http_alloc_get_socket_address(req,0, &port);
  903. ESP_LOGW_LOC(TAG, "%s requested invalid URL: [%s]",remote_ip, req->uri);
  904. if(network_status_lock_sta_ip_string(portMAX_DELAY)){
  905. sta_ip_address = strdup_psram(network_status_get_sta_ip_string());
  906. network_status_unlock_sta_ip_string();
  907. }
  908. else {
  909. ESP_LOGE(TAG,"Unable to obtain local IP address from WiFi Manager.");
  910. httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR , NULL);
  911. }
  912. ESP_LOGV_LOC(TAG, "Getting host name from request");
  913. char *req_host = alloc_get_http_header(req, "Host");
  914. user_agent = alloc_get_http_header(req,"User-Agent");
  915. if((useragentiscaptivenetwork = (user_agent!=NULL && strcasestr(user_agent,"CaptiveNetworkSupport"))==true)){
  916. ESP_LOGW_LOC(TAG,"Found user agent that supports captive networks! [%s]",user_agent);
  917. }
  918. esp_err_t hn_err = ESP_OK;
  919. ESP_LOGV_LOC(TAG, "Getting adapter host name");
  920. if((hn_err = tcpip_adapter_get_hostname(TCPIP_ADAPTER_IF_STA, &host_name )) !=ESP_OK) {
  921. ESP_LOGE_LOC(TAG, "Unable to get host name. Error: %s",esp_err_to_name(hn_err));
  922. err=err==ESP_OK?hn_err:err;
  923. }
  924. else {
  925. ESP_LOGV_LOC(TAG, "Host name is %s",host_name);
  926. }
  927. in_port_t loc_port=0;
  928. ESP_LOGV_LOC(TAG, "Getting local socket address");
  929. socket_local_address= http_alloc_get_socket_address(req,1, &loc_port);
  930. ESP_LOGD_LOC(TAG, "Peer IP: %s [port %u], System AP IP address: %s, System host: %s. Requested Host: [%s], uri [%s]",STR_OR_NA(remote_ip), port, STR_OR_NA(ap_ip_address), STR_OR_NA(host_name), STR_OR_NA(req_host), req->uri);
  931. /* captive portal functionality: redirect to access point IP for HOST that are not the access point IP OR the STA IP */
  932. /* determine if Host is from the STA IP address */
  933. if((request_contains_hostname = (host_name!=NULL) && (req_host!=NULL) && strcasestr(req_host,host_name)) == true){
  934. ESP_LOGD_LOC(TAG,"http request host = system host name %s", req_host);
  935. }
  936. else if((request_contains_hostname = (ap_host_name!=NULL) && (req_host!=NULL) && strcasestr(req_host,ap_host_name)) == true){
  937. ESP_LOGD_LOC(TAG,"http request host = AP system host name %s", req_host);
  938. }
  939. if((request_contains_ap_ip_address = (ap_ip_address!=NULL) && (req_host!=NULL) && strcasestr(req_host,ap_ip_address))== true){
  940. ESP_LOGD_LOC(TAG,"http request host is access point ip address %s", req_host);
  941. }
  942. if((connected_to_ap_ip_interface = (ap_ip_address!=NULL) && (socket_local_address!=NULL) && strcasestr(socket_local_address,ap_ip_address))==true){
  943. ESP_LOGD_LOC(TAG,"http request is connected to access point interface IP %s", ap_ip_address);
  944. }
  945. if((request_is_sta_ip_address = (sta_ip_address!=NULL) && (req_host!=NULL) && strcasestr(req_host,sta_ip_address))==true){
  946. ESP_LOGD_LOC(TAG,"http request host is WiFi client ip address %s", req_host);
  947. }
  948. if((connected_to_sta_ip_interface = (sta_ip_address!=NULL) && (socket_local_address!=NULL) && strcasestr(sta_ip_address,socket_local_address))==true){
  949. ESP_LOGD_LOC(TAG,"http request is connected to WiFi client ip address %s", sta_ip_address);
  950. }
  951. if((error == 0) || (error == HTTPD_404_NOT_FOUND && connected_to_ap_ip_interface && !(request_contains_ap_ip_address || request_contains_hostname ))) {
  952. process_redirect(req,"302 Found");
  953. }
  954. else {
  955. ESP_LOGD_LOC(TAG,"URL not found, and not processing captive portal so throw regular 404 error");
  956. httpd_resp_send_err(req, error, NULL);
  957. }
  958. FREE_AND_NULL(socket_local_address);
  959. FREE_AND_NULL(req_host);
  960. FREE_AND_NULL(user_agent);
  961. FREE_AND_NULL(sta_ip_address);
  962. FREE_AND_NULL(remote_ip);
  963. return err;
  964. }
  965. esp_err_t redirect_ev_handler(httpd_req_t *req){
  966. return redirect_processor(req,0);
  967. }
  968. esp_err_t messages_get_handler(httpd_req_t *req){
  969. ESP_LOGD_LOC(TAG, "serving [%s]", req->uri);
  970. if(!is_user_authenticated(req)){
  971. // todo: redirect to login page
  972. // return ESP_OK;
  973. }
  974. esp_err_t err = set_content_type_from_req(req);
  975. if(err != ESP_OK){
  976. return err;
  977. }
  978. cJSON * json_messages= messaging_retrieve_messages(messaging);
  979. if(json_messages!=NULL){
  980. char * json_text= cJSON_Print(json_messages);
  981. httpd_resp_send(req, (const char *)json_text, strlen(json_text));
  982. free(json_text);
  983. cJSON_Delete(json_messages);
  984. }
  985. else {
  986. httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR , "Unable to retrieve messages");
  987. }
  988. return ESP_OK;
  989. }
  990. esp_err_t status_get_handler(httpd_req_t *req){
  991. ESP_LOGD_LOC(TAG, "serving [%s]", req->uri);
  992. if(!is_user_authenticated(req)){
  993. // todo: redirect to login page
  994. // return ESP_OK;
  995. }
  996. esp_err_t err = set_content_type_from_req(req);
  997. if(err != ESP_OK){
  998. return err;
  999. }
  1000. if(network_status_lock_json_buffer(( TickType_t ) 200/portTICK_PERIOD_MS)) {
  1001. char *buff = network_status_alloc_get_ip_info_json();
  1002. network_status_unlock_json_buffer();
  1003. if(buff) {
  1004. httpd_resp_send(req, (const char *)buff, strlen(buff));
  1005. free(buff);
  1006. }
  1007. else {
  1008. httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR , "Empty status object");
  1009. }
  1010. }
  1011. else {
  1012. httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR , "Error retrieving status object");
  1013. }
  1014. // update status for next status call
  1015. network_async_update_status();
  1016. return ESP_OK;
  1017. }
  1018. esp_err_t err_handler(httpd_req_t *req, httpd_err_code_t error){
  1019. esp_err_t err = ESP_OK;
  1020. if(error != HTTPD_404_NOT_FOUND){
  1021. err = httpd_resp_send_err(req, error, NULL);
  1022. }
  1023. else {
  1024. err = redirect_processor(req,error);
  1025. }
  1026. return err;
  1027. }