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