diff --git a/WEBFiles/protect/scan.htm b/WEBFiles/protect/scan.htm index 4d30082..d2b2842 100644 --- a/WEBFiles/protect/scan.htm +++ b/WEBFiles/protect/scan.htm @@ -32,7 +32,7 @@

- +

diff --git a/WEBFiles/protect/wifi.htm b/WEBFiles/protect/wifi.htm index 45af0a4..b2b615e 100644 --- a/WEBFiles/protect/wifi.htm +++ b/WEBFiles/protect/wifi.htm @@ -57,16 +57,14 @@ @@ -179,7 +177,7 @@ var cfg = { wifi_phy:"~wifi_bgn~", wifi_mode:"~wifi_mode~", wifi_sleep:"~wifi_sleep~", - wifi_st_autn:"~wifi_st_auth~", + wifi_st_auth:"~wifi_st_auth~", wifi_st_sbss:"~wifi_st_sbss~", wifi_ap_hssid:"~wifi_ap_hssid~", wifi_ap_dhcp:"~wifi_ap_dhcp~", diff --git a/WEBFiles/time.inc b/WEBFiles/time.inc index dfef378..34a2b5a 100644 --- a/WEBFiles/time.inc +++ b/WEBFiles/time.inc @@ -4,6 +4,6 @@ if(x){ var d = new Date(x); document.getElementById('sntptime').innerHTML= d.toLocaleDateString()+" "+d.toLocaleTimeString(); } -var d = new Date(new Date()-(~sys_mactime~/1000)); +var d = new Date(new Date()-(~sys_time~)); document.getElementById('starttime').innerHTML= d.toLocaleDateString()+" "+d.toLocaleTimeString(); \ No newline at end of file diff --git a/WEBFiles/tst.xml b/WEBFiles/tst.xml index f817f5a..88a35c1 100644 --- a/WEBFiles/tst.xml +++ b/WEBFiles/tst.xml @@ -1 +1 @@ -Test~wifi_st_rssi~? +Test-1*~wifi_st_rssi~? diff --git a/flasher/file_info.jlink b/flasher/file_info.jlink index 2b24f94..103fba5 100644 --- a/flasher/file_info.jlink +++ b/flasher/file_info.jlink @@ -1,5 +1,5 @@ define call1 -set $ImageSize = 0xF1E0 +set $ImageSize = 0xF140 set $ImageAddr = 0x0D0000 end define call2 diff --git a/project/inc/tcpsrv/tcp_srv_conn.h b/project/inc/tcpsrv/tcp_srv_conn.h index 4468e0f..96e4997 100644 --- a/project/inc/tcpsrv/tcp_srv_conn.h +++ b/project/inc/tcpsrv/tcp_srv_conn.h @@ -25,7 +25,7 @@ enum srvconn_state { // приоритет pcb 1..127 1 - min, 127 - max #ifndef TCP_SRV_PRIO -#define TCP_SRV_PRIO 99 //TCP_PRIO_MIN +#define TCP_SRV_PRIO 99 // TCP_PRIO_MIN #endif // максимальное кол-во TCP c TIME_WAIT @@ -145,11 +145,11 @@ typedef err_t (*func_sent_callback)(TCP_SERV_CONN *ts_conn); // блок дан typedef struct t_TCP_SERV_CFG { struct t_tcpsrv_conn_flags flag; // начальные флаги для соединения uint16 port; // номер порта (=1 - client) - uint16 max_conn; // максимальное кол-во одновременных соединений, если client = кол-во повторов соединения - uint16 conn_count; // кол-во текущих соединений, при инициализации прописывает 0, если client = счетчик повторов соединения uint16 min_heap; // минимальный размер heap при открытии нового соединения, при = 0 заменяется на 8192. - uint16 time_wait_rec; // время (сек) ожидания запроса (передачи пакета) от клиента, до авто-закрытия соединения, по умолчанию TCP_SRV_RECV_WAIT сек. - uint16 time_wait_cls; // время (сек) до авто-закрытия соединения после приема или передачи, по умолчанию TCP_SRV_END_WAIT сек. + uint8 max_conn; // максимальное кол-во одновременных соединений, если client = кол-во повторов соединения + uint8 conn_count; // кол-во текущих соединений, при инициализации прописывает 0, если client = счетчик повторов соединения + uint8 time_wait_rec; // время (сек) ожидания запроса (передачи пакета) от клиента, до авто-закрытия соединения, по умолчанию TCP_SRV_RECV_WAIT сек. + uint8 time_wait_cls; // время (сек) до авто-закрытия соединения после приема или передачи, по умолчанию TCP_SRV_END_WAIT сек. TCP_SERV_CONN * conn_links; // указатель на цепочку активных соединений, при инициализации или отсуствии активных соединений = NULL struct tcp_pcb *pcb; // начальный pcb [LISTEN] если сервер, иначе NULL func_disconect_calback func_discon_cb; // функция вызываемая после закрытия соединения, если = NULL - не вызывается diff --git a/project/inc/user_config.h b/project/inc/user_config.h index d628f15..766174c 100644 --- a/project/inc/user_config.h +++ b/project/inc/user_config.h @@ -11,13 +11,13 @@ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #define USE_WEB 80 // включить в трансялцию порт Web, если =0 - по умолчанию выключен -#define WEBSOCKET_ENA 1 // включить WEBSOCKET +#define WEBSOCKET_ENA 1 // включить WEBSOCKET +#define USE_SNTP 1 // включить в трансялцию драйвер SNTP, если =0 - по умолчанию выключен, = 1 - по умолчанию включен. +#define USE_NETBIOS 1 // включить в трансялцию драйвер NETBIOS, если =0 - по умолчанию выключен. //#define USE_CPU_SPEED 166 // установить частоту CPU (по умолчанию 83) /* -#define USE_NETBIOS 1 // включить в трансялцию драйвер NETBIOS, если =0 - по умолчанию выключен. -#define USE_SNTP 1 // включить в трансялцию драйвер SNTP, если =0 - по умолчанию выключен, = 1 - по умолчанию включен. #define USE_RS485DRV // использовать RS-485 драйвер #define MDB_RS485_MASTER // Modbus RTU RS-485 master & slave diff --git a/project/inc/web/web_srv.h b/project/inc/web/web_srv.h index 0126cec..10c4c6c 100644 --- a/project/inc/web/web_srv.h +++ b/project/inc/web/web_srv.h @@ -15,12 +15,21 @@ #define WEB_SVERSION "0.2.0" #define DEFAULT_WEB_PORT USE_WEB // 80 +#define USE_WEB_AUTH_LEVEL 1 /**************************************************************************** - Section: - Commands and Server Responses ***************************************************************************/ +typedef enum +{ + WEB_AUTH_NONE = 0, + WEB_AUTH_LEVEL_USER, + WEB_AUTH_LEVEL_USER1, + WEB_AUTH_LEVEL_WEBFS, + WEB_AUTH_LEVEL_OTA, + WEB_AUTH_LEVEL_SUPERVISOR +} WEB_AUTH_LEVEL_TYPE; + // File type definitions typedef enum { @@ -90,6 +99,10 @@ typedef struct uint32 web_disc_par; // параметры функции вызываемой по закрытию соединения #ifdef WEBSOCKET_ENA WS_FRSTAT ws; // параметры websoc +#endif +#if USE_WEB_AUTH_LEVEL + uint8 auth_level; // Уровень авторизации по паролю + uint8 auth_realm; // Требуемый уровень авторизации (минимальный уровень) #endif uint8 fileType; // File type to return with Content-Type (if SCB_FCALBACK) } WEB_SRV_CONN; diff --git a/project/inc/web/web_srv_int.h b/project/inc/web/web_srv_int.h index 8606dc0..6681d79 100644 --- a/project/inc/web/web_srv_int.h +++ b/project/inc/web/web_srv_int.h @@ -13,12 +13,10 @@ #define WEB_NAME_VERSION "PVs/0.2" -// #define WEBSOCKET_ENA 1 - // lifetime (sec) of static responses as string 60*60*24*14=1209600" #define FILE_CACHE_MAX_AGE_SEC 3600 // время для кеша файлов, ставить 0 пока тест! -#define MAX_HTTP_HEAD_BUF 3070 // максимальный размер HTTP запроса (GET) +#define MAX_HTTP_HEAD_BUF TCP_SRV_SERVER_MAX_RXBUF // максимальный размер HTTP запроса (GET) #define RESCHKS_SEND_SIZE 16 #define RESCHKE_SEND_SIZE 8 @@ -45,5 +43,6 @@ bool web_inc_fclose(WEB_SRV_CONN *web_conn); bool web_trim_bufi(TCP_SERV_CONN *ts_conn, uint8 *pdata, uint32 data_len); bool web_feee_bufi(TCP_SERV_CONN *ts_conn); //uint8 * head_find_ctr(HTTP_CONN *CurHTTP, const uint8 * c, int clen, int dlen); +uint8 UserAuthorization(uint8 *pbuf, size_t declen); #endif /* _INCLUDE_WEB_SRV_INT_H_ */ diff --git a/project/inc/wifi_user_set.h b/project/inc/wifi_user_set.h index da9a4df..f04e08f 100644 --- a/project/inc/wifi_user_set.h +++ b/project/inc/wifi_user_set.h @@ -34,7 +34,7 @@ //==== Interface 0 - wlan0 = AP =========== #define DEF_AP_SSID "RTL871X" #define DEF_AP_PASSWORD "0123456789" -#define DEF_AP_SECURITY RTW_SECURITY_WPA2_AES_PSK // RTW_SECURITY_OPEN, RTW_SECURITY_WEP_PSK +#define DEF_AP_SECURITY RTW_SECURITY_WPA2_AES_PSK // or RTW_SECURITY_OPEN #define DEF_AP_BEACON 100 // 100...6000 ms #define DEF_AP_CHANNEL 1 // 1..14 #define DEF_AP_CHANNEL 1 // 1..14 diff --git a/project/src/console/wifi_console.c b/project/src/console/wifi_console.c index 0f522fa..58e4181 100644 --- a/project/src/console/wifi_console.c +++ b/project/src/console/wifi_console.c @@ -31,13 +31,14 @@ LOCAL void fATPN(int argc, char *argv[]){ } else { strncpy(wifi_st_cfg.ssid, argv[1], NDIS_802_11_LENGTH_SSID); + int pswlen; if(argc > 2) { + pswlen = strlen(wifi_st_cfg.password); strncpy(wifi_st_cfg.password, argv[2], NDIS_802_11_LENGTH_SSID); - int i = strlen(wifi_st_cfg.password); - if(i > 7) { + if(pswlen > 7) { wifi_st_cfg.security_type = RTW_SECURITY_WPA2_AES_PSK; } - else if(!i) { + else if(!pswlen) { wifi_st_cfg.security_type = RTW_SECURITY_OPEN; } else { @@ -46,18 +47,25 @@ LOCAL void fATPN(int argc, char *argv[]){ } } else { + // default wifi_st_cfg.password[0] = 0; wifi_st_cfg.security_type = RTW_SECURITY_OPEN; } if(argc > 3) { - wifi_ap_cfg.security_type = translate_rtw_security(atoi(argv[3])); + if(pswlen > 7) { + wifi_st_cfg.security_type = translate_val_to_rtw_security(atoi(argv[3])); + } + else { + printf("password len < 8!\n"); + wifi_st_cfg.security_type = RTW_SECURITY_OPEN; + } } if(argc > 4) { - wifi_st_cfg.autoreconnect = atoi(argv[3]); + wifi_st_cfg.autoreconnect = atoi(argv[4]); } else wifi_st_cfg.autoreconnect = 0; if(argc > 5) { - wifi_st_cfg.reconnect_pause = atoi(argv[3]); + wifi_st_cfg.reconnect_pause = atoi(argv[5]); } else wifi_st_cfg.reconnect_pause = 5; show_wifi_st_cfg(); @@ -93,8 +101,7 @@ LOCAL void fATPA(int argc, char *argv[]){ wifi_ap_cfg.security_type = RTW_SECURITY_OPEN; } if(argc > 3) { - if(argv[3][0]=='0') wifi_st_cfg.security_type = RTW_SECURITY_OPEN; - else wifi_st_cfg.security_type = RTW_SECURITY_WEP_PSK; + wifi_ap_cfg.security_type = (argv[3][0] == '0')? RTW_SECURITY_OPEN : RTW_SECURITY_WPA2_AES_PSK; } if(argc > 4) { wifi_ap_cfg.channel = atoi(argv[4]); diff --git a/project/src/user/user_start.c b/project/src/user/user_start.c index 06a0ef7..dec7972 100644 --- a/project/src/user/user_start.c +++ b/project/src/user/user_start.c @@ -11,12 +11,20 @@ #include "task.h" #include "diag.h" #include "netbios/netbios.h" +#include "sntp/sntp.h" #include "user/sys_cfg.h" #include "web/web_srv.h" #include "webfs/webfs.h" struct SystemCfg syscfg = { - .cfg.w = SYS_CFG_DEBUG_ENA | SYS_CFG_NETBIOS_ENA, + .cfg.w = SYS_CFG_DEBUG_ENA +#if defined(USE_NETBIOS) && USE_NETBIOS + | SYS_CFG_NETBIOS_ENA +#endif +#if defined(USE_SNTP) && USE_SNTP + | SYS_CFG_SNTP_ENA +#endif + , #if defined(USE_WEB) .web_port = USE_WEB, #else @@ -63,9 +71,12 @@ void user_init_thrd(void) { /* Load cfg, init WiFi + LwIP init, WiFi start if wifi_cfg.mode != RTW_MODE_NONE */ wifi_init(); - +#if defined(USE_NETBIOS) if(syscfg.cfg.b.netbios_ena) netbios_init(); - +#endif +#if defined(USE_SNTP) + if(syscfg.cfg.b.sntp_ena) sntp_init(); +#endif // webstuff_init(); // httpd_init(); webserver_init(syscfg.web_port); diff --git a/project/src/web/web_auth.c b/project/src/web/web_auth.c new file mode 100644 index 0000000..b5f233b --- /dev/null +++ b/project/src/web/web_auth.c @@ -0,0 +1,48 @@ +/* + * web_auth.c + * + * Created on: 23/04/2017. + * Author: pvvx + */ +#include "autoconf.h" +#include "FreeRTOS.h" +#include "diag.h" +#include "web_utils.h" +#include "wifi_api.h" +#include "web_srv.h" +#include "rtl8195a/rtl_libc.h" +#include "esp_comp.h" + + +/* ---------------------------------------------------------------------------------- + * pbuf[77] = Username and password are combined into a string "username:password" + * Return: Authorization Level + * 0 - Not Authorized */ + +uint8 UserAuthorization(uint8 *pbuf, size_t declen) +{ + uint8 * psw = rtl_strchr(pbuf, ':'); + if(psw != NULL) { +#if USE_WEB_AUTH_LEVEL + if(rtl_strcmp(pbuf, "rtl871x:webfs_write") == 0) { + return WEB_AUTH_LEVEL_WEBFS; + } + if(rtl_strcmp(pbuf, "rtl871x:ota_write") == 0) { + return WEB_AUTH_LEVEL_OTA; + } + if(rtl_strcmp(pbuf, "rtl871x:supervisor") == 0) { + return WEB_AUTH_LEVEL_SUPERVISOR; + } +#endif + *psw++ = 0; + if(rom_xstrcmp(wifi_ap_cfg.ssid, pbuf) + && rom_xstrcmp( wifi_ap_cfg.password, psw)) { + return WEB_AUTH_LEVEL_USER; + } + if(rom_xstrcmp(wifi_st_cfg.ssid, pbuf) + && rom_xstrcmp( wifi_st_cfg.password, psw)) { + return WEB_AUTH_LEVEL_USER1; + } + } + return 0; +} diff --git a/project/src/web/web_int_callbacks.c b/project/src/web/web_int_callbacks.c index aa26a07..5e78c07 100644 --- a/project/src/web/web_int_callbacks.c +++ b/project/src/web/web_int_callbacks.c @@ -24,11 +24,11 @@ #include "esp_comp.h" #ifdef USE_NETBIOS -#include "netbios.h" +#include "netbios/netbios.h" #endif #ifdef USE_SNTP -#include "sntp.h" +#include "sntp/sntp.h" #endif #ifdef USE_CAPTDNS @@ -534,13 +534,13 @@ void ICACHE_FLASH_ATTR web_int_callback(TCP_SERV_CONN *ts_conn, uint8 *cstr) else ifcmp("auth") tcp_put((wifi_ap_cfg.security_type == RTW_SECURITY_OPEN) ? '0' : '1'); else ifcmp("hssid") tcp_put((wifi_ap_cfg.ssid_hidden & 1) + '0'); else ifcmp("bint") tcp_puts("%u", wifi_ap_cfg.beacon_interval); - else ifcmp("mac") tcp_puts(MACSTR, MAC2STR(xnetif[wlan_ap_netifn].hwaddr)); - else ifcmp("hostname") tcp_strcpy(lwip_host_name[wlan_ap_netifn]); + else ifcmp("mac") tcp_puts(MACSTR, MAC2STR(xnetif[WLAN_AP_NETIF_NUM].hwaddr)); + else ifcmp("hostname") tcp_strcpy(lwip_host_name[WLAN_AP_NETIF_NUM]); else ifcmp("dhcp") tcp_puts("%u", wifi_ap_dhcp.mode); else ifcmp("ip") tcp_puts(IPSTR, IP2STR(&wifi_ap_dhcp.ip)); else ifcmp("gw") tcp_puts(IPSTR, IP2STR(&wifi_ap_dhcp.gw)); else ifcmp("msk") tcp_puts(IPSTR, IP2STR(&wifi_ap_dhcp.mask)); - else ifcmp("cip") tcp_puts(IPSTR, IP2STR(&xnetif[wlan_st_netifn].ip_addr.addr)); + else ifcmp("cip") tcp_puts(IPSTR, IP2STR(&xnetif[WLAN_ST_NETIF_NUM].ip_addr.addr)); // else ifcmp("mac") strtomac(pvar, wifi_ap_cfg.macaddr); // else ifcmp("sip") tcp_puts(IPSTR, IP2STR(&wifi_ap_dhcp.start_ip)); @@ -574,13 +574,13 @@ void ICACHE_FLASH_ATTR web_int_callback(TCP_SERV_CONN *ts_conn, uint8 *cstr) os_memcpy((char *)&web_conn->msgbuf[web_conn->msgbuflen], wifi_st_cfg.password, len); web_conn->msgbuflen += len; } - else ifcmp("mac") tcp_puts(MACSTR, MAC2STR(xnetif[wlan_st_netifn].hwaddr)); + else ifcmp("mac") tcp_puts(MACSTR, MAC2STR(xnetif[WLAN_ST_NETIF_NUM].hwaddr)); else ifcmp("bssid") tcp_puts(MACSTR, MAC2STR(wifi_st_cfg.bssid)); else ifcmp("sbss") tcp_puts("%u", wifi_st_cfg.flg); #if LWIP_NETIF_HOSTNAME - else ifcmp("hostname") tcp_strcpy(lwip_host_name[wlan_st_netifn]); + else ifcmp("hostname") tcp_strcpy(lwip_host_name[WLAN_ST_NETIF_NUM]); #endif - else ifcmp("auth") tcp_puts("%u", wifi_st_cfg.security_type); + else ifcmp("auth") tcp_puts("%u", translate_rtw_security_to_val(wifi_st_cfg.security_type)); else ifcmp("dhcp") tcp_puts("%u", wifi_st_dhcp.mode); else ifcmp("ip") tcp_puts(IPSTR, IP2STR(&wifi_st_dhcp.ip)); else ifcmp("gw") tcp_puts(IPSTR, IP2STR(&wifi_st_dhcp.gw)); @@ -673,7 +673,7 @@ void ICACHE_FLASH_ATTR web_int_callback(TCP_SERV_CONN *ts_conn, uint8 *cstr) #ifdef USE_SNTP else ifcmp("sntp_") { cstr += 5; - ifcmp("time") tcp_puts("%u", get_sntp_time()); + ifcmp("time") tcp_puts("%u", sntp_gen_system_time(0)); // get_sntp_time else tcp_put('?'); } #endif diff --git a/project/src/web/web_int_vars.c b/project/src/web/web_int_vars.c index 947eb52..9f0a4cc 100644 --- a/project/src/web/web_int_vars.c +++ b/project/src/web/web_int_vars.c @@ -25,11 +25,11 @@ #include "esp_comp.h" #ifdef USE_NETBIOS -#include "netbios.h" +#include "netbios/netbios.h" #endif #ifdef USE_SNTP -#include "sntp.h" +#include "sntp/sntp.h" #endif #ifdef USE_LWIP_PING @@ -133,7 +133,7 @@ void ICACHE_FLASH_ATTR web_int_vars(TCP_SERV_CONN *ts_conn, uint8 *pcmd, uint8 * else os_printf(" - none!\n"); #endif } - else ifcmp("pinclr") syscfg.cfg.b.pin_clear_cfg_enable = (val)? 1 : 0; + else ifcmp("pinclr") syscfg.cfg.b.pin_clear_cfg_enable = (val)? 1 : 0; else ifcmp("debug") { syscfg.cfg.b.debug_print_enable = val; print_off = (!val) & 1; // rtl_print on/off @@ -152,8 +152,8 @@ void ICACHE_FLASH_ATTR web_int_vars(TCP_SERV_CONN *ts_conn, uint8 *pcmd, uint8 * #ifdef USE_SNTP else ifcmp("sntp") { syscfg.cfg.b.sntp_ena = (val)? 1 : 0; - if(syscfg.cfg.b.sntp_ena) sntp_inits(); - else sntp_close(); + if(syscfg.cfg.b.sntp_ena) sntp_init(); + else sntp_stop(); } #endif #ifdef USE_CAPTDNS @@ -198,7 +198,7 @@ void ICACHE_FLASH_ATTR web_int_vars(TCP_SERV_CONN *ts_conn, uint8 *pcmd, uint8 * else os_memset(wifi_ap_cfg.ssid, 0, sizeof(wifi_ap_cfg.ssid)); os_memcpy(wifi_ap_cfg.ssid, pvar, len); #ifdef USE_NETBIOS - netbios_set_name(wifi_ap_cfg.ssid); +// netbios_set_name(wlan_ap_netifn, wifi_ap_cfg.ssid); #endif } } @@ -212,7 +212,7 @@ void ICACHE_FLASH_ATTR web_int_vars(TCP_SERV_CONN *ts_conn, uint8 *pcmd, uint8 * } else ifcmp("chl") wifi_ap_cfg.channel = val; else ifcmp("mcns") wifi_ap_cfg.max_sta = val; - else ifcmp("auth") wifi_ap_cfg.security_type = (val)? RTW_SECURITY_WEP_PSK : RTW_SECURITY_OPEN; + else ifcmp("auth") wifi_ap_cfg.security_type = (val != 0); else ifcmp("hssid") wifi_ap_cfg.ssid_hidden = val; else ifcmp("bint") wifi_ap_cfg.beacon_interval = val; #if LWIP_NETIF_HOSTNAME @@ -259,7 +259,7 @@ void ICACHE_FLASH_ATTR web_int_vars(TCP_SERV_CONN *ts_conn, uint8 *pcmd, uint8 * else os_memset(wifi_st_cfg.password, 0, sizeof(wifi_st_cfg.password)); os_memcpy(wifi_st_cfg.password, pvar, len); } - else ifcmp("auth") wifi_st_cfg.security_type = val; + else ifcmp("auth") wifi_st_cfg.security_type = translate_val_to_rtw_security(val); else ifcmp("bssid") strtomac(pvar, wifi_st_cfg.bssid); else ifcmp("sbss") wifi_st_cfg.flg = val; #if LWIP_NETIF_HOSTNAME diff --git a/project/src/web/web_srv.c b/project/src/web/web_srv.c index 93154e0..373cbac 100644 --- a/project/src/web/web_srv.c +++ b/project/src/web/web_srv.c @@ -124,7 +124,7 @@ const char HTTPresponse_200_head[] ICACHE_RODATA_ATTR = "OK"; const char HTTPresponse_302_head[] ICACHE_RODATA_ATTR = "Found"; const char HTTPresponse_304_head[] ICACHE_RODATA_ATTR = "Not Modified"; const char HTTPresponse_400_head[] ICACHE_RODATA_ATTR = "Bad Request"; -const char HTTPresponse_401_head[] ICACHE_RODATA_ATTR = "Unauthorized\r\nWWW-Authenticate: Basic realm=\"Protected\""; +const char HTTPresponse_401_head[] ICACHE_RODATA_ATTR = "Unauthorized\r\nWWW-Authenticate: Basic realm=\"Protected%u\""; const char HTTPresponse_404_head[] ICACHE_RODATA_ATTR = "Not found"; const char HTTPresponse_411_head[] ICACHE_RODATA_ATTR = "Length Required"; const char HTTPresponse_413_head[] ICACHE_RODATA_ATTR = "Request Entity Too Large"; @@ -304,7 +304,7 @@ LOCAL WEB_SRV_CONN * ICACHE_FLASH_ATTR ReNew_web_conn(TCP_SERV_CONN *ts_conn) // /ssl/crypto/ssl_crypto_misc.c: // EXP_FUNC int STDCALL base64_decode(const uint8 *in, int len, uint8_t *out, int *outlen); // Username and password are combined into a string "username:password" -LOCAL bool ICACHE_FLASH_ATTR CheckAuthorization(uint8* base64str) +LOCAL uint8 ICACHE_FLASH_ATTR CheckAuthorization(uint8* base64str) { uint8 *pcmp = base64str; int len = 0; @@ -315,23 +315,41 @@ LOCAL bool ICACHE_FLASH_ATTR CheckAuthorization(uint8* base64str) if((len >= 4)&&(len <= 128) &&(base64decode(base64str, len, pbuf, &declen))) { pbuf[declen]='\0'; - uint8 ppsw[32+64+1]; - cmpcpystr(ppsw, wifi_ap_cfg.ssid, '\0','\0', 32); - len = rtl_strlen((char*)ppsw); - ppsw[len++] = ':'; - cmpcpystr(&ppsw[len], wifi_ap_cfg.password, '\0','\0', 64); #if DEBUGSOO > 1 os_printf("'%s' ", pbuf); #endif -#if DEBUGSOO > 2 - os_printf("<%s>[%u] ", ppsw, declen); -#endif - if(os_strncmp(pbuf, (char *)ppsw , declen) == 0) return true; + return UserAuthorization(pbuf, declen); }; - return false; + return 0; } //============================================================================= - +#define web_parse_cookie(CurHTTP, ts_conn) web_parse_vars(ts_conn, (CurHTTP)->pcookie, (CurHTTP)->cookie_len, '\0', ';') +#define web_parse_uri_vars(CurHTTP, ts_conn) web_parse_vars(ts_conn, (CurHTTP)->puri, (CurHTTP)->uri_len, '?', '&') +#define web_parse_content(CurHTTP, ts_conn) web_parse_vars(ts_conn, (CurHTTP)->pcontent, (CurHTTP)->content_len, '\0', '&') +LOCAL void ICACHE_FLASH_ATTR web_parse_vars(TCP_SERV_CONN *ts_conn, uint8 *vars, uint32 vars_len, uint8 start_char, uint8 end_char) +{ + if(vars == NULL || vars_len == 0) return; + uint8 *pcmp; + if(start_char) { + pcmp = cmpcpystr(NULL, vars, '\0', start_char, vars_len); // find start_char if available + start_char = '\0'; + } else pcmp = vars - 1; + while(pcmp != NULL) { + uint16 len = vars_len - (pcmp - vars); + uint8 *pcmd = pcmp; + pcmp = cmpcpystr(pcmp, pcmp + 1, start_char, '=', len); // skip spaces before variable name + if(pcmp == NULL) break; + urldecode(pcmd, pcmd, len, len); + len = vars_len - (pcmp - vars); + uint8 *pvar = pcmp; + pcmp = cmpcpystr(pcmp, pcmp + 1, '\0', end_char, len); + if(pcmd[0] != '\0') { + urldecode(pvar, pvar, len, len); + web_int_vars(ts_conn, pcmd, pvar); + } + } +} +/* //============================================================================= LOCAL void ICACHE_FLASH_ATTR web_parse_cookie(HTTP_CONN *CurHTTP, TCP_SERV_CONN *ts_conn) @@ -394,6 +412,7 @@ web_parse_content(HTTP_CONN *CurHTTP, TCP_SERV_CONN *ts_conn) } } while(pcmp != NULL); } +*/ //============================================================================= // Разбор имени файла и перевод в вид относительного URI. // (выкидывание HTTP://Host) @@ -411,7 +430,7 @@ web_parse_fname(HTTP_CONN *CurHTTP, TCP_SERV_CONN *ts_conn) uint8 cbuf[FileNameSize+16]; uint8 *pcbuf = cbuf; urldecode(pcbuf, CurHTTP->puri, sizeof(cbuf) - 1, CurHTTP->uri_len); - if((os_strncmp((char *)pcbuf, "HTTP://", 7) == 0)||(os_strncmp((char *)pcbuf, "http://", 7) == 0)) { + if(rom_xstrcmp((char *)pcbuf, "HTTP://")||(rom_xstrcmp((char *)pcbuf, "http://"))) { pcbuf += 7; uint8 *pcmp = os_strchr((char *)pcbuf, '/'); if(pcmp != NULL) pcbuf = pcmp; @@ -422,6 +441,9 @@ web_parse_fname(HTTP_CONN *CurHTTP, TCP_SERV_CONN *ts_conn) uint8 *pcmp = web_strnstr(CurHTTP->pFilename, ProtectedFilesName, os_strlen(CurHTTP->pFilename)); if(pcmp != NULL) { WEB_SRV_CONN *web_conn = (WEB_SRV_CONN *)ts_conn->linkd; +#if USE_WEB_AUTH_LEVEL + web_conn->auth_realm = WEB_AUTH_LEVEL_USER; +#endif SetSCB(SCB_AUTH); } }; @@ -598,7 +620,17 @@ parse_header(HTTP_CONN *CurHTTP, TCP_SERV_CONN *ts_conn) if(os_strncmp(pstr, "Basic", 5) == 0) { // The authorization method and a space i.e. "Basic" is then put before the encoded string. pstr += 5; while(*pstr == ' ') pstr++; - if(CheckAuthorization(pstr)) ClrSCB(SCB_AUTH); +#if USE_WEB_AUTH_LEVEL + web_conn->auth_level = CheckAuthorization(pstr); +#if DEBUGSOO > 1 + os_printf("%u?%u ", web_conn->auth_level, web_conn->auth_realm); +#endif + if(web_conn->auth_level >= web_conn->auth_realm) + ClrSCB(SCB_AUTH); +#else + if(CheckAuthorization(pstr)) + ClrSCB(SCB_AUTH); +#endif else { CurHTTP->httpStatus = 401; // 401 Unauthorized return false; @@ -821,6 +853,9 @@ LOCAL bool ICACHE_FLASH_ATTR webserver_open_file(HTTP_CONN *CurHTTP, TCP_SERV_CO return true; } else if(rom_xstrcmp(pstr, fsupload_fname)) { +#if USE_WEB_AUTH_LEVEL + web_conn->auth_realm = WEB_AUTH_LEVEL_WEBFS; +#endif SetSCB(SCB_AUTH); web_inc_fp(web_conn, WEBFS_UPLOAD_HANDLE); web_conn->content_len = sizeHTTPfsupload; @@ -1075,7 +1110,8 @@ web_print_headers(HTTP_CONN *CurHTTP, TCP_SERV_CONN *ts_conn) CurResp++; }; tcp_puts_fd("HTTP/1.1 %u ", CurResp->status); - tcp_strcpy(CurResp->headers); + if(CurResp->status == 401) tcp_puts_fd(CurResp->headers, web_conn->auth_realm); + else tcp_strcpy(CurResp->headers); tcp_strcpy_fd("\r\nServer: " WEB_NAME_VERSION "\r\nConnection: close\r\n"); if(CheckSCB(SCB_REDIR)) { tcp_puts_fd("Location: %s\r\n\r\n", CurHTTP->pFilename); @@ -1990,7 +2026,7 @@ err_t ICACHE_FLASH_ATTR webserver_init(uint16 portn) if (p != NULL) { // изменим конфиг на наше усмотрение: if(syscfg.cfg.b.web_time_wait_delete) p->flag.pcb_time_wait_free = 1; // пусть убивает, для теста и проксей - p->max_conn = 256; // сработает по heap_size + p->max_conn = 99; // сработает по heap_size #if DEBUGSOO > 3 os_printf("Max connection %d, time waits %d & %d, min heap size %d\n", p->max_conn, p->time_wait_rec, p->time_wait_cls, p->min_heap); diff --git a/project/src/web/web_utils.c b/project/src/web/web_utils.c index 020e98a..b6c704f 100644 --- a/project/src/web/web_utils.c +++ b/project/src/web/web_utils.c @@ -46,10 +46,7 @@ int ICACHE_RAM_ATTR rom_xstrcpy(char * pd, const char * ps) } #else int len = 0; - while(*ps) { - *pd++ = *ps++; - len++; - } + while((*pd++ = *ps++) != 0) len++; return len; #endif } diff --git a/sdkset.mk b/sdkset.mk index c5543c2..e63151d 100644 --- a/sdkset.mk +++ b/sdkset.mk @@ -113,6 +113,7 @@ SRC_C += sdk/component/common/api/wifi/wifi_promisc.c SRC_C += sdk/component/common/api/wifi/wifi_simple_config.c SRC_C += sdk/component/common/api/wifi/wifi_util.c SRC_C += sdk/component/common/api/lwip_netconf.c +SRC_C += sdk/component/common/api/wifi_api.c #network - app #SRC_C += sdk/component/common/utilities/ssl_client.c @@ -121,8 +122,8 @@ SRC_C += sdk/component/common/api/lwip_netconf.c #SRC_C += sdk/component/common/utilities/uart_ymodem.c #SRC_C += sdk/component/common/utilities/update.c #SRC_C += sdk/component/common/application/uart_adapter/uart_adapter.c -SRC_C += sdk/component/common/api/network/src/wlan_network.c -SRC_C += sdk/component/common/api/wifi_interactive_mode.c +#SRC_C += sdk/component/common/api/network/src/wlan_network.c +#SRC_C += sdk/component/common/api/wifi_interactive_mode.c #SRC_C += sdk/component/common/api/network/src/ping_test.c #network - lwip @@ -397,7 +398,6 @@ ADD_SRC_C += sdk/component/soc/realtek/8195a/misc/rtl_std_lib/lib_rtlstd/c_stdio #ADD_SRC_C += sdk/component/common/drivers/sdio/realtek/sdio_host/src/sdio_host.c #ADD_SRC_C += sdk/component/soc/realtek/8195a/fwlib/src/hal_sdio_host.c #ADD_SRC_C += sdk/component/common/file_system/fatfs/disk_if/src/sdcard.c -ADD_SRC_C += sdk/component/common/api/wifi_api.c #============================================= # PROGECT #============================================= @@ -419,6 +419,7 @@ ADD_SRC_C += project/src/web/web_websocket.c ADD_SRC_C += project/src/web/websock.c ADD_SRC_C += project/src/web/web_int_callbacks.c ADD_SRC_C += project/src/web/web_int_vars.c +ADD_SRC_C += project/src/web/web_auth.c #CFLAGS += -DDEFAULT_BAUDRATE=1562500 #if CONFIG_ENABLE_P2P and ...: