From e169ec2bce1ad4bc0b62961853811c59e212cfe3 Mon Sep 17 00:00:00 2001 From: ZhaoWei Xu Date: Mon, 20 Jul 2020 09:06:11 +0800 Subject: [PATCH] Bumped revision to 5.1.1 --- release/src-rt/Makefile | 2 +- release/src-rt/target.mak | 5 - release/src/router/httpd/dbapi.c | 16 + release/src/router/httpd/dbapi.h | 1 + release/src/router/httpd/web.c | 18 +- release/src/router/rc/merlinr.c | 24 +- release/src/router/rc/services.c | 16 +- release/src/router/rc/watchdog.c | 5 +- .../rom/webs_scripts/merlinr_webs_note.sh | 72 +- release/src/router/smartdns/.clang-format | 10 + .../.github/ISSUE_TEMPLATE/feature.md | 20 + .../smartdns/.github/ISSUE_TEMPLATE/issue.md | 29 + release/src/router/smartdns/.gitignore | 4 + release/src/router/smartdns/LICENSE | 155 +- release/src/router/smartdns/Makefile | 47 + release/src/router/smartdns/ReadMe.md | 1377 +++--- release/src/router/smartdns/ReadMe_en.md | 1370 +++--- .../src/router/smartdns/doc/alipay_donate.jpg | Bin 69292 -> 53406 bytes .../src/router/smartdns/etc/init.d/smartdns | 14 +- .../smartdns/etc/smartdns/smartdns.conf | 40 +- .../src/router/smartdns/package/build-pkg.sh | 14 +- .../src/router/smartdns/package/linux/install | 249 + .../src/router/smartdns/package/linux/make.sh | 11 +- .../package/luci-compat/control/control | 7 + .../package/luci-compat/control/postinst | 21 + .../package/luci-compat/control/postinst-pkg | 4 + .../package/luci-compat/control/prerm | 20 + .../package/luci-compat/debian-binary | 1 + .../files/etc/uci-defaults/50_luci-smartdns | 26 + .../files/luci/controller/smartdns.lua | 83 + .../files/luci/i18n/smartdns.zh-cn.po | 299 ++ .../luci/model/cbi/smartdns/smartdns.lua | 342 ++ .../luci/model/cbi/smartdns/upstream.lua | 129 + .../luci-compat/files/luci/model/smartdns.lua | 31 + .../luci/view/smartdns/smartdns_status.htm | 41 + .../smartdns/package/luci-compat/make.sh | 135 + .../package/luci-compat/tool/po2lmo/Makefile | 12 + .../luci-compat/tool/po2lmo/src/po2lmo.c | 247 + .../tool/po2lmo/src/template_lmo.c | 328 ++ .../tool/po2lmo/src/template_lmo.h | 92 + .../smartdns/package/luci/control/control | 3 +- .../package/luci/control/postinst-pkg | 4 - .../luci/files/luci/i18n/smartdns.zh-cn.po | 593 +-- .../share/luci/menu.d/luci-app-smartdns.json | 12 + .../share/rpcd/acl.d/luci-app-smartdns.json | 23 + .../resources/view/smartdns/smartdns.js | 492 ++ .../src/router/smartdns/package/luci/make.sh | 10 +- .../router/smartdns/package/openwrt/Makefile | 57 +- .../smartdns/package/openwrt/address.conf | 32 +- .../package/openwrt/blacklist-ip.conf | 6 +- .../smartdns/package/openwrt/custom.conf | 26 +- .../package/openwrt/files/etc/init.d/smartdns | 373 +- .../smartdns/package/optware/S50smartdns | 86 +- release/src/router/smartdns/src/Makefile | 20 +- release/src/router/smartdns/src/dns.c | 4021 +++++++++-------- release/src/router/smartdns/src/dns.h | 17 +- release/src/router/smartdns/src/dns_cache.c | 838 ++-- release/src/router/smartdns/src/dns_cache.h | 176 +- release/src/router/smartdns/src/dns_client.c | 330 +- release/src/router/smartdns/src/dns_client.h | 10 +- release/src/router/smartdns/src/dns_conf.c | 2872 ++++++------ release/src/router/smartdns/src/dns_conf.h | 502 +- release/src/router/smartdns/src/dns_server.c | 337 +- release/src/router/smartdns/src/dns_server.h | 3 +- release/src/router/smartdns/src/fast_ping.c | 3394 +++++++------- release/src/router/smartdns/src/fast_ping.h | 118 +- release/src/router/smartdns/src/http_parse.c | 926 ++-- release/src/router/smartdns/src/http_parse.h | 174 +- release/src/router/smartdns/src/include/art.h | 502 +- .../src/router/smartdns/src/include/conf.h | 283 +- .../src/router/smartdns/src/include/radix.h | 324 +- .../src/router/smartdns/src/include/rbtree.h | 610 +-- .../router/smartdns/src/include/stringutil.h | 84 +- release/src/router/smartdns/src/lib/art.c | 2258 ++++----- release/src/router/smartdns/src/lib/conf.c | 622 +-- release/src/router/smartdns/src/lib/radix.c | 1352 +++--- release/src/router/smartdns/src/lib/rbtree.c | 1048 ++--- .../src/router/smartdns/src/lib/stringutil.c | 32 +- release/src/router/smartdns/src/smartdns.c | 899 ++-- release/src/router/smartdns/src/util.c | 67 +- release/src/router/smartdns/src/util.h | 12 +- .../smartdns/systemd/smartdns.service.in | 18 + release/src/router/softcenter/Makefile | 35 +- release/src/router/softcenter/Softcenter.asp | 18 +- .../router/softcenter/Softcenter_mount.asp | 179 - release/src/router/softcenter/jffsinit.sh | 112 +- release/src/router/softcenter/scCN.json | 3 +- release/src/router/softcenter/scEN.json | 5 +- release/src/router/softcenter/scTW.json | 3 +- .../softcenter/ROG/res/softcenter.css | 52 +- .../softcenter/ROG/webs/Main_Soft_center.asp | 777 ---- .../softcenter/ROG/webs/Main_Soft_setting.asp | 217 - .../softcenter/TUF/res/softcenter.css | 108 - .../softcenter/TUF/webs/Main_Soft_center.asp | 784 ---- .../softcenter/TUF/webs/Main_Soft_setting.asp | 217 - .../router/softcenter/softcenter/automount.sh | 13 + .../softcenter/bin/softcenter-services.sh | 30 + .../softcenter/bin/softcenter-unmount.sh | 26 + .../softcenter/softcenter/bin/softcenter.sh | 45 +- .../softcenter/softcenter/res/sc1CN.json | 21 + .../softcenter/softcenter/res/sc1EN.json | 21 + .../softcenter/softcenter/res/sc1TW.json | 21 + .../softcenter/softcenter/res/softcenter.css | 19 + .../softcenter/scripts/ks_app_install.sh | 113 +- .../{ks_tar_intall.sh => ks_tar_install.sh} | 16 + .../softcenter/webs/Main_Soft_center.asp | 111 +- .../softcenter/webs/Main_Soft_setting.asp | 32 +- 107 files changed, 16546 insertions(+), 15315 deletions(-) mode change 100644 => 100755 release/src/router/rom/webs_scripts/merlinr_webs_note.sh create mode 100644 release/src/router/smartdns/.clang-format create mode 100644 release/src/router/smartdns/.github/ISSUE_TEMPLATE/feature.md create mode 100644 release/src/router/smartdns/.github/ISSUE_TEMPLATE/issue.md create mode 100644 release/src/router/smartdns/.gitignore create mode 100644 release/src/router/smartdns/Makefile create mode 100644 release/src/router/smartdns/package/linux/install create mode 100644 release/src/router/smartdns/package/luci-compat/control/control create mode 100644 release/src/router/smartdns/package/luci-compat/control/postinst create mode 100644 release/src/router/smartdns/package/luci-compat/control/postinst-pkg create mode 100644 release/src/router/smartdns/package/luci-compat/control/prerm create mode 100644 release/src/router/smartdns/package/luci-compat/debian-binary create mode 100644 release/src/router/smartdns/package/luci-compat/files/etc/uci-defaults/50_luci-smartdns create mode 100644 release/src/router/smartdns/package/luci-compat/files/luci/controller/smartdns.lua create mode 100644 release/src/router/smartdns/package/luci-compat/files/luci/i18n/smartdns.zh-cn.po create mode 100644 release/src/router/smartdns/package/luci-compat/files/luci/model/cbi/smartdns/smartdns.lua create mode 100644 release/src/router/smartdns/package/luci-compat/files/luci/model/cbi/smartdns/upstream.lua create mode 100644 release/src/router/smartdns/package/luci-compat/files/luci/model/smartdns.lua create mode 100644 release/src/router/smartdns/package/luci-compat/files/luci/view/smartdns/smartdns_status.htm create mode 100644 release/src/router/smartdns/package/luci-compat/make.sh create mode 100644 release/src/router/smartdns/package/luci-compat/tool/po2lmo/Makefile create mode 100644 release/src/router/smartdns/package/luci-compat/tool/po2lmo/src/po2lmo.c create mode 100644 release/src/router/smartdns/package/luci-compat/tool/po2lmo/src/template_lmo.c create mode 100644 release/src/router/smartdns/package/luci-compat/tool/po2lmo/src/template_lmo.h create mode 100644 release/src/router/smartdns/package/luci/files/root/usr/share/luci/menu.d/luci-app-smartdns.json create mode 100644 release/src/router/smartdns/package/luci/files/root/usr/share/rpcd/acl.d/luci-app-smartdns.json create mode 100644 release/src/router/smartdns/package/luci/files/root/www/luci-static/resources/view/smartdns/smartdns.js create mode 100644 release/src/router/smartdns/systemd/smartdns.service.in delete mode 100644 release/src/router/softcenter/Softcenter_mount.asp delete mode 100644 release/src/router/softcenter/softcenter/ROG/webs/Main_Soft_center.asp delete mode 100644 release/src/router/softcenter/softcenter/ROG/webs/Main_Soft_setting.asp delete mode 100644 release/src/router/softcenter/softcenter/TUF/res/softcenter.css delete mode 100644 release/src/router/softcenter/softcenter/TUF/webs/Main_Soft_center.asp delete mode 100644 release/src/router/softcenter/softcenter/TUF/webs/Main_Soft_setting.asp create mode 100644 release/src/router/softcenter/softcenter/automount.sh create mode 100644 release/src/router/softcenter/softcenter/bin/softcenter-services.sh create mode 100644 release/src/router/softcenter/softcenter/bin/softcenter-unmount.sh create mode 100644 release/src/router/softcenter/softcenter/res/sc1CN.json create mode 100644 release/src/router/softcenter/softcenter/res/sc1EN.json create mode 100644 release/src/router/softcenter/softcenter/res/sc1TW.json rename release/src/router/softcenter/softcenter/scripts/{ks_tar_intall.sh => ks_tar_install.sh} (87%) diff --git a/release/src-rt/Makefile b/release/src-rt/Makefile index 98d06ea3bf..50299fe374 100644 --- a/release/src-rt/Makefile +++ b/release/src-rt/Makefile @@ -70,7 +70,7 @@ export PATH := $(RELEASEDIR)/tools:$(SRCBASE)/ctools:$(PATH) #K3C/K3/SBRAC1900P/SBRAC3200P/R7000/R8000/R7900P/R8000P export MERLINR_NAME := RTACRH17 export MERLINR_VER_MAJOR :=B -export MERLINR_VER_MINOR :=5.1.0 +export MERLINR_VER_MINOR :=5.1.1 export MERLINR_VER := $(MERLINR_VER_MAJOR)$(MERLINR_VER_MINOR) export MERLINRVER := $(MERLINR_NAME)_$(MERLINR_VER) ifeq ($(MERLINR_NAME),RTACRH17) diff --git a/release/src-rt/target.mak b/release/src-rt/target.mak index 44bf2443f7..0fca422e60 100644 --- a/release/src-rt/target.mak +++ b/release/src-rt/target.mak @@ -398,11 +398,6 @@ export VZW-AC1300 := IPV6SUPP=y HTTPS=y SSH=y QCA=y IPQ40XX=y PARENTAL2=y OPENVP ATF=y QCA_TW_AUTO_BAND4=y STAINFO=y HIVE_LIB=y HIVE_BIN=y \ WIFICLONE=y QCA_VAP_LOCALMAC=y PSISTLOG=y LYRA_HIDE=y CSU2_2=y DUAL_BACKHAUL=n ETHBACKHAUL=n VZW_DMC=y -export RT-ACRH17 := IPV6SUPP=y HTTPS=y SSH=y QCA=y IPQ40XX=y BBEXTRAS=y USBEXTRAS=y SAMBA3=y MEDIASRV=y PARENTAL2=y OPENVPN=y VPNC=y EMAIL=y YANDEXDNS=y ACCEL_PPTPD=y PRINTER=y USB="USB" APP="network" EBTABLES=y AUTODICT=y LANWAN_LED=y BUILD_NAME="RT-AC82U" RTAC82U=y SHP=y NVRAM_64K=y TUNEK="n" OPTIMIZE_XBOX=y ODMPID=y BOOT_FLASH_TYPE=NAND MDNS=y FINDASUS=y XHCI=y ATEUSB3_FORCE=y EXT4FS=y TEMPROOTFS=y NTFS="tuxera" TFAT=y HFS="tuxera" DUMP_OOPS_MSG=y DEBUGFS=y \ - REBOOT_SCHEDULE=y NOIPTV=y \ - DISK_MONITOR=y UBI=y UBIFS=y PSISTLOG=y WPSMULTIBAND=y BLINK_LED=y LAN4WAN_LED=y WANRED_LED=y BTN_WPS_ALLLED=y \ - NEW_USER_LOW_RSSI=y REDIRECT_DNAME=y ATF=y QCA_TW_AUTO_BAND4=y STAINFO=y NEWSSID_REV2=y LAN50=y NEW_APP_ARM=y SW_HW_AUTH=y NATNL_AIHOME=y UTF8_SSID=y SOFTCENTER=y SMARTDNS=y FRS_LIVE_UPDATE=y UUPLUGIN=y - ############################################################################ # Qualcomm Atheros little-endian ARM platform, linux-3.4.x # SOC: IPQ8064 diff --git a/release/src/router/httpd/dbapi.c b/release/src/router/httpd/dbapi.c index 3475910940..6b680e39ea 100644 --- a/release/src/router/httpd/dbapi.c +++ b/release/src/router/httpd/dbapi.c @@ -141,6 +141,22 @@ int dbclient_start(dbclient* client) { return 0; } +int dbclient_rm(dbclient* client, const char* key, int nk) { + int n1,n2; + + if(nk < 0) { + return -1; + } + + n1 = nk + 2 + 6; + check_buf(client, n1 + HEADER_PREFIX); + n2 = snprintf(client->buf, client->buf_max, "%s%07d remove %s\n", MAGIC, n1, key); + client->buf[n2] = '\0'; + write(client->remote_fd, client->buf, n2); + + return 0; +} + int dbclient_bulk(dbclient* client, const char* command, const char* key, int nk, const char* value, int nv) { int n1,n2,nc; diff --git a/release/src/router/httpd/dbapi.h b/release/src/router/httpd/dbapi.h index c15819dc76..e1afe9b99c 100644 --- a/release/src/router/httpd/dbapi.h +++ b/release/src/router/httpd/dbapi.h @@ -39,6 +39,7 @@ typedef struct _dbclient { typedef int (*fn_db_parse)(dbclient* client, webs_t wp, char* prefix, char* key, char* value); int dbclient_start(dbclient* client); +int dbclient_rm(dbclient* client, const char* key, int nk); int dbclient_bulk(dbclient* client, const char* command, const char* key, int nk, const char* value, int nv); int dbclient_end(dbclient* client); int dbclient_list(dbclient* client, char* prefix, webs_t wp, fn_db_parse fn); diff --git a/release/src/router/httpd/web.c b/release/src/router/httpd/web.c index d65ea73364..04dcf40895 100755 --- a/release/src/router/httpd/web.c +++ b/release/src/router/httpd/web.c @@ -9715,7 +9715,7 @@ static int ej_get_simact_result(int eid, webs_t wp, int argc, char_t **argv){ if(len > 0){ if(buf[len] == '\n' || buf[len] == '\r') buf[len] = '\0'; - websWrite(wp, buf); + websWrite(wp, "\"%s\"",buf); break; } } @@ -15095,7 +15095,7 @@ applydb_cgi(webs_t wp, char_t *urlPrefix, char_t *webDir, int arg, char *result = NULL; char *temp = NULL; char *name = websGetVar(wp, "p",""); - char *userm = strstr(url, "use_rm=1"); + char *userm = websGetVar(wp, "use_rm", ""); char scPath[128]; char *post_db_buf = post_json_buf; @@ -15133,8 +15133,8 @@ applydb_cgi(webs_t wp, char_t *urlPrefix, char_t *webDir, int arg, strcpy(dbval, temp+1); strncpy(dbvar, dbjson[j], strlen(dbjson[j])-strlen(temp)); //logmessage("HTTPD", "name: %s post: %s", dbvar, dbval); - if(userm) - doSystem("dbus remove %s", dbvar); + if(*userm || dbval[0]=='\0') + dbclient_rm(&client, dbvar, strlen(dbvar)); else dbclient_bulk(&client, "set", dbvar, strlen(dbvar), dbval, strlen(dbval)); } @@ -15164,9 +15164,9 @@ applydb_cgi(webs_t wp, char_t *urlPrefix, char_t *webDir, int arg, temp=strstr(dbjson[j], "="); strcpy(dbval, temp+1); strncpy(dbvar, dbjson[j], strlen(dbjson[j])-strlen(temp)); - //logmessage("HTTPD", "name: %s post: %s", dbvar, dbval); - if(userm) - doSystem("dbus remove %s", dbvar); + //logmessage("HTTPD", "dbvar: %s dbval: %s", dbvar, dbval); + if(*userm || dbval[0]=='\0') + dbclient_rm(&client, dbvar, strlen(dbvar)); else dbclient_bulk(&client, "set", dbvar, strlen(dbvar), dbval, strlen(dbval)); } @@ -15307,7 +15307,7 @@ do_logread(webs_t wp, char_t *urlPrefix, char_t *webDir, int arg, //sscanf(url, "logreaddb.cgi?%s", filename); char *filename = websGetVar(wp, "p",""); char *script = websGetVar(wp, "script", ""); - if(script){ + if(*script){ sprintf(scPath, "/jffs/softcenter/scripts/%s", script); strlcpy(SystemCmd, scPath, sizeof(SystemCmd)); sys_script("syscmd.sh"); @@ -23158,7 +23158,7 @@ ej_get_wan_lan_status(int eid, webs_t wp, int argc, char **argv) if (wanLanStatus == NULL || wanLanLinkSpeed == NULL || wanLanCount == NULL) goto error; -#if defined(K3) || defined(R8000P) || defined(R7900P) +#if defined(K3) || defined(R8000P) || defined(R7900P) || defined(EA6700) fp = popen("rc Get_PhyStatus", "r"); #else fp = popen("ATE Get_WanLanStatus", "r"); diff --git a/release/src/router/rc/merlinr.c b/release/src/router/rc/merlinr.c index 1fac3fb8dc..dbccac814f 100644 --- a/release/src/router/rc/merlinr.c +++ b/release/src/router/rc/merlinr.c @@ -81,12 +81,12 @@ void merlinr_init_done() { _dprintf("############################ MerlinR init done #################################\n"); #ifdef RTCONFIG_SOFTCENTER - if (!f_exists("/jffs/softcenter/scripts/ks_tar_intall.sh") && nvram_match("sc_mount","0")){ + if (!f_exists("/jffs/softcenter/scripts/ks_tar_install.sh") && nvram_match("sc_mount","0")){ doSystem("/usr/sbin/jffsinit.sh &"); logmessage("Softcenter/软件中心", "Installing/开始安装......"); logmessage("Softcenter/软件中心", "Wait a minute/1分钟后完成安装"); _dprintf("....softcenter ok....\n"); - } else if (f_exists("/jffs/softcenter/scripts/ks_tar_intall.sh") && nvram_match("sc_mount","0")) + } else if (f_exists("/jffs/softcenter/scripts/ks_tar_install.sh") && nvram_match("sc_mount","0")) nvram_set("sc_installed","1"); //else if (!f_exists("/jffs/softcenter/scripts/ks_tar_intall.sh") && nvram_match("sc_mount","1")) //nvram_set("sc_installed","0"); @@ -97,11 +97,9 @@ void merlinr_init_done() doSystem("sed -i '/softcenter-mount.sh/d' /jffs/scripts/post-mount"); } + doSystem("dbus set softcenter_firmware_version=`nvram get extendno|cut -d \"_\" -f2|cut -d \"-\" -f1|cut -c2-6`"); #endif -#if defined(RTCONFIG_QCA) - if(!nvram_get("bl_ver")) - nvram_set("bl_ver", "1.0.0.0"); -#elif defined(RTCONFIG_RALINK) +#if defined(RTCONFIG_QCA) || defined(RTCONFIG_RALINK) if(!nvram_get("bl_ver")) nvram_set("bl_ver", nvram_get("blver")); #elif defined(RTCONFIG_LANTIQ) @@ -169,6 +167,10 @@ void merlinr_init_done() #if defined(TUFAX3000) && defined(MERLINR_VER_MAJOR_X) //tufax3000=ax82u,ax58u=ax3000 //enable_4t4r(); +#elif defined(GTAC2900) && defined(MERLINR_VER_MAJOR_X) +//ac86u <--> gtac2900 + patch_ac86(); + //patch_gt2900(); #endif } @@ -391,9 +393,9 @@ int merlinr_firmware_check_update_main(int argc, char *argv[]) //_dprintf("%s#%s\n",fwver,cur_fwver); if(versioncmp((cur_fwver+1),(fwver+1))==1){ nvram_set("webs_state_url", ""); -#if defined(SBRAC3200P) || defined(RTACRH17) || defined(RTAC3200) || defined(RTAC85P) +#if defined(RTACRH17) || defined(RTAC3200) || defined(RTAC85P) snprintf(info,sizeof(info),"3004_382_%s_%s-%s",modelname,fwver,tag); -#elif defined(RTAC68U) +#elif defined(RTAC68U) || defined(RTAC3100) || defined(RTAC88U) snprintf(info,sizeof(info),"3004_385_%s_%s-%s",modelname,fwver,tag); #else snprintf(info,sizeof(info),"3004_384_%s_%s-%s",modelname,fwver,tag); @@ -446,9 +448,9 @@ int merlinr_firmware_check_update_main(int argc, char *argv[]) curl_global_cleanup(); GODONE: -#if defined(SBRAC3200P) || defined(RTACRH17) || defined(RTAC3200) || defined(RTAC85P) +#if defined(RTACRH17) || defined(RTAC3200) || defined(RTAC85P) snprintf(info,sizeof(info),"3004_382_%s",nvram_get("extendno")); -#elif defined(RTAC68U) +#elif defined(RTAC68U) || defined(RTAC3100) || defined(RTAC88U) snprintf(info,sizeof(info),"3004_385_%s",nvram_get("extendno")); #else snprintf(info,sizeof(info),"3004_384_%s",nvram_get("extendno")); @@ -586,7 +588,7 @@ void softcenter_eval(int sig) // snprintf(path, sizeof(path), "%s/softcenter-unmount.sh", sc); // snprintf(action, sizeof(action), "unmount"); } else { - logmessage("Softcenter", "sig=%s, bug?",sig); + logmessage("Softcenter", "sig=%d, bug?",sig); return; } char *eval_argv[] = { path, action, NULL }; diff --git a/release/src/router/rc/services.c b/release/src/router/rc/services.c index 12fb1fdeb8..5c19dd08ed 100644 --- a/release/src/router/rc/services.c +++ b/release/src/router/rc/services.c @@ -4130,9 +4130,19 @@ start_smartdns(void) //fprintf(fp, "log-file /var/log/smartdns.log\n"); //fprintf(fp, "log-size 128k\n"); //fprintf(fp, "log-num 2\n"); - fprintf(fp, "server 114.114.114.114\n"); - fprintf(fp, "server 119.29.29.29\n"); - fprintf(fp, "server 223.5.5.5\n"); +#if !defined(K3C) && !defined(K3) && !defined(SBRAC1900P) && !defined(SBRAC3200P) && !defined(R8000P) + if(!strncmp(nvram_get("territory_code"), "CN",2)){ +#endif + fprintf(fp, "server 114.114.114.114\n"); + fprintf(fp, "server 119.29.29.29\n"); + fprintf(fp, "server 223.5.5.5\n"); +#if !defined(K3C) && !defined(K3) && !defined(SBRAC1900P) && !defined(SBRAC3200P) && !defined(R8000P) + } else { + fprintf(fp, "server 8.8.8.8\n"); + fprintf(fp, "server 208.67.222.222\n"); + fprintf(fp, "server 1.1.1.1\n"); + } +#endif for (unit = WAN_UNIT_FIRST; unit < WAN_UNIT_MAX; unit++) { char *wan_xdns; char wan_xdns_buf[sizeof("255.255.255.255 ")*2]; diff --git a/release/src/router/rc/watchdog.c b/release/src/router/rc/watchdog.c index 174e87c687..b998623ac4 100644 --- a/release/src/router/rc/watchdog.c +++ b/release/src/router/rc/watchdog.c @@ -5382,6 +5382,9 @@ static void softcenter_sig_check() if(f_exists("/jffs/softcenter/bin/softcenter.sh")) { softcenter_eval(SOFTCENTER_MOUNT); nvram_set_int("sc_mount_sig", 0); + } else if(!f_exists("/jffs/softcenter/bin/softcenter.sh") && nvram_match("sc_mount", "1")) { + //remount to sdb sdc not sda + doSystem("sh /jffs/softcenter/automount.sh &"); } } if(nvram_match("sc_services_sig", "1")) { @@ -5774,7 +5777,7 @@ void ntevent_intranet_usage_insight() tm = localtime(&now); /* send event at 9:00 each Monday */ - if (tm->tm_wday == 1 && tm->tm_hour == 9) { + if (tm->tm_wday == 1 && tm->tm_hour == 9 && tm->tm_min == 0) { snprintf(str, 32, "0x%x", HINT_INTERNET_USAGE_INSIGHT_EVENT); eval("Notify_Event2NC", str, ""); } diff --git a/release/src/router/rom/webs_scripts/merlinr_webs_note.sh b/release/src/router/rom/webs_scripts/merlinr_webs_note.sh old mode 100644 new mode 100755 index 69d3bff9c0..f5b45f242e --- a/release/src/router/rom/webs_scripts/merlinr_webs_note.sh +++ b/release/src/router/rom/webs_scripts/merlinr_webs_note.sh @@ -1,33 +1,83 @@ #!/bin/sh -wget_timeout=`nvram get apps_wget_timeout` -wget_options="-q -t 2 -T $wget_timeout --no-check-certificate" +wget_options="-q -t 2 -T 30 --no-check-certificate" + +dl_path_SQ="https://dlcdnets.asus.com/pub/ASUS/LiveUpdate/Release/Wireless_SQ" +dl_path_SQ_beta="https://dlcdnets.asus.com/pub/ASUS/LiveUpdate/Release/Wireless_SQ/app" +dl_path_file="https://update.paldier.com" nvram set cfg_note=0 get_preferred_lang=`nvram get preferred_lang` LANG="$get_preferred_lang" +# get release note +forsq=`nvram get apps_sq` +if [ -z "$forsq" ]; then + forsq=0 +fi + +echo "---- Get amas release note start ----" >> /tmp/webs_upgrade.log if [ $# != 2 ]; then - echo "---- no model name or version ----" >> /tmp/webs_note.log + echo "---- no model name or version ----" >> /tmp/webs_upgrade.log nvram set cfg_note=2 exit 0 fi new_firm=`echo $2 | sed s/'\.'/_/4 | sed s/'\.'//g;` -echo "---- $new_firm ----" >> /tmp/webs_note.log +echo "---- $1 $new_firm ----" >> /tmp/webs_upgrade.log releasenote_file=$1_"$new_firm"_"$LANG"_note.zip releasenote_file_US=$1_"$new_firm"_US_note.zip releasenote_path="/tmp/release_note.txt" -echo "---- download real release note for $1 ----" >> /tmp/webs_note.log -wget $wget_options https://update.paldier.com/$releasenote_file -O $releasenote_path -if [ "$?" != "0" ]; then - wget $wget_options https://update.paldier.com/$releasenote_file_US -O $releasenote_path + +wget_release="" +wget_release2="" +if [ "$forsq" -ge 2 ] && [ "$forsq" -le 9 ]; then + echo "---- download SQ beta_user release note ${dl_path_SQ_beta}${forsq}/$releasenote_file ----" >> /tmp/webs_upgrade.log + wget $wget_options ${dl_path_SQ_beta}${forsq}/$releasenote_file -O $releasenote_path + wget_release=$? + echo "---- [LiveUpdate] wget pLang release note, exit code: ${wget_release} ----" >> /tmp/webs_upgrade.log + if [ "$wget_release" != "0" ]; then + echo "---- download SQ beta_user release note ${dl_path_SQ_beta}${forsq}/$releasenote_file_US ----" >> /tmp/webs_upgrade.log + wget $wget_options ${dl_path_SQ_beta}${forsq}/$releasenote_file_US -O $releasenote_path + wget_release2=$? + echo "---- [LiveUpdate] wget US release note, exit code: ${wget_release2} ----" >> /tmp/webs_upgrade.log + fi +elif [ "$forsq" == "1" ]; then + echo "---- download SQ release note ${dl_path_SQ}/$releasenote_file ----" >> /tmp/webs_upgrade.log + wget $wget_options ${dl_path_SQ}/$releasenote_file -O $releasenote_path + wget_release=$? + echo "---- [LiveUpdate] wget pLang release note, exit code: ${wget_release} ----" >> /tmp/webs_upgrade.log + if [ "$wget_release" != "0" ]; then + echo "---- download SQ release note ${dl_path_SQ}/$releasenote_file_US ----" >> /tmp/webs_upgrade.log + wget $wget_options ${dl_path_SQ}/$releasenote_file_US -O $releasenote_path + wget_release2=$? + echo "---- [LiveUpdate] wget US release note, exit code: ${wget_release2} ----" >> /tmp/webs_upgrade.log + fi +else + echo "---- download real release note ${dl_path_file} for $1 ----" >> /tmp/webs_upgrade.log + wget $wget_options ${dl_path_file}/$releasenote_file -O $releasenote_path + wget_release=$? + echo "---- [LiveUpdate] wget pLang release note, exit code: ${wget_release} ----" >> /tmp/webs_upgrade.log + if [ "$wget_release" != "0" ]; then + echo "---- download real release note ${dl_path_file}/$releasenote_file_US ----" >> /tmp/webs_upgrade.log + wget $wget_options ${dl_path_file}/$releasenote_file_US -O $releasenote_path + wget_release2=$? + echo "---- [LiveUpdate] wget US release note, exit code: ${wget_release2} ----" >> /tmp/webs_upgrade.log + fi fi -echo "---- https://update.paldier.com/$releasenote_file ----" >> /tmp/webs_note.log -if [ "$?" != "0" ] || [ ! -s $releasenote_path ]; then - echo "---- download release note failed ----" >> /tmp/webs_note.log +if [ "$wget_release" != "0" ] && [ "$wget_release2" != "0" ]; then + echo "---- download release note failed ----" >> /tmp/webs_upgrade.log nvram set cfg_note=3 exit 0 +elif [ ! -s $releasenote_path ]; then + echo "---- no exist release note ----" >> /tmp/webs_upgrade.log + nvram set cfg_note=3 + exit 0 +else + echo "---- Get release note successfully ----" >> /tmp/webs_upgrade.log fi + +echo "---- Get release note end. ----" >> /tmp/webs_upgrade.log nvram set cfg_note=1 + diff --git a/release/src/router/smartdns/.clang-format b/release/src/router/smartdns/.clang-format new file mode 100644 index 0000000000..7eecf0ee9c --- /dev/null +++ b/release/src/router/smartdns/.clang-format @@ -0,0 +1,10 @@ +#http://clang.llvm.org/docs/ClangFormatStyleOptions.html + +BasedOnStyle: LLVM +IndentWidth: 4 +TabWidth: 4 +UseTab: ForContinuationAndIndentation +MaxEmptyLinesToKeep: 1 +AllowShortFunctionsOnASingleLine: Empty +BreakBeforeBraces: Linux +ColumnLimit: 120 diff --git a/release/src/router/smartdns/.github/ISSUE_TEMPLATE/feature.md b/release/src/router/smartdns/.github/ISSUE_TEMPLATE/feature.md new file mode 100644 index 0000000000..221d77dadf --- /dev/null +++ b/release/src/router/smartdns/.github/ISSUE_TEMPLATE/feature.md @@ -0,0 +1,20 @@ +--- +name: 需求建议 +about: 需求建议描述 +title: '' +labels: '' +assignees: '' + +--- + +**需求应用场景** +请描述需求应用的场景和方式。 + +**建议的方案** +实现上述场景建议的方案。 + +**设备信息** +1. 设备信息(CPU,厂家) + +2. 固件信息 + diff --git a/release/src/router/smartdns/.github/ISSUE_TEMPLATE/issue.md b/release/src/router/smartdns/.github/ISSUE_TEMPLATE/issue.md new file mode 100644 index 0000000000..5f505d4218 --- /dev/null +++ b/release/src/router/smartdns/.github/ISSUE_TEMPLATE/issue.md @@ -0,0 +1,29 @@ +--- +name: 问题报告 +about: 问题现象描述 +title: '' +labels: '' +assignees: '' + +--- + +**问题现象** +简要描述问题出现的现象 + +**运行环境** +1. 固件型号 + +2. 运营商 + +**重现步骤** +1. 上游DNS配置。 + +2. 访问的域名。 + + +**信息收集** +1. 将/var/log/smrtdns.log日志作为附件上传。 +2. 如进程异常,请将coredump功能开启,上传coredump信息文件。 +在自定义界面,开启设置->自定义设置->生成coredump配置,重现问题后提交coredump文件 +coredump文件在/tmp目录下 + diff --git a/release/src/router/smartdns/.gitignore b/release/src/router/smartdns/.gitignore new file mode 100644 index 0000000000..d9e7a1f1ca --- /dev/null +++ b/release/src/router/smartdns/.gitignore @@ -0,0 +1,4 @@ +.vscode +.o +.DS_Store +.swp. diff --git a/release/src/router/smartdns/LICENSE b/release/src/router/smartdns/LICENSE index dbbe355815..f288702d2f 100644 --- a/release/src/router/smartdns/LICENSE +++ b/release/src/router/smartdns/LICENSE @@ -1,21 +1,23 @@ - GNU AFFERO GENERAL PUBLIC LICENSE - Version 3, 19 November 2007 + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 - Copyright (C) 2007 Free Software Foundation, Inc. + Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble - The GNU Affero General Public License is a free, copyleft license for -software and other kinds of works, specifically designed to ensure -cooperation with the community in the case of network server software. + The GNU General Public License is a free, copyleft license for +software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, -our General Public Licenses are intended to guarantee your freedom to +the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free -software for all its users. +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you @@ -24,34 +26,44 @@ them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. - Developers that use our General Public Licenses protect your rights -with two steps: (1) assert copyright on the software, and (2) offer -you this License which gives you legal permission to copy, distribute -and/or modify the software. - - A secondary benefit of defending all users' freedom is that -improvements made in alternate versions of the program, if they -receive widespread use, become available for other developers to -incorporate. Many developers of free software are heartened and -encouraged by the resulting cooperation. However, in the case of -software used on network servers, this result may fail to come about. -The GNU General Public License permits making a modified version and -letting the public access it on a server without ever releasing its -source code to the public. - - The GNU Affero General Public License is designed specifically to -ensure that, in such cases, the modified source code becomes available -to the community. It requires the operator of a network server to -provide the source code of the modified version running there to the -users of that server. Therefore, public use of a modified version, on -a publicly accessible server, gives the public access to the source -code of the modified version. - - An older license, called the Affero General Public License and -published by Affero, was designed to accomplish similar goals. This is -a different license, not a version of the Affero GPL, but Affero has -released a new version of the Affero GPL which permits relicensing under -this license. + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. @@ -60,7 +72,7 @@ modification follow. 0. Definitions. - "This License" refers to version 3 of the GNU Affero General Public License. + "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. @@ -537,45 +549,35 @@ to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. - 13. Remote Network Interaction; Use with the GNU General Public License. - - Notwithstanding any other provision of this License, if you modify the -Program, your modified version must prominently offer all users -interacting with it remotely through a computer network (if your version -supports such interaction) an opportunity to receive the Corresponding -Source of your version by providing access to the Corresponding Source -from a network server at no charge, through some standard or customary -means of facilitating copying of software. This Corresponding Source -shall include the Corresponding Source for any work covered by version 3 -of the GNU General Public License that is incorporated pursuant to the -following paragraph. + 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed -under version 3 of the GNU General Public License into a single +under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, -but the work with which it is combined will remain governed by version -3 of the GNU General Public License. +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of -the GNU Affero General Public License from time to time. Such new versions -will be similar in spirit to the present version, but may differ in detail to +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU Affero General +Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the -GNU Affero General Public License, you may choose any version ever published +GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future -versions of the GNU Affero General Public License can be used, that proxy's +versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. @@ -633,29 +635,40 @@ the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, or + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. + GNU General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU General Public License + along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. - If your software can interact with users remotely through a computer -network, you should also make sure that it provides a way for users to -get its source. For example, if your program is a web application, its -interface could display a "Source" link that leads users to an archive -of the code. There are many ways you could offer source, and different -solutions will be better for different programs; see section 13 for the -specific requirements. + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU AGPL, see -. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/release/src/router/smartdns/Makefile b/release/src/router/smartdns/Makefile new file mode 100644 index 0000000000..461fbd5b3e --- /dev/null +++ b/release/src/router/smartdns/Makefile @@ -0,0 +1,47 @@ +# Copyright (C) 2018-2020 Ruilin Peng (Nick) . +# +# smartdns is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# smartdns is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +PKG_CONFIG := pkg-config +DESTDIR := +PREFIX := /usr +SBINDIR := $(PREFIX)/sbin +SYSCONFDIR := /etc +RUNSTATEDIR := /var/run +SYSTEMDSYSTEMUNITDIR := $(shell ${PKG_CONFIG} --variable=systemdsystemunitdir systemd) +SMARTDNS_SYSTEMD = systemd/smartdns.service + +.PHONY: all clean install SMARTDNS_BIN +all: SMARTDNS_BIN + +SMARTDNS_BIN: $(SMARTDNS_SYSTEMD) + $(MAKE) $(MFLAGS) -C src all + +$(SMARTDNS_SYSTEMD): systemd/smartdns.service.in + cp $< $@ + sed -i 's|@SBINDIR@|$(SBINDIR)|' $@ + sed -i 's|@SYSCONFDIR@|$(SYSCONFDIR)|' $@ + sed -i 's|@RUNSTATEDIR@|$(RUNSTATEDIR)|' $@ + +clean: + $(MAKE) $(MFLAGS) -C src clean + $(RM) $(SMARTDNS_SYSTEMD) + +install: SMARTDNS_BIN + install -v -m 0640 -D -t $(DESTDIR)$(SYSCONFDIR)/default etc/default/smartdns + install -v -m 0755 -D -t $(DESTDIR)$(SYSCONFDIR)/init.d etc/init.d/smartdns + install -v -m 0640 -D -t $(DESTDIR)$(SYSCONFDIR)/smartdns etc/smartdns/smartdns.conf + install -v -m 0755 -D -t $(DESTDIR)$(SBINDIR) src/smartdns + install -v -m 0644 -D -t $(DESTDIR)$(SYSTEMDSYSTEMUNITDIR) systemd/smartdns.service + diff --git a/release/src/router/smartdns/ReadMe.md b/release/src/router/smartdns/ReadMe.md index 39a60f9465..164179b37f 100644 --- a/release/src/router/smartdns/ReadMe.md +++ b/release/src/router/smartdns/ReadMe.md @@ -1,705 +1,672 @@ -# SmartDNS - -**[English](ReadMe_en.md)** - -![SmartDNS](doc/smartdns-banner.png) -SmartDNS是一个运行在本地的DNS服务器,SmartDNS接受本地客户端的DNS查询请求,从多个上游DNS服务器获取DNS查询结果,并将访问速度最快的结果返回给客户端,提高网络访问速度。 -同时支持指定特定域名IP地址,并高性匹配,达到过滤广告的效果。 -与dnsmasq的all-servers不同,smartdns返回的是访问速度最快的解析结果。 (详细差异请看[FAQ](#faq)) - -支持树莓派,openwrt,华硕路由器,windows等设备。 - -## 目录 - -1. [软件效果展示](#软件效果展示) -1. [特性](#特性) -1. [架构](#架构) -1. [使用](#使用) - 1. [下载配套安装包](#下载配套安装包) - 1. [标准Linux系统安装](#标准linux系统安装树莓派x86_64系统) - 1. [openwrt/LEDE](#openwrtlede) - 1. [华硕路由器原生固件/梅林固件](#华硕路由器原生固件梅林固件) - 1. [optware/entware](#optwareentware) - 1. [Windows 10 WSL安装/WSL ubuntu](#windows-10-wsl安装wsl-ubuntu) -1. [配置参数](#配置参数) -1. [捐助](#donate) -1. [FAQ](#faq) - -## 软件效果展示 - -**阿里DNS** -使用阿里DNS查询百度IP,并检测结果。 - -```shell -pi@raspberrypi:~/code/smartdns_build $ nslookup www.baidu.com 223.5.5.5 -Server: 223.5.5.5 -Address: 223.5.5.5#53 - -Non-authoritative answer: -www.baidu.com canonical name = www.a.shifen.com. -Name: www.a.shifen.com -Address: 180.97.33.108 -Name: www.a.shifen.com -Address: 180.97.33.107 - -pi@raspberrypi:~/code/smartdns_build $ ping 180.97.33.107 -c 2 -PING 180.97.33.107 (180.97.33.107) 56(84) bytes of data. -64 bytes from 180.97.33.107: icmp_seq=1 ttl=55 time=24.3 ms -64 bytes from 180.97.33.107: icmp_seq=2 ttl=55 time=24.2 ms - ---- 180.97.33.107 ping statistics --- -2 packets transmitted, 2 received, 0% packet loss, time 1001ms -rtt min/avg/max/mdev = 24.275/24.327/24.380/0.164 ms -pi@raspberrypi:~/code/smartdns_build $ ping 180.97.33.108 -c 2 -PING 180.97.33.108 (180.97.33.108) 56(84) bytes of data. -64 bytes from 180.97.33.108: icmp_seq=1 ttl=55 time=31.1 ms -64 bytes from 180.97.33.108: icmp_seq=2 ttl=55 time=31.0 ms - ---- 180.97.33.108 ping statistics --- -2 packets transmitted, 2 received, 0% packet loss, time 1001ms -rtt min/avg/max/mdev = 31.014/31.094/31.175/0.193 ms -``` - -**smartdns** -使用SmartDNS查询百度IP,并检测结果。 - -```shell -pi@raspberrypi:~/code/smartdns_build $ nslookup www.baidu.com -Server: 192.168.1.1 -Address: 192.168.1.1#53 - -Non-authoritative answer: -www.baidu.com canonical name = www.a.shifen.com. -Name: www.a.shifen.com -Address: 14.215.177.39 - -pi@raspberrypi:~/code/smartdns_build $ ping 14.215.177.39 -c 2 -PING 14.215.177.39 (14.215.177.39) 56(84) bytes of data. -64 bytes from 14.215.177.39: icmp_seq=1 ttl=56 time=6.31 ms -64 bytes from 14.215.177.39: icmp_seq=2 ttl=56 time=5.95 ms - ---- 14.215.177.39 ping statistics --- -2 packets transmitted, 2 received, 0% packet loss, time 1001ms -rtt min/avg/max/mdev = 5.954/6.133/6.313/0.195 ms - -``` - -从对比看出,smartdns找到访问www.baidu.com最快的IP地址,这样访问百度比阿里DNS速度快5倍。 - -## 特性 - -1. **多DNS上游服务器** - 支持配置多个上游DNS服务器,并同时进行查询,即使其中有DNS服务器异常,也不会影响查询。 - -1. **返回最快IP地址** - 支持从域名所属IP地址列表中查找到访问速度最快的IP地址,并返回给客户端,提高网络访问速度。 - -1. **支持多种查询协议** - 支持UDP,TCP,TLS, HTTPS查询,以及非53端口查询。 - -1. **特定域名IP地址指定** - 支持指定域名的IP地址,达到广告过滤效果,避免恶意网站的效果。 - -1. **域名高性能后缀匹配** - 支持域名后缀匹配模式,简化过滤配置,过滤20万条记录时间<1ms - -1. **域名分流** - 支持域名分流,不同类型的域名到不同的DNS服务器查询。 - -1. **Linux/Windows多平台支持** - 支持标准Linux系统(树莓派),openwrt系统各种固件,华硕路由器原生固件。以及支持Windows 10 WSL (Windows Subsystem for Linux)。 - -1. **支持IPV4, IPV6双栈** - 支持IPV4,IPV6网络,支持查询A, AAAA记录,支持双栈IP速度优化,并支持完全禁用IPV6 AAAA解析。 - -1. **高性能,占用资源少** - 多线程异步IO模式,cache缓存查询结果。 - -## 架构 - -![Architecture](doc/architecture.png) - -1. SmartDNS接收本地网络设备的DNS查询请求,如PC,手机的查询请求。 -2. SmartDNS将查询请求发送到多个上游DNS服务器,可采用标准UDP查询,非标准端口UDP查询,及TCP查询。 -3. 上游DNS服务器返回域名对应的Server IP地址列表。SmartDNS检测与本地网络访问速度最快的Server IP。 -4. 将访问速度最快的Server IP返回给本地客户端。 - -## 使用 - -### 下载配套安装包 - --------------- - -下载配套版本的SmartDNS安装包,对应安装包配套关系如下。 - -|系统 |安装包|说明 -|-----|-----|----- -|标准Linux系统(树莓派)| smartdns.xxxxxxxx.armhf.deb|支持树莓派Raspbian stretch,Debian 9系统。 -|标准Linux系统(Armbian arm64)| smartdns.xxxxxxxx.arm64.deb|支持ARM64的Debian stretch,Debian 9系统。 -|标准Linux系统(x86_64)| smartdns.xxxxxxxx.x86_64.tar.gz|支持x86_64 Linux 系统。 -|Windows 10 WSL (ubuntu)| smartdns.xxxxxxxx.x86_64.tar.gz|支持Windows 10 WSL ubuntu系统。 -|标准Linux系统(x86)| smartdns.xxxxxxxx.x86.tar.gz|支持x86系统。 -|华硕原生固件(optware)|smartdns.xxxxxxx.mipsbig.ipk|支持MIPS大端架构的系统,如RT-AC55U, RT-AC66U. -|华硕原生固件(optware)|smartdns.xxxxxxx.mipsel.ipk|支持MIPS小端架构的系统。 -|华硕原生固件(optware)|smartdns.xxxxxxx.arm.ipk|支持arm小端架构的系统,如RT-AC68U。 -|Padavan|smartdns.xxxxxxx.mipselsf.ipk|padavan固件。 -|openwrt 15.01|smartdns.xxxxxxxx.ar71xx.ipk|支持AR71XX MIPS系统。 -|openwrt 15.01|smartdns.xxxxxxxx.ramips_24kec.ipk|支持MT762X等小端路由器 -|openwrt 15.01(潘多拉)|smartdns.xxxxxxxx.mipsel_24kec_dsp.ipk|支持MT7620系列的潘多拉固件 -|openwrt 15.01(潘多拉)|smartdns.xxxxxxxx.mips_74kc_dsp2.ipk|支持AR71xx系列的潘多拉固件 -|openwrt 18.06|smartdns.xxxxxxxx.mips_24kc.ipk|支持AR71XX MIPS系统。 -|openwrt 18.06|smartdns.xxxxxxxx.mipsel_24kc.ipk|支持MT726X等小端路由器 -|openwrt 18.06|smartdns.xxxxxxxx.x86_64.ipk|支持x86_64路由器 -|openwrt 18.06|smartdns.xxxxxxxx.i386_pentium4.ipk|支持x86路由器 -|openwrt 18.06|smartdns.xxxxxxxxxxx.arm_cortex-a9.ipk|支持arm A9核心CPU的路由器 -|openwrt 18.06|smartdns.xxxxxxxxx.arm_cortex-a7_neon-vfpv4.ipk|支持arm A7核心CPU的路由器 -|openwrt LUCI|luci-app-smartdns.xxxxxxxxx.xxxx.all.ipk|openwrt管理统一界面 - -* openwrt系统CPU架构比较多,上述表格未列出所有支持系统,请查看CPU架构后下载。 -* merlin梅林固件理论和华硕固件一致,所以根据硬件类型安装相应的ipk包即可。(梅林暂时未验证,有问题提交issue) -* CPU架构可在路由器管理界面找到,查看方法: - 登录路由器,点击`System`->`Software`,点击`Configuration` Tab页面,在opkg安装源中可找到对应软件架构,下载路径中可找到,如下,架构为ar71xx - - ```shell - src/gz chaos_calmer_base http://downloads.openwrt.org/chaos_calmer/15.05/ar71xx/generic/packages/base - ``` - -* 或ssh登录系统后通过如下命令查询软件架构: - - * **openwrt系列命令** - - ```shell - opkg print_architecture - ``` - - * **optware系列命令** - - ```shell - ipkg print_architecture - ``` - - * **debian系列命令** - - ```shell - dpkg --print-architecture - ``` - - * **例如** - - 下面的查询结果`arch ar71xx 10`表示ar71xx系列架构,选择`smartdns.xxxxxxxx.ar71xx.ipk`安装包 - - ```shell - root@OpenWrt:~# opkg print_architecture - arch all 1 - arch noarch 1 - arch ar71xx 10 - ``` - -* **请在Release页面下载:[点击此处下载](https://github.com/pymumu/smartdns/releases)** - -```shell -https://github.com/pymumu/smartdns/releases -``` - -* 各种设备的安装步骤,请参考后面的章节。 - -### 标准Linux系统安装/树莓派/X86_64系统 - --------------- - -1. 安装 - - 下载配套安装包`smartdns.xxxxxxxx.armhf.deb`,并上传到Linux系统中。 执行如下命令安装 - - ```shell - dpkg -i smartdns.xxxxxxxx.armhf.deb - ``` - - x86系统下载配套安装包`smartdns.xxxxxxxx.x86-64.tar.gz`, 并上传到Linux系统中。 执行如下命令安装 - - ```shell - tar zxf smartdns.xxxxxxxx.x86-64.tar.gz - cd smartdns - chmod +x ./install - ./install -i - ``` - -1. 修改配置 - - 安装完成后,可配置smartdns的上游服务器信息。具体配置参数参考`配置参数`说明。 - 一般情况下,只需要增加`server [IP]:port`, `server-tcp [IP]:port`配置项, - 尽可能配置多个上游DNS服务器,包括国内外的服务器。配置参数请查看`配置参数`章节。 - - ```shell - vi /etc/smartdns/smartdns.conf - ``` - -1. 启动服务 - - ```shell - systemctl enable smartdns - systemctl start smartdns - ``` - -1. 将DNS请求转发的SmartDNS解析。 - - 修改本地路由器的DNS服务器,将DNS服务器配置为SmartDNS。 - * 登录到本地网络的路由器中,配置树莓派分配静态IP地址。 - * 修改WAN口或者DHCP DNS为树莓派IP地址。 - 注意: - I. 每款路由器配置方法不尽相同,请百度搜索相关的配置方法。 - II.华为等路由器可能不支持配置DNS为本地IP,请修改PC端,手机端DNS服务器为树莓派IP。 - -1. 检测服务是否配置成功。 - - 使用`nslookup -querytype=ptr 0.0.0.0`查询域名 - 看命令结果中的`name`项目是否显示为`smartdns`或`主机名`,如`smartdns`则表示生效 - - ```shell - pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr 0.0.0.0 - Server: 192.168.1.1 - Address: 192.168.1.1#53 - - Non-authoritative answer: - 0.0.0.0.in-addr.arpa name = smartdns. - ``` - -### openwrt/LEDE - --------------- - -1. 安装 - - 将软件使用winscp上传到路由器的/root目录,执行如下命令安装 - - ```shell - opkg install smartdns.xxxxxxxx.xxxx.ipk - opkg install luci-app-smartdns.xxxxxxxx.xxxx.all.ipk - ``` - -1. 修改配置 - - 登录openwrt管理页面,打开`Services`->`SmartDNS`进行配置。 - * 在`Upstream Servers`增加上游DNS服务器配置,建议配置多个国内外DNS服务器。 - * 在`Domain Address`指定特定域名的IP地址,可用于广告屏蔽。 - -1. 启用服务 - - SmartDNS服务生效方法有两种,`一种是直接作为主DNS服务`;`另一种是作为dnsmasq的上游`。 - 默认情况下,SmartDNS采用第一种方式。如下两种方式根据需求选择即可。 - -1. 启用方法一:作为主DNS(默认方案) - - * **启用smartdns的53端口重定向** - - 登录路由器,点击`Services`->`SmartDNS`->`redirect`,选择`重定向53端口到SmartDNS`启用53端口转发。 - - * **检测转发服务是否配置成功** - - 使用`nslookup -querytype=ptr 0.0.0.0`查询域名 - 看命令结果中的`name`项目是否显示为`smartdns`或`主机名`,如`smartdns`则表示生效 - - ```shell - pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr 0.0.0.0 - Server: 192.168.1.1 - Address: 192.168.1.1#53 - - Non-authoritative answer: - 0.0.0.0.in-addr.arpa name = smartdns. - ``` - - * **界面提示重定向失败** - - * 检查iptable,ip6table命令是否正确安装。 - * openwrt 15.01系统不支持IPV6重定向,如网络需要支持IPV6,请将DNSMASQ上游改为smartdns,或者将smartdns的端口改为53,并停用dnsmasq。 - * LEDE之后系统,请安装IPV6的nat转发驱动。点击`system`->`Software`,点击`update lists`更新软件列表后,安装`ip6tables-mod-nat` - * 使用如下命令检查路由规则是否生效。 - - ```shell - iptables -t nat -L PREROUTING | grep REDIRECT - ``` - - * 如转发功能不正常,请使用方法二:作为DNSMASQ的上游。 - -1. 方法二:作为DNSMASQ的上游 - - * **将dnsmasq的请求发送到smartdns** - - 登录路由器,点击`Services`->`SmartDNS`->`redirect`,选择`作为dnsmasq的上游服务器`设置dnsmasq的上游服务器为smartdns。 - - * **检测上游服务是否配置成功** - - * 方法一:使用`nslookup -querytype=ptr 0.0.0.0`查询域名 - 看命令结果中的`name`项目是否显示为`smartdns`或`主机名`,如`smartdns`则表示生效 - - ```shell - pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr 0.0.0.0 - Server: 192.168.1.1 - Address: 192.168.1.1#53 - - Non-authoritative answer: - 0.0.0.0.in-addr.arpa name = smartdns. - ``` - - * 方法二:使用`nslookup`查询`www.baidu.com`域名,查看结果中百度的IP地址是否`只有一个`,如有多个IP地址返回,则表示未生效,请多尝试几个域名检查。 - - ```shell - pi@raspberrypi:~ $ nslookup www.baidu.com 192.168.1.1 - Server: 192.168.1.1 - Address: 192.168.1.1#53 - - Non-authoritative answer: - www.baidu.com canonical name = www.a.shifen.com. - Name: www.a.shifen.com - Address: 14.215.177.38 - ``` - -1. 启动服务 - - 勾选配置页面中的`Enable(启用)`来启动SmartDNS - -1. 注意: - - * 如已经安装chinaDNS,建议将chinaDNS的上游配置为SmartDNS。 - * SmartDNS默认情况,将53端口的请求转发到SmartDNS的本地端口,由`Redirect`配置选项控制。 - -### 华硕路由器原生固件/梅林固件 - --------------- - -说明:梅林固件派生自华硕固件,理论上可以直接使用华硕配套的安装包使用。但目前未经验证,如有问题,请提交issue。 - -1. 准备 - - 在使用此软件时,需要确认路由器是否支持U盘,并准备好U盘一个。 - -1. 启用SSH登录 - - 登录管理界面,点击`系统管理`->点击`系统设置`,配置`Enable SSH`为`Lan Only`。 - SSH登录用户名密码与管理界面相同。 - -1. 下载`Download Master` - - 在管理界面点击`USB相关应用`->点击`Download Master`下载。 - 下载完成后,启用`Download Master`,如果不需要下载功能,此处可以卸载`Download Master`,但要保证卸载前Download Master是启用的。 - -1. 安装SmartDNS - - 将软件使用winscp上传到路由器的`/tmp/mnt/sda1`目录。(或网上邻居复制到sda1共享目录) - - ```shell - ipkg install smartdns.xxxxxxx.mipsbig.ipk - ``` - -1. 重启路由器生效服务 - - 待路由器启动后,使用`nslookup -querytype=ptr 0.0.0.0`查询域名 - 看命令结果中的`name`项目是否显示为`smartdns`或`主机名`,如`smartdns`则表示生效 - - ```shell - pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr 0.0.0.0 - Server: 192.168.1.1 - Address: 192.168.1.1#53 - - Non-authoritative answer: - 0.0.0.0.in-addr.arpa name = smartdns. - ``` - -1. 额外说明 - - 上述过程,smartdns将安装到U盘根目录,采用optware的模式运行。 - 其目录结构如下: (此处仅列出smartdns相关文件) - - ```shell - U盘 - └── asusware.mipsbig - ├── bin - ├── etc - | ├── smartdns - | | └── smartdns.conf - | └── init.d - | └── S50smartdns - ├── lib - ├── sbin - ├── usr - | └── sbin - | └── smartdns - .... - ``` - - 如要修改配置,可以ssh登录路由器,使用vi命令修改 - - ```shell - vi /opt/etc/smartdns/smartdns.conf - ``` - - 也可以通过网上邻居修改,网上邻居共享目录`sda1`看不到`asusware.mipsbig`目录,但可以直接在`文件管理器`中输入`asusware.mipsbig\etc\init.d`访问 - - ```shell - \\192.168.1.1\sda1\asusware.mipsbig\etc\init.d - ``` - -### optware/entware - --------------- - -1. 准备 - - 在使用此软件时,需要确认路由器是否支持U盘,并准备好U盘一个。 - -1. 安装SmartDNS - - 将软件使用winscp上传到路由器的`/tmp`目录。 - - ```shell - ipkg install smartdns.xxxxxxx.mipsbig.ipk - ``` - -1. 修改smartdns配置 - - ```shell - vi /opt/etc/smartdns/smartdns.conf - ``` - - 另外,如需支持IPV6,可设置工作模式为`2`,将dnsmasq的DNS服务禁用,smartdns为主用DNS服务器。将文件`/opt/etc/smartdns/smartdns-opt.conf`,中的`SMARTDNS_WORKMODE`修改为2. - - ```shell - SMARTDNS_WORKMODE="2" - ``` - -1. 重启路由器生效服务 - - 待路由器启动后,使用`nslookup -querytype=ptr 0.0.0.0`查询域名 - 看命令结果中的`name`项目是否显示为`smartdns`或`主机名`,如`smartdns`则表示生效 - - ```shell - pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr 0.0.0.0 - Server: 192.168.1.1 - Address: 192.168.1.1#53 - - Non-authoritative answer: - 0.0.0.0.in-addr.arpa name = smartdns. - ``` - - 注意:若服务没有自动启动,则需要设置optwre/entware自动启动,具体方法参考optware/entware的文档。 - -### Windows 10 WSL安装/WSL ubuntu - --------------- - -1. 安装Windows 10 WSL ubuntu系统 - - 安装Windows 10 WSL运行环境,发行版本选择ubuntu系统。安装步骤请参考[WSL安装说明](https://docs.microsoft.com/en-us/windows/wsl/install-win10) - -1. 安装smartdns - - 下载安装包`smartdns.xxxxxxxx.x86_64.tar.gz`,并解压到D盘根目录。解压后目录如下: - - ```shell - D:\SMARTDNS - ├─etc - │ ├─default - │ ├─init.d - │ └─smartdns - ├─package - │ └─windows - ├─src - └─systemd - - ``` - - 双击`D:\smartdns\package\windows`目录下的`install.bat`进行安装。要求输入密码时,请输入`WLS ubuntu`的密码。 - -1. 修改配置 - - 记事本打开`D:\smartdns\etc\smartdns`目录中的`smartdns.conf`配置文件配置smartdns。具体配置参数参考`配置参数`说明。 - 一般情况下,只需要增加`server [IP]:port`, `server-tcp [IP]:port`配置项, - 尽可能配置多个上游DNS服务器,包括国内外的服务器。配置参数请查看`配置参数`章节。 - -1. 重新加载配置 - - 双击`D:\smartdns\package\windows`目录下的`reload.bat`进行安装。要求输入密码时,请输入`WLS ubuntu`的密码。 - -1. 将DNS请求转发的SmartDNS解析。 - - 将Windows的默认DNS服务器修改为`127.0.0.1`,具体步骤参考[IP配置](https://support.microsoft.com/zh-cn/help/15089/windows-change-tcp-ip-settings) - -1. 检测服务是否配置成功。 - - 使用`nslookup -querytype=ptr 0.0.0.0`查询域名 - 看命令结果中的`name`项目是否显示为`smartdns`或`主机名`,如`smartdns`则表示生效 - - ```shell - pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr 0.0.0.0 - Server: 192.168.1.1 - Address: 192.168.1.1#53 - - Non-authoritative answer: - 0.0.0.0.in-addr.arpa name = smartdns. - ``` - -## 配置参数 - -|参数| 功能 |默认值|配置值|例子| -|--|--|--|--|--| -|server-name|DNS服务器名称|操作系统主机名/smartdns|符合主机名规格的字符串|server-name smartdns -|bind|DNS监听端口号|[::]:53|可绑定多个端口
`IP:PORT`: 服务器IP,端口号。
`[-group]`: 请求时使用的DNS服务器组。
`[-no-rule-addr]`:跳过address规则。
`[-no-rule-nameserver]`:跳过Nameserver规则。
`[-no-rule-ipset]`:跳过Ipset规则。
`[no-rule-soa]`:跳过SOA(#)规则.
`[no-dualstack-selection]`:停用双栈测速。
`[-no-speed-check]`:停用测速。
`[-no-cache]`:停止缓存|bind :53 -|bind|TCP DNS监听端口号|[::]:53|可绑定多个端口
`IP:PORT`: 服务器IP,端口号。
`[-group]`: 请求时使用的DNS服务器组。
`[-no-rule-addr]`:跳过address规则。
`[-no-rule-nameserver]`:跳过Nameserver规则。
`[-no-rule-ipset]`:跳过Ipset规则。
`[no-rule-soa]`:跳过SOA(#)规则.
`[no-dualstack-selection]`:停用双栈测速。
`[-no-speed-check]`:停用测速。
`[-no-cache]`:停止缓存|bind-tcp :53 -|cache-size|域名结果缓存个数|512|数字|cache-size 512 -|tcp-idle-time|TCP链接空闲超时时间|120|数字|tcp-idle-time 120 -|rr-ttl|域名结果TTL|远程查询结果|大于0的数字|rr-ttl 600 -|rr-ttl-min|允许的最小TTL值|远程查询结果|大于0的数字|rr-ttl-min 60 -|rr-ttl-max|允许的最大TTL值|远程查询结果|大于0的数字|rr-ttl-max 600 -|log-level|设置日志级别|error|fatal,error,warn,notice,info,debug|log-level error -|log-file|日志文件路径|/var/log/smartdns.log|路径|log-file /var/log/smartdns.log -|log-size|日志大小|128K|数字+K,M,G|log-size 128K -|log-num|日志归档个数|2|数字|log-num 2 -|audit-enable|设置审计启用|no|[yes\|no]|audit-enable yes -|audit-file|审计文件路径|/var/log/smartdns-audit.log|路径|audit-file /var/log/smartdns-audit.log -|audit-size|审计大小|128K|数字+K,M,G|audit-size 128K -|audit-num|审计归档个数|2|数字|audit-num 2 -|conf-file|附加配置文件|无|文件路径|conf-file /etc/smartdns/smartdns.more.conf -|server|上游UDP DNS|无|可重复
`[ip][:port]`:服务器IP,端口可选。
`[-blacklist-ip]`:blacklist-ip参数指定使用blacklist-ip配置IP过滤结果。
`[-whitelist-ip]`:whitelist-ip参数指定仅接受whitelist-ip中配置IP范围。
`[-group [group] ...]`:DNS服务器所属组,比如office, foreign,和nameserver配套使用。
`[-exclude-default-group]`:将DNS服务器从默认组中排除| server 8.8.8.8:53 -blacklist-ip -group g1 -|server-tcp|上游TCP DNS|无|可重复
`[ip][:port]`:服务器IP,端口可选。
`[-blacklist-ip]`:blacklist-ip参数指定使用blacklist-ip配置IP过滤结果。
`[-whitelist-ip]`:whitelist-ip参数指定仅接受whitelist-ip中配置IP范围。
`[-group [group] ...]`:DNS服务器所属组,比如office, foreign,和nameserver配套使用。
`[-exclude-default-group]`:将DNS服务器从默认组中排除| server-tcp 8.8.8.8:53 -|server-tls|上游TLS DNS|无|可重复
`[ip][:port]`:服务器IP,端口可选。
`[-spki-pin [sha256-pin]]`: TLS合法性校验SPKI值,base64编码的sha256 SPKI pin值
`[-host-name]`:TLS SNI名称。
`[-tls-host-verify]`: TLS证书主机名校验。
`[-blacklist-ip]`:blacklist-ip参数指定使用blacklist-ip配置IP过滤结果。
`[-whitelist-ip]`:whitelist-ip参数指定仅接受whitelist-ip中配置IP范围。
`[-group [group] ...]`:DNS服务器所属组,比如office, foreign,和nameserver配套使用。
`[-exclude-default-group]`:将DNS服务器从默认组中排除| server-tls 8.8.8.8:853 -|server-https|上游HTTPS DNS|无|可重复
`https://[host][:port]/path`:服务器IP,端口可选。
`[-spki-pin [sha256-pin]]`: TLS合法性校验SPKI值,base64编码的sha256 SPKI pin值
`[-host-name]`:TLS SNI名称
`[-http-host]`:http协议头主机名。
`[-tls-host-verify]`: TLS证书主机名校验。
`[-blacklist-ip]`:blacklist-ip参数指定使用blacklist-ip配置IP过滤结果。
`[-whitelist-ip]`:whitelist-ip参数指定仅接受whitelist-ip中配置IP范围。
`[-group [group] ...]`:DNS服务器所属组,比如office, foreign,和nameserver配套使用。
`[-exclude-default-group]`:将DNS服务器从默认组中排除| server-https https://cloudflare-dns.com/dns-query -|speed-check-mode|测速模式选择|无|[ping\|tcp:[80]\|none]|speed-check-mode ping,tcp:80 -|address|指定域名IP地址|无|address /domain/[ip\|-\|-4\|-6\|#\|#4\|#6]
`-`表示忽略
`#`表示返回SOA
`4`表示IPV4
`6`表示IPV6| address /www.example.com/1.2.3.4 -|nameserver|指定域名使用server组解析|无|nameserver /domain/[group\|-], `group`为组名,`-`表示忽略此规则,配套server中的`-group`参数使用| nameserver /www.example.com/office -|ipset|域名IPSET|None|ipset /domain/[ipset\|-], `-`表示忽略|ipset /www.example.com/pass -|ipset-timeout|设置IPSET超时功能启用|auto|[yes]|ipset-timeout yes -|bogus-nxdomain|假冒IP地址过滤|无|[ip/subnet],可重复| bogus-nxdomain 1.2.3.4/16 -|ignore-ip|忽略IP地址|无|[ip/subnet],可重复| ignore-ip 1.2.3.4/16 -|whitelist-ip|白名单IP地址|无|[ip/subnet],可重复| whitelist-ip 1.2.3.4/16 -|blacklist-ip|黑名单IP地址|无|[ip/subnet],可重复| blacklist-ip 1.2.3.4/16 -|force-AAAA-SOA|强制AAAA地址返回SOA|no|[yes\|no]|force-AAAA-SOA yes -|prefetch-domain|域名预先获取功能|no|[yes\|no]|prefetch-domain yes -|dualstack-ip-selection|双栈IP优选|no|[yes\|no]|dualstack-ip-selection yes -|dualstack-ip-selection-threshold|双栈IP优选阈值|30ms|毫秒|dualstack-ip-selection-threshold [0-1000] - -## FAQ - -1. SmartDNS和DNSMASQ有什么区别 - SMARTDNS在设计上并不是替换DNSMASQ的,SMARTDNS主要功能集中在DNS解析增强上,增强部分有: - * 多上游服务器并发请求,对结果进行测速后,返回最佳结果; - * address,ipset域名匹配采用高效算法,查询匹配更加快速高效,路由器设备依然高效。 - * 域名匹配支持忽略特定域名,可单独匹配IPv4, IPV6,支持多样化定制。 - * 针对广告屏蔽功能做增强,返回SOA,屏蔽广告效果更佳; - * IPV4,IPV6双栈IP优选机制,在双网情况下,选择最快的网络通讯。 - * 支持最新的TLS, HTTPS协议,提供安全的DNS查询能力。 - * ECS支持,是查询结果更佳准确。 - * IP黑名单,忽略IP机制,使域名查询更佳准确。 - * 域名预查询,访问常用网站更加快速。 - * 域名TTL可指定,使访问更快速。 - * 高速缓存机制,使访问更快速。 - * 异步日志,审计机制,在记录信息的同时不影响DNS查询性能。 - * 域名组(group)机制,特定域名使用特定上游服务器组查询,避免隐私泄漏。 - * 第二DNS支持自定义更多行为。 - -1. 如何配置上游服务器最佳。 - smartdns有测速机制,在配置上游服务器时,建议配置多个上游DNS服务器,包含多个不同区域的服务器,但总数建议在10个左右。推荐配置 - * 运营商DNS。 - * 国内公共DNS,如`119.29.29.29`, `223.5.5.5`。 - * 国外公共DNS,如`8.8.8.8`, `8.8.4.4`。 - -1. 如何启用审计日志 - 审计日志记录客户端请求的域名,记录信息包括,请求时间,请求IP,请求域名,请求类型,如果要启用审计日志,在配置界面配置`audit-enable yes`启用,`audit-size`, `audit-file`, `audit-num`分别配置审计日志文件大小,审计日志文件路径,和审计日志文件个数。审计日志文件将会压缩存储以节省空间。 - -1. 如何避免隐私泄漏 - smartdns默认情况下,会将请求发送到所有配置的DNS服务器,若上游DNS服务器使用DNS,或记录日志,将会导致隐私泄漏。为避免隐私泄漏,请尽量: - * 配置使用可信的DNS服务器。 - * 优先使用TLS查询。 - * 设置上游DNS服务器组。 - -1. 如何屏蔽广告 - smartdns具备高性能域名匹配算法,通过域名方式过滤广告非常高效,如要屏蔽广告,只需要配置类似如下记录即可,如,屏蔽`*.ad.com`,则配置: - - ```sh - address /ad.com/# - ``` - - 域名的使后缀模式,过滤*.ad.com,`#`表示返回SOA,使屏蔽广告更加高效,如果要单独屏蔽IPV4, 或IPV6, 在`#`后面增加数字,如`#4`表示对IPV4生效。若想忽略特定子域名的屏蔽,可配置如下,如忽略`pass.ad.com`,可配置如下: - - ```sh - address /pass.ad.com/- - ``` - -1. 如何使用DNS查询分流 - 某些情况下,需要将有些域名使用特定的DNS服务器来查询来做到DNS分流。比如。 - - ```sh - .home -> 192.168.1.1 - .office -> 10.0.0.1 - ``` - - .home 结尾的域名发送到192.168.1.1解析 - .office 结尾的域名发送到10.0.0.1解析 - 其他域名采用默认的模式解析。 - 这种情况的分流配置如下: - - ```sh - #配置上游,用-group指定组名,用-exclude-default-group将服务器从默认组中排除。 - server 192.168.1.1 -group home -exclude-default-group - server 10.0.0.1 -group office -exclude-default-group - server 8.8.8.8 - - #配置解析的域名 - nameserver /.home/home - nameserver /.office/office - ``` - - 通过上述配置即可实现DNS解析分流,如果需要实现按请求端端口分流,可以配置第二DNS服务器,bind配置增加--group参数指定分流名称。 - - ```sh - bind :7053 -group office - bind :8053 -group home - ``` - -1. IPV4, IPV6双栈IP优选功能如何使用 - 目前IPV6已经开始普及,但IPV6网络在速度上,某些情况下还不如IPV4,为在双栈网络下获得较好的体验,smartdns提供来双栈IP优选机制,同一个域名,若IPV4的速度远快与IPV6,那么smartdns就会阻止IPV6的解析,让PC使用IPV4访问,具体配置文件通过`dualstack-ip-selection yes`启用此功能,通过`dualstack-ip-selection-threshold [time]`来修改阈值。如果要完全禁止IPV6 AAAA记录解析,可设置`force-AAAA-SOA yes`。 - -1. 如何提高cache效率,加快访问速度 - smartdns提供了域名缓存机制,对查询的域名,进行缓存,缓存时间符合DNS TTL规范。为提高缓存命中率,可采用如下措施: - * 适当增大cache的记录数 - 通过`cache-size`来设置缓存记录数。 - 查询压力大的环境下,并且有内存大的机器的情况下,可适当调大。 - - * 适当设置最小TTL值 - 通过`rr-ttl-min`将最低DNS TTL时间设置为一个合理值,延长缓存时间。 - 建议是超时时间设置在10~30分钟,避免服务器域名变化时,查询到失效域名。 - - * 开启域名预获取功能 - 通过`prefetch-domain yes`来启用域名预先获取功能,提高查询命中率。 - 配合上述ttl超时时间,smartdns将在域名ttl即将超时使,再次发送查询请求,并缓存查询结果供后续使用。频繁访问的域名将会持续缓存。此功能将在空闲时消耗更多的CPU。 - -1. 第二DNS如何自定义更多行为 - 第二DNS可以作为其他DNS服务器的上游,提供更多的查询行为,通过bind配置支持可以绑定多个端口,不同端口可设置不同的标志,实现不同的功能,如 - - ```sh - # 绑定 6053端口,6053端口的请求将采用配置office组的上游查询,且不对结果进行测速,忽略address的配置地址。 - bind [::]:6053 -no-speed-check -group office -no-rule-addr - ``` - -## 编译 - -smartdns包含了编译软件包的脚本,支持编译luci,debian,openwrt,optare安装包,可执行`package/build-pkg.sh`编译。 - -## Donate - -如果你觉得此项目对你有帮助,请捐助我们,以使项目能持续发展,更加完善。 - -### PayPal - -[![Support via PayPal](https://cdn.rawgit.com/twolfson/paypal-github-button/1.0.0/dist/button.svg)](https://paypal.me/PengNick/) - -### Alipay 支付宝 - -![alipay](doc/alipay_donate.jpg) - -### Wechat 微信 - -![wechat](doc/wechat_donate.jpg) - -## 开源声明 - -Smartdns 基于GPL V3协议开源。 +# SmartDNS + +**[English](ReadMe_en.md)** + +![SmartDNS](doc/smartdns-banner.png) +SmartDNS是一个运行在本地的DNS服务器,SmartDNS接受本地客户端的DNS查询请求,从多个上游DNS服务器获取DNS查询结果,并将访问速度最快的结果返回给客户端,提高网络访问速度。 +同时支持指定特定域名IP地址,并高性匹配,达到过滤广告的效果。 +与dnsmasq的all-servers不同,smartdns返回的是访问速度最快的解析结果。 (详细差异请看[FAQ](#faq)) + +支持树莓派,openwrt,华硕路由器,windows等设备。 + +## 目录 + +1. [软件效果展示](#软件效果展示) +1. [特性](#特性) +1. [架构](#架构) +1. [使用](#使用) + 1. [下载配套安装包](#下载配套安装包) + 1. [标准Linux系统安装](#标准linux系统安装树莓派x86_64系统) + 1. [openwrt/LEDE](#openwrtlede) + 1. [华硕路由器原生固件/梅林固件](#华硕路由器原生固件梅林固件) + 1. [optware/entware](#optwareentware) + 1. [Windows 10 WSL安装/WSL ubuntu](#windows-10-wsl安装wsl-ubuntu) +1. [配置参数](#配置参数) +1. [捐助](#donate) +1. [FAQ](#faq) + +## 软件效果展示 + +**阿里DNS** +使用阿里DNS查询百度IP,并检测结果。 + +```shell +pi@raspberrypi:~/code/smartdns_build $ nslookup www.baidu.com 223.5.5.5 +Server: 223.5.5.5 +Address: 223.5.5.5#53 + +Non-authoritative answer: +www.baidu.com canonical name = www.a.shifen.com. +Name: www.a.shifen.com +Address: 180.97.33.108 +Name: www.a.shifen.com +Address: 180.97.33.107 + +pi@raspberrypi:~/code/smartdns_build $ ping 180.97.33.107 -c 2 +PING 180.97.33.107 (180.97.33.107) 56(84) bytes of data. +64 bytes from 180.97.33.107: icmp_seq=1 ttl=55 time=24.3 ms +64 bytes from 180.97.33.107: icmp_seq=2 ttl=55 time=24.2 ms + +--- 180.97.33.107 ping statistics --- +2 packets transmitted, 2 received, 0% packet loss, time 1001ms +rtt min/avg/max/mdev = 24.275/24.327/24.380/0.164 ms +pi@raspberrypi:~/code/smartdns_build $ ping 180.97.33.108 -c 2 +PING 180.97.33.108 (180.97.33.108) 56(84) bytes of data. +64 bytes from 180.97.33.108: icmp_seq=1 ttl=55 time=31.1 ms +64 bytes from 180.97.33.108: icmp_seq=2 ttl=55 time=31.0 ms + +--- 180.97.33.108 ping statistics --- +2 packets transmitted, 2 received, 0% packet loss, time 1001ms +rtt min/avg/max/mdev = 31.014/31.094/31.175/0.193 ms +``` + +**smartdns** +使用SmartDNS查询百度IP,并检测结果。 + +```shell +pi@raspberrypi:~/code/smartdns_build $ nslookup www.baidu.com +Server: 192.168.1.1 +Address: 192.168.1.1#53 + +Non-authoritative answer: +www.baidu.com canonical name = www.a.shifen.com. +Name: www.a.shifen.com +Address: 14.215.177.39 + +pi@raspberrypi:~/code/smartdns_build $ ping 14.215.177.39 -c 2 +PING 14.215.177.39 (14.215.177.39) 56(84) bytes of data. +64 bytes from 14.215.177.39: icmp_seq=1 ttl=56 time=6.31 ms +64 bytes from 14.215.177.39: icmp_seq=2 ttl=56 time=5.95 ms + +--- 14.215.177.39 ping statistics --- +2 packets transmitted, 2 received, 0% packet loss, time 1001ms +rtt min/avg/max/mdev = 5.954/6.133/6.313/0.195 ms + +``` + +从对比看出,smartdns找到访问www.baidu.com最快的IP地址,这样访问百度比阿里DNS速度快5倍。 + +## 特性 + +1. **多DNS上游服务器** + 支持配置多个上游DNS服务器,并同时进行查询,即使其中有DNS服务器异常,也不会影响查询。 + +1. **返回最快IP地址** + 支持从域名所属IP地址列表中查找到访问速度最快的IP地址,并返回给客户端,提高网络访问速度。 + +1. **支持多种查询协议** + 支持UDP,TCP,TLS, HTTPS查询,以及非53端口查询。 + +1. **特定域名IP地址指定** + 支持指定域名的IP地址,达到广告过滤效果,避免恶意网站的效果。 + +1. **域名高性能后缀匹配** + 支持域名后缀匹配模式,简化过滤配置,过滤20万条记录时间<1ms + +1. **域名分流** + 支持域名分流,不同类型的域名到不同的DNS服务器查询。 + +1. **Linux/Windows多平台支持** + 支持标准Linux系统(树莓派),openwrt系统各种固件,华硕路由器原生固件。以及支持Windows 10 WSL (Windows Subsystem for Linux)。 + +1. **支持IPV4, IPV6双栈** + 支持IPV4,IPV6网络,支持查询A, AAAA记录,支持双栈IP速度优化,并支持完全禁用IPV6 AAAA解析。 + +1. **高性能,占用资源少** + 多线程异步IO模式,cache缓存查询结果。 + +## 架构 + +![Architecture](doc/architecture.png) + +1. SmartDNS接收本地网络设备的DNS查询请求,如PC,手机的查询请求。 +2. SmartDNS将查询请求发送到多个上游DNS服务器,可采用标准UDP查询,非标准端口UDP查询,及TCP查询。 +3. 上游DNS服务器返回域名对应的Server IP地址列表。SmartDNS检测与本地网络访问速度最快的Server IP。 +4. 将访问速度最快的Server IP返回给本地客户端。 + +## 使用 + +### 下载配套安装包 + +-------------- + +下载配套版本的SmartDNS安装包,对应安装包配套关系如下。 + +|系统 |安装包|说明 +|-----|-----|----- +|标准Linux系统(树莓派)| smartdns.xxxxxxxx.arm-debian-all.deb|支持树莓派Raspbian stretch,Debian 9系统。 +|标准Linux系统(Armbian arm64)| smartdns.xxxxxxxx.aarch64-debian-all.deb|支持ARM64的Debian stretch,Debian 9系统。 +|标准Linux系统(x86_64)| smartdns.xxxxxxxx.x86_64-linux-all.tar.gz|支持x86_64 Linux 系统。 +|Windows 10 WSL (ubuntu)| smartdns.xxxxxxxx.x86_64-linux-all.tar.gz|支持Windows 10 WSL ubuntu系统。 +|标准Linux系统(x86)| smartdns.xxxxxxxx.x86-linux-all.tar.gz|支持x86系统。 +|optware|smartdns.xxxxxxxx.mips-optware-all.ipk|支持MIPS大端架构的optware系统。 +|optware|smartdns.xxxxxxxx.mipsel-optware-all.ipk|支持MIPS小端架构的optware系统。 +|optware|smartdns.xxxxxxxx.arm-optware-all.ipk|支持arm小端架构的optware系统。 +|openwrt|smartdns.xxxxxxxx.mips-openwrt-all.ipk|支持MIPS大端架构的openwrt系统。 +|openwrt|smartdns.xxxxxxxx.mipsel-openwrt-all.ipk|支持MIPS小端架构的openwrt系统。 +|openwrt|smartdns.xxxxxxxx.arm-openwrt-all.ipk|支持arm小端架构的openwrt系统。 +|openwrt LUCI|luci-app-smartdns.xxxxxxxxx.all.ipk|openwrt管理界面。 +|openwrt LUCI|luci-app-smartdns.xxxxxxxxx.all-luci-compat-all|兼容版本openwrt管理界面, openwrt 18.xx及之前版本安装。 + +* 单独release的软件包为静态编译软件包,无外部依赖,但体积大。若需要小体积软件包,请自行编译或从openwrt/entware仓库获取。 +* 因静态编译,软件包未强制判断CPU架构,安装不正确的软件包将会导致服务无法启动,请获取正确的软件包。 + +* **请在Release页面下载:[点击此处下载](https://github.com/pymumu/smartdns/releases)** + +```shell +https://github.com/pymumu/smartdns/releases +``` + +* 各种设备的安装步骤,请参考后面的章节。 + +### 标准Linux系统安装/树莓派/X86_64系统 + +-------------- + +1. 安装 + + 下载配套安装包`smartdns.xxxxxxxx.arm-debian-all.deb`,并上传到Linux系统中。 执行如下命令安装 + + ```shell + dpkg -i smartdns.xxxxxxxx.arm-debian-all.deb + ``` + + x86系统下载配套安装包`smartdns.xxxxxxxx.x86_64-linux-all.tar.gz`, 并上传到Linux系统中。 执行如下命令安装 + + ```shell + tar zxf smartdns.xxxxxxxx.x86_64-linux-all.tar.gz + cd smartdns + chmod +x ./install + ./install -i + ``` + +1. 修改配置 + + 安装完成后,可配置smartdns的上游服务器信息。具体配置参数参考`配置参数`说明。 + 一般情况下,只需要增加`server [IP]:port`, `server-tcp [IP]:port`配置项, + 尽可能配置多个上游DNS服务器,包括国内外的服务器。配置参数请查看`配置参数`章节。 + + ```shell + vi /etc/smartdns/smartdns.conf + ``` + +1. 启动服务 + + ```shell + systemctl enable smartdns + systemctl start smartdns + ``` + +1. 将DNS请求转发的SmartDNS解析。 + + 修改本地路由器的DNS服务器,将DNS服务器配置为SmartDNS。 + * 登录到本地网络的路由器中,配置树莓派分配静态IP地址。 + * 修改WAN口或者DHCP DNS为树莓派IP地址。 + 注意: + I. 每款路由器配置方法不尽相同,请百度搜索相关的配置方法。 + II.华为等路由器可能不支持配置DNS为本地IP,请修改PC端,手机端DNS服务器为树莓派IP。 + +1. 检测服务是否配置成功。 + + 使用`nslookup -querytype=ptr smartdns`查询域名 + 看命令结果中的`name`项目是否显示为`smartdns`或`主机名`,如`smartdns`则表示生效 + + ```shell + pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr smartdns + Server: 192.168.1.1 + Address: 192.168.1.1#53 + + Non-authoritative answer: + smartdns name = smartdns. + ``` + +### openwrt + +-------------- + +1. 安装 + + 将软件使用winscp上传到路由器的/root目录,执行如下命令安装 + + ```shell + opkg install smartdns.xxxxxxxx.xxxx.ipk + opkg install luci-app-smartdns.xxxxxxxx.xxxx.all.ipk + ``` + + * 注意: 19.07之前的版本,请安装`luci-app-smartdns.xxxxxxxxx.all-luci-compat-all`界面。 + +1. 修改配置 + + 登录openwrt管理页面,打开`Services`->`SmartDNS`进行配置。 + * 在`Upstream Servers`增加上游DNS服务器配置,建议配置多个国内外DNS服务器。 + * 在`Domain Address`指定特定域名的IP地址,可用于广告屏蔽。 + +1. 启用服务 + + SmartDNS服务生效方法有两种,`一种是直接作为主DNS服务`;`另一种是作为dnsmasq的上游`。 + 默认情况下,SmartDNS采用第一种方式。如下两种方式根据需求选择即可。 + +1. 启用方法一:作为主DNS(默认方案) + + * **启用smartdns的53端口重定向** + + 登录路由器,点击`Services`->`SmartDNS`->`redirect`,选择`重定向53端口到SmartDNS`启用53端口转发。 + + * **检测转发服务是否配置成功** + + 使用`nslookup -querytype=ptr smartdns`查询域名 + 看命令结果中的`name`项目是否显示为`smartdns`或`主机名`,如`smartdns`则表示生效 + + ```shell + pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr smartdns + Server: 192.168.1.1 + Address: 192.168.1.1#53 + + Non-authoritative answer: + smartdns name = smartdns. + ``` + + * **界面提示重定向失败** + + * 检查iptable,ip6table命令是否正确安装。 + * openwrt 15.01系统不支持IPV6重定向,如网络需要支持IPV6,请将DNSMASQ上游改为smartdns,或者将smartdns的端口改为53,并停用dnsmasq。 + * LEDE之后系统,请安装IPV6的nat转发驱动。点击`system`->`Software`,点击`update lists`更新软件列表后,安装`ip6tables-mod-nat` + * 使用如下命令检查路由规则是否生效。 + + ```shell + iptables -t nat -L PREROUTING | grep REDIRECT + ``` + + * 如转发功能不正常,请使用方法二:作为DNSMASQ的上游。 + +1. 方法二:作为DNSMASQ的上游 + + * **将dnsmasq的请求发送到smartdns** + + 登录路由器,点击`Services`->`SmartDNS`->`redirect`,选择`作为dnsmasq的上游服务器`设置dnsmasq的上游服务器为smartdns。 + + * **检测上游服务是否配置成功** + + * 方法一:使用`nslookup -querytype=ptr smartdns`查询域名 + 看命令结果中的`name`项目是否显示为`smartdns`或`主机名`,如`smartdns`则表示生效 + + ```shell + pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr smartdns + Server: 192.168.1.1 + Address: 192.168.1.1#53 + + Non-authoritative answer: + smartdns name = smartdns. + ``` + + * 方法二:使用`nslookup`查询`www.baidu.com`域名,查看结果中百度的IP地址是否`只有一个`,如有多个IP地址返回,则表示未生效,请多尝试几个域名检查。 + + ```shell + pi@raspberrypi:~ $ nslookup www.baidu.com 192.168.1.1 + Server: 192.168.1.1 + Address: 192.168.1.1#53 + + Non-authoritative answer: + www.baidu.com canonical name = www.a.shifen.com. + Name: www.a.shifen.com + Address: 14.215.177.38 + ``` + +1. 启动服务 + + 勾选配置页面中的`Enable(启用)`来启动SmartDNS + +1. 注意: + + * 如已经安装chinaDNS,建议将chinaDNS的上游配置为SmartDNS。 + * SmartDNS默认情况,将53端口的请求转发到SmartDNS的本地端口,由`Redirect`配置选项控制。 + +### 华硕路由器原生固件/梅林固件 + +-------------- + +说明:梅林固件派生自华硕固件,理论上可以直接使用华硕配套的安装包使用。但目前未经验证,如有问题,请提交issue。 + +1. 准备 + + 在使用此软件时,需要确认路由器是否支持U盘,并准备好U盘一个。 + +1. 启用SSH登录 + + 登录管理界面,点击`系统管理`->点击`系统设置`,配置`Enable SSH`为`Lan Only`。 + SSH登录用户名密码与管理界面相同。 + +1. 下载`Download Master` + + 在管理界面点击`USB相关应用`->点击`Download Master`下载。 + 下载完成后,启用`Download Master`,如果不需要下载功能,此处可以卸载`Download Master`,但要保证卸载前Download Master是启用的。 + +1. 安装SmartDNS + + 将软件使用winscp上传到路由器的`/tmp/mnt/sda1`目录。(或网上邻居复制到sda1共享目录) + + ```shell + ipkg install smartdns.xxxxxxx.mipsbig.ipk + ``` + +1. 重启路由器生效服务 + + 待路由器启动后,使用`nslookup -querytype=ptr smartdns`查询域名 + 看命令结果中的`name`项目是否显示为`smartdns`或`主机名`,如`smartdns`则表示生效 + + ```shell + pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr smartdns + Server: 192.168.1.1 + Address: 192.168.1.1#53 + + Non-authoritative answer: + smartdns name = smartdns. + ``` + +1. 额外说明 + + 上述过程,smartdns将安装到U盘根目录,采用optware的模式运行。 + 其目录结构如下: (此处仅列出smartdns相关文件) + + ```shell + U盘 + └── asusware.mipsbig + ├── bin + ├── etc + | ├── smartdns + | | └── smartdns.conf + | └── init.d + | └── S50smartdns + ├── lib + ├── sbin + ├── usr + | └── sbin + | └── smartdns + .... + ``` + + 如要修改配置,可以ssh登录路由器,使用vi命令修改 + + ```shell + vi /opt/etc/smartdns/smartdns.conf + ``` + + 也可以通过网上邻居修改,网上邻居共享目录`sda1`看不到`asusware.mipsbig`目录,但可以直接在`文件管理器`中输入`asusware.mipsbig\etc\init.d`访问 + + ```shell + \\192.168.1.1\sda1\asusware.mipsbig\etc\init.d + ``` + +### optware/entware + +-------------- + +1. 准备 + + 在使用此软件时,需要确认路由器是否支持U盘,并准备好U盘一个。 + +1. 安装SmartDNS + + 将软件使用winscp上传到路由器的`/tmp`目录。 + + ```shell + ipkg install smartdns.xxxxxxx.mipsbig.ipk + ``` + +1. 修改smartdns配置 + + ```shell + vi /opt/etc/smartdns/smartdns.conf + ``` + + 另外,如需支持IPV6,可设置工作模式为`2`,将dnsmasq的DNS服务禁用,smartdns为主用DNS服务器。将文件`/opt/etc/smartdns/smartdns-opt.conf`,中的`SMARTDNS_WORKMODE`修改为2. + + ```shell + SMARTDNS_WORKMODE="2" + ``` + +1. 重启路由器生效服务 + + 待路由器启动后,使用`nslookup -querytype=ptr smartdns`查询域名 + 看命令结果中的`name`项目是否显示为`smartdns`或`主机名`,如`smartdns`则表示生效 + + ```shell + pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr smartdns + Server: 192.168.1.1 + Address: 192.168.1.1#53 + + Non-authoritative answer: + smartdns name = smartdns. + ``` + + 注意:若服务没有自动启动,则需要设置optwre/entware自动启动,具体方法参考optware/entware的文档。 + +### Windows 10 WSL安装/WSL ubuntu + +-------------- + +1. 安装Windows 10 WSL ubuntu系统 + + 安装Windows 10 WSL运行环境,发行版本选择ubuntu系统。安装步骤请参考[WSL安装说明](https://docs.microsoft.com/en-us/windows/wsl/install-win10) + +1. 安装smartdns + + 下载安装包`smartdns.xxxxxxxx.x86-linux-all.tar.gz`,并解压到D盘根目录。解压后目录如下: + + ```shell + D:\SMARTDNS + ├─etc + │ ├─default + │ ├─init.d + │ └─smartdns + ├─package + │ └─windows + ├─src + └─systemd + + ``` + + 双击`D:\smartdns\package\windows`目录下的`install.bat`进行安装。要求输入密码时,请输入`WLS ubuntu`的密码。 + +1. 修改配置 + + 记事本打开`D:\smartdns\etc\smartdns`目录中的`smartdns.conf`配置文件配置smartdns。具体配置参数参考`配置参数`说明。 + 一般情况下,只需要增加`server [IP]:port`, `server-tcp [IP]:port`配置项, + 尽可能配置多个上游DNS服务器,包括国内外的服务器。配置参数请查看`配置参数`章节。 + +1. 重新加载配置 + + 双击`D:\smartdns\package\windows`目录下的`reload.bat`进行安装。要求输入密码时,请输入`WLS ubuntu`的密码。 + +1. 将DNS请求转发的SmartDNS解析。 + + 将Windows的默认DNS服务器修改为`127.0.0.1`,具体步骤参考[IP配置](https://support.microsoft.com/zh-cn/help/15089/windows-change-tcp-ip-settings) + +1. 检测服务是否配置成功。 + + 使用`nslookup -querytype=ptr smartdns`查询域名 + 看命令结果中的`name`项目是否显示为`smartdns`或`主机名`,如`smartdns`则表示生效 + + ```shell + pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr smartdns + Server: 192.168.1.1 + Address: 192.168.1.1#53 + + Non-authoritative answer: + smartdns name = smartdns. + ``` + +## 配置参数 + +|参数| 功能 |默认值|配置值|例子| +|--|--|--|--|--| +|server-name|DNS服务器名称|操作系统主机名/smartdns|符合主机名规格的字符串|server-name smartdns +|bind|DNS监听端口号|[::]:53|可绑定多个端口
`IP:PORT`: 服务器IP,端口号。
`[-group]`: 请求时使用的DNS服务器组。
`[-no-rule-addr]`:跳过address规则。
`[-no-rule-nameserver]`:跳过Nameserver规则。
`[-no-rule-ipset]`:跳过Ipset规则。
`[no-rule-soa]`:跳过SOA(#)规则.
`[no-dualstack-selection]`:停用双栈测速。
`[-no-speed-check]`:停用测速。
`[-no-cache]`:停止缓存|bind :53 +|bind-tcp|TCP DNS监听端口号|[::]:53|可绑定多个端口
`IP:PORT`: 服务器IP,端口号。
`[-group]`: 请求时使用的DNS服务器组。
`[-no-rule-addr]`:跳过address规则。
`[-no-rule-nameserver]`:跳过Nameserver规则。
`[-no-rule-ipset]`:跳过Ipset规则。
`[no-rule-soa]`:跳过SOA(#)规则.
`[no-dualstack-selection]`:停用双栈测速。
`[-no-speed-check]`:停用测速。
`[-no-cache]`:停止缓存|bind-tcp :53 +|cache-size|域名结果缓存个数|512|数字|cache-size 512 +|tcp-idle-time|TCP链接空闲超时时间|120|数字|tcp-idle-time 120 +|rr-ttl|域名结果TTL|远程查询结果|大于0的数字|rr-ttl 600 +|rr-ttl-min|允许的最小TTL值|远程查询结果|大于0的数字|rr-ttl-min 60 +|rr-ttl-max|允许的最大TTL值|远程查询结果|大于0的数字|rr-ttl-max 600 +|log-level|设置日志级别|error|fatal,error,warn,notice,info,debug|log-level error +|log-file|日志文件路径|/var/log/smartdns.log|路径|log-file /var/log/smartdns.log +|log-size|日志大小|128K|数字+K,M,G|log-size 128K +|log-num|日志归档个数|2|数字|log-num 2 +|audit-enable|设置审计启用|no|[yes\|no]|audit-enable yes +|audit-file|审计文件路径|/var/log/smartdns-audit.log|路径|audit-file /var/log/smartdns-audit.log +|audit-size|审计大小|128K|数字+K,M,G|audit-size 128K +|audit-num|审计归档个数|2|数字|audit-num 2 +|conf-file|附加配置文件|无|文件路径|conf-file /etc/smartdns/smartdns.more.conf +|server|上游UDP DNS|无|可重复
`[ip][:port]`:服务器IP,端口可选。
`[-blacklist-ip]`:blacklist-ip参数指定使用blacklist-ip配置IP过滤结果。
`[-whitelist-ip]`:whitelist-ip参数指定仅接受whitelist-ip中配置IP范围。
`[-group [group] ...]`:DNS服务器所属组,比如office, foreign,和nameserver配套使用。
`[-exclude-default-group]`:将DNS服务器从默认组中排除| server 8.8.8.8:53 -blacklist-ip -group g1 +|server-tcp|上游TCP DNS|无|可重复
`[ip][:port]`:服务器IP,端口可选。
`[-blacklist-ip]`:blacklist-ip参数指定使用blacklist-ip配置IP过滤结果。
`[-whitelist-ip]`:whitelist-ip参数指定仅接受whitelist-ip中配置IP范围。
`[-group [group] ...]`:DNS服务器所属组,比如office, foreign,和nameserver配套使用。
`[-exclude-default-group]`:将DNS服务器从默认组中排除| server-tcp 8.8.8.8:53 +|server-tls|上游TLS DNS|无|可重复
`[ip][:port]`:服务器IP,端口可选。
`[-spki-pin [sha256-pin]]`: TLS合法性校验SPKI值,base64编码的sha256 SPKI pin值
`[-host-name]`:TLS SNI名称。
`[-tls-host-verify]`: TLS证书主机名校验。
`-no-check-certificate:`:跳过证书校验。
`[-blacklist-ip]`:blacklist-ip参数指定使用blacklist-ip配置IP过滤结果。
`[-whitelist-ip]`:whitelist-ip参数指定仅接受whitelist-ip中配置IP范围。
`[-group [group] ...]`:DNS服务器所属组,比如office, foreign,和nameserver配套使用。
`[-exclude-default-group]`:将DNS服务器从默认组中排除| server-tls 8.8.8.8:853 +|server-https|上游HTTPS DNS|无|可重复
`https://[host][:port]/path`:服务器IP,端口可选。
`[-spki-pin [sha256-pin]]`: TLS合法性校验SPKI值,base64编码的sha256 SPKI pin值
`[-host-name]`:TLS SNI名称
`[-http-host]`:http协议头主机名。
`[-tls-host-verify]`: TLS证书主机名校验。
`-no-check-certificate:`:跳过证书校验。
`[-blacklist-ip]`:blacklist-ip参数指定使用blacklist-ip配置IP过滤结果。
`[-whitelist-ip]`:whitelist-ip参数指定仅接受whitelist-ip中配置IP范围。
`[-group [group] ...]`:DNS服务器所属组,比如office, foreign,和nameserver配套使用。
`[-exclude-default-group]`:将DNS服务器从默认组中排除| server-https https://cloudflare-dns.com/dns-query +|speed-check-mode|测速模式选择|无|[ping\|tcp:[80]\|none]|speed-check-mode ping,tcp:80 +|address|指定域名IP地址|无|address /domain/[ip\|-\|-4\|-6\|#\|#4\|#6]
`-`表示忽略
`#`表示返回SOA
`4`表示IPV4
`6`表示IPV6| address /www.example.com/1.2.3.4 +|nameserver|指定域名使用server组解析|无|nameserver /domain/[group\|-], `group`为组名,`-`表示忽略此规则,配套server中的`-group`参数使用| nameserver /www.example.com/office +|ipset|域名IPSET|None|ipset /domain/[ipset\|-], `-`表示忽略|ipset /www.example.com/pass +|ipset-timeout|设置IPSET超时功能启用|auto|[yes]|ipset-timeout yes +|domain-rules|设置域名规则|无|domain-rules /domain/ [-rules...]
`[-speed-check-mode]`: 测速模式,参考`speed-check-mode`配置
`[-address]`: 参考`address`配置
`[-nameserver]`: 参考`nameserver`配置
`[-ipset]`:参考`ipset`配置|domain-rules /www.example.com/ -speed-check-mode none +|bogus-nxdomain|假冒IP地址过滤|无|[ip/subnet],可重复| bogus-nxdomain 1.2.3.4/16 +|ignore-ip|忽略IP地址|无|[ip/subnet],可重复| ignore-ip 1.2.3.4/16 +|whitelist-ip|白名单IP地址|无|[ip/subnet],可重复| whitelist-ip 1.2.3.4/16 +|blacklist-ip|黑名单IP地址|无|[ip/subnet],可重复| blacklist-ip 1.2.3.4/16 +|force-AAAA-SOA|强制AAAA地址返回SOA|no|[yes\|no]|force-AAAA-SOA yes +|prefetch-domain|域名预先获取功能|no|[yes\|no]|prefetch-domain yes +|serve-expired|过期缓存服务功能|no|[yes\|no],开启此功能后,如果有请求时尝试回应TTL为0的过期记录,并并发查询记录,以避免查询等待|serve-expired yes +|serve-expired-ttl|过期缓存服务最长超时时间|0|秒,0:表示停用超时,> 0表示指定的超时的秒数|serve-expired-ttl 0 +|dualstack-ip-selection|双栈IP优选|no|[yes\|no]|dualstack-ip-selection yes +|dualstack-ip-selection-threshold|双栈IP优选阈值|30ms|毫秒|dualstack-ip-selection-threshold [0-1000] +|ca-file|证书文件|/etc/ssl/certs/ca-certificates.crt|路径|ca-file /etc/ssl/certs/ca-certificates.crt +|ca-path|证书文件路径|/etc/ssl/certs|路径|ca-path /etc/ssl/certs + +## FAQ + +1. SmartDNS和DNSMASQ有什么区别 + SMARTDNS在设计上并不是替换DNSMASQ的,SMARTDNS主要功能集中在DNS解析增强上,增强部分有: + * 多上游服务器并发请求,对结果进行测速后,返回最佳结果; + * address,ipset域名匹配采用高效算法,查询匹配更加快速高效,路由器设备依然高效。 + * 域名匹配支持忽略特定域名,可单独匹配IPv4, IPV6,支持多样化定制。 + * 针对广告屏蔽功能做增强,返回SOA,屏蔽广告效果更佳; + * IPV4,IPV6双栈IP优选机制,在双网情况下,选择最快的网络通讯。 + * 支持最新的TLS, HTTPS协议,提供安全的DNS查询能力。 + * ECS支持,是查询结果更佳准确。 + * IP黑名单,忽略IP机制,使域名查询更佳准确。 + * 域名预查询,访问常用网站更加快速。 + * 域名TTL可指定,使访问更快速。 + * 高速缓存机制,使访问更快速。 + * 异步日志,审计机制,在记录信息的同时不影响DNS查询性能。 + * 域名组(group)机制,特定域名使用特定上游服务器组查询,避免隐私泄漏。 + * 第二DNS支持自定义更多行为。 + +1. 如何配置上游服务器最佳。 + smartdns有测速机制,在配置上游服务器时,建议配置多个上游DNS服务器,包含多个不同区域的服务器,但总数建议在10个左右。推荐配置 + * 运营商DNS。 + * 国内公共DNS,如`119.29.29.29`, `223.5.5.5`。 + * 国外公共DNS,如`8.8.8.8`, `8.8.4.4`。 + +1. 如何启用审计日志 + 审计日志记录客户端请求的域名,记录信息包括,请求时间,请求IP,请求域名,请求类型,如果要启用审计日志,在配置界面配置`audit-enable yes`启用,`audit-size`, `audit-file`, `audit-num`分别配置审计日志文件大小,审计日志文件路径,和审计日志文件个数。审计日志文件将会压缩存储以节省空间。 + +1. 如何避免隐私泄漏 + smartdns默认情况下,会将请求发送到所有配置的DNS服务器,若上游DNS服务器使用DNS,或记录日志,将会导致隐私泄漏。为避免隐私泄漏,请尽量: + * 配置使用可信的DNS服务器。 + * 优先使用TLS查询。 + * 设置上游DNS服务器组。 + +1. 如何屏蔽广告 + smartdns具备高性能域名匹配算法,通过域名方式过滤广告非常高效,如要屏蔽广告,只需要配置类似如下记录即可,如,屏蔽`*.ad.com`,则配置: + + ```sh + address /ad.com/# + ``` + + 域名的使后缀模式,过滤*.ad.com,`#`表示返回SOA,使屏蔽广告更加高效,如果要单独屏蔽IPV4, 或IPV6, 在`#`后面增加数字,如`#4`表示对IPV4生效。若想忽略特定子域名的屏蔽,可配置如下,如忽略`pass.ad.com`,可配置如下: + + ```sh + address /pass.ad.com/- + ``` + +1. 如何使用DNS查询分流 + 某些情况下,需要将有些域名使用特定的DNS服务器来查询来做到DNS分流。比如。 + + ```sh + .home -> 192.168.1.1 + .office -> 10.0.0.1 + ``` + + .home 结尾的域名发送到192.168.1.1解析 + .office 结尾的域名发送到10.0.0.1解析 + 其他域名采用默认的模式解析。 + 这种情况的分流配置如下: + + ```sh + #配置上游,用-group指定组名,用-exclude-default-group将服务器从默认组中排除。 + server 192.168.1.1 -group home -exclude-default-group + server 10.0.0.1 -group office -exclude-default-group + server 8.8.8.8 + + #配置解析的域名 + nameserver /.home/home + nameserver /.office/office + ``` + + 通过上述配置即可实现DNS解析分流,如果需要实现按请求端端口分流,可以配置第二DNS服务器,bind配置增加--group参数指定分流名称。 + + ```sh + bind :7053 -group office + bind :8053 -group home + ``` + +1. IPV4, IPV6双栈IP优选功能如何使用 + 目前IPV6已经开始普及,但IPV6网络在速度上,某些情况下还不如IPV4,为在双栈网络下获得较好的体验,smartdns提供来双栈IP优选机制,同一个域名,若IPV4的速度远快与IPV6,那么smartdns就会阻止IPV6的解析,让PC使用IPV4访问,具体配置文件通过`dualstack-ip-selection yes`启用此功能,通过`dualstack-ip-selection-threshold [time]`来修改阈值。如果要完全禁止IPV6 AAAA记录解析,可设置`force-AAAA-SOA yes`。 + +1. 如何提高cache效率,加快访问速度 + smartdns提供了域名缓存机制,对查询的域名,进行缓存,缓存时间符合DNS TTL规范。为提高缓存命中率,可采用如下措施: + * 适当增大cache的记录数 + 通过`cache-size`来设置缓存记录数。 + 查询压力大的环境下,并且有内存大的机器的情况下,可适当调大。 + + * 适当设置最小TTL值 + 通过`rr-ttl-min`将最低DNS TTL时间设置为一个合理值,延长缓存时间。 + 建议是超时时间设置在10~30分钟,避免服务器域名变化时,查询到失效域名。 + + * 开启域名预获取功能 + 通过`prefetch-domain yes`来启用域名预先获取功能,提高查询命中率。 + 配合上述ttl超时时间,smartdns将在域名ttl即将超时使,再次发送查询请求,并缓存查询结果供后续使用。频繁访问的域名将会持续缓存。此功能将在空闲时消耗更多的CPU。 + + * 过期缓存服务功能 + 通过`serve-expired`来启用过期缓存服务功能,可提高缓存命中率的同时,降低CPU占用。 + 此功能会在TTL超时后,将返回TTL=0给客户端,并且同时再次发送查询请求,并缓存新的结果给后续使用。 + +1. 第二DNS如何自定义更多行为 + 第二DNS可以作为其他DNS服务器的上游,提供更多的查询行为,通过bind配置支持可以绑定多个端口,不同端口可设置不同的标志,实现不同的功能,如 + + ```sh + # 绑定 6053端口,6053端口的请求将采用配置office组的上游查询,且不对结果进行测速,忽略address的配置地址。 + bind [::]:6053 -no-speed-check -group office -no-rule-addr + ``` + +## 编译 + +smartdns包含了编译软件包的脚本,支持编译luci,debian,openwrt,optare安装包,可执行`package/build-pkg.sh`编译。 + +## Donate + +如果你觉得此项目对你有帮助,请捐助我们,以使项目能持续发展,更加完善。 + +### PayPal + +[![Support via PayPal](https://cdn.rawgit.com/twolfson/paypal-github-button/1.0.0/dist/button.svg)](https://paypal.me/PengNick/) + +### Alipay 支付宝 + +![alipay](doc/alipay_donate.jpg) + +### Wechat 微信 + +![wechat](doc/wechat_donate.jpg) + +## 开源声明 + +Smartdns 基于GPL V3协议开源。 diff --git a/release/src/router/smartdns/ReadMe_en.md b/release/src/router/smartdns/ReadMe_en.md index 67ada9119e..bc812cc074 100644 --- a/release/src/router/smartdns/ReadMe_en.md +++ b/release/src/router/smartdns/ReadMe_en.md @@ -1,702 +1,668 @@ -# SmartDNS - -![SmartDNS](doc/smartdns-banner.png) -SmartDNS is a local DNS server. SmartDNS accepts DNS query requests from local clients, obtains DNS query results from multiple upstream DNS servers, and returns the fastest access results to clients. -Avoiding DNS pollution and improving network access speed, supports high-performance ad filtering. -Unlike dnsmasq's all-servers, smartdns returns the fastest access resolution. ([read more](#faq)) - -Support Raspberry Pi, openwrt, ASUS router, Windows and other devices. - -## Table Of Content - -1. [Software Show](#software-show) -1. [Features](#features) -1. [Architecture](#architecture) -1. [Usage](#usage) - 1. [Download the package](#download-the-package) - 1. [Standard Linux system installation/Raspberry Pi, X86_64 system](#standard-linux-system-installation/raspberry-pi,-x86_64-system) - 1. [openwrt/LEDE](#openwrt/lede) - 1. [ASUS router native firmware / Merlin firmware](#asus-router-native-firmware-/-merlin-firmware) - 1. [optware/entware](#optware/entware) - 1. [Windows 10 WSL Installation/WSL ubuntu](#windows-10-wsl-installation/wsl-ubuntu) -1. [Configuration parameter](#configuration-parameter) -1. [Donate](#Donate) -1. [FAQ](#FAQ) - -## Software Show - -**Ali DNS** -Use Ali DNS to query Baidu's IP and test the results. - -```shell -pi@raspberrypi:~/code/smartdns_build $ nslookup www.baidu.com 223.5.5.5 -Server: 223.5.5.5 -Address: 223.5.5.5#53 - -Non-authoritative answer: -www.baidu.com canonical name = www.a.shifen.com. -Name: www.a.shifen.com -Address: 180.97.33.108 -Name: www.a.shifen.com -Address: 180.97.33.107 - -pi@raspberrypi:~/code/smartdns_build $ ping 180.97.33.107 -c 2 -PING 180.97.33.107 (180.97.33.107) 56(84) bytes of data. -64 bytes from 180.97.33.107: icmp_seq=1 ttl=55 time=24.3 ms -64 bytes from 180.97.33.107: icmp_seq=2 ttl=55 time=24.2 ms - ---- 180.97.33.107 ping statistics --- -2 packets transmitted, 2 received, 0% packet loss, time 1001ms -rtt min/avg/max/mdev = 24.275/24.327/24.380/0.164 ms -pi@raspberrypi:~/code/smartdns_build $ ping 180.97.33.108 -c 2 -PING 180.97.33.108 (180.97.33.108) 56(84) bytes of data. -64 bytes from 180.97.33.108: icmp_seq=1 ttl=55 time=31.1 ms -64 bytes from 180.97.33.108: icmp_seq=2 ttl=55 time=31.0 ms - ---- 180.97.33.108 ping statistics --- -2 packets transmitted, 2 received, 0% packet loss, time 1001ms -rtt min/avg/max/mdev = 31.014/31.094/31.175/0.193 ms -``` - -**smartdns** -Use SmartDNS to query Baidu IP and test the results. - -```shell -pi@raspberrypi:~/code/smartdns_build $ nslookup www.baidu.com -Server: 192.168.1.1 -Address: 192.168.1.1#53 - -Non-authoritative answer: -www.baidu.com canonical name = www.a.shifen.com. -Name: www.a.shifen.com -Address: 14.215.177.39 - -pi@raspberrypi:~/code/smartdns_build $ ping 14.215.177.39 -c 2 -PING 14.215.177.39 (14.215.177.39) 56(84) bytes of data. -64 bytes from 14.215.177.39: icmp_seq=1 ttl=56 time=6.31 ms -64 bytes from 14.215.177.39: icmp_seq=2 ttl=56 time=5.95 ms - ---- 14.215.177.39 ping statistics --- -2 packets transmitted, 2 received, 0% packet loss, time 1001ms -rtt min/avg/max/mdev = 5.954/6.133/6.313/0.195 ms - -``` - -From the comparison, smartdns found the fastest IP address to visit www.baidu.com, so accessing Baidu's DNS is 5 times faster than Ali DNS. - -## Features - -1. **Multiple upstream DNS servers** - Support configuring multiple upstream DNS servers and query at the same time.the query will not be affected, Even if there is a DNS server exception. - -2. **Return the fastest IP address** - Supports finding the fastest access IP address from the IP address list of the domain name and returning it to the client to avoid DNS pollution and improve network access speed. - -3. **Support for multiple query protocols** - Support UDP, TCP, TLS, HTTPS queries, and non-53 port queries, effectively avoiding DNS pollution. - -4. **Domain IP address specification** - Support configuring IP address of specific domain to achieve the effect of advertising filtering, and avoid malicious websites. - -5. **Domain name high performance rule filtering** - Support domain name suffix matching mode, simplify filtering configuration, filter 200,000 recording and take time <1ms. - -6. **Linux/Windows multi-platform support** - Support standard Linux system (Raspberry Pi), openwrt system various firmware, ASUS router native firmware. Support Windows 10 WSL (Windows Subsystem for Linux). - -7. **Support IPV4, IPV6 dual stack** - Support IPV4, IPV6 network, support query A, AAAA record, dual-stack IP selection, and disale IPV6 AAAA record. - -8. **High performance, low resource consumption** - Multi-threaded asynchronous IO mode, cache cache query results. - -## Architecture - -![Architecture](doc/architecture.png) - -1. SmartDNS receives DNS query requests from local network devices, such as PCs and mobile phone query requests. -2. SmartDNS sends query requests to multiple upstream DNS servers, using standard UDP queries, non-standard port UDP queries, and TCP queries. -3. The upstream DNS server returns a list of Server IP addresses corresponding to the domain name. SmartDNS detects the fastest Server IP with local network access. -4. Return the fastest accessed Server IP to the local client. - -## Usage - -### Download the package - --------------- - -Download the matching version of the SmartDNS installation package. The corresponding installation package is as follows. - -|system |package|Description -|-----|-----|----- -|Standard Linux system (Raspberry Pi)| smartdns.xxxxxxxx.armhf.deb|Support Raspberry Pi Raspbian stretch, Debian 9 system. -|Standard Linux system (Armbian arm64)| smartdns.xxxxxxxx.arm64.deb|Support Armbian debian stretch, Debian 9 system. -|Standard Linux system (x86_64)| smartdns.xxxxxxxx.x86_64.tar.gz|Support for x86_64 Linux systems. -|Windows 10 WSL (Ubuntu)| smartdns.xxxxxxxx.x86_64.tar.gz|Windows 10 WSL ubuntu. -|Standard Linux system (x86)| smartdns.xxxxxxxx.x86.tar.gz|Support for x86_64 systems. -|ASUS native firmware (optware)|smartdns.xxxxxxx.mipsbig.ipk|Systems that support the MIPS big-end architecture, such as RT-AC55U, RT-AC66U. -|ASUS native firmware (optware)|smartdns.xxxxxxx.mipsel.ipk|System that supports the MIPS little endian architecture. -|ASUS native firmware (optware)|smartdns.xxxxxxx.arm.ipk|System that supports the ARM small endian architecture, such as the RT-AC88U, RT-AC68U. -|Padavan|smartdns.xxxxxxx.mipselsf.ipk|padavan Firmware. -|openwrt 15.01|smartdns.xxxxxxxx.ar71xx.ipk|Support AR71XX MIPS system. -|openwrt 15.01|smartdns.xxxxxxxx.ramips_24kec.ipk|Support small-end routers such as MT762X -|openwrt 15.01(Pandora)|smartdns.xxxxxxxx.mipsel_24kec_dsp.ipk|Support for Pandora firmware of MT7620 series -|openwrt 15.01(Pandora)|smartdns.xxxxxxxx.mips_74kc_dsp2.ipk|Support for Pandora firmware of AR71xx series -|openwrt 18.06|smartdns.xxxxxxxx.mips_24kc.ipk|Support AR71XX MIPS system. -|openwrt 18.06|smartdns.xxxxxxxx.mipsel_24kc.ipk|Support small-end routers such as MT726X -|openwrt 18.06|smartdns.xxxxxxxx.x86_64.ipk|Support x86_64 router -|openwrt 18.06|smartdns.xxxxxxxx.i386_pentium4.ipk|Support x86_64 router -|openwrt 18.06|smartdns.xxxxxxxxxxx.arm_cortex-a9.ipk|Router supporting arm A9 core CPU -|openwrt 18.06|smartdns.xxxxxxxxx.arm_cortex-a7_neon-vfpv4.ipk|Router supporting arm A7 core CPU -|openwrt LUCI|luci-app-smartdns.xxxxxxxxx.xxxx.all.ipk|Openwrt management interface - -* The openwrt system supports a lot of CPU architecture. The above table does not list all the supported systems. Please check the CPU architecture and download it. -* The merlin Merlin firmware theory is the same as the ASUS firmware, so install the corresponding ipk package according to the hardware type. (Merlin is not verified yet, and has a problem to submit an issue) -* The CPU architecture can be found in the router management interface: - Log in to the router, click `System`->`Software`, click the `Configuration` tab page, and find the corresponding software architecture in the opkg installation source. The download path can be found, as follows, the architecture is ar71xx - - ```shell - src/gz chaos_calmer_base http://downloads.openwrt.org/chaos_calmer/15.05/ar71xx/generic/packages/base - ``` - -* Or after login to the system, you can query the architecture with the following commands: - - * **Openwrt series commands** - - ```shell - opkg print_architecture - ``` - - * **Optiware series commands** - - ```shell - ipkg print_architecture - ``` - - * **Dedebian Series Order** - - ```shell - dpkg -- print-architecture - ``` - - * **for example** - - The following query result `arch ar71xx 10` represents the ar71xx series architecture, so select the `smartdns.xxxxxxx.ar71xx.ipk` installation package. - - ```shell - Root@OpenWrt:# opkg print_architecture - Arch all 1 - Arch noarch 1 - Arch ar71xx 10 - ``` - -* **Please download from the Release page: [Download here](https://github.com/pymu/smartdns/releases)** - -```shell -https://github.com/pymumu/smartdns/releases -``` - -* For the installation procedure, please refer to the following sections. - -### Standard Linux system installation/Raspberry Pi, X86_64 system - --------------- - -1. Installation - - Download the installation package like `smartdns.xxxxxxxx.armhf.deb` and upload it to the Linux system. Run the following command to install - - ```shell - dpkg -i smartdns.xxxxxxxx.armhf.deb - ``` - - For X86-64 system, download the installation package like `smartdns.xxxxxxxx.x86-64.tar.gz` and upload it to the Linux system. Run the following command to install - - ```shell - tar zxf smartdns.xxxxxxxx.x86-64.tar.gz - cd smartdns - chmod +x ./install - ./install -i - ``` - -1. Configuration - - After the installation is complete, you can configure the upstream server to smartdns. Refer to the `Configuration Parameters` for specific configuration parameters. - In general, you only need to add `server [IP]:port`, `server-tcp [IP]:port` configuration items. - Configure as many upstream DNS servers as possible, including servers at home and abroad. Please refer to the `Configuration Parameters` section for configuration parameters. - - ```shell - vi /etc/smartdns/smartdns.conf - ``` - -1. Start Service - - ```shell - systemctl enable smartdns - systemctl start smartdns - ``` - -1. Forwarding DNS request to SmartDNS - - Modify the DNS server of the local router and configure the DNS server as SmartDNS. - * Log in to the router on the local network and configure the Raspberry Pi to assign a static IP address. - * Modify the WAN port or DHCP DNS to the Raspberry Pi IP address. - Note: - I. Each router configuration method is different. Please search Baidu for related configuration methods. - II. some routers may not support configuring custom DNS server. in this case, please modify the PC's, mobile phone's DNS server to the ip of Raspberry Pi. - -1. Check if the service is configured successfully - - Query domain name with `nslookup -querytype=ptr 0.0.0.0` - Check if the `name` item in the command result is displayed as `smartdns` or `hostname`, such as `smartdns` - - ```shell - pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr 0.0.0.0 - Server: 192.168.1.1 - Address: 192.168.1.1#53 - - Non-authoritative answer: - 0.0.0.0.in-addr.arpa name = smartdns. - ``` - -### openwrt/LEDE - --------------- - -1. Installation - - Upload the software to the /root directory of the router with winscp or other tool, and execute the following command to install it. - - ```shell - opkg install smartdns.xxxxxxxx.xxxx.ipk - opkg install luci-app-smartdns.xxxxxxxx.xxxx.all.ipk - ``` - -1. Configuration - - Log in to the openwrt management page and open `Services`->`SmartDNS` to configure SmartDNS. - * Add upstream DNS server configuration to `Upstream Servers`. It is recommended to configure multiple DNS servers at home and abroad. - * Specify the IP address of a specific domain name in `Domain Address`, which can be used for ad blocking. - -1. Start Service - - There are two ways to use the SmartDNS service, `one is directly as the primary DNS service`, `the other is as the upstream of dnsmasq`. - By default, SmartDNS uses the first method. You can choose according to your needs in the following two ways. - -1. Method 1: SmartDNS as primary DNS Server (default scheme) - - * **Enable SmartDNS port 53 port redirection** - - Log in to the router, click on `Services`->`SmartDNS`->`redirect`, select `Redirect 53 port to SmartDNS` option to enable port 53 forwarding. - - * **Check if the service is configured successfully** - - Query domain name with `nslookup -querytype=ptr 0.0.0.0` - See if the `name` item in the command result is displayed as `smartdns` or `hostname`, such as `smartdns` - - ```shell - pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr 0.0.0.0 - Server: 192.168.1.1 - Address: 192.168.1.1#53 - - Non-authoritative answer: - 0.0.0.0.in-addr.arpa name = smartdns. - ``` - - * **The interface prompts that the redirect failed** - - * Check if iptable, ip6table command is installed correctly. - * The openwrt 15.01 system does not support IPV6 redirection. If the network needs to support IPV6, please change DNSMASQ upstream to smartdns, or change the smartdns port to 53, and disable dnsmasq. - * After LEDE system, please install IPV6 nat forwarding driver. Click `system`->`Software`, click `update lists` to update the software list, install `ip6tables-mod-nat` - * Use the following command to check whether the routing rule takes effect. - - ```shell - iptables -t nat -L PREROUTING | grep REDIRECT - ``` - - * If the forwarding function is abnormal, please use Method 2: As the upstream of DNSMASQ. - -1. Method 2: SmartDNS as upstream DNS Server of DNSMASQ - - * **Forward dnsmasq's request to SmartDNS** - - Log in to the router, click on `Services`->`SmartDNS`->`redirect`, select `Run as dnsmasq upstream server` option to forwarding dnsmasq request to Smartdns. - - * **Check if the service is configured successfully** - - * Method 1: Query domain name with `nslookup -querytype=ptr 0.0.0.1` - See if the `name` item in the command result is displayed as `smartdns` or `hostname`, such as `smartdns` - - ```shell - pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr 0.0.0.0 - Server: 192.168.1.1 - Address: 192.168.1.1#53 - - Non-authoritative answer: - 0.0.0.0.in-addr.arpa name = smartdns. - ``` - - * Method 2: Use `nslookup` to query the `www.baidu.com` domain name to see if the IP address of Baidu in the result is `only one. If there are multiple IP addresses returned, it means that it is not valid. Please try to check several domain names. - - ```shell - pi@raspberrypi:~ $ nslookup www.baidu.com 192.168.1.1 - Server: 192.168.1.1 - Address: 192.168.1.1#53 - - Non-authoritative answer: - www.baidu.com canonical name = www.a.shifen.com. - Name: www.a.shifen.com - Address: 14.215.177.38 - ``` - -1. Start Service - - Check the `Enable' in the configuration page to start SmartDNS server. - -1. Note - - * If chinaDNS is already installed, it is recommended to configure the upstream of chinaDNS as SmartDNS. - * SmartDNS defaults to forwarding port 53 requests to the local port of SmartDNS, controlled by the `Redirect` configuration option. - -### ASUS router native firmware / Merlin firmware - --------------- - -Note: Merlin firmware is derived from ASUS firmware and can theoretically be used directly with the ASUS package. However, it is currently unverified. If you have any questions, please submit an issue. - -1. Prepare - - When using this software, you need to confirm whether the router supports U disk and prepare a USB disk. - -1. Enable SSH login - - Log in to the management interface, click `System Management`-> Click `System Settings` and configure `Enable SSH` to `Lan Only`. - The SSH login username and password are the same as the management interface. - -1. Insstall `Download Master` - - In the management interface, click `USB related application`-> click `Download Master` to download. - After the download is complete, enable `Download Master`. If you do not need the download function, you can uninstall `Download Master` here, but make sure that Download Master is enabled before uninstalling. - -1. Install SmartDNS - - Upload the software to the router's `/tmp/mnt/sda1` directory using winscp. (or copy the network neighborhood to the sda1 shared directory) - - ```shell - ipkg install smartdns.xxxxxxx.mipsbig.ipk - ``` - -1. Restart router - - After the router is started, use `nslookup -querytype=ptr 0.0.0.0` to query the domain name. - See if the `name` item in the command result is displayed as `smartdns` or `hostname`, such as `smartdns` - - ```shell - pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr 0.0.0.0 - Server: 192.168.1.1 - Address: 192.168.1.1#53 - - Non-authoritative answer: - 0.0.0.0.in-addr.arpa name = smartdns. - ``` - -1. Note - - In the above process, smartdns will be installed to the root directory of the U disk and run in optware mode. - Its directory structure is as follows: (only smartdns related files are listed here) - - ```shell - USB DISK - └── asusware.mipsbig - ├── bin - ├── etc - | ├── smartdns - | | └── smartdns.conf - | └── init.d - | └── S50smartdns - ├── lib - ├── sbin - ├── usr - | └── sbin - | └── smartdns - .... - ``` - - To modify the configuration, you can use ssh to login to the router and use the vi command to modify it. - - ```shell - vi /opt/etc/smartdns/smartdns.conf - ``` - - It can also be modified from Network Neighborhood. From the neighbor sharing directory `sda1` you can't see the `asusware.mipsbig` directory, but you can directly enter `asusware.mipsbig\etc\init.d` in `File Manager` to modify it. - - ```shell - \\192.168.1.1\sda1\asusware.mipsbig\etc\init.d - ``` - -### optware/entware - --------------- - -1. Prepare - - When using this software, you need to confirm whether the router supports USB disk and prepare a USB disk. - -1. Install SmartDNS - - Upload the software to `/tmp` directory of the router using winscp, and run the flollowing command to install. - - ```shell - ipkg install smartdns.xxxxxxx.mipsbig.ipk - ``` - -1. Modify the smartdns configuration - - ```shell - Vi /opt/etc/smartdns/smartdns.conf - ``` - - Note: if you need to support IPV6, you can set the worke-mode to `2`, this will disable the DNS service of dnsmasq, and smartdns run as the primary DNS server. Change `SMARTDNS_WORKMODE` in the file `/opt/etc/smartdns/smartdns-opt.conf` to 2. - - ```shell - SMARTDNS_WORKMODE="2" - ``` - -1. Restart the router to take effect - - After the router is started, use `nslookup -querytype=ptr 0.0.0.0` to query the domain name. - See if the `name` item in the command result is displayed as `smartdns` or `hostname`, such as `smartdns` - - ```shell - Pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr 0.0.0.0 - Server: 192.168.1.1 - Address: 192.168.1.1#53 - - Non-authoritative answer: - 0.0.0.0.in-addr.arpa name = smartdns. - ``` - - Note: If the service does not start automatically, you need to set optwre/entware to start automatically. For details, see the optware/entware documentation. - -### Windows 10 WSL Installation/WSL ubuntu - --------------- - -1. Install Windows 10 WSL ubuntu - - Install the Windows 10 WSL environment and select Ubuntu as default distribution. Please refer to [WSL installation instructions](https://docs.microsoft.com/en-us/windows/wsl/install-win10) for installation steps - -1. Install smartdns - - download install package `smartdns.xxxxxxxx.x86_64.tar.gz`,and unzip to the `D:\` directory, after decompression, the directory is as follows: - - ```shell - D:\SMARTDNS - ├─etc - │ ├─default - │ ├─init.d - │ └─smartdns - ├─package - │ └─windows - ├─src - └─systemd - - ``` - - Double-click `install.bat` in the `D:\smartdns\package\windows` directory for installation. Please enter the password for `WLS ubuntu` when input password. - -1. Configuration - - Edit `smartdns.conf` configuration file in `D:\smartdns\etc\smartdns` directory, you can configure the upstream server to smartdns. Refer to the `Configuration Parameters` for specific configuration parameters. - In general, you only need to add `server [IP]:port`, `server-tcp [IP]:port` configuration items. - Configure as many upstream DNS servers as possible, including servers at home and abroad. Please refer to the `Configuration Parameters` section for configuration parameters. - -1. Start Service - - Double-click `reload.bat` in the `D:\smartdns\package\windows` directory for reload. - -1. Forwarding DNS request to SmartDNS - - Modify the default DNS server for Windows to `127.0.0.1`, with these steps referred to [IP configuration](https://support.microsoft.com/en-us/help/15089/windows-change-tcp-ip-settings) - -1. Check if the service is configured successfully - - Query domain name with `nslookup -querytype=ptr 0.0.0.0` - Check if the `name` item in the command result is displayed as `smartdns` or `hostname`, such as `smartdns` - - ```shell - pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr 0.0.0.0 - Server: 192.168.1.1 - Address: 192.168.1.1#53 - - Non-authoritative answer: - 0.0.0.0.in-addr.arpa name = smartdns. - ``` - -## Configuration parameter - -|parameter|Parameter function|Default value|Value type|Example| -|--|--|--|--|--| -|server-name|DNS name|host name/smartdns|any string like hosname|server-name smartdns -|bind|DNS listening port number|[::]:53|Support binding multiple ports
`IP:PORT`: server IP, port number.
`[-group]`: The DNS server group used when requesting.
`[-no-rule-addr]`: Skip the address rule.
`[-no-rule-nameserver]`: Skip the Nameserver rule.
`[-no-rule-ipset]`: Skip the Ipset rule.
`[-no-rule-soa]`: Skip address SOA(#) rules.
`[-no-dualstack-selection]`: Disable dualstack ip selection.
`[-no-speed-check]`: Disable speed measurement.
`[-no-cache]`: stop caching |bind :53 -|bind-tcp|TCP mode DNS listening port number|[::]:53|Support binding multiple ports
`IP:PORT`: server IP, port number.
`[-group]`: The DNS server group used when requesting.
`[-no-rule-addr]`: Skip the address rule.
`[-no-rule-nameserver]`: Skip the Nameserver rule.
`[-no-rule-ipset]`: Skip the Ipset rule.
`[-no-rule-soa]`: Skip address SOA(#) rules.
`[-no-dualstack-selection]`: Disable dualstack ip selection.
`[-no-speed-check]`: Disable speed measurement.
`[-no-cache]`: stop caching |bind-tcp :53 -|cache-size|Domain name result cache number|512|integer|cache-size 512 -|tcp-idle-time|TCP connection idle timeout|120|integer|tcp-idle-time 120 -|rr-ttl|Domain name TTL|Remote query result|number greater than 0|rr-ttl 600 -|rr-ttl-min|Domain name Minimum TTL|Remote query result|number greater than 0|rr-ttl-min 60 -|rr-ttl-max|Domain name Maximum TTL|Remote query result|number greater than 0|rr-ttl-max 600 -|log-level|log level|error|fatal,error,warn,notice,info,debug|log-level error -|log-file|log path|/var/log/smartdns.log|File Pah|log-file /var/log/smartdns.log -|log-size|log size|128K|number+K,M,G|log-size 128K -|log-num|archived log number|2|Integer|log-num 2 -|audit-enable|audit log enable|no|[yes\|no]|audit-enable yes -|audit-file|audit log file|/var/log/smartdns-audit.log|File Path|audit-file /var/log/smartdns-audit.log -|audit-size|audit log size|128K|number+K,M,G|audit-size 128K -|audit-num|archived audit log number|2|Integer|audit-num 2 -|conf-file|additional conf file|None|File path|conf-file /etc/smartdns/smartdns.more.conf -|server|Upstream UDP DNS server|None|Repeatable
`[ip][:port]`: Server IP, port optional.
`[-blacklist-ip]`: The "-blacklist-ip" parameter is to filtering IPs which is configured by "blacklist-ip".
`[-whitelist-ip]`: whitelist-ip parameter specifies that only the IP range configured in whitelist-ip is accepted.
`[-group [group] ...]`: The group to which the DNS server belongs, such as office, foreign, use with nameserver.
`[-exclude-default-group]`: Exclude DNS servers from the default group| server 8.8.8.8:53 -blacklist-ip -|server-tcp|Upstream TCP DNS server|None|Repeatable
`[ip][:port]`: Server IP, port optional.
`[-blacklist-ip]`: The "-blacklist-ip" parameter is to filtering IPs which is configured by "blacklist-ip".
`[-whitelist-ip]`: whitelist-ip parameter specifies that only the IP range configured in whitelist-ip is accepted.
`[-group [group] ...]`: The group to which the DNS server belongs, such as office, foreign, use with nameserver.
`[-exclude-default-group]`: Exclude DNS servers from the default group| server-tcp 8.8.8.8:53 -|server-tls|Upstream TLS DNS server|None|Repeatable
`[ip][:port]`: Server IP, port optional.
`[-spki-pin [sha256-pin]]`: TLS verify SPKI value, a base64 encoded SHA256 hash
`[-host-name]`:TLS Server name.
`[-tls-host-verify]`: TLS cert hostname to verify.
`[-blacklist-ip]`: The "-blacklist-ip" parameter is to filtering IPs which is configured by "blacklist-ip".
`[-whitelist-ip]`: whitelist-ip parameter specifies that only the IP range configured in whitelist-ip is accepted.
`[-group [group] ...]`: The group to which the DNS server belongs, such as office, foreign, use with nameserver.
`[-exclude-default-group]`: Exclude DNS servers from the default group| server-tls 8.8.8.8:853 -|server-https|Upstream HTTPS DNS server|None|Repeatable
`https://[host][:port]/path`: Server IP, port optional.
`[-spki-pin [sha256-pin]]`: TLS verify SPKI value, a base64 encoded SHA256 hash
`[-host-name]`:TLS Server name
`[-http-host]`:http header host.
`[-tls-host-verify]`: TLS cert hostname to verify.
`[-blacklist-ip]`: The "-blacklist-ip" parameter is to filtering IPs which is configured by "blacklist-ip".
`[-whitelist-ip]`: whitelist-ip parameter specifies that only the IP range configured in whitelist-ip is accepted.
`[-group [group] ...]`: The group to which the DNS server belongs, such as office, foreign, use with nameserver.
`[-exclude-default-group]`: Exclude DNS servers from the default group| server-https https://cloudflare-dns.com/dns-query -|speed-check-mode|Speed ​​mode|None|[ping\|tcp:[80]\|none]|speed-check-mode ping,tcp:443 -|address|Domain IP address|None|address /domain/[ip\|-\|-4\|-6\|#\|#4\|#6], `-` for ignore, `#` for return SOA, `4` for IPV4, `6` for IPV6| address /www.example.com/1.2.3.4 -|nameserver|To query domain with specific server group|None|nameserver /domain/[group\|-], `group` is the group name, `-` means ignore this rule, use the `-group` parameter in the related server|nameserver /www.example.com/office -|ipset|Domain IPSet|None|ipset /domain/[ipset\|-], `-` for ignore|ipset /www.example.com/pass -|ipset-timeout|ipset timeout enable|auto|[yes]|ipset-timeout yes -|bogus-nxdomain|bogus IP address|None|[IP/subnet], Repeatable| bogus-nxdomain 1.2.3.4/16 -|ignore-ip|ignore ip address|None|[ip/subnet], Repeatable| ignore-ip 1.2.3.4/16 -|whitelist-ip|ip whitelist|None|[ip/subnet], Repeatable,When the filtering server responds IPs in the IP whitelist, only result in whitelist will be accepted| whitelist-ip 1.2.3.4/16 -|blacklist-ip|ip blacklist|None|[ip/subnet], Repeatable,When the filtering server responds IPs in the IP blacklist, The result will be discarded directly| blacklist-ip 1.2.3.4/16 -|force-AAAA-SOA|force AAAA query return SOA|no|[yes\|no]|force-AAAA-SOA yes -|prefetch-domain|domain prefetch feature|no|[yes\|no]|prefetch-domain yes -|dualstack-ip-selection|Dualstack ip selection|no|[yes\|no]|dualstack-ip-selection yes -|dualstack-ip-selection-threshold|Dualstack ip select threadhold|30ms|millisecond|dualstack-ip-selection-threshold [0-1000] - -## FAQ - -1. What is the difference between SmartDNS and DNSMASQ? - Smartdns is not designed to replace DNSMASQ. The main function of Smartdns is focused on DNS resolution enhancement, the difference are: - * Multiple upstream server concurrent requests, after the results are measured, return the best results; - * `address`, `ipset` domain name matching uses efficient algorithms, query matching is faster and more efficient, and router devices are still efficient. - * Domain name matching supports ignoring specific domain names, and can be individually matched to IPv4, IPV6, and supports diversified customization. - * Enhance the ad blocking feature, return SOA record, this block ads better; - * IPV4, IPV6 dual stack IP optimization mechanism, in the case of dual network, choose the fastest network. - * Supports the latest TLS, HTTPS protocol and provides secure DNS query capabilities. - * DNS anti-poison mechanism, and a variety of mechanisms to avoid DNS pollution. - * ECS support, the query results are better and more accurate. - * IP blacklist support, ignoring the blacklist IP to make domain name queries better and more accurate. - * Domain name pre-fetch, more faster to access popular websites. - * Domain name TTL can be specified to make access faster. - * Cache mechanism to make access faster. - * Asynchronous log, audit log mechanism, does not affect DNS query performance while recording information. - * Domain group mechanism, specific domain names use specific upstream server group queries to avoid privacy leakage. - * The second DNS supports customizing more behavior. - -1. What is the best practices for upstream server configuration? - Smartdns has a speed measurement mechanism. When configuring an upstream server, it is recommended to configure multiple upstream DNS servers, including servers in different regions, but the total number is recommended to be around 10. Recommended configuration - * Carrier DNS. - * Public DNS, such as `8.8.8.8`, `8.8.4.4`, `1.1.1.1`. - - For specific domain names, if there is a pollution, you can enable the anti-pollution mechanism. - -1. How to enable the audit log - The audit log records the domain name requested by the client. The record information includes the request time, the request IP address, the request domain name, and the request type. If you want to enable the audit log, configure `audit-enable yes` in the configuration file, `audit-size`, `Audit-file`, `audit-num` configure the audit log file size, the audit log file path, and the number of audit log files. The audit log file will be compressed to save space. - -1. How to avoid DNS privacy leaks - By default, smartdns will send requests to all configured DNS servers. If the upstream DNS servers record DNS logs, it will result in a DNS privacy leak. To avoid privacy leaks, try the following steps: - * Use trusted DNS servers. - * Use TLS servers. - * Set up an upstream DNS server group. - -1. How to block ads - Smartdns has a high-performance domain name matching algorithm. It is very efficient to filter advertisements by domain name. To block ads, you only need to configure records like the following configure. For example, if you block `*.ad.com`, configure as follows: - - ```sh - Address /ad.com/# - ``` - - The suffix mode of the domain name, filtering *.ad.com, `#` means returning SOA record. If you want to only block IPV4 or IPV6 separately, add a number after `#`, such as `#4` is for IPV4 blocking. If you want to ignore some specific subdomains, you can configure it as follows. e.g., if you ignore `pass.ad.com`, you can configure it as follows: - - ```sh - Address /pass.ad.com/- - ``` - -1. DNS query diversion - In some cases, some domain names need to be queried using a specific DNS server to do DNS diversion. such as. - - ```sh - .home -> 192.168.1.1 - .office -> 10.0.0.1 - ``` - - The domain name ending in .home is sent to 192.168.1.1 for resolving - The domain name ending in .office is sent to 10.0.0.1 for resolving - Other domain names are resolved using the default mode. - The diversion configuration for this case is as follows: - - ```sh - # Upstream configuration, use -group to specify the group name, and -exclude-default-group to exclude the server from the default group. - Server 192.168.1.1 -group home -exclude-default-group - Server 10.0.0.1 -group office -exclude-default-group - Server 8.8.8.8 - - #Configure the resolved domain name with specific group - Nameserver /.home/home - Nameserver /.office/office - ``` - - You can use the above configuration to implement DNS resolution and offload. If you need to implement traffic distribution on the requesting port, you can configure the second DNS server. The bind configuration is added. The group parameter specifies the traffic distribution name. - - ```sh - Bind :7053 -group office - Bind :8053 -group home - ``` - -1. How to use the IPV4, IPV6 dual stack IP optimization feature - At present, IPV6 network is not as fast as IPV4 in some cases. In order to get a better experience in the dual-stack network, SmartDNS provides a dual-stack IP optimization mechanism, the same domain name, and the speed of IPV4. Far faster than IPV6, then SmartDNS will block the resolution of IPV6, let the PC use IPV4, the feature is enabled by `dualstack-ip-selection yes`, `dualstack-ip-selection-threshold [time]` is for threshold. if you want to disable IPV6 AAAA record complete, please try `force-AAAA-SOA yes`. - -1. How to improve cache performace - Smartdns provides a domain name caching mechanism to cache the queried domain name, and the caching time is in accordance with the DNS TTL specification. To increase the cache hit rate, the following configuration can be taken: - * Increase the number of cache records appropriately - Set the number of cache records by `cache-size`. - In the case of a query with a high pressure environment and a machine with a large memory, it can be appropriately adjusted. - - * Set the minimum TTL value as appropriate - Set the minimum DNS TTL time to a appropriate value by `rr-ttl-min` to extend the cache time. - It is recommended that the timeout period be set to 10 to 30 minutes to avoid then invalid domain names when domain ip changes. - - * Enable domain pre-acquisition - Enable pre-fetching of domain names with `prefetch-domain yes` to improve query hit rate. - by default, Smartdns will send domain query request again before cache expire, and cache the result for the next query. Frequently accessed domain names will continue to be cached. This feature will consume more CPU when idle. - -1. How does the second DNS customize more behavior? - The second DNS can be used as the upstream of other DNS servers to provide more query behaviors. Bind configuration support can bind multiple ports. Different ports can be set with different flags to implement different functions, such as - - ```sh - # Binding 6053 port, request for port 6053 will be configured with the upstream query of the office group, and the result will not be measured. The address configuration address is ignored. - bind [::]:6053 -no-speed-check -group office -no-rule-addr - ``` - -## Compile - -smartdns contains scripts for compiling packages, supports compiling luci, debian, openwrt, opare installation packages, and can execute `package/build-pkg.sh` compilation. - -## [Donate](#Donate) - -If you feel that this project is helpful to you, please donate to us so that the project can continue to develop and be more perfect. - -### PayPal - -[![Support via PayPal](https://cdn.rawgit.com/twolfson/paypal-github-button/1.0.0/dist/button.svg)](https://paypal.me/PengNick/) - -### Alipay - -![alipay](doc/alipay_donate.jpg) - -### Wechat - -![wechat](doc/wechat_donate.jpg) - -## Open Source License - -Smartdns is licensed to the public under the GPL V3 License. +# SmartDNS + +![SmartDNS](doc/smartdns-banner.png) +SmartDNS is a local DNS server. SmartDNS accepts DNS query requests from local clients, obtains DNS query results from multiple upstream DNS servers, and returns the fastest access results to clients. +Avoiding DNS pollution and improving network access speed, supports high-performance ad filtering. +Unlike dnsmasq's all-servers, smartdns returns the fastest access resolution. ([read more](#faq)) + +Support Raspberry Pi, openwrt, ASUS router, Windows and other devices. + +## Table Of Content + +1. [Software Show](#software-show) +1. [Features](#features) +1. [Architecture](#architecture) +1. [Usage](#usage) + 1. [Download the package](#download-the-package) + 1. [Standard Linux system installation/Raspberry Pi, X86_64 system](#standard-linux-system-installation/raspberry-pi,-x86_64-system) + 1. [openwrt/LEDE](#openwrt/lede) + 1. [ASUS router native firmware / Merlin firmware](#asus-router-native-firmware-/-merlin-firmware) + 1. [optware/entware](#optware/entware) + 1. [Windows 10 WSL Installation/WSL ubuntu](#windows-10-wsl-installation/wsl-ubuntu) +1. [Configuration parameter](#configuration-parameter) +1. [Donate](#Donate) +1. [FAQ](#FAQ) + +## Software Show + +**Ali DNS** +Use Ali DNS to query Baidu's IP and test the results. + +```shell +pi@raspberrypi:~/code/smartdns_build $ nslookup www.baidu.com 223.5.5.5 +Server: 223.5.5.5 +Address: 223.5.5.5#53 + +Non-authoritative answer: +www.baidu.com canonical name = www.a.shifen.com. +Name: www.a.shifen.com +Address: 180.97.33.108 +Name: www.a.shifen.com +Address: 180.97.33.107 + +pi@raspberrypi:~/code/smartdns_build $ ping 180.97.33.107 -c 2 +PING 180.97.33.107 (180.97.33.107) 56(84) bytes of data. +64 bytes from 180.97.33.107: icmp_seq=1 ttl=55 time=24.3 ms +64 bytes from 180.97.33.107: icmp_seq=2 ttl=55 time=24.2 ms + +--- 180.97.33.107 ping statistics --- +2 packets transmitted, 2 received, 0% packet loss, time 1001ms +rtt min/avg/max/mdev = 24.275/24.327/24.380/0.164 ms +pi@raspberrypi:~/code/smartdns_build $ ping 180.97.33.108 -c 2 +PING 180.97.33.108 (180.97.33.108) 56(84) bytes of data. +64 bytes from 180.97.33.108: icmp_seq=1 ttl=55 time=31.1 ms +64 bytes from 180.97.33.108: icmp_seq=2 ttl=55 time=31.0 ms + +--- 180.97.33.108 ping statistics --- +2 packets transmitted, 2 received, 0% packet loss, time 1001ms +rtt min/avg/max/mdev = 31.014/31.094/31.175/0.193 ms +``` + +**smartdns** +Use SmartDNS to query Baidu IP and test the results. + +```shell +pi@raspberrypi:~/code/smartdns_build $ nslookup www.baidu.com +Server: 192.168.1.1 +Address: 192.168.1.1#53 + +Non-authoritative answer: +www.baidu.com canonical name = www.a.shifen.com. +Name: www.a.shifen.com +Address: 14.215.177.39 + +pi@raspberrypi:~/code/smartdns_build $ ping 14.215.177.39 -c 2 +PING 14.215.177.39 (14.215.177.39) 56(84) bytes of data. +64 bytes from 14.215.177.39: icmp_seq=1 ttl=56 time=6.31 ms +64 bytes from 14.215.177.39: icmp_seq=2 ttl=56 time=5.95 ms + +--- 14.215.177.39 ping statistics --- +2 packets transmitted, 2 received, 0% packet loss, time 1001ms +rtt min/avg/max/mdev = 5.954/6.133/6.313/0.195 ms + +``` + +From the comparison, smartdns found the fastest IP address to visit www.baidu.com, so accessing Baidu's DNS is 5 times faster than Ali DNS. + +## Features + +1. **Multiple upstream DNS servers** + Support configuring multiple upstream DNS servers and query at the same time.the query will not be affected, Even if there is a DNS server exception. + +2. **Return the fastest IP address** + Supports finding the fastest access IP address from the IP address list of the domain name and returning it to the client to avoid DNS pollution and improve network access speed. + +3. **Support for multiple query protocols** + Support UDP, TCP, TLS, HTTPS queries, and non-53 port queries, effectively avoiding DNS pollution. + +4. **Domain IP address specification** + Support configuring IP address of specific domain to achieve the effect of advertising filtering, and avoid malicious websites. + +5. **Domain name high performance rule filtering** + Support domain name suffix matching mode, simplify filtering configuration, filter 200,000 recording and take time <1ms. + +6. **Linux/Windows multi-platform support** + Support standard Linux system (Raspberry Pi), openwrt system various firmware, ASUS router native firmware. Support Windows 10 WSL (Windows Subsystem for Linux). + +7. **Support IPV4, IPV6 dual stack** + Support IPV4, IPV6 network, support query A, AAAA record, dual-stack IP selection, and disale IPV6 AAAA record. + +8. **High performance, low resource consumption** + Multi-threaded asynchronous IO mode, cache cache query results. + +## Architecture + +![Architecture](doc/architecture.png) + +1. SmartDNS receives DNS query requests from local network devices, such as PCs and mobile phone query requests. +2. SmartDNS sends query requests to multiple upstream DNS servers, using standard UDP queries, non-standard port UDP queries, and TCP queries. +3. The upstream DNS server returns a list of Server IP addresses corresponding to the domain name. SmartDNS detects the fastest Server IP with local network access. +4. Return the fastest accessed Server IP to the local client. + +## Usage + +### Download the package + +-------------- + +Download the matching version of the SmartDNS installation package. The corresponding installation package is as follows. + +|system |package|Description +|-----|-----|----- +|Standard Linux system (Raspberry Pi)| smartdns.xxxxxxxx.arm-debian-all.deb|Support Raspberry Pi Raspbian stretch, Debian 9 system. +|Standard Linux system (Armbian arm64)| smartdns.xxxxxxxx.aarch64-debian-all.deb|Support Armbian debian stretch, Debian 9 system. +|Standard Linux system (x86_64)| smartdns.xxxxxxxx.x86_64-linux-all.tar.gz|Support for x86_64 Linux systems. +|Windows 10 WSL (ubuntu)| smartdns.xxxxxxxx.x86_64-linux-all.tar.gz|Windows 10 WSL ubuntu. +|Standard Linux system (x86)| smartdns.xxxxxxxx.x86-linux-all.tar.gz|Support for x86_64 systems. +|optware|smartdns.xxxxxxxx.mips-optware-all.ipk|Support the MIPS big-endian architecture for optware。 +|optware|smartdns.xxxxxxxx.mipsel-optware-all.ipk|Support the MIPS little-endian architecture for optware。 +|optware|smartdns.xxxxxxxx.arm-optware-all.ipk|Support the arm architecture for optware。 +|openwrt|smartdns.xxxxxxxx.mips-openwrt-all.ipk|Support the MIPS big-endian architecture for openwrt。 +|openwrt|smartdns.xxxxxxxx.mipsel-openwrt-all.ipk|Support the MIPS little-endian architecture for openwrt。 +|openwrt|smartdns.xxxxxxxx.arm-openwrt-all.ipk|Support the arm architecture for openwrt。 +|openwrt LUCI|luci-app-smartdns.xxxxxxxxx.all.ipk|Openwrt management interface. +|openwrt LUCI|luci-app-smartdns.xxxxxxxxx.all-luci-compat-all|Compat Openwrt management interface for early openwrt. + +* The released packages are statically compiled. If you need a small size package, please compile it yourself or obtain it from the openwrt / entware repository. + +* **Please download from the Release page: [Download here](https://github.com/pymu/smartdns/releases)** + +```shell +https://github.com/pymumu/smartdns/releases +``` + +* For the installation procedure, please refer to the following sections. + +### Standard Linux system installation/Raspberry Pi, X86_64 system + +-------------- + +1. Installation + + Download the installation package like `smartdns.xxxxxxxx.arm-debian-all.deb` and upload it to the Linux system. Run the following command to install + + ```shell + dpkg -i smartdns.xxxxxxxx.arm-debian-all.deb + ``` + + For X86-64 system, download the installation package like `smartdns.xxxxxxxx.x86_64-linux-all.tar.gz` and upload it to the Linux system. Run the following command to install + + ```shell + tar zxf smartdns.xxxxxxxx.x86_64-linux-all.tar.gz + cd smartdns + chmod +x ./install + ./install -i + ``` + +1. Configuration + + After the installation is complete, you can configure the upstream server to smartdns. Refer to the `Configuration Parameters` for specific configuration parameters. + In general, you only need to add `server [IP]:port`, `server-tcp [IP]:port` configuration items. + Configure as many upstream DNS servers as possible, including servers at home and abroad. Please refer to the `Configuration Parameters` section for configuration parameters. + + ```shell + vi /etc/smartdns/smartdns.conf + ``` + +1. Start Service + + ```shell + systemctl enable smartdns + systemctl start smartdns + ``` + +1. Forwarding DNS request to SmartDNS + + Modify the DNS server of the local router and configure the DNS server as SmartDNS. + * Log in to the router on the local network and configure the Raspberry Pi to assign a static IP address. + * Modify the WAN port or DHCP DNS to the Raspberry Pi IP address. + Note: + I. Each router configuration method is different. Please search Baidu for related configuration methods. + II. some routers may not support configuring custom DNS server. in this case, please modify the PC's, mobile phone's DNS server to the ip of Raspberry Pi. + +1. Check if the service is configured successfully + + Query domain name with `nslookup -querytype=ptr smartdns` + Check if the `name` item in the command result is displayed as `smartdns` or `hostname`, such as `smartdns` + + ```shell + pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr smartdns + Server: 192.168.1.1 + Address: 192.168.1.1#53 + + Non-authoritative answer: + smartdns name = smartdns. + ``` + +### openwrt + +-------------- + +1. Installation + + Upload the software to the /root directory of the router with winscp or other tool, and execute the following command to install it. + + ```shell + opkg install smartdns.xxxxxxxx.xxxx.ipk + opkg install luci-app-smartdns.xxxxxxxx.xxxx.all.ipk + ``` + + * Note: For versions before openwrt 19.07, please install `luci-app-smartdns.xxxxxxxxx.all-luci-compat-all` package. + +1. Configuration + + Log in to the openwrt management page and open `Services`->`SmartDNS` to configure SmartDNS. + * Add upstream DNS server configuration to `Upstream Servers`. It is recommended to configure multiple DNS servers at home and abroad. + * Specify the IP address of a specific domain name in `Domain Address`, which can be used for ad blocking. + +1. Start Service + + There are two ways to use the SmartDNS service, `one is directly as the primary DNS service`, `the other is as the upstream of dnsmasq`. + By default, SmartDNS uses the first method. You can choose according to your needs in the following two ways. + +1. Method 1: SmartDNS as primary DNS Server (default scheme) + + * **Enable SmartDNS port 53 port redirection** + + Log in to the router, click on `Services`->`SmartDNS`->`redirect`, select `Redirect 53 port to SmartDNS` option to enable port 53 forwarding. + + * **Check if the service is configured successfully** + + Query domain name with `nslookup -querytype=ptr smartdns` + See if the `name` item in the command result is displayed as `smartdns` or `hostname`, such as `smartdns` + + ```shell + pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr smartdns + Server: 192.168.1.1 + Address: 192.168.1.1#53 + + Non-authoritative answer: + smartdns name = smartdns. + ``` + + * **The interface prompts that the redirect failed** + + * Check if iptable, ip6table command is installed correctly. + * The openwrt 15.01 system does not support IPV6 redirection. If the network needs to support IPV6, please change DNSMASQ upstream to smartdns, or change the smartdns port to 53, and disable dnsmasq. + * After LEDE system, please install IPV6 nat forwarding driver. Click `system`->`Software`, click `update lists` to update the software list, install `ip6tables-mod-nat` + * Use the following command to check whether the routing rule takes effect. + + ```shell + iptables -t nat -L PREROUTING | grep REDIRECT + ``` + + * If the forwarding function is abnormal, please use Method 2: As the upstream of DNSMASQ. + +1. Method 2: SmartDNS as upstream DNS Server of DNSMASQ + + * **Forward dnsmasq's request to SmartDNS** + + Log in to the router, click on `Services`->`SmartDNS`->`redirect`, select `Run as dnsmasq upstream server` option to forwarding dnsmasq request to Smartdns. + + * **Check if the service is configured successfully** + + * Method 1: Query domain name with `nslookup -querytype=ptr 0.0.0.1` + See if the `name` item in the command result is displayed as `smartdns` or `hostname`, such as `smartdns` + + ```shell + pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr smartdns + Server: 192.168.1.1 + Address: 192.168.1.1#53 + + Non-authoritative answer: + smartdns name = smartdns. + ``` + + * Method 2: Use `nslookup` to query the `www.baidu.com` domain name to see if the IP address of Baidu in the result is `only one. If there are multiple IP addresses returned, it means that it is not valid. Please try to check several domain names. + + ```shell + pi@raspberrypi:~ $ nslookup www.baidu.com 192.168.1.1 + Server: 192.168.1.1 + Address: 192.168.1.1#53 + + Non-authoritative answer: + www.baidu.com canonical name = www.a.shifen.com. + Name: www.a.shifen.com + Address: 14.215.177.38 + ``` + +1. Start Service + + Check the `Enable' in the configuration page to start SmartDNS server. + +1. Note + + * If chinaDNS is already installed, it is recommended to configure the upstream of chinaDNS as SmartDNS. + * SmartDNS defaults to forwarding port 53 requests to the local port of SmartDNS, controlled by the `Redirect` configuration option. + +### ASUS router native firmware / Merlin firmware + +-------------- + +Note: Merlin firmware is derived from ASUS firmware and can theoretically be used directly with the ASUS package. However, it is currently unverified. If you have any questions, please submit an issue. + +1. Prepare + + When using this software, you need to confirm whether the router supports U disk and prepare a USB disk. + +1. Enable SSH login + + Log in to the management interface, click `System Management`-> Click `System Settings` and configure `Enable SSH` to `Lan Only`. + The SSH login username and password are the same as the management interface. + +1. Insstall `Download Master` + + In the management interface, click `USB related application`-> click `Download Master` to download. + After the download is complete, enable `Download Master`. If you do not need the download function, you can uninstall `Download Master` here, but make sure that Download Master is enabled before uninstalling. + +1. Install SmartDNS + + Upload the software to the router's `/tmp/mnt/sda1` directory using winscp. (or copy the network neighborhood to the sda1 shared directory) + + ```shell + ipkg install smartdns.xxxxxxx.mipsbig.ipk + ``` + +1. Restart router + + After the router is started, use `nslookup -querytype=ptr smartdns` to query the domain name. + See if the `name` item in the command result is displayed as `smartdns` or `hostname`, such as `smartdns` + + ```shell + pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr smartdns + Server: 192.168.1.1 + Address: 192.168.1.1#53 + + Non-authoritative answer: + smartdns name = smartdns. + ``` + +1. Note + + In the above process, smartdns will be installed to the root directory of the U disk and run in optware mode. + Its directory structure is as follows: (only smartdns related files are listed here) + + ```shell + USB DISK + └── asusware.mipsbig + ├── bin + ├── etc + | ├── smartdns + | | └── smartdns.conf + | └── init.d + | └── S50smartdns + ├── lib + ├── sbin + ├── usr + | └── sbin + | └── smartdns + .... + ``` + + To modify the configuration, you can use ssh to login to the router and use the vi command to modify it. + + ```shell + vi /opt/etc/smartdns/smartdns.conf + ``` + + It can also be modified from Network Neighborhood. From the neighbor sharing directory `sda1` you can't see the `asusware.mipsbig` directory, but you can directly enter `asusware.mipsbig\etc\init.d` in `File Manager` to modify it. + + ```shell + \\192.168.1.1\sda1\asusware.mipsbig\etc\init.d + ``` + +### optware/entware + +-------------- + +1. Prepare + + When using this software, you need to confirm whether the router supports USB disk and prepare a USB disk. + +1. Install SmartDNS + + Upload the software to `/tmp` directory of the router using winscp, and run the flollowing command to install. + + ```shell + ipkg install smartdns.xxxxxxx.mipsbig.ipk + ``` + +1. Modify the smartdns configuration + + ```shell + Vi /opt/etc/smartdns/smartdns.conf + ``` + + Note: if you need to support IPV6, you can set the worke-mode to `2`, this will disable the DNS service of dnsmasq, and smartdns run as the primary DNS server. Change `SMARTDNS_WORKMODE` in the file `/opt/etc/smartdns/smartdns-opt.conf` to 2. + + ```shell + SMARTDNS_WORKMODE="2" + ``` + +1. Restart the router to take effect + + After the router is started, use `nslookup -querytype=ptr smartdns` to query the domain name. + See if the `name` item in the command result is displayed as `smartdns` or `hostname`, such as `smartdns` + + ```shell + Pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr smartdns + Server: 192.168.1.1 + Address: 192.168.1.1#53 + + Non-authoritative answer: + smartdns name = smartdns. + ``` + + Note: If the service does not start automatically, you need to set optwre/entware to start automatically. For details, see the optware/entware documentation. + +### Windows 10 WSL Installation/WSL ubuntu + +-------------- + +1. Install Windows 10 WSL ubuntu + + Install the Windows 10 WSL environment and select Ubuntu as default distribution. Please refer to [WSL installation instructions](https://docs.microsoft.com/en-us/windows/wsl/install-win10) for installation steps + +1. Install smartdns + + download install package `smartdns.xxxxxxxx.x86_64-linux-all.tar.gz`,and unzip to the `D:\` directory, after decompression, the directory is as follows: + + ```shell + D:\SMARTDNS + ├─etc + │ ├─default + │ ├─init.d + │ └─smartdns + ├─package + │ └─windows + ├─src + └─systemd + + ``` + + Double-click `install.bat` in the `D:\smartdns\package\windows` directory for installation. Please enter the password for `WLS ubuntu` when input password. + +1. Configuration + + Edit `smartdns.conf` configuration file in `D:\smartdns\etc\smartdns` directory, you can configure the upstream server to smartdns. Refer to the `Configuration Parameters` for specific configuration parameters. + In general, you only need to add `server [IP]:port`, `server-tcp [IP]:port` configuration items. + Configure as many upstream DNS servers as possible, including servers at home and abroad. Please refer to the `Configuration Parameters` section for configuration parameters. + +1. Start Service + + Double-click `reload.bat` in the `D:\smartdns\package\windows` directory for reload. + +1. Forwarding DNS request to SmartDNS + + Modify the default DNS server for Windows to `127.0.0.1`, with these steps referred to [IP configuration](https://support.microsoft.com/en-us/help/15089/windows-change-tcp-ip-settings) + +1. Check if the service is configured successfully + + Query domain name with `nslookup -querytype=ptr smartdns` + Check if the `name` item in the command result is displayed as `smartdns` or `hostname`, such as `smartdns` + + ```shell + pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr smartdns + Server: 192.168.1.1 + Address: 192.168.1.1#53 + + Non-authoritative answer: + smartdns name = smartdns. + ``` + +## Configuration parameter + +|parameter|Parameter function|Default value|Value type|Example| +|--|--|--|--|--| +|server-name|DNS name|host name/smartdns|any string like hosname|server-name smartdns +|bind|DNS listening port number|[::]:53|Support binding multiple ports
`IP:PORT`: server IP, port number.
`[-group]`: The DNS server group used when requesting.
`[-no-rule-addr]`: Skip the address rule.
`[-no-rule-nameserver]`: Skip the Nameserver rule.
`[-no-rule-ipset]`: Skip the Ipset rule.
`[-no-rule-soa]`: Skip address SOA(#) rules.
`[-no-dualstack-selection]`: Disable dualstack ip selection.
`[-no-speed-check]`: Disable speed measurement.
`[-no-cache]`: stop caching |bind :53 +|bind-tcp|TCP mode DNS listening port number|[::]:53|Support binding multiple ports
`IP:PORT`: server IP, port number.
`[-group]`: The DNS server group used when requesting.
`[-no-rule-addr]`: Skip the address rule.
`[-no-rule-nameserver]`: Skip the Nameserver rule.
`[-no-rule-ipset]`: Skip the Ipset rule.
`[-no-rule-soa]`: Skip address SOA(#) rules.
`[-no-dualstack-selection]`: Disable dualstack ip selection.
`[-no-speed-check]`: Disable speed measurement.
`[-no-cache]`: stop caching |bind-tcp :53 +|cache-size|Domain name result cache number|512|integer|cache-size 512 +|tcp-idle-time|TCP connection idle timeout|120|integer|tcp-idle-time 120 +|rr-ttl|Domain name TTL|Remote query result|number greater than 0|rr-ttl 600 +|rr-ttl-min|Domain name Minimum TTL|Remote query result|number greater than 0|rr-ttl-min 60 +|rr-ttl-max|Domain name Maximum TTL|Remote query result|number greater than 0|rr-ttl-max 600 +|log-level|log level|error|fatal,error,warn,notice,info,debug|log-level error +|log-file|log path|/var/log/smartdns.log|File Pah|log-file /var/log/smartdns.log +|log-size|log size|128K|number+K,M,G|log-size 128K +|log-num|archived log number|2|Integer|log-num 2 +|audit-enable|audit log enable|no|[yes\|no]|audit-enable yes +|audit-file|audit log file|/var/log/smartdns-audit.log|File Path|audit-file /var/log/smartdns-audit.log +|audit-size|audit log size|128K|number+K,M,G|audit-size 128K +|audit-num|archived audit log number|2|Integer|audit-num 2 +|conf-file|additional conf file|None|File path|conf-file /etc/smartdns/smartdns.more.conf +|server|Upstream UDP DNS server|None|Repeatable
`[ip][:port]`: Server IP, port optional.
`[-blacklist-ip]`: The "-blacklist-ip" parameter is to filtering IPs which is configured by "blacklist-ip".
`[-whitelist-ip]`: whitelist-ip parameter specifies that only the IP range configured in whitelist-ip is accepted.
`[-group [group] ...]`: The group to which the DNS server belongs, such as office, foreign, use with nameserver.
`[-exclude-default-group]`: Exclude DNS servers from the default group| server 8.8.8.8:53 -blacklist-ip +|server-tcp|Upstream TCP DNS server|None|Repeatable
`[ip][:port]`: Server IP, port optional.
`[-blacklist-ip]`: The "-blacklist-ip" parameter is to filtering IPs which is configured by "blacklist-ip".
`[-whitelist-ip]`: whitelist-ip parameter specifies that only the IP range configured in whitelist-ip is accepted.
`[-group [group] ...]`: The group to which the DNS server belongs, such as office, foreign, use with nameserver.
`[-exclude-default-group]`: Exclude DNS servers from the default group| server-tcp 8.8.8.8:53 +|server-tls|Upstream TLS DNS server|None|Repeatable
`[ip][:port]`: Server IP, port optional.
`[-spki-pin [sha256-pin]]`: TLS verify SPKI value, a base64 encoded SHA256 hash
`[-host-name]`:TLS Server name.
`[-tls-host-verify]`: TLS cert hostname to verify.
`-no-check-certificate:`: No check certificate.
`[-blacklist-ip]`: The "-blacklist-ip" parameter is to filtering IPs which is configured by "blacklist-ip".
`[-whitelist-ip]`: whitelist-ip parameter specifies that only the IP range configured in whitelist-ip is accepted.
`[-group [group] ...]`: The group to which the DNS server belongs, such as office, foreign, use with nameserver.
`[-exclude-default-group]`: Exclude DNS servers from the default group| server-tls 8.8.8.8:853 +|server-https|Upstream HTTPS DNS server|None|Repeatable
`https://[host][:port]/path`: Server IP, port optional.
`[-spki-pin [sha256-pin]]`: TLS verify SPKI value, a base64 encoded SHA256 hash
`[-host-name]`:TLS Server name
`[-http-host]`:http header host.
`[-tls-host-verify]`: TLS cert hostname to verify.
`-no-check-certificate:`: No check certificate.
`[-blacklist-ip]`: The "-blacklist-ip" parameter is to filtering IPs which is configured by "blacklist-ip".
`[-whitelist-ip]`: whitelist-ip parameter specifies that only the IP range configured in whitelist-ip is accepted.
`[-group [group] ...]`: The group to which the DNS server belongs, such as office, foreign, use with nameserver.
`[-exclude-default-group]`: Exclude DNS servers from the default group| server-https https://cloudflare-dns.com/dns-query +|speed-check-mode|Speed ​​mode|None|[ping\|tcp:[80]\|none]|speed-check-mode ping,tcp:443 +|address|Domain IP address|None|address /domain/[ip\|-\|-4\|-6\|#\|#4\|#6], `-` for ignore, `#` for return SOA, `4` for IPV4, `6` for IPV6| address /www.example.com/1.2.3.4 +|nameserver|To query domain with specific server group|None|nameserver /domain/[group\|-], `group` is the group name, `-` means ignore this rule, use the `-group` parameter in the related server|nameserver /www.example.com/office +|ipset|Domain IPSet|None|ipset /domain/[ipset\|-], `-` for ignore|ipset /www.example.com/pass +|ipset-timeout|ipset timeout enable|auto|[yes]|ipset-timeout yes +|domain-rules|set domain rules|None|domain-rules /domain/ [-rules...]
`[-speed-check-mode]`: set speed check mode,same as parameter `speed-check-mode`
`[-address]`: same as parameter `address`
`[-nameserver]`: same as parameter `nameserver`
`[-ipset]`: same as parameter `ipset`|domain-rules /www.example.com/ -speed-check-mode none +|bogus-nxdomain|bogus IP address|None|[IP/subnet], Repeatable| bogus-nxdomain 1.2.3.4/16 +|ignore-ip|ignore ip address|None|[ip/subnet], Repeatable| ignore-ip 1.2.3.4/16 +|whitelist-ip|ip whitelist|None|[ip/subnet], Repeatable,When the filtering server responds IPs in the IP whitelist, only result in whitelist will be accepted| whitelist-ip 1.2.3.4/16 +|blacklist-ip|ip blacklist|None|[ip/subnet], Repeatable,When the filtering server responds IPs in the IP blacklist, The result will be discarded directly| blacklist-ip 1.2.3.4/16 +|force-AAAA-SOA|force AAAA query return SOA|no|[yes\|no]|force-AAAA-SOA yes +|prefetch-domain|domain prefetch feature|no|[yes\|no]|prefetch-domain yes +|serve-expired|Cache serve expired feature|no|[yes\|no], Attempts to serve old responses from cache with a TTL of 0 in the response without waiting for the actual resolution to finish.|serve-expired yes +|serve-expired-ttl|Cache serve expired limite TTL|0|second,0:disable,> 0 seconds after expiration|serve-expired-ttl 0 +|dualstack-ip-selection|Dualstack ip selection|no|[yes\|no]|dualstack-ip-selection yes +|dualstack-ip-selection-threshold|Dualstack ip select threadhold|30ms|millisecond|dualstack-ip-selection-threshold [0-1000] +|ca-file|certificate file|/etc/ssl/certs/ca-certificates.crt|path|ca-file /etc/ssl/certs/ca-certificates.crt +|ca-path|certificates path|/etc/ssl/certs|path|ca-path /etc/ssl/certs + +## FAQ + +1. What is the difference between SmartDNS and DNSMASQ? + Smartdns is not designed to replace DNSMASQ. The main function of Smartdns is focused on DNS resolution enhancement, the difference are: + * Multiple upstream server concurrent requests, after the results are measured, return the best results; + * `address`, `ipset` domain name matching uses efficient algorithms, query matching is faster and more efficient, and router devices are still efficient. + * Domain name matching supports ignoring specific domain names, and can be individually matched to IPv4, IPV6, and supports diversified customization. + * Enhance the ad blocking feature, return SOA record, this block ads better; + * IPV4, IPV6 dual stack IP optimization mechanism, in the case of dual network, choose the fastest network. + * Supports the latest TLS, HTTPS protocol and provides secure DNS query capabilities. + * DNS anti-poison mechanism, and a variety of mechanisms to avoid DNS pollution. + * ECS support, the query results are better and more accurate. + * IP blacklist support, ignoring the blacklist IP to make domain name queries better and more accurate. + * Domain name pre-fetch, more faster to access popular websites. + * Domain name TTL can be specified to make access faster. + * Cache mechanism to make access faster. + * Asynchronous log, audit log mechanism, does not affect DNS query performance while recording information. + * Domain group mechanism, specific domain names use specific upstream server group queries to avoid privacy leakage. + * The second DNS supports customizing more behavior. + +1. What is the best practices for upstream server configuration? + Smartdns has a speed measurement mechanism. When configuring an upstream server, it is recommended to configure multiple upstream DNS servers, including servers in different regions, but the total number is recommended to be around 10. Recommended configuration + * Carrier DNS. + * Public DNS, such as `8.8.8.8`, `8.8.4.4`, `1.1.1.1`. + + For specific domain names, if there is a pollution, you can enable the anti-pollution mechanism. + +1. How to enable the audit log + The audit log records the domain name requested by the client. The record information includes the request time, the request IP address, the request domain name, and the request type. If you want to enable the audit log, configure `audit-enable yes` in the configuration file, `audit-size`, `Audit-file`, `audit-num` configure the audit log file size, the audit log file path, and the number of audit log files. The audit log file will be compressed to save space. + +1. How to avoid DNS privacy leaks + By default, smartdns will send requests to all configured DNS servers. If the upstream DNS servers record DNS logs, it will result in a DNS privacy leak. To avoid privacy leaks, try the following steps: + * Use trusted DNS servers. + * Use TLS servers. + * Set up an upstream DNS server group. + +1. How to block ads + Smartdns has a high-performance domain name matching algorithm. It is very efficient to filter advertisements by domain name. To block ads, you only need to configure records like the following configure. For example, if you block `*.ad.com`, configure as follows: + + ```sh + Address /ad.com/# + ``` + + The suffix mode of the domain name, filtering *.ad.com, `#` means returning SOA record. If you want to only block IPV4 or IPV6 separately, add a number after `#`, such as `#4` is for IPV4 blocking. If you want to ignore some specific subdomains, you can configure it as follows. e.g., if you ignore `pass.ad.com`, you can configure it as follows: + + ```sh + Address /pass.ad.com/- + ``` + +1. DNS query diversion + In some cases, some domain names need to be queried using a specific DNS server to do DNS diversion. such as. + + ```sh + .home -> 192.168.1.1 + .office -> 10.0.0.1 + ``` + + The domain name ending in .home is sent to 192.168.1.1 for resolving + The domain name ending in .office is sent to 10.0.0.1 for resolving + Other domain names are resolved using the default mode. + The diversion configuration for this case is as follows: + + ```sh + # Upstream configuration, use -group to specify the group name, and -exclude-default-group to exclude the server from the default group. + Server 192.168.1.1 -group home -exclude-default-group + Server 10.0.0.1 -group office -exclude-default-group + Server 8.8.8.8 + + #Configure the resolved domain name with specific group + Nameserver /.home/home + Nameserver /.office/office + ``` + + You can use the above configuration to implement DNS resolution and offload. If you need to implement traffic distribution on the requesting port, you can configure the second DNS server. The bind configuration is added. The group parameter specifies the traffic distribution name. + + ```sh + Bind :7053 -group office + Bind :8053 -group home + ``` + +1. How to use the IPV4, IPV6 dual stack IP optimization feature + At present, IPV6 network is not as fast as IPV4 in some cases. In order to get a better experience in the dual-stack network, SmartDNS provides a dual-stack IP optimization mechanism, the same domain name, and the speed of IPV4. Far faster than IPV6, then SmartDNS will block the resolution of IPV6, let the PC use IPV4, the feature is enabled by `dualstack-ip-selection yes`, `dualstack-ip-selection-threshold [time]` is for threshold. if you want to disable IPV6 AAAA record complete, please try `force-AAAA-SOA yes`. + +1. How to improve cache performace + Smartdns provides a domain name caching mechanism to cache the queried domain name, and the caching time is in accordance with the DNS TTL specification. To increase the cache hit rate, the following configuration can be taken: + * Increase the number of cache records appropriately + Set the number of cache records by `cache-size`. + In the case of a query with a high pressure environment and a machine with a large memory, it can be appropriately adjusted. + + * Set the minimum TTL value as appropriate + Set the minimum DNS TTL time to a appropriate value by `rr-ttl-min` to extend the cache time. + It is recommended that the timeout period be set to 10 to 30 minutes to avoid then invalid domain names when domain ip changes. + + * Enable domain pre-acquisition + Enable pre-fetching of domain names with `prefetch-domain yes` to improve query hit rate. + by default, Smartdns will send domain query request again before cache expire, and cache the result for the next query. Frequently accessed domain names will continue to be cached. This feature will consume more CPU when idle. + + * Cache serve expired feature + Enable cache serve expired feature with `serve-expired yes` to improve the cache hit rate and reduce the CPU consumption. + This feature will return TTL = 0 to the client after the TTL timeout, and send a new query request again at the same time, and cache the new results for later query. + +1. How does the second DNS customize more behavior? + The second DNS can be used as the upstream of other DNS servers to provide more query behaviors. Bind configuration support can bind multiple ports. Different ports can be set with different flags to implement different functions, such as + + ```sh + # Binding 6053 port, request for port 6053 will be configured with the upstream query of the office group, and the result will not be measured. The address configuration address is ignored. + bind [::]:6053 -no-speed-check -group office -no-rule-addr + ``` + +## Compile + +smartdns contains scripts for compiling packages, supports compiling luci, debian, openwrt, opare installation packages, and can execute `package/build-pkg.sh` compilation. + +## [Donate](#Donate) + +If you feel that this project is helpful to you, please donate to us so that the project can continue to develop and be more perfect. + +### PayPal + +[![Support via PayPal](https://cdn.rawgit.com/twolfson/paypal-github-button/1.0.0/dist/button.svg)](https://paypal.me/PengNick/) + +### Alipay + +![alipay](doc/alipay_donate.jpg) + +### Wechat + +![wechat](doc/wechat_donate.jpg) + +## Open Source License + +Smartdns is licensed to the public under the GPL V3 License. diff --git a/release/src/router/smartdns/doc/alipay_donate.jpg b/release/src/router/smartdns/doc/alipay_donate.jpg index 73ee72c26505351075cea6c7c6dceadb1d76fb51..7ce3d7d83ed49ba0d358127ed79f3a494a654c5f 100644 GIT binary patch literal 53406 zcmb@u3p`ZY|3ADLm)shWq}w=ADn#xflP)AlccGd}NMe%QYRr~G7jjEZiOEr^#FT5f z4Y@@jDVGsrj1n0$LygVM?0MGcob&zu{{R2;dOgqcdUglfHhb;8*7~gX=l%J7-s^~a z#DkFPP6sCkNJmUf42gyn;fn>oM_z1L9YU#h{`=r)D zn7QlH;EyH{_zo=uUmkIOkj&h52nqy0B?oAE?*6%-CdMYl*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TKD@Z~OCyNd4cl#8c z9y+djb$@wNQF>yZxoWP@4`FBCU2AP3W!uY^0DTm~Uu~ECeaqvJTaMy~0Z*t@FjV>X zI{w6UxJ};X;4%>1M#f3&-+;=Z2xX#)*yk_jVngl;*VfWrLpwlGoBqgfhVK^;F$6?w zFW*%+ETF!Q1;n?%VoXacnAh^>&y-0hVg!qyc>K%JFWLt{XxORQt?5OFCaznQWIkTng$HpBFX&C z{PB$V_9XjK@cD_C20;hZ7gMXAsy9R#aDKm=M~ID{tfTNvZ$T^{t=p1fXffysIwJ-bEe)~f-AQcg1A5bBT38G zS92gH^+4CggqU~L21!>G7l?m9cm2*iRNlTz}HIIs%ZQj1M$6Baa%6s7wS^U6g+>lZ`-5)AHLbndKslxKNyzo+05<- zA(pQu@lAw$bbDWKSMpPr1K*0SWX1T(Ri%B>lWllmBVM#t#C}}eF>;B^f_qaV77v>2PD>!A>NV{zCQb<*hoB7=pcB&pA5w z-?w29J?YUz7{{~^^$sLIX+Q9-BRne#S*b62vW@1kr<`q3&xBi~Z%>GC+adbJ4r)?8 zluE*7sQV$)%W<#Ov|%EIT9mAQ;DbSinV(LS%80&_T)lc+F{24GIM~P(9S(tosZ^rG z6dPp_U1ywp)8ZJe*|+PQHz`S#Y3$WF8ld9*>BYlNn+2;{cG^f)osS&Z@UVLb!qS>b zE3<96FIx(fGi3&Jf*j3VUDD1(0y{8KV^SEoc`zlUe$tP3%i6#juU3lrzCOO3qH=sv z9(lshkly!>0yv72?NptVUdaO-d>Z~CBf z!+g&ck-v~NOlQV|U+(t5Eu;|n-Ha3e;;bdfvN^y)=dRgKFc}YC|RsQ-}o}Dx*TRQWT{4{wS/dev/null)" if [ ! -e "/proc/$PID" ] || [ -z "$PID" ]; then echo "smartdns server is not running." exit 1 diff --git a/release/src/router/smartdns/etc/smartdns/smartdns.conf b/release/src/router/smartdns/etc/smartdns/smartdns.conf index 27b2212112..c5af23f2ca 100644 --- a/release/src/router/smartdns/etc/smartdns/smartdns.conf +++ b/release/src/router/smartdns/etc/smartdns/smartdns.conf @@ -1,4 +1,4 @@ -# dns server name, defaut is host name +# dns server name, default is host name # server-name, # example: # server-name smartdns @@ -22,6 +22,7 @@ # -no-cache: skip cache. # -no-rule-soa: Skip address SOA(#) rules. # -no-dualstack-selection: Disable dualstack ip selection. +# -force-aaaa-soa: force AAAA query return SOA. # example: # IPV4: # bind :53 @@ -43,6 +44,14 @@ cache-size 512 # prefetch-domain [yes|no] # prefetch-domain yes +# cache serve expired +# serve-expired [yes|no] +# serve-expired yes + +# cache serve expired TTL +# serve-expired-ttl [num] +# serve-expired-ttl 0 + # List of hosts that supply bogus NX domain results # bogus-nxdomain [ip/subnet] @@ -97,12 +106,20 @@ log-level info # dns audit # audit-enable [yes|no]: enable or disable audit. # audit-enable yes -# audit-SOA [yes|no]: enable or disalbe log soa result. +# audit-SOA [yes|no]: enable or disable log soa result. # audit-size size of each audit file, support k,m,g # audit-file /var/log/smartdns-audit.log # audit-size 128k # audit-num 2 +# certificate file +# ca-file [file] +# ca-file /etc/ssl/certs/ca-certificates.crt + +# certificate path +# ca-path [path] +# ca-path /etc/ss/certs + # remote udp dns server list # server [IP]:[PORT] [-blacklist-ip] [-whitelist-ip] [-check-edns] [-group [group] ...] [-exclude-default-group] # default port is 53 @@ -121,8 +138,9 @@ log-level info # remote tls dns server list # server-tls [IP]:[PORT] [-blacklist-ip] [-whitelist-ip] [-spki-pin [sha256-pin]] [-group [group] ...] [-exclude-default-group] # -spki-pin: TLS spki pin to verify. -# -tls-host-check: cert hostname to verify. -# -hostname: TLS sni hostname. +# -tls-host-verify: cert hostname to verify. +# -host-name: TLS sni hostname. +# -no-check-certificate: no check certificate. # Get SPKI with this command: # echo | openssl s_client -connect '[ip]:853' | openssl x509 -pubkey -noout | openssl pkey -pubin -outform der | openssl dgst -sha256 -binary | openssl enc -base64 # default port is 853 @@ -132,9 +150,10 @@ log-level info # remote https dns server list # server-https https://[host]:[port]/path [-blacklist-ip] [-whitelist-ip] [-spki-pin [sha256-pin]] [-group [group] ...] [-exclude-default-group] # -spki-pin: TLS spki pin to verify. -# -tls-host-check: cert hostname to verify. -# -hostname: TLS sni hostname. +# -tls-host-verify: cert hostname to verify. +# -host-name: TLS sni hostname. # -http-host: http host. +# -no-check-certificate: no check certificate. # default port is 443 # server-https https://cloudflare-dns.com/dns-query @@ -156,3 +175,12 @@ log-level info # ipset /domain/[ipset|-] # ipset /www.example.com/block, set ipset with ipset name of block # ipset /www.example.com/-, ignore this domain + +# set domain rules +# domain-rules /domain/ [-speed-check-mode [...]] +# rules: +# -speed-check-mode [mode]: speed check mode +# speed-check-mode [ping|tcp:port|none|,] +# -address [address|-]: same as address option +# -nameserver [group|-]: same as nameserver option +# -ipset [ipset|-]: same as ipset option diff --git a/release/src/router/smartdns/package/build-pkg.sh b/release/src/router/smartdns/package/build-pkg.sh index bb9c5aaa68..f3e6b36161 100644 --- a/release/src/router/smartdns/package/build-pkg.sh +++ b/release/src/router/smartdns/package/build-pkg.sh @@ -13,8 +13,8 @@ showhelp() { echo "Usage: $0 [OPTION]" echo "Options:" - echo " --platform [luci|debian|openwrt|optware|linux] build for platform. " - echo " --arch [all|armhf|arm64|x86_64|...] build for architecture, e.g. " + echo " --platform [luci|luci-compat|debian|openwrt|optware|linux] build for platform. " + echo " --arch [all|armhf|arm64|x86-64|...] build for architecture, e.g. " echo " --cross-tool [cross-tool] cross compiler, e.g. mips-openwrt-linux-" echo "" echo "Advance Options:" @@ -26,8 +26,10 @@ showhelp() echo "Example:" echo " build luci:" echo " $0 --platform luci" + echo " build luci:" + echo " $0 --platform luci-compat" echo " build debian:" - echo " $0 --platform debian --arch x86_64" + echo " $0 --platform debian --arch x86-64" echo " build raspbian pi:" echo " $0 --platform debian --arch armhf" echo " build optware mips:" @@ -35,14 +37,14 @@ showhelp() echo " build openwrt mips:" echo " $0 --platform openwrt --arch mips_24kc" echo " build generic linux:" - echo " $0 --platform linux --arch x86_64" + echo " $0 --platform linux --arch x86-64" } build_smartdns() { if [ "$PLATFORM" != "luci" ]; then - make -C $CODE_DIR/src clean - make -C $CODE_DIR/src all -j8 VER=$VER $MAKE_ARGS + make -C $CODE_DIR clean $MAKE_ARGS + make -C $CODE_DIR all -j8 VER=$VER $MAKE_ARGS if [ $? -ne 0 ]; then echo "make smartdns failed" exit 1 diff --git a/release/src/router/smartdns/package/linux/install b/release/src/router/smartdns/package/linux/install new file mode 100644 index 0000000000..b8466b6980 --- /dev/null +++ b/release/src/router/smartdns/package/linux/install @@ -0,0 +1,249 @@ +#!/bin/sh +# +# Copyright (C) 2018-2020 Ruilin Peng (Nick) . +# +# smartdns is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# smartdns is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +INST_DIR=$(cd $(dirname $0);pwd) +ISWSL=1 # 1 means not WSL, 0 means wsl + +showhelp() +{ + echo "Usage: install [OPTION]" + echo "Options:" + echo " -i install smartdns." + echo " -u uninstall smartdns." + echo " --prefix [dir] prefix directory." + echo " -h show this message." +} + +start_service() +{ + if [ $ISSYSTEMD -ne 0 ]; then + chkconfig smartdns on >/dev/null 2>&1 + service smartdns start + return $? + fi + + systemctl daemon-reload + systemctl enable smartdns + systemctl start smartdns +} + +stop_service() +{ + if [ $ISSYSTEMD -ne 0 ]; then + service smartdns stop + chkconfig smartdns off >/dev/null 2>&1 + return 0 + fi + + systemctl stop smartdns + systemctl disable smartdns + + return 0 +} + +clean_service() +{ + if [ $ISSYSTEMD -ne 0 ]; then + return 0 + fi + systemctl daemon-reload +} + +get_systemd_path() +{ + service="`systemctl --no-legend| grep '\.service' | head -n 1 | awk '{print $1}'`" + SERVICE_PATH="`systemctl show $service | grep FragmentPath | awk -F'=' '{print $2}'`" + dirname $SERVICE_PATH +} + +install_files() +{ + install -v -d $SMARTDNS_CONF_DIR + if [ $? -ne 0 ]; then + return 1 + fi + + install -v -m 0755 -t $PREFIX/usr/sbin usr/sbin/smartdns + if [ $? -ne 0 ]; then + return 1 + fi + + if [ -e "$PREFIX$SMARTDNS_CONF_DIR/smartdns.conf" ]; then + cp etc/smartdns/smartdns.conf $PREFIX$SMARTDNS_CONF_DIR/smartdns.conf.pkg + else + install -v -m 0640 -t $PREFIX$SMARTDNS_CONF_DIR etc/smartdns/smartdns.conf + if [ $? -ne 0 ]; then + return 1 + fi + fi + + install -v -m 0640 -t $PREFIX/etc/default etc/default/smartdns + if [ $? -ne 0 ]; then + return 1 + fi + + install -v -m 0755 -t $SMARTDNS_INIT_DIR etc/init.d/smartdns + if [ $? -ne 0 ]; then + if [ $ISSYSTEMD -ne 0 ]; then + return 1 + fi + fi + + if [ $ISSYSTEMD -eq 0 ]; then + SYSTEM_UNIT_PATH="`get_systemd_path`" + if [ -z "$SYSTEM_UNIT_PATH" ]; then + return 1 + fi + install -v -m 0644 -t $PREFIX$SYSTEM_UNIT_PATH systemd/smartdns.service + if [ $? -ne 0 ]; then + return 1 + fi + fi + + return 0 +} + +uninstall_smartdns() +{ + if [ -z "$PREFIX" ]; then + stop_service 2>/dev/null + fi + rmdir $PREFIX$SMARTDNS_CONF_DIR 2>/dev/null + rm -f $PREFIX/usr/sbin/smartdns + rm -f $PREFIX/etc/default/smartdns + + if [ $ISWSL -eq 0 ]; then + sed -i '\#%sudo ALL=NOPASSWD: /etc/init.d/smartdns#d' /etc/sudoers 2>/dev/null + fi + + if [ $ISSYSTEMD -eq 0 ]; then + SYSTEM_UNIT_PATH="`get_systemd_path`" + if [ ! -z "$SYSTEM_UNIT_PATH" ]; then + rm -f $PREFIX$SYSTEM_UNIT_PATH/smartdns.service + fi + fi + + if [ -z "$PREFIX" ]; then + clean_service + fi +} + + +install_smartdns() +{ + local ret + + which smartdns >/dev/null 2>&1 + if [ $? -eq 0 ]; then + echo "Already installed." + return 1 + fi + + install_files + ret=$? + if [ $ret -ne 0 ]; then + uninstall_smartdns + return $ret + fi + + if [ -z "$PREFIX" ]; then + start_service + fi + + if [ $ISWSL -eq 0 ]; then + grep "%sudo ALL=NOPASSWD: /etc/init.d/smartdns" /etc/sudoers >/dev/null 2>&1 + if [ $? -ne 0 ]; then + echo "%sudo ALL=NOPASSWD: /etc/init.d/smartdns" >> /etc/sudoers + fi + fi + + return 0 +} + +init_dir() +{ + local ID=`id -u` + if [ $ID -ne 0 ]; then + echo "Please run as root." + return 1 + fi + + SMARTDNS_CONF_DIR=$PREFIX/etc/smartdns + SMARTDNS_INIT_DIR=$PREFIX/etc/init.d + which systemctl >/dev/null 2>&1 + ISSYSTEMD="$?" + # Running under WSL (Windows Subsystem for Linux)? + cat /proc/version | grep Microsoft >/dev/null 2>&1; + if [ $? -eq 0 ]; then + ISSYSTEMD=1 + ISWSL=0 + fi + + cd $INST_DIR +} + +main() +{ + ACTION="" + + OPTS=`getopt -o iuh --long help,prefix: \ + -n "" -- "$@"` + + if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi + + # Note the quotes around `$TEMP': they are essential! + eval set -- "$OPTS" + + while true; do + case "$1" in + --prefix) + PREFIX="$2" + shift 2;; + -h | --help ) + showhelp + return 0 + shift ;; + -i ) + ACTION="INSTALL" + shift ;; + -u ) + ACTION="UNINSTALL" + shift ;; + -- ) shift; break ;; + * ) break ;; + esac + done + + init_dir + + if [ -z "$ACTION" ]; then + showhelp + return 0 + elif [ "$ACTION" = "INSTALL" ]; then + install_smartdns + return $? + elif [ "$ACTION" = "UNINSTALL" ]; then + uninstall_smartdns + return 0 + fi + +} + +main $@ +exit $? + + diff --git a/release/src/router/smartdns/package/linux/make.sh b/release/src/router/smartdns/package/linux/make.sh index c200c343a8..32aeba9ce8 100644 --- a/release/src/router/smartdns/package/linux/make.sh +++ b/release/src/router/smartdns/package/linux/make.sh @@ -23,12 +23,17 @@ build() cd $PKG_ROOT/ # Generic x86_64 - mkdir $PKG_ROOT/smartdns/src -p + mkdir $PKG_ROOT/smartdns/usr/sbin -p mkdir $PKG_ROOT/smartdns/package -p + mkdir $PKG_ROOT/smartdns/systemd -p + cd $SMARTDNS_DIR cp package/windows $PKG_ROOT/smartdns/package/ -a - cp etc systemd *.md LICENSE install $PKG_ROOT/smartdns/ -a - cp src/smartdns $PKG_ROOT/smartdns/src -a + cp etc *.md LICENSE package/linux/install $PKG_ROOT/smartdns/ -a + cp systemd/smartdns.service $PKG_ROOT/smartdns/systemd + cp src/smartdns $PKG_ROOT/smartdns/usr/sbin -a + chmod +x $PKG_ROOT/smartdns/install + if [ $? -ne 0 ]; then echo "copy smartdns file failed" rm -fr $PKG_ROOT diff --git a/release/src/router/smartdns/package/luci-compat/control/control b/release/src/router/smartdns/package/luci-compat/control/control new file mode 100644 index 0000000000..e0feefc030 --- /dev/null +++ b/release/src/router/smartdns/package/luci-compat/control/control @@ -0,0 +1,7 @@ +Package: luci-app-smartdns +Version: git-18.201.27126-7bf0367-1 +Depends: libc, smartdns +Source: feeds/luci/applications/luci-app-smartdns +Section: luci +Architecture: all +Description: A smartdns server diff --git a/release/src/router/smartdns/package/luci-compat/control/postinst b/release/src/router/smartdns/package/luci-compat/control/postinst new file mode 100644 index 0000000000..3a5aa3a1f8 --- /dev/null +++ b/release/src/router/smartdns/package/luci-compat/control/postinst @@ -0,0 +1,21 @@ +#!/bin/sh +# +# Copyright (C) 2018-2020 Ruilin Peng (Nick) . +# +# smartdns is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# smartdns is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +[ "${IPKG_NO_SCRIPT}" = "1" ] && exit 0 +[ -x ${IPKG_INSTROOT}/lib/functions.sh ] || exit 0 +. ${IPKG_INSTROOT}/lib/functions.sh +default_postinst $0 $@ diff --git a/release/src/router/smartdns/package/luci-compat/control/postinst-pkg b/release/src/router/smartdns/package/luci-compat/control/postinst-pkg new file mode 100644 index 0000000000..ded67b630f --- /dev/null +++ b/release/src/router/smartdns/package/luci-compat/control/postinst-pkg @@ -0,0 +1,4 @@ +[ -n "${IPKG_INSTROOT}" ] || { + (. /etc/uci-defaults/50_luci-smartdns) && rm -f /etc/uci-defaults/50_luci-smartdns + exit 0 +} diff --git a/release/src/router/smartdns/package/luci-compat/control/prerm b/release/src/router/smartdns/package/luci-compat/control/prerm new file mode 100644 index 0000000000..0468c7a50e --- /dev/null +++ b/release/src/router/smartdns/package/luci-compat/control/prerm @@ -0,0 +1,20 @@ +#!/bin/sh +# +# Copyright (C) 2018-2020 Ruilin Peng (Nick) . +# +# smartdns is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# smartdns is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +[ -x ${IPKG_INSTROOT}/lib/functions.sh ] || exit 0 +. ${IPKG_INSTROOT}/lib/functions.sh +default_prerm $0 $@ diff --git a/release/src/router/smartdns/package/luci-compat/debian-binary b/release/src/router/smartdns/package/luci-compat/debian-binary new file mode 100644 index 0000000000..cd5ac039d6 --- /dev/null +++ b/release/src/router/smartdns/package/luci-compat/debian-binary @@ -0,0 +1 @@ +2.0 diff --git a/release/src/router/smartdns/package/luci-compat/files/etc/uci-defaults/50_luci-smartdns b/release/src/router/smartdns/package/luci-compat/files/etc/uci-defaults/50_luci-smartdns new file mode 100644 index 0000000000..c05b86bc72 --- /dev/null +++ b/release/src/router/smartdns/package/luci-compat/files/etc/uci-defaults/50_luci-smartdns @@ -0,0 +1,26 @@ +#!/bin/sh +# +# Copyright (C) 2018-2020 Ruilin Peng (Nick) . +# +# smartdns is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# smartdns is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +uci -q batch <<-EOF >/dev/null + delete ucitrack.@smartdns[-1] + add ucitrack smartdns + set ucitrack.@smartdns[-1].init=smartdns + commit ucitrack +EOF + +rm -f /tmp/luci-indexcache +exit 0 diff --git a/release/src/router/smartdns/package/luci-compat/files/luci/controller/smartdns.lua b/release/src/router/smartdns/package/luci-compat/files/luci/controller/smartdns.lua new file mode 100644 index 0000000000..a8bd737383 --- /dev/null +++ b/release/src/router/smartdns/package/luci-compat/files/luci/controller/smartdns.lua @@ -0,0 +1,83 @@ +-- +-- Copyright (C) 2018-2020 Ruilin Peng (Nick) . +-- +-- smartdns is free software: you can redistribute it and/or modify +-- it under the terms of the GNU General Public License as published by +-- the Free Software Foundation, either version 3 of the License, or +-- (at your option) any later version. +-- +-- smartdns is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program. If not, see . + +module("luci.controller.smartdns", package.seeall) +local smartdns = require "luci.model.smartdns" + +function index() + if not nixio.fs.access("/etc/config/smartdns") then + return + end + + local page + page = entry({"admin", "services", "smartdns"}, cbi("smartdns/smartdns"), _("SmartDNS"), 60) + page.dependent = true + page = entry({"admin", "services", "smartdns", "status"}, call("act_status")) + page.leaf = true + page = entry({"admin", "services", "smartdns", "upstream"}, cbi("smartdns/upstream"), nil) + page.leaf = true +end + +local function is_running() + return luci.sys.call("pidof smartdns >/dev/null") == 0 +end + +function act_status() + local e={} + local ipv6_server; + local redirect_mode="none"; + + e.ipv6_works = 2; + e.ipv4_works = 2; + e.ipv6_server = 1; + e.dnsmasq_forward = 0; + redirect_mode = smartdns.get_config_option("smartdns", "smartdns", "redirect", nil); + if redirect_mode == "redirect" then + e.redirect = 1 + elseif redirect_mode == "dnsmasq-upstream" then + e.redirect = 2 + else + e.redirect = 0 + end + + e.local_port = smartdns.get_config_option("smartdns", "smartdns", "port", nil); + ipv6_server = smartdns.get_config_option("smartdns", "smartdns", "ipv6_server", nil); + if e.redirect == 1 then + if e.local_port ~= nil and e.local_port ~= "53" then + e.ipv4_works = luci.sys.call("iptables -t nat -nL PREROUTING 2>/dev/null | grep REDIRECT | grep dpt:53 | grep %q >/dev/null 2>&1" % e.local_port) == 0 + if ipv6_server == "1" then + e.ipv6_works = luci.sys.call("ip6tables -t nat -nL PREROUTING 2>/dev/null| grep REDIRECT | grep dpt:53 | grep %q >/dev/null 2>&1" % e.local_port) == 0 + else + e.ipv6_works = 2 + end + else + e.redirect = 0 + end + elseif e.redirect == 2 then + local str; + local dnsmasq_server = luci.sys.exec("uci get dhcp.@dnsmasq[0].server") + if e.local_port ~= nil then + str = "127.0.0.1#" .. e.local_port + if string.sub(dnsmasq_server,1,string.len(str)) == str then + e.dnsmasq_forward = 1 + end + end + end + e.running = is_running() + + luci.http.prepare_content("application/json") + luci.http.write_json(e) +end diff --git a/release/src/router/smartdns/package/luci-compat/files/luci/i18n/smartdns.zh-cn.po b/release/src/router/smartdns/package/luci-compat/files/luci/i18n/smartdns.zh-cn.po new file mode 100644 index 0000000000..338035ac22 --- /dev/null +++ b/release/src/router/smartdns/package/luci-compat/files/luci/i18n/smartdns.zh-cn.po @@ -0,0 +1,299 @@ +msgid "" +msgstr "Content-Type: text/plain; charset=UTF-8\n" + +msgid "SmartDNS" +msgstr "SmartDNS" + +msgid "SmartDNS is a local high-performance DNS server" +msgstr "SmartDNS是一个本地高性能DNS服务器" + +msgid "SmartDNS Server" +msgstr "SmartDNS 服务器" + +msgid "SmartDNS is a local high-performance DNS server, supports finding fastest IP, supports ad filtering, and supports avoiding DNS poisoning." +msgstr "SmartDNS是一个本地高性能DNS服务器,支持返回最快IP,支持广告过滤。" + +msgid "Custom Settings" +msgstr "自定义设置" + +msgid "General Settings" +msgstr "基本设置" + +msgid "Settings" +msgstr "设置" + +msgid "Advanced Settings" +msgstr "高级设置" + +msgid "Generate Coredump" +msgstr "生成coredump" + +msgid "Generate Coredump file when smartdns crash, coredump file is located at /tmp/smartdns.xxx.core." +msgstr "当smartdns异常时生成coredump文件,coredump文件在/tmp/smartdns.xxx.core." + +msgid "Server Name" +msgstr "服务器名称" + +msgid "Smartdns server name" +msgstr "SmartDNS的服务器名称,默认为smartdns,留空为主机名" + +msgid "SmartDNS is a local dns server to find fastest ip." +msgstr "本地高性能服务器,优化网络访问性能。" + +msgid "Enable or disable smartdns server" +msgstr "启用或禁用SmartDNS服务" + +msgid "Local Port" +msgstr "本地端口" + +msgid "Smartdns local server port" +msgstr "SmartDNS本地服务端口" + +msgid "IPV4 53 Port Redirect Failure" +msgstr "IPV4 53端口重定向失败" + +msgid "IPV6 53 Port Redirect Failure" +msgstr "IPV6 53端口重定向失败" + +msgid "Dnsmasq Forwared To Smartdns Failure" +msgstr "重定向dnsmasq到smartdns失败" + +msgid "TCP Server" +msgstr "TCP服务器" + +msgid "Enable TCP DNS Server" +msgstr "启用TCP服务器" + +msgid "IPV6 Server" +msgstr "IPV6服务器" + +msgid "Enable IPV6 DNS Server" +msgstr "启用IPV6服务器" + +msgid "Dual-stack IP Selection" +msgstr "双栈IP优选" + +msgid "Enable IP selection between IPV4 and IPV6" +msgstr "启用或禁用IPV4,IPV6间的IP优选策略。" + +msgid "Domain prefetch" +msgstr "域名预加载" + +msgid "Enable domain prefetch, accelerate domain response speed." +msgstr "启用域名预加载,加速域名响应速度。" + +msgid "Serve expired" +msgstr "过期缓存服务" + +msgid "Attempts to serve old responses from cache with a TTL of 0 in the response without waiting for the actual resolution to finish." +msgstr "查询性能优化,有请求时尝试回应TTL为0的过期记录,以避免查询等待。" + +msgid "Redirect" +msgstr "重定向" + +msgid "SmartDNS redirect mode" +msgstr "SmartDNS 重定向模式" + +msgid "Run as dnsmasq upstream server" +msgstr "作为dnsmasq的上游服务器" + +msgid "Redirect 53 port to SmartDNS" +msgstr "重定向53端口到SmartDNS" + +msgid "Cache Size" +msgstr "缓存大小" + +msgid "DNS domain result cache size" +msgstr "缓存DNS的结果,缓存大小,配置零则不缓存" + +msgid "Domain TTL" +msgstr "域名TTL" + +msgid "TTL for all domain result." +msgstr "设置所有域名的TTL值" + +msgid "Domain TTL Min" +msgstr "域名TTL最小值" + +msgid "Minimum TTL for all domain result." +msgstr "设置所有域名的TTL最小值" + +msgid "Domain TTL Max" +msgstr "域名TTL最大值" + +msgid "Maximum TTL for all domain result." +msgstr "设置所有域名的TTL最大值" + +msgid "smartdns custom settings" +msgstr "smartdns 自定义设置,具体配置参数参考指导" + +msgid "Second Server Settings" +msgstr "第二DNS服务器" + +msgid "Enable or disable second DNS server." +msgstr "是否启用第二DNS服务器。" + +msgid "Skip Speed Check" +msgstr "跳过测速" + +msgid "Do not check speed." +msgstr "禁用测速。" + +msgid "Server Group" +msgstr "服务器组" + +msgid "Query DNS through specific dns server group, such as office, home." +msgstr "使用指定服务器组查询,比如office, home。" + +msgid "Skip Address Rules" +msgstr "跳过address规则" + +msgid "Skip address rules." +msgstr "跳过address规则。" + +msgid "Skip Nameserver Rule" +msgstr "跳过Nameserver规则" + +msgid "Skip nameserver rules." +msgstr "跳过Nameserver规则。" + +msgid "Skip Ipset Rule" +msgstr "跳过ipset规则" + +msgid "Skip ipset rules." +msgstr "跳过ipset规则。" + +msgid "Skip SOA Address Rule" +msgstr "跳过address SOA(#)规则" + +msgid "Skip SOA address rules." +msgstr "跳过address SOA(#)规则。" + +msgid "Skip Dualstack Selection" +msgstr "跳过双栈优选" + +msgid "Skip Dualstack Selection." +msgstr "跳过双栈优选。" + +msgid "Skip Cache" +msgstr "跳过cache" + +msgid "Skip Cache." +msgstr "跳过cache。" + +msgid "Upstream Servers" +msgstr "上游服务器" + +msgid "Upstream Servers, support UDP, TCP protocol. Please configure multiple DNS servers, including multiple foreign DNS servers." +msgstr "上游DNS服务器列表,支持UDP,TCP协议,请配置多个上游DNS服务器,包括多个国内外服务器" + +msgid "DNS Server Name" +msgstr "DNS服务器名称" + +msgid "port" +msgstr "端口" + +msgid "DNS Server port" +msgstr "DNS服务器端口" + +msgid "DNS Server ip" +msgstr "DNS服务器IP" + +msgid "type" +msgstr "类型" + +msgid "DNS Server type" +msgstr "协议类型" + +msgid "Domain Address" +msgstr "域名地址" + +msgid "TLS Hostname Verify" +msgstr "校验TLS主机名" + +msgid "Set TLS hostname to verify." +msgstr "设置校验TLS主机名。" + +msgid "No check certificate" +msgstr "停用证书校验" + +msgid "Do not check certificate." +msgstr "不校验证书的合法性。" + +msgid "TLS SNI name" +msgstr "TLS SNI名称" + +msgid "HTTP Host" +msgstr "HTTP主机" + +msgid "Sets the server name indication for query." +msgstr "设置查询时使用的服务器SNI名称。" + +msgid "Set the HTTP host used for the query. Use this parameter when the host of the URL address is an IP address." +msgstr "设置查询时使用的HTTP主机,当URL地址的host是IP地址时,使用此参数。" + +msgid "Server Group" +msgstr "服务器组" + +msgid "DNS Server group belongs to, used with nameserver, such as office, home." +msgstr "DNS服务器所属组, 配合nameserver使用,例如:office,home。" + +msgid "IP Blacklist Filtering" +msgstr "IP黑名单过滤" + +msgid "Anti Answer Forgery" +msgstr "反回答伪造" + +msgid "Anti answer forgery, if DNS does not work properly after enabling, please turn off this feature" +msgstr "反回答伪造,如果启用后DNS工作不正常,请关闭此功能。" + +msgid "Filtering IP with blacklist" +msgstr "使用IP黑名单过滤" + +msgid "TLS SPKI Pinning" +msgstr "TLS SPKI 指纹" + +msgid "Used to verify the validity of the TLS server, The value is Base64 encoded SPKI fingerprint, leaving blank to indicate that the validity of TLS is not verified." +msgstr "用于校验TLS服务器的有效性,数值为Base64编码的SPKI指纹, 留空表示不验证TLS的合法性" + +msgid "Additional Server Args" +msgstr "额外的服务器参数" + +msgid "Additional Args for upstream dns servers" +msgstr "额外的上游DNS服务器参数" + +msgid "Upstream DNS Server Configuration" +msgstr "上游DNS服务器配置" + +msgid "Set Specific domain ip address." +msgstr "指定特定域名的IP地址" + +msgid "Specify an IP address to return for any host in the given domains, Queries in the domains are never forwarded and always replied to with the specified IP address which may be IPv4 or IPv6." +msgstr "配置特定域名返回特定的IP地址,域名查询将不到上游服务器请求,直接返回配置的IP地址,可用于广告屏蔽。" + +msgid "IP Blacklist" +msgstr "IP黑名单" + +msgid "Set Specific ip blacklist." +msgstr "设置IP黑名单列表" + +msgid "Configure IP blacklists that will be filtered from the results of specific DNS server." +msgstr "配置需要从指定域名服务器结果过滤的IP黑名单。" + +msgid "Technical Support" +msgstr "技术支持" + +msgid "If you like this software, please buy me a cup of coffee." +msgstr "如果本软件对你有帮助,请给作者加个蛋。" + +msgid "SmartDNS official website" +msgstr "SmartDNS官方网站" + +msgid "open website" +msgstr "打开网站" + +msgid "Donate to smartdns" +msgstr "捐助smartdns项目" + +msgid "Donate" +msgstr "捐助" diff --git a/release/src/router/smartdns/package/luci-compat/files/luci/model/cbi/smartdns/smartdns.lua b/release/src/router/smartdns/package/luci-compat/files/luci/model/cbi/smartdns/smartdns.lua new file mode 100644 index 0000000000..b9ba907faa --- /dev/null +++ b/release/src/router/smartdns/package/luci-compat/files/luci/model/cbi/smartdns/smartdns.lua @@ -0,0 +1,342 @@ +-- +-- Copyright (C) 2018-2020 Ruilin Peng (Nick) . +-- +-- smartdns is free software: you can redistribute it and/or modify +-- it under the terms of the GNU General Public License as published by +-- the Free Software Foundation, either version 3 of the License, or +-- (at your option) any later version. +-- +-- smartdns is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program. If not, see . + +require ("nixio.fs") +require ("luci.http") +require ("luci.dispatcher") +require ("nixio.fs") + +m = Map("smartdns") +m.title = translate("SmartDNS Server") +m.description = translate("SmartDNS is a local high-performance DNS server, supports finding fastest IP, supports ad filtering, and supports avoiding DNS poisoning.") + +m:section(SimpleSection).template = "smartdns/smartdns_status" + +-- Basic +s = m:section(TypedSection, "smartdns", translate("Settings"), translate("General Settings")) +s.anonymous = true + +s:tab("settings", translate("General Settings")) +s:tab("seconddns", translate("Second Server Settings")) +s:tab("custom", translate("Custom Settings")) + +---- Eanble +o = s:taboption("settings", Flag, "enabled", translate("Enable"), translate("Enable or disable smartdns server")) +o.default = o.disabled +o.rempty = false + +---- server name +o = s:taboption("settings", Value, "server_name", translate("Server Name"), translate("Smartdns server name")) +o.default = "smartdns" +o.datatype = "hostname" +o.rempty = false + +---- Port +o = s:taboption("settings", Value, "port", translate("Local Port"), translate("Smartdns local server port")) +o.placeholder = 6053 +o.default = 6053 +o.datatype = "port" +o.rempty = false + +---- Enable TCP server +o = s:taboption("settings", Flag, "tcp_server", translate("TCP Server"), translate("Enable TCP DNS Server")) +o.rmempty = false +o.default = o.enabled +o.cfgvalue = function(...) + return Flag.cfgvalue(...) or "1" +end + +---- Support IPV6 +o = s:taboption("settings", Flag, "ipv6_server", translate("IPV6 Server"), translate("Enable IPV6 DNS Server")) +o.rmempty = false +o.default = o.enabled +o.cfgvalue = function(...) + return Flag.cfgvalue(...) or "1" +end + +---- Support DualStack ip selection +o = s:taboption("settings", Flag, "dualstack_ip_selection", translate("Dual-stack IP Selection"), translate("Enable IP selection between IPV4 and IPV6")) +o.rmempty = false +o.default = o.disabled +o.cfgvalue = function(...) + return Flag.cfgvalue(...) or "0" +end + +---- Domain prefetch load +o = s:taboption("settings", Flag, "prefetch_domain", translate("Domain prefetch"), translate("Enable domain prefetch, accelerate domain response speed.")) +o.rmempty = false +o.default = o.disabled +o.cfgvalue = function(...) + return Flag.cfgvalue(...) or "0" +end + +---- Domain Serve expired +o = s:taboption("settings", Flag, "serve_expired", translate("Serve expired"), + translate("Attempts to serve old responses from cache with a TTL of 0 in the response without waiting for the actual resolution to finish.")) +o.rmempty = false +o.default = o.disabled +o.cfgvalue = function(...) + return Flag.cfgvalue(...) or "0" +end + +---- Redirect +o = s:taboption("settings", ListValue, "redirect", translate("Redirect"), translate("SmartDNS redirect mode")) +o.placeholder = "none" +o:value("none", translate("none")) +o:value("dnsmasq-upstream", translate("Run as dnsmasq upstream server")) +o:value("redirect", translate("Redirect 53 port to SmartDNS")) +o.default = "none" +o.rempty = false + +---- cache-size +o = s:taboption("settings", Value, "cache_size", translate("Cache Size"), translate("DNS domain result cache size")) +o.rempty = true + +---- rr-ttl +o = s:taboption("settings", Value, "rr_ttl", translate("Domain TTL"), translate("TTL for all domain result.")) +o.rempty = true + +---- rr-ttl-min +o = s:taboption("settings", Value, "rr_ttl_min", translate("Domain TTL Min"), translate("Minimum TTL for all domain result.")) +o.rempty = true +o.placeholder = "300" +o.default = 300 +o.optional = true + +---- second dns server +---- rr-ttl-max +o = s:taboption("settings", Value, "rr_ttl_max", translate("Domain TTL Max"), translate("Maximum TTL for all domain result.")) +o.rempty = true + +---- Eanble +o = s:taboption("seconddns", Flag, "seconddns_enabled", translate("Enable"), translate("Enable or disable second DNS server.")) +o.default = o.disabled +o.rempty = false + +---- Port +o = s:taboption("seconddns", Value, "seconddns_port", translate("Local Port"), translate("Smartdns local server port")) +o.placeholder = 6553 +o.default = 6553 +o.datatype = "port" +o.rempty = false + +---- Enable TCP server +o = s:taboption("seconddns", Flag, "seconddns_tcp_server", translate("TCP Server"), translate("Enable TCP DNS Server")) +o.rmempty = false +o.default = o.enabled +o.cfgvalue = function(...) + return Flag.cfgvalue(...) or "1" +end + +---- dns server group +o = s:taboption("seconddns", Value, "seconddns_server_group", translate("Server Group"), translate("Query DNS through specific dns server group, such as office, home.")) +o.rmempty = true +o.placeholder = "default" +o.datatype = "hostname" +o.rempty = true + +o = s:taboption("seconddns", Flag, "seconddns_no_speed_check", translate("Skip Speed Check"), translate("Do not check speed.")) +o.rmempty = false +o.default = o.disabled +o.cfgvalue = function(...) + return Flag.cfgvalue(...) or "0" +end + +---- skip address rules +o = s:taboption("seconddns", Flag, "seconddns_no_rule_addr", translate("Skip Address Rules"), translate("Skip address rules.")) +o.rmempty = false +o.default = o.disabled +o.cfgvalue = function(...) + return Flag.cfgvalue(...) or "0" +end + +---- skip name server rules +o = s:taboption("seconddns", Flag, "seconddns_no_rule_nameserver", translate("Skip Nameserver Rule"), translate("Skip nameserver rules.")) +o.rmempty = false +o.default = o.disabled +o.cfgvalue = function(...) + return Flag.cfgvalue(...) or "0" +end + +---- skip ipset rules +o = s:taboption("seconddns", Flag, "seconddns_no_rule_ipset", translate("Skip Ipset Rule"), translate("Skip ipset rules.")) +o.rmempty = false +o.default = o.disabled +o.cfgvalue = function(...) + return Flag.cfgvalue(...) or "0" +end + +---- skip soa address rule +o = s:taboption("seconddns", Flag, "seconddns_no_rule_soa", translate("Skip SOA Address Rule"), translate("Skip SOA address rules.")) +o.rmempty = false +o.default = o.disabled +o.cfgvalue = function(...) + return Flag.cfgvalue(...) or "0" +end + +o = s:taboption("seconddns", Flag, "seconddns_no_dualstack_selection", translate("Skip Dualstack Selection"), translate("Skip Dualstack Selection.")) +o.rmempty = false +o.default = o.disabled +o.cfgvalue = function(...) + return Flag.cfgvalue(...) or "0" +end + +---- skip cache +o = s:taboption("seconddns", Flag, "seconddns_no_cache", translate("Skip Cache"), translate("Skip Cache.")) +o.rmempty = false +o.default = o.disabled +o.cfgvalue = function(...) + return Flag.cfgvalue(...) or "0" +end + +---- Force AAAA SOA +o = s:taboption("seconddns", Flag, "force_aaaa_soa", translate("Force AAAA SOA"), translate("Force AAAA SOA.")) +o.rmempty = false +o.default = o.disabled +o.cfgvalue = function(...) + return Flag.cfgvalue(...) or "0" +end + +----- custom settings +custom = s:taboption("custom", Value, "Custom Settings", + translate(""), + translate("smartdns custom settings")) + +custom.template = "cbi/tvalue" +custom.rows = 20 + +function custom.cfgvalue(self, section) + return nixio.fs.readfile("/etc/smartdns/custom.conf") +end + +function custom.write(self, section, value) + value = value:gsub("\r\n?", "\n") + nixio.fs.writefile("/etc/smartdns/custom.conf", value) +end + +o = s:taboption("custom", Flag, "coredump", translate("Generate Coredump"), translate("Generate Coredump file when smartdns crash, coredump file is located at /tmp/smartdns.xxx.core.")) +o.rmempty = false +o.default = o.disabled +o.cfgvalue = function(...) + return Flag.cfgvalue(...) or "0" +end + +-- Upstream servers +s = m:section(TypedSection, "server", translate("Upstream Servers"), translate("Upstream Servers, support UDP, TCP protocol. " .. + "Please configure multiple DNS servers, including multiple foreign DNS servers.")) + +s.anonymous = true +s.addremove = true +s.template = "cbi/tblsection" +s.extedit = luci.dispatcher.build_url("admin/services/smartdns/upstream/%s") + +---- enable flag +o = s:option(Flag, "enabled", translate("Enable"), translate("Enable")) +o.rmempty = false +o.default = o.enabled +o.cfgvalue = function(...) + return Flag.cfgvalue(...) or "1" +end + +---- name +s:option(Value, "name", translate("DNS Server Name"), translate("DNS Server Name")) + +---- IP address +o = s:option(Value, "ip", translate("ip"), translate("DNS Server ip")) +o.datatype = "or(ipaddr, string)" +o.rmempty = false +---- port +o = s:option(Value, "port", translate("port"), translate("DNS Server port")) +o.placeholder = "default" +o.datatype = "port" +o.rempty = true +o:depends("type", "udp") +o:depends("type", "tcp") +o:depends("type", "tls") + +---- type +o = s:option(ListValue, "type", translate("type"), translate("DNS Server type")) +o.placeholder = "udp" +o:value("udp", translate("udp")) +o:value("tcp", translate("tcp")) +o:value("tls", translate("tls")) +o:value("https", translate("https")) +o.default = "udp" +o.rempty = false + +s = m:section(TypedSection, "smartdns", translate("Advanced Settings"), translate("Advanced Settings")); +s.anonymous = true; + +s:tab("domain-address", translate("Domain Address"), translate("Set Specific domain ip address.")); +s:tab("blackip-list", translate("IP Blacklist"), translate("Set Specific ip blacklist.")); + +-- Doman addresss +addr = s:taboption("domain-address", Value, "address", + translate(""), + translate("Specify an IP address to return for any host in the given domains, Queries in the domains are never forwarded and always replied to with the specified IP address which may be IPv4 or IPv6.")) + +addr.template = "cbi/tvalue" +addr.rows = 20 + +function addr.cfgvalue(self, section) + return nixio.fs.readfile("/etc/smartdns/address.conf") +end + +function addr.write(self, section, value) + value = value:gsub("\r\n?", "\n") + nixio.fs.writefile("/etc/smartdns/address.conf", value) +end + +-- IP Blacklist +addr = s:taboption("blackip-list", Value, "blacklist_ip", + translate(""), + translate("Configure IP blacklists that will be filtered from the results of specific DNS server.")) + +addr.template = "cbi/tvalue" +addr.rows = 20 + +function addr.cfgvalue(self, section) + return nixio.fs.readfile("/etc/smartdns/blacklist-ip.conf") +end + +function addr.write(self, section, value) + value = value:gsub("\r\n?", "\n") + nixio.fs.writefile("/etc/smartdns/blacklist-ip.conf", value) +end + +-- Technical Support +s = m:section(TypedSection, "smartdns", translate("Technical Support"), + translate("If you like this software, please buy me a cup of coffee.")) +s.anonymous = true + +o = s:option(Button, "web") +o.title = translate("SmartDNS official website") +o.inputtitle = translate("open website") +o.inputstyle = "apply" +o.write = function() + luci.http.redirect("https://pymumu.github.io/smartdns") +end + +o = s:option(Button, "Donate") +o.title = translate("Donate to smartdns") +o.inputtitle = translate("Donate") +o.inputstyle = "apply" +o.write = function() + luci.http.redirect("https://pymumu.github.io/smartdns/#donate") +end + +return m + diff --git a/release/src/router/smartdns/package/luci-compat/files/luci/model/cbi/smartdns/upstream.lua b/release/src/router/smartdns/package/luci-compat/files/luci/model/cbi/smartdns/upstream.lua new file mode 100644 index 0000000000..1bb612fe9b --- /dev/null +++ b/release/src/router/smartdns/package/luci-compat/files/luci/model/cbi/smartdns/upstream.lua @@ -0,0 +1,129 @@ +-- +-- Copyright (C) 2018-2020 Ruilin Peng (Nick) . +-- +-- smartdns is free software: you can redistribute it and/or modify +-- it under the terms of the GNU General Public License as published by +-- the Free Software Foundation, either version 3 of the License, or +-- (at your option) any later version. +-- +-- smartdns is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program. If not, see . + +local sid = arg[1] + +m = Map("smartdns", "%s - %s" %{translate("SmartDNS Server"), translate("Upstream DNS Server Configuration")}) +m.redirect = luci.dispatcher.build_url("admin/services/smartdns") + +if m.uci:get("smartdns", sid) ~= "server" then + luci.http.redirect(m.redirect) + return +end + +-- [[ Edit Server ]]-- +s = m:section(NamedSection, sid, "server") +s.anonymous = true +s.addremove = false + +---- name +s:option(Value, "name", translate("DNS Server Name"), translate("DNS Server Name")) + +---- IP address +o = s:option(Value, "ip", translate("ip"), translate("DNS Server ip")) +o.datatype = "or(host, string)" +o.rmempty = false +---- port +o = s:option(Value, "port", translate("port"), translate("DNS Server port")) +o.placeholder = "default" +o.datatype = "port" +o.rempty = true +o:depends("type", "udp") +o:depends("type", "tcp") +o:depends("type", "tls") + +---- type +o = s:option(ListValue, "type", translate("type"), translate("DNS Server type")) +o.placeholder = "udp" +o:value("udp", translate("udp")) +o:value("tcp", translate("tcp")) +o:value("tls", translate("tls")) +o:value("https", translate("https")) +o.default = "udp" +o.rempty = false + +---- server group +o = s:option(Value, "server_group", translate("Server Group"), translate("DNS Server group belongs to, used with nameserver, such as office, home.")) +o.rmempty = true +o.placeholder = "default" +o.datatype = "hostname" +o.rempty = true + +---- blacklist_ip +o = s:option(Flag, "blacklist_ip", translate("IP Blacklist Filtering"), translate("Filtering IP with blacklist")) +o.rmempty = false +o.default = o.disabled +o.cfgvalue = function(...) + return Flag.cfgvalue(...) or "0" +end + +---- TLS host verify +o = s:option(Value, "tls_host_verify", translate("TLS Hostname Verify"), translate("Set TLS hostname to verify.")) +o.default = "" +o.datatype = "string" +o.rempty = true +o:depends("type", "tls") +o:depends("type", "https") + +---- certificate verify +o = s:option(Flag, "no_check_certificate", translate("No check certificate"), translate("Do not check certificate.")) +o.rmempty = false +o.default = o.disabled +o.cfgvalue = function(...) + return Flag.cfgvalue(...) or "0" +end +o:depends("type", "tls") +o:depends("type", "https") + +---- SNI host name +o = s:option(Value, "host_name", translate("TLS SNI name"), translate("Sets the server name indication for query.")) +o.default = "" +o.datatype = "hostname" +o.rempty = true +o:depends("type", "tls") +o:depends("type", "https") + +---- http host +o = s:option(Value, "http_host", translate("HTTP Host"), translate("Set the HTTP host used for the query. Use this parameter when the host of the URL address is an IP address.")) +o.default = "" +o.datatype = "hostname" +o.rempty = true +o:depends("type", "https") + +---- anti-Answer-Forgery +-- o = s:option(Flag, "check_edns", translate("Anti Answer Forgery"), translate("Anti answer forgery, if DNS does not work properly after enabling, please turn off this feature")) +-- o.rmempty = false +-- o.default = o.disabled +-- o:depends("type", "udp") +-- o.cfgvalue = function(...) +-- return Flag.cfgvalue(...) or "0" +-- end + +---- SPKI pin +o = s:option(Value, "spki_pin", translate("TLS SPKI Pinning"), translate("Used to verify the validity of the TLS server, The value is Base64 encoded SPKI fingerprint, leaving blank to indicate that the validity of TLS is not verified.")) +o.default = "" +o.datatype = "string" +o.rempty = true +o:depends("type", "tls") +o:depends("type", "https") + +---- other args +o = s:option(Value, "addition_arg", translate("Additional Server Args"), translate("Additional Args for upstream dns servers")) +o.default = "" +o.rempty = true +o.optional = true + +return m \ No newline at end of file diff --git a/release/src/router/smartdns/package/luci-compat/files/luci/model/smartdns.lua b/release/src/router/smartdns/package/luci-compat/files/luci/model/smartdns.lua new file mode 100644 index 0000000000..ff32306c42 --- /dev/null +++ b/release/src/router/smartdns/package/luci-compat/files/luci/model/smartdns.lua @@ -0,0 +1,31 @@ +-- +-- Copyright (C) 2018-2020 Ruilin Peng (Nick) . +-- +-- smartdns is free software: you can redistribute it and/or modify +-- it under the terms of the GNU General Public License as published by +-- the Free Software Foundation, either version 3 of the License, or +-- (at your option) any later version. +-- +-- smartdns is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program. If not, see . + +require ("nixio.fs") +require ("luci.http") +require ("luci.dispatcher") +require ("nixio.fs") + +local uci = require "luci.model.uci".cursor() + +module("luci.model.smartdns", package.seeall) + +function get_config_option(module, section, option, default) + return uci:get_first(module, section, option) or default +end + +return m + diff --git a/release/src/router/smartdns/package/luci-compat/files/luci/view/smartdns/smartdns_status.htm b/release/src/router/smartdns/package/luci-compat/files/luci/view/smartdns/smartdns_status.htm new file mode 100644 index 0000000000..c56dc20770 --- /dev/null +++ b/release/src/router/smartdns/package/luci-compat/files/luci/view/smartdns/smartdns_status.htm @@ -0,0 +1,41 @@ + + +
+

+ <%:Collecting data...%> +

+
diff --git a/release/src/router/smartdns/package/luci-compat/make.sh b/release/src/router/smartdns/package/luci-compat/make.sh new file mode 100644 index 0000000000..1cbce90359 --- /dev/null +++ b/release/src/router/smartdns/package/luci-compat/make.sh @@ -0,0 +1,135 @@ +#!/bin/sh +# +# Copyright (C) 2018-2020 Ruilin Peng (Nick) . +# +# smartdns is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# smartdns is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +CURR_DIR=$(cd $(dirname $0);pwd) + +VER="`date +"1.%Y.%m.%d-%H%M"`" +SMARTDNS_DIR=$CURR_DIR/../../ +PO2LMO= + +showhelp() +{ + echo "Usage: make [OPTION]" + echo "Options:" + echo " -o output directory." + echo " --arch archtecture." + echo " --ver version." + echo " -h show this message." +} + +build_tool() +{ + make -C $ROOT/tool/po2lmo -j + PO2LMO="$ROOT/tool/po2lmo/src/po2lmo" + +} + +clean_tool() +{ + make -C $ROOT/tool/po2lmo clean +} + +build() +{ + + ROOT=/tmp/luci-app-smartdns + rm -fr $ROOT + + mkdir -p $ROOT + cp $CURR_DIR/* $ROOT/ -af + cd $ROOT/ + build_tool + mkdir $ROOT/root/usr/lib/lua/ -p + cp $ROOT/files/luci $ROOT/root/usr/lib/lua/ -af + + #Generate Language + $PO2LMO $ROOT/files/luci/i18n/smartdns.zh-cn.po $ROOT/root/usr/lib/lua/luci/i18n/smartdns.zh-cn.lmo + rm $ROOT/root/usr/lib/lua/luci/i18n/smartdns.zh-cn.po + + cp $ROOT/files/etc $ROOT/root/ -af + INST_SIZE="`du -sb $ROOT/root/ | awk '{print $1}'`" + + sed -i "s/^Architecture.*/Architecture: all/g" $ROOT/control/control + sed -i "s/Version:.*/Version: $VER/" $ROOT/control/control + + if [ ! -z "$INST_SIZE" ]; then + echo "Installed-Size: $INST_SIZE" >> $ROOT/control/control + fi + + cd $ROOT/control + chmod +x * + tar zcf ../control.tar.gz ./ + cd $ROOT + + tar zcf $ROOT/data.tar.gz -C root . + tar zcf $OUTPUTDIR/luci-app-smartdns.$VER.$FILEARCH.ipk ./control.tar.gz ./data.tar.gz ./debian-binary + + rm -fr $ROOT/ +} + +main() +{ + OPTS=`getopt -o o:h --long arch:,ver:,filearch: \ + -n "" -- "$@"` + + if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi + + # Note the quotes around `$TEMP': they are essential! + eval set -- "$OPTS" + + while true; do + case "$1" in + --arch) + ARCH="$2" + shift 2;; + --filearch) + FILEARCH="$2" + shift 2;; + --ver) + VER="$2" + shift 2;; + -o ) + OUTPUTDIR="$2" + shift 2;; + -h | --help ) + showhelp + return 0 + shift ;; + -- ) shift; break ;; + * ) break ;; + esac + done + + if [ -z "$ARCH" ]; then + echo "please input arch." + return 1; + fi + + if [ -z "$FILEARCH" ]; then + FILEARCH=$ARCH + fi + + if [ -z "$OUTPUTDIR" ]; then + OUTPUTDIR=$CURR_DIR; + fi + + build +} + +main $@ +exit $? + + diff --git a/release/src/router/smartdns/package/luci-compat/tool/po2lmo/Makefile b/release/src/router/smartdns/package/luci-compat/tool/po2lmo/Makefile new file mode 100644 index 0000000000..ad2c133207 --- /dev/null +++ b/release/src/router/smartdns/package/luci-compat/tool/po2lmo/Makefile @@ -0,0 +1,12 @@ + +INSTALL = install +PREFIX = /usr/bin + +po2lmo: src/po2lmo.o src/template_lmo.o + $(CC) $(LDFLAGS) -o src/po2lmo src/po2lmo.o src/template_lmo.o + +install: + $(INSTALL) -m 755 src/po2lmo $(PREFIX) + +clean: + $(RM) src/po2lmo src/*.o diff --git a/release/src/router/smartdns/package/luci-compat/tool/po2lmo/src/po2lmo.c b/release/src/router/smartdns/package/luci-compat/tool/po2lmo/src/po2lmo.c new file mode 100644 index 0000000000..0da792b680 --- /dev/null +++ b/release/src/router/smartdns/package/luci-compat/tool/po2lmo/src/po2lmo.c @@ -0,0 +1,247 @@ +/* + * lmo - Lua Machine Objects - PO to LMO conversion tool + * + * Copyright (C) 2009-2012 Jo-Philipp Wich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "template_lmo.h" + +static void die(const char *msg) +{ + fprintf(stderr, "Error: %s\n", msg); + exit(1); +} + +static void usage(const char *name) +{ + fprintf(stderr, "Usage: %s input.po output.lmo\n", name); + exit(1); +} + +static void print(const void *ptr, size_t size, size_t nmemb, FILE *stream) +{ + if( fwrite(ptr, size, nmemb, stream) == 0 ) + die("Failed to write stdout"); +} + +static int extract_string(const char *src, char *dest, int len) +{ + int pos = 0; + int esc = 0; + int off = -1; + + for( pos = 0; (pos < strlen(src)) && (pos < len); pos++ ) + { + if( (off == -1) && (src[pos] == '"') ) + { + off = pos + 1; + } + else if( off >= 0 ) + { + if( esc == 1 ) + { + switch (src[pos]) + { + case '"': + case '\\': + off++; + break; + } + dest[pos-off] = src[pos]; + esc = 0; + } + else if( src[pos] == '\\' ) + { + dest[pos-off] = src[pos]; + esc = 1; + } + else if( src[pos] != '"' ) + { + dest[pos-off] = src[pos]; + } + else + { + dest[pos-off] = '\0'; + break; + } + } + } + + return (off > -1) ? strlen(dest) : -1; +} + +static int cmp_index(const void *a, const void *b) +{ + uint32_t x = ((const lmo_entry_t *)a)->key_id; + uint32_t y = ((const lmo_entry_t *)b)->key_id; + + if (x < y) + return -1; + else if (x > y) + return 1; + + return 0; +} + +static void print_uint32(uint32_t x, FILE *out) +{ + uint32_t y = htonl(x); + print(&y, sizeof(uint32_t), 1, out); +} + +static void print_index(void *array, int n, FILE *out) +{ + lmo_entry_t *e; + + qsort(array, n, sizeof(*e), cmp_index); + + for (e = array; n > 0; n--, e++) + { + print_uint32(e->key_id, out); + print_uint32(e->val_id, out); + print_uint32(e->offset, out); + print_uint32(e->length, out); + } +} + +int main(int argc, char *argv[]) +{ + char line[4096]; + char key[4096]; + char val[4096]; + char tmp[4096]; + int state = 0; + int offset = 0; + int length = 0; + int n_entries = 0; + void *array = NULL; + lmo_entry_t *entry = NULL; + uint32_t key_id, val_id; + + FILE *in; + FILE *out; + + if( (argc != 3) || ((in = fopen(argv[1], "r")) == NULL) || ((out = fopen(argv[2], "w")) == NULL) ) + usage(argv[0]); + + memset(line, 0, sizeof(key)); + memset(key, 0, sizeof(val)); + memset(val, 0, sizeof(val)); + + while( (NULL != fgets(line, sizeof(line), in)) || (state >= 2 && feof(in)) ) + { + if( state == 0 && strstr(line, "msgid \"") == line ) + { + switch(extract_string(line, key, sizeof(key))) + { + case -1: + die("Syntax error in msgid"); + case 0: + state = 1; + break; + default: + state = 2; + } + } + else if( state == 1 || state == 2 ) + { + if( strstr(line, "msgstr \"") == line || state == 2 ) + { + switch(extract_string(line, val, sizeof(val))) + { + case -1: + state = 4; + break; + default: + state = 3; + } + } + else + { + switch(extract_string(line, tmp, sizeof(tmp))) + { + case -1: + state = 2; + break; + default: + strcat(key, tmp); + } + } + } + else if( state == 3 ) + { + switch(extract_string(line, tmp, sizeof(tmp))) + { + case -1: + state = 4; + break; + default: + strcat(val, tmp); + } + } + + if( state == 4 ) + { + if( strlen(key) > 0 && strlen(val) > 0 ) + { + key_id = sfh_hash(key, strlen(key)); + val_id = sfh_hash(val, strlen(val)); + + if( key_id != val_id ) + { + n_entries++; + array = realloc(array, n_entries * sizeof(lmo_entry_t)); + entry = (lmo_entry_t *)array + n_entries - 1; + + if (!array) + die("Out of memory"); + + entry->key_id = key_id; + entry->val_id = val_id; + entry->offset = offset; + entry->length = strlen(val); + + length = strlen(val) + ((4 - (strlen(val) % 4)) % 4); + + print(val, length, 1, out); + offset += length; + } + } + + state = 0; + memset(key, 0, sizeof(key)); + memset(val, 0, sizeof(val)); + } + + memset(line, 0, sizeof(line)); + } + + print_index(array, n_entries, out); + + if( offset > 0 ) + { + print_uint32(offset, out); + fsync(fileno(out)); + fclose(out); + } + else + { + fclose(out); + unlink(argv[2]); + } + + fclose(in); + return(0); +} diff --git a/release/src/router/smartdns/package/luci-compat/tool/po2lmo/src/template_lmo.c b/release/src/router/smartdns/package/luci-compat/tool/po2lmo/src/template_lmo.c new file mode 100644 index 0000000000..27205a7228 --- /dev/null +++ b/release/src/router/smartdns/package/luci-compat/tool/po2lmo/src/template_lmo.c @@ -0,0 +1,328 @@ +/* + * lmo - Lua Machine Objects - Base functions + * + * Copyright (C) 2009-2010 Jo-Philipp Wich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "template_lmo.h" + +/* + * Hash function from http://www.azillionmonkeys.com/qed/hash.html + * Copyright (C) 2004-2008 by Paul Hsieh + */ + +uint32_t sfh_hash(const char *data, int len) +{ + uint32_t hash = len, tmp; + int rem; + + if (len <= 0 || data == NULL) return 0; + + rem = len & 3; + len >>= 2; + + /* Main loop */ + for (;len > 0; len--) { + hash += sfh_get16(data); + tmp = (sfh_get16(data+2) << 11) ^ hash; + hash = (hash << 16) ^ tmp; + data += 2*sizeof(uint16_t); + hash += hash >> 11; + } + + /* Handle end cases */ + switch (rem) { + case 3: hash += sfh_get16(data); + hash ^= hash << 16; + hash ^= data[sizeof(uint16_t)] << 18; + hash += hash >> 11; + break; + case 2: hash += sfh_get16(data); + hash ^= hash << 11; + hash += hash >> 17; + break; + case 1: hash += *data; + hash ^= hash << 10; + hash += hash >> 1; + } + + /* Force "avalanching" of final 127 bits */ + hash ^= hash << 3; + hash += hash >> 5; + hash ^= hash << 4; + hash += hash >> 17; + hash ^= hash << 25; + hash += hash >> 6; + + return hash; +} + +uint32_t lmo_canon_hash(const char *str, int len) +{ + char res[4096]; + char *ptr, prev; + int off; + + if (!str || len >= sizeof(res)) + return 0; + + for (prev = ' ', ptr = res, off = 0; off < len; prev = *str, off++, str++) + { + if (isspace(*str)) + { + if (!isspace(prev)) + *ptr++ = ' '; + } + else + { + *ptr++ = *str; + } + } + + if ((ptr > res) && isspace(*(ptr-1))) + ptr--; + + return sfh_hash(res, ptr - res); +} + +lmo_archive_t * lmo_open(const char *file) +{ + int in = -1; + uint32_t idx_offset = 0; + struct stat s; + + lmo_archive_t *ar = NULL; + + if (stat(file, &s) == -1) + goto err; + + if ((in = open(file, O_RDONLY)) == -1) + goto err; + + if ((ar = (lmo_archive_t *)malloc(sizeof(*ar))) != NULL) + { + memset(ar, 0, sizeof(*ar)); + + ar->fd = in; + ar->size = s.st_size; + + fcntl(ar->fd, F_SETFD, fcntl(ar->fd, F_GETFD) | FD_CLOEXEC); + + if ((ar->mmap = mmap(NULL, ar->size, PROT_READ, MAP_SHARED, ar->fd, 0)) == MAP_FAILED) + goto err; + + idx_offset = ntohl(*((const uint32_t *) + (ar->mmap + ar->size - sizeof(uint32_t)))); + + if (idx_offset >= ar->size) + goto err; + + ar->index = (lmo_entry_t *)(ar->mmap + idx_offset); + ar->length = (ar->size - idx_offset - sizeof(uint32_t)) / sizeof(lmo_entry_t); + ar->end = ar->mmap + ar->size; + + return ar; + } + +err: + if (in > -1) + close(in); + + if (ar != NULL) + { + if ((ar->mmap != NULL) && (ar->mmap != MAP_FAILED)) + munmap(ar->mmap, ar->size); + + free(ar); + } + + return NULL; +} + +void lmo_close(lmo_archive_t *ar) +{ + if (ar != NULL) + { + if ((ar->mmap != NULL) && (ar->mmap != MAP_FAILED)) + munmap(ar->mmap, ar->size); + + close(ar->fd); + free(ar); + + ar = NULL; + } +} + + +lmo_catalog_t *_lmo_catalogs = NULL; +lmo_catalog_t *_lmo_active_catalog = NULL; + +int lmo_load_catalog(const char *lang, const char *dir) +{ + DIR *dh = NULL; + char pattern[16]; + char path[PATH_MAX]; + struct dirent *de = NULL; + + lmo_archive_t *ar = NULL; + lmo_catalog_t *cat = NULL; + + if (!lmo_change_catalog(lang)) + return 0; + + if (!dir || !(dh = opendir(dir))) + goto err; + + if (!(cat = malloc(sizeof(*cat)))) + goto err; + + memset(cat, 0, sizeof(*cat)); + + snprintf(cat->lang, sizeof(cat->lang), "%s", lang); + snprintf(pattern, sizeof(pattern), "*.%s.lmo", lang); + + while ((de = readdir(dh)) != NULL) + { + if (!fnmatch(pattern, de->d_name, 0)) + { + snprintf(path, sizeof(path), "%s/%s", dir, de->d_name); + ar = lmo_open(path); + + if (ar) + { + ar->next = cat->archives; + cat->archives = ar; + } + } + } + + closedir(dh); + + cat->next = _lmo_catalogs; + _lmo_catalogs = cat; + + if (!_lmo_active_catalog) + _lmo_active_catalog = cat; + + return 0; + +err: + if (dh) closedir(dh); + if (cat) free(cat); + + return -1; +} + +int lmo_change_catalog(const char *lang) +{ + lmo_catalog_t *cat; + + for (cat = _lmo_catalogs; cat; cat = cat->next) + { + if (!strncmp(cat->lang, lang, sizeof(cat->lang))) + { + _lmo_active_catalog = cat; + return 0; + } + } + + return -1; +} + +static lmo_entry_t * lmo_find_entry(lmo_archive_t *ar, uint32_t hash) +{ + unsigned int m, l, r; + uint32_t k; + + l = 0; + r = ar->length - 1; + + while (1) + { + m = l + ((r - l) / 2); + + if (r < l) + break; + + k = ntohl(ar->index[m].key_id); + + if (k == hash) + return &ar->index[m]; + + if (k > hash) + { + if (!m) + break; + + r = m - 1; + } + else + { + l = m + 1; + } + } + + return NULL; +} + +int lmo_translate(const char *key, int keylen, char **out, int *outlen) +{ + uint32_t hash; + lmo_entry_t *e; + lmo_archive_t *ar; + + if (!key || !_lmo_active_catalog) + return -2; + + hash = lmo_canon_hash(key, keylen); + + for (ar = _lmo_active_catalog->archives; ar; ar = ar->next) + { + if ((e = lmo_find_entry(ar, hash)) != NULL) + { + *out = ar->mmap + ntohl(e->offset); + *outlen = ntohl(e->length); + return 0; + } + } + + return -1; +} + +void lmo_close_catalog(const char *lang) +{ + lmo_archive_t *ar, *next; + lmo_catalog_t *cat, *prev; + + for (prev = NULL, cat = _lmo_catalogs; cat; prev = cat, cat = cat->next) + { + if (!strncmp(cat->lang, lang, sizeof(cat->lang))) + { + if (prev) + prev->next = cat->next; + else + _lmo_catalogs = cat->next; + + for (ar = cat->archives; ar; ar = next) + { + next = ar->next; + lmo_close(ar); + } + + free(cat); + break; + } + } +} diff --git a/release/src/router/smartdns/package/luci-compat/tool/po2lmo/src/template_lmo.h b/release/src/router/smartdns/package/luci-compat/tool/po2lmo/src/template_lmo.h new file mode 100644 index 0000000000..57f59aa56b --- /dev/null +++ b/release/src/router/smartdns/package/luci-compat/tool/po2lmo/src/template_lmo.h @@ -0,0 +1,92 @@ +/* + * lmo - Lua Machine Objects - General header + * + * Copyright (C) 2009-2012 Jo-Philipp Wich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _TEMPLATE_LMO_H_ +#define _TEMPLATE_LMO_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if (defined(__GNUC__) && defined(__i386__)) +#define sfh_get16(d) (*((const uint16_t *) (d))) +#else +#define sfh_get16(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8)\ + +(uint32_t)(((const uint8_t *)(d))[0]) ) +#endif + + +struct lmo_entry { + uint32_t key_id; + uint32_t val_id; + uint32_t offset; + uint32_t length; +} __attribute__((packed)); + +typedef struct lmo_entry lmo_entry_t; + + +struct lmo_archive { + int fd; + int length; + uint32_t size; + lmo_entry_t *index; + char *mmap; + char *end; + struct lmo_archive *next; +}; + +typedef struct lmo_archive lmo_archive_t; + + +struct lmo_catalog { + char lang[6]; + struct lmo_archive *archives; + struct lmo_catalog *next; +}; + +typedef struct lmo_catalog lmo_catalog_t; + + +uint32_t sfh_hash(const char *data, int len); +uint32_t lmo_canon_hash(const char *data, int len); + +lmo_archive_t * lmo_open(const char *file); +void lmo_close(lmo_archive_t *ar); + + +extern lmo_catalog_t *_lmo_catalogs; +extern lmo_catalog_t *_lmo_active_catalog; + +int lmo_load_catalog(const char *lang, const char *dir); +int lmo_change_catalog(const char *lang); +int lmo_translate(const char *key, int keylen, char **out, int *outlen); +void lmo_close_catalog(const char *lang); + +#endif diff --git a/release/src/router/smartdns/package/luci/control/control b/release/src/router/smartdns/package/luci/control/control index 2cd9e99934..e0feefc030 100644 --- a/release/src/router/smartdns/package/luci/control/control +++ b/release/src/router/smartdns/package/luci/control/control @@ -4,5 +4,4 @@ Depends: libc, smartdns Source: feeds/luci/applications/luci-app-smartdns Section: luci Architecture: all -Installed-Size: 1040 -Description: A smartdns server module +Description: A smartdns server diff --git a/release/src/router/smartdns/package/luci/control/postinst-pkg b/release/src/router/smartdns/package/luci/control/postinst-pkg index ded67b630f..e69de29bb2 100644 --- a/release/src/router/smartdns/package/luci/control/postinst-pkg +++ b/release/src/router/smartdns/package/luci/control/postinst-pkg @@ -1,4 +0,0 @@ -[ -n "${IPKG_INSTROOT}" ] || { - (. /etc/uci-defaults/50_luci-smartdns) && rm -f /etc/uci-defaults/50_luci-smartdns - exit 0 -} diff --git a/release/src/router/smartdns/package/luci/files/luci/i18n/smartdns.zh-cn.po b/release/src/router/smartdns/package/luci/files/luci/i18n/smartdns.zh-cn.po index 567cdf15fa..ee00152f18 100644 --- a/release/src/router/smartdns/package/luci/files/luci/i18n/smartdns.zh-cn.po +++ b/release/src/router/smartdns/package/luci/files/luci/i18n/smartdns.zh-cn.po @@ -1,282 +1,311 @@ -msgid "" -msgstr "Content-Type: text/plain; charset=UTF-8\n" - -msgid "SmartDNS" -msgstr "SmartDNS" - -msgid "SmartDNS is a local high-performance DNS server" -msgstr "SmartDNS是一个本地高性能DNS服务器" - -msgid "SmartDNS Server" -msgstr "SmartDNS 服务器" - -msgid "SmartDNS is a local high-performance DNS server, supports finding fastest IP, supports ad filtering, and supports avoiding DNS poisoning." -msgstr "SmartDNS是一个本地高性能DNS服务器,支持返回最快IP,支持广告过滤。" - -msgid "Custom Settings" -msgstr "自定义设置" - -msgid "Generate Coredump" -msgstr "生成coredump" - -msgid "Generate Coredump file when smartdns crash, coredump file is located at /tmp/smartdns.xxx.core." -msgstr "当smartdns异常时生成coredump文件,coredump文件在/tmp/smartdns.xxx.core." - -msgid "Server Name" -msgstr "服务器名称" - -msgid "Smartdns server name" -msgstr "SmartDNS的服务器名称,默认为smartdns,留空为主机名" - -msgid "SmartDNS is a local dns server to find fastest ip." -msgstr "本地高性能服务器,优化网络访问性能。" - -msgid "Enable or disable smartdns server" -msgstr "启用或禁用SmartDNS服务" - -msgid "Local Port" -msgstr "本地端口" - -msgid "Smartdns local server port" -msgstr "SmartDNS本地服务端口" - -msgid "IPV4 53 Port Redirect Failure" -msgstr "IPV4 53端口重定向失败" - -msgid "IPV6 53 Port Redirect Failure" -msgstr "IPV6 53端口重定向失败" - -msgid "Dnsmasq Forwared To Smartdns Failure" -msgstr "重定向dnsmasq到smartdns失败" - -msgid "TCP Server" -msgstr "TCP服务器" - -msgid "Enable TCP DNS Server" -msgstr "启用TCP服务器" - -msgid "IPV6 Server" -msgstr "IPV6服务器" - -msgid "Enable IPV6 DNS Server" -msgstr "启用IPV6服务器" - -msgid "Dual-stack IP Selection" -msgstr "双栈IP优选" - -msgid "Enable IP selection between IPV4 and IPV6" -msgstr "启用或禁用IPV4,IPV6间的IP优选策略。" - -msgid "Domain prefetch" -msgstr "域名预加载" - -msgid "Enable domain prefetch, accelerate domain response speed." -msgstr "启用域名预加载,加速域名响应速度。" - -msgid "Redirect" -msgstr "重定向" - -msgid "SmartDNS redirect mode" -msgstr "SmartDNS 重定向模式" - -msgid "Run as dnsmasq upstream server" -msgstr "作为dnsmasq的上游服务器" - -msgid "Redirect 53 port to SmartDNS" -msgstr "重定向53端口到SmartDNS" - -msgid "Cache Size" -msgstr "缓存大小" - -msgid "DNS domain result cache size" -msgstr "缓存DNS的结果,缓存大小,配置零则不缓存" - -msgid "Domain TTL" -msgstr "域名TTL" - -msgid "TTL for all domain result." -msgstr "设置所有域名的TTL值" - -msgid "Domain TTL Min" -msgstr "域名TTL最小值" - -msgid "Minimum TTL for all domain result." -msgstr "设置所有域名的TTL最小值" - -msgid "Domain TTL Max" -msgstr "域名TTL最大值" - -msgid "Maximum TTL for all domain result." -msgstr "设置所有域名的TTL最大值" - -msgid "smartdns custom settings" -msgstr "smartdns 自定义设置,具体配置参数参考指导" - -msgid "Second Server Settings" -msgstr "第二DNS服务器" - -msgid "Enable or disable second DNS server." -msgstr "是否启用第二DNS服务器。" - -msgid "Skip Speed Check" -msgstr "跳过测速" - -msgid "Do not check speed." -msgstr "禁用测速。" - -msgid "Server Group" -msgstr "服务器组" - -msgid "Query DNS through specific dns server group, such as office, home." -msgstr "使用指定服务器组查询,比如office, home。" - -msgid "Skip Address Rules" -msgstr "跳过address规则" - -msgid "Skip address rules." -msgstr "跳过address规则。" - -msgid "Skip Nameserver Rule" -msgstr "跳过Nameserver规则" - -msgid "Skip nameserver rules." -msgstr "跳过Nameserver规则。" - -msgid "Skip Ipset Rule" -msgstr "跳过ipset规则" - -msgid "Skip ipset rules." -msgstr "跳过ipset规则。" - -msgid "Skip SOA Address Rule" -msgstr "跳过address SOA(#)规则" - -msgid "Skip SOA address rules." -msgstr "跳过address SOA(#)规则。" - -msgid "Skip Dualstack Selection" -msgstr "跳过双栈优选" - -msgid "Skip Sualstack Selection." -msgstr "跳过双栈优选。" - -msgid "Skip Cache" -msgstr "跳过cache" - -msgid "Skip Cache." -msgstr "跳过cache。" - -msgid "Upstream Servers" -msgstr "上游服务器" - -msgid "Upstream Servers, support UDP, TCP protocol. Please configure multiple DNS servers, including multiple foreign DNS servers." -msgstr "上游DNS服务器列表,支持UDP,TCP协议,请配置多个上游DNS服务器,包括多个国内外服务器" - -msgid "DNS Server Name" -msgstr "DNS服务器名称" - -msgid "port" -msgstr "端口" - -msgid "DNS Server port" -msgstr "DNS服务器端口" - -msgid "DNS Server ip" -msgstr "DNS服务器IP" - -msgid "type" -msgstr "类型" - -msgid "DNS Server type" -msgstr "协议类型" - -msgid "Domain Address" -msgstr "域名地址" - -msgid "TLS Hostname Verify" -msgstr "校验TLS主机名" - -msgid "Set TLS hostname to verify." -msgstr "设置校验TLS主机名。" - -msgid "TLS SNI name" -msgstr "TLS SNI名称" - -msgid "HTTP Host" -msgstr "HTTP主机" - -msgid "Sets the server name indication for query." -msgstr "设置查询时使用的服务器SNI名称。" - -msgid "Set the HTTP host used for the query. Use this parameter when the host of the URL address is an IP address." -msgstr "设置查询时使用的HTTP主机,当URL地址的host是IP地址时,使用此参数。" - -msgid "Server Group" -msgstr "服务器组" - -msgid "DNS Server group belongs to, used with nameserver, such as office, home." -msgsr "DNS服务器所属组, 配合nameserver使用,例如:office,home。" - -msgid "IP Blacklist Filtering" -msgstr "IP黑名单过滤" - -msgid "Anti Answer Forgery" -msgstr "反回答伪造" - -msgid "Anti answer forgery, if DNS does not work properly after enabling, please turn off this feature" -msgstr "反回答伪造,如果启用后DNS工作不正常,请关闭此功能。" - -msgid "Filtering IP with blacklist" -msgstr "使用IP黑名单过滤" - -msgid "TLS SPKI Pinning" -msgstr "TLS SPKI 指纹" - -msgid "Used to verify the validity of the TLS server, The value is Base64 encoded SPKI fingerprint, leaving blank to indicate that the validity of TLS is not verified." -msgstr "用于校验TLS服务器的有效性,数值为Base64编码的SPKI指纹, 留空表示不验证TLS的合法性" - -msgid "Additional Server Args" -msgstr "额外的服务器参数" - -msgid "Additional Args for upstream dns servers" -msgstr "额外的上游DNS服务器参数" - -msgid "Upstream DNS Server Configuration" -msgstr "上游DNS服务器配置" - -msgid "Set Specific domain ip address." -msgstr "指定特定域名的IP地址" - -msgid "Specify an IP address to return for any host in the given domains, Queries in the domains are never forwarded and always replied to with the specified IP address which may be IPv4 or IPv6." -msgstr "配置特定域名返回特定的IP地址,域名查询将不到上游服务器请求,直接返回配置的IP地址,可用于广告屏蔽。" - -msgid "IP Blacklist" -msgstr "IP黑名单" - -msgid "Set Specific ip blacklist." -msgstr "设置IP黑名单列表" - -msgid "Configure IP blacklists that will be filtered from the results of specific DNS server." -msgstr "配置需要从指定域名服务器结果过滤的IP黑名单。" - -msgid "Technical Support" -msgstr "技术支持" - -msgid "If you like this software, please buy me a cup of coffee." -msgstr "如果本软件对你有帮助,请给作者加个蛋。" - -msgid "SmartDNS official website" -msgstr "SmartDNS官方网站" - -msgid "open website" -msgstr "打开网站" - -msgid "Donate to smartdns" -msgstr "捐助smartdns项目" - -msgid "Donate" -msgstr "捐助" - - - - +msgid "" +msgstr "Content-Type: text/plain; charset=UTF-8\n" + +msgid "SmartDNS" +msgstr "SmartDNS" + +msgid "SmartDNS is a local high-performance DNS server" +msgstr "SmartDNS是一个本地高性能DNS服务器" + +msgid "SmartDNS Server" +msgstr "SmartDNS 服务器" + +msgid "SmartDNS is a local high-performance DNS server, supports finding fastest IP, supports ad filtering, and supports avoiding DNS poisoning." +msgstr "SmartDNS是一个本地高性能DNS服务器,支持返回最快IP,支持广告过滤。" + +msgid "Custom Settings" +msgstr "自定义设置" + +msgid "General Settings" +msgstr "基本设置" + +msgid "Settings" +msgstr "设置" + +msgid "Advanced Settings" +msgstr "高级设置" + +msgid "RUNNING" +msgstr "运行中" + +msgid "NOT RUNNING" +msgstr "未运行" + +msgid "Generate Coredump" +msgstr "生成coredump" + +msgid "Generate Coredump file when smartdns crash, coredump file is located at /tmp/smartdns.xxx.core." +msgstr "当smartdns异常时生成coredump文件,coredump文件在/tmp/smartdns.xxx.core." + +msgid "Server Name" +msgstr "服务器名称" + +msgid "Smartdns server name" +msgstr "SmartDNS的服务器名称,默认为smartdns,留空为主机名" + +msgid "SmartDNS is a local dns server to find fastest ip." +msgstr "本地高性能服务器,优化网络访问性能。" + +msgid "Enable or disable smartdns server" +msgstr "启用或禁用SmartDNS服务" + +msgid "Local Port" +msgstr "本地端口" + +msgid "Smartdns local server port" +msgstr "SmartDNS本地服务端口" + +msgid "IPV4 53 Port Redirect Failure" +msgstr "IPV4 53端口重定向失败" + +msgid "IPV6 53 Port Redirect Failure" +msgstr "IPV6 53端口重定向失败" + +msgid "Dnsmasq Forwared To Smartdns Failure" +msgstr "重定向dnsmasq到smartdns失败" + +msgid "TCP Server" +msgstr "TCP服务器" + +msgid "Enable TCP DNS Server" +msgstr "启用TCP服务器" + +msgid "IPV6 Server" +msgstr "IPV6服务器" + +msgid "Enable IPV6 DNS Server" +msgstr "启用IPV6服务器" + +msgid "Dual-stack IP Selection" +msgstr "双栈IP优选" + +msgid "Enable IP selection between IPV4 and IPV6" +msgstr "启用或禁用IPV4,IPV6间的IP优选策略。" + +msgid "Domain prefetch" +msgstr "域名预加载" + +msgid "Enable domain prefetch, accelerate domain response speed." +msgstr "启用域名预加载,加速域名响应速度。" + +msgid "Serve expired" +msgstr "缓存过期服务" + +msgid "Attempts to serve old responses from cache with a TTL of 0 in the response without waiting for the actual resolution to finish." +msgstr "查询性能优化,有请求时尝试回应TTL为0的过期记录,以避免查询等待。" + +msgid "Redirect" +msgstr "重定向" + +msgid "SmartDNS redirect mode" +msgstr "SmartDNS 重定向模式" + +msgid "Run as dnsmasq upstream server" +msgstr "作为dnsmasq的上游服务器" + +msgid "Redirect 53 port to SmartDNS" +msgstr "重定向53端口到SmartDNS" + +msgid "Cache Size" +msgstr "缓存大小" + +msgid "DNS domain result cache size" +msgstr "缓存DNS的结果,缓存大小,配置零则不缓存" + +msgid "Domain TTL" +msgstr "域名TTL" + +msgid "TTL for all domain result." +msgstr "设置所有域名的TTL值" + +msgid "Domain TTL Min" +msgstr "域名TTL最小值" + +msgid "Minimum TTL for all domain result." +msgstr "设置所有域名的TTL最小值" + +msgid "Domain TTL Max" +msgstr "域名TTL最大值" + +msgid "Maximum TTL for all domain result." +msgstr "设置所有域名的TTL最大值" + +msgid "smartdns custom settings" +msgstr "smartdns 自定义设置,具体配置参数参考指导" + +msgid "Second Server Settings" +msgstr "第二DNS服务器" + +msgid "Enable or disable second DNS server." +msgstr "是否启用第二DNS服务器。" + +msgid "Skip Speed Check" +msgstr "跳过测速" + +msgid "Do not check speed." +msgstr "禁用测速。" + +msgid "Server Group" +msgstr "服务器组" + +msgid "Query DNS through specific dns server group, such as office, home." +msgstr "使用指定服务器组查询,比如office, home。" + +msgid "Skip Address Rules" +msgstr "跳过address规则" + +msgid "Skip address rules." +msgstr "跳过address规则。" + +msgid "Skip Nameserver Rule" +msgstr "跳过Nameserver规则" + +msgid "Skip nameserver rules." +msgstr "跳过Nameserver规则。" + +msgid "Skip Ipset Rule" +msgstr "跳过ipset规则" + +msgid "Skip ipset rules." +msgstr "跳过ipset规则。" + +msgid "Skip SOA Address Rule" +msgstr "跳过address SOA(#)规则" + +msgid "Skip SOA address rules." +msgstr "跳过address SOA(#)规则。" + +msgid "Skip Dualstack Selection" +msgstr "跳过双栈优选" + +msgid "Skip Dualstack Selection." +msgstr "跳过双栈优选。" + +msgid "Skip Cache" +msgstr "跳过cache" + +msgid "Skip Cache." +msgstr "跳过cache。" + +msgid "Force AAAA SOA" +msgstr "停用IPV6地址解析" + +msgid "Force AAAA SOA." +msgstr "停用IPV6地址解析。" + +msgid "Upstream Servers" +msgstr "上游服务器" + +msgid "Upstream Servers, support UDP, TCP protocol. Please configure multiple DNS servers, including multiple foreign DNS servers." +msgstr "上游DNS服务器列表,支持UDP,TCP协议,请配置多个上游DNS服务器,包括多个国内外服务器" + +msgid "DNS Server Name" +msgstr "DNS服务器名称" + +msgid "port" +msgstr "端口" + +msgid "DNS Server port" +msgstr "DNS服务器端口" + +msgid "DNS Server ip" +msgstr "DNS服务器IP" + +msgid "type" +msgstr "类型" + +msgid "DNS Server type" +msgstr "协议类型" + +msgid "Domain Address" +msgstr "域名地址" + +msgid "TLS Hostname Verify" +msgstr "校验TLS主机名" + +msgid "Set TLS hostname to verify." +msgstr "设置校验TLS主机名。" + +msgid "No check certificate" +msgstr "停用证书校验" + +msgid "Do not check certificate." +msgstr "不校验证书的合法性。" + +msgid "TLS SNI name" +msgstr "TLS SNI名称" + +msgid "HTTP Host" +msgstr "HTTP主机" + +msgid "Sets the server name indication for query." +msgstr "设置查询时使用的服务器SNI名称。" + +msgid "Set the HTTP host used for the query. Use this parameter when the host of the URL address is an IP address." +msgstr "设置查询时使用的HTTP主机,当URL地址的host是IP地址时,使用此参数。" + +msgid "Server Group" +msgstr "服务器组" + +msgid "DNS Server group belongs to, used with nameserver, such as office, home." +msgstr "DNS服务器所属组, 配合nameserver使用,例如:office,home。" + +msgid "IP Blacklist Filtering" +msgstr "IP黑名单过滤" + +msgid "Anti Answer Forgery" +msgstr "反回答伪造" + +msgid "Anti answer forgery, if DNS does not work properly after enabling, please turn off this feature" +msgstr "反回答伪造,如果启用后DNS工作不正常,请关闭此功能。" + +msgid "Filtering IP with blacklist" +msgstr "使用IP黑名单过滤" + +msgid "TLS SPKI Pinning" +msgstr "TLS SPKI 指纹" + +msgid "Used to verify the validity of the TLS server, The value is Base64 encoded SPKI fingerprint, leaving blank to indicate that the validity of TLS is not verified." +msgstr "用于校验TLS服务器的有效性,数值为Base64编码的SPKI指纹, 留空表示不验证TLS的合法性" + +msgid "Additional Server Args" +msgstr "额外的服务器参数" + +msgid "Additional Args for upstream dns servers" +msgstr "额外的上游DNS服务器参数" + +msgid "Upstream DNS Server Configuration" +msgstr "上游DNS服务器配置" + +msgid "Set Specific domain ip address." +msgstr "指定特定域名的IP地址" + +msgid "Specify an IP address to return for any host in the given domains, Queries in the domains are never forwarded and always replied to with the specified IP address which may be IPv4 or IPv6." +msgstr "配置特定域名返回特定的IP地址,域名查询将不到上游服务器请求,直接返回配置的IP地址,可用于广告屏蔽。" + +msgid "IP Blacklist" +msgstr "IP黑名单" + +msgid "Set Specific ip blacklist." +msgstr "设置IP黑名单列表" + +msgid "Configure IP blacklists that will be filtered from the results of specific DNS server." +msgstr "配置需要从指定域名服务器结果过滤的IP黑名单。" + +msgid "Technical Support" +msgstr "技术支持" + +msgid "If you like this software, please buy me a cup of coffee." +msgstr "如果本软件对你有帮助,请给作者加个蛋。" + +msgid "SmartDNS official website" +msgstr "SmartDNS官方网站" + +msgid "open website" +msgstr "打开网站" + +msgid "Donate to smartdns" +msgstr "捐助smartdns项目" + +msgid "Donate" +msgstr "捐助" diff --git a/release/src/router/smartdns/package/luci/files/root/usr/share/luci/menu.d/luci-app-smartdns.json b/release/src/router/smartdns/package/luci/files/root/usr/share/luci/menu.d/luci-app-smartdns.json new file mode 100644 index 0000000000..91b4402484 --- /dev/null +++ b/release/src/router/smartdns/package/luci/files/root/usr/share/luci/menu.d/luci-app-smartdns.json @@ -0,0 +1,12 @@ +{ + "admin/services/smartdns": { + "title": "SmartDNS", + "action": { + "type": "view", + "path": "smartdns/smartdns" + }, + "depends": { + "uci": { "smartdns": true } + } + } +} diff --git a/release/src/router/smartdns/package/luci/files/root/usr/share/rpcd/acl.d/luci-app-smartdns.json b/release/src/router/smartdns/package/luci/files/root/usr/share/rpcd/acl.d/luci-app-smartdns.json new file mode 100644 index 0000000000..78fbb1c509 --- /dev/null +++ b/release/src/router/smartdns/package/luci/files/root/usr/share/rpcd/acl.d/luci-app-smartdns.json @@ -0,0 +1,23 @@ +{ + "luci-app-smartdns": { + "description": "Grant access to LuCI app smartdns", + "read": { + "file": { + "/etc/smartdns/*": [ "read" ], + "/usr/sbin/iptables -t nat -nL PREROUTING": [ "exec" ], + "/usr/sbin/ip6tables -t nat -nL PREROUTING": [ "exec" ], + "/usr/sbin/smartdns": [ "exec" ] + }, + "ubus": { + "service": [ "list" ] + }, + "uci": [ "smartdns" ] + }, + "write": { + "file": { + "/etc/smartdns/*": [ "write" ] + }, + "uci": [ "smartdns" ] + } + } +} diff --git a/release/src/router/smartdns/package/luci/files/root/www/luci-static/resources/view/smartdns/smartdns.js b/release/src/router/smartdns/package/luci/files/root/www/luci-static/resources/view/smartdns/smartdns.js new file mode 100644 index 0000000000..4d137753c7 --- /dev/null +++ b/release/src/router/smartdns/package/luci/files/root/www/luci-static/resources/view/smartdns/smartdns.js @@ -0,0 +1,492 @@ +/************************************************************************* + * + * Copyright (C) 2018-2020 Ruilin Peng (Nick) . + * + * smartdns is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * smartdns is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + + +'use strict'; +'require fs'; +'require uci'; +'require form'; +'require rpc'; + +var conf = 'smartdns'; +var callServiceList = rpc.declare({ + object: 'service', + method: 'list', + params: ['name'], + expect: { '': {} } +}); + +function getPidOfSmartdns() { + return L.resolveDefault(callServiceList(conf), {}) + .then(function (res) { + var isrunning = false; + try { + isrunning = res[conf]['instances']['smartdns']['running']; + } catch (e) { } + return isrunning; + }); +} + +function getIPTablesRedirect() { + return fs.exec('/usr/sbin/iptables', ['-t', 'nat', '-nL', 'PREROUTING']).then(function (res) { + if (res.code === 0) { + return res.stdout.trim(); + } else { + return ""; + } + }); +} + +function getIP6TablesRedirect() { + return fs.exec('/usr/sbin/ip6tables', ['-t', 'nat', '-nL', 'PREROUTING']).then(function (res) { + if (res.code === 0) { + return res.stdout.trim(); + } else { + return ""; + } + }); +} + +function smartdnsServiceStatus() { + return Promise.all([ + getPidOfSmartdns(), + getIPTablesRedirect(), + getIP6TablesRedirect() + ]); +} + +function smartdnsRenderStatus(res) { + var renderHTML = ""; + var isRunning = res[0]; + var ipt = res[1]; + var ip6t = res[2]; + + var serverPort = uci.get_first('smartdns', 'smartdns', 'port'); + var redirectMode = uci.get_first('smartdns', 'smartdns', 'redirect'); + var ipv6Enabled = uci.get_first('smartdns', 'smartdns', 'ipv6_server'); + + if (isRunning) { + renderHTML += "SmartDNS - " + _("RUNNING") + ""; + } else { + renderHTML += "SmartDNS - " + _("NOT RUNNING") + ""; + return renderHTML; + } + + if (redirectMode === "dnsmasq-upstream") { + var matchLine = "127.0.0.1#" + serverPort; + var dnsmasqServer = uci.get_first('dhcp', 'dnsmasq', 'server') || ""; + + if (dnsmasqServer.indexOf(matchLine) < 0) { + renderHTML += "
" + _("Dnsmasq Forwared To Smartdns Failure") + ""; + } + } else if (redirectMode === "redirect") { + var redirectRules = (ipt || '').split(/\n/).filter(function (rule) { + return rule.match(/REDIRECT/) && rule.match(/dpt:53/) && rule.match("ports " + serverPort); + }); + + if (redirectRules.length <= 0) { + renderHTML += "
" + _("IPV4 53 Port Redirect Failure") + ""; + if (ipv6Enabled) { + var redirectRules = (ip6t || '').split(/\n/).filter(function (rule) { + return rule.match(/REDIRECT/) && rule.match(/dpt:53/) && rule.match("ports " + serverPort); + }); + if (redirectRules.length <= 0) { + renderHTML += "
" + _("IPV6 53 Port Redirect Failure") + ""; + } + } + } + } + + return renderHTML; +} + +return L.view.extend({ + load: function () { + return Promise.all([ + uci.load('smartdns'), + uci.load('dhcp') + ]); + }, + render: function (stats) { + var m, s, o; + + m = new form.Map('smartdns', _('SmartDNS')); + m.title = _("SmartDNS Server"); + m.description = _("SmartDNS is a local high-performance DNS server, supports finding fastest IP, " + + "supports ad filtering, and supports avoiding DNS poisoning."); + + s = m.section(form.NamedSection, '_status'); + s.anonymous = true; + s.render = function (section_id) { + L.Poll.add(function () { + return L.resolveDefault(smartdnsServiceStatus()).then(function (res) { + var view = document.getElementById("service_status"); + view.innerHTML = smartdnsRenderStatus(res); + }); + }); + + return E('div', { class: 'cbi-map' }, + E('div', { class: 'cbi-section' }, [ + E('div', { id: 'service_status' }, + _('Collecting data ...')) + ]) + ); + } + + // Basic; + s = m.section(form.TypedSection, "smartdns", _("Settings"), _("General Settings")); + s.anonymous = true; + + s.tab("settings", _("General Settings")); + s.tab("seconddns", _("Second Server Settings")); + s.tab("custom", _("Custom Settings")); + + // Eanble; + o = s.taboption("settings", form.Flag, "enabled", _("Enable"), _("Enable or disable smartdns server")); + o.default = o.disabled; + o.rempty = false; + + // server name; + o = s.taboption("settings", form.Value, "server_name", _("Server Name"), _("Smartdns server name")); + o.default = "smartdns"; + o.datatype = "hostname"; + o.rempty = false; + + // Port; + o = s.taboption("settings", form.Value, "port", _("Local Port"), _("Smartdns local server port")); + o.placeholder = 6053; + o.default = 6053; + o.datatype = "port"; + o.rempty = false; + + // Enable TCP server; + o = s.taboption("settings", form.Flag, "tcp_server", _("TCP Server"), _("Enable TCP DNS Server")); + o.rmempty = false; + o.default = o.enabled; + + // Support IPV6; + o = s.taboption("settings", form.Flag, "ipv6_server", _("IPV6 Server"), _("Enable IPV6 DNS Server")); + o.rmempty = false; + o.default = o.enabled; + + // Support DualStack ip selection; + o = s.taboption("settings", form.Flag, "dualstack_ip_selection", _("Dual-stack IP Selection"), + _("Enable IP selection between IPV4 and IPV6")); + o.rmempty = false; + o.default = o.disabled; + + // Domain prefetch load ; + o = s.taboption("settings", form.Flag, "prefetch_domain", _("Domain prefetch"), + _("Enable domain prefetch, accelerate domain response speed.")); + o.rmempty = false; + o.default = o.disabled; + + // Domain Serve expired + o = s.taboption("settings", form.Flag, "serve_expired", _("Serve expired"), + _("Attempts to serve old responses from cache with a TTL of 0 in the response without waiting for the actual resolution to finish.")); + o.rmempty = false; + o.default = o.disabled; + + // Redirect; + o = s.taboption("settings", form.ListValue, "redirect", _("Redirect"), _("SmartDNS redirect mode")); + o.placeholder = "none"; + o.value("none", _("none")); + o.value("dnsmasq-upstream", _("Run as dnsmasq upstream server")); + o.value("redirect", _("Redirect 53 port to SmartDNS")); + o.default = "none"; + o.rempty = false; + + // cache-size; + o = s.taboption("settings", form.Value, "cache_size", _("Cache Size"), _("DNS domain result cache size")); + o.rempty = true; + + // rr-ttl; + o = s.taboption("settings", form.Value, "rr_ttl", _("Domain TTL"), _("TTL for all domain result.")); + o.rempty = true; + + // rr-ttl-min; + o = s.taboption("settings", form.Value, "rr_ttl_min", _("Domain TTL Min"), + _("Minimum TTL for all domain result.")); + o.rempty = true; + o.placeholder = "300"; + o.default = 300; + o.optional = true; + + // second dns server; + // rr-ttl-max; + o = s.taboption("settings", form.Value, "rr_ttl_max", _("Domain TTL Max"), + _("Maximum TTL for all domain result.")); + o.rempty = true; + + // Eanble; + o = s.taboption("seconddns", form.Flag, "seconddns_enabled", _("Enable"), + _("Enable or disable second DNS server.")); + o.default = o.disabled; + o.rempty = false; + + // Port; + o = s.taboption("seconddns", form.Value, "seconddns_port", _("Local Port"), _("Smartdns local server port")); + o.placeholder = 6553; + o.default = 6553; + o.datatype = "port"; + o.rempty = false; + + // Enable TCP server; + o = s.taboption("seconddns", form.Flag, "seconddns_tcp_server", _("TCP Server"), _("Enable TCP DNS Server")); + o.rmempty = false; + o.default = o.enabled; + + // dns server group; + o = s.taboption("seconddns", form.Value, "seconddns_server_group", _("Server Group"), + _("Query DNS through specific dns server group, such as office, home.")); + o.rmempty = true; + o.placeholder = "default"; + o.datatype = "hostname"; + o.rempty = true; + + o = s.taboption("seconddns", form.Flag, "seconddns_no_speed_check", _("Skip Speed Check"), + _("Do not check speed.")); + o.rmempty = false; + o.default = o.disabled; + + // skip address rules; + o = s.taboption("seconddns", form.Flag, "seconddns_no_rule_addr", _("Skip Address Rules"), + _("Skip address rules.")); + o.rmempty = false; + o.default = o.disabled; + + // skip name server rules; + o = s.taboption("seconddns", form.Flag, "seconddns_no_rule_nameserver", _("Skip Nameserver Rule"), + _("Skip nameserver rules.")); + o.rmempty = false; + o.default = o.disabled; + + // skip ipset rules; + o = s.taboption("seconddns", form.Flag, "seconddns_no_rule_ipset", _("Skip Ipset Rule"), + _("Skip ipset rules.")); + o.rmempty = false; + o.default = o.disabled; + + // skip soa address rule; + o = s.taboption("seconddns", form.Flag, "seconddns_no_rule_soa", _("Skip SOA Address Rule"), + _("Skip SOA address rules.")); + o.rmempty = false; + o.default = o.disabled; + + o = s.taboption("seconddns", form.Flag, "seconddns_no_dualstack_selection", _("Skip Dualstack Selection"), + _("Skip Dualstack Selection.")); + o.rmempty = false; + o.default = o.disabled; + + // skip cache; + o = s.taboption("seconddns", form.Flag, "seconddns_no_cache", _("Skip Cache"), _("Skip Cache.")); + o.rmempty = false; + o.default = o.disabled; + + // Force AAAA SOA + o = s.taboption("seconddns", form.Flag, "force_aaaa_soa", _("Force AAAA SOA"), _("Force AAAA SOA.")); + o.rmempty = false; + o.default = o.disabled; + + // custom settings; + o = s.taboption("custom", form.TextValue, "custom_conf", + "", _("smartdns custom settings")); + + o.rows = 20; + o.cfgvalue = function (section_id) { + return fs.trimmed('/etc/smartdns/custom.conf'); + }; + o.write = function (section_id, formvalue) { + return fs.write('/etc/smartdns/custom.conf', formvalue.trim().replace(/\r\n/g, '\n') + '\n'); + }; + + o = s.taboption("custom", form.Flag, "coredump", _("Generate Coredump"), + _("Generate Coredump file when smartdns crash, coredump file is located at /tmp/smartdns.xxx.core.")); + o.rmempty = false; + o.default = o.disabled; + // Upstream servers; + s = m.section(form.GridSection, "server", _("Upstream Servers"), + _("Upstream Servers, support UDP, TCP protocol. Please configure multiple DNS servers, " + + "including multiple foreign DNS servers.")); + s.anonymous = true; + s.addremove = true; + + s.tab('general', _('General Settings')); + s.tab('advanced', _('Advanced Settings')); + + // enable flag; + o = s.taboption("general", form.Flag, "enabled", _("Enable"), _("Enable")); + o.rmempty = false; + o.default = o.enabled; + o.editable = true; + + // name; + o = s.taboption("general", form.Value, "name", _("DNS Server Name"), _("DNS Server Name")); + + // IP address; + o = s.taboption("general", form.Value, "ip", _("ip"), _("DNS Server ip")); + o.datatype = "or(ipaddr, string)"; + o.rmempty = false; + + // port; + o = s.taboption("general", form.Value, "port", _("port"), _("DNS Server port")); + o.placeholder = "default"; + o.datatype = "port"; + o.rempty = true; + o.depends("type", "udp"); + o.depends("type", "tcp"); + o.depends("type", "tls"); + + // type; + o = s.taboption("general", form.ListValue, "type", _("type"), _("DNS Server type")); + o.placeholder = "udp"; + o.value("udp", _("udp")); + o.value("tcp", _("tcp")); + o.value("tls", _("tls")); + o.value("https", _("https")); + o.default = "udp"; + o.rempty = false; + + // Advanced Options + // server group + o = s.taboption("advanced", form.Value, "server_group", _("Server Group"), _("DNS Server group belongs to, " + + "used with nameserver, such as office, home.")) + o.rmempty = true + o.placeholder = "default" + o.datatype = "hostname" + o.rempty = true + o.modalonly = true; + + // blacklist_ip + o = s.taboption("advanced", form.Flag, "blacklist_ip", _("IP Blacklist Filtering"), + _("Filtering IP with blacklist")) + o.rmempty = false + o.default = o.disabled + o.modalonly = true; + + // TLS host verify + o = s.taboption("advanced", form.Value, "tls_host_verify", _("TLS Hostname Verify"), + _("Set TLS hostname to verify.")) + o.default = "" + o.datatype = "string" + o.rempty = true + o.modalonly = true; + o.depends("type", "tls") + o.depends("type", "https") + + // certificate verify + o = s.taboption("advanced", form.Flag, "no_check_certificate", _("No check certificate"), + _("Do not check certificate.")) + o.rmempty = false + o.default = o.disabled + o.modalonly = true; + o.depends("type", "tls") + o.depends("type", "https") + + // SNI host name + o = s.taboption("advanced", form.Value, "host_name", _("TLS SNI name"), + _("Sets the server name indication for query.")) + o.default = "" + o.datatype = "hostname" + o.rempty = true + o.modalonly = true; + o.depends("type", "tls") + o.depends("type", "https") + + // http host + o = s.taboption("advanced", form.Value, "http_host", _("HTTP Host"), + _("Set the HTTP host used for the query. Use this parameter when the host of the URL address is an IP address.")) + o.default = "" + o.datatype = "hostname" + o.rempty = true + o.modalonly = true; + o.depends("type", "https") + + // SPKI pin + o = s.taboption("advanced", form.Value, "spki_pin", _("TLS SPKI Pinning"), + _("Used to verify the validity of the TLS server, The value is Base64 encoded SPKI fingerprint, " + + "leaving blank to indicate that the validity of TLS is not verified.")) + o.default = "" + o.datatype = "string" + o.rempty = true + o.modalonly = true; + o.depends("type", "tls") + o.depends("type", "https") + + // other args + o = s.taboption("advanced", form.Value, "addition_arg", _("Additional Server Args"), + _("Additional Args for upstream dns servers")) + o.default = "" + o.rempty = true + o.modalonly = true; + + // Doman addresss; + s = m.section(form.TypedSection, "smartdns", _("Advanced Settings"), _("Advanced Settings")); + s.anonymous = true; + + s.tab("domain-address", _("Domain Address"), _("Set Specific domain ip address.")); + s.tab("blackip-list", _("IP Blacklist"), _("Set Specific ip blacklist.")); + + o = s.taboption("domain-address", form.TextValue, "address_conf", + "", + _("Specify an IP address to return for any host in the given domains, Queries in the domains are never " + + "forwarded and always replied to with the specified IP address which may be IPv4 or IPv6.")); + o.rows = 20; + o.cfgvalue = function (section_id) { + return fs.trimmed('/etc/smartdns/address.conf'); + }; + o.write = function (section_id, formvalue) { + return fs.write('/etc/smartdns/address.conf', formvalue.trim().replace(/\r\n/g, '\n') + '\n'); + }; + + // IP Blacklist; + // blacklist; + o = s.taboption("blackip-list", form.TextValue, "blackip_ip_conf", + "", _("Configure IP blacklists that will be filtered from the results of specific DNS server.")); + o.rows = 20; + o.cfgvalue = function (section_id) { + return fs.trimmed('/etc/smartdns/blacklist-ip.conf'); + }; + o.write = function (section_id, formvalue) { + return fs.write('/etc/smartdns/blacklist-ip.conf', formvalue.trim().replace(/\r\n/g, '\n') + '\n'); + }; + + // Doman addresss; + s = m.section(form.TypedSection, "smartdns", _("Technical Support"), + _("If you like this software, please buy me a cup of coffee.")); + s.anonymous = true; + + o = s.option(form.Button, "web"); + o.title = _("SmartDNS official website"); + o.inputtitle = _("open website"); + o.inputstyle = "apply"; + o.onclick = function () { + window.open("https://pymumu.github.io/smartdns", '_blank'); + }; + + o = s.option(form.Button, "Donate"); + o.title = _("Donate to smartdns"); + o.inputtitle = _("Donate"); + o.inputstyle = "apply"; + o.onclick = function () { + window.open("https://pymumu.github.io/smartdns/#donate", '_blank'); + }; + + return m.render(); + } +}); diff --git a/release/src/router/smartdns/package/luci/make.sh b/release/src/router/smartdns/package/luci/make.sh index e5b404a7bd..ed3ff201a4 100644 --- a/release/src/router/smartdns/package/luci/make.sh +++ b/release/src/router/smartdns/package/luci/make.sh @@ -52,14 +52,16 @@ build() cp $CURR_DIR/* $ROOT/ -af cd $ROOT/ build_tool - mkdir $ROOT/root/usr/lib/lua/ -p - cp $ROOT/files/luci $ROOT/root/usr/lib/lua/ -af + mkdir $ROOT/root/usr/lib/lua/luci -p + mkdir $ROOT/root/usr/share/rpcd/acl.d/ -p + cp $ROOT/files/luci/i18n $ROOT/root/usr/lib/lua/luci/ -avf + #Generate Language $PO2LMO $ROOT/files/luci/i18n/smartdns.zh-cn.po $ROOT/root/usr/lib/lua/luci/i18n/smartdns.zh-cn.lmo rm $ROOT/root/usr/lib/lua/luci/i18n/smartdns.zh-cn.po - cp $ROOT/files/etc $ROOT/root/ -af + cp $ROOT/files/root/* $ROOT/root/ -avf INST_SIZE="`du -sb $ROOT/root/ | awk '{print $1}'`" sed -i "s/^Architecture.*/Architecture: all/g" $ROOT/control/control @@ -75,7 +77,7 @@ build() cd $ROOT tar zcf $ROOT/data.tar.gz -C root . - tar zcf $OUTPUTDIR/luci-app-smartdns.$VER.$FILEARCH.ipk control.tar.gz data.tar.gz debian-binary + tar zcf $OUTPUTDIR/luci-app-smartdns.$VER.$FILEARCH.ipk ./control.tar.gz ./data.tar.gz ./debian-binary rm -fr $ROOT/ } diff --git a/release/src/router/smartdns/package/openwrt/Makefile b/release/src/router/smartdns/package/openwrt/Makefile index ac1d5bd1a4..60b1681680 100644 --- a/release/src/router/smartdns/package/openwrt/Makefile +++ b/release/src/router/smartdns/package/openwrt/Makefile @@ -1,58 +1,45 @@ # -# Copyright (C) 2018-2020 Ruilin Peng (Nick) . +# Copyright (c) 2018-2019 Nick Peng (pymumu@gmail.com) +# This is free software, licensed under the GNU General Public License v3. # -# smartdns is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# smartdns is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program. If not, see . + include $(TOPDIR)/rules.mk PKG_NAME:=smartdns +PKG_VERSION:=1.2019.28 +PKG_RELEASE:=1 + +PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.xz +PKG_SOURCE_SUBDIR:=$(PKG_NAME)-$(PKG_VERSION) PKG_SOURCE_PROTO:=git -PKG_SOURCE_URL:=https://github.com/pymumu/smartdns.git +PKG_SOURCE_URL:=https://www.github.com/pymumu/smartdns.git +PKG_SOURCE_VERSION:=982002e836e486fb4e360bc10e84e7e7197caf46 +PKG_MIRROR_HASH:=ae889b521ecf114660ce5597af5c361f5970a7dcb75dadf61b938ba3d2baba54 -PKG_REV:=d51f5e6eeba7bfde1b108fe32d540bd429550573 -PKG_VERSION:=1.2019.11.02-1102 -PKG_RELEASE:=1 -PKG_LICENSE:=GPL-3.0 +PKG_MAINTAINER:=Nick Peng +PKG_LICENSE:=GPL-3.0-or-later +PKG_LICENSE_FILES:=LICENSE -PKG_SOURCE_VERSION:=$(PKG_REV) -PKG_SOURCE_SUBDIR:=$(PKG_NAME)-$(PKG_VERSION) -PKG_SOURCE:=$(PKG_SOURCE_SUBDIR).tar.gz -PKG_BUILD_DIR:=$(BUILD_DIR)/$(PKG_SOURCE_SUBDIR) +PKG_BUILD_PARALLEL:=1 include $(INCLUDE_DIR)/package.mk -MAKE_ARGS := CFLAGS="$(TARGET_CFLAGS)" CC=$(TARGET_CC) +MAKE_VARS += VER=$(PKG_VERSION) +MAKE_PATH:=src define Package/smartdns SECTION:=net CATEGORY:=Network TITLE:=smartdns server - URL:=http://github.com/pymumu/smartdns/ - MAINTAINER:=Nick Peng - DEPENDS:=+libopenssl + DEPENDS:=+libpthread +libopenssl + URL:=https://www.github.com/pymumu/smartdns/ endef define Package/smartdns/description -SmartDNS is a local DNS server. SmartDNS accepts DNS query requests from local clients, obtains DNS query results from multiple upstream DNS servers, and returns the fastest access results to clients. -endef - -define Build/Configure - mkdir -p $(PKG_INSTALL_DIR) -endef - -define Build/Compile - $(MAKE) -C $(PKG_BUILD_DIR)/src $(MAKE_ARGS) all +SmartDNS is a local DNS server which accepts DNS query requests from local network clients, +get DNS query results from multiple upstream DNS servers concurrently, and returns the fastest IP to clients. +Unlike dnsmasq's all-servers, smartdns returns the fastest IP. endef define Package/smartdns/conffiles diff --git a/release/src/router/smartdns/package/openwrt/address.conf b/release/src/router/smartdns/package/openwrt/address.conf index 592b3caf91..0f41344463 100644 --- a/release/src/router/smartdns/package/openwrt/address.conf +++ b/release/src/router/smartdns/package/openwrt/address.conf @@ -1,16 +1,16 @@ -# Add domains which you want to force to an IP address here. -# The example below send any host in example.com to a local webserver. -# address /domain/[ip|-|-4|-6|#|#4|#6] -# address /www.example.com/1.2.3.4, return ip 1.2.3.4 to client -# address /www.example.com/-, ignore address, query from upstream, suffix 4, for ipv4, 6 for ipv6, none for all -# address /www.example.com/#, return SOA to client, suffix 4, for ipv4, 6 for ipv6, none for all - -# specific ipset to domain -# ipset /domain/[ipset|-] -# ipset /www.example.com/block, set ipset with ipset name of block -# ipset /www.example.com/-, ignore this domain - -# specific nameserver to domain -# nameserver /domain/[group|-] -# nameserver /www.example.com/office, Set the domain name to use the appropriate server group. -# nameserver /www.example.com/-, ignore this domain +# Add domains which you want to force to an IP address here. +# The example below send any host in example.com to a local webserver. +# address /domain/[ip|-|-4|-6|#|#4|#6] +# address /www.example.com/1.2.3.4, return ip 1.2.3.4 to client +# address /www.example.com/-, ignore address, query from upstream, suffix 4, for ipv4, 6 for ipv6, none for all +# address /www.example.com/#, return SOA to client, suffix 4, for ipv4, 6 for ipv6, none for all + +# specific ipset to domain +# ipset /domain/[ipset|-] +# ipset /www.example.com/block, set ipset with ipset name of block +# ipset /www.example.com/-, ignore this domain + +# specific nameserver to domain +# nameserver /domain/[group|-] +# nameserver /www.example.com/office, Set the domain name to use the appropriate server group. +# nameserver /www.example.com/-, ignore this domain diff --git a/release/src/router/smartdns/package/openwrt/blacklist-ip.conf b/release/src/router/smartdns/package/openwrt/blacklist-ip.conf index ddb0965c38..7d26a7f2d6 100644 --- a/release/src/router/smartdns/package/openwrt/blacklist-ip.conf +++ b/release/src/router/smartdns/package/openwrt/blacklist-ip.conf @@ -1,4 +1,4 @@ -# Add IP blacklist which you want to filtering from some DNS server here. -# The example below filtering ip from the result of DNS server which is configured with -blacklist-ip. -# blacklist-ip [ip/subnet] +# Add IP blacklist which you want to filtering from some DNS server here. +# The example below filtering ip from the result of DNS server which is configured with -blacklist-ip. +# blacklist-ip [ip/subnet] # blacklist-ip 254.0.0.1/16 \ No newline at end of file diff --git a/release/src/router/smartdns/package/openwrt/custom.conf b/release/src/router/smartdns/package/openwrt/custom.conf index 3713dfadf3..0d146302f3 100644 --- a/release/src/router/smartdns/package/openwrt/custom.conf +++ b/release/src/router/smartdns/package/openwrt/custom.conf @@ -1,14 +1,14 @@ -# Add custom settings here. - -# set log level -# log-level [level], level=fatal, error, warn, notice, info, debug -# log-level error - -# log-size k,m,g -# log-size 128k - -# log-file /var/log/smartdns.log -# log-num 2 - -# List of hosts that supply bogus NX domain results +# Add custom settings here. + +# set log level +# log-level [level], level=fatal, error, warn, notice, info, debug +# log-level error + +# log-size k,m,g +# log-size 128k + +# log-file /var/log/smartdns.log +# log-num 2 + +# List of hosts that supply bogus NX domain results # bogus-nxdomain [ip/subnet] \ No newline at end of file diff --git a/release/src/router/smartdns/package/openwrt/files/etc/init.d/smartdns b/release/src/router/smartdns/package/openwrt/files/etc/init.d/smartdns index f4eabc7f30..d04a36af8e 100644 --- a/release/src/router/smartdns/package/openwrt/files/etc/init.d/smartdns +++ b/release/src/router/smartdns/package/openwrt/files/etc/init.d/smartdns @@ -22,7 +22,6 @@ SERVICE_USE_PID=1 SERVICE_WRITE_PID=1 SERVICE_DAEMONIZE=1 SERVICE_PID_FILE="/var/run/smartdns.pid" -BASECONFIGFILE="/etc/smartdns/smartdns.conf" SMARTDNS_CONF_DIR="/etc/smartdns" SMARTDNS_VAR_CONF_DIR="/var/etc/smartdns" SMARTDNS_CONF="$SMARTDNS_VAR_CONF_DIR/smartdns.conf" @@ -37,22 +36,18 @@ set_forward_dnsmasq() { local PORT="$1" addr="127.0.0.1#$PORT" - OLD_SERVER="`uci get dhcp.@dnsmasq[0].server 2>/dev/null`" - echo $OLD_SERVER | grep "^$addr" >/dev/null 2>&1 - if [ $? -eq 0 ]; then + OLD_SERVER="$(uci get dhcp.@dnsmasq[0].server 2>/dev/null)" + if echo "$OLD_SERVER" | grep "^$addr" >/dev/null 2>&1; then return fi uci delete dhcp.@dnsmasq[0].server 2>/dev/null - uci add_list dhcp.@dnsmasq[0].server=$addr + uci add_list dhcp.@dnsmasq[0].server="$addr" for server in $OLD_SERVER; do - if [ "$server" = "$addr" ]; then - continue - fi - uci add_list dhcp.@dnsmasq[0].server=$server + [ "$server" = "$addr" ] && continue + uci add_list dhcp.@dnsmasq[0].server="$server" done - uci delete dhcp.@dnsmasq[0].resolvfile 2>/dev/null uci set dhcp.@dnsmasq[0].noresolv=1 - uci commit dhcp + uci commit dhcp /etc/init.d/dnsmasq restart } @@ -60,18 +55,16 @@ stop_forward_dnsmasq() { local OLD_PORT="$1" addr="127.0.0.1#$OLD_PORT" - OLD_SERVER="`uci get dhcp.@dnsmasq[0].server 2>/dev/null`" - echo $OLD_SERVER | grep "^$addr" >/dev/null 2>&1 - if [ $? -ne 0 ]; then + OLD_SERVER="$(uci get dhcp.@dnsmasq[0].server 2>/dev/null)" + if ! echo "$OLD_SERVER" | grep "^$addr" >/dev/null 2>&1; then return fi - uci del_list dhcp.@dnsmasq[0].server=$addr 2>/dev/null - addrlist="`uci get dhcp.@dnsmasq[0].server 2>/dev/null`" - if [ -z "$addrlist" ] ; then - uci set dhcp.@dnsmasq[0].resolvfile=/tmp/resolv.conf.auto 2>/dev/null + uci del_list dhcp.@dnsmasq[0].server="$addr" 2>/dev/null + addrlist="$(uci get dhcp.@dnsmasq[0].server 2>/dev/null)" + [ -z "$addrlist" ] && { uci delete dhcp.@dnsmasq[0].noresolv 2>/dev/null - fi + } uci commit dhcp /etc/init.d/dnsmasq restart } @@ -81,26 +74,24 @@ set_iptable() local ipv6_server=$1 local tcp_server=$2 - IPS="`ifconfig | grep "inet addr" | grep -v ":127" | grep "Bcast" | awk '{print $2}' | awk -F : '{print $2}'`" + IPS="$(ifconfig | grep "inet addr" | grep -v ":127" | grep "Bcast" | awk '{print $2}' | awk -F : '{print $2}')" for IP in $IPS do - if [ "$tcp_server" == "1" ]; then - iptables -t nat -A PREROUTING -p tcp -d $IP --dport 53 -j REDIRECT --to-ports $SMARTDNS_PORT >/dev/null 2>&1 + if [ "$tcp_server" = "1" ]; then + iptables -t nat -A PREROUTING -p tcp -d "$IP" --dport 53 -j REDIRECT --to-ports "$SMARTDNS_PORT" >/dev/null 2>&1 fi - iptables -t nat -A PREROUTING -p udp -d $IP --dport 53 -j REDIRECT --to-ports $SMARTDNS_PORT >/dev/null 2>&1 + iptables -t nat -A PREROUTING -p udp -d "$IP" --dport 53 -j REDIRECT --to-ports "$SMARTDNS_PORT" >/dev/null 2>&1 done - if [ "$ipv6_server" == 0 ]; then - return - fi + [ "$ipv6_server" = 0 ] && return - IPS="`ifconfig | grep "inet6 addr" | grep -v " fe80::" | grep -v " ::1" | grep "Global" | awk '{print $3}'`" + IPS="$(ifconfig | grep "inet6 addr" | grep -v " fe80::" | grep -v " ::1" | grep "Global" | awk '{print $3}')" for IP in $IPS do - if [ "$tcp_server" == "1" ]; then - ip6tables -t nat -A PREROUTING -p tcp -d $IP --dport 53 -j REDIRECT --to-ports $SMARTDNS_PORT >/dev/null 2>&1 + if [ "$tcp_server" = "1" ]; then + ip6tables -t nat -A PREROUTING -p tcp -d "$IP" --dport 53 -j REDIRECT --to-ports "$SMARTDNS_PORT" >/dev/null 2>&1 fi - ip6tables -t nat -A PREROUTING -p udp -d $IP --dport 53 -j REDIRECT --to-ports $SMARTDNS_PORT >/dev/null 2>&1 + ip6tables -t nat -A PREROUTING -p udp -d "$IP" --dport 53 -j REDIRECT --to-ports "$SMARTDNS_PORT" >/dev/null 2>&1 done } @@ -109,24 +100,22 @@ clear_iptable() { local OLD_PORT="$1" local ipv6_server=$2 - IPS="`ifconfig | grep "inet addr" | grep -v ":127" | grep "Bcast" | awk '{print $2}' | awk -F : '{print $2}'`" + IPS="$(ifconfig | grep "inet addr" | grep -v ":127" | grep "Bcast" | awk '{print $2}' | awk -F : '{print $2}')" for IP in $IPS do - iptables -t nat -D PREROUTING -p udp -d $IP --dport 53 -j REDIRECT --to-ports $OLD_PORT >/dev/null 2>&1 - iptables -t nat -D PREROUTING -p tcp -d $IP --dport 53 -j REDIRECT --to-ports $OLD_PORT >/dev/null 2>&1 + iptables -t nat -D PREROUTING -p udp -d "$IP" --dport 53 -j REDIRECT --to-ports "$OLD_PORT" >/dev/null 2>&1 + iptables -t nat -D PREROUTING -p tcp -d "$IP" --dport 53 -j REDIRECT --to-ports "$OLD_PORT" >/dev/null 2>&1 done - if [ "$ipv6_server" == 0 ]; then - return - fi + [ "$ipv6_server" = 0 ] && return - IPS="`ifconfig | grep "inet6 addr" | grep -v " fe80::" | grep -v " ::1" | grep "Global" | awk '{print $3}'`" + IPS="$(ifconfig | grep "inet6 addr" | grep -v " fe80::" | grep -v " ::1" | grep "Global" | awk '{print $3}')" for IP in $IPS do - ip6tables -t nat -D PREROUTING -p udp -d $IP --dport 53 -j REDIRECT --to-ports $OLD_PORT >/dev/null 2>&1 - ip6tables -t nat -D PREROUTING -p tcp -d $IP --dport 53 -j REDIRECT --to-ports $OLD_PORT >/dev/null 2>&1 + ip6tables -t nat -D PREROUTING -p udp -d "$IP" --dport 53 -j REDIRECT --to-ports "$OLD_PORT" >/dev/null 2>&1 + ip6tables -t nat -D PREROUTING -p tcp -d "$IP" --dport 53 -j REDIRECT --to-ports "$OLD_PORT" >/dev/null 2>&1 done - + } service_triggers() { @@ -134,7 +123,6 @@ service_triggers() { procd_add_reload_trigger smartdns } - conf_append() { echo "$1 $2" >> $SMARTDNS_CONF_TMP @@ -144,23 +132,16 @@ get_tz() { SET_TZ="" - if [ -e "/etc/localtime" ]; then - return - fi - + [ -e "/etc/localtime" ] && return + for tzfile in /etc/TZ /var/etc/TZ do - if [ ! -e "$tzfile" ]; then - continue - fi - - tz="`cat $tzfile 2>/dev/null`" + [ -e "$tzfile" ] || continue + tz="$(cat $tzfile 2>/dev/null)" done - - if [ -z "$tz" ]; then - return - fi - + + [ -z "$tz" ] && return + SET_TZ=$tz } @@ -170,22 +151,21 @@ load_server() local ADDITIONAL_ARGS="" local DNS_ADDRESS="" - config_get_bool "enabled" "$section" "enabled" "1" - config_get "port" "$section" "port" "" - config_get "type" "$section" "type" "udp" - config_get "ip" "$section" "ip" "" - config_get "tls_host_verify" "$section" "tls_host_verify" "" - config_get "host_name" "$section" "host_name" "" - config_get "http_host" "$section" "http_host" "" - config_get "server_group" "$section" "server_group" "" - config_get "blacklist_ip" "$section" "blacklist_ip" "0" - config_get "check_edns" "$section" "check_edns" "0" - config_get "spki_pin" "$section" "spki_pin" "" - config_get "addition_arg" "$section" "addition_arg" "" - - if [ "$enabled" = "0" ]; then - return - fi + config_get_bool enabled "$section" "enabled" "1" + config_get port "$section" "port" "" + config_get type "$section" "type" "udp" + config_get ip "$section" "ip" "" + config_get tls_host_verify "$section" "tls_host_verify" "" + config_get no_check_certificate "$section" "no_check_certificate" "" + config_get host_name "$section" "host_name" "" + config_get http_host "$section" "http_host" "" + config_get server_group "$section" "server_group" "" + config_get blacklist_ip "$section" "blacklist_ip" "0" + config_get check_edns "$section" "check_edns" "0" + config_get spki_pin "$section" "spki_pin" "" + config_get addition_arg "$section" "addition_arg" "" + + [ "$enabled" = "0" ] && return if [ -z "$ip" ] || [ -z "$type" ]; then return @@ -200,107 +180,71 @@ load_server() SERVER="server-https" fi - if [ ! -z "`echo $ip | grep ":" | grep -v "https://"`" ]; then - if [ -z "`echo $ip | grep "\["`" ]; then + if echo "$ip" | grep ":" | grep -q -v "https://" >/dev/null 2>&1; then + if ! echo "$ip" | grep -q "\\[" >/dev/null 2>&1; then ip="[$ip]" fi fi - if [ ! -z "$tls_host_verify" ]; then - ADDITIONAL_ARGS="$ADDITIONAL_ARGS -tls-host-verify $tls_host_verify" - fi - - if [ ! -z "$host_name" ]; then - ADDITIONAL_ARGS="$ADDITIONAL_ARGS -host-name $host_name" - fi - - if [ ! -z "$http_host" ]; then - ADDITIONAL_ARGS="$ADDITIONAL_ARGS -http-host $http_host" - fi - - if [ ! -z "$server_group" ]; then - ADDITIONAL_ARGS="$ADDITIONAL_ARGS -group $server_group" - fi - - if [ "$blacklist_ip" != "0" ]; then - ADDITIONAL_ARGS="$ADDITIONAL_ARGS -blacklist-ip" - fi + [ -z "$tls_host_verify" ] || ADDITIONAL_ARGS="$ADDITIONAL_ARGS -tls-host-verify $tls_host_verify" + [ -z "$no_check_certificate" ] || ADDITIONAL_ARGS="$ADDITIONAL_ARGS -no-check-certificate" + [ -z "$host_name" ] || ADDITIONAL_ARGS="$ADDITIONAL_ARGS -host-name $host_name" + [ -z "$http_host" ] || ADDITIONAL_ARGS="$ADDITIONAL_ARGS -http-host $http_host" + [ -z "$server_group" ] || ADDITIONAL_ARGS="$ADDITIONAL_ARGS -group $server_group" + [ "$blacklist_ip" = "0" ] || ADDITIONAL_ARGS="$ADDITIONAL_ARGS -blacklist-ip" + [ "$check_edns" = "0" ] || ADDITIONAL_ARGS="$ADDITIONAL_ARGS -check-edns" + [ -z "$spki_pin" ] || ADDITIONAL_ARGS="$ADDITIONAL_ARGS -spki-pin $spki_pin" - if [ "$check_edns" != "0" ]; then - ADDITIONAL_ARGS="$ADDITIONAL_ARGS -check-edns" - fi - - if [ ! -z "$spki_pin" ]; then - ADDITIONAL_ARGS="$ADDITIONAL_ARGS -spki-pin $spki_pin" - fi - - if [ ! -z "$port" ]; then - DNS_ADDRESS="$ip:$port" - else + if [ -z "$port" ]; then DNS_ADDRESS="$ip" + else + DNS_ADDRESS="$ip:$port" fi - if [ "$type" = "https" ]; then - DNS_ADDRESS="$ip" - fi + [ "$type" = "https" ] && DNS_ADDRESS="$ip" conf_append "$SERVER" "$DNS_ADDRESS $ADDITIONAL_ARGS $addition_arg" } -load_second_server() +load_second_server() { local section="$1" local ARGS="" local ADDR="" - config_get_bool "seconddns_enabled" "$section" "seconddns_enabled" "0" - if [ "$seconddns_enabled" = "0" ]; then - return - fi + config_get_bool seconddns_enabled "$section" "seconddns_enabled" "0" + [ "$seconddns_enabled" = "0" ] && return - config_get "seconddns_port" "$section" "seconddns_port" "7053" + config_get seconddns_port "$section" "seconddns_port" "6553" - config_get_bool "seconddns_no_speed_check" "$section" "seconddns_no_speed_check" "0" - if [ "$seconddns_no_speed_check" = "1" ]; then - ARGS="$ARGS -no-speed-check" - fi + config_get_bool seconddns_no_speed_check "$section" "seconddns_no_speed_check" "0" + [ "$seconddns_no_speed_check" = "1" ] && ARGS="$ARGS -no-speed-check" - config_get "seconddns_server_group" "$section" "seconddns_server_group" "" - if [ ! -z "$seconddns_server_group" ]; then - ARGS="$ARGS -group $seconddns_server_group" - fi + config_get seconddns_server_group "$section" "seconddns_server_group" "" + [ -z "$seconddns_server_group" ] || ARGS="$ARGS -group $seconddns_server_group" - config_get_bool "seconddns_no_rule_addr" "$section" "seconddns_no_rule_addr" "0" - if [ "$seconddns_no_rule_addr" = "1" ]; then - ARGS="$ARGS -no-rule-addr" - fi + config_get_bool seconddns_no_rule_addr "$section" "seconddns_no_rule_addr" "0" + [ "$seconddns_no_rule_addr" = "1" ] && ARGS="$ARGS -no-rule-addr" - config_get_bool "seconddns_no_rule_nameserver" "$section" "seconddns_no_rule_nameserver" "0" - if [ "$seconddns_no_rule_nameserver" = "1" ]; then - ARGS="$ARGS -no-rule-nameserver" - fi + config_get_bool seconddns_no_rule_nameserver "$section" "seconddns_no_rule_nameserver" "0" + [ "$seconddns_no_rule_nameserver" = "1" ] && ARGS="$ARGS -no-rule-nameserver" - config_get_bool "seconddns_no_rule_ipset" "$section" "seconddns_no_rule_ipset" "0" - if [ "$seconddns_no_rule_ipset" = "1" ]; then - ARGS="$ARGS -no-rule-ipset" - fi + config_get_bool seconddns_no_rule_ipset "$section" "seconddns_no_rule_ipset" "0" + [ "$seconddns_no_rule_ipset" = "1" ] && ARGS="$ARGS -no-rule-ipset" - config_get_bool "seconddns_no_rule_soa" "$section" "seconddns_no_rule_soa" "0" - if [ "$seconddns_no_rule_soa" = "1" ]; then - ARGS="$ARGS -no-rule-soa" - fi + config_get_bool seconddns_no_rule_soa "$section" "seconddns_no_rule_soa" "0" + [ "$seconddns_no_rule_soa" = "1" ] && ARGS="$ARGS -no-rule-soa" - config_get_bool "seconddns_no_dualstack_selection" "$section" "seconddns_no_dualstack_selection" "0" - if [ "$seconddns_no_dualstack_selection" = "1" ]; then - ARGS="$ARGS -no-dualstack-selection" - fi + config_get_bool seconddns_no_dualstack_selection "$section" "seconddns_no_dualstack_selection" "0" + [ "$seconddns_no_dualstack_selection" = "1" ] && ARGS="$ARGS -no-dualstack-selection" - config_get_bool "seconddns_no_cache" "$section" "seconddns_no_cache" "0" - if [ "$seconddns_no_cache" = "1" ]; then - ARGS="$ARGS -no-cache" - fi + config_get_bool seconddns_no_cache "$section" "seconddns_no_cache" "0" + [ "$seconddns_no_cache" = "1" ] && ARGS="$ARGS -no-cache" + + config_get_bool force_aaaa_soa "$section" "force_aaaa_soa" "0" + [ "$force_aaaa_soa" = "1" ] && ARGS="$ARGS -force-aaaa-soa" - config_get "ipv6_server" "$section" "ipv6_server" "1" + config_get ipv6_server "$section" "ipv6_server" "1" if [ "$ipv6_server" = "1" ]; then ADDR="[::]" else @@ -309,12 +253,10 @@ load_second_server() conf_append "bind" "$ADDR:$seconddns_port $ARGS" config_get_bool "seconddns_tcp_server" "$section" "seconddns_tcp_server" "1" - if [ "$seconddns_tcp_server" = "1" ]; then - conf_append "bind-tcp" "$ADDR:$seconddns_port $ARGS" - fi + [ "$seconddns_tcp_server" = "1" ] && conf_append "bind-tcp" "$ADDR:$seconddns_port $ARGS" } -load_service() +load_service() { local section="$1" args="" @@ -322,102 +264,77 @@ load_service() mkdir -p $SMARTDNS_VAR_CONF_DIR rm -f $SMARTDNS_CONF_TMP - config_get_bool "enabled" "$section" "enabled" '0' + config_get_bool enabled "$section" "enabled" '0' - config_get "server_name" "$section" "server_name" "" - if [ ! -z "$server_name" ]; then - conf_append "server-name" "$server_name" - fi + config_get server_name "$section" "server_name" "" + [ -z "$server_name" ] || conf_append "server-name" "$server_name" - config_get "coredump" "$section" "coredump" "0" - if [ "$coredump" = "1" ]; then - COREDUMP="1" - fi + config_get coredump "$section" "coredump" "0" + [ "$coredump" = "1" ] && COREDUMP="1" - config_get "port" "$section" "port" "6053" - config_get "ipv6_server" "$section" "ipv6_server" "1" - config_get "tcp_server" "$section" "tcp_server" "1" + config_get port "$section" "port" "6053" + config_get ipv6_server "$section" "ipv6_server" "1" + config_get tcp_server "$section" "tcp_server" "1" if [ "$ipv6_server" = "1" ]; then conf_append "bind" "[::]:$port" else conf_append "bind" ":$port" fi - if [ "$tcp_server" = "1" ]; then + [ "$tcp_server" = "1" ] && { if [ "$ipv6_server" = "1" ]; then conf_append "bind-tcp" "[::]:$port" else conf_append "bind-tcp" ":$port" fi - fi - config_get "dualstack_ip_selection" "$section" "dualstack_ip_selection" "0" - if [ "$dualstack_ip_selection" = "1" ]; then - conf_append "dualstack-ip-selection" "yes" - fi + } + config_get dualstack_ip_selection "$section" "dualstack_ip_selection" "0" + [ "$dualstack_ip_selection" = "1" ] && conf_append "dualstack-ip-selection" "yes" - config_get "prefetch_domain" "$section" "prefetch_domain" "0" - if [ "$prefetch_domain" = "1" ]; then - conf_append "prefetch-domain" "yes" - fi + config_get prefetch_domain "$section" "prefetch_domain" "0" + [ "$prefetch_domain" = "1" ] && conf_append "prefetch-domain" "yes" + + config_get serve_expired "$section" "serve_expired" "0" + [ "$serve_expired" = "1" ] && conf_append "serve-expired" "yes" SMARTDNS_PORT="$port" - config_get "cache_size" "$section" "cache_size" "" - if [ ! -z "$cache_size" ]; then - conf_append "cache-size" "$cache_size" - fi + config_get cache_size "$section" "cache_size" "" + [ -z "$cache_size" ] || conf_append "cache-size" "$cache_size" - config_get "rr_ttl" "$section" "rr_ttl" "" - if [ ! -z "$rr_ttl" ]; then - conf_append "rr-ttl" "$rr_ttl" - fi + config_get rr_ttl "$section" "rr_ttl" "" + [ -z "$rr_ttl" ] || conf_append "rr-ttl" "$rr_ttl" - config_get "rr_ttl_min" "$section" "rr_ttl_min" "" - if [ ! -z "$rr_ttl_min" ]; then - conf_append "rr-ttl-min" "$rr_ttl_min" - fi + config_get rr_ttl_min "$section" "rr_ttl_min" "" + [ -z "$rr_ttl_min" ] || conf_append "rr-ttl-min" "$rr_ttl_min" - config_get "rr_ttl_max" "$section" "rr_ttl_max" "" - if [ ! -z "$rr_ttl_max" ]; then - conf_append "rr-ttl-max" "$rr_ttl_max" - fi + config_get rr_ttl_max "$section" "rr_ttl_max" "" + [ -z "$rr_ttl_max" ] || conf_append "rr-ttl-max" "$rr_ttl_max" - config_get "log_size" "$section" "log_size" "64K" - if [ ! -z "$log_size" ]; then - conf_append "log-size" "$log_size" - fi + config_get log_size "$section" "log_size" "64K" + [ -z "$log_size" ] || conf_append "log-size" "$log_size" - config_get "log_num" "$section" "log_num" "1" - if [ ! -z "$log_num" ]; then - conf_append "log-num" "$log_num" - fi + config_get log_num "$section" "log_num" "1" + [ -z "$log_num" ] || conf_append "log-num" "$log_num" - config_get "log_level" "$section" "log_level" "error" - if [ ! -z "$log_level" ]; then - conf_append "log-level" "$log_level" - fi + config_get log_level "$section" "log_level" "error" + [ -z "$log_level" ]|| conf_append "log-level" "$log_level" - config_get "log_file" "$section" "log_file" "" - if [ ! -z "$log_file" ]; then - conf_append "log-file" "$log_file" - fi + config_get log_file "$section" "log_file" "" + [ -z "$log_file" ] || conf_append "log-file" "$log_file" - config_get "redirect" "$section" "redirect" "none" - config_get "old_redirect" "$section" "old_redirect" "none" - config_get "old_port" "$section" "old_port" "0" - config_get "old_enabled" "$section" "old_enabled" "0" + config_get redirect "$section" "redirect" "none" + config_get old_redirect "$section" "old_redirect" "none" + config_get old_port "$section" "old_port" "0" + config_get old_enabled "$section" "old_enabled" "0" if [ "$old_redirect" != "$redirect" ] || [ "$old_port" != "$SMARTDNS_PORT" ] || [ "$old_enabled" = "1" -a "$enabled" = "0" ]; then - if [ "$old_redirect" != "none" ]; then - if [ "$old_port" != "0" ]; then - clear_iptable "$old_port" "$ipv6_server" - fi - if [ "$old_redirect" == "dnsmasq-upstream" ]; then - stop_forward_dnsmasq "$old_port" - fi - fi + [ "$old_redirect" = "none" ] || { + [ "$old_port" = "0" ] || clear_iptable "$old_port" "$ipv6_server" + [ "$old_redirect" = "dnsmasq-upstream" ] && stop_forward_dnsmasq "$old_port" + } fi - + uci delete smartdns.@smartdns[0].old_redirect 2>/dev/null uci delete smartdns.@smartdns[0].old_port 2>/dev/null uci delete smartdns.@smartdns[0].old_enabled 2>/dev/null @@ -438,31 +355,29 @@ load_service() config_foreach load_server "server" - echo "conf-file $ADDRESS_CONF" >> $SMARTDNS_CONF_TMP - echo "conf-file $BLACKLIST_IP_CONF" >> $SMARTDNS_CONF_TMP - echo "conf-file $CUSTOM_CONF" >> $SMARTDNS_CONF_TMP + { + echo "conf-file $ADDRESS_CONF" + echo "conf-file $BLACKLIST_IP_CONF" + echo "conf-file $CUSTOM_CONF" + } >> $SMARTDNS_CONF_TMP mv $SMARTDNS_CONF_TMP $SMARTDNS_CONF procd_open_instance "smartdns" - if [ "$COREDUMP" = "1" ]; then + [ "$COREDUMP" = "1" ] && { args="$args -S" procd_set_param limits core="unlimited" - fi - + } + get_tz - if [ ! -z "$SET_TZ" ]; then - procd_set_param env TZ="$SET_TZ" - fi + [ -z "$SET_TZ" ] || procd_set_param env TZ="$SET_TZ" procd_set_param command /usr/sbin/smartdns -f -c $SMARTDNS_CONF $args - if [ "$RESPAWN" = "1" ]; then - procd_set_param respawn ${respawn_threshold:-3600} ${respawn_timeout:-5} ${respawn_retry:-5} - fi + [ "$RESPAWN" = "1" ] && procd_set_param respawn ${respawn_threshold:-3600} ${respawn_timeout:-5} ${respawn_retry:-5} procd_set_param file "$SMARTDNS_CONF" procd_close_instance } -start_service() +start_service() { config_load "smartdns" config_foreach load_service "smartdns" diff --git a/release/src/router/smartdns/package/optware/S50smartdns b/release/src/router/smartdns/package/optware/S50smartdns index 3924a4d12d..393b96289d 100644 --- a/release/src/router/smartdns/package/optware/S50smartdns +++ b/release/src/router/smartdns/package/optware/S50smartdns @@ -43,56 +43,56 @@ set_iptable() redirect_tcp=1; fi - IPS="`ifconfig | grep "inet addr" | grep -v ":127" | grep "Bcast" | awk '{print $2}' | awk -F: '{print $2}'`" + IPS="$(ifconfig | grep "inet addr" | grep -v ":127" | grep "Bcast" | awk '{print $2}' | awk -F: '{print $2}')" for IP in $IPS do if [ $redirect_tcp -eq 1 ]; then - iptables -t nat -A PREROUTING -p tcp -d $IP --dport 53 -j REDIRECT --to-ports $SMARTDNS_PORT > /dev/null 2>&1 + iptables -t nat -A PREROUTING -p tcp -d "$IP" --dport 53 -j REDIRECT --to-ports "$SMARTDNS_PORT" > /dev/null 2>&1 fi - iptables -t nat -A PREROUTING -p udp -d $IP --dport 53 -j REDIRECT --to-ports $SMARTDNS_PORT > /dev/null 2>&1 + iptables -t nat -A PREROUTING -p udp -d "$IP" --dport 53 -j REDIRECT --to-ports "$SMARTDNS_PORT" > /dev/null 2>&1 done } clear_iptable() { - IPS="`ifconfig | grep "inet addr" | grep -v ":127" | grep "Bcast" | awk '{print $2}' | awk -F: '{print $2}'`" + IPS="$(ifconfig | grep "inet addr" | grep -v ":127" | grep "Bcast" | awk '{print $2}' | awk -F: '{print $2}')" for IP in $IPS do - iptables -t nat -D PREROUTING -p tcp -d $IP --dport 53 -j REDIRECT --to-ports $SMARTDNS_PORT > /dev/null 2>&1 - iptables -t nat -D PREROUTING -p udp -d $IP --dport 53 -j REDIRECT --to-ports $SMARTDNS_PORT > /dev/null 2>&1 + iptables -t nat -D PREROUTING -p tcp -d "$IP" --dport 53 -j REDIRECT --to-ports "$SMARTDNS_PORT" > /dev/null 2>&1 + iptables -t nat -D PREROUTING -p udp -d "$IP" --dport 53 -j REDIRECT --to-ports "$SMARTDNS_PORT" > /dev/null 2>&1 done } get_dnsmasq_cmd() { - CMD="`ps | grep -e '[a-zA-Z]\{0,2\} \{1,\}dnsmasq' | grep -v grep 2>/dev/null`" + CMD="$(ps 2>/dev/null | grep -e '[a-zA-Z]\{0,2\} \{1,\}dnsmasq' | grep -v grep 2>/dev/null)" if [ ! -z "$CMD" ]; then return fi - CMD="`ps | grep '/usr/sbin/dnsmasq' | grep -v grep 2>/dev/null`" + CMD="$(ps 2>/dev/null | grep '/usr/sbin/dnsmasq' | grep -v grep 2>/dev/null)" if [ ! -z "$CMD" ]; then return fi - CMD="`ps | grep 'dnsmasq' | grep -v grep 2>/dev/null`" + CMD="$(ps 2>/dev/null | grep 'dnsmasq' | grep -v grep 2>/dev/null)" if [ ! -z "$CMD" ]; then return fi - CMD="`ps ax | grep -e '[a-zA-Z]\{0,2\} \{1,\}dnsmasq' | grep -v grep 2>/dev/null`" + CMD="$(ps ax 2>/dev/null | grep -e '[a-zA-Z]\{0,2\} \{1,\}dnsmasq' | grep -v grep 2>/dev/null)" if [ ! -z "$CMD" ]; then return fi - CMD="`ps ax | grep /usr/sbin/dnsmasq | grep -v grep 2>/dev/null`" + CMD="$(ps ax 2>/dev/null | grep /usr/sbin/dnsmasq | grep -v grep 2>/dev/null)" if [ ! -z "$CMD" ]; then return fi - CMD="`ps ax | grep 'dnsmasq' | grep -v grep 2>/dev/null`" + CMD="$(ps ax 2>/dev/null | grep 'dnsmasq' | grep -v grep 2>/dev/null)" if [ ! -z "$CMD" ]; then return fi @@ -108,15 +108,15 @@ restart_dnsmasq() return 1 fi - PID=`echo "$CMD" | awk '{print $1}'` + PID="$(echo "$CMD" | awk '{print $1}')" if [ ! -d "/proc/$PID" ]; then echo "dnsmasq is not running" return 1 fi - kill -9 $PID + kill -9 "$PID" - DNSMASQ_CMD="`echo $CMD | awk '{for(i=5; i<=NF;i++)printf \$i " "}'`" + DNSMASQ_CMD="$(echo "$CMD" | awk '{for(i=5; i<=NF;i++)printf $i " "}')" $DNSMASQ_CMD } @@ -124,21 +124,20 @@ restart_dnsmasq() get_server_ip() { CONF_FILE=$1 - IPS="`ifconfig | grep "inet addr" | grep -v ":127" | grep "Bcast" | awk '{print $2}' | awk -F: '{print $2}'`" - LOCAL_SERVER_IP="" + IPS="$(ifconfig | grep "inet addr" | grep -v ":127" | grep "Bcast" | awk '{print $2}' | awk -F: '{print $2}')" for IP in $IPS do N=3 while [ $N -gt 0 ] do - ADDR=`echo $IP | awk -F. "{for(i=1;i<=$N;i++)printf \\$i\".\"}"` - grep "dhcp-range=" $CONF_FILE | grep $ADDR >/dev/null 2>&1 + ADDR="$(echo "$IP" | awk -F. "{for(i=1;i<="$N";i++)printf \$i\".\"}")" + grep "dhcp-range=" "$CONF_FILE" | grep "$ADDR" >/dev/null 2>&1 if [ $? -eq 0 ]; then - SERVER_TAG="`grep "^dhcp-range *=" $CONF_FILE | grep $ADDR | awk -F= '{print $2}' | awk -F, '{print $1}'`" + SERVER_TAG="$(grep "^dhcp-range *=" "$CONF_FILE" | grep "$ADDR" | awk -F= '{print $2}' | awk -F, '{print $1}')" LOCAL_SERVER_IP="$IP" - return 0 + return 1 fi - N="`expr $N - 1`" + N=$((N-1)) done done @@ -152,19 +151,20 @@ set_dnsmasq_conf() local CONF_FILE=$1 get_server_ip $CONF_FILE + if [ "$LOCAL_SERVER_IP" ] && [ "$SERVER_TAG" ]; then - grep "dhcp-option *=" $CONF_FILE | grep "$SERVER_TAG,6,$LOCAL_SERVER_IP" > /dev/null 2>&1 + grep "dhcp-option *=" "$CONF_FILE" | grep "$SERVER_TAG,6,$LOCAL_SERVER_IP" > /dev/null 2>&1 if [ $? -ne 0 ]; then - sed -i "/^dhcp-option *=$SERVER_TAG,6,/d" $CONF_FILE - echo "dhcp-option=$SERVER_TAG,6,$LOCAL_SERVER_IP" >> $CONF_FILE + sed -i "/^dhcp-option *=$SERVER_TAG,6,/d" "$CONF_FILE" + echo "dhcp-option=$SERVER_TAG,6,$LOCAL_SERVER_IP" >> "$CONF_FILE" RESTART_DNSMASQ=1 fi fi - grep "^port *=0" $CONF_FILE > /dev/null 2>&1 + grep "^port *=0" "$CONF_FILE" > /dev/null 2>&1 if [ $? -ne 0 ]; then - sed -i "/^port *=/d" $CONF_FILE - echo "port=0" >> $CONF_FILE + sed -i "/^port *=/d" "$CONF_FILE" + echo "port=0" >> "$CONF_FILE" RESTART_DNSMASQ=1 fi } @@ -179,7 +179,7 @@ set_dnsmasq() continue fi - set_dnsmasq_conf $conf + set_dnsmasq_conf "$conf" done if [ $RESTART_DNSMASQ -ne 0 ]; then @@ -193,18 +193,18 @@ clear_dnsmasq_conf() local SERVER_TAG="" local CONF_FILE=$1 - get_server_ip $CONF_FILE + get_server_ip "$CONF_FILE" if [ "$LOCAL_SERVER_IP" ] && [ "$SERVER_TAG" ]; then - grep "dhcp-option *=" $CONF_FILE | grep "$SERVER_TAG,6,$LOCAL_SERVER_IP" > /dev/null 2>&1 + grep "dhcp-option *=" "$CONF_FILE" | grep "$SERVER_TAG,6,$LOCAL_SERVER_IP" > /dev/null 2>&1 if [ $? -eq 0 ]; then - sed -i "/^dhcp-option *=$SERVER_TAG,6,/d" $CONF_FILE + sed -i "/^dhcp-option *=$SERVER_TAG,6,/d" "$CONF_FILE" RESTART_DNSMASQ=1 fi fi - grep "^port *=" $CONF_FILE > /dev/null 2>&1 + grep "^port *=" "$CONF_FILE" > /dev/null 2>&1 if [ $? -eq 0 ]; then - sed -i "/^port *=/d" $CONF_FILE + sed -i "/^port *=/d" "$CONF_FILE" RESTART_DNSMASQ=1 fi } @@ -219,7 +219,7 @@ clear_dnsmasq() continue fi - clear_dnsmasq_conf $conf + clear_dnsmasq_conf "$conf" done if [ $RESTART_DNSMASQ -ne 0 ]; then @@ -232,11 +232,11 @@ set_smartdns_port() if [ "$SMARTDNS_WORKMODE" = "0" ]; then return 0 elif [ "$SMARTDNS_WORKMODE" = "1" ]; then - sed -i "s/^\(bind .*\):53 *\(.*\)\$/\1:$SMARTDNS_PORT \2/g" $SMARTDNS_CONF - sed -i "s/^\(bind-tcp .*\):53 *\(.*\)\$/\1:$SMARTDNS_PORT \2/g" $SMARTDNS_CONF + sed -i "s/^\\(bind .*\\):53 *\\(.*\\)\$/\\1:$SMARTDNS_PORT \\2/g" $SMARTDNS_CONF + sed -i "s/^\\(bind-tcp .*\\):53 *\\(.*\\)\$/\\1:$SMARTDNS_PORT \\2/g" $SMARTDNS_CONF elif [ "$SMARTDNS_WORKMODE" = "2" ]; then - sed -i "s/^\(bind .*\):$SMARTDNS_PORT *\(.*\)\$/\1:53 \2/g" $SMARTDNS_CONF - sed -i "s/^\(bind-tcp .*\):$SMARTDNS_PORT *\(.*\)\$/\1:53 \2/g" $SMARTDNS_CONF + sed -i "s/^\\(bind .*\\):$SMARTDNS_PORT *\\(.*\\)\$/\\1:53 \\2/g" $SMARTDNS_CONF + sed -i "s/^\\(bind-tcp .*\\):$SMARTDNS_PORT *\\(.*\\)\$/\\1:53 \\2/g" $SMARTDNS_CONF else return 1 fi @@ -286,7 +286,7 @@ get_tz() continue fi - tz="`cat $tzfile 2>/dev/null`" + tz="$(cat $tzfile 2>/dev/null)" done if [ -z "$tz" ]; then @@ -311,7 +311,7 @@ case "$1" in fi ;; status) - pid="`cat $SMARTDNS_PID |head -n 1 2>/dev/null`" + pid="$(cat $SMARTDNS_PID |head -n 1 2>/dev/null)" if [ -z "$pid" ]; then echo "smartdns not running." return 0 @@ -326,7 +326,7 @@ case "$1" in ;; stop) clear_rule - pid="`cat $SMARTDNS_PID | head -n 1 2>/dev/null`" + pid="$(cat "$SMARTDNS_PID" | head -n 1 2>/dev/null)" if [ -z "$pid" ]; then echo "smartdns not running." return 0 @@ -336,7 +336,7 @@ case "$1" in return 0; fi - kill -9 $pid 2>/dev/null + kill -9 "$pid" 2>/dev/null ;; restart) $0 stop diff --git a/release/src/router/smartdns/src/Makefile b/release/src/router/smartdns/src/Makefile index 5d78531e8b..95e51c8e36 100644 --- a/release/src/router/smartdns/src/Makefile +++ b/release/src/router/smartdns/src/Makefile @@ -14,25 +14,26 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . - +include $(TOP)/.config BIN=smartdns -ifeq ($(MERLINR_NAME), $(filter $(MERLINR_NAME), K3 SBRAC1900P SBRAC3200P RTAC68U)) +ifeq ($(BUILD_NAME), $(filter $(BUILD_NAME), RT-AC88U RT-AC3100 RT-AC3200 RT-AC68U RT-AC5300)) OBJS_LIB=lib/rbtree.o lib/art.o lib/bitops.o lib/radix.o lib/conf.o lib/ifaddrs.o else OBJS_LIB=lib/rbtree.o lib/art.o lib/bitops.o lib/radix.o lib/conf.o endif OBJS=smartdns.o fast_ping.o dns_client.o dns_server.o dns.o util.o tlog.o dns_conf.o dns_cache.o http_parse.o $(OBJS_LIB) -ifeq ($(MERLINR_NAME), $(filter $(MERLINR_NAME), GTAC5300 GTAC2900 RTAC86U R7900P R8000P)) +ifeq ($(RTCONFIG_HND_ROUTER),y) CFLAGS +=-O1 -g -Wall -Wstrict-prototypes -fno-omit-frame-pointer -Wstrict-aliasing else CFLAGS +=-O2 -g -Wall -Wstrict-prototypes -fno-omit-frame-pointer -Wstrict-aliasing endif CFLAGS +=-I./include -I$(TOP)/openssl/include -CFLAGS += -DBASE_FILE_NAME=\"$(notdir $<)\" -LDFLAGS +=-L$(TOP)/openssl -lssl -lcrypto ifeq ($(MERLINR_NAME), $(filter $(MERLINR_NAME), RTACRH17 RTAC82U)) LDFLAGS +=-ldl endif + +CFLAGS += -DBASE_FILE_NAME=\"$(notdir $<)\" +LDFLAGS +=-L$(TOP)/openssl -lssl -lcrypto CFLAGS += -DSMARTDNS_VERION=\"$(MERLINR_VER_MINOR)\" CXXFLAGS=-O2 -g -Wall -std=c++11 CXXFLAGS +=-Iinclude @@ -42,12 +43,19 @@ CXXFLAGS +=-Iinclude LDFLAGS += -lssl -lcrypto -lpthread #endif -.PHONY: all +ifneq ($(RTCONFIG_RALINK),y) +.PHONY: all clean all: $(BIN) $(BIN) : $(OBJS) $(CC) $(OBJS) -o $@ $(LDFLAGS) +else +.PHONY: all clean +all: + cp ./smartdns_mipsle ./smartdns +endif clean: $(RM) $(OBJS) $(BIN) + diff --git a/release/src/router/smartdns/src/dns.c b/release/src/router/smartdns/src/dns.c index 7f040c3cad..0e4399234c 100644 --- a/release/src/router/smartdns/src/dns.c +++ b/release/src/router/smartdns/src/dns.c @@ -1,2004 +1,2017 @@ -/************************************************************************* - * - * Copyright (C) 2018-2020 Ruilin Peng (Nick) . - * - * smartdns is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * smartdns is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#define _GNU_SOURCE -#include "dns.h" -#include "tlog.h" -#include "stringutil.h" -#include -#include -#include -#include -#include -#include -#include - -#define QR_MASK 0x8000 -#define OPCODE_MASK 0x7800 -#define AA_MASK 0x0400 -#define TC_MASK 0x0200 -#define RD_MASK 0x0100 -#define RA_MASK 0x0080 -#define RCODE_MASK 0x000F -#define DNS_RR_END (0XFFFF) - -#define UNUSED(expr) \ - do { \ - (void)(expr); \ - } while (0) - -/* read short and move pointer */ -static short _dns_read_short(unsigned char **buffer) -{ - unsigned short value; - - value = ntohs(*((unsigned short *)(*buffer))); - *buffer += 2; - return value; -} - -/* write char and move pointer */ -static __attribute__((unused)) void _dns_write_char(unsigned char **buffer, unsigned char value) -{ - **buffer = value; - *buffer += 1; -} - -/* read char and move pointer */ -static unsigned char _dns_read_char(unsigned char **buffer) -{ - unsigned char value = **buffer; - *buffer += 1; - return value; -} - -/* write short and move pointer */ -static void _dns_write_short(unsigned char **buffer, unsigned short value) -{ - value = htons(value); - *((unsigned short *)(*buffer)) = value; - *buffer += 2; -} - -/* write int and move pointer */ -static void _dns_write_int(unsigned char **buffer, unsigned int value) -{ - value = htonl(value); - *((unsigned int *)(*buffer)) = value; - *buffer += 4; -} - -/* read int and move pointer */ -static unsigned int _dns_read_int(unsigned char **buffer) -{ - unsigned int value; - - value = ntohl(*((unsigned int *)(*buffer))); - *buffer += 4; - - return value; -} - -/* iterator get rrs begin */ -struct dns_rrs *dns_get_rrs_start(struct dns_packet *packet, dns_rr_type type, int *count) -{ - unsigned short start; - struct dns_head *head = &packet->head; - - /* get rrs count by rrs type */ - switch (type) { - case DNS_RRS_QD: - *count = head->qdcount; - start = packet->questions; - break; - case DNS_RRS_AN: - *count = head->ancount; - start = packet->answers; - break; - case DNS_RRS_NS: - *count = head->nscount; - start = packet->nameservers; - break; - case DNS_RRS_NR: - *count = head->nrcount; - start = packet->additional; - break; - case DNS_RRS_OPT: - *count = packet->optcount; - start = packet->optional; - break; - default: - return NULL; - break; - } - - /* if not resource record, reutrn null */ - if (start == DNS_RR_END) { - return NULL; - } - - /* return rrs data start address */ - return (struct dns_rrs *)(packet->data + start); -} - -/* iterator next rrs */ -struct dns_rrs *dns_get_rrs_next(struct dns_packet *packet, struct dns_rrs *rrs) -{ - if (rrs->next == DNS_RR_END) { - return NULL; - } - - return (struct dns_rrs *)(packet->data + rrs->next); -} - -/* iterator add rrs begin */ -static unsigned char *_dns_add_rrs_start(struct dns_packet *packet, int *maxlen) -{ - struct dns_rrs *rrs; - unsigned char *end = packet->data + packet->len; - - rrs = (struct dns_rrs *)end; - *maxlen = packet->size - packet->len - sizeof(*packet) - sizeof(*rrs); - if (*maxlen <= 0) { - /* if size exceeds max packet size, return NULL */ - return NULL; - } - return rrs->data; -} - -/* iterator add rrs end */ -static int _dns_rr_add_end(struct dns_packet *packet, int type, dns_type_t rtype, int len) -{ - struct dns_rrs *rrs; - struct dns_rrs *rrs_next; - struct dns_head *head = &packet->head; - unsigned char *end = packet->data + packet->len; - unsigned short *count; - unsigned short *start; - - rrs = (struct dns_rrs *)end; - if (packet->len + len > packet->size - sizeof(*packet) - sizeof(*rrs)) { - return -1; - } - - switch (type) { - case DNS_RRS_QD: - count = &head->qdcount; - start = &packet->questions; - break; - case DNS_RRS_AN: - count = &head->ancount; - start = &packet->answers; - break; - case DNS_RRS_NS: - count = &head->nscount; - start = &packet->nameservers; - break; - case DNS_RRS_NR: - count = &head->nrcount; - start = &packet->additional; - break; - case DNS_RRS_OPT: - count = &packet->optcount; - start = &packet->optional; - break; - default: - return -1; - break; - } - - /* add data to end of dns_packet, and set previouse rrs point to this rrs */ - if (*start != DNS_RR_END) { - rrs_next = (struct dns_rrs *)(packet->data + *start); - while (rrs_next->next != DNS_RR_END) { - rrs_next = (struct dns_rrs *)(packet->data + rrs_next->next); - } - rrs_next->next = packet->len; - } else { - *start = packet->len; - } - - /* update rrs head info */ - rrs->len = len; - rrs->type = rtype; - rrs->next = DNS_RR_END; - - /* update total data length */ - *count += 1; - packet->len += len + sizeof(*rrs); - return 0; -} - -static inline int _dns_data_left_len(struct dns_data_context *data_context) -{ - /* check whether data length out of bound */ - return data_context->maxsize - (data_context->ptr - data_context->data); -} - -static int _dns_add_qr_head(struct dns_data_context *data_context, char *domain, int qtype, int qclass) -{ - /* question head */ - /* |domain | - * |qtype | qclass | - */ - while (1) { - if (_dns_data_left_len(data_context) < 4) { - return -1; - } - *data_context->ptr = *domain; - if (*domain == '\0') { - data_context->ptr++; - break; - } - data_context->ptr++; - domain++; - } - - if (_dns_data_left_len(data_context) < 4) { - return -1; - } - - *((unsigned short *)(data_context->ptr)) = qtype; - data_context->ptr += 2; - - *((unsigned short *)(data_context->ptr)) = qclass; - data_context->ptr += 2; - - return 0; -} - -static int _dns_get_qr_head(struct dns_data_context *data_context, char *domain, int maxsize, int *qtype, int *qclass) -{ - int i; - int is_read_all = 0; - /* question head */ - /* |domain | - * |qtype | qclass | - */ - for (i = 0; i < maxsize - 1; i++) { - if (_dns_data_left_len(data_context) < 4) { - return -1; - } - *domain = *data_context->ptr; - if (*data_context->ptr == '\0') { - domain++; - data_context->ptr++; - i++; - is_read_all = 1; - break; - } - *domain = *data_context->ptr; - domain++; - data_context->ptr++; - } - - *domain = '\0'; - if (is_read_all == 0) { - return -1; - } - - if (_dns_data_left_len(data_context) < 4) { - return -1; - } - - *qtype = *((unsigned short *)(data_context->ptr)); - data_context->ptr += 2; - - *qclass = *((unsigned short *)(data_context->ptr)); - data_context->ptr += 2; - - return 0; -} - -static int _dns_add_rr_head(struct dns_data_context *data_context, char *domain, int qtype, int qclass, int ttl, int rr_len) -{ - int len = 0; - - /* resource record head */ - /* |domain | - * |qtype | qclass | - * | ttl | - * | rrlen | rrdata | - */ - len = _dns_add_qr_head(data_context, domain, qtype, qclass); - if (len < 0) { - return -1; - } - - if (_dns_data_left_len(data_context) < 6) { - return -1; - } - - *((unsigned int *)(data_context->ptr)) = ttl; - data_context->ptr += 4; - - *((unsigned short *)(data_context->ptr)) = rr_len; - data_context->ptr += 2; - - return 0; -} - -static int _dns_get_rr_head(struct dns_data_context *data_context, char *domain, int maxsize, int *qtype, int *qclass, int *ttl, int *rr_len) -{ - int len = 0; - - /* resource record head */ - /* |domain | - * |qtype | qclass | - * | ttl | - * | rrlen | rrdata | - */ - len = _dns_get_qr_head(data_context, domain, maxsize, qtype, qclass); - - if (_dns_data_left_len(data_context) < 6) { - return -1; - } - - *ttl = *((unsigned int *)(data_context->ptr)); - data_context->ptr += 4; - - *rr_len = *((unsigned short *)(data_context->ptr)); - data_context->ptr += 2; - - return len; -} - -static int _dns_add_RAW(struct dns_packet *packet, dns_rr_type rrtype, dns_type_t rtype, char *domain, int ttl, void *raw, int raw_len) -{ - int maxlen = 0; - int len = 0; - struct dns_data_context data_context; - - /* resource record */ - /* |domain | - * |qtype | qclass | - * | ttl | - * | rrlen | rrdata | - */ - unsigned char *data = _dns_add_rrs_start(packet, &maxlen); - if (data == NULL) { - return -1; - } - - if (raw_len >= maxlen) { - return -1; - } - - data_context.data = data; - data_context.ptr = data; - data_context.maxsize = maxlen; - - /* add rr head */ - len = _dns_add_rr_head(&data_context, domain, rtype, DNS_C_IN, ttl, raw_len); - if (len < 0) { - return -1; - } - - /* add rr data */ - memcpy(data_context.ptr, raw, raw_len); - data_context.ptr += raw_len; - len = data_context.ptr - data_context.data; - - return _dns_rr_add_end(packet, rrtype, rtype, len); -} - -static int _dns_get_RAW(struct dns_rrs *rrs, char *domain, int maxsize, int *ttl, void *raw, int *raw_len) -{ - int qtype = 0; - int qclass = 0; - int rr_len = 0; - int ret = 0; - struct dns_data_context data_context; - - /* resource record head */ - /* |domain | - * |qtype | qclass | - * | ttl | - * | rrlen | rrdata | - */ - unsigned char *data = rrs->data; - - data_context.data = data; - data_context.ptr = data; - data_context.maxsize = rrs->len; - - /* get rr head */ - ret = _dns_get_rr_head(&data_context, domain, maxsize, &qtype, &qclass, ttl, &rr_len); - if (ret < 0) { - return -1; - } - - if (qtype != rrs->type || rr_len > *raw_len) { - return -1; - } - - /* get rr data */ - memcpy(raw, data_context.ptr, rr_len); - data_context.ptr += rr_len; - *raw_len = rr_len; - - return 0; -} - -static int _dns_add_opt_RAW(struct dns_packet *packet, dns_opt_code_t opt_rrtype, void *raw, int raw_len) -{ - unsigned char opt_data[DNS_MAX_OPT_LEN]; - struct dns_opt *opt = (struct dns_opt *)opt_data; - int len = 0; - - opt->code = DNS_OPT_T_TCP_KEEPALIVE; - opt->length = sizeof(unsigned short); - - memcpy(opt->data, raw, raw_len); - len += raw_len; - len += sizeof(*opt); - - return _dns_add_RAW(packet, DNS_RRS_OPT, DNS_OPT_T_TCP_KEEPALIVE, "", 0, opt_data, len); -} - -static int _dns_get_opt_RAW(struct dns_rrs *rrs, char *domain, int maxsize, int *ttl, struct dns_opt *dns_opt, int *dns_optlen) -{ - *dns_optlen = DNS_MAX_OPT_LEN; - - return _dns_get_RAW(rrs, domain, maxsize, ttl, dns_opt, dns_optlen); -} - -static int __attribute__((unused)) _dns_add_OPT(struct dns_packet *packet, dns_rr_type type, unsigned short opt_code, unsigned short opt_len, struct dns_opt *opt) -{ - // TODO - - int maxlen = 0; - int len = 0; - struct dns_data_context data_context; - int total_len = sizeof(*opt) + opt->length; - int ttl = 0; - - /* - +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ - 0: | OPTION-CODE | - +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ - 2: | OPTION-LENGTH | - +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ - 4: | | - / OPTION-DATA / - / / - +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ - */ - unsigned char *data = _dns_add_rrs_start(packet, &maxlen); - if (data == NULL) { - return -1; - } - - if (total_len > maxlen) { - return -1; - } - - data_context.data = data; - data_context.ptr = data; - data_context.maxsize = maxlen; - - ttl = (opt_code << 16) | opt_len; - - /* add rr head */ - len = _dns_add_rr_head(&data_context, "", type, DNS_C_IN, ttl, total_len); - if (len < 0) { - return -1; - } - - /* add rr data */ - memcpy(data_context.ptr, opt, total_len); - data_context.ptr += total_len; - len = data_context.ptr - data_context.data; - - return _dns_rr_add_end(packet, type, DNS_T_OPT, len); -} - -static int __attribute__((unused)) _dns_get_OPT(struct dns_rrs *rrs, unsigned short *opt_code, unsigned short *opt_len, struct dns_opt *opt, int *opt_maxlen) -{ - // TODO - - int qtype = 0; - int qclass = 0; - int rr_len = 0; - int ret = 0; - struct dns_data_context data_context; - char domain[DNS_MAX_CNAME_LEN]; - int maxsize = DNS_MAX_CNAME_LEN; - int ttl = 0; - unsigned char *data = rrs->data; - - data_context.data = data; - data_context.ptr = data; - data_context.maxsize = rrs->len; - - /* get rr head */ - ret = _dns_get_rr_head(&data_context, domain, maxsize, &qtype, &qclass, &ttl, &rr_len); - if (ret < 0) { - return -1; - } - - if (qtype != rrs->type || rr_len > *opt_len) { - return -1; - } - - /* get rr data */ - *opt_code = ttl >> 16; - *opt_len = ttl & 0xFFFF; - memcpy(opt, data_context.ptr, rr_len); - data_context.ptr += rr_len; - *opt_maxlen = rr_len; - - return 0; -} - -int dns_add_CNAME(struct dns_packet *packet, dns_rr_type type, char *domain, int ttl, char *cname) -{ - int rr_len = strnlen(cname, DNS_MAX_CNAME_LEN) + 1; - return _dns_add_RAW(packet, type, DNS_T_CNAME, domain, ttl, cname, rr_len); -} - -int dns_get_CNAME(struct dns_rrs *rrs, char *domain, int maxsize, int *ttl, char *cname, int cname_size) -{ - int len = cname_size; - return _dns_get_RAW(rrs, domain, maxsize, ttl, cname, &len); -} - -int dns_add_A(struct dns_packet *packet, dns_rr_type type, char *domain, int ttl, unsigned char addr[DNS_RR_A_LEN]) -{ - return _dns_add_RAW(packet, type, DNS_T_A, domain, ttl, addr, DNS_RR_A_LEN); -} - -int dns_get_A(struct dns_rrs *rrs, char *domain, int maxsize, int *ttl, unsigned char addr[DNS_RR_A_LEN]) -{ - int len = DNS_RR_A_LEN; - return _dns_get_RAW(rrs, domain, maxsize, ttl, addr, &len); -} - -int dns_add_PTR(struct dns_packet *packet, dns_rr_type type, char *domain, int ttl, char *cname) -{ - int rr_len = strnlen(cname, DNS_MAX_CNAME_LEN) + 1; - return _dns_add_RAW(packet, type, DNS_T_PTR, domain, ttl, cname, rr_len); -} - -int dns_get_PTR(struct dns_rrs *rrs, char *domain, int maxsize, int *ttl, char *cname, int cname_size) -{ - int len = cname_size; - return _dns_get_RAW(rrs, domain, maxsize, ttl, cname, &len); -} - -int dns_add_NS(struct dns_packet *packet, dns_rr_type type, char *domain, int ttl, char *cname) -{ - int rr_len = strnlen(cname, DNS_MAX_CNAME_LEN) + 1; - return _dns_add_RAW(packet, type, DNS_T_NS, domain, ttl, cname, rr_len); -} - -int dns_get_NS(struct dns_rrs *rrs, char *domain, int maxsize, int *ttl, char *cname, int cname_size) -{ - int len = cname_size; - return _dns_get_RAW(rrs, domain, maxsize, ttl, cname, &len); -} - -int dns_add_AAAA(struct dns_packet *packet, dns_rr_type type, char *domain, int ttl, unsigned char addr[DNS_RR_AAAA_LEN]) -{ - return _dns_add_RAW(packet, type, DNS_T_AAAA, domain, ttl, addr, DNS_RR_AAAA_LEN); -} - -int dns_get_AAAA(struct dns_rrs *rrs, char *domain, int maxsize, int *ttl, unsigned char addr[DNS_RR_AAAA_LEN]) -{ - int len = DNS_RR_AAAA_LEN; - return _dns_get_RAW(rrs, domain, maxsize, ttl, addr, &len); -} - -int dns_add_SOA(struct dns_packet *packet, dns_rr_type type, char *domain, int ttl, struct dns_soa *soa) -{ - /* SOA */ - /*| mname | - *| rname | - *| serial | - *| refersh | - *| retry | - *| expire | - *| minimum | - */ - unsigned char data[sizeof(*soa)]; - unsigned char *ptr = data; - int len = 0; - safe_strncpy((char *)ptr, soa->mname, DNS_MAX_CNAME_LEN); - ptr += strnlen(soa->mname, DNS_MAX_CNAME_LEN - 1) + 1; - safe_strncpy((char *)ptr, soa->rname, DNS_MAX_CNAME_LEN); - ptr += strnlen(soa->rname, DNS_MAX_CNAME_LEN - 1) + 1; - memcpy(ptr, &soa->serial, sizeof(unsigned int)); - ptr += 4; - memcpy(ptr, &soa->refresh, sizeof(unsigned int)); - ptr += 4; - memcpy(ptr, &soa->retry, sizeof(unsigned int)); - ptr += 4; - memcpy(ptr, &soa->expire, sizeof(unsigned int)); - ptr += 4; - memcpy(ptr, &soa->minimum, sizeof(unsigned int)); - ptr += 4; - len = ptr - data; - - return _dns_add_RAW(packet, type, DNS_T_SOA, domain, ttl, data, len); -} - -int dns_get_SOA(struct dns_rrs *rrs, char *domain, int maxsize, int *ttl, struct dns_soa *soa) -{ - unsigned char data[sizeof(*soa)]; - unsigned char *ptr = data; - int len = sizeof(data); - - /* SOA */ - /*| mname | - *| rname | - *| serial | - *| refersh | - *| retry | - *| expire | - *| minimum | - */ - if (_dns_get_RAW(rrs, domain, maxsize, ttl, data, &len) != 0) { - return -1; - } - - safe_strncpy(soa->mname, (char *)ptr, DNS_MAX_CNAME_LEN - 1); - ptr += strnlen(soa->mname, DNS_MAX_CNAME_LEN - 1) + 1; - if (ptr - data >= len) { - return -1; - } - safe_strncpy(soa->rname, (char *)ptr, DNS_MAX_CNAME_LEN - 1); - ptr += strnlen(soa->rname, DNS_MAX_CNAME_LEN - 1) + 1; - if (ptr - data + 20 > len) { - return -1; - } - soa->serial = *((unsigned int *)ptr); - ptr += 4; - soa->refresh = *((unsigned int *)ptr); - ptr += 4; - soa->retry = *((unsigned int *)ptr); - ptr += 4; - soa->expire = *((unsigned int *)ptr); - ptr += 4; - soa->minimum = *((unsigned int *)ptr); - ptr += 4; - - return 0; -} - -int dns_set_OPT_payload_size(struct dns_packet *packet, int payload_size) -{ - if (payload_size < 512) { - payload_size = 512; - } - - packet->payloadsize = payload_size; - return 0; -} - -int dns_get_OPT_payload_size(struct dns_packet *packet) -{ - return packet->payloadsize; -} - -int dns_add_OPT_ECS(struct dns_packet *packet, struct dns_opt_ecs *ecs) -{ - unsigned char opt_data[DNS_MAX_OPT_LEN]; - struct dns_opt *opt = (struct dns_opt *)opt_data; - int len = 0; - - opt->code = DNS_OPT_T_ECS; - opt->length = sizeof(*ecs); - memcpy(opt->data, ecs, sizeof(*ecs)); - - /* ecs size 4 + bit of address*/ - len = sizeof(*opt) + 4; - len += (ecs->source_prefix / 8); - len += (ecs->source_prefix % 8 > 0) ? 1 : 0; - - return _dns_add_RAW(packet, DNS_RRS_OPT, DNS_OPT_T_ECS, "", 0, opt_data, len); -} - -int dns_get_OPT_ECS(struct dns_rrs *rrs, unsigned short *opt_code, unsigned short *opt_len, struct dns_opt_ecs *ecs) -{ - unsigned char opt_data[DNS_MAX_OPT_LEN]; - struct dns_opt *opt = (struct dns_opt *)opt_data; - int len = DNS_MAX_OPT_LEN; - int ttl = 0; - - if (_dns_get_RAW(rrs, NULL, 0, &ttl, opt_data, &len) != 0) { - return -1; - } - - if (len < sizeof(*opt)) { - return -1; - } - - if (opt->code != DNS_OPT_T_ECS) { - return -1; - } - - memcpy(ecs, opt->data, opt->length); - - return 0; -} - -int dns_add_OPT_TCP_KEEYALIVE(struct dns_packet *packet, unsigned short timeout) -{ - unsigned short timeout_net = htons(timeout); - int data_len = 0; - - if (timeout > 0) { - data_len = sizeof(timeout); - } - - return _dns_add_opt_RAW(packet, DNS_OPT_T_TCP_KEEPALIVE, &timeout_net, data_len); -} - -int dns_get_OPT_TCP_KEEYALIVE(struct dns_rrs *rrs, unsigned short *opt_code, unsigned short *opt_len, unsigned short *timeout) -{ - unsigned char opt_data[DNS_MAX_OPT_LEN]; - struct dns_opt *opt = (struct dns_opt *)opt_data; - int len = DNS_MAX_OPT_LEN; - int ttl = 0; - unsigned char *data = NULL; - - if (_dns_get_opt_RAW(rrs, NULL, 0, &ttl, opt, &len) != 0) { - return -1; - } - - if (len < sizeof(*opt)) { - return -1; - } - - if (opt->code != DNS_OPT_T_TCP_KEEPALIVE) { - return -1; - } - - if (opt->length == 0) { - *timeout = 0; - return 0; - } - - if (opt->length != sizeof(unsigned short)) { - return -1; - } - - data = opt->data; - - *timeout = _dns_read_short(&data); - - return 0; -} - -/* - * Format: - * |DNS_NAME\0(string)|qtype(short)|qclass(short)| - */ -int dns_add_domain(struct dns_packet *packet, char *domain, int qtype, int qclass) -{ - int len = 0; - int maxlen = 0; - unsigned char *data = _dns_add_rrs_start(packet, &maxlen); - struct dns_data_context data_context; - - if (data == NULL) { - return -1; - } - - data_context.data = data; - data_context.ptr = data; - data_context.maxsize = maxlen; - - len = _dns_add_qr_head(&data_context, domain, qtype, qclass); - if (len < 0) { - return -1; - } - - len = data_context.ptr - data_context.data; - - return _dns_rr_add_end(packet, DNS_RRS_QD, DNS_T_CNAME, len); -} - -int dns_get_domain(struct dns_rrs *rrs, char *domain, int maxsize, int *qtype, int *qclass) -{ - struct dns_data_context data_context; - unsigned char *data = rrs->data; - - if (rrs->type != DNS_T_CNAME) { - return -1; - } - - data_context.data = data; - data_context.ptr = data; - data_context.maxsize = rrs->len; - - return _dns_get_qr_head(&data_context, domain, maxsize, qtype, qclass); -} - -static inline int _dns_left_len(struct dns_context *context) -{ - return context->maxsize - (context->ptr - context->data); -} - -static int _dns_decode_head(struct dns_context *context) -{ - unsigned int fields; - int len = 12; - struct dns_head *head = &context->packet->head; - - if (_dns_left_len(context) < len) { - return -1; - } - - /* - 0 1 2 3 4 5 6 7 8 9 A B C D E F - +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - | ID | - +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - |QR| Opcode |AA|TC|RD|RA| Z | RCODE | - +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - | QDCOUNT | - +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - | ANCOUNT | - +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - | NSCOUNT | - +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - | ARCOUNT | - +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - */ - - head->id = _dns_read_short(&context->ptr); - fields = _dns_read_short(&context->ptr); - head->qr = (fields & QR_MASK) >> 15; - head->opcode = (fields & OPCODE_MASK) >> 11; - head->aa = (fields & AA_MASK) >> 10; - head->tc = (fields & TC_MASK) >> 9; - head->rd = (fields & RD_MASK) >> 8; - head->ra = (fields & RA_MASK) >> 7; - head->rcode = (fields & RCODE_MASK) >> 0; - head->qdcount = _dns_read_short(&context->ptr); - head->ancount = _dns_read_short(&context->ptr); - head->nscount = _dns_read_short(&context->ptr); - head->nrcount = _dns_read_short(&context->ptr); - - return 0; -} - -static int _dns_encode_head(struct dns_context *context) -{ - int len = 12; - struct dns_head *head = &context->packet->head; - - if (_dns_left_len(context) < len) { - return -1; - } - - _dns_write_short(&context->ptr, head->id); - - int fields = 0; - fields |= (head->qr << 15) & QR_MASK; - fields |= (head->opcode << 11) & OPCODE_MASK; - fields |= (head->aa << 10) & AA_MASK; - fields |= (head->tc << 9) & TC_MASK; - fields |= (head->rd << 8) & RD_MASK; - fields |= (head->ra << 7) & RA_MASK; - fields |= (head->rcode << 0) & RCODE_MASK; - _dns_write_short(&context->ptr, fields); - - _dns_write_short(&context->ptr, head->qdcount); - _dns_write_short(&context->ptr, head->ancount); - _dns_write_short(&context->ptr, head->nscount); - _dns_write_short(&context->ptr, head->nrcount); - return len; -} - -static int _dns_encode_head_count(struct dns_context *context) -{ - int len = 12; - struct dns_head *head = &context->packet->head; - unsigned char *ptr = context->data; - - ptr += 4; - _dns_write_short(&ptr, head->qdcount); - _dns_write_short(&ptr, head->ancount); - _dns_write_short(&ptr, head->nscount); - _dns_write_short(&ptr, head->nrcount); - return len; -} - -static int _dns_decode_domain(struct dns_context *context, char *output, int size) -{ - int output_len = 0; - int copy_len = 0; - int len = 0; - unsigned char *ptr = context->ptr; - int is_compressed = 0; - int ptr_jump = 0; - - /*[len]string[len]string...[0]0 */ - while (1) { - if (ptr > context->data + context->maxsize || ptr < context->data || output_len >= size - 1 || ptr_jump > 4) { - return -1; - } - - len = *ptr; - if (len == 0) { - *output = 0; - ptr++; - break; - } - - /* compressed domain */ - if (len >= 0xC0) { - if ((ptr + 2) > (context->data + context->maxsize)) { - return -1; - } - /* - 0 1 2 3 4 5 6 7 8 9 A B C D E F - +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - | 1 1| OFFSET | - +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - */ - /* read offset */ - len = _dns_read_short(&ptr) & 0x3FFF; - if (is_compressed == 0) { - context->ptr = ptr; - } - ptr = context->data + len; - if (ptr > context->data + context->maxsize) { - tlog(TLOG_DEBUG, "length is not enough %u:%ld, %p, %p", context->maxsize, (long)(ptr - context->data), context->ptr, context->data); - return -1; - } - is_compressed = 1; - ptr_jump++; - continue; - } - - ptr_jump = 0; - - /* change [len] to '.' */ - if (output_len > 0) { - *output = '.'; - output++; - output_len += 1; - } - - if (ptr > context->data + context->maxsize) { - tlog(TLOG_DEBUG, "length is not enough %u:%ld, %p, %p", context->maxsize, (long)(ptr - context->data), context->ptr, context->data); - return -1; - } - - ptr++; - if (output_len < size - 1) { - /* copy sub string */ - copy_len = (len < size - output_len) ? len : size - 1 - output_len; - if ((ptr + copy_len) > (context->data + context->maxsize)) { - tlog(TLOG_DEBUG, "length is not enough %u:%ld, %p, %p", context->maxsize, (long)(ptr - context->data), context->ptr, context->data); - return -1; - } - memcpy(output, ptr, copy_len); - } - - ptr += len; - output += len; - output_len += len; - } - - if (is_compressed == 0) { - context->ptr = ptr; - } - - return 0; -} - -static int _dns_encode_domain(struct dns_context *context, char *domain) -{ - int num = 0; - int total_len = 0; - unsigned char *ptr_num = context->ptr++; - - /*[len]string[len]string...[0]0 */ - while (_dns_left_len(context) > 1 && *domain != 0) { - if (*domain == '.') { - *ptr_num = num; - num = 0; - ptr_num = context->ptr; - domain++; - context->ptr++; - continue; - } - *context->ptr = *domain; - num++; - context->ptr++; - domain++; - total_len++; - } - - *ptr_num = num; - if (total_len > 0) { - /* if domain is '\0', [domain] is '\0' */ - *(context->ptr) = 0; - context->ptr++; - } - return 0; -} - -static int _dns_decode_qr_head(struct dns_context *context, char *domain, int domain_size, int *qtype, int *qclass) -{ - int ret = 0; - /* - 0 1 2 3 4 5 6 7 8 9 A B C D E F - +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - | | - / / - / NAME / - | | - +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - | TYPE | - +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - | CLASS | - +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - */ - ret = _dns_decode_domain(context, domain, domain_size); - if (ret < 0) { - tlog(TLOG_DEBUG, "decode domain failed."); - return -1; - } - - if (_dns_left_len(context) < 4) { - tlog(TLOG_DEBUG, "left length is not enough, %s.", domain); - return -1; - } - - *qtype = _dns_read_short(&context->ptr); - *qclass = _dns_read_short(&context->ptr); - - return 0; -} - -static int _dns_encode_qr_head(struct dns_context *context, char *domain, int qtype, int qclass) -{ - int ret = 0; - ret = _dns_encode_domain(context, domain); - if (ret < 0) { - return -1; - } - - if (_dns_left_len(context) < 4) { - return -1; - } - - _dns_write_short(&context->ptr, qtype); - _dns_write_short(&context->ptr, qclass); - - return 0; -} - -static int _dns_decode_rr_head(struct dns_context *context, char *domain, int domain_size, int *qtype, int *qclass, int *ttl, int *rr_len) -{ - int len = 0; - - len = _dns_decode_qr_head(context, domain, domain_size, qtype, qclass); - if (len < 0) { - tlog(TLOG_DEBUG, "decode qr head failed."); - return -1; - } - - if (_dns_left_len(context) < 6) { - tlog(TLOG_DEBUG, "left length is not enough."); - return -1; - } - - *ttl = _dns_read_int(&context->ptr); - *rr_len = _dns_read_short(&context->ptr); - - return 0; -} - -static int _dns_encode_rr_head(struct dns_context *context, char *domain, int qtype, int qclass, int ttl, int rr_len) -{ - int ret = 0; - ret = _dns_encode_qr_head(context, domain, qtype, qclass); - if (ret < 0) { - return -1; - } - - if (_dns_left_len(context) < 6) { - return -1; - } - - _dns_write_int(&context->ptr, ttl); - _dns_write_short(&context->ptr, rr_len); - - return 0; -} - -static int _dns_encode_raw(struct dns_context *context, struct dns_rrs *rrs) -{ - int ret; - int qtype = 0; - int qclass = 0; - int ttl = 0; - char domain[DNS_MAX_CNAME_LEN]; - int rr_len; - struct dns_data_context data_context; - /* - 0 1 2 3 4 5 6 7 8 9 A B C D E F - +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - | | - / / - / NAME / - | | - +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - | TYPE | - +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - | CLASS | - +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - | TTL | - | | - +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - | RDLENGTH | - +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--| - / RDATA / - / / - +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ - */ - - data_context.data = rrs->data; - data_context.ptr = rrs->data; - data_context.maxsize = rrs->len; - - ret = _dns_get_rr_head(&data_context, domain, DNS_MAX_CNAME_LEN, &qtype, &qclass, &ttl, &rr_len); - if (ret < 0) { - return -1; - } - - ret = _dns_encode_rr_head(context, domain, qtype, qclass, ttl, rr_len); - if (ret < 0) { - return -1; - } - - if (_dns_left_len(context) < rr_len) { - return -1; - } - - memcpy(context->ptr, data_context.ptr, rr_len); - context->ptr += rr_len; - data_context.ptr += rr_len; - - return 0; -} - -static int _dns_decode_raw(struct dns_context *context, unsigned char *raw, int len) -{ - if (_dns_left_len(context) < len) { - return -1; - } - - memcpy(raw, context->ptr, len); - context->ptr += len; - return 0; -} - -static int _dns_decode_CNAME(struct dns_context *context, char *cname, int cname_size) -{ - int ret = 0; - ret = _dns_decode_domain(context, cname, cname_size); - if (ret < 0) { - return -1; - } - - return 0; -} - -static int _dns_encode_CNAME(struct dns_context *context, struct dns_rrs *rrs) -{ - int ret; - int qtype = 0; - int qclass = 0; - int ttl = 0; - char domain[DNS_MAX_CNAME_LEN]; - int rr_len; - struct dns_data_context data_context; - - data_context.data = rrs->data; - data_context.ptr = rrs->data; - data_context.maxsize = rrs->len; - - ret = _dns_get_rr_head(&data_context, domain, DNS_MAX_CNAME_LEN, &qtype, &qclass, &ttl, &rr_len); - if (ret < 0) { - return -1; - } - - /* when code domain, len must plus 1, because of length at the begining */ - rr_len++; - if (rr_len > rrs->len) { - return -1; - } - - ret = _dns_encode_rr_head(context, domain, qtype, qclass, ttl, rr_len); - if (ret < 0) { - return -1; - } - - ret = _dns_encode_domain(context, (char *)data_context.ptr); - if (ret < 0) { - return -1; - } - - data_context.ptr += strnlen((char *)(data_context.ptr), DNS_MAX_CNAME_LEN) + 1; - - return 0; -} - -static int _dns_decode_SOA(struct dns_context *context, struct dns_soa *soa) -{ - int ret = 0; - ret = _dns_decode_domain(context, soa->mname, DNS_MAX_CNAME_LEN - 1); - if (ret < 0) { - return -1; - } - - ret = _dns_decode_domain(context, soa->rname, DNS_MAX_CNAME_LEN - 1); - if (ret < 0) { - return -1; - } - - if (_dns_left_len(context) < 20) { - return -1; - } - - soa->serial = _dns_read_int(&context->ptr); - soa->refresh = _dns_read_int(&context->ptr); - soa->retry = _dns_read_int(&context->ptr); - soa->expire = _dns_read_int(&context->ptr); - soa->minimum = _dns_read_int(&context->ptr); - - return 0; -} - -static int _dns_encode_SOA(struct dns_context *context, struct dns_rrs *rrs) -{ - int ret; - int qtype = 0; - int qclass = 0; - int ttl = 0; - char domain[DNS_MAX_CNAME_LEN]; - int rr_len; - struct dns_data_context data_context; - - data_context.data = rrs->data; - data_context.ptr = rrs->data; - data_context.maxsize = rrs->len; - - ret = _dns_get_rr_head(&data_context, domain, DNS_MAX_CNAME_LEN, &qtype, &qclass, &ttl, &rr_len); - if (ret < 0) { - return -1; - } - - /* when code two domain, len must plus 2, because of length at the begining */ - rr_len += 2; - if (rr_len > rrs->len) { - return -1; - } - - ret = _dns_encode_rr_head(context, domain, qtype, qclass, ttl, rr_len); - if (ret < 0) { - return -1; - } - - /* mname */ - ret = _dns_encode_domain(context, (char *)data_context.ptr); - if (ret < 0) { - return -1; - } - - data_context.ptr += strnlen((char *)(data_context.ptr), DNS_MAX_CNAME_LEN) + 1; - - /* rname */ - ret = _dns_encode_domain(context, (char *)data_context.ptr); - if (ret < 0) { - return -1; - } - - data_context.ptr += strnlen((char *)(data_context.ptr), DNS_MAX_CNAME_LEN) + 1; - - if (_dns_left_len(context) < 20) { - return -1; - } - - _dns_write_int(&context->ptr, *(unsigned int *)data_context.ptr); - data_context.ptr += 4; - _dns_write_int(&context->ptr, *(unsigned int *)data_context.ptr); - data_context.ptr += 4; - _dns_write_int(&context->ptr, *(unsigned int *)data_context.ptr); - data_context.ptr += 4; - _dns_write_int(&context->ptr, *(unsigned int *)data_context.ptr); - data_context.ptr += 4; - _dns_write_int(&context->ptr, *(unsigned int *)data_context.ptr); - data_context.ptr += 4; - - return 0; -} - -static int _dns_decode_opt_ecs(struct dns_context *context, struct dns_opt_ecs *ecs) -{ - // TODO - - int len = 0; - if (_dns_left_len(context) < 4) { - return -1; - } - - ecs->family = _dns_read_short(&context->ptr); - ecs->source_prefix = _dns_read_char(&context->ptr); - ecs->scope_prefix = _dns_read_char(&context->ptr); - len = (ecs->source_prefix / 8); - len += (ecs->source_prefix % 8 > 0) ? 1 : 0; - - if (_dns_left_len(context) < len) { - return -1; - } - - memcpy(ecs->addr, context->ptr, len); - context->ptr += len; - - tlog(TLOG_DEBUG, "ECS: family:%d, source_prefix:%d, scope_prefix:%d, len:%d", ecs->family, ecs->source_prefix, ecs->scope_prefix, len); - tlog(TLOG_DEBUG, "%d.%d.%d.%d", ecs->addr[0], ecs->addr[1], ecs->addr[2], ecs->addr[3]); - - return 0; -} - -static int _dns_encode_OPT(struct dns_context *context, struct dns_rrs *rrs) -{ - int ret; - int opt_code = 0; - int qclass = 0; - char domain[DNS_MAX_CNAME_LEN]; - struct dns_data_context data_context; - int rr_len = 0; - int ttl; - struct dns_opt *dns_opt = NULL; - - data_context.data = rrs->data; - data_context.ptr = rrs->data; - data_context.maxsize = rrs->len; - - ret = _dns_get_rr_head(&data_context, domain, DNS_MAX_CNAME_LEN, &opt_code, &qclass, &ttl, &rr_len); - if (ret < 0) { - return -1; - } - - if (rr_len < sizeof(*dns_opt)) { - return -1; - } - - if (_dns_left_len(context) < (rr_len)) { - return -1; - } - - dns_opt = (struct dns_opt *)data_context.ptr; - _dns_write_short(&context->ptr, dns_opt->code); - _dns_write_short(&context->ptr, dns_opt->length); - - if (_dns_left_len(context) < dns_opt->length) { - return -1; - } - - memcpy(context->ptr, dns_opt->data, dns_opt->length); - context->ptr += dns_opt->length; - - return 0; -} - -static int _dns_get_opts_data_len(struct dns_packet *packet, struct dns_rrs *rrs, int count) -{ - int i = 0; - int len = 0; - int opt_code = 0; - int qclass = 0; - int ttl; - int ret; - char domain[DNS_MAX_CNAME_LEN]; - struct dns_data_context data_context; - int rr_len = 0; - - for (i = 0; i < count && rrs; i++, rrs = dns_get_rrs_next(packet, rrs)) { - data_context.data = rrs->data; - data_context.ptr = rrs->data; - data_context.maxsize = rrs->len; - - ret = _dns_get_rr_head(&data_context, domain, DNS_MAX_CNAME_LEN, &opt_code, &qclass, &ttl, &rr_len); - if (ret < 0) { - return -1; - } - - len += rr_len; - } - - return len; -} - -static int _dns_encode_opts(struct dns_packet *packet, struct dns_context *context, struct dns_rrs *rrs, int count) -{ - int i = 0; - int len = 0; - int ret = 0; - unsigned int rcode = 0; - int rr_len = 0; - int payloadsize = packet->payloadsize; - - rr_len = _dns_get_opts_data_len(packet, rrs, count); - if (rr_len < 0) { - return -1; - } - - if (payloadsize < DNS_DEFAULT_PACKET_SIZE) { - payloadsize = DNS_DEFAULT_PACKET_SIZE; - } - - ret = _dns_encode_rr_head(context, "", DNS_T_OPT, payloadsize, rcode, rr_len); - if (ret < 0) { - return -1; - } - - if (_dns_left_len(context) < rr_len) { - return -1; - } - - for (i = 0; i < count && rrs; i++, rrs = dns_get_rrs_next(packet, rrs)) { - len = _dns_encode_OPT(context, rrs); - if (len < 0) { - return -1; - } - } - - return 0; -} - -static int _dns_decode_opt(struct dns_context *context, dns_rr_type type, unsigned int ttl, int rr_len) -{ - unsigned short opt_code; - unsigned short opt_len; - unsigned short ercode = (ttl >> 16) & 0xFFFF; - unsigned short ever = (ttl)&0xFFFF; - unsigned char *start = context->ptr; - struct dns_packet *packet = context->packet; - int ret = 0; - - UNUSED(ever); - - /* - Field Name Field Type Description - ------------------------------------------------------ - NAME domain name empty (root domain) - TYPE u_int16_t OPT - CLASS u_int16_t sender's UDP payload size - TTL u_int32_t extended RCODE and flags - RDLEN u_int16_t describes RDATA - RDATA octet stream {attribute,value} pairs - - +0 (MSB) +1 (LSB) - +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ - 0: | OPTION-CODE | - +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ - 2: | OPTION-LENGTH | - +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ - 4: | | - / OPTION-DATA / - / / - +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ - - TTL - +0 (MSB) +1 (LSB) - +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ - 0: | EXTENDED-RCODE | VERSION | - +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ - 2: | Z | - +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ - */ - - if (ercode != 0) { - tlog(TLOG_ERROR, "extend rcode invalid."); - return -1; - } - - while (context->ptr - start < rr_len) { - if (_dns_left_len(context) < 4) { - return -1; - } - opt_code = _dns_read_short(&context->ptr); - opt_len = _dns_read_short(&context->ptr); - - if (_dns_left_len(context) < opt_len) { - tlog(TLOG_ERROR, "read opt data failed, opt_code = %d, opt_le = %d", opt_code, opt_len); - return -1; - } - - tlog(TLOG_DEBUG, "opt type %d", opt_code); - switch (opt_code) { - case DNS_OPT_T_ECS: { - struct dns_opt_ecs ecs; - ret = _dns_decode_opt_ecs(context, &ecs); - if (ret != 0) { - tlog(TLOG_ERROR, "decode ecs failed."); - return -1; - } - - ret = dns_add_OPT_ECS(packet, &ecs); - if (ret != 0) { - tlog(TLOG_ERROR, "add ecs failed."); - return -1; - } - } break; - default: - context->ptr += opt_len; - tlog(TLOG_DEBUG, "DNS opt type = %d not supported", opt_code); - break; - } - } - - return 0; -} - -static int _dns_decode_qd(struct dns_context *context) -{ - struct dns_packet *packet = context->packet; - int len; - int qtype = 0; - int qclass = 0; - char domain[DNS_MAX_CNAME_LEN]; - - len = _dns_decode_qr_head(context, domain, DNS_MAX_CNAME_LEN, &qtype, &qclass); - if (len < 0) { - return -1; - } - - len = dns_add_domain(packet, domain, qtype, qclass); - if (len < 0) { - return -1; - } - - return 0; -} - -static int _dns_decode_an(struct dns_context *context, dns_rr_type type) -{ - int ret; - int qtype = 0; - int qclass = 0; - int ttl; - int rr_len = 0; - char domain[DNS_MAX_CNAME_LEN]; - struct dns_packet *packet = context->packet; - unsigned char *start; - - /* decode rr head */ - ret = _dns_decode_rr_head(context, domain, DNS_MAX_CNAME_LEN, &qtype, &qclass, &ttl, &rr_len); - if (ret < 0) { - tlog(TLOG_DEBUG, "decode head failed."); - return -1; - } - start = context->ptr; - - /* decode answer */ - switch (qtype) { - case DNS_T_A: { - unsigned char addr[DNS_RR_A_LEN]; - ret = _dns_decode_raw(context, addr, sizeof(addr)); - if (ret < 0) { - tlog(TLOG_ERROR, "decode A failed, %s", domain); - return -1; - } - - ret = dns_add_A(packet, type, domain, ttl, addr); - if (ret < 0) { - tlog(TLOG_ERROR, "add A failed, %s", domain); - return -1; - } - } break; - case DNS_T_CNAME: { - char cname[DNS_MAX_CNAME_LEN]; - ret = _dns_decode_CNAME(context, cname, DNS_MAX_CNAME_LEN); - if (ret < 0) { - tlog(TLOG_ERROR, "decode CNAME failed, %s", domain); - return -1; - } - - ret = dns_add_CNAME(packet, type, domain, ttl, cname); - if (ret < 0) { - tlog(TLOG_ERROR, "add CNAME failed, %s", domain); - return -1; - } - } break; - case DNS_T_SOA: { - struct dns_soa soa; - ret = _dns_decode_SOA(context, &soa); - if (ret < 0) { - tlog(TLOG_ERROR, "decode CNAME failed, %s", domain); - return -1; - } - - ret = dns_add_SOA(packet, type, domain, ttl, &soa); - if (ret < 0) { - tlog(TLOG_ERROR, "add CNAME failed, %s", domain); - return -1; - } - } break; - case DNS_T_NS: { - char ns[DNS_MAX_CNAME_LEN]; - ret = _dns_decode_CNAME(context, ns, DNS_MAX_CNAME_LEN); - if (ret < 0) { - tlog(TLOG_ERROR, "decode NS failed, %s", domain); - return -1; - } - - ret = dns_add_NS(packet, type, domain, ttl, ns); - if (ret < 0) { - tlog(TLOG_ERROR, "add NS failed, %s", domain); - return -1; - } - } break; - case DNS_T_PTR: { - char name[DNS_MAX_CNAME_LEN]; - ret = _dns_decode_CNAME(context, name, DNS_MAX_CNAME_LEN); - if (ret < 0) { - tlog(TLOG_ERROR, "decode PTR failed, %s", domain); - return -1; - } - - ret = dns_add_PTR(packet, type, domain, ttl, name); - if (ret < 0) { - tlog(TLOG_ERROR, "add PTR failed, %s", domain); - return -1; - } - } break; - case DNS_T_AAAA: { - unsigned char addr[DNS_RR_AAAA_LEN]; - ret = _dns_decode_raw(context, addr, sizeof(addr)); - if (ret < 0) { - tlog(TLOG_ERROR, "decode AAAA failed, %s", domain); - return -1; - } - - ret = dns_add_AAAA(packet, type, domain, ttl, addr); - if (ret < 0) { - tlog(TLOG_ERROR, "add AAAA failed, %s", domain); - return -1; - } - } break; - case DNS_T_OPT: { - unsigned char *opt_start = context->ptr; - ret = _dns_decode_opt(context, type, ttl, rr_len); - if (ret < 0) { - tlog(TLOG_ERROR, "decode opt failed, %s", domain); - return -1; - } - - if (context->ptr - opt_start != rr_len) { - tlog(TLOG_ERROR, "opt length mitchmatch, %s\n", domain); - return -1; - } - - dns_set_OPT_payload_size(packet, qclass); - } break; - default: - if (_dns_left_len(context) < rr_len) { - tlog(TLOG_DEBUG, "length mitchmatch\n"); - return -1; - } - context->ptr += rr_len; - tlog(TLOG_DEBUG, "DNS type = %d not supported", qtype); - break; - } - - if (context->ptr - start != rr_len) { - tlog(TLOG_ERROR, "length mitchmatch , %s, %ld:%d", domain, (long)(context->ptr - start), rr_len); - return -1; - } - - return 0; -} - -static int _dns_encode_qd(struct dns_context *context, struct dns_rrs *rrs) -{ - int ret; - int qtype = 0; - int qclass = 0; - char domain[DNS_MAX_CNAME_LEN]; - struct dns_data_context data_context; - - data_context.data = rrs->data; - data_context.ptr = rrs->data; - data_context.maxsize = rrs->len; - - ret = _dns_get_qr_head(&data_context, domain, DNS_MAX_CNAME_LEN, &qtype, &qclass); - if (ret < 0) { - return -1; - } - - ret = _dns_encode_qr_head(context, domain, qtype, qclass); - if (ret < 0) { - return -1; - } - - return 0; -} - -static int _dns_encode_an(struct dns_context *context, struct dns_rrs *rrs) -{ - int ret; - switch (rrs->type) { - case DNS_T_A: - case DNS_T_AAAA: { - ret = _dns_encode_raw(context, rrs); - if (ret < 0) { - return -1; - } - } break; - case DNS_T_CNAME: - case DNS_T_PTR: - ret = _dns_encode_CNAME(context, rrs); - if (ret < 0) { - return -1; - } - break; - case DNS_T_SOA: - ret = _dns_encode_SOA(context, rrs); - if (ret < 0) { - return -1; - } - break; - default: - break; - } - - return 0; -} - -static int _dns_decode_body(struct dns_context *context) -{ - struct dns_packet *packet = context->packet; - struct dns_head *head = &packet->head; - int i = 0; - int ret = 0; - int count = 0; - - count = head->qdcount; - head->qdcount = 0; - for (i = 0; i < count; i++) { - ret = _dns_decode_qd(context); - if (ret < 0) { - tlog(TLOG_DEBUG, "decode qd failed."); - return -1; - } - } - - count = head->ancount; - head->ancount = 0; - for (i = 0; i < count; i++) { - ret = _dns_decode_an(context, DNS_RRS_AN); - if (ret < 0) { - tlog(TLOG_DEBUG, "decode an failed."); - return -1; - } - } - - count = head->nscount; - head->nscount = 0; - for (i = 0; i < count; i++) { - ret = _dns_decode_an(context, DNS_RRS_NS); - if (ret < 0) { - tlog(TLOG_DEBUG, "decode ns failed."); - return -1; - } - } - - count = head->nrcount; - head->nrcount = 0; - for (i = 0; i < count; i++) { - ret = _dns_decode_an(context, DNS_RRS_NR); - if (ret < 0) { - tlog(TLOG_DEBUG, "decode nr failed."); - return -1; - } - } - - return 0; -} - -static int _dns_encode_body(struct dns_context *context) -{ - struct dns_packet *packet = context->packet; - struct dns_head *head = &packet->head; - int i = 0; - int len = 0; - struct dns_rrs *rrs; - int count; - - rrs = dns_get_rrs_start(packet, DNS_RRS_QD, &count); - head->qdcount = count; - for (i = 0; i < count && rrs; i++, rrs = dns_get_rrs_next(packet, rrs)) { - len = _dns_encode_qd(context, rrs); - if (len < 0) { - return -1; - } - } - - rrs = dns_get_rrs_start(packet, DNS_RRS_AN, &count); - head->ancount = count; - for (i = 0; i < count && rrs; i++, rrs = dns_get_rrs_next(packet, rrs)) { - len = _dns_encode_an(context, rrs); - if (len < 0) { - return -1; - } - } - - rrs = dns_get_rrs_start(packet, DNS_RRS_NS, &count); - head->nscount = count; - for (i = 0; i < count && rrs; i++, rrs = dns_get_rrs_next(packet, rrs)) { - len = _dns_encode_an(context, rrs); - if (len < 0) { - return -1; - } - } - - rrs = dns_get_rrs_start(packet, DNS_RRS_NR, &count); - head->nrcount = count; - for (i = 0; i < count && rrs; i++, rrs = dns_get_rrs_next(packet, rrs)) { - len = _dns_encode_an(context, rrs); - if (len < 0) { - return -1; - } - } - - rrs = dns_get_rrs_start(packet, DNS_RRS_OPT, &count); - if (count > 0 || packet->payloadsize > 0) { - len = _dns_encode_opts(packet, context, rrs, count); - if (len < 0) { - return -1; - } - head->nrcount++; - } - - return 0; -} - -int dns_packet_init(struct dns_packet *packet, int size, struct dns_head *head) -{ - struct dns_head *init_head = &packet->head; - if (size < sizeof(*packet)) { - return -1; - } - - memset(packet, 0, size); - packet->size = size; - init_head->id = head->id; - init_head->qr = head->qr; - init_head->opcode = head->opcode; - init_head->aa = head->aa; - init_head->tc = head->tc; - init_head->rd = head->rd; - init_head->ra = head->ra; - init_head->rcode = head->rcode; - packet->questions = DNS_RR_END; - packet->answers = DNS_RR_END; - packet->nameservers = DNS_RR_END; - packet->additional = DNS_RR_END; - packet->optional = DNS_RR_END; - packet->optcount = 0; - packet->payloadsize = 0; - - return 0; -} - -int dns_decode(struct dns_packet *packet, int maxsize, unsigned char *data, int size) -{ - struct dns_head *head = &packet->head; - struct dns_context context; - int ret = 0; - - memset(&context, 0, sizeof(context)); - memset(packet, 0, sizeof(*packet)); - - context.data = data; - context.packet = packet; - context.ptr = data; - context.maxsize = size; - - ret = dns_packet_init(packet, maxsize, head); - if (ret != 0) { - return -1; - } - - ret = _dns_decode_head(&context); - if (ret < 0) { - return -1; - } - - ret = _dns_decode_body(&context); - if (ret < 0) { - tlog(TLOG_DEBUG, "decode body failed.\n"); - return -1; - } - - return 0; -} - -int dns_encode(unsigned char *data, int size, struct dns_packet *packet) -{ - int ret = 0; - struct dns_context context; - - memset(&context, 0, sizeof(context)); - context.data = data; - context.packet = packet; - context.ptr = data; - context.maxsize = size; - - ret = _dns_encode_head(&context); - if (ret < 0) { - return -1; - } - - ret = _dns_encode_body(&context); - if (ret < 0) { - return -1; - } - - ret = _dns_encode_head_count(&context); - if (ret < 0) { - return -1; - } - - return context.ptr - context.data; -} - -#if 0 -static void dns_debug(void) -{ - unsigned char data[1024]; - int len; - char buff[4096]; - - int fd = open("dns.bin", O_RDWR); - if (fd < 0) { - return; - } - len = read(fd, data, 1024); - close(fd); - if (len < 0) { - return; - } - - struct dns_packet *packet = (struct dns_packet *)buff; - if (dns_decode(packet, 4096, data, len) != 0) { - tlog(TLOG_ERROR, "decode failed.\n"); - } - - memset(data, 0, sizeof(data)); - len = dns_encode(data, 1024, packet); - if (len < 0) { - tlog(TLOG_ERROR, "encode failed."); - } - - fd = open("dns-cmp.bin", O_CREAT | O_TRUNC | O_RDWR); - write(fd, data, len); - close(fd); -} -#endif +/************************************************************************* + * + * Copyright (C) 2018-2020 Ruilin Peng (Nick) . + * + * smartdns is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * smartdns is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#define _GNU_SOURCE +#include "dns.h" +#include "stringutil.h" +#include "tlog.h" +#include +#include +#include +#include +#include +#include +#include + +#define QR_MASK 0x8000 +#define OPCODE_MASK 0x7800 +#define AA_MASK 0x0400 +#define TC_MASK 0x0200 +#define RD_MASK 0x0100 +#define RA_MASK 0x0080 +#define RCODE_MASK 0x000F +#define DNS_RR_END (0XFFFF) + +#define UNUSED(expr) \ + do { \ + (void)(expr); \ + } while (0) + +/* read short and move pointer */ +static short _dns_read_short(unsigned char **buffer) +{ + unsigned short value; + + value = ntohs(*((unsigned short *)(*buffer))); + *buffer += 2; + return value; +} + +/* write char and move pointer */ +static __attribute__((unused)) void _dns_write_char(unsigned char **buffer, unsigned char value) +{ + **buffer = value; + *buffer += 1; +} + +/* read char and move pointer */ +static unsigned char _dns_read_char(unsigned char **buffer) +{ + unsigned char value = **buffer; + *buffer += 1; + return value; +} + +/* write short and move pointer */ +static void _dns_write_short(unsigned char **buffer, unsigned short value) +{ + value = htons(value); + *((unsigned short *)(*buffer)) = value; + *buffer += 2; +} + +/* write int and move pointer */ +static void _dns_write_int(unsigned char **buffer, unsigned int value) +{ + value = htonl(value); + *((unsigned int *)(*buffer)) = value; + *buffer += 4; +} + +/* read int and move pointer */ +static unsigned int _dns_read_int(unsigned char **buffer) +{ + unsigned int value; + + value = ntohl(*((unsigned int *)(*buffer))); + *buffer += 4; + + return value; +} + +/* iterator get rrs begin */ +struct dns_rrs *dns_get_rrs_start(struct dns_packet *packet, dns_rr_type type, int *count) +{ + unsigned short start; + struct dns_head *head = &packet->head; + + /* get rrs count by rrs type */ + switch (type) { + case DNS_RRS_QD: + *count = head->qdcount; + start = packet->questions; + break; + case DNS_RRS_AN: + *count = head->ancount; + start = packet->answers; + break; + case DNS_RRS_NS: + *count = head->nscount; + start = packet->nameservers; + break; + case DNS_RRS_NR: + *count = head->nrcount; + start = packet->additional; + break; + case DNS_RRS_OPT: + *count = packet->optcount; + start = packet->optional; + break; + default: + return NULL; + break; + } + + /* if not resource record, reutrn null */ + if (start == DNS_RR_END) { + return NULL; + } + + /* return rrs data start address */ + return (struct dns_rrs *)(packet->data + start); +} + +/* iterator next rrs */ +struct dns_rrs *dns_get_rrs_next(struct dns_packet *packet, struct dns_rrs *rrs) +{ + if (rrs->next == DNS_RR_END) { + return NULL; + } + + return (struct dns_rrs *)(packet->data + rrs->next); +} + +/* iterator add rrs begin */ +static unsigned char *_dns_add_rrs_start(struct dns_packet *packet, int *maxlen) +{ + struct dns_rrs *rrs; + unsigned char *end = packet->data + packet->len; + + rrs = (struct dns_rrs *)end; + *maxlen = packet->size - packet->len - sizeof(*packet) - sizeof(*rrs); + if (*maxlen <= 0) { + /* if size exceeds max packet size, return NULL */ + return NULL; + } + return rrs->data; +} + +/* iterator add rrs end */ +static int _dns_rr_add_end(struct dns_packet *packet, int type, dns_type_t rtype, int len) +{ + struct dns_rrs *rrs; + struct dns_rrs *rrs_next; + struct dns_head *head = &packet->head; + unsigned char *end = packet->data + packet->len; + unsigned short *count; + unsigned short *start; + + rrs = (struct dns_rrs *)end; + if (packet->len + len > packet->size - sizeof(*packet) - sizeof(*rrs)) { + return -1; + } + + switch (type) { + case DNS_RRS_QD: + count = &head->qdcount; + start = &packet->questions; + break; + case DNS_RRS_AN: + count = &head->ancount; + start = &packet->answers; + break; + case DNS_RRS_NS: + count = &head->nscount; + start = &packet->nameservers; + break; + case DNS_RRS_NR: + count = &head->nrcount; + start = &packet->additional; + break; + case DNS_RRS_OPT: + count = &packet->optcount; + start = &packet->optional; + break; + default: + return -1; + break; + } + + /* add data to end of dns_packet, and set previouse rrs point to this rrs */ + if (*start != DNS_RR_END) { + rrs_next = (struct dns_rrs *)(packet->data + *start); + while (rrs_next->next != DNS_RR_END) { + rrs_next = (struct dns_rrs *)(packet->data + rrs_next->next); + } + rrs_next->next = packet->len; + } else { + *start = packet->len; + } + + /* update rrs head info */ + rrs->len = len; + rrs->type = rtype; + rrs->next = DNS_RR_END; + + /* update total data length */ + *count += 1; + packet->len += len + sizeof(*rrs); + return 0; +} + +static inline int _dns_data_left_len(struct dns_data_context *data_context) +{ + /* check whether data length out of bound */ + return data_context->maxsize - (data_context->ptr - data_context->data); +} + +static int _dns_add_qr_head(struct dns_data_context *data_context, char *domain, int qtype, int qclass) +{ + /* question head */ + /* |domain | + * |qtype | qclass | + */ + while (1) { + if (_dns_data_left_len(data_context) < 4) { + return -1; + } + *data_context->ptr = *domain; + if (*domain == '\0') { + data_context->ptr++; + break; + } + data_context->ptr++; + domain++; + } + + if (_dns_data_left_len(data_context) < 4) { + return -1; + } + + *((unsigned short *)(data_context->ptr)) = qtype; + data_context->ptr += 2; + + *((unsigned short *)(data_context->ptr)) = qclass; + data_context->ptr += 2; + + return 0; +} + +static int _dns_get_qr_head(struct dns_data_context *data_context, char *domain, int maxsize, int *qtype, int *qclass) +{ + int i; + int is_read_all = 0; + /* question head */ + /* |domain | + * |qtype | qclass | + */ + for (i = 0; i < maxsize - 1; i++) { + if (_dns_data_left_len(data_context) < 4) { + return -1; + } + *domain = *data_context->ptr; + if (*data_context->ptr == '\0') { + domain++; + data_context->ptr++; + i++; + is_read_all = 1; + break; + } + *domain = *data_context->ptr; + domain++; + data_context->ptr++; + } + + *domain = '\0'; + if (is_read_all == 0) { + return -1; + } + + if (_dns_data_left_len(data_context) < 4) { + return -1; + } + + *qtype = *((unsigned short *)(data_context->ptr)); + data_context->ptr += 2; + + *qclass = *((unsigned short *)(data_context->ptr)); + data_context->ptr += 2; + + return 0; +} + +static int _dns_add_rr_head(struct dns_data_context *data_context, char *domain, int qtype, int qclass, int ttl, + int rr_len) +{ + int len = 0; + + /* resource record head */ + /* |domain | + * |qtype | qclass | + * | ttl | + * | rrlen | rrdata | + */ + len = _dns_add_qr_head(data_context, domain, qtype, qclass); + if (len < 0) { + return -1; + } + + if (_dns_data_left_len(data_context) < 6) { + return -1; + } + + *((unsigned int *)(data_context->ptr)) = ttl; + data_context->ptr += 4; + + *((unsigned short *)(data_context->ptr)) = rr_len; + data_context->ptr += 2; + + return 0; +} + +static int _dns_get_rr_head(struct dns_data_context *data_context, char *domain, int maxsize, int *qtype, int *qclass, + int *ttl, int *rr_len) +{ + int len = 0; + + /* resource record head */ + /* |domain | + * |qtype | qclass | + * | ttl | + * | rrlen | rrdata | + */ + len = _dns_get_qr_head(data_context, domain, maxsize, qtype, qclass); + + if (_dns_data_left_len(data_context) < 6) { + return -1; + } + + *ttl = *((unsigned int *)(data_context->ptr)); + data_context->ptr += 4; + + *rr_len = *((unsigned short *)(data_context->ptr)); + data_context->ptr += 2; + + return len; +} + +static int _dns_add_RAW(struct dns_packet *packet, dns_rr_type rrtype, dns_type_t rtype, char *domain, int ttl, + void *raw, int raw_len) +{ + int maxlen = 0; + int len = 0; + struct dns_data_context data_context; + + /* resource record */ + /* |domain | + * |qtype | qclass | + * | ttl | + * | rrlen | rrdata | + */ + unsigned char *data = _dns_add_rrs_start(packet, &maxlen); + if (data == NULL) { + return -1; + } + + if (raw_len >= maxlen) { + return -1; + } + + data_context.data = data; + data_context.ptr = data; + data_context.maxsize = maxlen; + + /* add rr head */ + len = _dns_add_rr_head(&data_context, domain, rtype, DNS_C_IN, ttl, raw_len); + if (len < 0) { + return -1; + } + + /* add rr data */ + memcpy(data_context.ptr, raw, raw_len); + data_context.ptr += raw_len; + len = data_context.ptr - data_context.data; + + return _dns_rr_add_end(packet, rrtype, rtype, len); +} + +static int _dns_get_RAW(struct dns_rrs *rrs, char *domain, int maxsize, int *ttl, void *raw, int *raw_len) +{ + int qtype = 0; + int qclass = 0; + int rr_len = 0; + int ret = 0; + struct dns_data_context data_context; + + /* resource record head */ + /* |domain | + * |qtype | qclass | + * | ttl | + * | rrlen | rrdata | + */ + unsigned char *data = rrs->data; + + data_context.data = data; + data_context.ptr = data; + data_context.maxsize = rrs->len; + + /* get rr head */ + ret = _dns_get_rr_head(&data_context, domain, maxsize, &qtype, &qclass, ttl, &rr_len); + if (ret < 0) { + return -1; + } + + if (qtype != rrs->type || rr_len > *raw_len) { + return -1; + } + + /* get rr data */ + memcpy(raw, data_context.ptr, rr_len); + data_context.ptr += rr_len; + *raw_len = rr_len; + + return 0; +} + +static int _dns_add_opt_RAW(struct dns_packet *packet, dns_opt_code_t opt_rrtype, void *raw, int raw_len) +{ + unsigned char opt_data[DNS_MAX_OPT_LEN]; + struct dns_opt *opt = (struct dns_opt *)opt_data; + int len = 0; + + opt->code = DNS_OPT_T_TCP_KEEPALIVE; + opt->length = sizeof(unsigned short); + + memcpy(opt->data, raw, raw_len); + len += raw_len; + len += sizeof(*opt); + + return _dns_add_RAW(packet, DNS_RRS_OPT, DNS_OPT_T_TCP_KEEPALIVE, "", 0, opt_data, len); +} + +static int _dns_get_opt_RAW(struct dns_rrs *rrs, char *domain, int maxsize, int *ttl, struct dns_opt *dns_opt, + int *dns_optlen) +{ + *dns_optlen = DNS_MAX_OPT_LEN; + + return _dns_get_RAW(rrs, domain, maxsize, ttl, dns_opt, dns_optlen); +} + +static int __attribute__((unused)) _dns_add_OPT(struct dns_packet *packet, dns_rr_type type, unsigned short opt_code, + unsigned short opt_len, struct dns_opt *opt) +{ + // TODO + + int maxlen = 0; + int len = 0; + struct dns_data_context data_context; + int total_len = sizeof(*opt) + opt->length; + int ttl = 0; + + /* + +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ + 0: | OPTION-CODE | + +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ + 2: | OPTION-LENGTH | + +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ + 4: | | + / OPTION-DATA / + / / + +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ + */ + unsigned char *data = _dns_add_rrs_start(packet, &maxlen); + if (data == NULL) { + return -1; + } + + if (total_len > maxlen) { + return -1; + } + + data_context.data = data; + data_context.ptr = data; + data_context.maxsize = maxlen; + + ttl = (opt_code << 16) | opt_len; + + /* add rr head */ + len = _dns_add_rr_head(&data_context, "", type, DNS_C_IN, ttl, total_len); + if (len < 0) { + return -1; + } + + /* add rr data */ + memcpy(data_context.ptr, opt, total_len); + data_context.ptr += total_len; + len = data_context.ptr - data_context.data; + + return _dns_rr_add_end(packet, type, DNS_T_OPT, len); +} + +static int __attribute__((unused)) _dns_get_OPT(struct dns_rrs *rrs, unsigned short *opt_code, unsigned short *opt_len, + struct dns_opt *opt, int *opt_maxlen) +{ + // TODO + + int qtype = 0; + int qclass = 0; + int rr_len = 0; + int ret = 0; + struct dns_data_context data_context; + char domain[DNS_MAX_CNAME_LEN]; + int maxsize = DNS_MAX_CNAME_LEN; + int ttl = 0; + unsigned char *data = rrs->data; + + data_context.data = data; + data_context.ptr = data; + data_context.maxsize = rrs->len; + + /* get rr head */ + ret = _dns_get_rr_head(&data_context, domain, maxsize, &qtype, &qclass, &ttl, &rr_len); + if (ret < 0) { + return -1; + } + + if (qtype != rrs->type || rr_len > *opt_len) { + return -1; + } + + /* get rr data */ + *opt_code = ttl >> 16; + *opt_len = ttl & 0xFFFF; + memcpy(opt, data_context.ptr, rr_len); + data_context.ptr += rr_len; + *opt_maxlen = rr_len; + + return 0; +} + +int dns_add_CNAME(struct dns_packet *packet, dns_rr_type type, char *domain, int ttl, char *cname) +{ + int rr_len = strnlen(cname, DNS_MAX_CNAME_LEN) + 1; + return _dns_add_RAW(packet, type, DNS_T_CNAME, domain, ttl, cname, rr_len); +} + +int dns_get_CNAME(struct dns_rrs *rrs, char *domain, int maxsize, int *ttl, char *cname, int cname_size) +{ + int len = cname_size; + return _dns_get_RAW(rrs, domain, maxsize, ttl, cname, &len); +} + +int dns_add_A(struct dns_packet *packet, dns_rr_type type, char *domain, int ttl, unsigned char addr[DNS_RR_A_LEN]) +{ + return _dns_add_RAW(packet, type, DNS_T_A, domain, ttl, addr, DNS_RR_A_LEN); +} + +int dns_get_A(struct dns_rrs *rrs, char *domain, int maxsize, int *ttl, unsigned char addr[DNS_RR_A_LEN]) +{ + int len = DNS_RR_A_LEN; + return _dns_get_RAW(rrs, domain, maxsize, ttl, addr, &len); +} + +int dns_add_PTR(struct dns_packet *packet, dns_rr_type type, char *domain, int ttl, char *cname) +{ + int rr_len = strnlen(cname, DNS_MAX_CNAME_LEN) + 1; + return _dns_add_RAW(packet, type, DNS_T_PTR, domain, ttl, cname, rr_len); +} + +int dns_get_PTR(struct dns_rrs *rrs, char *domain, int maxsize, int *ttl, char *cname, int cname_size) +{ + int len = cname_size; + return _dns_get_RAW(rrs, domain, maxsize, ttl, cname, &len); +} + +int dns_add_NS(struct dns_packet *packet, dns_rr_type type, char *domain, int ttl, char *cname) +{ + int rr_len = strnlen(cname, DNS_MAX_CNAME_LEN) + 1; + return _dns_add_RAW(packet, type, DNS_T_NS, domain, ttl, cname, rr_len); +} + +int dns_get_NS(struct dns_rrs *rrs, char *domain, int maxsize, int *ttl, char *cname, int cname_size) +{ + int len = cname_size; + return _dns_get_RAW(rrs, domain, maxsize, ttl, cname, &len); +} + +int dns_add_AAAA(struct dns_packet *packet, dns_rr_type type, char *domain, int ttl, + unsigned char addr[DNS_RR_AAAA_LEN]) +{ + return _dns_add_RAW(packet, type, DNS_T_AAAA, domain, ttl, addr, DNS_RR_AAAA_LEN); +} + +int dns_get_AAAA(struct dns_rrs *rrs, char *domain, int maxsize, int *ttl, unsigned char addr[DNS_RR_AAAA_LEN]) +{ + int len = DNS_RR_AAAA_LEN; + return _dns_get_RAW(rrs, domain, maxsize, ttl, addr, &len); +} + +int dns_add_SOA(struct dns_packet *packet, dns_rr_type type, char *domain, int ttl, struct dns_soa *soa) +{ + /* SOA */ + /*| mname | + *| rname | + *| serial | + *| refersh | + *| retry | + *| expire | + *| minimum | + */ + unsigned char data[sizeof(*soa)]; + unsigned char *ptr = data; + int len = 0; + safe_strncpy((char *)ptr, soa->mname, DNS_MAX_CNAME_LEN); + ptr += strnlen(soa->mname, DNS_MAX_CNAME_LEN - 1) + 1; + safe_strncpy((char *)ptr, soa->rname, DNS_MAX_CNAME_LEN); + ptr += strnlen(soa->rname, DNS_MAX_CNAME_LEN - 1) + 1; + memcpy(ptr, &soa->serial, sizeof(unsigned int)); + ptr += 4; + memcpy(ptr, &soa->refresh, sizeof(unsigned int)); + ptr += 4; + memcpy(ptr, &soa->retry, sizeof(unsigned int)); + ptr += 4; + memcpy(ptr, &soa->expire, sizeof(unsigned int)); + ptr += 4; + memcpy(ptr, &soa->minimum, sizeof(unsigned int)); + ptr += 4; + len = ptr - data; + + return _dns_add_RAW(packet, type, DNS_T_SOA, domain, ttl, data, len); +} + +int dns_get_SOA(struct dns_rrs *rrs, char *domain, int maxsize, int *ttl, struct dns_soa *soa) +{ + unsigned char data[sizeof(*soa)]; + unsigned char *ptr = data; + int len = sizeof(data); + + /* SOA */ + /*| mname | + *| rname | + *| serial | + *| refersh | + *| retry | + *| expire | + *| minimum | + */ + if (_dns_get_RAW(rrs, domain, maxsize, ttl, data, &len) != 0) { + return -1; + } + + safe_strncpy(soa->mname, (char *)ptr, DNS_MAX_CNAME_LEN - 1); + ptr += strnlen(soa->mname, DNS_MAX_CNAME_LEN - 1) + 1; + if (ptr - data >= len) { + return -1; + } + safe_strncpy(soa->rname, (char *)ptr, DNS_MAX_CNAME_LEN - 1); + ptr += strnlen(soa->rname, DNS_MAX_CNAME_LEN - 1) + 1; + if (ptr - data + 20 > len) { + return -1; + } + soa->serial = *((unsigned int *)ptr); + ptr += 4; + soa->refresh = *((unsigned int *)ptr); + ptr += 4; + soa->retry = *((unsigned int *)ptr); + ptr += 4; + soa->expire = *((unsigned int *)ptr); + ptr += 4; + soa->minimum = *((unsigned int *)ptr); + ptr += 4; + + return 0; +} + +int dns_set_OPT_payload_size(struct dns_packet *packet, int payload_size) +{ + if (payload_size < 512) { + payload_size = 512; + } + + packet->payloadsize = payload_size; + return 0; +} + +int dns_get_OPT_payload_size(struct dns_packet *packet) +{ + return packet->payloadsize; +} + +int dns_add_OPT_ECS(struct dns_packet *packet, struct dns_opt_ecs *ecs) +{ + unsigned char opt_data[DNS_MAX_OPT_LEN]; + struct dns_opt *opt = (struct dns_opt *)opt_data; + int len = 0; + + opt->code = DNS_OPT_T_ECS; + opt->length = sizeof(*ecs); + memcpy(opt->data, ecs, sizeof(*ecs)); + + /* ecs size 4 + bit of address*/ + len = sizeof(*opt) + 4; + len += (ecs->source_prefix / 8); + len += (ecs->source_prefix % 8 > 0) ? 1 : 0; + + return _dns_add_RAW(packet, DNS_RRS_OPT, DNS_OPT_T_ECS, "", 0, opt_data, len); +} + +int dns_get_OPT_ECS(struct dns_rrs *rrs, unsigned short *opt_code, unsigned short *opt_len, struct dns_opt_ecs *ecs) +{ + unsigned char opt_data[DNS_MAX_OPT_LEN]; + struct dns_opt *opt = (struct dns_opt *)opt_data; + int len = DNS_MAX_OPT_LEN; + int ttl = 0; + + if (_dns_get_RAW(rrs, NULL, 0, &ttl, opt_data, &len) != 0) { + return -1; + } + + if (len < sizeof(*opt)) { + return -1; + } + + if (opt->code != DNS_OPT_T_ECS) { + return -1; + } + + memcpy(ecs, opt->data, opt->length); + + return 0; +} + +int dns_add_OPT_TCP_KEEYALIVE(struct dns_packet *packet, unsigned short timeout) +{ + unsigned short timeout_net = htons(timeout); + int data_len = 0; + + if (timeout > 0) { + data_len = sizeof(timeout); + } + + return _dns_add_opt_RAW(packet, DNS_OPT_T_TCP_KEEPALIVE, &timeout_net, data_len); +} + +int dns_get_OPT_TCP_KEEYALIVE(struct dns_rrs *rrs, unsigned short *opt_code, unsigned short *opt_len, + unsigned short *timeout) +{ + unsigned char opt_data[DNS_MAX_OPT_LEN]; + struct dns_opt *opt = (struct dns_opt *)opt_data; + int len = DNS_MAX_OPT_LEN; + int ttl = 0; + unsigned char *data = NULL; + + if (_dns_get_opt_RAW(rrs, NULL, 0, &ttl, opt, &len) != 0) { + return -1; + } + + if (len < sizeof(*opt)) { + return -1; + } + + if (opt->code != DNS_OPT_T_TCP_KEEPALIVE) { + return -1; + } + + if (opt->length == 0) { + *timeout = 0; + return 0; + } + + if (opt->length != sizeof(unsigned short)) { + return -1; + } + + data = opt->data; + + *timeout = _dns_read_short(&data); + + return 0; +} + +/* + * Format: + * |DNS_NAME\0(string)|qtype(short)|qclass(short)| + */ +int dns_add_domain(struct dns_packet *packet, char *domain, int qtype, int qclass) +{ + int len = 0; + int maxlen = 0; + unsigned char *data = _dns_add_rrs_start(packet, &maxlen); + struct dns_data_context data_context; + + if (data == NULL) { + return -1; + } + + data_context.data = data; + data_context.ptr = data; + data_context.maxsize = maxlen; + + len = _dns_add_qr_head(&data_context, domain, qtype, qclass); + if (len < 0) { + return -1; + } + + len = data_context.ptr - data_context.data; + + return _dns_rr_add_end(packet, DNS_RRS_QD, DNS_T_CNAME, len); +} + +int dns_get_domain(struct dns_rrs *rrs, char *domain, int maxsize, int *qtype, int *qclass) +{ + struct dns_data_context data_context; + unsigned char *data = rrs->data; + + if (rrs->type != DNS_T_CNAME) { + return -1; + } + + data_context.data = data; + data_context.ptr = data; + data_context.maxsize = rrs->len; + + return _dns_get_qr_head(&data_context, domain, maxsize, qtype, qclass); +} + +static inline int _dns_left_len(struct dns_context *context) +{ + return context->maxsize - (context->ptr - context->data); +} + +static int _dns_decode_head(struct dns_context *context) +{ + unsigned int fields; + int len = 12; + struct dns_head *head = &context->packet->head; + + if (_dns_left_len(context) < len) { + return -1; + } + + /* + 0 1 2 3 4 5 6 7 8 9 A B C D E F + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + | ID | + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + |QR| Opcode |AA|TC|RD|RA| Z | RCODE | + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + | QDCOUNT | + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + | ANCOUNT | + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + | NSCOUNT | + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + | ARCOUNT | + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + */ + + head->id = _dns_read_short(&context->ptr); + fields = _dns_read_short(&context->ptr); + head->qr = (fields & QR_MASK) >> 15; + head->opcode = (fields & OPCODE_MASK) >> 11; + head->aa = (fields & AA_MASK) >> 10; + head->tc = (fields & TC_MASK) >> 9; + head->rd = (fields & RD_MASK) >> 8; + head->ra = (fields & RA_MASK) >> 7; + head->rcode = (fields & RCODE_MASK) >> 0; + head->qdcount = _dns_read_short(&context->ptr); + head->ancount = _dns_read_short(&context->ptr); + head->nscount = _dns_read_short(&context->ptr); + head->nrcount = _dns_read_short(&context->ptr); + + return 0; +} + +static int _dns_encode_head(struct dns_context *context) +{ + int len = 12; + struct dns_head *head = &context->packet->head; + + if (_dns_left_len(context) < len) { + return -1; + } + + _dns_write_short(&context->ptr, head->id); + + int fields = 0; + fields |= (head->qr << 15) & QR_MASK; + fields |= (head->opcode << 11) & OPCODE_MASK; + fields |= (head->aa << 10) & AA_MASK; + fields |= (head->tc << 9) & TC_MASK; + fields |= (head->rd << 8) & RD_MASK; + fields |= (head->ra << 7) & RA_MASK; + fields |= (head->rcode << 0) & RCODE_MASK; + _dns_write_short(&context->ptr, fields); + + _dns_write_short(&context->ptr, head->qdcount); + _dns_write_short(&context->ptr, head->ancount); + _dns_write_short(&context->ptr, head->nscount); + _dns_write_short(&context->ptr, head->nrcount); + return len; +} + +static int _dns_encode_head_count(struct dns_context *context) +{ + int len = 12; + struct dns_head *head = &context->packet->head; + unsigned char *ptr = context->data; + + ptr += 4; + _dns_write_short(&ptr, head->qdcount); + _dns_write_short(&ptr, head->ancount); + _dns_write_short(&ptr, head->nscount); + _dns_write_short(&ptr, head->nrcount); + return len; +} + +static int _dns_decode_domain(struct dns_context *context, char *output, int size) +{ + int output_len = 0; + int copy_len = 0; + int len = 0; + unsigned char *ptr = context->ptr; + int is_compressed = 0; + int ptr_jump = 0; + + /*[len]string[len]string...[0]0 */ + while (1) { + if (ptr > context->data + context->maxsize || ptr < context->data || output_len >= size - 1 || ptr_jump > 4) { + return -1; + } + + len = *ptr; + if (len == 0) { + *output = 0; + ptr++; + break; + } + + /* compressed domain */ + if (len >= 0xC0) { + if ((ptr + 2) > (context->data + context->maxsize)) { + return -1; + } + /* + 0 1 2 3 4 5 6 7 8 9 A B C D E F + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + | 1 1| OFFSET | + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + */ + /* read offset */ + len = _dns_read_short(&ptr) & 0x3FFF; + if (is_compressed == 0) { + context->ptr = ptr; + } + ptr = context->data + len; + if (ptr > context->data + context->maxsize) { + tlog(TLOG_DEBUG, "length is not enough %u:%ld, %p, %p", context->maxsize, (long)(ptr - context->data), + context->ptr, context->data); + return -1; + } + is_compressed = 1; + ptr_jump++; + continue; + } + + ptr_jump = 0; + + /* change [len] to '.' */ + if (output_len > 0) { + *output = '.'; + output++; + output_len += 1; + } + + if (ptr > context->data + context->maxsize) { + tlog(TLOG_DEBUG, "length is not enough %u:%ld, %p, %p", context->maxsize, (long)(ptr - context->data), + context->ptr, context->data); + return -1; + } + + ptr++; + if (output_len < size - 1) { + /* copy sub string */ + copy_len = (len < size - output_len) ? len : size - 1 - output_len; + if ((ptr + copy_len) > (context->data + context->maxsize)) { + tlog(TLOG_DEBUG, "length is not enough %u:%ld, %p, %p", context->maxsize, (long)(ptr - context->data), + context->ptr, context->data); + return -1; + } + memcpy(output, ptr, copy_len); + } + + ptr += len; + output += len; + output_len += len; + } + + if (is_compressed == 0) { + context->ptr = ptr; + } + + return 0; +} + +static int _dns_encode_domain(struct dns_context *context, char *domain) +{ + int num = 0; + int total_len = 0; + unsigned char *ptr_num = context->ptr++; + + /*[len]string[len]string...[0]0 */ + while (_dns_left_len(context) > 1 && *domain != 0) { + if (*domain == '.') { + *ptr_num = num; + num = 0; + ptr_num = context->ptr; + domain++; + context->ptr++; + continue; + } + *context->ptr = *domain; + num++; + context->ptr++; + domain++; + total_len++; + } + + *ptr_num = num; + if (total_len > 0) { + /* if domain is '\0', [domain] is '\0' */ + *(context->ptr) = 0; + context->ptr++; + } + return 0; +} + +static int _dns_decode_qr_head(struct dns_context *context, char *domain, int domain_size, int *qtype, int *qclass) +{ + int ret = 0; + /* + 0 1 2 3 4 5 6 7 8 9 A B C D E F + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + | | + / / + / NAME / + | | + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + | TYPE | + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + | CLASS | + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + */ + ret = _dns_decode_domain(context, domain, domain_size); + if (ret < 0) { + tlog(TLOG_DEBUG, "decode domain failed."); + return -1; + } + + if (_dns_left_len(context) < 4) { + tlog(TLOG_DEBUG, "left length is not enough, %s.", domain); + return -1; + } + + *qtype = _dns_read_short(&context->ptr); + *qclass = _dns_read_short(&context->ptr); + + return 0; +} + +static int _dns_encode_qr_head(struct dns_context *context, char *domain, int qtype, int qclass) +{ + int ret = 0; + ret = _dns_encode_domain(context, domain); + if (ret < 0) { + return -1; + } + + if (_dns_left_len(context) < 4) { + return -1; + } + + _dns_write_short(&context->ptr, qtype); + _dns_write_short(&context->ptr, qclass); + + return 0; +} + +static int _dns_decode_rr_head(struct dns_context *context, char *domain, int domain_size, int *qtype, int *qclass, + int *ttl, int *rr_len) +{ + int len = 0; + + len = _dns_decode_qr_head(context, domain, domain_size, qtype, qclass); + if (len < 0) { + tlog(TLOG_DEBUG, "decode qr head failed."); + return -1; + } + + if (_dns_left_len(context) < 6) { + tlog(TLOG_DEBUG, "left length is not enough."); + return -1; + } + + *ttl = _dns_read_int(&context->ptr); + *rr_len = _dns_read_short(&context->ptr); + + return 0; +} + +static int _dns_encode_rr_head(struct dns_context *context, char *domain, int qtype, int qclass, int ttl, int rr_len) +{ + int ret = 0; + ret = _dns_encode_qr_head(context, domain, qtype, qclass); + if (ret < 0) { + return -1; + } + + if (_dns_left_len(context) < 6) { + return -1; + } + + _dns_write_int(&context->ptr, ttl); + _dns_write_short(&context->ptr, rr_len); + + return 0; +} + +static int _dns_encode_raw(struct dns_context *context, struct dns_rrs *rrs) +{ + int ret; + int qtype = 0; + int qclass = 0; + int ttl = 0; + char domain[DNS_MAX_CNAME_LEN]; + int rr_len; + struct dns_data_context data_context; + /* + 0 1 2 3 4 5 6 7 8 9 A B C D E F + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + | | + / / + / NAME / + | | + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + | TYPE | + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + | CLASS | + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + | TTL | + | | + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + | RDLENGTH | + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--| + / RDATA / + / / + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + */ + + data_context.data = rrs->data; + data_context.ptr = rrs->data; + data_context.maxsize = rrs->len; + + ret = _dns_get_rr_head(&data_context, domain, DNS_MAX_CNAME_LEN, &qtype, &qclass, &ttl, &rr_len); + if (ret < 0) { + return -1; + } + + ret = _dns_encode_rr_head(context, domain, qtype, qclass, ttl, rr_len); + if (ret < 0) { + return -1; + } + + if (_dns_left_len(context) < rr_len) { + return -1; + } + + memcpy(context->ptr, data_context.ptr, rr_len); + context->ptr += rr_len; + data_context.ptr += rr_len; + + return 0; +} + +static int _dns_decode_raw(struct dns_context *context, unsigned char *raw, int len) +{ + if (_dns_left_len(context) < len) { + return -1; + } + + memcpy(raw, context->ptr, len); + context->ptr += len; + return 0; +} + +static int _dns_decode_CNAME(struct dns_context *context, char *cname, int cname_size) +{ + int ret = 0; + ret = _dns_decode_domain(context, cname, cname_size); + if (ret < 0) { + return -1; + } + + return 0; +} + +static int _dns_encode_CNAME(struct dns_context *context, struct dns_rrs *rrs) +{ + int ret; + int qtype = 0; + int qclass = 0; + int ttl = 0; + char domain[DNS_MAX_CNAME_LEN]; + int rr_len; + struct dns_data_context data_context; + + data_context.data = rrs->data; + data_context.ptr = rrs->data; + data_context.maxsize = rrs->len; + + ret = _dns_get_rr_head(&data_context, domain, DNS_MAX_CNAME_LEN, &qtype, &qclass, &ttl, &rr_len); + if (ret < 0) { + return -1; + } + + /* when code domain, len must plus 1, because of length at the begining */ + rr_len++; + if (rr_len > rrs->len) { + return -1; + } + + ret = _dns_encode_rr_head(context, domain, qtype, qclass, ttl, rr_len); + if (ret < 0) { + return -1; + } + + ret = _dns_encode_domain(context, (char *)data_context.ptr); + if (ret < 0) { + return -1; + } + + data_context.ptr += strnlen((char *)(data_context.ptr), DNS_MAX_CNAME_LEN) + 1; + + return 0; +} + +static int _dns_decode_SOA(struct dns_context *context, struct dns_soa *soa) +{ + int ret = 0; + ret = _dns_decode_domain(context, soa->mname, DNS_MAX_CNAME_LEN - 1); + if (ret < 0) { + return -1; + } + + ret = _dns_decode_domain(context, soa->rname, DNS_MAX_CNAME_LEN - 1); + if (ret < 0) { + return -1; + } + + if (_dns_left_len(context) < 20) { + return -1; + } + + soa->serial = _dns_read_int(&context->ptr); + soa->refresh = _dns_read_int(&context->ptr); + soa->retry = _dns_read_int(&context->ptr); + soa->expire = _dns_read_int(&context->ptr); + soa->minimum = _dns_read_int(&context->ptr); + + return 0; +} + +static int _dns_encode_SOA(struct dns_context *context, struct dns_rrs *rrs) +{ + int ret; + int qtype = 0; + int qclass = 0; + int ttl = 0; + char domain[DNS_MAX_CNAME_LEN]; + int rr_len; + struct dns_data_context data_context; + + data_context.data = rrs->data; + data_context.ptr = rrs->data; + data_context.maxsize = rrs->len; + + ret = _dns_get_rr_head(&data_context, domain, DNS_MAX_CNAME_LEN, &qtype, &qclass, &ttl, &rr_len); + if (ret < 0) { + return -1; + } + + /* when code two domain, len must plus 2, because of length at the begining */ + rr_len += 2; + if (rr_len > rrs->len) { + return -1; + } + + ret = _dns_encode_rr_head(context, domain, qtype, qclass, ttl, rr_len); + if (ret < 0) { + return -1; + } + + /* mname */ + ret = _dns_encode_domain(context, (char *)data_context.ptr); + if (ret < 0) { + return -1; + } + + data_context.ptr += strnlen((char *)(data_context.ptr), DNS_MAX_CNAME_LEN) + 1; + + /* rname */ + ret = _dns_encode_domain(context, (char *)data_context.ptr); + if (ret < 0) { + return -1; + } + + data_context.ptr += strnlen((char *)(data_context.ptr), DNS_MAX_CNAME_LEN) + 1; + + if (_dns_left_len(context) < 20) { + return -1; + } + + _dns_write_int(&context->ptr, *(unsigned int *)data_context.ptr); + data_context.ptr += 4; + _dns_write_int(&context->ptr, *(unsigned int *)data_context.ptr); + data_context.ptr += 4; + _dns_write_int(&context->ptr, *(unsigned int *)data_context.ptr); + data_context.ptr += 4; + _dns_write_int(&context->ptr, *(unsigned int *)data_context.ptr); + data_context.ptr += 4; + _dns_write_int(&context->ptr, *(unsigned int *)data_context.ptr); + data_context.ptr += 4; + + return 0; +} + +static int _dns_decode_opt_ecs(struct dns_context *context, struct dns_opt_ecs *ecs) +{ + // TODO + + int len = 0; + if (_dns_left_len(context) < 4) { + return -1; + } + + ecs->family = _dns_read_short(&context->ptr); + ecs->source_prefix = _dns_read_char(&context->ptr); + ecs->scope_prefix = _dns_read_char(&context->ptr); + len = (ecs->source_prefix / 8); + len += (ecs->source_prefix % 8 > 0) ? 1 : 0; + + if (_dns_left_len(context) < len) { + return -1; + } + + memcpy(ecs->addr, context->ptr, len); + context->ptr += len; + + tlog(TLOG_DEBUG, "ECS: family:%d, source_prefix:%d, scope_prefix:%d, len:%d", ecs->family, ecs->source_prefix, + ecs->scope_prefix, len); + tlog(TLOG_DEBUG, "%d.%d.%d.%d", ecs->addr[0], ecs->addr[1], ecs->addr[2], ecs->addr[3]); + + return 0; +} + +static int _dns_encode_OPT(struct dns_context *context, struct dns_rrs *rrs) +{ + int ret; + int opt_code = 0; + int qclass = 0; + char domain[DNS_MAX_CNAME_LEN]; + struct dns_data_context data_context; + int rr_len = 0; + int ttl; + struct dns_opt *dns_opt = NULL; + + data_context.data = rrs->data; + data_context.ptr = rrs->data; + data_context.maxsize = rrs->len; + + ret = _dns_get_rr_head(&data_context, domain, DNS_MAX_CNAME_LEN, &opt_code, &qclass, &ttl, &rr_len); + if (ret < 0) { + return -1; + } + + if (rr_len < sizeof(*dns_opt)) { + return -1; + } + + if (_dns_left_len(context) < (rr_len)) { + return -1; + } + + dns_opt = (struct dns_opt *)data_context.ptr; + _dns_write_short(&context->ptr, dns_opt->code); + _dns_write_short(&context->ptr, dns_opt->length); + + if (_dns_left_len(context) < dns_opt->length) { + return -1; + } + + memcpy(context->ptr, dns_opt->data, dns_opt->length); + context->ptr += dns_opt->length; + + return 0; +} + +static int _dns_get_opts_data_len(struct dns_packet *packet, struct dns_rrs *rrs, int count) +{ + int i = 0; + int len = 0; + int opt_code = 0; + int qclass = 0; + int ttl; + int ret; + char domain[DNS_MAX_CNAME_LEN]; + struct dns_data_context data_context; + int rr_len = 0; + + for (i = 0; i < count && rrs; i++, rrs = dns_get_rrs_next(packet, rrs)) { + data_context.data = rrs->data; + data_context.ptr = rrs->data; + data_context.maxsize = rrs->len; + + ret = _dns_get_rr_head(&data_context, domain, DNS_MAX_CNAME_LEN, &opt_code, &qclass, &ttl, &rr_len); + if (ret < 0) { + return -1; + } + + len += rr_len; + } + + return len; +} + +static int _dns_encode_opts(struct dns_packet *packet, struct dns_context *context, struct dns_rrs *rrs, int count) +{ + int i = 0; + int len = 0; + int ret = 0; + unsigned int rcode = 0; + int rr_len = 0; + int payloadsize = packet->payloadsize; + + rr_len = _dns_get_opts_data_len(packet, rrs, count); + if (rr_len < 0) { + return -1; + } + + if (payloadsize < DNS_DEFAULT_PACKET_SIZE) { + payloadsize = DNS_DEFAULT_PACKET_SIZE; + } + + ret = _dns_encode_rr_head(context, "", DNS_T_OPT, payloadsize, rcode, rr_len); + if (ret < 0) { + return -1; + } + + if (_dns_left_len(context) < rr_len) { + return -1; + } + + for (i = 0; i < count && rrs; i++, rrs = dns_get_rrs_next(packet, rrs)) { + len = _dns_encode_OPT(context, rrs); + if (len < 0) { + return -1; + } + } + + return 0; +} + +static int _dns_decode_opt(struct dns_context *context, dns_rr_type type, unsigned int ttl, int rr_len) +{ + unsigned short opt_code; + unsigned short opt_len; + unsigned short ercode = (ttl >> 16) & 0xFFFF; + unsigned short ever = (ttl)&0xFFFF; + unsigned char *start = context->ptr; + struct dns_packet *packet = context->packet; + int ret = 0; + + UNUSED(ever); + + /* + Field Name Field Type Description + ------------------------------------------------------ + NAME domain name empty (root domain) + TYPE u_int16_t OPT + CLASS u_int16_t sender's UDP payload size + TTL u_int32_t extended RCODE and flags + RDLEN u_int16_t describes RDATA + RDATA octet stream {attribute,value} pairs + + +0 (MSB) +1 (LSB) + +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ + 0: | OPTION-CODE | + +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ + 2: | OPTION-LENGTH | + +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ + 4: | | + / OPTION-DATA / + / / + +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ + + TTL + +0 (MSB) +1 (LSB) + +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ + 0: | EXTENDED-RCODE | VERSION | + +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ + 2: | Z | + +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ + */ + + if (ercode != 0) { + tlog(TLOG_ERROR, "extend rcode invalid."); + return -1; + } + + while (context->ptr - start < rr_len) { + if (_dns_left_len(context) < 4) { + return -1; + } + opt_code = _dns_read_short(&context->ptr); + opt_len = _dns_read_short(&context->ptr); + + if (_dns_left_len(context) < opt_len) { + tlog(TLOG_ERROR, "read opt data failed, opt_code = %d, opt_le = %d", opt_code, opt_len); + return -1; + } + + tlog(TLOG_DEBUG, "opt type %d", opt_code); + switch (opt_code) { + case DNS_OPT_T_ECS: { + struct dns_opt_ecs ecs; + ret = _dns_decode_opt_ecs(context, &ecs); + if (ret != 0) { + tlog(TLOG_ERROR, "decode ecs failed."); + return -1; + } + + ret = dns_add_OPT_ECS(packet, &ecs); + if (ret != 0) { + tlog(TLOG_ERROR, "add ecs failed."); + return -1; + } + } break; + default: + context->ptr += opt_len; + tlog(TLOG_DEBUG, "DNS opt type = %d not supported", opt_code); + break; + } + } + + return 0; +} + +static int _dns_decode_qd(struct dns_context *context) +{ + struct dns_packet *packet = context->packet; + int len; + int qtype = 0; + int qclass = 0; + char domain[DNS_MAX_CNAME_LEN]; + + len = _dns_decode_qr_head(context, domain, DNS_MAX_CNAME_LEN, &qtype, &qclass); + if (len < 0) { + return -1; + } + + len = dns_add_domain(packet, domain, qtype, qclass); + if (len < 0) { + return -1; + } + + return 0; +} + +static int _dns_decode_an(struct dns_context *context, dns_rr_type type) +{ + int ret; + int qtype = 0; + int qclass = 0; + int ttl; + int rr_len = 0; + char domain[DNS_MAX_CNAME_LEN]; + struct dns_packet *packet = context->packet; + unsigned char *start; + + /* decode rr head */ + ret = _dns_decode_rr_head(context, domain, DNS_MAX_CNAME_LEN, &qtype, &qclass, &ttl, &rr_len); + if (ret < 0) { + tlog(TLOG_DEBUG, "decode head failed."); + return -1; + } + start = context->ptr; + + /* decode answer */ + switch (qtype) { + case DNS_T_A: { + unsigned char addr[DNS_RR_A_LEN]; + ret = _dns_decode_raw(context, addr, sizeof(addr)); + if (ret < 0) { + tlog(TLOG_ERROR, "decode A failed, %s", domain); + return -1; + } + + ret = dns_add_A(packet, type, domain, ttl, addr); + if (ret < 0) { + tlog(TLOG_ERROR, "add A failed, %s", domain); + return -1; + } + } break; + case DNS_T_CNAME: { + char cname[DNS_MAX_CNAME_LEN]; + ret = _dns_decode_CNAME(context, cname, DNS_MAX_CNAME_LEN); + if (ret < 0) { + tlog(TLOG_ERROR, "decode CNAME failed, %s", domain); + return -1; + } + + ret = dns_add_CNAME(packet, type, domain, ttl, cname); + if (ret < 0) { + tlog(TLOG_ERROR, "add CNAME failed, %s", domain); + return -1; + } + } break; + case DNS_T_SOA: { + struct dns_soa soa; + ret = _dns_decode_SOA(context, &soa); + if (ret < 0) { + tlog(TLOG_ERROR, "decode CNAME failed, %s", domain); + return -1; + } + + ret = dns_add_SOA(packet, type, domain, ttl, &soa); + if (ret < 0) { + tlog(TLOG_ERROR, "add CNAME failed, %s", domain); + return -1; + } + } break; + case DNS_T_NS: { + char ns[DNS_MAX_CNAME_LEN]; + ret = _dns_decode_CNAME(context, ns, DNS_MAX_CNAME_LEN); + if (ret < 0) { + tlog(TLOG_ERROR, "decode NS failed, %s", domain); + return -1; + } + + ret = dns_add_NS(packet, type, domain, ttl, ns); + if (ret < 0) { + tlog(TLOG_ERROR, "add NS failed, %s", domain); + return -1; + } + } break; + case DNS_T_PTR: { + char name[DNS_MAX_CNAME_LEN]; + ret = _dns_decode_CNAME(context, name, DNS_MAX_CNAME_LEN); + if (ret < 0) { + tlog(TLOG_ERROR, "decode PTR failed, %s", domain); + return -1; + } + + ret = dns_add_PTR(packet, type, domain, ttl, name); + if (ret < 0) { + tlog(TLOG_ERROR, "add PTR failed, %s", domain); + return -1; + } + } break; + case DNS_T_AAAA: { + unsigned char addr[DNS_RR_AAAA_LEN]; + ret = _dns_decode_raw(context, addr, sizeof(addr)); + if (ret < 0) { + tlog(TLOG_ERROR, "decode AAAA failed, %s", domain); + return -1; + } + + ret = dns_add_AAAA(packet, type, domain, ttl, addr); + if (ret < 0) { + tlog(TLOG_ERROR, "add AAAA failed, %s", domain); + return -1; + } + } break; + case DNS_T_OPT: { + unsigned char *opt_start = context->ptr; + ret = _dns_decode_opt(context, type, ttl, rr_len); + if (ret < 0) { + tlog(TLOG_ERROR, "decode opt failed, %s", domain); + return -1; + } + + if (context->ptr - opt_start != rr_len) { + tlog(TLOG_ERROR, "opt length mitchmatch, %s\n", domain); + return -1; + } + + dns_set_OPT_payload_size(packet, qclass); + } break; + default: + if (_dns_left_len(context) < rr_len) { + tlog(TLOG_DEBUG, "length mitchmatch\n"); + return -1; + } + context->ptr += rr_len; + tlog(TLOG_DEBUG, "DNS type = %d not supported", qtype); + break; + } + + if (context->ptr - start != rr_len) { + tlog(TLOG_ERROR, "length mitchmatch , %s, %ld:%d", domain, (long)(context->ptr - start), rr_len); + return -1; + } + + return 0; +} + +static int _dns_encode_qd(struct dns_context *context, struct dns_rrs *rrs) +{ + int ret; + int qtype = 0; + int qclass = 0; + char domain[DNS_MAX_CNAME_LEN]; + struct dns_data_context data_context; + + data_context.data = rrs->data; + data_context.ptr = rrs->data; + data_context.maxsize = rrs->len; + + ret = _dns_get_qr_head(&data_context, domain, DNS_MAX_CNAME_LEN, &qtype, &qclass); + if (ret < 0) { + return -1; + } + + ret = _dns_encode_qr_head(context, domain, qtype, qclass); + if (ret < 0) { + return -1; + } + + return 0; +} + +static int _dns_encode_an(struct dns_context *context, struct dns_rrs *rrs) +{ + int ret; + switch (rrs->type) { + case DNS_T_A: + case DNS_T_AAAA: { + ret = _dns_encode_raw(context, rrs); + if (ret < 0) { + return -1; + } + } break; + case DNS_T_CNAME: + case DNS_T_PTR: + ret = _dns_encode_CNAME(context, rrs); + if (ret < 0) { + return -1; + } + break; + case DNS_T_SOA: + ret = _dns_encode_SOA(context, rrs); + if (ret < 0) { + return -1; + } + break; + default: + break; + } + + return 0; +} + +static int _dns_decode_body(struct dns_context *context) +{ + struct dns_packet *packet = context->packet; + struct dns_head *head = &packet->head; + int i = 0; + int ret = 0; + int count = 0; + + count = head->qdcount; + head->qdcount = 0; + for (i = 0; i < count; i++) { + ret = _dns_decode_qd(context); + if (ret < 0) { + tlog(TLOG_DEBUG, "decode qd failed."); + return -1; + } + } + + count = head->ancount; + head->ancount = 0; + for (i = 0; i < count; i++) { + ret = _dns_decode_an(context, DNS_RRS_AN); + if (ret < 0) { + tlog(TLOG_DEBUG, "decode an failed."); + return -1; + } + } + + count = head->nscount; + head->nscount = 0; + for (i = 0; i < count; i++) { + ret = _dns_decode_an(context, DNS_RRS_NS); + if (ret < 0) { + tlog(TLOG_DEBUG, "decode ns failed."); + return -1; + } + } + + count = head->nrcount; + head->nrcount = 0; + for (i = 0; i < count; i++) { + ret = _dns_decode_an(context, DNS_RRS_NR); + if (ret < 0) { + tlog(TLOG_DEBUG, "decode nr failed."); + return -1; + } + } + + return 0; +} + +static int _dns_encode_body(struct dns_context *context) +{ + struct dns_packet *packet = context->packet; + struct dns_head *head = &packet->head; + int i = 0; + int len = 0; + struct dns_rrs *rrs; + int count; + + rrs = dns_get_rrs_start(packet, DNS_RRS_QD, &count); + head->qdcount = count; + for (i = 0; i < count && rrs; i++, rrs = dns_get_rrs_next(packet, rrs)) { + len = _dns_encode_qd(context, rrs); + if (len < 0) { + return -1; + } + } + + rrs = dns_get_rrs_start(packet, DNS_RRS_AN, &count); + head->ancount = count; + for (i = 0; i < count && rrs; i++, rrs = dns_get_rrs_next(packet, rrs)) { + len = _dns_encode_an(context, rrs); + if (len < 0) { + return -1; + } + } + + rrs = dns_get_rrs_start(packet, DNS_RRS_NS, &count); + head->nscount = count; + for (i = 0; i < count && rrs; i++, rrs = dns_get_rrs_next(packet, rrs)) { + len = _dns_encode_an(context, rrs); + if (len < 0) { + return -1; + } + } + + rrs = dns_get_rrs_start(packet, DNS_RRS_NR, &count); + head->nrcount = count; + for (i = 0; i < count && rrs; i++, rrs = dns_get_rrs_next(packet, rrs)) { + len = _dns_encode_an(context, rrs); + if (len < 0) { + return -1; + } + } + + rrs = dns_get_rrs_start(packet, DNS_RRS_OPT, &count); + if (count > 0 || packet->payloadsize > 0) { + len = _dns_encode_opts(packet, context, rrs, count); + if (len < 0) { + return -1; + } + head->nrcount++; + } + + return 0; +} + +int dns_packet_init(struct dns_packet *packet, int size, struct dns_head *head) +{ + struct dns_head *init_head = &packet->head; + if (size < sizeof(*packet)) { + return -1; + } + + memset(packet, 0, size); + packet->size = size; + init_head->id = head->id; + init_head->qr = head->qr; + init_head->opcode = head->opcode; + init_head->aa = head->aa; + init_head->tc = head->tc; + init_head->rd = head->rd; + init_head->ra = head->ra; + init_head->rcode = head->rcode; + packet->questions = DNS_RR_END; + packet->answers = DNS_RR_END; + packet->nameservers = DNS_RR_END; + packet->additional = DNS_RR_END; + packet->optional = DNS_RR_END; + packet->optcount = 0; + packet->payloadsize = 0; + + return 0; +} + +int dns_decode(struct dns_packet *packet, int maxsize, unsigned char *data, int size) +{ + struct dns_head *head = &packet->head; + struct dns_context context; + int ret = 0; + + memset(&context, 0, sizeof(context)); + memset(packet, 0, sizeof(*packet)); + + context.data = data; + context.packet = packet; + context.ptr = data; + context.maxsize = size; + + ret = dns_packet_init(packet, maxsize, head); + if (ret != 0) { + return -1; + } + + ret = _dns_decode_head(&context); + if (ret < 0) { + return -1; + } + + ret = _dns_decode_body(&context); + if (ret < 0) { + tlog(TLOG_DEBUG, "decode body failed.\n"); + return -1; + } + + return 0; +} + +int dns_encode(unsigned char *data, int size, struct dns_packet *packet) +{ + int ret = 0; + struct dns_context context; + + memset(&context, 0, sizeof(context)); + context.data = data; + context.packet = packet; + context.ptr = data; + context.maxsize = size; + + ret = _dns_encode_head(&context); + if (ret < 0) { + return -1; + } + + ret = _dns_encode_body(&context); + if (ret < 0) { + return -1; + } + + ret = _dns_encode_head_count(&context); + if (ret < 0) { + return -1; + } + + return context.ptr - context.data; +} + +#if 0 +static void dns_debug(void) +{ + unsigned char data[1024]; + int len; + char buff[4096]; + + int fd = open("dns.bin", O_RDWR); + if (fd < 0) { + return; + } + len = read(fd, data, 1024); + close(fd); + if (len < 0) { + return; + } + + struct dns_packet *packet = (struct dns_packet *)buff; + if (dns_decode(packet, 4096, data, len) != 0) { + tlog(TLOG_ERROR, "decode failed.\n"); + } + + memset(data, 0, sizeof(data)); + len = dns_encode(data, 1024, packet); + if (len < 0) { + tlog(TLOG_ERROR, "encode failed."); + } + + fd = open("dns-cmp.bin", O_CREAT | O_TRUNC | O_RDWR); + write(fd, data, len); + close(fd); +} +#endif diff --git a/release/src/router/smartdns/src/dns.h b/release/src/router/smartdns/src/dns.h index 9b59dd4468..366050b5f0 100644 --- a/release/src/router/smartdns/src/dns.h +++ b/release/src/router/smartdns/src/dns.h @@ -44,7 +44,10 @@ typedef enum dns_rr_type { DNS_RRS_END, } dns_rr_type; -typedef enum dns_class { DNS_C_IN = 1, DNS_C_ANY = 255 } dns_class_t; +typedef enum dns_class { + DNS_C_IN = 1, // DNS C IN + DNS_C_ANY = 255 +} dns_class_t; typedef enum dns_type { DNS_T_A = 1, @@ -63,10 +66,10 @@ typedef enum dns_type { DNS_T_ALL = 255 } dns_type_t; -typedef enum dns_opt_code { - DNS_OPT_T_ECS = 8, +typedef enum dns_opt_code { + DNS_OPT_T_ECS = 8, // OPT ECS DNS_OPT_T_TCP_KEEPALIVE = 11, - DNS_OPT_T_ALL = 255 + DNS_OPT_T_ALL = 255 } dns_opt_code_t; typedef enum dns_opcode { @@ -196,7 +199,8 @@ int dns_get_A(struct dns_rrs *rrs, char *domain, int maxsize, int *ttl, unsigned int dns_add_PTR(struct dns_packet *packet, dns_rr_type type, char *domain, int ttl, char *cname); int dns_get_PTR(struct dns_rrs *rrs, char *domain, int maxsize, int *ttl, char *cname, int cname_size); -int dns_add_AAAA(struct dns_packet *packet, dns_rr_type type, char *domain, int ttl, unsigned char addr[DNS_RR_AAAA_LEN]); +int dns_add_AAAA(struct dns_packet *packet, dns_rr_type type, char *domain, int ttl, + unsigned char addr[DNS_RR_AAAA_LEN]); int dns_get_AAAA(struct dns_rrs *rrs, char *domain, int maxsize, int *ttl, unsigned char addr[DNS_RR_AAAA_LEN]); int dns_add_SOA(struct dns_packet *packet, dns_rr_type type, char *domain, int ttl, struct dns_soa *soa); @@ -212,7 +216,8 @@ int dns_add_OPT_ECS(struct dns_packet *packet, struct dns_opt_ecs *ecs); int dns_get_OPT_ECS(struct dns_rrs *rrs, unsigned short *opt_code, unsigned short *opt_len, struct dns_opt_ecs *ecs); int dns_add_OPT_TCP_KEEYALIVE(struct dns_packet *packet, unsigned short timeout); -int dns_get_OPT_TCP_KEEYALIVE(struct dns_rrs *rrs, unsigned short *opt_code, unsigned short *opt_len, unsigned short *timeout); +int dns_get_OPT_TCP_KEEYALIVE(struct dns_rrs *rrs, unsigned short *opt_code, unsigned short *opt_len, + unsigned short *timeout); /* * Packet operation */ diff --git a/release/src/router/smartdns/src/dns_cache.c b/release/src/router/smartdns/src/dns_cache.c index 679d1bd605..c495623980 100644 --- a/release/src/router/smartdns/src/dns_cache.c +++ b/release/src/router/smartdns/src/dns_cache.c @@ -1,386 +1,452 @@ -/************************************************************************* - * - * Copyright (C) 2018-2020 Ruilin Peng (Nick) . - * - * smartdns is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * smartdns is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#include "dns_cache.h" -#include "stringutil.h" -#include "tlog.h" -#include - -#define DNS_CACHE_MAX_HITNUM 5000 -#define DNS_CACHE_HITNUM_STEP 2 -#define DNS_CACHE_HITNUM_STEP_MAX 6 - -struct dns_cache_head { - DECLARE_HASHTABLE(cache_hash, 10); - struct list_head cache_list; - atomic_t num; - int size; - pthread_mutex_t lock; -}; - -static struct dns_cache_head dns_cache_head; - -int dns_cache_init(int size) -{ - INIT_LIST_HEAD(&dns_cache_head.cache_list); - hash_init(dns_cache_head.cache_hash); - atomic_set(&dns_cache_head.num, 0); - dns_cache_head.size = size; - - pthread_mutex_init(&dns_cache_head.lock, NULL); - - return 0; -} - -static __attribute__((unused)) struct dns_cache *_dns_cache_last(void) -{ - return list_last_entry(&dns_cache_head.cache_list, struct dns_cache, list); -} - -static struct dns_cache *_dns_cache_first(void) -{ - return list_first_entry_or_null(&dns_cache_head.cache_list, struct dns_cache, list); -} - -static void _dns_cache_delete(struct dns_cache *dns_cache) -{ - hash_del(&dns_cache->node); - list_del_init(&dns_cache->list); - atomic_dec(&dns_cache_head.num); - free(dns_cache); -} - -void dns_cache_get(struct dns_cache *dns_cache) -{ - if (atomic_inc_return(&dns_cache->ref) == 1) { - tlog(TLOG_ERROR, "BUG: dns_cache is invalid."); - return; - } -} - -void dns_cache_release(struct dns_cache *dns_cache) -{ - if (dns_cache == NULL) { - return; - } - if (!atomic_dec_and_test(&dns_cache->ref)) { - return; - } - - _dns_cache_delete(dns_cache); -} - -static void _dns_cache_remove(struct dns_cache *dns_cache) -{ - hash_del(&dns_cache->node); - list_del_init(&dns_cache->list); - dns_cache_release(dns_cache); -} - -int dns_cache_replace(char *domain, char *cname, int cname_ttl, int ttl, dns_type_t qtype, unsigned char *addr, int addr_len, int speed) -{ - struct dns_cache *dns_cache = NULL; - - if (dns_cache_head.size <= 0) { - return 0; - } - - /* lookup existing cache */ - dns_cache = dns_cache_lookup(domain, qtype); - if (dns_cache == NULL) { - return 0; - } - - if (ttl < DNS_CACHE_TTL_MIN) { - ttl = DNS_CACHE_TTL_MIN; - } - - /* update cache data */ - pthread_mutex_lock(&dns_cache_head.lock); - dns_cache->ttl = ttl; - dns_cache->qtype = qtype; - dns_cache->ttl = ttl; - dns_cache->del_pending = 0; - dns_cache->speed = speed; - time(&dns_cache->insert_time); - if (qtype == DNS_T_A) { - if (addr_len != DNS_RR_A_LEN) { - goto errout_unlock; - } - memcpy(dns_cache->addr, addr, DNS_RR_A_LEN); - } else if (qtype == DNS_T_AAAA) { - if (addr_len != DNS_RR_AAAA_LEN) { - goto errout_unlock; - } - memcpy(dns_cache->addr, addr, DNS_RR_AAAA_LEN); - } else { - goto errout_unlock; - } - - if (cname) { - safe_strncpy(dns_cache->cname, cname, DNS_MAX_CNAME_LEN); - dns_cache->cname_ttl = cname_ttl; - } - pthread_mutex_unlock(&dns_cache_head.lock); - - dns_cache_release(dns_cache); - return 0; -errout_unlock: - pthread_mutex_unlock(&dns_cache_head.lock); -// errout: - if (dns_cache) { - dns_cache_release(dns_cache); - } - return -1; -} - -int dns_cache_insert(char *domain, char *cname, int cname_ttl, int ttl, dns_type_t qtype, unsigned char *addr, int addr_len, int speed) -{ - uint32_t key = 0; - struct dns_cache *dns_cache = NULL; - - if (dns_cache_head.size <= 0) { - return 0; - } - - /* if cache already exists, free */ - dns_cache = dns_cache_lookup(domain, qtype); - if (dns_cache) { - dns_cache_delete(dns_cache); - dns_cache_release(dns_cache); - dns_cache = NULL; - } - - dns_cache = malloc(sizeof(*dns_cache)); - if (dns_cache == NULL) { - goto errout; - } - - if (ttl < DNS_CACHE_TTL_MIN) { - ttl = DNS_CACHE_TTL_MIN; - } - - key = hash_string(domain); - key = jhash(&qtype, sizeof(qtype), key); - safe_strncpy(dns_cache->domain, domain, DNS_MAX_CNAME_LEN); - dns_cache->cname[0] = 0; - dns_cache->qtype = qtype; - dns_cache->ttl = ttl; - atomic_set(&dns_cache->hitnum, 3); - dns_cache->hitnum_update_add = DNS_CACHE_HITNUM_STEP; - dns_cache->del_pending = 0; - dns_cache->speed = speed; - atomic_set(&dns_cache->ref, 1); - time(&dns_cache->insert_time); - if (qtype == DNS_T_A) { - if (addr_len != DNS_RR_A_LEN) { - goto errout; - } - memcpy(dns_cache->addr, addr, DNS_RR_A_LEN); - } else if (qtype == DNS_T_AAAA) { - if (addr_len != DNS_RR_AAAA_LEN) { - goto errout; - } - memcpy(dns_cache->addr, addr, DNS_RR_AAAA_LEN); - } else { - goto errout; - } - - if (cname) { - safe_strncpy(dns_cache->cname, cname, DNS_MAX_CNAME_LEN); - dns_cache->cname_ttl = cname_ttl; - } - - pthread_mutex_lock(&dns_cache_head.lock); - hash_add(dns_cache_head.cache_hash, &dns_cache->node, key); - list_add_tail(&dns_cache->list, &dns_cache_head.cache_list); - INIT_LIST_HEAD(&dns_cache->check_list); - - /* Release extra cache, remove oldest cache record */ - if (atomic_inc_return(&dns_cache_head.num) > dns_cache_head.size) { - struct dns_cache *del_cache; - del_cache = _dns_cache_first(); - if (del_cache) { - _dns_cache_remove(del_cache); - } - } - pthread_mutex_unlock(&dns_cache_head.lock); - - return 0; -errout: - if (dns_cache) { - free(dns_cache); - } - - return -1; -} - -struct dns_cache *dns_cache_lookup(char *domain, dns_type_t qtype) -{ - uint32_t key = 0; - struct dns_cache *dns_cache = NULL; - struct dns_cache *dns_cache_ret = NULL; - time_t now; - - if (dns_cache_head.size <= 0) { - return NULL; - } - - key = hash_string(domain); - key = jhash(&qtype, sizeof(qtype), key); - - time(&now); - /* find cache */ - pthread_mutex_lock(&dns_cache_head.lock); - hash_for_each_possible(dns_cache_head.cache_hash, dns_cache, node, key) - { - if (dns_cache->qtype != qtype) { - continue; - } - - if (strncmp(domain, dns_cache->domain, DNS_MAX_CNAME_LEN) != 0) { - continue; - } - - dns_cache_ret = dns_cache; - break; - } - - if (dns_cache_ret) { - /* Return NULL if the cache times out */ - if (now - dns_cache_ret->insert_time > dns_cache_ret->ttl) { - _dns_cache_remove(dns_cache_ret); - dns_cache_ret = NULL; - } else { - dns_cache_get(dns_cache_ret); - } - } - - pthread_mutex_unlock(&dns_cache_head.lock); - - return dns_cache_ret; -} - -int dns_cache_get_ttl(struct dns_cache *dns_cache) -{ - time_t now; - int ttl = 0; - time(&now); - - ttl = dns_cache->insert_time + dns_cache->ttl - now; - if (ttl < 0) { - return 0; - } - - return ttl; -} - -void dns_cache_delete(struct dns_cache *dns_cache) -{ - pthread_mutex_lock(&dns_cache_head.lock); - _dns_cache_remove(dns_cache); - pthread_mutex_unlock(&dns_cache_head.lock); -} - -int dns_cache_hitnum_dec_get(struct dns_cache *dns_cache) -{ - int hitnum = 0; - pthread_mutex_lock(&dns_cache_head.lock); - hitnum = atomic_dec_return(&dns_cache->hitnum); - if (dns_cache->hitnum_update_add > DNS_CACHE_HITNUM_STEP) { - dns_cache->hitnum_update_add--; - } - pthread_mutex_unlock(&dns_cache_head.lock); - - return hitnum; -} - -void dns_cache_update(struct dns_cache *dns_cache) -{ - pthread_mutex_lock(&dns_cache_head.lock); - if (!list_empty(&dns_cache->list)) { - list_del_init(&dns_cache->list); - list_add_tail(&dns_cache->list, &dns_cache_head.cache_list); - atomic_add(dns_cache->hitnum_update_add, &dns_cache->hitnum); - if (atomic_read(&dns_cache->hitnum) > DNS_CACHE_MAX_HITNUM) { - atomic_set(&dns_cache->hitnum, DNS_CACHE_MAX_HITNUM); - } - - if (dns_cache->hitnum_update_add < DNS_CACHE_HITNUM_STEP_MAX) { - dns_cache->hitnum_update_add++; - } - } - pthread_mutex_unlock(&dns_cache_head.lock); -} - -void dns_cache_invalidate(dns_cache_preinvalid_callback callback, int ttl_pre) -{ - struct dns_cache *dns_cache = NULL; - struct dns_cache *tmp; - time_t now; - int ttl = 0; - LIST_HEAD(checklist); - - if (dns_cache_head.size <= 0) { - return; - } - - time(&now); - pthread_mutex_lock(&dns_cache_head.lock); - list_for_each_entry_safe(dns_cache, tmp, &dns_cache_head.cache_list, list) - { - ttl = dns_cache->insert_time + dns_cache->ttl - now; - if (ttl > 0 && ttl < ttl_pre) { - /* If the TTL time is in the pre-timeout range, call callback function */ - if (callback && dns_cache->del_pending == 0) { - list_add_tail(&dns_cache->check_list, &checklist); - dns_cache_get(dns_cache); - dns_cache->del_pending = 1; - continue; - } - } - - if (ttl < 0) { - _dns_cache_remove(dns_cache); - } - } - pthread_mutex_unlock(&dns_cache_head.lock); - - list_for_each_entry_safe(dns_cache, tmp, &checklist, check_list) - { - /* run callback */ - if (callback) { - callback(dns_cache); - } - dns_cache_release(dns_cache); - } -} - -void dns_cache_destroy(void) -{ - struct dns_cache *dns_cache = NULL; - struct dns_cache *tmp; - pthread_mutex_lock(&dns_cache_head.lock); - list_for_each_entry_safe(dns_cache, tmp, &dns_cache_head.cache_list, list) - { - _dns_cache_delete(dns_cache); - } - pthread_mutex_unlock(&dns_cache_head.lock); - - pthread_mutex_destroy(&dns_cache_head.lock); -} +/************************************************************************* + * + * Copyright (C) 2018-2020 Ruilin Peng (Nick) . + * + * smartdns is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * smartdns is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "dns_cache.h" +#include "stringutil.h" +#include "tlog.h" +#include + +#define DNS_CACHE_MAX_HITNUM 5000 +#define DNS_CACHE_HITNUM_STEP 2 +#define DNS_CACHE_HITNUM_STEP_MAX 6 + +struct dns_cache_head { + DECLARE_HASHTABLE(cache_hash, 10); + struct list_head cache_list; + struct list_head inactive_list; + atomic_t num; + int size; + int enable_inactive; + int inactive_list_expired; + pthread_mutex_t lock; +}; + +static struct dns_cache_head dns_cache_head; + +int dns_cache_init(int size, int enable_inactive, int inactive_list_expired) +{ + INIT_LIST_HEAD(&dns_cache_head.cache_list); + INIT_LIST_HEAD(&dns_cache_head.inactive_list); + hash_init(dns_cache_head.cache_hash); + atomic_set(&dns_cache_head.num, 0); + dns_cache_head.size = size; + dns_cache_head.enable_inactive = enable_inactive; + dns_cache_head.inactive_list_expired = inactive_list_expired; + + pthread_mutex_init(&dns_cache_head.lock, NULL); + + return 0; +} + +static __attribute__((unused)) struct dns_cache *_dns_cache_last(void) +{ + struct dns_cache *dns_cache = NULL; + + dns_cache = list_last_entry(&dns_cache_head.inactive_list, struct dns_cache, list); + if (dns_cache) { + return dns_cache; + } + + return list_last_entry(&dns_cache_head.cache_list, struct dns_cache, list); +} + +static struct dns_cache *_dns_cache_first(void) +{ + struct dns_cache *dns_cache = NULL; + + dns_cache = list_first_entry_or_null(&dns_cache_head.inactive_list, struct dns_cache, list); + if (dns_cache) { + return dns_cache; + } + + return list_first_entry_or_null(&dns_cache_head.cache_list, struct dns_cache, list); +} + +static void _dns_cache_delete(struct dns_cache *dns_cache) +{ + hash_del(&dns_cache->node); + list_del_init(&dns_cache->list); + atomic_dec(&dns_cache_head.num); + free(dns_cache); +} + +void dns_cache_get(struct dns_cache *dns_cache) +{ + if (atomic_inc_return(&dns_cache->ref) == 1) { + tlog(TLOG_ERROR, "BUG: dns_cache is invalid."); + return; + } +} + +void dns_cache_release(struct dns_cache *dns_cache) +{ + if (dns_cache == NULL) { + return; + } + if (!atomic_dec_and_test(&dns_cache->ref)) { + return; + } + + _dns_cache_delete(dns_cache); +} + +static void _dns_cache_remove(struct dns_cache *dns_cache) +{ + hash_del(&dns_cache->node); + list_del_init(&dns_cache->list); + dns_cache_release(dns_cache); +} + +static void _dns_cache_move_inactive(struct dns_cache *dns_cache) +{ + list_del_init(&dns_cache->list); + list_add_tail(&dns_cache->list, &dns_cache_head.inactive_list); +} + +int dns_cache_replace(char *domain, char *cname, int cname_ttl, int ttl, dns_type_t qtype, unsigned char *addr, + int addr_len, int speed) +{ + struct dns_cache *dns_cache = NULL; + + if (dns_cache_head.size <= 0) { + return 0; + } + + /* lookup existing cache */ + dns_cache = dns_cache_lookup(domain, qtype); + if (dns_cache == NULL) { + return 0; + } + + if (ttl < DNS_CACHE_TTL_MIN) { + ttl = DNS_CACHE_TTL_MIN; + } + + /* update cache data */ + pthread_mutex_lock(&dns_cache_head.lock); + dns_cache->ttl = ttl; + dns_cache->qtype = qtype; + dns_cache->ttl = ttl; + dns_cache->del_pending = 0; + dns_cache->speed = speed; + time(&dns_cache->insert_time); + if (qtype == DNS_T_A) { + if (addr_len != DNS_RR_A_LEN) { + goto errout_unlock; + } + memcpy(dns_cache->addr, addr, DNS_RR_A_LEN); + } else if (qtype == DNS_T_AAAA) { + if (addr_len != DNS_RR_AAAA_LEN) { + goto errout_unlock; + } + memcpy(dns_cache->addr, addr, DNS_RR_AAAA_LEN); + } else { + goto errout_unlock; + } + + if (cname) { + safe_strncpy(dns_cache->cname, cname, DNS_MAX_CNAME_LEN); + dns_cache->cname_ttl = cname_ttl; + } + + list_del_init(&dns_cache->list); + list_add_tail(&dns_cache->list, &dns_cache_head.cache_list); + pthread_mutex_unlock(&dns_cache_head.lock); + + dns_cache_release(dns_cache); + return 0; +errout_unlock: + pthread_mutex_unlock(&dns_cache_head.lock); + // errout: + if (dns_cache) { + dns_cache_release(dns_cache); + } + return -1; +} + +int dns_cache_insert(char *domain, char *cname, int cname_ttl, int ttl, dns_type_t qtype, unsigned char *addr, + int addr_len, int speed) +{ + uint32_t key = 0; + struct dns_cache *dns_cache = NULL; + + if (dns_cache_head.size <= 0) { + return 0; + } + + /* if cache already exists, free */ + dns_cache = dns_cache_lookup(domain, qtype); + if (dns_cache) { + dns_cache_delete(dns_cache); + dns_cache_release(dns_cache); + dns_cache = NULL; + } + + dns_cache = malloc(sizeof(*dns_cache)); + if (dns_cache == NULL) { + goto errout; + } + + if (ttl < DNS_CACHE_TTL_MIN) { + ttl = DNS_CACHE_TTL_MIN; + } + + key = hash_string(domain); + key = jhash(&qtype, sizeof(qtype), key); + safe_strncpy(dns_cache->domain, domain, DNS_MAX_CNAME_LEN); + dns_cache->cname[0] = 0; + dns_cache->qtype = qtype; + dns_cache->ttl = ttl; + atomic_set(&dns_cache->hitnum, 3); + dns_cache->hitnum_update_add = DNS_CACHE_HITNUM_STEP; + dns_cache->del_pending = 0; + dns_cache->speed = speed; + atomic_set(&dns_cache->ref, 1); + time(&dns_cache->insert_time); + if (qtype == DNS_T_A) { + if (addr_len != DNS_RR_A_LEN) { + goto errout; + } + memcpy(dns_cache->addr, addr, DNS_RR_A_LEN); + } else if (qtype == DNS_T_AAAA) { + if (addr_len != DNS_RR_AAAA_LEN) { + goto errout; + } + memcpy(dns_cache->addr, addr, DNS_RR_AAAA_LEN); + } else { + goto errout; + } + + if (cname) { + safe_strncpy(dns_cache->cname, cname, DNS_MAX_CNAME_LEN); + dns_cache->cname_ttl = cname_ttl; + } + + pthread_mutex_lock(&dns_cache_head.lock); + hash_add(dns_cache_head.cache_hash, &dns_cache->node, key); + list_add_tail(&dns_cache->list, &dns_cache_head.cache_list); + INIT_LIST_HEAD(&dns_cache->check_list); + + /* Release extra cache, remove oldest cache record */ + if (atomic_inc_return(&dns_cache_head.num) > dns_cache_head.size) { + struct dns_cache *del_cache; + del_cache = _dns_cache_first(); + if (del_cache) { + _dns_cache_remove(del_cache); + } + } + pthread_mutex_unlock(&dns_cache_head.lock); + + return 0; +errout: + if (dns_cache) { + free(dns_cache); + } + + return -1; +} + +struct dns_cache *dns_cache_lookup(char *domain, dns_type_t qtype) +{ + uint32_t key = 0; + struct dns_cache *dns_cache = NULL; + struct dns_cache *dns_cache_ret = NULL; + time_t now; + + if (dns_cache_head.size <= 0) { + return NULL; + } + + key = hash_string(domain); + key = jhash(&qtype, sizeof(qtype), key); + + time(&now); + /* find cache */ + pthread_mutex_lock(&dns_cache_head.lock); + hash_for_each_possible(dns_cache_head.cache_hash, dns_cache, node, key) + { + if (dns_cache->qtype != qtype) { + continue; + } + + if (strncmp(domain, dns_cache->domain, DNS_MAX_CNAME_LEN) != 0) { + continue; + } + + dns_cache_ret = dns_cache; + break; + } + + if (dns_cache_ret) { + /* Return NULL if the cache times out */ + if (dns_cache_head.enable_inactive == 0 && (now - dns_cache_ret->insert_time > dns_cache_ret->ttl)) { + _dns_cache_remove(dns_cache_ret); + dns_cache_ret = NULL; + } else { + dns_cache_get(dns_cache_ret); + } + } + + pthread_mutex_unlock(&dns_cache_head.lock); + + return dns_cache_ret; +} + +int dns_cache_get_ttl(struct dns_cache *dns_cache) +{ + time_t now; + int ttl = 0; + time(&now); + + ttl = dns_cache->insert_time + dns_cache->ttl - now; + if (ttl < 0) { + return 0; + } + + return ttl; +} + +void dns_cache_delete(struct dns_cache *dns_cache) +{ + pthread_mutex_lock(&dns_cache_head.lock); + _dns_cache_remove(dns_cache); + pthread_mutex_unlock(&dns_cache_head.lock); +} + +int dns_cache_hitnum_dec_get(struct dns_cache *dns_cache) +{ + int hitnum = 0; + pthread_mutex_lock(&dns_cache_head.lock); + hitnum = atomic_dec_return(&dns_cache->hitnum); + if (dns_cache->hitnum_update_add > DNS_CACHE_HITNUM_STEP) { + dns_cache->hitnum_update_add--; + } + pthread_mutex_unlock(&dns_cache_head.lock); + + return hitnum; +} + +void dns_cache_update(struct dns_cache *dns_cache) +{ + pthread_mutex_lock(&dns_cache_head.lock); + if (!list_empty(&dns_cache->list)) { + list_del_init(&dns_cache->list); + list_add_tail(&dns_cache->list, &dns_cache_head.cache_list); + atomic_add(dns_cache->hitnum_update_add, &dns_cache->hitnum); + if (atomic_read(&dns_cache->hitnum) > DNS_CACHE_MAX_HITNUM) { + atomic_set(&dns_cache->hitnum, DNS_CACHE_MAX_HITNUM); + } + + if (dns_cache->hitnum_update_add < DNS_CACHE_HITNUM_STEP_MAX) { + dns_cache->hitnum_update_add++; + } + } + pthread_mutex_unlock(&dns_cache_head.lock); +} + +void _dns_cache_remove_expired_ttl(time_t *now) +{ + struct dns_cache *dns_cache = NULL; + struct dns_cache *tmp; + int ttl = 0; + + list_for_each_entry_safe(dns_cache, tmp, &dns_cache_head.inactive_list, list) + { + ttl = dns_cache->insert_time + dns_cache->ttl - *now; + if (ttl > 0) { + continue; + } + + if (dns_cache_head.inactive_list_expired + ttl > 0) { + continue; + } + + _dns_cache_remove(dns_cache); + } +} + +void dns_cache_invalidate(dns_cache_preinvalid_callback callback, int ttl_pre) +{ + struct dns_cache *dns_cache = NULL; + struct dns_cache *tmp; + time_t now; + int ttl = 0; + LIST_HEAD(checklist); + + if (dns_cache_head.size <= 0) { + return; + } + + time(&now); + pthread_mutex_lock(&dns_cache_head.lock); + list_for_each_entry_safe(dns_cache, tmp, &dns_cache_head.cache_list, list) + { + ttl = dns_cache->insert_time + dns_cache->ttl - now; + if (ttl > 0 && ttl < ttl_pre) { + /* If the TTL time is in the pre-timeout range, call callback function */ + if (callback && dns_cache->del_pending == 0) { + list_add_tail(&dns_cache->check_list, &checklist); + dns_cache_get(dns_cache); + dns_cache->del_pending = 1; + continue; + } + } + + if (ttl < 0) { + if (dns_cache_head.enable_inactive) { + _dns_cache_move_inactive(dns_cache); + } else { + _dns_cache_remove(dns_cache); + } + } + } + + if (dns_cache_head.enable_inactive && dns_cache_head.inactive_list_expired != 0) { + _dns_cache_remove_expired_ttl(&now); + } + + pthread_mutex_unlock(&dns_cache_head.lock); + + list_for_each_entry_safe(dns_cache, tmp, &checklist, check_list) + { + /* run callback */ + if (callback) { + callback(dns_cache); + } + dns_cache_release(dns_cache); + } +} + +void dns_cache_destroy(void) +{ + struct dns_cache *dns_cache = NULL; + struct dns_cache *tmp; + pthread_mutex_lock(&dns_cache_head.lock); + list_for_each_entry_safe(dns_cache, tmp, &dns_cache_head.inactive_list, list) + { + _dns_cache_delete(dns_cache); + } + + list_for_each_entry_safe(dns_cache, tmp, &dns_cache_head.cache_list, list) + { + _dns_cache_delete(dns_cache); + } + pthread_mutex_unlock(&dns_cache_head.lock); + + pthread_mutex_destroy(&dns_cache_head.lock); +} diff --git a/release/src/router/smartdns/src/dns_cache.h b/release/src/router/smartdns/src/dns_cache.h index cb1195533f..691b8bfd79 100644 --- a/release/src/router/smartdns/src/dns_cache.h +++ b/release/src/router/smartdns/src/dns_cache.h @@ -1,87 +1,89 @@ -/************************************************************************* - * - * Copyright (C) 2018-2020 Ruilin Peng (Nick) . - * - * smartdns is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * smartdns is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#ifndef _SMARTDNS_CACHE_H -#define _SMARTDNS_CACHE_H - -#include "atomic.h" -#include "dns.h" -#include "hash.h" -#include "hashtable.h" -#include "list.h" -#include -#include - -#ifdef __cpluscplus -extern "C" { -#endif - -#define DNS_CACHE_TTL_MIN 30 - -struct dns_cache { - struct hlist_node node; - struct list_head list; - struct list_head check_list; - atomic_t ref; - char domain[DNS_MAX_CNAME_LEN]; - char cname[DNS_MAX_CNAME_LEN]; - unsigned int cname_ttl; - unsigned int ttl; - int speed; - atomic_t hitnum; - int hitnum_update_add; - int del_pending; - time_t insert_time; - dns_type_t qtype; - union { - unsigned char ipv4_addr[DNS_RR_A_LEN]; - unsigned char ipv6_addr[DNS_RR_AAAA_LEN]; - unsigned char addr[0]; - }; -}; - -int dns_cache_init(int size); - -int dns_cache_replace(char *domain, char *cname, int cname_ttl, int ttl, dns_type_t qtype, unsigned char *addr, int addr_len, int speed); - -int dns_cache_insert(char *domain, char *cname, int cname_ttl, int ttl, dns_type_t qtype, unsigned char *addr, int addr_len, int speed); - -struct dns_cache *dns_cache_lookup(char *domain, dns_type_t qtype); - -void dns_cache_delete(struct dns_cache *dns_cache); - -void dns_cache_get(struct dns_cache *dns_cache); - -void dns_cache_release(struct dns_cache *dns_cache); - -int dns_cache_hitnum_dec_get(struct dns_cache *dns_cache); - -void dns_cache_update(struct dns_cache *dns_cache); - -typedef void dns_cache_preinvalid_callback(struct dns_cache *dns_cache); - -void dns_cache_invalidate(dns_cache_preinvalid_callback callback, int ttl_pre); - -int dns_cache_get_ttl(struct dns_cache *dns_cache); - -void dns_cache_destroy(void); - -#ifdef __cpluscplus -} -#endif -#endif // !_SMARTDNS_CACHE_H +/************************************************************************* + * + * Copyright (C) 2018-2020 Ruilin Peng (Nick) . + * + * smartdns is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * smartdns is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef _SMARTDNS_CACHE_H +#define _SMARTDNS_CACHE_H + +#include "atomic.h" +#include "dns.h" +#include "hash.h" +#include "hashtable.h" +#include "list.h" +#include +#include + +#ifdef __cpluscplus +extern "C" { +#endif + +#define DNS_CACHE_TTL_MIN 30 + +struct dns_cache { + struct hlist_node node; + struct list_head list; + struct list_head check_list; + atomic_t ref; + char domain[DNS_MAX_CNAME_LEN]; + char cname[DNS_MAX_CNAME_LEN]; + unsigned int cname_ttl; + unsigned int ttl; + int speed; + atomic_t hitnum; + int hitnum_update_add; + int del_pending; + time_t insert_time; + dns_type_t qtype; + union { + unsigned char ipv4_addr[DNS_RR_A_LEN]; + unsigned char ipv6_addr[DNS_RR_AAAA_LEN]; + unsigned char addr[0]; + }; +}; + +int dns_cache_init(int size, int enable_inactive, int inactive_list_expired); + +int dns_cache_replace(char *domain, char *cname, int cname_ttl, int ttl, dns_type_t qtype, unsigned char *addr, + int addr_len, int speed); + +int dns_cache_insert(char *domain, char *cname, int cname_ttl, int ttl, dns_type_t qtype, unsigned char *addr, + int addr_len, int speed); + +struct dns_cache *dns_cache_lookup(char *domain, dns_type_t qtype); + +void dns_cache_delete(struct dns_cache *dns_cache); + +void dns_cache_get(struct dns_cache *dns_cache); + +void dns_cache_release(struct dns_cache *dns_cache); + +int dns_cache_hitnum_dec_get(struct dns_cache *dns_cache); + +void dns_cache_update(struct dns_cache *dns_cache); + +typedef void dns_cache_preinvalid_callback(struct dns_cache *dns_cache); + +void dns_cache_invalidate(dns_cache_preinvalid_callback callback, int ttl_pre); + +int dns_cache_get_ttl(struct dns_cache *dns_cache); + +void dns_cache_destroy(void); + +#ifdef __cpluscplus +} +#endif +#endif // !_SMARTDNS_CACHE_H diff --git a/release/src/router/smartdns/src/dns_client.c b/release/src/router/smartdns/src/dns_client.c index eccb8e87b9..18b6d43d1a 100644 --- a/release/src/router/smartdns/src/dns_client.c +++ b/release/src/router/smartdns/src/dns_client.c @@ -29,8 +29,8 @@ #include "tlog.h" #include "util.h" #include -#include #include +#include #include #include #include @@ -46,7 +46,6 @@ #include #include #include -#include #include #include #include @@ -59,11 +58,11 @@ #define DNS_TCP_IDLE_TIMEOUT (60 * 10) #define DNS_TCP_CONNECT_TIMEOUT (5) #define DNS_QUERY_TIMEOUT (500) -#define DNS_QUERY_RETRY (3) +#define DNS_QUERY_RETRY (6) +#define DNS_PENDING_SERVER_RETRY 40 #define SOCKET_PRIORITY (6) #define SOCKET_IP_TOS (IPTOS_LOWDELAY | IPTOS_RELIABILITY) - /* ECS info */ struct dns_client_ecs { int enable; @@ -108,6 +107,7 @@ struct dns_server_info { SSL *ssl; SSL_CTX *ssl_ctx; SSL_SESSION *ssl_session; + char skip_check_cert; dns_server_status status; struct dns_server_buff send_buff; @@ -136,6 +136,7 @@ struct dns_server_pending_group { struct dns_server_pending { struct list_head list; + atomic_t refcnt; char host[DNS_HOSTNAME_LEN]; char ipv4[DNS_HOSTNAME_LEN]; @@ -148,6 +149,7 @@ struct dns_server_pending { unsigned int query_v6; /* server type */ dns_server_type_t type; + int retry_cnt; int port; @@ -246,12 +248,11 @@ static LIST_HEAD(pending_servers); static pthread_mutex_t pending_server_mutex = PTHREAD_MUTEX_INITIALIZER; static int dns_client_has_bootstrap_dns = 0; -const char *_dns_server_get_type_string(dns_server_type_t type) +const char *_dns_server_get_type_string(dns_server_type_t type) { const char *type_str = ""; - switch (type) - { + switch (type) { case DNS_SERVER_UDP: type_str = "udp"; break; @@ -321,8 +322,9 @@ static int _dns_client_server_exist(const char *server_ip, int port, dns_server_ return -1; } -static void _dns_client_server_update_ttl(struct ping_host_struct *ping_host, const char *host, FAST_PING_RESULT result, struct sockaddr *addr, - socklen_t addr_len, int seqno, int ttl, struct timeval *tv, void *userptr) +static void _dns_client_server_update_ttl(struct ping_host_struct *ping_host, const char *host, FAST_PING_RESULT result, + struct sockaddr *addr, socklen_t addr_len, int seqno, int ttl, + struct timeval *tv, void *userptr) { struct dns_server_info *server_info = userptr; if (result != PING_RESULT_RESPONSE || server_info == NULL) { @@ -478,7 +480,8 @@ static int _dns_client_add_to_pending_group(char *group_name, char *server_ip, i } /* add server to group */ -static int _dns_client_add_to_group_pending(char *group_name, char *server_ip, int port, dns_server_type_t server_type, int ispending) +static int _dns_client_add_to_group_pending(char *group_name, char *server_ip, int port, dns_server_type_t server_type, + int ispending) { struct dns_server_info *server_info = NULL; @@ -712,8 +715,42 @@ static char *_dns_client_server_get_spki(struct dns_server_info *server_info, in return spki; } +static int _dns_client_set_trusted_cert(SSL_CTX *ssl_ctx) +{ + char *cafile = NULL; + char *capath = NULL; + int cert_path_set = 0; + + if (dns_conf_ca_file[0]) { + cafile = dns_conf_ca_file; + } + + if (dns_conf_ca_path[0]) { + capath = dns_conf_ca_path; + } + + if (cafile == NULL && capath == NULL) { + if (SSL_CTX_set_default_verify_paths(ssl_ctx)) { + cafile = "/etc/ssl/certs/ca-certificates.crt"; + capath = "/etc/ssl/certs"; + } else { + cert_path_set = 1; + } + } + + if (cert_path_set == 0) { + if (!SSL_CTX_load_verify_locations(ssl_ctx, cafile, capath)) { + tlog(TLOG_WARN, "load certificate from %s:%s failed.", cafile, capath); + return -1; + } + } + + return 0; +} + /* add dns server information */ -static int _dns_client_server_add(char *server_ip, char *server_host, int port, dns_server_type_t server_type, struct client_dns_server_flags *flags) +static int _dns_client_server_add(char *server_ip, char *server_host, int port, dns_server_type_t server_type, + struct client_dns_server_flags *flags) { struct dns_server_info *server_info = NULL; struct addrinfo *gai = NULL; @@ -721,6 +758,7 @@ static int _dns_client_server_add(char *server_ip, char *server_host, int port, int ttl = 0; char port_s[8]; int sock_type; + char skip_check_cert = 0; switch (server_type) { case DNS_SERVER_UDP: { @@ -745,11 +783,13 @@ static int _dns_client_server_add(char *server_ip, char *server_host, int port, } } sock_type = SOCK_STREAM; + skip_check_cert = flag_https->skip_check_cert; } break; case DNS_SERVER_TLS: { struct client_dns_server_flag_tls *flag_tls = &flags->tls; spki_data_len = flag_tls->spi_len; sock_type = SOCK_STREAM; + skip_check_cert = flag_tls->skip_check_cert; } break; case DNS_SERVER_TCP: sock_type = SOCK_STREAM; @@ -795,6 +835,7 @@ static int _dns_client_server_add(char *server_ip, char *server_host, int port, server_info->status = DNS_SERVER_STATUS_INIT; server_info->ttl = ttl; server_info->ttl_range = 0; + server_info->skip_check_cert = skip_check_cert; memcpy(&server_info->flags, flags, sizeof(server_info->flags)); /* exclude this server from default group */ @@ -812,6 +853,11 @@ static int _dns_client_server_add(char *server_ip, char *server_host, int port, #else server_info->ssl_ctx = SSL_CTX_new(SSLv23_client_method()); #endif + if (_dns_client_set_trusted_cert(server_info->ssl_ctx) != 0) { + tlog(TLOG_WARN, "disable check certificate for %s.", server_info->ip); + server_info->skip_check_cert = 1; + } + if (server_info->ssl_ctx == NULL) { tlog(TLOG_ERROR, "init ssl failed."); goto errout; @@ -820,7 +866,8 @@ static int _dns_client_server_add(char *server_ip, char *server_host, int port, /* safe address info */ if (gai->ai_addrlen > sizeof(server_info->in6)) { - tlog(TLOG_ERROR, "addr len invalid, %d, %zd, %d", gai->ai_addrlen, sizeof(server_info->addr), server_info->ai_family); + tlog(TLOG_ERROR, "addr len invalid, %d, %zd, %d", gai->ai_addrlen, sizeof(server_info->addr), + server_info->ai_family); goto errout; } memcpy(&server_info->addr, gai->ai_addr, gai->ai_addrlen); @@ -828,7 +875,8 @@ static int _dns_client_server_add(char *server_ip, char *server_host, int port, /* start ping task */ if (server_type == DNS_SERVER_UDP) { if (ttl <= 0 && (server_info->flags.result_flag & DNSSERVER_FLAG_CHECK_TTL)) { - server_info->ping_host = fast_ping_start(PING_TYPE_DNS, server_ip, 0, 60000, 1000, _dns_client_server_update_ttl, server_info); + server_info->ping_host = + fast_ping_start(PING_TYPE_DNS, server_ip, 0, 60000, 1000, _dns_client_server_update_ttl, server_info); if (server_info->ping_host == NULL) { tlog(TLOG_ERROR, "start ping failed."); goto errout; @@ -879,7 +927,6 @@ static void _dns_client_close_socket(struct dns_server_info *server_info) if (server_info->ssl) { /* Shutdown ssl */ - SSL_shutdown(server_info->ssl); SSL_free(server_info->ssl); server_info->ssl = NULL; } @@ -961,7 +1008,51 @@ static int _dns_client_server_remove(char *server_ip, int port, dns_server_type_ return -1; } -static int _dns_client_server_pending(char *server_ip, int port, dns_server_type_t server_type, struct client_dns_server_flags *flags) +void _dns_client_server_pending_get(struct dns_server_pending *pending) +{ + if (atomic_inc_return(&pending->refcnt) <= 0) { + tlog(TLOG_ERROR, "BUG: pending ref is invalid"); + abort(); + } +} + +void _dns_client_server_pending_release_lck(struct dns_server_pending *pending) +{ + int refcnt = atomic_dec_return(&pending->refcnt); + + if (refcnt) { + if (refcnt < 0) { + tlog(TLOG_ERROR, "BUG: pending refcnt is %d", refcnt); + abort(); + } + return; + } + + list_del_init(&pending->list); + free(pending); +} + +void _dns_client_server_pending_release(struct dns_server_pending *pending) +{ + int refcnt = atomic_dec_return(&pending->refcnt); + + if (refcnt) { + if (refcnt < 0) { + tlog(TLOG_ERROR, "BUG: pending refcnt is %d", refcnt); + abort(); + } + return; + } + + pthread_mutex_lock(&pending_server_mutex); + list_del_init(&pending->list); + pthread_mutex_unlock(&pending_server_mutex); + + free(pending); +} + +static int _dns_client_server_pending(char *server_ip, int port, dns_server_type_t server_type, + struct client_dns_server_flags *flags) { struct dns_server_pending *pending = NULL; @@ -981,6 +1072,7 @@ static int _dns_client_server_pending(char *server_ip, int port, dns_server_type pending->ipv6[0] = 0; pending->has_v4 = 0; pending->has_v6 = 0; + _dns_client_server_pending_get(pending); INIT_LIST_HEAD(&pending->group_list); memcpy(&pending->flags, flags, sizeof(struct client_dns_server_flags)); @@ -996,8 +1088,8 @@ static int _dns_client_server_pending(char *server_ip, int port, dns_server_type return -1; } -static int _dns_client_add_server_pending(char *server_ip, char *server_host, int port, dns_server_type_t server_type, struct client_dns_server_flags *flags, - int ispending) +static int _dns_client_add_server_pending(char *server_ip, char *server_host, int port, dns_server_type_t server_type, + struct client_dns_server_flags *flags, int ispending) { int ret; @@ -1027,7 +1119,8 @@ static int _dns_client_add_server_pending(char *server_ip, char *server_host, in return -1; } -int dns_client_add_server(char *server_ip, int port, dns_server_type_t server_type, struct client_dns_server_flags *flags) +int dns_client_add_server(char *server_ip, int port, dns_server_type_t server_type, + struct client_dns_server_flags *flags) { return _dns_client_add_server_pending(server_ip, NULL, port, server_type, flags, 1); } @@ -1243,7 +1336,8 @@ static int _dns_replied_check_add(struct dns_query_struct *dns_query, struct soc return 0; } -static int _dns_client_recv(struct dns_server_info *server_info, unsigned char *inpacket, int inpacket_len, struct sockaddr *from, socklen_t from_len) +static int _dns_client_recv(struct dns_server_info *server_info, unsigned char *inpacket, int inpacket_len, + struct sockaddr *from, socklen_t from_len) { int len; int i; @@ -1265,8 +1359,8 @@ static int _dns_client_recv(struct dns_server_info *server_info, unsigned char * len = dns_decode(packet, DNS_PACKSIZE, inpacket, inpacket_len); if (len != 0) { char host_name[DNS_MAX_CNAME_LEN]; - tlog(TLOG_WARN, "decode failed, packet len = %d, tc = %d, id = %d, from = %s\n", inpacket_len, packet->head.tc, packet->head.id, - gethost_by_addr(host_name, sizeof(host_name), from)); + tlog(TLOG_WARN, "decode failed, packet len = %d, tc = %d, id = %d, from = %s\n", inpacket_len, packet->head.tc, + packet->head.id, gethost_by_addr(host_name, sizeof(host_name), from)); return -1; } @@ -1276,9 +1370,12 @@ static int _dns_client_recv(struct dns_server_info *server_info, unsigned char * return -1; } - tlog(TLOG_DEBUG, "qdcount = %d, ancount = %d, nscount = %d, nrcount = %d, len = %d, id = %d, tc = %d, rd = %d, ra = %d, rcode = %d, payloadsize = %d\n", - packet->head.qdcount, packet->head.ancount, packet->head.nscount, packet->head.nrcount, inpacket_len, packet->head.id, packet->head.tc, - packet->head.rd, packet->head.ra, packet->head.rcode, dns_get_OPT_payload_size(packet)); + tlog(TLOG_DEBUG, + "qdcount = %d, ancount = %d, nscount = %d, nrcount = %d, len = %d, id = %d, tc = %d, rd = %d, ra = %d, rcode " + "= %d, payloadsize = %d\n", + packet->head.qdcount, packet->head.ancount, packet->head.nscount, packet->head.nrcount, inpacket_len, + packet->head.id, packet->head.tc, packet->head.rd, packet->head.ra, packet->head.rcode, + dns_get_OPT_payload_size(packet)); /* get question */ rrs = dns_get_rrs_start(packet, DNS_RRS_QD, &rr_count); @@ -1317,7 +1414,8 @@ static int _dns_client_recv(struct dns_server_info *server_info, unsigned char * /* notify caller dns query result */ if (query->callback) { - ret = query->callback(query->domain, DNS_QUERY_RESULT, server_info->flags.result_flag, packet, inpacket, inpacket_len, query->user_ptr); + ret = query->callback(query->domain, DNS_QUERY_RESULT, server_info->flags.result_flag, packet, inpacket, + inpacket_len, query->user_ptr); if (request_num == 0 || ret) { /* if all server replied, or done, stop query, release resource */ _dns_client_query_remove(query); @@ -1474,11 +1572,11 @@ static int _DNS_client_create_socket_tls(struct dns_server_info *server_info, ch // ? this cause ssl crash ? // setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(yes)); + // setsockopt(fd, IPPROTO_TCP, TCP_THIN_DUPACK, &yes, sizeof(yes)); + // setsockopt(fd, IPPROTO_TCP, TCP_THIN_LINEAR_TIMEOUTS, &yes, sizeof(yes)); // set_sock_keepalive(fd, 15, 3, 4); setsockopt(fd, SOL_SOCKET, SO_PRIORITY, &priority, sizeof(priority)); setsockopt(fd, IPPROTO_IP, IP_TOS, &ip_tos, sizeof(ip_tos)); - setsockopt(fd, IPPROTO_TCP, TCP_THIN_DUPACK, &yes, sizeof(yes)); - setsockopt(fd, IPPROTO_TCP, TCP_THIN_LINEAR_TIMEOUTS, &yes, sizeof(yes)); if (connect(fd, (struct sockaddr *)&server_info->addr, server_info->ai_addrlen) != 0) { if (errno != EINPROGRESS) { @@ -1602,7 +1700,8 @@ static int _dns_client_process_udp(struct dns_server_info *server_info, struct e } } - tlog(TLOG_DEBUG, "recv udp packet from %s, len: %d, ttl: %d", gethost_by_addr(from_host, sizeof(from_host), (struct sockaddr *)&from), len, ttl); + tlog(TLOG_DEBUG, "recv udp packet from %s, len: %d, ttl: %d", + gethost_by_addr(from_host, sizeof(from_host), (struct sockaddr *)&from), len, ttl); /* update recv time */ time(&server_info->last_recv); @@ -1747,7 +1846,8 @@ static int _dns_client_socket_recv(struct dns_server_info *server_info) if (server_info->type == DNS_SERVER_UDP) { return -1; } else if (server_info->type == DNS_SERVER_TCP) { - return recv(server_info->fd, server_info->recv_buff.data + server_info->recv_buff.len, DNS_TCP_BUFFER - server_info->recv_buff.len, 0); + return recv(server_info->fd, server_info->recv_buff.data + server_info->recv_buff.len, + DNS_TCP_BUFFER - server_info->recv_buff.len, 0); } else if (server_info->type == DNS_SERVER_TLS || server_info->type == DNS_SERVER_HTTPS) { return _dns_client_socket_ssl_recv(server_info->ssl, server_info->recv_buff.data + server_info->recv_buff.len, DNS_TCP_BUFFER - server_info->recv_buff.len); @@ -1762,29 +1862,31 @@ static int _dns_client_process_tcp_buff(struct dns_server_info *server_info) int dns_packet_len = 0; struct http_head *http_head = NULL; unsigned char *inpacket_data = NULL; + int ret = -1; while (1) { if (server_info->type == DNS_SERVER_HTTPS) { http_head = http_head_init(4096); if (http_head == NULL) { - goto errout; + goto out; } len = http_head_parse(http_head, (char *)server_info->recv_buff.data, server_info->recv_buff.len); if (len < 0) { - tlog(TLOG_DEBUG, "remote server not supported."); if (len == -1) { - break; + ret = 0; + goto out; } - goto errout; + + tlog(TLOG_DEBUG, "remote server not supported."); + goto out; } if (http_head_get_httpcode(http_head) != 200) { - tlog(TLOG_WARN, "http server query from %s:%d failed, server return http code : %d, %s", - server_info->ip, server_info->port, - http_head_get_httpcode(http_head), - http_head_get_httpcode_msg(http_head)); - goto errout; + tlog(TLOG_WARN, "http server query from %s:%d failed, server return http code : %d, %s", + server_info->ip, server_info->port, http_head_get_httpcode(http_head), + http_head_get_httpcode_msg(http_head)); + goto out; } dns_packet_len = http_head_get_data_len(http_head); @@ -1797,12 +1899,13 @@ static int _dns_client_process_tcp_buff(struct dns_server_info *server_info) len = ntohs(*((unsigned short *)(inpacket_data))); if (len <= 0 || len >= DNS_IN_PACKSIZE) { /* data len is invalid */ - goto errout; + goto out; } if (len > server_info->recv_buff.len - 2) { /* len is not expceded, wait and recv */ - break; + ret = 0; + goto out; } inpacket_data = server_info->recv_buff.data + 2; @@ -1812,8 +1915,9 @@ static int _dns_client_process_tcp_buff(struct dns_server_info *server_info) tlog(TLOG_DEBUG, "recv tcp packet from %s, len = %d", server_info->ip, len); /* process result */ - if (_dns_client_recv(server_info, inpacket_data, dns_packet_len, &server_info->addr, server_info->ai_addrlen) != 0) { - goto errout; + if (_dns_client_recv(server_info, inpacket_data, dns_packet_len, &server_info->addr, server_info->ai_addrlen) != + 0) { + goto out; } if (http_head) { @@ -1822,21 +1926,26 @@ static int _dns_client_process_tcp_buff(struct dns_server_info *server_info) } server_info->recv_buff.len -= len; + if (server_info->recv_buff.len < 0) { + tlog(TLOG_ERROR, "Internal error."); + abort(); + } /* move to next result */ if (server_info->recv_buff.len > 0) { memmove(server_info->recv_buff.data, server_info->recv_buff.data + len, server_info->recv_buff.len); } else { - break; + ret = 0; + goto out; } } - return 0; -errout: + ret = 0; +out: if (http_head) { http_head_destroy(http_head); } - return -1; + return ret; } static int _dns_client_process_tcp(struct dns_server_info *server_info, struct epoll_event *event, unsigned long now) @@ -1880,7 +1989,7 @@ static int _dns_client_process_tcp(struct dns_server_info *server_info, struct e time(&server_info->last_recv); server_info->recv_buff.len += len; - if (server_info->recv_buff.len < 2) { + if (server_info->recv_buff.len <= 2) { /* wait and recv */ return 0; } @@ -1917,6 +2026,9 @@ static int _dns_client_process_tcp(struct dns_server_info *server_info, struct e server_info->send_buff.len -= len; if (server_info->send_buff.len > 0) { memmove(server_info->send_buff.data, server_info->send_buff.data + len, server_info->send_buff.len); + } else if (server_info->send_buff.len < 0) { + tlog(TLOG_ERROR, "Internal Error"); + abort(); } pthread_mutex_unlock(&client.server_list_lock); } @@ -1930,7 +2042,7 @@ static int _dns_client_process_tcp(struct dns_server_info *server_info, struct e event.events = EPOLLIN; event.data.ptr = server_info; if (epoll_ctl(client.epoll_fd, EPOLL_CTL_MOD, server_info->fd, &event) != 0) { - tlog(TLOG_ERROR, "epoll ctl failed."); + tlog(TLOG_ERROR, "epoll ctl failed, %s", strerror(errno)); goto errout; } } @@ -1980,13 +2092,15 @@ static int _dns_client_tls_matchName(const char *host, const char *pattern, int if (i == size && host[j] == '\0') { match = 0; } - + return match; } static int _dns_client_tls_verify(struct dns_server_info *server_info) { X509 *cert = NULL; + X509_PUBKEY *pubkey = NULL; + X509_NAME *cert_name = NULL; char peer_CN[256]; char cert_fingerprint[256]; int i = 0; @@ -2007,20 +2121,45 @@ static int _dns_client_tls_verify(struct dns_server_info *server_info) return -1; } - X509_NAME_get_text_by_NID(X509_get_subject_name(cert), NID_commonName, peer_CN, 256); + if (server_info->skip_check_cert == 0) { + long res = SSL_get_verify_result(server_info->ssl); + if (res != X509_V_OK) { + tlog(TLOG_WARN, "peer server certificate verify failed."); + goto errout; + } + } + + cert_name = X509_get_subject_name(cert); + if (cert_name == NULL) { + tlog(TLOG_ERROR, "get subject name failed."); + goto errout; + } + + if (X509_NAME_get_text_by_NID(cert_name, NID_commonName, peer_CN, 256) == -1) { + tlog(TLOG_ERROR, "cannot found x509 name"); + goto errout; + } + tlog(TLOG_DEBUG, "peer CN: %s", peer_CN); /* check tls host */ tls_host_verify = _dns_client_server_get_tls_host_verify(server_info); if (tls_host_verify) { - if (_dns_client_tls_matchName(peer_CN, tls_host_verify, strnlen(tls_host_verify, DNS_MAX_CNAME_LEN)) != 0) { - tlog(TLOG_INFO, "server %s CN is invalid, peer CN: %s, expect CN: %s", server_info->ip, peer_CN, tls_host_verify); + if (_dns_client_tls_matchName(tls_host_verify, peer_CN, strnlen(peer_CN, DNS_MAX_CNAME_LEN)) != 0) { + tlog(TLOG_INFO, "server %s CN is invalid, peer CN: %s, expect CN: %s", server_info->ip, peer_CN, + tls_host_verify); goto errout; } } + pubkey = X509_get_X509_PUBKEY(cert); + if (pubkey == NULL) { + tlog(TLOG_ERROR, "get pub key failed."); + goto errout; + } + /* get spki pin */ - key_len = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), NULL); + key_len = i2d_X509_PUBKEY(pubkey, NULL); if (key_len <= 0) { tlog(TLOG_ERROR, "get x509 public key failed."); goto errout; @@ -2033,7 +2172,7 @@ static int _dns_client_tls_verify(struct dns_server_info *server_info) goto errout; } - i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), &key_data_tmp); + i2d_X509_PUBKEY(pubkey, &key_data_tmp); /* Get the SHA256 value of SPKI */ key_sha256 = SSL_SHA256(key_data, key_len, NULL); @@ -2056,7 +2195,7 @@ static int _dns_client_tls_verify(struct dns_server_info *server_info) tlog(TLOG_DEBUG, "cert SPKI pin(%s): %s", "sha256", cert_fingerprint); spki = _dns_client_server_get_spki(server_info, &spki_len); - if (spki) { + if (spki && spki_len > 0 && spki_len <= SHA256_DIGEST_LENGTH) { /* check SPKI */ if (memcmp(spki, key_sha256, spki_len) != 0) { tlog(TLOG_INFO, "server %s cert spki is invalid", server_info->ip); @@ -2111,7 +2250,7 @@ static int _dns_client_process_tls(struct dns_server_info *server_info, struct e fd_event.data.ptr = server_info; if (epoll_ctl(client.epoll_fd, EPOLL_CTL_MOD, server_info->fd, &fd_event) != 0) { - tlog(TLOG_ERROR, "epoll ctl failed."); + tlog(TLOG_ERROR, "epoll ctl failed, %s", strerror(errno)); goto errout; } @@ -2147,7 +2286,7 @@ static int _dns_client_process_tls(struct dns_server_info *server_info, struct e fd_event.events = EPOLLIN | EPOLLOUT; fd_event.data.ptr = server_info; if (epoll_ctl(client.epoll_fd, EPOLL_CTL_MOD, server_info->fd, &fd_event) != 0) { - tlog(TLOG_ERROR, "epoll ctl failed."); + tlog(TLOG_ERROR, "epoll ctl failed, %s", strerror(errno)); goto errout; } } @@ -2290,11 +2429,11 @@ static int _dns_client_send_tls(struct dns_server_info *server_info, void *packe send_len = _dns_client_socket_ssl_send(server_info->ssl, inpacket, len); if (send_len < 0) { - if (errno == EAGAIN || errno == EPIPE || server_info->ssl == NULL ) { + if (errno == EAGAIN || errno == EPIPE || server_info->ssl == NULL) { /* save data to buffer, and retry when EPOLLOUT is available */ return _dns_client_send_data_to_buffer(server_info, inpacket, len); } else if (server_info->ssl && errno != ENOMEM) { - SSL_shutdown(server_info->ssl); + SSL_set_shutdown(server_info->ssl, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN); } return -1; } else if (send_len < len) { @@ -2340,11 +2479,11 @@ static int _dns_client_send_https(struct dns_server_info *server_info, void *pac send_len = _dns_client_socket_ssl_send(server_info->ssl, inpacket, http_len); if (send_len < 0) { - if (errno == EAGAIN || errno == EPIPE || server_info->ssl == NULL ) { + if (errno == EAGAIN || errno == EPIPE || server_info->ssl == NULL) { /* save data to buffer, and retry when EPOLLOUT is available */ return _dns_client_send_data_to_buffer(server_info, inpacket, http_len); } else if (server_info->ssl && errno != ENOMEM) { - SSL_shutdown(server_info->ssl); + SSL_set_shutdown(server_info->ssl, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN); } return -1; } else if (send_len < http_len) { @@ -2407,9 +2546,11 @@ static int _dns_client_send_packet(struct dns_query_struct *query, void *packet, if (ret != 0) { if (send_err != ENOMEM) { - tlog(TLOG_ERROR, "send query to %s failed, %s, type: %d", server_info->ip, strerror(send_err), server_info->type); + tlog(TLOG_ERROR, "send query to %s failed, %s, type: %d", server_info->ip, strerror(send_err), + server_info->type); } else { - tlog(TLOG_DEBUG, "send query to %s failed, %s, type: %d", server_info->ip, strerror(send_err), server_info->type); + tlog(TLOG_DEBUG, "send query to %s failed, %s, type: %d", server_info->ip, strerror(send_err), + server_info->type); } atomic_dec(&query->dns_request_sent); continue; @@ -2586,29 +2727,32 @@ static void _dns_client_check_servers(void) pthread_mutex_unlock(&client.server_list_lock); } -static int _dns_client_pending_server_resolve(char *domain, dns_rtcode_t rtcode, dns_type_t addr_type, char *ip, unsigned int ping_time, void *user_ptr) +static int _dns_client_pending_server_resolve(char *domain, dns_rtcode_t rtcode, dns_type_t addr_type, char *ip, + unsigned int ping_time, void *user_ptr) { struct dns_server_pending *pending = user_ptr; + int ret = 0; if (addr_type == DNS_T_A) { - pending->has_v4 = 1; pending->ping_time_v4 = -1; if (rtcode == DNS_RC_NOERROR) { + pending->has_v4 = 1; pending->ping_time_v4 = ping_time; safe_strncpy(pending->ipv4, ip, DNS_HOSTNAME_LEN); } } else if (addr_type == DNS_T_AAAA) { - pending->has_v6 = 1; pending->ping_time_v6 = -1; if (rtcode == DNS_RC_NOERROR) { + pending->has_v6 = 1; pending->ping_time_v6 = ping_time; safe_strncpy(pending->ipv6, ip, DNS_HOSTNAME_LEN); } } else { - return -1; + ret = -1; } - return 0; + _dns_client_server_pending_release(pending); + return ret; } static int _dns_client_add_pendings(struct dns_server_pending *pending, char *ip) @@ -2641,37 +2785,61 @@ static void _dns_client_add_pending_servers(void) if (++dely < 3) { return; } + dely = 0; pthread_mutex_lock(&pending_server_mutex); list_for_each_entry_safe(pending, tmp, &pending_servers, list) { /* send dns type A, AAAA query to bootstrap DNS server */ + int add_success = 0; + char *dnsserver_ip = NULL; + if (pending->query_v4 == 0) { pending->query_v4 = 1; - dns_server_query(pending->host, DNS_T_A, _dns_client_pending_server_resolve, pending); + _dns_client_server_pending_get(pending); + if (dns_server_query(pending->host, DNS_T_A, _dns_client_pending_server_resolve, pending) != 0) { + _dns_client_server_pending_release_lck(pending); + } } if (pending->query_v6 == 0) { pending->query_v6 = 1; - dns_server_query(pending->host, DNS_T_AAAA, _dns_client_pending_server_resolve, pending); + _dns_client_server_pending_get(pending); + if (dns_server_query(pending->host, DNS_T_AAAA, _dns_client_pending_server_resolve, pending) != 0) { + _dns_client_server_pending_release_lck(pending); + } } /* if both A, AAAA has query result, select fastest IP address */ if (pending->has_v4 && pending->has_v6) { - char *ip = NULL; + if (pending->ping_time_v4 <= pending->ping_time_v6 && pending->ipv4[0]) { - ip = pending->ipv4; + dnsserver_ip = pending->ipv4; } else { - ip = pending->ipv6; + dnsserver_ip = pending->ipv6; } + } else if (pending->has_v4) { + dnsserver_ip = pending->ipv4; + } else if (pending->has_v6) { + dnsserver_ip = pending->ipv6; + } - if (ip[0]) { - if (_dns_client_add_pendings(pending, ip) != 0) { - tlog(TLOG_WARN, "add pending DNS server %s failed.", pending->host); - } + if (dnsserver_ip && dnsserver_ip[0]) { + if (_dns_client_add_pendings(pending, dnsserver_ip) == 0) { + add_success = 1; + } + } + + pending->retry_cnt++; + if (pending->retry_cnt >= DNS_PENDING_SERVER_RETRY || add_success) { + if (add_success == 0) { + tlog(TLOG_WARN, "add pending DNS server %s failed.", pending->host); } - list_del_init(&pending->list); - free(pending); + _dns_client_server_pending_release_lck(pending); + } else { + tlog(TLOG_DEBUG, "add pending DNS server %s failed, retry %d...", pending->host, pending->retry_cnt); + pending->query_v4 = 0; + pending->query_v6 = 0; } /* if has no bootstrap DNS, just call getaddrinfo to get address */ @@ -2682,8 +2850,8 @@ static void _dns_client_add_pending_servers(void) exit(1); return; } - list_del_init(&pending->list); - free(pending); + + _dns_client_server_pending_release_lck(pending); } } pthread_mutex_unlock(&pending_server_mutex); diff --git a/release/src/router/smartdns/src/dns_client.h b/release/src/router/smartdns/src/dns_client.h index 5610399046..c04a5d82a7 100644 --- a/release/src/router/smartdns/src/dns_client.h +++ b/release/src/router/smartdns/src/dns_client.h @@ -52,8 +52,9 @@ int dns_client_init(void); int dns_client_set_ecs(char *ip, int subnet); /* query result notify function */ -typedef int (*dns_client_callback)(char *domain, dns_result_type rtype, unsigned int result_flag, struct dns_packet *packet, unsigned char *inpacket, - int inpacket_len, void *user_ptr); +typedef int (*dns_client_callback)(char *domain, dns_result_type rtype, unsigned int result_flag, + struct dns_packet *packet, unsigned char *inpacket, int inpacket_len, + void *user_ptr); /* query domain */ int dns_client_query(char *domain, int qtype, dns_client_callback callback, void *user_ptr, const char *group_name); @@ -69,6 +70,7 @@ struct client_dns_server_flag_tls { int spi_len; char hostname[DNS_MAX_CNAME_LEN]; char tls_host_verify[DNS_MAX_CNAME_LEN]; + char skip_check_cert; }; struct client_dns_server_flag_https { @@ -78,6 +80,7 @@ struct client_dns_server_flag_https { char httphost[DNS_MAX_CNAME_LEN]; char path[DNS_MAX_CNAME_LEN]; char tls_host_verify[DNS_MAX_CNAME_LEN]; + char skip_check_cert; }; struct client_dns_server_flags { @@ -95,7 +98,8 @@ struct client_dns_server_flags { int dns_client_spki_decode(const char *spki, unsigned char *spki_data_out); /* add remote dns server */ -int dns_client_add_server(char *server_ip, int port, dns_server_type_t server_type, struct client_dns_server_flags *flags); +int dns_client_add_server(char *server_ip, int port, dns_server_type_t server_type, + struct client_dns_server_flags *flags); /* remove remote dns server */ int dns_client_remove_server(char *server_ip, int port, dns_server_type_t server_type); diff --git a/release/src/router/smartdns/src/dns_conf.c b/release/src/router/smartdns/src/dns_conf.c index cdf90cf642..6812753301 100644 --- a/release/src/router/smartdns/src/dns_conf.c +++ b/release/src/router/smartdns/src/dns_conf.c @@ -1,1362 +1,1510 @@ -/************************************************************************* - * - * Copyright (C) 2018-2020 Ruilin Peng (Nick) . - * - * smartdns is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * smartdns is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#include "dns_conf.h" -#include "list.h" -#include "rbtree.h" -#include "tlog.h" -#include "util.h" -#include -#include -#include -#include -#include -#include -#include - -#define DEFAULT_DNS_CACHE_SIZE 512 - -/* ipset */ -struct dns_ipset_table { - DECLARE_HASHTABLE(ipset, 8); -}; -static struct dns_ipset_table dns_ipset_table; - -/* dns groups */ -struct dns_group_table dns_group_table; - -/* server ip/port */ -struct dns_bind_ip dns_conf_bind_ip[DNS_MAX_BIND_IP]; -int dns_conf_bind_ip_num = 0; -int dns_conf_tcp_idle_time = 120; - -/* cache */ -int dns_conf_cachesize = DEFAULT_DNS_CACHE_SIZE; -int dns_conf_prefetch = 0; - -/* upstream servers */ -struct dns_servers dns_conf_servers[DNS_MAX_SERVERS]; -char dns_conf_server_name[DNS_MAX_SERVER_NAME_LEN]; -int dns_conf_server_num; - -struct dns_domain_check_order dns_conf_check_order = { - .order = {DOMAIN_CHECK_ICMP, DOMAIN_CHECK_TCP}, - .tcp_port = 80, -}; - -/* logging */ -int dns_conf_log_level = TLOG_ERROR; -char dns_conf_log_file[DNS_MAX_PATH]; -size_t dns_conf_log_size = 1024 * 1024; -int dns_conf_log_num = 8; - -/* auditing */ -int dns_conf_audit_enable = 0; -int dns_conf_audit_log_SOA; -char dns_conf_audit_file[DNS_MAX_PATH]; -size_t dns_conf_audit_size = 1024 * 1024; -int dns_conf_audit_num = 2; - -/* address rules */ -art_tree dns_conf_domain_rule; -struct dns_conf_address_rule dns_conf_address_rule; - -/* dual-stack selection */ -int dns_conf_dualstack_ip_selection; -int dns_conf_dualstack_ip_selection_threshold = 30; - -/* TTL */ -int dns_conf_rr_ttl; -int dns_conf_rr_ttl_min; -int dns_conf_rr_ttl_max; -int dns_conf_force_AAAA_SOA; - -int dns_conf_ipset_timeout_enable; - -/* ECS */ -struct dns_edns_client_subnet dns_conf_ipv4_ecs; -struct dns_edns_client_subnet dns_conf_ipv6_ecs; - -char dns_conf_sni_proxy_ip[DNS_MAX_IPLEN]; - -/* create and get dns server group */ -static struct dns_server_groups *_dns_conf_get_group(const char *group_name) -{ - uint32_t key = 0; - struct dns_server_groups *group = NULL; - - key = hash_string(group_name); - hash_for_each_possible(dns_group_table.group, group, node, key) - { - if (strncmp(group->group_name, group_name, DNS_MAX_IPLEN) == 0) { - return group; - } - } - - group = malloc(sizeof(*group)); - if (group == NULL) { - goto errout; - } - - memset(group, 0, sizeof(*group)); - safe_strncpy(group->group_name, group_name, DNS_GROUP_NAME_LEN); - hash_add(dns_group_table.group, &group->node, key); - - return group; -errout: - if (group) { - free(group); - } - - return NULL; -} - -static int _dns_conf_get_group_set(const char *group_name, struct dns_servers *server) -{ - struct dns_server_groups *group = NULL; - int i = 0; - - group = _dns_conf_get_group(group_name); - if (group == NULL) { - return -1; - } - - for (i = 0; i < group->server_num; i++) { - if (group->servers[i] == server) { - return 0; - } - } - - if (group->server_num >= DNS_MAX_SERVERS) { - return -1; - } - - group->servers[group->server_num] = server; - group->server_num++; - - return 0; -} - -static const char *_dns_conf_get_group_name(const char *group_name) -{ - struct dns_server_groups *group = NULL; - - group = _dns_conf_get_group(group_name); - if (group == NULL) { - return NULL; - } - - return group->group_name; -} - -static void _config_group_table_destroy(void) -{ - struct dns_server_groups *group = NULL; - struct hlist_node *tmp = NULL; - int i; - - hash_for_each_safe(dns_group_table.group, i, tmp, group, node) - { - hlist_del_init(&group->node); - free(group); - } -} - -static int _config_server(int argc, char *argv[], dns_server_type_t type, int default_port) -{ - int index = dns_conf_server_num; - struct dns_servers *server; - int port = -1; - char *ip = NULL; - int opt = 0; - unsigned int result_flag = 0; - unsigned int server_flag = 0; - unsigned char *spki = NULL; - - int ttl = 0; - /* clang-format off */ - static struct option long_options[] = { - {"blacklist-ip", no_argument, NULL, 'b'}, /* filtering with blacklist-ip */ - {"whitelist-ip", no_argument, NULL, 'w'}, /* filtering with whitelist-ip */ -#ifdef FEATURE_CHECK_EDNS - /* experimental feature */ - {"check-edns", no_argument, NULL, 'e'}, /* check edns */ -#endif - {"spki-pin", required_argument, NULL, 'p'}, /* check SPKI pin */ - {"host-name", required_argument, NULL, 'h'}, /* host name */ - {"http-host", required_argument, NULL, 'H'}, /* http host */ - {"tls-host-verify", required_argument, NULL, 'V' }, /* verify tls hostname */ - {"group", required_argument, NULL, 'g'}, /* add to group */ - {"exclude-default-group", no_argument, NULL, 'E'}, /* ecluse this from default group */ - {NULL, no_argument, NULL, 0} - }; - /* clang-format on */ - if (argc <= 1) { - tlog(TLOG_ERROR, "invalid parameter."); - return -1; - } - - if (index >= DNS_MAX_SERVERS) { - tlog(TLOG_WARN, "exceeds max server number, %s", ip); - return 0; - } - - server = &dns_conf_servers[index]; - server->spki[0] = '\0'; - server->path[0] = '\0'; - server->hostname[0] = '\0'; - server->httphost[0] = '\0'; - server->tls_host_verify[0] = '\0'; - - ip = argv[1]; - - if (type == DNS_SERVER_HTTPS) { - if (parse_uri(ip, NULL, server->server, &port, server->path) != 0) { - return -1; - } - safe_strncpy(server->hostname, server->server, sizeof(server->hostname)); - safe_strncpy(server->httphost, server->server, sizeof(server->httphost)); - if (server->path[0] == 0) { - safe_strncpy(server->path, "/", sizeof(server->path)); - } - } else { - /* parse ip, port from ip */ - if (parse_ip(ip, server->server, &port) != 0) { - return -1; - } - } - - /* if port is not defined, set port to default 53 */ - if (port == PORT_NOT_DEFINED) { - port = default_port; - } - - /* process extra options */ - optind = 1; - while (1) { - opt = getopt_long_only(argc, argv, "", long_options, NULL); - if (opt == -1) { - break; - } - - switch (opt) { - case 'b': { - result_flag |= DNSSERVER_FLAG_BLACKLIST_IP; - break; - } - case 'w': { - result_flag |= DNSSERVER_FLAG_WHITELIST_IP; - break; - } - case 'e': { - result_flag |= DNSSERVER_FLAG_CHECK_EDNS; - break; - } - case 'h': { - safe_strncpy(server->hostname, optarg, DNS_MAX_CNAME_LEN); - break; - } - case 'H': { - safe_strncpy(server->httphost, optarg, DNS_MAX_CNAME_LEN); - break; - } - case 'E': { - server_flag |= SERVER_FLAG_EXCLUDE_DEFAULT; - break; - } - case 'g': { - if (_dns_conf_get_group_set(optarg, server) != 0) { - tlog(TLOG_ERROR, "add group failed."); - goto errout; - } - break; - } - case 'p': { - safe_strncpy(server->spki, optarg, DNS_MAX_SPKI_LEN); - break; - } - case 'V': { - safe_strncpy(server->tls_host_verify, optarg, DNS_MAX_CNAME_LEN); - break; - } - default: - break; - } - } - - /* add new server */ - server->type = type; - server->port = port; - server->result_flag = result_flag; - server->server_flag = server_flag; - server->ttl = ttl; - dns_conf_server_num++; - tlog(TLOG_DEBUG, "add server %s, flag: %X, ttl: %d", ip, result_flag, ttl); - - return 0; - -errout: - if (spki) { - free(spki); - } - - return -1; -} - -static int _config_domain_iter_free(void *data, const unsigned char *key, uint32_t key_len, void *value) -{ - struct dns_domain_rule *domain_rule = value; - int i = 0; - - if (domain_rule == NULL) { - return 0; - } - - for (i = 0; i < DOMAIN_RULE_MAX; i++) { - if (domain_rule->rules[i] == NULL) { - continue; - } - - free(domain_rule->rules[i]); - } - - free(domain_rule); - return 0; -} - -static void _config_domain_destroy(void) -{ - art_iter(&dns_conf_domain_rule, _config_domain_iter_free, NULL); - art_tree_destroy(&dns_conf_domain_rule); -} - -static void _config_address_destroy(radix_node_t *node, void *cbctx) -{ - if (node == NULL) { - return; - } - - if (node->data == NULL) { - return; - } - - free(node->data); - node->data = NULL; -} - -static int _config_domain_rule_add(char *domain, enum domain_rule type, void *rule) -{ - struct dns_domain_rule *domain_rule = NULL; - struct dns_domain_rule *old_domain_rule = NULL; - struct dns_domain_rule *add_domain_rule = NULL; - - char domain_key[DNS_MAX_CONF_CNAME_LEN]; - int len = 0; - - /* Reverse string, for suffix match */ - len = strlen(domain); - if (len >= sizeof(domain_key)) { - tlog(TLOG_ERROR, "domain name %s too long", domain); - goto errout; - } - reverse_string(domain_key, domain, len, 1); - domain_key[len] = '.'; - len++; - domain_key[len] = 0; - - if (type >= DOMAIN_RULE_MAX) { - goto errout; - } - - /* Get existing or create domain rule */ - domain_rule = art_search(&dns_conf_domain_rule, (unsigned char *)domain_key, len); - if (domain_rule == NULL) { - add_domain_rule = malloc(sizeof(*add_domain_rule)); - if (add_domain_rule == NULL) { - goto errout; - } - memset(add_domain_rule, 0, sizeof(*add_domain_rule)); - domain_rule = add_domain_rule; - } - - /* add new rule to domain */ - if (domain_rule->rules[type]) { - free(domain_rule->rules[type]); - domain_rule->rules[type] = NULL; - } - - domain_rule->rules[type] = rule; - - /* update domain rule */ - if (add_domain_rule) { - old_domain_rule = art_insert(&dns_conf_domain_rule, (unsigned char *)domain_key, len, add_domain_rule); - if (old_domain_rule) { - free(old_domain_rule); - } - } - - return 0; -errout: - if (add_domain_rule) { - free(add_domain_rule); - } - - tlog(TLOG_ERROR, "add doamin %s rule failed", domain); - return -1; -} - -static int _config_domain_rule_flag_set(char *domain, unsigned int flag) -{ - struct dns_domain_rule *domain_rule = NULL; - struct dns_domain_rule *old_domain_rule = NULL; - struct dns_domain_rule *add_domain_rule = NULL; - struct dns_rule_flags *rule_flags = NULL; - - char domain_key[DNS_MAX_CONF_CNAME_LEN]; - int len = 0; - - len = strlen(domain); - if (len >= sizeof(domain_key)) { - tlog(TLOG_ERROR, "domain %s too long", domain); - return -1; - } - reverse_string(domain_key, domain, len, 1); - domain_key[len] = '.'; - len++; - domain_key[len] = 0; - - /* Get existing or create domain rule */ - domain_rule = art_search(&dns_conf_domain_rule, (unsigned char *)domain_key, len); - if (domain_rule == NULL) { - add_domain_rule = malloc(sizeof(*add_domain_rule)); - if (add_domain_rule == NULL) { - goto errout; - } - memset(add_domain_rule, 0, sizeof(*add_domain_rule)); - domain_rule = add_domain_rule; - } - - /* add new rule to domain */ - if (domain_rule->rules[DOMAIN_RULE_FLAGS] == NULL) { - rule_flags = malloc(sizeof(*rule_flags)); - rule_flags->flags = 0; - domain_rule->rules[DOMAIN_RULE_FLAGS] = rule_flags; - } - - rule_flags = domain_rule->rules[DOMAIN_RULE_FLAGS]; - rule_flags->flags |= flag; - - /* update domain rule */ - if (add_domain_rule) { - old_domain_rule = art_insert(&dns_conf_domain_rule, (unsigned char *)domain_key, len, add_domain_rule); - if (old_domain_rule) { - free(old_domain_rule); - } - } - - return 0; -errout: - if (add_domain_rule) { - free(add_domain_rule); - } - - tlog(TLOG_ERROR, "add doamin %s rule failed", domain); - return 0; -} - -static void _config_ipset_table_destroy(void) -{ - struct dns_ipset_name *ipset_name = NULL; - struct hlist_node *tmp = NULL; - int i; - - hash_for_each_safe(dns_ipset_table.ipset, i, tmp, ipset_name, node) - { - hlist_del_init(&ipset_name->node); - free(ipset_name); - } -} - -static const char *_dns_conf_get_ipset(const char *ipsetname) -{ - uint32_t key = 0; - struct dns_ipset_name *ipset_name = NULL; - - key = hash_string(ipsetname); - hash_for_each_possible(dns_ipset_table.ipset, ipset_name, node, key) - { - if (strncmp(ipset_name->ipsetname, ipsetname, DNS_MAX_IPSET_NAMELEN) == 0) { - return ipset_name->ipsetname; - } - } - - ipset_name = malloc(sizeof(*ipset_name)); - if (ipset_name == NULL) { - goto errout; - } - - key = hash_string(ipsetname); - safe_strncpy(ipset_name->ipsetname, ipsetname, DNS_MAX_IPSET_NAMELEN); - hash_add(dns_ipset_table.ipset, &ipset_name->node, key); - - return ipset_name->ipsetname; -errout: - if (ipset_name) { - free(ipset_name); - } - - return NULL; -} - -static int _config_ipset(void *data, int argc, char *argv[]) -{ - struct dns_ipset_rule *ipset_rule = NULL; - char domain[DNS_MAX_CONF_CNAME_LEN]; - char ipsetname[DNS_MAX_IPSET_NAMELEN]; - const char *ipset = NULL; - char *begin = NULL; - char *end = NULL; - int len = 0; - char *value = argv[1]; - - if (argc <= 1) { - goto errout; - } - - /* first field */ - begin = strstr(value, "/"); - if (begin == NULL) { - goto errout; - } - - /* second field */ - begin++; - end = strstr(begin, "/"); - if (end == NULL) { - goto errout; - } - - /* remove prefix . */ - while (*begin == '.') { - begin++; - } - - /* Get domain */ - len = end - begin; - if (len >= sizeof(domain)) { - tlog(TLOG_ERROR, "domain name %s too long", value); - goto errout; - } - - memcpy(domain, begin, len); - domain[len] = '\0'; - - len = strlen(end + 1); - if (len <= 0) { - goto errout; - } - - /* Process domain option */ - if (strncmp(end + 1, "-", sizeof("-")) != 0) { - /* new ipset domain */ - safe_strncpy(ipsetname, end + 1, DNS_MAX_IPSET_NAMELEN); - ipset = _dns_conf_get_ipset(ipsetname); - if (ipset == NULL) { - goto errout; - } - - ipset_rule = malloc(sizeof(*ipset_rule)); - if (ipset_rule == NULL) { - goto errout; - } - - ipset_rule->ipsetname = ipset; - } else { - /* ignore this domain */ - if (_config_domain_rule_flag_set(domain, DOMAIN_FLAG_IPSET_IGNORE) != 0) { - goto errout; - } - - return 0; - } - - if (_config_domain_rule_add(domain, DOMAIN_RULE_IPSET, ipset_rule) != 0) { - goto errout; - } - - return 0; -errout: - if (ipset_rule) { - free(ipset_rule); - } - - tlog(TLOG_ERROR, "add ipset %s failed", value); - return 0; -} - -static int _config_address(void *data, int argc, char *argv[]) -{ - struct dns_address_IPV4 *address_ipv4 = NULL; - struct dns_address_IPV6 *address_ipv6 = NULL; - void *address = NULL; - char *value = argv[1]; - char ip[MAX_IP_LEN]; - char domain[DNS_MAX_CONF_CNAME_LEN]; - char *begin = NULL; - char *end = NULL; - int len = 0; - int port; - struct sockaddr_storage addr; - socklen_t addr_len = sizeof(addr); - enum domain_rule type = 0; - unsigned int flag = 0; - - if (argc <= 1) { - goto errout; - } - - /* first field */ - begin = strstr(value, "/"); - if (begin == NULL) { - goto errout; - } - - /* second field */ - begin++; - end = strstr(begin, "/"); - if (end == NULL) { - goto errout; - } - - /* remove prefix . */ - while (*begin == '.') { - begin++; - } - - /* get domain */ - len = end - begin; - - if (len >= sizeof(domain)) { - tlog(TLOG_ERROR, "domain name %s too long", value); - goto errout; - } - - memcpy(domain, begin, len); - domain[len] = 0; - - if (*(end + 1) == '#') { - if (strncmp(end + 1, "#4", sizeof("#4")) == 0) { - flag = DOMAIN_FLAG_ADDR_IPV4_SOA; - } else if (strncmp(end + 1, "#6", sizeof("#6")) == 0) { - flag = DOMAIN_FLAG_ADDR_IPV6_SOA; - } else if (strncmp(end + 1, "#", sizeof("#")) == 0) { - flag = DOMAIN_FLAG_ADDR_SOA; - } else { - goto errout; - } - - /* add SOA rule */ - if (_config_domain_rule_flag_set(domain, flag) != 0) { - goto errout; - } - - return 0; - } else if (*(end + 1) == '-') { - if (strncmp(end + 1, "-4", sizeof("-4")) == 0) { - flag = DOMAIN_FLAG_ADDR_IPV4_IGN; - } else if (strncmp(end + 1, "-6", sizeof("-6")) == 0) { - flag = DOMAIN_FLAG_ADDR_IPV6_IGN; - } else if (strncmp(end + 1, "-", sizeof("-")) == 0) { - flag = DOMAIN_FLAG_ADDR_IGN; - } else { - goto errout; - } - - /* ignore rule */ - if (_config_domain_rule_flag_set(domain, flag) != 0) { - goto errout; - } - - return 0; - } else { - /* set address to domain */ - if (parse_ip(end + 1, ip, &port) != 0) { - goto errout; - } - - if (getaddr_by_host(ip, (struct sockaddr *)&addr, &addr_len) != 0) { - goto errout; - } - - switch (addr.ss_family) { - case AF_INET: { - struct sockaddr_in *addr_in; - address_ipv4 = malloc(sizeof(*address_ipv4)); - if (address_ipv4 == NULL) { - goto errout; - } - - addr_in = (struct sockaddr_in *)&addr; - memcpy(address_ipv4->ipv4_addr, &addr_in->sin_addr.s_addr, 4); - type = DOMAIN_RULE_ADDRESS_IPV4; - address = address_ipv4; - } break; - case AF_INET6: { - struct sockaddr_in6 *addr_in6; - addr_in6 = (struct sockaddr_in6 *)&addr; - if (IN6_IS_ADDR_V4MAPPED(&addr_in6->sin6_addr)) { - address_ipv4 = malloc(sizeof(*address_ipv4)); - if (address_ipv4 == NULL) { - goto errout; - } - memcpy(address_ipv4->ipv4_addr, addr_in6->sin6_addr.s6_addr + 12, 4); - type = DOMAIN_RULE_ADDRESS_IPV4; - address = address_ipv4; - } else { - address_ipv6 = malloc(sizeof(*address_ipv6)); - if (address_ipv6 == NULL) { - goto errout; - } - memcpy(address_ipv6->ipv6_addr, addr_in6->sin6_addr.s6_addr, 16); - type = DOMAIN_RULE_ADDRESS_IPV6; - address = address_ipv6; - } - } break; - default: - goto errout; - } - } - - /* add domain to ART-tree */ - if (_config_domain_rule_add(domain, type, address) != 0) { - goto errout; - } - - return 0; -errout: - if (address) { - free(address); - } - - tlog(TLOG_ERROR, "add address %s failed", value); - return 0; -} - -static int _config_speed_check_mode(void *data, int argc, char *argv[]) -{ - char mode[DNS_MAX_OPT_LEN]; - char *field; - char *ptr; - int order = 0; - int port = 80; - int i = 0; - - if (argc <= 1) { - return -1; - } - - safe_strncpy(mode, argv[1], sizeof(mode)); - ptr = mode; - do { - field = ptr; - ptr = strstr(mode, ","); - if (field == NULL || order >= DOMAIN_CHECK_NUM) { - return 0; - } - - if (ptr) { - *ptr = 0; - } - - if (strncmp(field, "ping", sizeof("ping")) == 0) { - dns_conf_check_order.order[order] = DOMAIN_CHECK_ICMP; - } else if (strstr(field, "tcp") == field) { - char *port_str = strstr(field, ":"); - if (port_str) { - port = atoi(port_str + 1); - if (port <= 0 || port >= 65535) { - port = 80; - } - } - - dns_conf_check_order.order[order] = DOMAIN_CHECK_TCP; - dns_conf_check_order.tcp_port = port; - } else if (strncmp(field, "none", sizeof("none")) == 0) { - dns_conf_check_order.order[order] = DOMAIN_CHECK_NONE; - for (i = order + 1; i < DOMAIN_CHECK_NUM; i++) { - dns_conf_check_order.order[i] = DOMAIN_CHECK_NONE; - } - - return 0; - } - order++; - if (ptr) { - ptr++; - } - - } while (1); - - return 0; -} - -static int _config_bind_ip(int argc, char *argv[], DNS_BIND_TYPE type) -{ - int index = dns_conf_bind_ip_num; - struct dns_bind_ip *bind_ip; - char *ip = NULL; - int opt = 0; - char group_name[DNS_GROUP_NAME_LEN]; - const char *group = NULL; - unsigned int server_flag = 0; - - /* clang-format off */ - static struct option long_options[] = { - {"group", required_argument, NULL, 'g'}, /* add to group */ - {"no-rule-addr", no_argument, NULL, 'A'}, - {"no-rule-nameserver", no_argument, NULL, 'N'}, - {"no-rule-ipset", no_argument, NULL, 'I'}, - {"no-rule-sni-proxy", no_argument, NULL, 'P'}, - {"no-rule-soa", no_argument, NULL, 'O'}, - {"no-speed-check", no_argument, NULL, 'S'}, - {"no-cache", no_argument, NULL, 'C'}, - {"no-dualstack-selection", no_argument, NULL, 'D'}, - {NULL, no_argument, NULL, 0} - }; - /* clang-format on */ - if (argc <= 1) { - tlog(TLOG_ERROR, "invalid parameter."); - goto errout; - } - - if (index >= DNS_MAX_SERVERS) { - tlog(TLOG_WARN, "exceeds max server number, %s", ip); - return 0; - } - - bind_ip = &dns_conf_bind_ip[index]; - bind_ip->type = type; - bind_ip->flags = 0; - ip = argv[1]; - safe_strncpy(bind_ip->ip, ip, DNS_MAX_IPLEN); - - /* process extra options */ - optind = 1; - while (1) { - opt = getopt_long_only(argc, argv, "", long_options, NULL); - if (opt == -1) { - break; - } - - switch (opt) { - case 'g': { - safe_strncpy(group_name, optarg, DNS_GROUP_NAME_LEN); - group = _dns_conf_get_group_name(group_name); - break; - } - case 'A': { - server_flag |= BIND_FLAG_NO_RULE_ADDR; - break; - } - case 'N': { - server_flag |= BIND_FLAG_NO_RULE_NAMESERVER; - break; - } - case 'I': { - server_flag |= BIND_FLAG_NO_RULE_IPSET; - break; - } - case 'P': { - server_flag |= BIND_FLAG_NO_RULE_SNIPROXY; - break; - } - case 'S': { - server_flag |= BIND_FLAG_NO_SPEED_CHECK; - break; - } - case 'C': { - server_flag |= BIND_FLAG_NO_CACHE; - break; - } - case 'O': { - server_flag |= BIND_FLAG_NO_RULE_SOA; - break; - } - case 'D': { - server_flag |= BIND_FLAG_NO_DUALSTACK_SELECTION; - break; - } - default: - break; - } - } - - /* add new server */ - bind_ip->flags = server_flag; - bind_ip->group = group; - dns_conf_bind_ip_num++; - tlog(TLOG_DEBUG, "bind ip %s, type:%d, flag: %X", ip, type, server_flag); - - return 0; - -errout: - return -1; -} - -static int _config_bind_ip_udp(void *data, int argc, char *argv[]) -{ - return _config_bind_ip(argc, argv, DNS_BIND_TYPE_UDP); -} - -static int _config_bind_ip_tcp(void *data, int argc, char *argv[]) -{ - return _config_bind_ip(argc, argv, DNS_BIND_TYPE_TCP); -} - -static int _config_server_udp(void *data, int argc, char *argv[]) -{ - return _config_server(argc, argv, DNS_SERVER_UDP, DEFAULT_DNS_PORT); -} - -static int _config_server_tcp(void *data, int argc, char *argv[]) -{ - return _config_server(argc, argv, DNS_SERVER_TCP, DEFAULT_DNS_PORT); -} - -static int _config_server_tls(void *data, int argc, char *argv[]) -{ - return _config_server(argc, argv, DNS_SERVER_TLS, DEFAULT_DNS_TLS_PORT); -} - -static int _config_server_https(void *data, int argc, char *argv[]) -{ - int ret = 0; - ret = _config_server(argc, argv, DNS_SERVER_HTTPS, DEFAULT_DNS_HTTPS_PORT); - - return ret; -} - -static int _config_nameserver(void *data, int argc, char *argv[]) -{ - struct dns_nameserver_rule *nameserver_rule = NULL; - char domain[DNS_MAX_CONF_CNAME_LEN]; - char group_name[DNS_GROUP_NAME_LEN]; - const char *group = NULL; - char *begin = NULL; - char *end = NULL; - int len = 0; - char *value = argv[1]; - - if (argc <= 1) { - goto errout; - } - - /* first field */ - begin = strstr(value, "/"); - if (begin == NULL) { - goto errout; - } - - /* second field */ - begin++; - end = strstr(begin, "/"); - if (end == NULL) { - goto errout; - } - - /* remove prefix . */ - while (*begin == '.') { - begin++; - } - - len = end - begin; - - if (len >= sizeof(domain)) { - tlog(TLOG_ERROR, "domain name %s too long", value); - goto errout; - } - - memcpy(domain, begin, len); - domain[len] = '\0'; - - len = strlen(end + 1); - if (len <= 0) { - goto errout; - } - - if (strncmp(end + 1, "-", sizeof("-")) != 0) { - safe_strncpy(group_name, end + 1, DNS_GROUP_NAME_LEN); - group = _dns_conf_get_group_name(group_name); - if (group == NULL) { - goto errout; - } - - nameserver_rule = malloc(sizeof(*nameserver_rule)); - if (nameserver_rule == NULL) { - goto errout; - } - - nameserver_rule->group_name = group; - } else { - /* ignore this domain */ - if (_config_domain_rule_flag_set(domain, DOMAIN_FLAG_NAMESERVER_IGNORE) != 0) { - goto errout; - } - - return 0; - } - - if (_config_domain_rule_add(domain, DOMAIN_RULE_NAMESERVER, nameserver_rule) != 0) { - goto errout; - } - - return 0; -errout: - if (nameserver_rule) { - free(nameserver_rule); - } - - tlog(TLOG_ERROR, "add nameserver %s failed", value); - return 0; -} - -static radix_node_t *_create_addr_node(char *addr) -{ - radix_node_t *node; - void *p; - prefix_t prefix; - const char *errmsg = NULL; - radix_tree_t *tree = NULL; - - p = prefix_pton(addr, -1, &prefix, &errmsg); - if (p == NULL) { - return NULL; - } - - switch (prefix.family) { - case AF_INET: - tree = dns_conf_address_rule.ipv4; - break; - case AF_INET6: - tree = dns_conf_address_rule.ipv6; - break; - } - - node = radix_lookup(tree, &prefix); - return node; -} - -static int _config_iplist_rule(char *subnet, enum address_rule rule) -{ - radix_node_t *node = NULL; - struct dns_ip_address_rule *ip_rule = NULL; - - node = _create_addr_node(subnet); - if (node == NULL) { - return -1; - } - - if (node->data == NULL) { - ip_rule = malloc(sizeof(*ip_rule)); - if (ip_rule == NULL) { - return -1; - } - - node->data = ip_rule; - memset(ip_rule, 0, sizeof(*ip_rule)); - } - - ip_rule = node->data; - - switch (rule) { - case ADDRESS_RULE_BLACKLIST: - ip_rule->blacklist = 1; - break; - case ADDRESS_RULE_WHITELIST: - ip_rule->whitelist = 1; - break; - case ADDRESS_RULE_BOGUS: - ip_rule->bogus = 1; - break; - case ADDRESS_RULE_IP_IGNORE: - ip_rule->ip_ignore = 1; - break; - default: - return -1; - } - - return 0; -} - -static int _config_blacklist_ip(void *data, int argc, char *argv[]) -{ - if (argc <= 1) { - return -1; - } - - return _config_iplist_rule(argv[1], ADDRESS_RULE_BLACKLIST); -} - -static int _conf_bogus_nxdomain(void *data, int argc, char *argv[]) -{ - if (argc <= 1) { - return -1; - } - - return _config_iplist_rule(argv[1], ADDRESS_RULE_BOGUS); -} - -static int _conf_ip_ignore(void *data, int argc, char *argv[]) -{ - if (argc <= 1) { - return -1; - } - - return _config_iplist_rule(argv[1], ADDRESS_RULE_IP_IGNORE); -} - -static int _conf_whitelist_ip(void *data, int argc, char *argv[]) -{ - if (argc <= 1) { - return -1; - } - - return _config_iplist_rule(argv[1], ADDRESS_RULE_WHITELIST); -} - -static int _conf_edns_client_subnet(void *data, int argc, char *argv[]) -{ - char *slash = NULL; - char *value = NULL; - int subnet = 0; - struct dns_edns_client_subnet *ecs = NULL; - struct sockaddr_storage addr; - socklen_t addr_len = sizeof(addr); - - if (argc <= 1 || data == NULL) { - return -1; - } - - value = argv[1]; - - slash = strstr(value, "/"); - if (slash) { - *slash = 0; - slash++; - subnet = atoi(slash); - if (subnet < 0 || subnet > 128) { - return -1; - } - } - - if (getaddr_by_host(value, (struct sockaddr *)&addr, &addr_len) != 0) { - goto errout; - } - - switch (addr.ss_family) { - case AF_INET: - ecs = &dns_conf_ipv4_ecs; - break; - case AF_INET6: - ecs = &dns_conf_ipv6_ecs; - break; - default: - goto errout; - } - - safe_strncpy(ecs->ip, value, DNS_MAX_IPLEN); - ecs->subnet = subnet; - ecs->enable = 1; - - return 0; - -errout: - return -1; -} - -static int _config_log_level(void *data, int argc, char *argv[]) -{ - /* read log level and set */ - char *value = argv[1]; - - if (strncmp("debug", value, MAX_LINE_LEN) == 0) { - dns_conf_log_level = TLOG_DEBUG; - } else if (strncmp("info", value, MAX_LINE_LEN) == 0) { - dns_conf_log_level = TLOG_INFO; - } else if (strncmp("notice", value, MAX_LINE_LEN) == 0) { - dns_conf_log_level = TLOG_NOTICE; - } else if (strncmp("warn", value, MAX_LINE_LEN) == 0) { - dns_conf_log_level = TLOG_WARN; - } else if (strncmp("error", value, MAX_LINE_LEN) == 0) { - dns_conf_log_level = TLOG_ERROR; - } else if (strncmp("fatal", value, MAX_LINE_LEN) == 0) { - dns_conf_log_level = TLOG_FATAL; - } else { - return -1; - } - - return 0; -} - -static struct config_item _config_item[] = { - CONF_STRING("server-name", (char *)dns_conf_server_name, DNS_MAX_SERVER_NAME_LEN), - CONF_CUSTOM("bind", _config_bind_ip_udp, NULL), - CONF_CUSTOM("bind-tcp", _config_bind_ip_tcp, NULL), - CONF_CUSTOM("server", _config_server_udp, NULL), - CONF_CUSTOM("server-tcp", _config_server_tcp, NULL), - CONF_CUSTOM("server-tls", _config_server_tls, NULL), - CONF_CUSTOM("server-https", _config_server_https, NULL), - CONF_CUSTOM("nameserver", _config_nameserver, NULL), - CONF_CUSTOM("address", _config_address, NULL), - CONF_YESNO("ipset-timeout", &dns_conf_ipset_timeout_enable), - CONF_CUSTOM("ipset", _config_ipset, NULL), - CONF_CUSTOM("speed-check-mode", _config_speed_check_mode, NULL), - CONF_INT("tcp-idle-time", &dns_conf_tcp_idle_time, 0, 3600), - CONF_INT("cache-size", &dns_conf_cachesize, 0, CONF_INT_MAX), - CONF_YESNO("prefetch-domain", &dns_conf_prefetch), - CONF_YESNO("dualstack-ip-selection", &dns_conf_dualstack_ip_selection), - CONF_INT("dualstack-ip-selection-threshold", &dns_conf_dualstack_ip_selection_threshold, 0, 1000), - CONF_CUSTOM("log-level", _config_log_level, NULL), - CONF_STRING("log-file", (char *)dns_conf_log_file, DNS_MAX_PATH), - CONF_SIZE("log-size", &dns_conf_log_size, 0, 1024 * 1024 * 1024), - CONF_INT("log-num", &dns_conf_log_num, 0, 1024), - CONF_YESNO("audit-enable", &dns_conf_audit_enable), - CONF_YESNO("audit-SOA", &dns_conf_audit_log_SOA), - CONF_STRING("audit-file", (char *)&dns_conf_audit_file, DNS_MAX_PATH), - CONF_SIZE("audit-size", &dns_conf_audit_size, 0, 1024 * 1024 * 1024), - CONF_INT("audit-num", &dns_conf_audit_num, 0, 1024), - CONF_INT("rr-ttl", &dns_conf_rr_ttl, 0, CONF_INT_MAX), - CONF_INT("rr-ttl-min", &dns_conf_rr_ttl_min, 0, CONF_INT_MAX), - CONF_INT("rr-ttl-max", &dns_conf_rr_ttl_max, 0, CONF_INT_MAX), - CONF_YESNO("force-AAAA-SOA", &dns_conf_force_AAAA_SOA), - CONF_CUSTOM("blacklist-ip", _config_blacklist_ip, NULL), - CONF_CUSTOM("whitelist-ip", _conf_whitelist_ip, NULL), - CONF_CUSTOM("bogus-nxdomain", _conf_bogus_nxdomain, NULL), - CONF_CUSTOM("ignore-ip", _conf_ip_ignore, NULL), - CONF_CUSTOM("edns-client-subnet", _conf_edns_client_subnet, NULL), - CONF_CUSTOM("conf-file", config_addtional_file, NULL), - CONF_END(), -}; - -static int _conf_printf(const char *file, int lineno, int ret) -{ - if (ret == CONF_RET_ERR) { - tlog(TLOG_ERROR, "process config file '%s' failed at line %d.", file, lineno); - syslog(LOG_NOTICE, "process config file '%s' failed at line %d.", file, lineno); - return -1; - } else if (ret == CONF_RET_WARN) { - tlog(TLOG_WARN, "process config file '%s' failed at line %d.", file, lineno); - syslog(LOG_NOTICE, "process config file '%s' failed at line %d.", file, lineno); - return -1; - } - - return 0; -} - -int config_addtional_file(void *data, int argc, char *argv[]) -{ - char *conf_file = argv[1]; - char file_path[DNS_MAX_PATH]; - char file_path_dir[DNS_MAX_PATH]; - - if (conf_file[0] != '/') { - safe_strncpy(file_path_dir, conf_get_conf_file(), DNS_MAX_PATH); - dirname(file_path_dir); - if (snprintf(file_path, DNS_MAX_PATH, "%s/%s", file_path_dir, conf_file) < 0) { - return -1; - } - } else { - safe_strncpy(file_path, conf_file, DNS_MAX_PATH); - } - - if (access(file_path, R_OK) != 0) { - tlog(TLOG_WARN, "conf file %s is not readable.", file_path); - syslog(LOG_NOTICE, "conf file %s is not readable.", file_path); - return 0; - } - - return load_conf(file_path, _config_item, _conf_printf); -} - -static int _dns_server_load_conf_init(void) -{ - dns_conf_address_rule.ipv4 = New_Radix(); - dns_conf_address_rule.ipv6 = New_Radix(); - if (dns_conf_address_rule.ipv4 == NULL || dns_conf_address_rule.ipv6 == NULL) { - tlog(TLOG_WARN, "init radix tree failed."); - return -1; - } - - art_tree_init(&dns_conf_domain_rule); - - hash_init(dns_ipset_table.ipset); - hash_init(dns_group_table.group); - - return 0; -} - -void dns_server_load_exit(void) -{ - _config_domain_destroy(); - Destroy_Radix(dns_conf_address_rule.ipv4, _config_address_destroy, NULL); - Destroy_Radix(dns_conf_address_rule.ipv6, _config_address_destroy, NULL); - _config_ipset_table_destroy(); - _config_group_table_destroy(); -} - -static int _dns_conf_speed_check_mode_verify(void) -{ - int i, j; - int has_cap = has_network_raw_cap(); - int print_log = 0; - if (has_cap == 1) { - return 0; - } - - for (i = 0; i < DOMAIN_CHECK_NUM; i++) { - if (dns_conf_check_order.order[i] == DOMAIN_CHECK_ICMP) { - for (j = i + 1; j < DOMAIN_CHECK_NUM; j++) { - dns_conf_check_order.order[j - 1] = dns_conf_check_order.order[j]; - } - dns_conf_check_order.order[j - 1] = DOMAIN_CHECK_NONE; - print_log = 1; - } - } - - if (print_log) { - tlog(TLOG_WARN, "speed check by ping is disabled because smartdns does not have network raw privileges"); - } - - return 0; -} - -static int _dns_conf_load_post(void) -{ - _dns_conf_speed_check_mode_verify(); - return 0; -} - -int dns_server_load_conf(const char *file) -{ - int ret = 0; - _dns_server_load_conf_init(); - openlog("smartdns", LOG_CONS | LOG_NDELAY, LOG_LOCAL1); - ret = load_conf(file, _config_item, _conf_printf); - closelog(); - _dns_conf_load_post(); - return ret; -} +/************************************************************************* + * + * Copyright (C) 2018-2020 Ruilin Peng (Nick) . + * + * smartdns is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * smartdns is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "dns_conf.h" +#include "list.h" +#include "rbtree.h" +#include "tlog.h" +#include "util.h" +#include +#include +#include +#include +#include +#include +#include + +#define DEFAULT_DNS_CACHE_SIZE 512 + +/* ipset */ +struct dns_ipset_table { + DECLARE_HASHTABLE(ipset, 8); +}; +static struct dns_ipset_table dns_ipset_table; + +/* dns groups */ +struct dns_group_table dns_group_table; + +/* server ip/port */ +struct dns_bind_ip dns_conf_bind_ip[DNS_MAX_BIND_IP]; +int dns_conf_bind_ip_num = 0; +int dns_conf_tcp_idle_time = 120; + +/* cache */ +int dns_conf_cachesize = DEFAULT_DNS_CACHE_SIZE; +int dns_conf_prefetch = 0; +int dns_conf_serve_expired = 0; +int dns_conf_serve_expired_ttl = 0; + +/* upstream servers */ +struct dns_servers dns_conf_servers[DNS_MAX_SERVERS]; +char dns_conf_server_name[DNS_MAX_SERVER_NAME_LEN]; +int dns_conf_server_num; + +struct dns_domain_check_order dns_conf_check_order = { + .order = {DOMAIN_CHECK_ICMP, DOMAIN_CHECK_TCP}, + .tcp_port = 80, +}; +int dns_has_cap_ping = 0; + +/* logging */ +int dns_conf_log_level = TLOG_ERROR; +char dns_conf_log_file[DNS_MAX_PATH]; +size_t dns_conf_log_size = 1024 * 1024; +int dns_conf_log_num = 8; + +/* CA file */ +char dns_conf_ca_file[DNS_MAX_PATH]; +char dns_conf_ca_path[DNS_MAX_PATH]; + +/* auditing */ +int dns_conf_audit_enable = 0; +int dns_conf_audit_log_SOA; +char dns_conf_audit_file[DNS_MAX_PATH]; +size_t dns_conf_audit_size = 1024 * 1024; +int dns_conf_audit_num = 2; + +/* address rules */ +art_tree dns_conf_domain_rule; +struct dns_conf_address_rule dns_conf_address_rule; + +/* dual-stack selection */ +int dns_conf_dualstack_ip_selection; +int dns_conf_dualstack_ip_selection_threshold = 30; + +/* TTL */ +int dns_conf_rr_ttl; +int dns_conf_rr_ttl_min; +int dns_conf_rr_ttl_max; +int dns_conf_force_AAAA_SOA; + +int dns_conf_ipset_timeout_enable; + +/* ECS */ +struct dns_edns_client_subnet dns_conf_ipv4_ecs; +struct dns_edns_client_subnet dns_conf_ipv6_ecs; + +char dns_conf_sni_proxy_ip[DNS_MAX_IPLEN]; + +static int _get_domain(char *value, char *domain, int max_dmain_size, char **ptr_after_domain) +{ + char *begin = NULL; + char *end = NULL; + int len = 0; + + /* first field */ + begin = strstr(value, "/"); + if (begin == NULL) { + goto errout; + } + + /* second field */ + begin++; + end = strstr(begin, "/"); + if (end == NULL) { + goto errout; + } + + /* remove prefix . */ + while (*begin == '.') { + begin++; + } + + /* Get domain */ + len = end - begin; + if (len >= max_dmain_size) { + tlog(TLOG_ERROR, "domain name %s too long", value); + goto errout; + } + + memcpy(domain, begin, len); + domain[len] = '\0'; + + if (ptr_after_domain) { + *ptr_after_domain = end + 1; + } + + return 0; +errout: + return -1; +} + +/* create and get dns server group */ +static struct dns_server_groups *_dns_conf_get_group(const char *group_name) +{ + uint32_t key = 0; + struct dns_server_groups *group = NULL; + + key = hash_string(group_name); + hash_for_each_possible(dns_group_table.group, group, node, key) + { + if (strncmp(group->group_name, group_name, DNS_MAX_IPLEN) == 0) { + return group; + } + } + + group = malloc(sizeof(*group)); + if (group == NULL) { + goto errout; + } + + memset(group, 0, sizeof(*group)); + safe_strncpy(group->group_name, group_name, DNS_GROUP_NAME_LEN); + hash_add(dns_group_table.group, &group->node, key); + + return group; +errout: + if (group) { + free(group); + } + + return NULL; +} + +static int _dns_conf_get_group_set(const char *group_name, struct dns_servers *server) +{ + struct dns_server_groups *group = NULL; + int i = 0; + + group = _dns_conf_get_group(group_name); + if (group == NULL) { + return -1; + } + + for (i = 0; i < group->server_num; i++) { + if (group->servers[i] == server) { + return 0; + } + } + + if (group->server_num >= DNS_MAX_SERVERS) { + return -1; + } + + group->servers[group->server_num] = server; + group->server_num++; + + return 0; +} + +static const char *_dns_conf_get_group_name(const char *group_name) +{ + struct dns_server_groups *group = NULL; + + group = _dns_conf_get_group(group_name); + if (group == NULL) { + return NULL; + } + + return group->group_name; +} + +static void _config_group_table_destroy(void) +{ + struct dns_server_groups *group = NULL; + struct hlist_node *tmp = NULL; + int i; + + hash_for_each_safe(dns_group_table.group, i, tmp, group, node) + { + hlist_del_init(&group->node); + free(group); + } +} + +static int _config_server(int argc, char *argv[], dns_server_type_t type, int default_port) +{ + int index = dns_conf_server_num; + struct dns_servers *server; + int port = -1; + char *ip = NULL; + int opt = 0; + unsigned int result_flag = 0; + unsigned int server_flag = 0; + unsigned char *spki = NULL; + + int ttl = 0; + /* clang-format off */ + static struct option long_options[] = { + {"blacklist-ip", no_argument, NULL, 'b'}, /* filtering with blacklist-ip */ + {"whitelist-ip", no_argument, NULL, 'w'}, /* filtering with whitelist-ip */ +#ifdef FEATURE_CHECK_EDNS + /* experimental feature */ + {"check-edns", no_argument, NULL, 'e'}, /* check edns */ +#endif + {"spki-pin", required_argument, NULL, 'p'}, /* check SPKI pin */ + {"host-name", required_argument, NULL, 'h'}, /* host name */ + {"http-host", required_argument, NULL, 'H'}, /* http host */ + {"no-check-certificate", no_argument, NULL, 'N'}, /* do not check certificate */ + {"tls-host-verify", required_argument, NULL, 'V' }, /* verify tls hostname */ + {"group", required_argument, NULL, 'g'}, /* add to group */ + {"exclude-default-group", no_argument, NULL, 'E'}, /* ecluse this from default group */ + {NULL, no_argument, NULL, 0} + }; + /* clang-format on */ + if (argc <= 1) { + tlog(TLOG_ERROR, "invalid parameter."); + return -1; + } + + if (index >= DNS_MAX_SERVERS) { + tlog(TLOG_WARN, "exceeds max server number, %s", ip); + return 0; + } + + server = &dns_conf_servers[index]; + server->spki[0] = '\0'; + server->path[0] = '\0'; + server->hostname[0] = '\0'; + server->httphost[0] = '\0'; + server->tls_host_verify[0] = '\0'; + + ip = argv[1]; + + if (type == DNS_SERVER_HTTPS) { + if (parse_uri(ip, NULL, server->server, &port, server->path) != 0) { + return -1; + } + safe_strncpy(server->hostname, server->server, sizeof(server->hostname)); + safe_strncpy(server->httphost, server->server, sizeof(server->httphost)); + if (server->path[0] == 0) { + safe_strncpy(server->path, "/", sizeof(server->path)); + } + } else { + /* parse ip, port from ip */ + if (parse_ip(ip, server->server, &port) != 0) { + return -1; + } + } + + /* if port is not defined, set port to default 53 */ + if (port == PORT_NOT_DEFINED) { + port = default_port; + } + + /* process extra options */ + optind = 1; + while (1) { + opt = getopt_long_only(argc, argv, "", long_options, NULL); + if (opt == -1) { + break; + } + + switch (opt) { + case 'b': { + result_flag |= DNSSERVER_FLAG_BLACKLIST_IP; + break; + } + case 'w': { + result_flag |= DNSSERVER_FLAG_WHITELIST_IP; + break; + } + case 'e': { + result_flag |= DNSSERVER_FLAG_CHECK_EDNS; + break; + } + case 'h': { + safe_strncpy(server->hostname, optarg, DNS_MAX_CNAME_LEN); + break; + } + case 'H': { + safe_strncpy(server->httphost, optarg, DNS_MAX_CNAME_LEN); + break; + } + case 'E': { + server_flag |= SERVER_FLAG_EXCLUDE_DEFAULT; + break; + } + case 'g': { + if (_dns_conf_get_group_set(optarg, server) != 0) { + tlog(TLOG_ERROR, "add group failed."); + goto errout; + } + break; + } + case 'p': { + safe_strncpy(server->spki, optarg, DNS_MAX_SPKI_LEN); + break; + } + case 'V': { + safe_strncpy(server->tls_host_verify, optarg, DNS_MAX_CNAME_LEN); + break; + } + case 'N': { + server->skip_check_cert = 1; + break; + } + default: + break; + } + } + + /* add new server */ + server->type = type; + server->port = port; + server->result_flag = result_flag; + server->server_flag = server_flag; + server->ttl = ttl; + dns_conf_server_num++; + tlog(TLOG_DEBUG, "add server %s, flag: %X, ttl: %d", ip, result_flag, ttl); + + return 0; + +errout: + if (spki) { + free(spki); + } + + return -1; +} + +static int _config_domain_iter_free(void *data, const unsigned char *key, uint32_t key_len, void *value) +{ + struct dns_domain_rule *domain_rule = value; + int i = 0; + + if (domain_rule == NULL) { + return 0; + } + + for (i = 0; i < DOMAIN_RULE_MAX; i++) { + if (domain_rule->rules[i] == NULL) { + continue; + } + + free(domain_rule->rules[i]); + } + + free(domain_rule); + return 0; +} + +static void _config_domain_destroy(void) +{ + art_iter(&dns_conf_domain_rule, _config_domain_iter_free, NULL); + art_tree_destroy(&dns_conf_domain_rule); +} + +static void _config_address_destroy(radix_node_t *node, void *cbctx) +{ + if (node == NULL) { + return; + } + + if (node->data == NULL) { + return; + } + + free(node->data); + node->data = NULL; +} + +static int _config_domain_rule_add(char *domain, enum domain_rule type, void *rule) +{ + struct dns_domain_rule *domain_rule = NULL; + struct dns_domain_rule *old_domain_rule = NULL; + struct dns_domain_rule *add_domain_rule = NULL; + + char domain_key[DNS_MAX_CONF_CNAME_LEN]; + int len = 0; + + /* Reverse string, for suffix match */ + len = strlen(domain); + if (len >= sizeof(domain_key)) { + tlog(TLOG_ERROR, "domain name %s too long", domain); + goto errout; + } + reverse_string(domain_key, domain, len, 1); + domain_key[len] = '.'; + len++; + domain_key[len] = 0; + + if (type >= DOMAIN_RULE_MAX) { + goto errout; + } + + /* Get existing or create domain rule */ + domain_rule = art_search(&dns_conf_domain_rule, (unsigned char *)domain_key, len); + if (domain_rule == NULL) { + add_domain_rule = malloc(sizeof(*add_domain_rule)); + if (add_domain_rule == NULL) { + goto errout; + } + memset(add_domain_rule, 0, sizeof(*add_domain_rule)); + domain_rule = add_domain_rule; + } + + /* add new rule to domain */ + if (domain_rule->rules[type]) { + free(domain_rule->rules[type]); + domain_rule->rules[type] = NULL; + } + + domain_rule->rules[type] = rule; + + /* update domain rule */ + if (add_domain_rule) { + old_domain_rule = art_insert(&dns_conf_domain_rule, (unsigned char *)domain_key, len, add_domain_rule); + if (old_domain_rule) { + free(old_domain_rule); + } + } + + return 0; +errout: + if (add_domain_rule) { + free(add_domain_rule); + } + + tlog(TLOG_ERROR, "add doamin %s rule failed", domain); + return -1; +} + +static int _config_domain_rule_flag_set(char *domain, unsigned int flag) +{ + struct dns_domain_rule *domain_rule = NULL; + struct dns_domain_rule *old_domain_rule = NULL; + struct dns_domain_rule *add_domain_rule = NULL; + struct dns_rule_flags *rule_flags = NULL; + + char domain_key[DNS_MAX_CONF_CNAME_LEN]; + int len = 0; + + len = strlen(domain); + if (len >= sizeof(domain_key)) { + tlog(TLOG_ERROR, "domain %s too long", domain); + return -1; + } + reverse_string(domain_key, domain, len, 1); + domain_key[len] = '.'; + len++; + domain_key[len] = 0; + + /* Get existing or create domain rule */ + domain_rule = art_search(&dns_conf_domain_rule, (unsigned char *)domain_key, len); + if (domain_rule == NULL) { + add_domain_rule = malloc(sizeof(*add_domain_rule)); + if (add_domain_rule == NULL) { + goto errout; + } + memset(add_domain_rule, 0, sizeof(*add_domain_rule)); + domain_rule = add_domain_rule; + } + + /* add new rule to domain */ + if (domain_rule->rules[DOMAIN_RULE_FLAGS] == NULL) { + rule_flags = malloc(sizeof(*rule_flags)); + rule_flags->flags = 0; + domain_rule->rules[DOMAIN_RULE_FLAGS] = rule_flags; + } + + rule_flags = domain_rule->rules[DOMAIN_RULE_FLAGS]; + rule_flags->flags |= flag; + + /* update domain rule */ + if (add_domain_rule) { + old_domain_rule = art_insert(&dns_conf_domain_rule, (unsigned char *)domain_key, len, add_domain_rule); + if (old_domain_rule) { + free(old_domain_rule); + } + } + + return 0; +errout: + if (add_domain_rule) { + free(add_domain_rule); + } + + tlog(TLOG_ERROR, "add doamin %s rule failed", domain); + return 0; +} + +static void _config_ipset_table_destroy(void) +{ + struct dns_ipset_name *ipset_name = NULL; + struct hlist_node *tmp = NULL; + int i; + + hash_for_each_safe(dns_ipset_table.ipset, i, tmp, ipset_name, node) + { + hlist_del_init(&ipset_name->node); + free(ipset_name); + } +} + +static const char *_dns_conf_get_ipset(const char *ipsetname) +{ + uint32_t key = 0; + struct dns_ipset_name *ipset_name = NULL; + + key = hash_string(ipsetname); + hash_for_each_possible(dns_ipset_table.ipset, ipset_name, node, key) + { + if (strncmp(ipset_name->ipsetname, ipsetname, DNS_MAX_IPSET_NAMELEN) == 0) { + return ipset_name->ipsetname; + } + } + + ipset_name = malloc(sizeof(*ipset_name)); + if (ipset_name == NULL) { + goto errout; + } + + key = hash_string(ipsetname); + safe_strncpy(ipset_name->ipsetname, ipsetname, DNS_MAX_IPSET_NAMELEN); + hash_add(dns_ipset_table.ipset, &ipset_name->node, key); + + return ipset_name->ipsetname; +errout: + if (ipset_name) { + free(ipset_name); + } + + return NULL; +} + +static int _conf_domain_rule_ipset(char *domain, const char *ipsetname) +{ + struct dns_ipset_rule *ipset_rule = NULL; + const char *ipset = NULL; + + /* Process domain option */ + if (strncmp(ipsetname, "-", sizeof("-")) != 0) { + /* new ipset domain */ + ipset = _dns_conf_get_ipset(ipsetname); + if (ipset == NULL) { + goto errout; + } + + ipset_rule = malloc(sizeof(*ipset_rule)); + if (ipset_rule == NULL) { + goto errout; + } + + ipset_rule->ipsetname = ipset; + } else { + /* ignore this domain */ + if (_config_domain_rule_flag_set(domain, DOMAIN_FLAG_IPSET_IGNORE) != 0) { + goto errout; + } + + return 0; + } + + if (_config_domain_rule_add(domain, DOMAIN_RULE_IPSET, ipset_rule) != 0) { + goto errout; + } + + return 0; +errout: + if (ipset_rule) { + free(ipset_rule); + } + + tlog(TLOG_ERROR, "add ipset %s failed", ipsetname); + return 0; +} + +static int _config_ipset(void *data, int argc, char *argv[]) +{ + char domain[DNS_MAX_CONF_CNAME_LEN]; + char *value = argv[1]; + + if (argc <= 1) { + goto errout; + } + + if (_get_domain(value, domain, DNS_MAX_CONF_CNAME_LEN, &value) != 0) { + goto errout; + } + + return _conf_domain_rule_ipset(domain, value); +errout: + tlog(TLOG_ERROR, "add ipset %s failed", value); + return 0; +} + +static int _conf_domain_rule_address(char *domain, const char *domain_address) +{ + struct dns_address_IPV4 *address_ipv4 = NULL; + struct dns_address_IPV6 *address_ipv6 = NULL; + void *address = NULL; + char ip[MAX_IP_LEN]; + int port; + struct sockaddr_storage addr; + socklen_t addr_len = sizeof(addr); + enum domain_rule type = 0; + unsigned int flag = 0; + + if (*(domain_address) == '#') { + if (strncmp(domain_address, "#4", sizeof("#4")) == 0) { + flag = DOMAIN_FLAG_ADDR_IPV4_SOA; + } else if (strncmp(domain_address, "#6", sizeof("#6")) == 0) { + flag = DOMAIN_FLAG_ADDR_IPV6_SOA; + } else if (strncmp(domain_address, "#", sizeof("#")) == 0) { + flag = DOMAIN_FLAG_ADDR_SOA; + } else { + goto errout; + } + + /* add SOA rule */ + if (_config_domain_rule_flag_set(domain, flag) != 0) { + goto errout; + } + + return 0; + } else if (*(domain_address) == '-') { + if (strncmp(domain_address, "-4", sizeof("-4")) == 0) { + flag = DOMAIN_FLAG_ADDR_IPV4_IGN; + } else if (strncmp(domain_address, "-6", sizeof("-6")) == 0) { + flag = DOMAIN_FLAG_ADDR_IPV6_IGN; + } else if (strncmp(domain_address, "-", sizeof("-")) == 0) { + flag = DOMAIN_FLAG_ADDR_IGN; + } else { + goto errout; + } + + /* ignore rule */ + if (_config_domain_rule_flag_set(domain, flag) != 0) { + goto errout; + } + + return 0; + } else { + /* set address to domain */ + if (parse_ip(domain_address, ip, &port) != 0) { + goto errout; + } + + if (getaddr_by_host(ip, (struct sockaddr *)&addr, &addr_len) != 0) { + goto errout; + } + + switch (addr.ss_family) { + case AF_INET: { + struct sockaddr_in *addr_in; + address_ipv4 = malloc(sizeof(*address_ipv4)); + if (address_ipv4 == NULL) { + goto errout; + } + + addr_in = (struct sockaddr_in *)&addr; + memcpy(address_ipv4->ipv4_addr, &addr_in->sin_addr.s_addr, 4); + type = DOMAIN_RULE_ADDRESS_IPV4; + address = address_ipv4; + } break; + case AF_INET6: { + struct sockaddr_in6 *addr_in6; + addr_in6 = (struct sockaddr_in6 *)&addr; + if (IN6_IS_ADDR_V4MAPPED(&addr_in6->sin6_addr)) { + address_ipv4 = malloc(sizeof(*address_ipv4)); + if (address_ipv4 == NULL) { + goto errout; + } + memcpy(address_ipv4->ipv4_addr, addr_in6->sin6_addr.s6_addr + 12, 4); + type = DOMAIN_RULE_ADDRESS_IPV4; + address = address_ipv4; + } else { + address_ipv6 = malloc(sizeof(*address_ipv6)); + if (address_ipv6 == NULL) { + goto errout; + } + memcpy(address_ipv6->ipv6_addr, addr_in6->sin6_addr.s6_addr, 16); + type = DOMAIN_RULE_ADDRESS_IPV6; + address = address_ipv6; + } + } break; + default: + goto errout; + } + } + + /* add domain to ART-tree */ + if (_config_domain_rule_add(domain, type, address) != 0) { + goto errout; + } + + return 0; +errout: + if (address) { + free(address); + } + + tlog(TLOG_ERROR, "add address %s, %s failed", domain, domain_address); + return 0; +} + +static int _config_address(void *data, int argc, char *argv[]) +{ + char *value = argv[1]; + char domain[DNS_MAX_CONF_CNAME_LEN]; + + if (argc <= 1) { + goto errout; + } + + if (_get_domain(value, domain, DNS_MAX_CONF_CNAME_LEN, &value) != 0) { + goto errout; + } + + return _conf_domain_rule_address(domain, value); +errout: + tlog(TLOG_ERROR, "add address %s failed", value); + return 0; +} + +static int _config_speed_check_mode_parser(struct dns_domain_check_order *check_order, const char *mode) +{ + char tmpbuff[DNS_MAX_OPT_LEN]; + char *field; + char *ptr; + int order = 0; + int port = 80; + int i = 0; + + safe_strncpy(tmpbuff, mode, DNS_MAX_OPT_LEN); + memset(check_order, 0, sizeof(*check_order)); + + ptr = tmpbuff; + do { + field = ptr; + ptr = strstr(ptr, ","); + if (field == NULL || order >= DOMAIN_CHECK_NUM) { + return 0; + } + + if (ptr) { + *ptr = 0; + } + + if (strncmp(field, "ping", sizeof("ping")) == 0) { + if (dns_has_cap_ping == 0) { + if (ptr) { + ptr++; + } + continue; + } + check_order->order[order] = DOMAIN_CHECK_ICMP; + } else if (strstr(field, "tcp") == field) { + char *port_str = strstr(field, ":"); + if (port_str) { + port = atoi(port_str + 1); + if (port <= 0 || port >= 65535) { + port = 80; + } + } + + check_order->order[order] = DOMAIN_CHECK_TCP; + check_order->tcp_port = port; + } else if (strncmp(field, "none", sizeof("none")) == 0) { + check_order->order[order] = DOMAIN_CHECK_NONE; + for (i = order + 1; i < DOMAIN_CHECK_NUM; i++) { + check_order->order[i] = DOMAIN_CHECK_NONE; + } + + return 0; + } + order++; + if (ptr) { + ptr++; + } + + } while (ptr); + + return 0; +} + +static int _config_speed_check_mode(void *data, int argc, char *argv[]) +{ + char mode[DNS_MAX_OPT_LEN]; + + if (argc <= 1) { + return -1; + } + + safe_strncpy(mode, argv[1], sizeof(mode)); + return _config_speed_check_mode_parser(&dns_conf_check_order, mode); +} + +static int _config_bind_ip(int argc, char *argv[], DNS_BIND_TYPE type) +{ + int index = dns_conf_bind_ip_num; + struct dns_bind_ip *bind_ip; + char *ip = NULL; + int opt = 0; + char group_name[DNS_GROUP_NAME_LEN]; + const char *group = NULL; + unsigned int server_flag = 0; + + /* clang-format off */ + static struct option long_options[] = { + {"group", required_argument, NULL, 'g'}, /* add to group */ + {"no-rule-addr", no_argument, NULL, 'A'}, + {"no-rule-nameserver", no_argument, NULL, 'N'}, + {"no-rule-ipset", no_argument, NULL, 'I'}, + {"no-rule-sni-proxy", no_argument, NULL, 'P'}, + {"no-rule-soa", no_argument, NULL, 'O'}, + {"no-speed-check", no_argument, NULL, 'S'}, + {"no-cache", no_argument, NULL, 'C'}, + {"no-dualstack-selection", no_argument, NULL, 'D'}, + {"force-aaaa-soa", no_argument, NULL, 'F'}, + {NULL, no_argument, NULL, 0} + }; + /* clang-format on */ + if (argc <= 1) { + tlog(TLOG_ERROR, "invalid parameter."); + goto errout; + } + + if (index >= DNS_MAX_SERVERS) { + tlog(TLOG_WARN, "exceeds max server number, %s", ip); + return 0; + } + + bind_ip = &dns_conf_bind_ip[index]; + bind_ip->type = type; + bind_ip->flags = 0; + ip = argv[1]; + safe_strncpy(bind_ip->ip, ip, DNS_MAX_IPLEN); + + /* process extra options */ + optind = 1; + while (1) { + opt = getopt_long_only(argc, argv, "", long_options, NULL); + if (opt == -1) { + break; + } + + switch (opt) { + case 'g': { + safe_strncpy(group_name, optarg, DNS_GROUP_NAME_LEN); + group = _dns_conf_get_group_name(group_name); + break; + } + case 'A': { + server_flag |= BIND_FLAG_NO_RULE_ADDR; + break; + } + case 'N': { + server_flag |= BIND_FLAG_NO_RULE_NAMESERVER; + break; + } + case 'I': { + server_flag |= BIND_FLAG_NO_RULE_IPSET; + break; + } + case 'P': { + server_flag |= BIND_FLAG_NO_RULE_SNIPROXY; + break; + } + case 'S': { + server_flag |= BIND_FLAG_NO_SPEED_CHECK; + break; + } + case 'C': { + server_flag |= BIND_FLAG_NO_CACHE; + break; + } + case 'O': { + server_flag |= BIND_FLAG_NO_RULE_SOA; + break; + } + case 'D': { + server_flag |= BIND_FLAG_NO_DUALSTACK_SELECTION; + break; + } + case 'F': { + server_flag |= BIND_FLAG_FORCE_AAAA_SOA; + break; + } + default: + break; + } + } + + /* add new server */ + bind_ip->flags = server_flag; + bind_ip->group = group; + dns_conf_bind_ip_num++; + tlog(TLOG_DEBUG, "bind ip %s, type:%d, flag: %X", ip, type, server_flag); + + return 0; + +errout: + return -1; +} + +static int _config_bind_ip_udp(void *data, int argc, char *argv[]) +{ + return _config_bind_ip(argc, argv, DNS_BIND_TYPE_UDP); +} + +static int _config_bind_ip_tcp(void *data, int argc, char *argv[]) +{ + return _config_bind_ip(argc, argv, DNS_BIND_TYPE_TCP); +} + +static int _config_server_udp(void *data, int argc, char *argv[]) +{ + return _config_server(argc, argv, DNS_SERVER_UDP, DEFAULT_DNS_PORT); +} + +static int _config_server_tcp(void *data, int argc, char *argv[]) +{ + return _config_server(argc, argv, DNS_SERVER_TCP, DEFAULT_DNS_PORT); +} + +static int _config_server_tls(void *data, int argc, char *argv[]) +{ + return _config_server(argc, argv, DNS_SERVER_TLS, DEFAULT_DNS_TLS_PORT); +} + +static int _config_server_https(void *data, int argc, char *argv[]) +{ + int ret = 0; + ret = _config_server(argc, argv, DNS_SERVER_HTTPS, DEFAULT_DNS_HTTPS_PORT); + + return ret; +} + +static int _conf_domain_rule_nameserver(char *domain, const char *group_name) +{ + struct dns_nameserver_rule *nameserver_rule = NULL; + const char *group = NULL; + + if (strncmp(group_name, "-", sizeof("-")) != 0) { + group = _dns_conf_get_group_name(group_name); + if (group == NULL) { + goto errout; + } + + nameserver_rule = malloc(sizeof(*nameserver_rule)); + if (nameserver_rule == NULL) { + goto errout; + } + + nameserver_rule->group_name = group; + } else { + /* ignore this domain */ + if (_config_domain_rule_flag_set(domain, DOMAIN_FLAG_NAMESERVER_IGNORE) != 0) { + goto errout; + } + + return 0; + } + + if (_config_domain_rule_add(domain, DOMAIN_RULE_NAMESERVER, nameserver_rule) != 0) { + goto errout; + } + + return 0; +errout: + if (nameserver_rule) { + free(nameserver_rule); + } + + tlog(TLOG_ERROR, "add nameserver %s, %s failed", domain, group_name); + return 0; +} + +static int _config_nameserver(void *data, int argc, char *argv[]) +{ + char domain[DNS_MAX_CONF_CNAME_LEN]; + char *value = argv[1]; + + if (argc <= 1) { + goto errout; + } + + if (_get_domain(value, domain, DNS_MAX_CONF_CNAME_LEN, &value) != 0) { + goto errout; + } + + return _conf_domain_rule_nameserver(domain, value); +errout: + tlog(TLOG_ERROR, "add nameserver %s failed", value); + return 0; +} + +static radix_node_t *_create_addr_node(char *addr) +{ + radix_node_t *node; + void *p; + prefix_t prefix; + const char *errmsg = NULL; + radix_tree_t *tree = NULL; + + p = prefix_pton(addr, -1, &prefix, &errmsg); + if (p == NULL) { + return NULL; + } + + switch (prefix.family) { + case AF_INET: + tree = dns_conf_address_rule.ipv4; + break; + case AF_INET6: + tree = dns_conf_address_rule.ipv6; + break; + } + + node = radix_lookup(tree, &prefix); + return node; +} + +static int _config_iplist_rule(char *subnet, enum address_rule rule) +{ + radix_node_t *node = NULL; + struct dns_ip_address_rule *ip_rule = NULL; + + node = _create_addr_node(subnet); + if (node == NULL) { + return -1; + } + + if (node->data == NULL) { + ip_rule = malloc(sizeof(*ip_rule)); + if (ip_rule == NULL) { + return -1; + } + + node->data = ip_rule; + memset(ip_rule, 0, sizeof(*ip_rule)); + } + + ip_rule = node->data; + + switch (rule) { + case ADDRESS_RULE_BLACKLIST: + ip_rule->blacklist = 1; + break; + case ADDRESS_RULE_WHITELIST: + ip_rule->whitelist = 1; + break; + case ADDRESS_RULE_BOGUS: + ip_rule->bogus = 1; + break; + case ADDRESS_RULE_IP_IGNORE: + ip_rule->ip_ignore = 1; + break; + default: + return -1; + } + + return 0; +} + +static int _config_blacklist_ip(void *data, int argc, char *argv[]) +{ + if (argc <= 1) { + return -1; + } + + return _config_iplist_rule(argv[1], ADDRESS_RULE_BLACKLIST); +} + +static int _conf_bogus_nxdomain(void *data, int argc, char *argv[]) +{ + if (argc <= 1) { + return -1; + } + + return _config_iplist_rule(argv[1], ADDRESS_RULE_BOGUS); +} + +static int _conf_ip_ignore(void *data, int argc, char *argv[]) +{ + if (argc <= 1) { + return -1; + } + + return _config_iplist_rule(argv[1], ADDRESS_RULE_IP_IGNORE); +} + +static int _conf_whitelist_ip(void *data, int argc, char *argv[]) +{ + if (argc <= 1) { + return -1; + } + + return _config_iplist_rule(argv[1], ADDRESS_RULE_WHITELIST); +} + +static int _conf_edns_client_subnet(void *data, int argc, char *argv[]) +{ + char *slash = NULL; + char *value = NULL; + int subnet = 0; + struct dns_edns_client_subnet *ecs = NULL; + struct sockaddr_storage addr; + socklen_t addr_len = sizeof(addr); + + if (argc <= 1 || data == NULL) { + return -1; + } + + value = argv[1]; + + slash = strstr(value, "/"); + if (slash) { + *slash = 0; + slash++; + subnet = atoi(slash); + if (subnet < 0 || subnet > 128) { + return -1; + } + } + + if (getaddr_by_host(value, (struct sockaddr *)&addr, &addr_len) != 0) { + goto errout; + } + + switch (addr.ss_family) { + case AF_INET: + ecs = &dns_conf_ipv4_ecs; + break; + case AF_INET6: + ecs = &dns_conf_ipv6_ecs; + break; + default: + goto errout; + } + + safe_strncpy(ecs->ip, value, DNS_MAX_IPLEN); + ecs->subnet = subnet; + ecs->enable = 1; + + return 0; + +errout: + return -1; +} + +static int _conf_domain_rule_speed_check(char *domain, const char *mode) +{ + struct dns_domain_check_order *check_order; + + check_order = malloc(sizeof(*check_order)); + if (check_order == NULL) { + goto errout; + } + + if (_config_speed_check_mode_parser(check_order, mode) != 0) { + goto errout; + } + + if (_config_domain_rule_add(domain, DOMAIN_RULE_CHECKSPEED, check_order) != 0) { + goto errout; + } + + return 0; +errout: + if (check_order) { + free(check_order); + } + return 0; +} + +static int _conf_domain_rules(void *data, int argc, char *argv[]) +{ + int opt = 0; + char domain[DNS_MAX_CONF_CNAME_LEN]; + char *value = argv[1]; + + /* clang-format off */ + static struct option long_options[] = { + {"speed-check-mode", required_argument, NULL, 'c'}, + {"address", required_argument, NULL, 'a'}, + {"ipset", required_argument, NULL, 'p'}, + {"nameserver", required_argument, NULL, 'n'}, + {NULL, no_argument, NULL, 0} + }; + /* clang-format on */ + + if (argc <= 1) { + tlog(TLOG_ERROR, "invalid parameter."); + goto errout; + } + + if (_get_domain(value, domain, DNS_MAX_CONF_CNAME_LEN, &value) != 0) { + goto errout; + } + + /* process extra options */ + optind = 1; + while (1) { + opt = getopt_long_only(argc, argv, "", long_options, NULL); + if (opt == -1) { + break; + } + + switch (opt) { + case 'c': { + const char *check_mode = optarg; + if (check_mode == NULL) { + goto errout; + } + + if (_conf_domain_rule_speed_check(domain, check_mode) != 0) { + tlog(TLOG_ERROR, "add check-speed-rule rule failed."); + goto errout; + } + + break; + } + case 'a': { + const char *address = optarg; + if (address == NULL) { + goto errout; + } + + if (_conf_domain_rule_address(domain, address) != 0) { + tlog(TLOG_ERROR, "add address rule failed."); + goto errout; + } + + break; + } + case 'p': { + const char *ipsetname = optarg; + if (ipsetname == NULL) { + goto errout; + } + + if (_conf_domain_rule_ipset(domain, ipsetname) != 0) { + tlog(TLOG_ERROR, "add ipset rule failed."); + goto errout; + } + + break; + } + case 'n': { + const char *nameserver_group = optarg; + if (nameserver_group == NULL) { + goto errout; + } + + if (_conf_domain_rule_nameserver(domain, nameserver_group) != 0) { + tlog(TLOG_ERROR, "add nameserver rule failed."); + goto errout; + } + + break; + } + default: + break; + } + } + + return 0; +errout: + return -1; +} + +static int _config_log_level(void *data, int argc, char *argv[]) +{ + /* read log level and set */ + char *value = argv[1]; + + if (strncmp("debug", value, MAX_LINE_LEN) == 0) { + dns_conf_log_level = TLOG_DEBUG; + } else if (strncmp("info", value, MAX_LINE_LEN) == 0) { + dns_conf_log_level = TLOG_INFO; + } else if (strncmp("notice", value, MAX_LINE_LEN) == 0) { + dns_conf_log_level = TLOG_NOTICE; + } else if (strncmp("warn", value, MAX_LINE_LEN) == 0) { + dns_conf_log_level = TLOG_WARN; + } else if (strncmp("error", value, MAX_LINE_LEN) == 0) { + dns_conf_log_level = TLOG_ERROR; + } else if (strncmp("fatal", value, MAX_LINE_LEN) == 0) { + dns_conf_log_level = TLOG_FATAL; + } else { + return -1; + } + + return 0; +} + +static struct config_item _config_item[] = { + CONF_STRING("server-name", (char *)dns_conf_server_name, DNS_MAX_SERVER_NAME_LEN), + CONF_CUSTOM("bind", _config_bind_ip_udp, NULL), + CONF_CUSTOM("bind-tcp", _config_bind_ip_tcp, NULL), + CONF_CUSTOM("server", _config_server_udp, NULL), + CONF_CUSTOM("server-tcp", _config_server_tcp, NULL), + CONF_CUSTOM("server-tls", _config_server_tls, NULL), + CONF_CUSTOM("server-https", _config_server_https, NULL), + CONF_CUSTOM("nameserver", _config_nameserver, NULL), + CONF_CUSTOM("address", _config_address, NULL), + CONF_YESNO("ipset-timeout", &dns_conf_ipset_timeout_enable), + CONF_CUSTOM("ipset", _config_ipset, NULL), + CONF_CUSTOM("speed-check-mode", _config_speed_check_mode, NULL), + CONF_INT("tcp-idle-time", &dns_conf_tcp_idle_time, 0, 3600), + CONF_INT("cache-size", &dns_conf_cachesize, 0, CONF_INT_MAX), + CONF_YESNO("prefetch-domain", &dns_conf_prefetch), + CONF_YESNO("serve-expired", &dns_conf_serve_expired), + CONF_INT("serve-expired-ttl", &dns_conf_serve_expired_ttl, 0, CONF_INT_MAX), + CONF_YESNO("dualstack-ip-selection", &dns_conf_dualstack_ip_selection), + CONF_INT("dualstack-ip-selection-threshold", &dns_conf_dualstack_ip_selection_threshold, 0, 1000), + CONF_CUSTOM("log-level", _config_log_level, NULL), + CONF_STRING("log-file", (char *)dns_conf_log_file, DNS_MAX_PATH), + CONF_SIZE("log-size", &dns_conf_log_size, 0, 1024 * 1024 * 1024), + CONF_INT("log-num", &dns_conf_log_num, 0, 1024), + CONF_YESNO("audit-enable", &dns_conf_audit_enable), + CONF_YESNO("audit-SOA", &dns_conf_audit_log_SOA), + CONF_STRING("audit-file", (char *)&dns_conf_audit_file, DNS_MAX_PATH), + CONF_SIZE("audit-size", &dns_conf_audit_size, 0, 1024 * 1024 * 1024), + CONF_INT("audit-num", &dns_conf_audit_num, 0, 1024), + CONF_INT("rr-ttl", &dns_conf_rr_ttl, 0, CONF_INT_MAX), + CONF_INT("rr-ttl-min", &dns_conf_rr_ttl_min, 0, CONF_INT_MAX), + CONF_INT("rr-ttl-max", &dns_conf_rr_ttl_max, 0, CONF_INT_MAX), + CONF_YESNO("force-AAAA-SOA", &dns_conf_force_AAAA_SOA), + CONF_CUSTOM("blacklist-ip", _config_blacklist_ip, NULL), + CONF_CUSTOM("whitelist-ip", _conf_whitelist_ip, NULL), + CONF_CUSTOM("bogus-nxdomain", _conf_bogus_nxdomain, NULL), + CONF_CUSTOM("ignore-ip", _conf_ip_ignore, NULL), + CONF_CUSTOM("edns-client-subnet", _conf_edns_client_subnet, NULL), + CONF_CUSTOM("domain-rules", _conf_domain_rules, NULL), + CONF_STRING("ca-file", (char *)&dns_conf_ca_file, DNS_MAX_PATH), + CONF_STRING("ca-path", (char *)&dns_conf_ca_path, DNS_MAX_PATH), + CONF_CUSTOM("conf-file", config_addtional_file, NULL), + CONF_END(), +}; + +static int _conf_printf(const char *file, int lineno, int ret) +{ + if (ret == CONF_RET_ERR) { + tlog(TLOG_ERROR, "process config file '%s' failed at line %d.", file, lineno); + syslog(LOG_NOTICE, "process config file '%s' failed at line %d.", file, lineno); + return -1; + } else if (ret == CONF_RET_WARN) { + tlog(TLOG_WARN, "process config file '%s' failed at line %d.", file, lineno); + syslog(LOG_NOTICE, "process config file '%s' failed at line %d.", file, lineno); + return -1; + } + + return 0; +} + +int config_addtional_file(void *data, int argc, char *argv[]) +{ + char *conf_file = argv[1]; + char file_path[DNS_MAX_PATH]; + char file_path_dir[DNS_MAX_PATH]; + + if (conf_file[0] != '/') { + safe_strncpy(file_path_dir, conf_get_conf_file(), DNS_MAX_PATH); + dirname(file_path_dir); + if (snprintf(file_path, DNS_MAX_PATH, "%s/%s", file_path_dir, conf_file) < 0) { + return -1; + } + } else { + safe_strncpy(file_path, conf_file, DNS_MAX_PATH); + } + + if (access(file_path, R_OK) != 0) { + tlog(TLOG_WARN, "conf file %s is not readable.", file_path); + syslog(LOG_NOTICE, "conf file %s is not readable.", file_path); + return 0; + } + + return load_conf(file_path, _config_item, _conf_printf); +} + +static int _dns_server_load_conf_init(void) +{ + dns_conf_address_rule.ipv4 = New_Radix(); + dns_conf_address_rule.ipv6 = New_Radix(); + if (dns_conf_address_rule.ipv4 == NULL || dns_conf_address_rule.ipv6 == NULL) { + tlog(TLOG_WARN, "init radix tree failed."); + return -1; + } + + art_tree_init(&dns_conf_domain_rule); + + hash_init(dns_ipset_table.ipset); + hash_init(dns_group_table.group); + + return 0; +} + +void dns_server_load_exit(void) +{ + _config_domain_destroy(); + Destroy_Radix(dns_conf_address_rule.ipv4, _config_address_destroy, NULL); + Destroy_Radix(dns_conf_address_rule.ipv6, _config_address_destroy, NULL); + _config_ipset_table_destroy(); + _config_group_table_destroy(); +} + +static int _dns_conf_speed_check_mode_verify(void) +{ + int i, j; + int print_log = 0; + + if (dns_has_cap_ping == 1) { + return 0; + } + + for (i = 0; i < DOMAIN_CHECK_NUM; i++) { + if (dns_conf_check_order.order[i] == DOMAIN_CHECK_ICMP) { + for (j = i + 1; j < DOMAIN_CHECK_NUM; j++) { + dns_conf_check_order.order[j - 1] = dns_conf_check_order.order[j]; + } + dns_conf_check_order.order[j - 1] = DOMAIN_CHECK_NONE; + print_log = 1; + } + } + + if (print_log) { + tlog(TLOG_WARN, "speed check by ping is disabled because smartdns does not have network raw privileges"); + } + + return 0; +} + +static int _dns_conf_load_pre(void) +{ + if (_dns_server_load_conf_init() != 0) { + goto errout; + } + + dns_has_cap_ping = has_network_raw_cap(); + + return 0; + +errout: + return -1; +} + +static int _dns_conf_load_post(void) +{ + _dns_conf_speed_check_mode_verify(); + + return 0; +} + +int dns_server_load_conf(const char *file) +{ + int ret = 0; + _dns_conf_load_pre(); + openlog("smartdns", LOG_CONS | LOG_NDELAY, LOG_LOCAL1); + ret = load_conf(file, _config_item, _conf_printf); + closelog(); + _dns_conf_load_post(); + return ret; +} diff --git a/release/src/router/smartdns/src/dns_conf.h b/release/src/router/smartdns/src/dns_conf.h index c02e3cb373..9658111689 100644 --- a/release/src/router/smartdns/src/dns_conf.h +++ b/release/src/router/smartdns/src/dns_conf.h @@ -1,247 +1,255 @@ -/************************************************************************* - * - * Copyright (C) 2018-2020 Ruilin Peng (Nick) . - * - * smartdns is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * smartdns is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#ifndef _DNS_CONF -#define _DNS_CONF - -#include "art.h" -#include "conf.h" -#include "dns.h" -#include "dns_client.h" -#include "hash.h" -#include "hashtable.h" -#include "list.h" -#include "radix.h" - -#ifdef __cpluscplus -extern "C" { -#endif - -#define DNS_MAX_BIND_IP 16 -#define DNS_MAX_SERVERS 64 -#define DNS_MAX_SERVER_NAME_LEN 128 -#define DNS_MAX_IPSET_NAMELEN 32 -#define DNS_GROUP_NAME_LEN 32 -#define DNS_NAX_GROUP_NUMBER 16 -#define DNS_MAX_IPLEN 64 -#define DNS_MAX_SPKI_LEN 64 -#define DNS_MAX_URL_LEN 256 -#define DNS_MAX_PATH 1024 -#define DEFAULT_DNS_PORT 53 -#define DEFAULT_DNS_TLS_PORT 853 -#define DEFAULT_DNS_HTTPS_PORT 443 -#define DNS_MAX_CONF_CNAME_LEN 256 -#define SMARTDNS_CONF_FILE "/etc/smartdns/smartdns.conf" -#define SMARTDNS_LOG_FILE "/var/log/smartdns.log" -#define SMARTDNS_AUDIT_FILE "/var/log/smartdns-audit.log" - -enum domain_rule { - DOMAIN_RULE_FLAGS = 0, - DOMAIN_RULE_ADDRESS_IPV4, - DOMAIN_RULE_ADDRESS_IPV6, - DOMAIN_RULE_IPSET, - DOMAIN_RULE_NAMESERVER, - DOMAIN_RULE_MAX, -}; - -typedef enum { - DNS_BIND_TYPE_UDP, - DNS_BIND_TYPE_TCP, - DNS_BIND_TYPE_TLS, -} DNS_BIND_TYPE; - -#define DOMAIN_CHECK_NONE 0 -#define DOMAIN_CHECK_ICMP 1 -#define DOMAIN_CHECK_TCP 2 -#define DOMAIN_CHECK_NUM 2 - -#define DOMAIN_FLAG_ADDR_SOA (1 << 0) -#define DOMAIN_FLAG_ADDR_IPV4_SOA (1 << 1) -#define DOMAIN_FLAG_ADDR_IPV6_SOA (1 << 2) -#define DOMAIN_FLAG_ADDR_IGN (1 << 3) -#define DOMAIN_FLAG_ADDR_IPV4_IGN (1 << 4) -#define DOMAIN_FLAG_ADDR_IPV6_IGN (1 << 5) -#define DOMAIN_FLAG_IPSET_IGNORE (1 << 6) -#define DOMAIN_FLAG_NAMESERVER_IGNORE (1 << 7) - -#define SERVER_FLAG_EXCLUDE_DEFAULT (1 << 0) - -#define BIND_FLAG_NO_RULE_ADDR (1 << 0) -#define BIND_FLAG_NO_RULE_NAMESERVER (1 << 1) -#define BIND_FLAG_NO_RULE_IPSET (1 << 2) -#define BIND_FLAG_NO_RULE_SNIPROXY (1 << 3) -#define BIND_FLAG_NO_RULE_SOA (1 << 4) -#define BIND_FLAG_NO_SPEED_CHECK (1 << 5) -#define BIND_FLAG_NO_CACHE (1 << 6) -#define BIND_FLAG_NO_DUALSTACK_SELECTION (1 << 7) - -struct dns_rule_flags { - unsigned int flags; -}; - -struct dns_address_IPV4 { - unsigned char ipv4_addr[DNS_RR_A_LEN]; -}; - -struct dns_address_IPV6 { - unsigned char ipv6_addr[DNS_RR_AAAA_LEN]; -}; - -struct dns_ipset_name { - struct hlist_node node; - char ipsetname[DNS_MAX_IPSET_NAMELEN]; -}; - -struct dns_ipset_rule { - const char *ipsetname; -}; - -struct dns_domain_rule { - void *rules[DOMAIN_RULE_MAX]; -}; - -struct dns_nameserver_rule { - const char *group_name; -}; - -struct dns_server_groups { - struct hlist_node node; - char group_name[DNS_GROUP_NAME_LEN]; - int server_num; - struct dns_servers *servers[DNS_MAX_SERVERS]; -}; - -struct dns_domain_check_order { - char order[DOMAIN_CHECK_NUM]; - unsigned short tcp_port; -}; - -struct dns_group_table { - DECLARE_HASHTABLE(group, 8); -}; -extern struct dns_group_table dns_group_table; - -struct dns_servers { - char server[DNS_MAX_IPLEN]; - unsigned short port; - unsigned int result_flag; - unsigned int server_flag; - int ttl; - dns_server_type_t type; - char spki[DNS_MAX_SPKI_LEN]; - char hostname[DNS_MAX_CNAME_LEN]; - char httphost[DNS_MAX_CNAME_LEN]; - char tls_host_verify[DNS_MAX_CNAME_LEN]; - char path[DNS_MAX_URL_LEN]; -}; - -/* ip address lists of domain */ -struct dns_bogus_ip_address { - struct hlist_node node; - dns_type_t addr_type; - union { - unsigned char ipv4_addr[DNS_RR_A_LEN]; - unsigned char ipv6_addr[DNS_RR_AAAA_LEN]; - unsigned char addr[0]; - }; -}; - -enum address_rule { - ADDRESS_RULE_BLACKLIST = 1, - ADDRESS_RULE_WHITELIST = 2, - ADDRESS_RULE_BOGUS = 3, - ADDRESS_RULE_IP_IGNORE = 4, -}; - -struct dns_ip_address_rule { - unsigned int blacklist : 1; - unsigned int whitelist : 1; - unsigned int bogus : 1; - unsigned int ip_ignore : 1; -}; - -struct dns_edns_client_subnet { - int enable; - char ip[DNS_MAX_IPLEN]; - int subnet; -}; - -struct dns_conf_address_rule { - radix_tree_t *ipv4; - radix_tree_t *ipv6; -}; - -struct dns_bind_ip { - DNS_BIND_TYPE type; - uint32_t flags; - char ip[DNS_MAX_IPLEN]; - const char *group; -}; - -extern struct dns_bind_ip dns_conf_bind_ip[DNS_MAX_BIND_IP]; -extern int dns_conf_bind_ip_num; - -extern int dns_conf_tcp_idle_time; -extern int dns_conf_cachesize; -extern int dns_conf_prefetch; -extern struct dns_servers dns_conf_servers[DNS_MAX_SERVERS]; -extern int dns_conf_server_num; - -extern int dns_conf_log_level; -extern char dns_conf_log_file[DNS_MAX_PATH]; -extern size_t dns_conf_log_size; -extern int dns_conf_log_num; - -extern struct dns_domain_check_order dns_conf_check_order; - -extern struct dns_server_groups dns_conf_server_groups[DNS_NAX_GROUP_NUMBER]; -extern int dns_conf_server_group_num; - -extern int dns_conf_audit_enable; -extern int dns_conf_audit_log_SOA; -extern char dns_conf_audit_file[DNS_MAX_PATH]; -extern size_t dns_conf_audit_size; -extern int dns_conf_audit_num; - -extern char dns_conf_server_name[DNS_MAX_SERVER_NAME_LEN]; -extern art_tree dns_conf_domain_rule; -extern struct dns_conf_address_rule dns_conf_address_rule; - -extern int dns_conf_dualstack_ip_selection; -extern int dns_conf_dualstack_ip_selection_threshold; - -extern int dns_conf_rr_ttl; -extern int dns_conf_rr_ttl_min; -extern int dns_conf_rr_ttl_max; -extern int dns_conf_force_AAAA_SOA; -extern int dns_conf_ipset_timeout_enable; - -extern struct dns_edns_client_subnet dns_conf_ipv4_ecs; -extern struct dns_edns_client_subnet dns_conf_ipv6_ecs; - -extern char dns_conf_sni_proxy_ip[DNS_MAX_IPLEN]; - -void dns_server_load_exit(void); - -int dns_server_load_conf(const char *file); - -extern int config_addtional_file(void *data, int argc, char *argv[]); -#ifdef __cpluscplus -} -#endif -#endif // !_DNS_CONF +/************************************************************************* + * + * Copyright (C) 2018-2020 Ruilin Peng (Nick) . + * + * smartdns is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * smartdns is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef _DNS_CONF +#define _DNS_CONF + +#include "art.h" +#include "conf.h" +#include "dns.h" +#include "dns_client.h" +#include "hash.h" +#include "hashtable.h" +#include "list.h" +#include "radix.h" + +#ifdef __cpluscplus +extern "C" { +#endif + +#define DNS_MAX_BIND_IP 16 +#define DNS_MAX_SERVERS 64 +#define DNS_MAX_SERVER_NAME_LEN 128 +#define DNS_MAX_IPSET_NAMELEN 32 +#define DNS_GROUP_NAME_LEN 32 +#define DNS_NAX_GROUP_NUMBER 16 +#define DNS_MAX_IPLEN 64 +#define DNS_MAX_SPKI_LEN 64 +#define DNS_MAX_URL_LEN 256 +#define DNS_MAX_PATH 1024 +#define DEFAULT_DNS_PORT 53 +#define DEFAULT_DNS_TLS_PORT 853 +#define DEFAULT_DNS_HTTPS_PORT 443 +#define DNS_MAX_CONF_CNAME_LEN 256 +#define SMARTDNS_CONF_FILE "/etc/smartdns/smartdns.conf" +#define SMARTDNS_LOG_FILE "/var/log/smartdns.log" +#define SMARTDNS_AUDIT_FILE "/var/log/smartdns-audit.log" + +enum domain_rule { + DOMAIN_RULE_FLAGS = 0, + DOMAIN_RULE_ADDRESS_IPV4, + DOMAIN_RULE_ADDRESS_IPV6, + DOMAIN_RULE_IPSET, + DOMAIN_RULE_NAMESERVER, + DOMAIN_RULE_CHECKSPEED, + DOMAIN_RULE_MAX, +}; + +typedef enum { + DNS_BIND_TYPE_UDP, + DNS_BIND_TYPE_TCP, + DNS_BIND_TYPE_TLS, +} DNS_BIND_TYPE; + +#define DOMAIN_CHECK_NONE 0 +#define DOMAIN_CHECK_ICMP 1 +#define DOMAIN_CHECK_TCP 2 +#define DOMAIN_CHECK_NUM 2 + +#define DOMAIN_FLAG_ADDR_SOA (1 << 0) +#define DOMAIN_FLAG_ADDR_IPV4_SOA (1 << 1) +#define DOMAIN_FLAG_ADDR_IPV6_SOA (1 << 2) +#define DOMAIN_FLAG_ADDR_IGN (1 << 3) +#define DOMAIN_FLAG_ADDR_IPV4_IGN (1 << 4) +#define DOMAIN_FLAG_ADDR_IPV6_IGN (1 << 5) +#define DOMAIN_FLAG_IPSET_IGNORE (1 << 6) +#define DOMAIN_FLAG_NAMESERVER_IGNORE (1 << 7) + +#define SERVER_FLAG_EXCLUDE_DEFAULT (1 << 0) + +#define BIND_FLAG_NO_RULE_ADDR (1 << 0) +#define BIND_FLAG_NO_RULE_NAMESERVER (1 << 1) +#define BIND_FLAG_NO_RULE_IPSET (1 << 2) +#define BIND_FLAG_NO_RULE_SNIPROXY (1 << 3) +#define BIND_FLAG_NO_RULE_SOA (1 << 4) +#define BIND_FLAG_NO_SPEED_CHECK (1 << 5) +#define BIND_FLAG_NO_CACHE (1 << 6) +#define BIND_FLAG_NO_DUALSTACK_SELECTION (1 << 7) +#define BIND_FLAG_FORCE_AAAA_SOA (1 << 8) + +struct dns_rule_flags { + unsigned int flags; +}; + +struct dns_address_IPV4 { + unsigned char ipv4_addr[DNS_RR_A_LEN]; +}; + +struct dns_address_IPV6 { + unsigned char ipv6_addr[DNS_RR_AAAA_LEN]; +}; + +struct dns_ipset_name { + struct hlist_node node; + char ipsetname[DNS_MAX_IPSET_NAMELEN]; +}; + +struct dns_ipset_rule { + const char *ipsetname; +}; + +struct dns_domain_rule { + void *rules[DOMAIN_RULE_MAX]; +}; + +struct dns_nameserver_rule { + const char *group_name; +}; + +struct dns_server_groups { + struct hlist_node node; + char group_name[DNS_GROUP_NAME_LEN]; + int server_num; + struct dns_servers *servers[DNS_MAX_SERVERS]; +}; + +struct dns_domain_check_order { + char order[DOMAIN_CHECK_NUM]; + unsigned short tcp_port; +}; + +struct dns_group_table { + DECLARE_HASHTABLE(group, 8); +}; +extern struct dns_group_table dns_group_table; + +struct dns_servers { + char server[DNS_MAX_IPLEN]; + unsigned short port; + unsigned int result_flag; + unsigned int server_flag; + int ttl; + dns_server_type_t type; + char skip_check_cert; + char spki[DNS_MAX_SPKI_LEN]; + char hostname[DNS_MAX_CNAME_LEN]; + char httphost[DNS_MAX_CNAME_LEN]; + char tls_host_verify[DNS_MAX_CNAME_LEN]; + char path[DNS_MAX_URL_LEN]; +}; + +/* ip address lists of domain */ +struct dns_bogus_ip_address { + struct hlist_node node; + dns_type_t addr_type; + union { + unsigned char ipv4_addr[DNS_RR_A_LEN]; + unsigned char ipv6_addr[DNS_RR_AAAA_LEN]; + unsigned char addr[0]; + }; +}; + +enum address_rule { + ADDRESS_RULE_BLACKLIST = 1, + ADDRESS_RULE_WHITELIST = 2, + ADDRESS_RULE_BOGUS = 3, + ADDRESS_RULE_IP_IGNORE = 4, +}; + +struct dns_ip_address_rule { + unsigned int blacklist : 1; + unsigned int whitelist : 1; + unsigned int bogus : 1; + unsigned int ip_ignore : 1; +}; + +struct dns_edns_client_subnet { + int enable; + char ip[DNS_MAX_IPLEN]; + int subnet; +}; + +struct dns_conf_address_rule { + radix_tree_t *ipv4; + radix_tree_t *ipv6; +}; + +struct dns_bind_ip { + DNS_BIND_TYPE type; + uint32_t flags; + char ip[DNS_MAX_IPLEN]; + const char *group; +}; + +extern struct dns_bind_ip dns_conf_bind_ip[DNS_MAX_BIND_IP]; +extern int dns_conf_bind_ip_num; + +extern int dns_conf_tcp_idle_time; +extern int dns_conf_cachesize; +extern int dns_conf_prefetch; +extern int dns_conf_serve_expired; +extern int dns_conf_serve_expired_ttl; +extern struct dns_servers dns_conf_servers[DNS_MAX_SERVERS]; +extern int dns_conf_server_num; + +extern int dns_conf_log_level; +extern char dns_conf_log_file[DNS_MAX_PATH]; +extern size_t dns_conf_log_size; +extern int dns_conf_log_num; + +extern char dns_conf_ca_file[DNS_MAX_PATH]; +extern char dns_conf_ca_path[DNS_MAX_PATH]; + +extern struct dns_domain_check_order dns_conf_check_order; + +extern struct dns_server_groups dns_conf_server_groups[DNS_NAX_GROUP_NUMBER]; +extern int dns_conf_server_group_num; + +extern int dns_conf_audit_enable; +extern int dns_conf_audit_log_SOA; +extern char dns_conf_audit_file[DNS_MAX_PATH]; +extern size_t dns_conf_audit_size; +extern int dns_conf_audit_num; + +extern char dns_conf_server_name[DNS_MAX_SERVER_NAME_LEN]; +extern art_tree dns_conf_domain_rule; +extern struct dns_conf_address_rule dns_conf_address_rule; + +extern int dns_conf_dualstack_ip_selection; +extern int dns_conf_dualstack_ip_selection_threshold; + +extern int dns_conf_rr_ttl; +extern int dns_conf_rr_ttl_min; +extern int dns_conf_rr_ttl_max; +extern int dns_conf_force_AAAA_SOA; +extern int dns_conf_ipset_timeout_enable; + +extern struct dns_edns_client_subnet dns_conf_ipv4_ecs; +extern struct dns_edns_client_subnet dns_conf_ipv6_ecs; + +extern char dns_conf_sni_proxy_ip[DNS_MAX_IPLEN]; + +void dns_server_load_exit(void); + +int dns_server_load_conf(const char *file); + +extern int config_addtional_file(void *data, int argc, char *argv[]); +#ifdef __cpluscplus +} +#endif +#endif // !_DNS_CONF diff --git a/release/src/router/smartdns/src/dns_server.c b/release/src/router/smartdns/src/dns_server.c index 8dba5cc1ce..04abb3366e 100644 --- a/release/src/router/smartdns/src/dns_server.c +++ b/release/src/router/smartdns/src/dns_server.c @@ -183,6 +183,7 @@ struct dns_request { int has_soa; atomic_t notified; + atomic_t do_callback; atomic_t adblock; atomic_t soa_num; @@ -205,6 +206,8 @@ static struct dns_server server; static tlog_log *dns_audit; +static int _dns_server_prefetch_request(char *domain, dns_type_t qtype); + static int _dns_server_forward_request(unsigned char *inpacket, int inpacket_len) { tlog(TLOG_DEBUG, "forward request.\n"); @@ -259,8 +262,10 @@ static int _dns_server_is_return_soa(struct dns_request *request) return 0; } - if (dns_conf_force_AAAA_SOA == 1 && request->qtype == DNS_T_AAAA) { - return 1; + if (request->qtype == DNS_T_AAAA) { + if (_dns_server_has_bind_flag(request, BIND_FLAG_FORCE_AAAA_SOA) == 0 || dns_conf_force_AAAA_SOA == 1) { + return 1; + } } rule_flag = request->domain_rule.rules[DOMAIN_RULE_FLAGS]; @@ -294,12 +299,15 @@ static void _dns_server_audit_log(struct dns_request *request) } if (request->qtype == DNS_T_AAAA && request->has_ipv6) { - snprintf(req_result, sizeof(req_result), "%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x", request->ipv6_addr[0], - request->ipv6_addr[1], request->ipv6_addr[2], request->ipv6_addr[3], request->ipv6_addr[4], request->ipv6_addr[5], request->ipv6_addr[6], - request->ipv6_addr[7], request->ipv6_addr[8], request->ipv6_addr[9], request->ipv6_addr[10], request->ipv6_addr[11], request->ipv6_addr[12], + snprintf(req_result, sizeof(req_result), + "%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x", request->ipv6_addr[0], + request->ipv6_addr[1], request->ipv6_addr[2], request->ipv6_addr[3], request->ipv6_addr[4], + request->ipv6_addr[5], request->ipv6_addr[6], request->ipv6_addr[7], request->ipv6_addr[8], + request->ipv6_addr[9], request->ipv6_addr[10], request->ipv6_addr[11], request->ipv6_addr[12], request->ipv6_addr[13], request->ipv6_addr[14], request->ipv6_addr[15]); } else if (request->qtype == DNS_T_A && request->has_ipv4) { - snprintf(req_result, sizeof(req_result), "%d.%d.%d.%d", request->ipv4_addr[0], request->ipv4_addr[1], request->ipv4_addr[2], request->ipv4_addr[3]); + snprintf(req_result, sizeof(req_result), "%d.%d.%d.%d", request->ipv4_addr[0], request->ipv4_addr[1], + request->ipv4_addr[2], request->ipv4_addr[3]); } else if (request->has_soa) { if (!dns_conf_audit_log_SOA) { return; @@ -312,9 +320,11 @@ static void _dns_server_audit_log(struct dns_request *request) gethost_by_addr(req_host, sizeof(req_host), &request->addr); tlog_localtime(&tm); - snprintf(req_time, sizeof(req_time), "[%.4d-%.2d-%.2d %.2d:%.2d:%.2d,%.3d]", tm.year, tm.mon, tm.mday, tm.hour, tm.min, tm.sec, tm.usec / 1000); + snprintf(req_time, sizeof(req_time), "[%.4d-%.2d-%.2d %.2d:%.2d:%.2d,%.3d]", tm.year, tm.mon, tm.mday, tm.hour, + tm.min, tm.sec, tm.usec / 1000); - tlog_printf(dns_audit, "%s %s query %s, type %d, result %s\n", req_time, req_host, request->domain, request->qtype, req_result); + tlog_printf(dns_audit, "%s %s query %s, type %d, result %s\n", req_time, req_host, request->domain, request->qtype, + req_result); } static int _dns_add_rrs(struct dns_packet *packet, struct dns_request *request) @@ -432,7 +442,8 @@ static int _dns_server_reply_tcp_to_buffer(struct dns_server_conn_tcp_client *tc return 0; } -static int _dns_server_reply_tcp(struct dns_request *request, struct dns_server_conn_tcp_client *tcpclient, void *packet, unsigned short len) +static int _dns_server_reply_tcp(struct dns_request *request, struct dns_server_conn_tcp_client *tcpclient, + void *packet, unsigned short len) { int send_len = 0; unsigned char inpacket_data[DNS_IN_PACKSIZE]; @@ -460,10 +471,12 @@ static int _dns_server_reply_tcp(struct dns_request *request, struct dns_server_ return 0; } -static int _dns_server_reply_udp(struct dns_request *request, struct dns_server_conn_udp *udpserver, unsigned char *inpacket, int inpacket_len) +static int _dns_server_reply_udp(struct dns_request *request, struct dns_server_conn_udp *udpserver, + unsigned char *inpacket, int inpacket_len) { int send_len = 0; - send_len = sendto(udpserver->head.fd, inpacket, inpacket_len, 0, (struct sockaddr *)&request->addr, request->addr_len); + send_len = + sendto(udpserver->head.fd, inpacket, inpacket_len, 0, (struct sockaddr *)&request->addr, request->addr_len); if (send_len != inpacket_len) { tlog(TLOG_ERROR, "send failed."); return -1; @@ -548,6 +561,19 @@ static int _dns_reply(struct dns_request *request) return _dns_reply_inpacket(request, inpacket, encode_len); } +static int _dns_result_callback_nxdomain(struct dns_request *request) +{ + char ip[DNS_MAX_CNAME_LEN]; + unsigned int ping_time = -1; + + ip[0] = 0; + if (request->result_callback == NULL) { + return 0; + } + + return request->result_callback(request->domain, DNS_RC_NXDOMAIN, request->qtype, ip, ping_time, request->user_ptr); +} + static int _dns_result_callback(struct dns_request *request) { char ip[DNS_MAX_CNAME_LEN]; @@ -557,34 +583,42 @@ static int _dns_result_callback(struct dns_request *request) return 0; } + if (atomic_inc_return(&request->do_callback) != 1) { + return 0; + } + ip[0] = 0; if (request->qtype == DNS_T_A) { if (request->has_ipv4 == 0) { goto out; } - sprintf(ip, "%d.%d.%d.%d", request->ipv4_addr[0], request->ipv4_addr[1], request->ipv4_addr[2], request->ipv4_addr[3]); + sprintf(ip, "%d.%d.%d.%d", request->ipv4_addr[0], request->ipv4_addr[1], request->ipv4_addr[2], + request->ipv4_addr[3]); ping_time = request->ping_ttl_v4; - return request->result_callback(request->domain, request->rcode, request->qtype, ip, ping_time, request->user_ptr); + return request->result_callback(request->domain, request->rcode, request->qtype, ip, ping_time, + request->user_ptr); } else if (request->qtype == DNS_T_AAAA) { if (request->has_ipv6 == 0) { goto out; } - sprintf(ip, "%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x", request->ipv6_addr[0], request->ipv6_addr[1], - request->ipv6_addr[2], request->ipv6_addr[3], request->ipv6_addr[4], request->ipv6_addr[5], request->ipv6_addr[6], request->ipv6_addr[7], - request->ipv6_addr[8], request->ipv6_addr[9], request->ipv6_addr[10], request->ipv6_addr[11], request->ipv6_addr[12], request->ipv6_addr[13], - request->ipv6_addr[14], request->ipv6_addr[15]); + sprintf(ip, "%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x", request->ipv6_addr[0], + request->ipv6_addr[1], request->ipv6_addr[2], request->ipv6_addr[3], request->ipv6_addr[4], + request->ipv6_addr[5], request->ipv6_addr[6], request->ipv6_addr[7], request->ipv6_addr[8], + request->ipv6_addr[9], request->ipv6_addr[10], request->ipv6_addr[11], request->ipv6_addr[12], + request->ipv6_addr[13], request->ipv6_addr[14], request->ipv6_addr[15]); ping_time = request->ping_ttl_v6; - return request->result_callback(request->domain, request->rcode, request->qtype, ip, ping_time, request->user_ptr); + return request->result_callback(request->domain, request->rcode, request->qtype, ip, ping_time, + request->user_ptr); } - request->result_callback(request->domain, DNS_RC_NXDOMAIN, request->qtype, ip, ping_time, request->user_ptr); + _dns_result_callback_nxdomain(request); return 0; out: - request->result_callback(request->domain, DNS_RC_NXDOMAIN, request->qtype, ip, ping_time, request->user_ptr); + _dns_result_callback_nxdomain(request); return 0; } @@ -672,8 +706,8 @@ static int _dns_server_request_complete_A(struct dns_request *request) return 0; } - tlog(TLOG_INFO, "result: %s, rcode: %d, %d.%d.%d.%d\n", request->domain, request->rcode, request->ipv4_addr[0], request->ipv4_addr[1], - request->ipv4_addr[2], request->ipv4_addr[3]); + tlog(TLOG_INFO, "result: %s, rcode: %d, %d.%d.%d.%d\n", request->domain, request->rcode, request->ipv4_addr[0], + request->ipv4_addr[1], request->ipv4_addr[2], request->ipv4_addr[3]); request->has_soa = 0; if (request->has_ping_result == 0 && request->ttl_v4 > DNS_SERVER_TMOUT_TTL) { @@ -686,10 +720,12 @@ static int _dns_server_request_complete_A(struct dns_request *request) /* if doing prefetch, update cache only */ if (request->prefetch) { - dns_cache_replace(request->domain, cname, cname_ttl, request->ttl_v4, DNS_T_A, request->ipv4_addr, DNS_RR_A_LEN, request->ping_ttl_v4); + dns_cache_replace(request->domain, cname, cname_ttl, request->ttl_v4, DNS_T_A, request->ipv4_addr, DNS_RR_A_LEN, + request->ping_ttl_v4); } else { /* insert result to cache */ - dns_cache_insert(request->domain, cname, cname_ttl, request->ttl_v4, DNS_T_A, request->ipv4_addr, DNS_RR_A_LEN, request->ping_ttl_v4); + dns_cache_insert(request->domain, cname, cname_ttl, request->ttl_v4, DNS_T_A, request->ipv4_addr, DNS_RR_A_LEN, + request->ping_ttl_v4); } return 0; @@ -706,10 +742,13 @@ static int _dns_server_request_complete_AAAA(struct dns_request *request) } if (request->has_ipv6) { - tlog(TLOG_INFO, "result: %s, rcode: %d, %.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x", request->domain, request->rcode, - request->ipv6_addr[0], request->ipv6_addr[1], request->ipv6_addr[2], request->ipv6_addr[3], request->ipv6_addr[4], request->ipv6_addr[5], - request->ipv6_addr[6], request->ipv6_addr[7], request->ipv6_addr[8], request->ipv6_addr[9], request->ipv6_addr[10], request->ipv6_addr[11], - request->ipv6_addr[12], request->ipv6_addr[13], request->ipv6_addr[14], request->ipv6_addr[15]); + tlog(TLOG_INFO, + "result: %s, rcode: %d, %.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x", + request->domain, request->rcode, request->ipv6_addr[0], request->ipv6_addr[1], request->ipv6_addr[2], + request->ipv6_addr[3], request->ipv6_addr[4], request->ipv6_addr[5], request->ipv6_addr[6], + request->ipv6_addr[7], request->ipv6_addr[8], request->ipv6_addr[9], request->ipv6_addr[10], + request->ipv6_addr[11], request->ipv6_addr[12], request->ipv6_addr[13], request->ipv6_addr[14], + request->ipv6_addr[15]); if (request->has_ping_result == 0 && request->ttl_v6 > DNS_SERVER_TMOUT_TTL) { request->ttl_v6 = DNS_SERVER_TMOUT_TTL; @@ -718,10 +757,12 @@ static int _dns_server_request_complete_AAAA(struct dns_request *request) /* if doing prefetch, update cache only */ if (_dns_server_has_bind_flag(request, BIND_FLAG_NO_CACHE) != 0) { if (request->prefetch) { - dns_cache_replace(request->domain, cname, cname_ttl, request->ttl_v6, DNS_T_AAAA, request->ipv6_addr, DNS_RR_AAAA_LEN, request->ping_ttl_v6); + dns_cache_replace(request->domain, cname, cname_ttl, request->ttl_v6, DNS_T_AAAA, request->ipv6_addr, + DNS_RR_AAAA_LEN, request->ping_ttl_v6); } else { /* insert result to cache */ - dns_cache_insert(request->domain, cname, cname_ttl, request->ttl_v6, DNS_T_AAAA, request->ipv6_addr, DNS_RR_AAAA_LEN, request->ping_ttl_v6); + dns_cache_insert(request->domain, cname, cname_ttl, request->ttl_v6, DNS_T_AAAA, request->ipv6_addr, + DNS_RR_AAAA_LEN, request->ping_ttl_v6); } } @@ -729,17 +770,20 @@ static int _dns_server_request_complete_AAAA(struct dns_request *request) } if (request->has_ipv4 && (request->ping_ttl_v4 > 0)) { - tlog(TLOG_INFO, "result: %s, rcode: %d, %d.%d.%d.%d\n", request->domain, request->rcode, request->ipv4_addr[0], request->ipv4_addr[1], - request->ipv4_addr[2], request->ipv4_addr[3]); + tlog(TLOG_INFO, "result: %s, rcode: %d, %d.%d.%d.%d\n", request->domain, request->rcode, request->ipv4_addr[0], + request->ipv4_addr[1], request->ipv4_addr[2], request->ipv4_addr[3]); /* if ipv4 is fasting than ipv6, add ipv4 to cache, and return SOA for AAAA request */ - if ((request->ping_ttl_v4 + (dns_conf_dualstack_ip_selection_threshold * 10)) < request->ping_ttl_v6 || request->ping_ttl_v6 < 0) { + if ((request->ping_ttl_v4 + (dns_conf_dualstack_ip_selection_threshold * 10)) < request->ping_ttl_v6 || + request->ping_ttl_v6 < 0) { tlog(TLOG_DEBUG, "Force IPV4 perfered."); if (_dns_server_has_bind_flag(request, BIND_FLAG_NO_CACHE) != 0) { if (request->prefetch) { - dns_cache_replace(request->domain, cname, cname_ttl, request->ttl_v4, DNS_T_A, request->ipv4_addr, DNS_RR_A_LEN, request->ping_ttl_v4); + dns_cache_replace(request->domain, cname, cname_ttl, request->ttl_v4, DNS_T_A, request->ipv4_addr, + DNS_RR_A_LEN, request->ping_ttl_v4); } else { - dns_cache_insert(request->domain, cname, cname_ttl, request->ttl_v4, DNS_T_A, request->ipv4_addr, DNS_RR_A_LEN, request->ping_ttl_v4); + dns_cache_insert(request->domain, cname, cname_ttl, request->ttl_v4, DNS_T_A, request->ipv4_addr, + DNS_RR_A_LEN, request->ping_ttl_v4); } } @@ -868,16 +912,19 @@ static void _dns_server_select_possible_ipaddress(struct dns_request *request) case DNS_T_A: { memcpy(request->ipv4_addr, selected_addr_map->ipv4_addr, DNS_RR_A_LEN); request->ttl_v4 = DNS_SERVER_TMOUT_TTL; - tlog(TLOG_DEBUG, "possible result: %s, rcode: %d, %d.%d.%d.%d\n", request->domain, request->rcode, request->ipv4_addr[0], request->ipv4_addr[1], - request->ipv4_addr[2], request->ipv4_addr[3]); + tlog(TLOG_DEBUG, "possible result: %s, rcode: %d, %d.%d.%d.%d\n", request->domain, request->rcode, + request->ipv4_addr[0], request->ipv4_addr[1], request->ipv4_addr[2], request->ipv4_addr[3]); } break; case DNS_T_AAAA: { memcpy(request->ipv6_addr, selected_addr_map->ipv6_addr, DNS_RR_AAAA_LEN); request->ttl_v6 = DNS_SERVER_TMOUT_TTL; - tlog(TLOG_DEBUG, "possible result: %s, rcode: %d, %.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x", request->domain, - request->rcode, request->ipv6_addr[0], request->ipv6_addr[1], request->ipv6_addr[2], request->ipv6_addr[3], request->ipv6_addr[4], - request->ipv6_addr[5], request->ipv6_addr[6], request->ipv6_addr[7], request->ipv6_addr[8], request->ipv6_addr[9], request->ipv6_addr[10], - request->ipv6_addr[11], request->ipv6_addr[12], request->ipv6_addr[13], request->ipv6_addr[14], request->ipv6_addr[15]); + tlog(TLOG_DEBUG, + "possible result: %s, rcode: %d, %.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x", + request->domain, request->rcode, request->ipv6_addr[0], request->ipv6_addr[1], request->ipv6_addr[2], + request->ipv6_addr[3], request->ipv6_addr[4], request->ipv6_addr[5], request->ipv6_addr[6], + request->ipv6_addr[7], request->ipv6_addr[8], request->ipv6_addr[9], request->ipv6_addr[10], + request->ipv6_addr[11], request->ipv6_addr[12], request->ipv6_addr[13], request->ipv6_addr[14], + request->ipv6_addr[15]); } break; default: break; @@ -956,6 +1003,8 @@ static struct dns_request *_dns_server_new_request(void) atomic_set(&request->adblock, 0); atomic_set(&request->soa_num, 0); atomic_set(&request->refcnt, 0); + atomic_set(&request->notified, 0); + atomic_set(&request->do_callback, 0); request->ping_ttl_v4 = -1; request->ping_ttl_v6 = -1; request->prefetch = 0; @@ -973,8 +1022,9 @@ static struct dns_request *_dns_server_new_request(void) return NULL; } -static void _dns_server_ping_result(struct ping_host_struct *ping_host, const char *host, FAST_PING_RESULT result, struct sockaddr *addr, socklen_t addr_len, - int seqno, int ttl, struct timeval *tv, void *userptr) +static void _dns_server_ping_result(struct ping_host_struct *ping_host, const char *host, FAST_PING_RESULT result, + struct sockaddr *addr, socklen_t addr_len, int seqno, int ttl, struct timeval *tv, + void *userptr) { struct dns_request *request = userptr; int may_complete = 0; @@ -1156,7 +1206,8 @@ static int _dns_server_get_conf_ttl(int ttl) return ttl; } -static int _dns_server_ip_rule_check(struct dns_request *request, unsigned char *addr, int addr_len, dns_type_t addr_type, int result_flag) +static int _dns_server_ip_rule_check(struct dns_request *request, unsigned char *addr, int addr_len, + dns_type_t addr_type, int result_flag) { prefix_t prefix; radix_node_t *node = NULL; @@ -1241,7 +1292,8 @@ static int _dns_server_is_adblock_ipv6(unsigned char addr[16]) return -1; } -static int _dns_server_process_answer_A(struct dns_rrs *rrs, struct dns_request *request, char *domain, unsigned int result_flag, int ping_timeout) +static int _dns_server_process_answer_A(struct dns_rrs *rrs, struct dns_request *request, char *domain, + unsigned int result_flag, int ping_timeout) { int ttl; int ip_check_result = 0; @@ -1314,7 +1366,8 @@ static int _dns_server_process_answer_A(struct dns_rrs *rrs, struct dns_request return 0; } -static int _dns_server_process_answer_AAAA(struct dns_rrs *rrs, struct dns_request *request, char *domain, unsigned int result_flag, int ping_timeout) +static int _dns_server_process_answer_AAAA(struct dns_rrs *rrs, struct dns_request *request, char *domain, + unsigned int result_flag, int ping_timeout) { unsigned char addr[16]; char name[DNS_MAX_CNAME_LEN] = {0}; @@ -1329,8 +1382,9 @@ static int _dns_server_process_answer_AAAA(struct dns_rrs *rrs, struct dns_reque _dns_server_request_get(request); dns_get_AAAA(rrs, name, DNS_MAX_CNAME_LEN, &ttl, addr); - tlog(TLOG_DEBUG, "domain: %s TTL: %d IP: %.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x", name, ttl, addr[0], addr[1], addr[2], - addr[3], addr[4], addr[5], addr[6], addr[7], addr[8], addr[9], addr[10], addr[11], addr[12], addr[13], addr[14], addr[15]); + tlog(TLOG_DEBUG, "domain: %s TTL: %d IP: %.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x", + name, ttl, addr[0], addr[1], addr[2], addr[3], addr[4], addr[5], addr[6], addr[7], addr[8], addr[9], addr[10], + addr[11], addr[12], addr[13], addr[14], addr[15]); ip_check_result = _dns_server_ip_rule_check(request, addr, 16, DNS_T_AAAA, result_flag); if (ip_check_result == 0) { @@ -1374,8 +1428,9 @@ static int _dns_server_process_answer_AAAA(struct dns_rrs *rrs, struct dns_reque return -1; } - sprintf(ip, "[%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x]", addr[0], addr[1], addr[2], addr[3], addr[4], addr[5], addr[6], - addr[7], addr[8], addr[9], addr[10], addr[11], addr[12], addr[13], addr[14], addr[15]); + sprintf(ip, "[%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x]", addr[0], addr[1], addr[2], + addr[3], addr[4], addr[5], addr[6], addr[7], addr[8], addr[9], addr[10], addr[11], addr[12], addr[13], + addr[14], addr[15]); /* start ping */ if (_dns_server_check_speed(request, ip, 0, ping_timeout) != 0) { @@ -1385,7 +1440,8 @@ static int _dns_server_process_answer_AAAA(struct dns_rrs *rrs, struct dns_reque return 0; } -static int _dns_server_process_answer(struct dns_request *request, char *domain, struct dns_packet *packet, unsigned int result_flag) +static int _dns_server_process_answer(struct dns_request *request, char *domain, struct dns_packet *packet, + unsigned int result_flag) { int ttl; char name[DNS_MAX_CNAME_LEN] = {0}; @@ -1452,9 +1508,11 @@ static int _dns_server_process_answer(struct dns_request *request, char *domain, request->has_soa = 1; request->rcode = packet->head.rcode; dns_get_SOA(rrs, name, 128, &ttl, &request->soa); - tlog(TLOG_DEBUG, "domain: %s, qtype: %d, SOA: mname: %s, rname: %s, serial: %d, refresh: %d, retry: %d, expire: %d, minimum: %d", domain, - request->qtype, request->soa.mname, request->soa.rname, request->soa.serial, request->soa.refresh, request->soa.retry, request->soa.expire, - request->soa.minimum); + tlog(TLOG_DEBUG, + "domain: %s, qtype: %d, SOA: mname: %s, rname: %s, serial: %d, refresh: %d, retry: %d, expire: " + "%d, minimum: %d", + domain, request->qtype, request->soa.mname, request->soa.rname, request->soa.serial, + request->soa.refresh, request->soa.retry, request->soa.expire, request->soa.minimum); if (atomic_inc_return(&request->soa_num) >= (dns_server_num() / 2)) { _dns_server_request_complete(request); } @@ -1483,7 +1541,8 @@ static int dns_server_update_reply_packet_id(struct dns_request *request, unsign return 0; } -static int _dns_server_passthrough_rule_check(struct dns_request *request, char *domain, struct dns_packet *packet, unsigned int result_flag) +static int _dns_server_passthrough_rule_check(struct dns_request *request, char *domain, struct dns_packet *packet, + unsigned int result_flag) { int ttl; char name[DNS_MAX_CNAME_LEN] = {0}; @@ -1542,8 +1601,10 @@ static int _dns_server_passthrough_rule_check(struct dns_request *request, char _dns_server_request_get(request); dns_get_AAAA(rrs, name, DNS_MAX_CNAME_LEN, &ttl, addr); - tlog(TLOG_DEBUG, "domain: %s TTL: %d IP: %.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x", name, ttl, addr[0], addr[1], - addr[2], addr[3], addr[4], addr[5], addr[6], addr[7], addr[8], addr[9], addr[10], addr[11], addr[12], addr[13], addr[14], addr[15]); + tlog(TLOG_DEBUG, + "domain: %s TTL: %d IP: %.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x", + name, ttl, addr[0], addr[1], addr[2], addr[3], addr[4], addr[5], addr[6], addr[7], addr[8], + addr[9], addr[10], addr[11], addr[12], addr[13], addr[14], addr[15]); ip_check_result = _dns_server_ip_rule_check(request, addr, 16, DNS_T_AAAA, result_flag); if (ip_check_result == 0) { @@ -1566,7 +1627,8 @@ static int _dns_server_passthrough_rule_check(struct dns_request *request, char return -1; } -static int _dns_server_reply_passthrouth(struct dns_request *request, struct dns_packet *packet, unsigned char *inpacket, int inpacket_len) +static int _dns_server_reply_passthrouth(struct dns_request *request, struct dns_packet *packet, + unsigned char *inpacket, int inpacket_len) { int ret = 0; @@ -1574,6 +1636,10 @@ static int _dns_server_reply_passthrouth(struct dns_request *request, struct dns return 0; } + if (request->conn == NULL) { + return 0; + } + /* When passthrough, modify the id to be the id of the client request. */ dns_server_update_reply_packet_id(request, inpacket, inpacket_len); ret = _dns_reply_inpacket(request, inpacket, inpacket_len); @@ -1581,8 +1647,9 @@ static int _dns_server_reply_passthrouth(struct dns_request *request, struct dns return ret; } -static int dns_server_resolve_callback(char *domain, dns_result_type rtype, unsigned int result_flag, struct dns_packet *packet, unsigned char *inpacket, - int inpacket_len, void *user_ptr) +static int dns_server_resolve_callback(char *domain, dns_result_type rtype, unsigned int result_flag, + struct dns_packet *packet, unsigned char *inpacket, int inpacket_len, + void *user_ptr) { struct dns_request *request = user_ptr; int ip_num = 0; @@ -1617,6 +1684,7 @@ static int dns_server_resolve_callback(char *domain, dns_result_type rtype, unsi /* Not need to wait check result if only has one ip address */ if (ip_num == 1 && request_wait == 1) { + request->has_ping_result = 1; _dns_server_request_complete(request); _dns_server_request_remove(request); } @@ -1653,23 +1721,28 @@ static int _dns_server_process_ptr(struct dns_request *request) struct sockaddr_in *addr_in; addr_in = (struct sockaddr_in *)ifa->ifa_addr; addr = (unsigned char *)&(addr_in->sin_addr.s_addr); - snprintf(reverse_addr, sizeof(reverse_addr), "%d.%d.%d.%d.in-addr.arpa", addr[3], addr[2], addr[1], addr[0]); + snprintf(reverse_addr, sizeof(reverse_addr), "%d.%d.%d.%d.in-addr.arpa", addr[3], addr[2], addr[1], + addr[0]); } break; case AF_INET6: { struct sockaddr_in6 *addr_in6; addr_in6 = (struct sockaddr_in6 *)ifa->ifa_addr; if (IN6_IS_ADDR_V4MAPPED(&addr_in6->sin6_addr)) { addr = addr_in6->sin6_addr.s6_addr + 12; - snprintf(reverse_addr, sizeof(reverse_addr), "%d.%d.%d.%d.in-addr.arpa", addr[3], addr[2], addr[1], addr[0]); + snprintf(reverse_addr, sizeof(reverse_addr), "%d.%d.%d.%d.in-addr.arpa", addr[3], addr[2], addr[1], + addr[0]); } else { addr = addr_in6->sin6_addr.s6_addr; snprintf(reverse_addr, sizeof(reverse_addr), - "%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.ip6.arpa", addr[15] & 0xF, - (addr[15] >> 4) & 0xF, addr[14] & 0xF, (addr[14] >> 4) & 0xF, addr[13] & 0xF, (addr[13] >> 4) & 0xF, addr[12] & 0xF, - (addr[12] >> 4) & 0xF, addr[11] & 0xF, (addr[11] >> 4) & 0xF, addr[10] & 0xF, (addr[10] >> 4) & 0xF, addr[9] & 0xF, - (addr[9] >> 4) & 0xF, addr[8] & 0xF, (addr[8] >> 4) & 0xF, addr[7] & 0xF, (addr[7] >> 4) & 0xF, addr[6] & 0xF, (addr[6] >> 4) & 0xF, - addr[5] & 0xF, (addr[5] >> 4) & 0xF, addr[4] & 0xF, (addr[4] >> 4) & 0xF, addr[3] & 0xF, (addr[3] >> 4) & 0xF, addr[2] & 0xF, - (addr[2] >> 4) & 0xF, addr[1] & 0xF, (addr[1] >> 4) & 0xF, addr[0] & 0xF, (addr[0] >> 4) & 0xF); + "%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x." + "%x.ip6.arpa", + addr[15] & 0xF, (addr[15] >> 4) & 0xF, addr[14] & 0xF, (addr[14] >> 4) & 0xF, addr[13] & 0xF, + (addr[13] >> 4) & 0xF, addr[12] & 0xF, (addr[12] >> 4) & 0xF, addr[11] & 0xF, + (addr[11] >> 4) & 0xF, addr[10] & 0xF, (addr[10] >> 4) & 0xF, addr[9] & 0xF, + (addr[9] >> 4) & 0xF, addr[8] & 0xF, (addr[8] >> 4) & 0xF, addr[7] & 0xF, (addr[7] >> 4) & 0xF, + addr[6] & 0xF, (addr[6] >> 4) & 0xF, addr[5] & 0xF, (addr[5] >> 4) & 0xF, addr[4] & 0xF, + (addr[4] >> 4) & 0xF, addr[3] & 0xF, (addr[3] >> 4) & 0xF, addr[2] & 0xF, (addr[2] >> 4) & 0xF, + addr[1] & 0xF, (addr[1] >> 4) & 0xF, addr[0] & 0xF, (addr[0] >> 4) & 0xF); } } break; default: @@ -1688,6 +1761,11 @@ static int _dns_server_process_ptr(struct dns_request *request) found = 1; } + /* Determine if the smartdns service is in effect. */ + if (found == 0 && strncmp(request->domain, "smartdns", sizeof("smartdns")) == 0) { + found = 1; + } + if (found == 0) { goto errout; } @@ -1705,7 +1783,8 @@ static int _dns_server_process_ptr(struct dns_request *request) return -1; } -static void _dns_server_log_rule(const char *domain, enum domain_rule rule_type, unsigned char *rule_key, int rule_key_len) +static void _dns_server_log_rule(const char *domain, enum domain_rule rule_type, unsigned char *rule_key, + int rule_key_len) { char rule_name[DNS_MAX_CNAME_LEN]; @@ -1720,8 +1799,7 @@ static void _dns_server_log_rule(const char *domain, enum domain_rule rule_type, static void _dns_server_update_rule_by_flags(struct dns_request *request) { - struct dns_rule_flags *rule_flag = - (struct dns_rule_flags *)request->domain_rule.rules[0]; + struct dns_rule_flags *rule_flag = (struct dns_rule_flags *)request->domain_rule.rules[0]; unsigned int flags = 0; if (rule_flag == NULL) { @@ -1797,7 +1875,8 @@ void _dns_server_get_domain_rule(struct dns_request *request) domain_key[domain_len] = 0; /* find domain rule */ - art_substring_walk(&dns_conf_domain_rule, (unsigned char *)domain_key, domain_len, _dns_server_get_rules, &walk_args); + art_substring_walk(&dns_conf_domain_rule, (unsigned char *)domain_key, domain_len, _dns_server_get_rules, + &walk_args); if (likely(dns_conf_log_level > TLOG_DEBUG)) { return; } @@ -1930,6 +2009,19 @@ static int _dns_server_process_address(struct dns_request *request) return -1; } +static void _dns_server_prolcess_speed_check_rule(struct dns_request *request) +{ + struct dns_domain_check_order *check_order = NULL; + + /* get domain rule flag */ + check_order = request->domain_rule.rules[DOMAIN_RULE_CHECKSPEED]; + if (check_order == NULL) { + return; + } + + request->check_order_list = check_order; +} + static int _dns_server_process_cache(struct dns_request *request) { struct dns_cache *dns_cache = NULL; @@ -1941,6 +2033,15 @@ static int _dns_server_process_cache(struct dns_request *request) dns_cache = dns_cache_lookup(request->domain, request->qtype); if (dns_cache == NULL) { + if (request->dualstack_selection && request->qtype == DNS_T_AAAA) { + dns_cache_A = dns_cache_lookup(request->domain, DNS_T_A); + if (dns_cache_A) { + tlog(TLOG_DEBUG, "No IPV6 Found, Force IPV4 perfered."); + dns_cache_release(dns_cache_A); + dns_cache_release(dns_cache); + return _dns_server_reply_SOA(DNS_RC_NOERROR, request); + } + } goto errout; } @@ -1951,7 +2052,8 @@ static int _dns_server_process_cache(struct dns_request *request) if (request->dualstack_selection && request->qtype == DNS_T_AAAA) { dns_cache_A = dns_cache_lookup(request->domain, DNS_T_A); if (dns_cache_A && (dns_cache_A->speed > 0)) { - if ((dns_cache_A->speed + (dns_conf_dualstack_ip_selection_threshold * 10)) < dns_cache->speed || dns_cache->speed < 0) { + if ((dns_cache_A->speed + (dns_conf_dualstack_ip_selection_threshold * 10)) < dns_cache->speed || + dns_cache->speed < 0) { tlog(TLOG_DEBUG, "Force IPV4 perfered."); dns_cache_release(dns_cache_A); dns_cache_release(dns_cache); @@ -1991,7 +2093,11 @@ static int _dns_server_process_cache(struct dns_request *request) _dns_reply(request); } - dns_cache_update(dns_cache); + if (dns_cache_get_ttl(dns_cache) == 0) { + _dns_server_prefetch_request(request->domain, request->qtype); + } else { + dns_cache_update(dns_cache); + } dns_cache_release(dns_cache); if (dns_cache_A) { @@ -2027,7 +2133,8 @@ static void _dns_server_request_set_enable_prefetch(struct dns_request *request) request->prefetch = 1; } -static int _dns_server_request_set_client_addr(struct dns_request *request, struct sockaddr_storage *from, socklen_t from_len) +static int _dns_server_request_set_client_addr(struct dns_request *request, struct sockaddr_storage *from, + socklen_t from_len) { switch (from->ss_family) { case AF_INET: @@ -2104,6 +2211,17 @@ static const char *_dns_server_get_request_groupname(struct dns_request *request return NULL; } +static void _dns_server_check_set_passthrough(struct dns_request *request) +{ + if (request->check_order_list->order[0] == DOMAIN_CHECK_NONE) { + request->passthrough = 1; + } + + if (_dns_server_has_bind_flag(request, BIND_FLAG_NO_SPEED_CHECK) == 0) { + request->passthrough = 1; + } +} + static int _dns_server_do_query(struct dns_request *request, const char *domain, int qtype) { int ret = -1; @@ -2138,6 +2256,12 @@ static int _dns_server_do_query(struct dns_request *request, const char *domain, goto clean_exit; } + /* process speed check rule */ + _dns_server_prolcess_speed_check_rule(request); + + /* check and set passthrough */ + _dns_server_check_set_passthrough(request); + /* process cache */ if (request->prefetch == 0) { if (_dns_server_process_cache(request) == 0) { @@ -2181,19 +2305,9 @@ static int _dns_server_do_query(struct dns_request *request, const char *domain, return ret; } -static void _dns_server_check_set_passthrough(struct dns_request *request, struct dns_server_conn_head *conn) -{ - if (request->check_order_list->order[0] == DOMAIN_CHECK_NONE) { - request->passthrough = 1; - } - - if (_dns_server_has_bind_flag(request, BIND_FLAG_NO_SPEED_CHECK) == 0) { - request->passthrough = 1; - } -} - -static int _dns_server_recv(struct dns_server_conn_head *conn, unsigned char *inpacket, int inpacket_len, struct sockaddr_storage *local, socklen_t local_len, - struct sockaddr_storage *from, socklen_t from_len) +static int _dns_server_recv(struct dns_server_conn_head *conn, unsigned char *inpacket, int inpacket_len, + struct sockaddr_storage *local, socklen_t local_len, struct sockaddr_storage *from, + socklen_t from_len) { int decode_len; int ret = -1; @@ -2209,16 +2323,19 @@ static int _dns_server_recv(struct dns_server_conn_head *conn, unsigned char *in int qtype = DNS_T_ALL; /* decode packet */ - tlog(TLOG_DEBUG, "recv query packet from %s, len = %d", gethost_by_addr(name, sizeof(name), (struct sockaddr *)from), inpacket_len); + tlog(TLOG_DEBUG, "recv query packet from %s, len = %d", + gethost_by_addr(name, sizeof(name), (struct sockaddr *)from), inpacket_len); decode_len = dns_decode(packet, DNS_PACKSIZE, inpacket, inpacket_len); if (decode_len < 0) { tlog(TLOG_DEBUG, "decode failed.\n"); goto errout; } - tlog(TLOG_DEBUG, "request qdcount = %d, ancount = %d, nscount = %d, nrcount = %d, len = %d, id = %d, tc = %d, rd = %d, ra = %d, rcode = %d\n", - packet->head.qdcount, packet->head.ancount, packet->head.nscount, packet->head.nrcount, inpacket_len, packet->head.id, packet->head.tc, - packet->head.rd, packet->head.ra, packet->head.rcode); + tlog(TLOG_DEBUG, + "request qdcount = %d, ancount = %d, nscount = %d, nrcount = %d, len = %d, id = %d, tc = %d, rd = %d, ra = " + "%d, rcode = %d\n", + packet->head.qdcount, packet->head.ancount, packet->head.nscount, packet->head.nrcount, inpacket_len, + packet->head.id, packet->head.tc, packet->head.rd, packet->head.ra, packet->head.rcode); if (packet->head.qr != DNS_QR_QUERY) { goto errout; @@ -2249,7 +2366,6 @@ static int _dns_server_recv(struct dns_server_conn_head *conn, unsigned char *in memcpy(&request->localaddr, local, local_len); _dns_server_request_set_client(request, conn); - _dns_server_check_set_passthrough(request, conn); _dns_server_request_set_client_addr(request, from, from_len); _dns_server_request_set_id(request, packet->head.id); _dns_server_set_dualstack_selection(request); @@ -2315,7 +2431,7 @@ int dns_server_query(char *domain, int qtype, dns_result_callback callback, void goto errout; } - _dns_server_request_release_complete(request, 0); + _dns_server_request_release_complete(request, 1); return ret; errout: if (request) { @@ -2390,7 +2506,8 @@ static int _dns_server_client_close(struct dns_server_conn_head *conn) return 0; } -static int _dns_server_tcp_accept(struct dns_server_conn_tcp_server *tcpserver, struct epoll_event *event, unsigned long now) +static int _dns_server_tcp_accept(struct dns_server_conn_tcp_server *tcpserver, struct epoll_event *event, + unsigned long now) { struct sockaddr_storage addr; struct dns_server_conn_tcp_client *tcpclient = NULL; @@ -2454,7 +2571,8 @@ static int _dns_server_tcp_recv(struct dns_server_conn_tcp_client *tcpclient) return 0; } - len = recv(tcpclient->head.fd, tcpclient->recvbuff.buf + tcpclient->recvbuff.size, sizeof(tcpclient->recvbuff.buf) - tcpclient->recvbuff.size, 0); + len = recv(tcpclient->head.fd, tcpclient->recvbuff.buf + tcpclient->recvbuff.size, + sizeof(tcpclient->recvbuff.buf) - tcpclient->recvbuff.size, 0); if (len < 0) { if (errno == EAGAIN) { return RECV_ERROR_AGAIN; @@ -2496,7 +2614,7 @@ static int _dns_server_tcp_process_one_request(struct dns_server_conn_tcp_client return RECV_ERROR_FAIL; } - if (request_len > (total_len - proceed_len)) { + if (request_len > (total_len - proceed_len - sizeof(unsigned short))) { ret = RECV_ERROR_AGAIN; break; } @@ -2504,8 +2622,8 @@ static int _dns_server_tcp_process_one_request(struct dns_server_conn_tcp_client request_data = (unsigned char *)(tcpclient->recvbuff.buf + proceed_len + sizeof(unsigned short)); /* process one record */ - if (_dns_server_recv(&tcpclient->head, request_data, request_len, &tcpclient->localaddr, tcpclient->localaddr_len, &tcpclient->addr, - tcpclient->addr_len) != 0) { + if (_dns_server_recv(&tcpclient->head, request_data, request_len, &tcpclient->localaddr, + tcpclient->localaddr_len, &tcpclient->addr, tcpclient->addr_len) != 0) { tlog(TLOG_ERROR, "process tcp request failed."); return RECV_ERROR_FAIL; } @@ -2588,7 +2706,8 @@ static int _dns_server_tcp_send(struct dns_server_conn_tcp_client *tcpclient) return 0; } -static int _dns_server_process_tcp(struct dns_server_conn_tcp_client *dnsserver, struct epoll_event *event, unsigned long now) +static int _dns_server_process_tcp(struct dns_server_conn_tcp_client *dnsserver, struct epoll_event *event, + unsigned long now) { int ret = 0; @@ -2662,16 +2781,18 @@ static void _dns_server_second_ping_check(struct dns_request *request) switch (addr_map->addr_type) { case DNS_T_A: { _dns_server_request_get(request); - sprintf(ip, "%d.%d.%d.%d", addr_map->ipv4_addr[0], addr_map->ipv4_addr[1], addr_map->ipv4_addr[2], addr_map->ipv4_addr[3]); + sprintf(ip, "%d.%d.%d.%d", addr_map->ipv4_addr[0], addr_map->ipv4_addr[1], addr_map->ipv4_addr[2], + addr_map->ipv4_addr[3]); if (_dns_server_check_speed(request, ip, 1, DNS_PING_SECOND_TIMEOUT) != 0) { _dns_server_request_release(request); } } break; case DNS_T_AAAA: { _dns_server_request_get(request); - sprintf(ip, "[%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x]", addr_map->ipv6_addr[0], addr_map->ipv6_addr[1], - addr_map->ipv6_addr[2], addr_map->ipv6_addr[3], addr_map->ipv6_addr[4], addr_map->ipv6_addr[5], addr_map->ipv6_addr[6], - addr_map->ipv6_addr[7], addr_map->ipv6_addr[8], addr_map->ipv6_addr[9], addr_map->ipv6_addr[10], addr_map->ipv6_addr[11], + sprintf(ip, "[%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x]", + addr_map->ipv6_addr[0], addr_map->ipv6_addr[1], addr_map->ipv6_addr[2], addr_map->ipv6_addr[3], + addr_map->ipv6_addr[4], addr_map->ipv6_addr[5], addr_map->ipv6_addr[6], addr_map->ipv6_addr[7], + addr_map->ipv6_addr[8], addr_map->ipv6_addr[9], addr_map->ipv6_addr[10], addr_map->ipv6_addr[11], addr_map->ipv6_addr[12], addr_map->ipv6_addr[13], addr_map->ipv6_addr[14], addr_map->ipv6_addr[15]); if (_dns_server_check_speed(request, ip, 1, DNS_PING_SECOND_TIMEOUT) != 0) { @@ -2696,7 +2817,8 @@ static void _dns_server_prefetch_domain(struct dns_cache *dns_cache) } /* start prefetch domain */ - tlog(TLOG_DEBUG, "prefetch by cache %s, qtype %d, ttl %d, hitnum %d", dns_cache->domain, dns_cache->qtype, dns_cache->ttl, hitnum); + tlog(TLOG_DEBUG, "prefetch by cache %s, qtype %d, ttl %d, hitnum %d", dns_cache->domain, dns_cache->qtype, + dns_cache->ttl, hitnum); if (_dns_server_prefetch_request(dns_cache->domain, dns_cache->qtype) != 0) { tlog(TLOG_ERROR, "prefetch domain %s, qtype %d, failed.", dns_cache->domain, dns_cache->qtype); } @@ -2928,7 +3050,8 @@ static int _dns_create_socket(const char *host_ip, int type) fd = socket(gai->ai_family, gai->ai_socktype, gai->ai_protocol); if (fd < 0) { - tlog(TLOG_ERROR, "create socket failed, family = %d, type = %d, proto = %d, %s\n", gai->ai_family, gai->ai_socktype, gai->ai_protocol, strerror(errno)); + tlog(TLOG_ERROR, "create socket failed, family = %d, type = %d, proto = %d, %s\n", gai->ai_family, + gai->ai_socktype, gai->ai_protocol, strerror(errno)); goto errout; } @@ -3113,7 +3236,7 @@ int dns_server_init(void) return -1; } - if (dns_cache_init(dns_conf_cachesize) != 0) { + if (dns_cache_init(dns_conf_cachesize, dns_conf_serve_expired, dns_conf_serve_expired_ttl) != 0) { tlog(TLOG_ERROR, "init cache failed."); return -1; } diff --git a/release/src/router/smartdns/src/dns_server.h b/release/src/router/smartdns/src/dns_server.h index e19f18a603..358bd601f9 100644 --- a/release/src/router/smartdns/src/dns_server.h +++ b/release/src/router/smartdns/src/dns_server.h @@ -36,7 +36,8 @@ void dns_server_stop(void); void dns_server_exit(void); /* query result notify function */ -typedef int (*dns_result_callback)(char *domain, dns_rtcode_t rtcode, dns_type_t addr_type, char *ip, unsigned int ping_time, void *user_ptr); +typedef int (*dns_result_callback)(char *domain, dns_rtcode_t rtcode, dns_type_t addr_type, char *ip, + unsigned int ping_time, void *user_ptr); /* query domain */ int dns_server_query(char *domain, int qtype, dns_result_callback callback, void *user_ptr); diff --git a/release/src/router/smartdns/src/fast_ping.c b/release/src/router/smartdns/src/fast_ping.c index 85f5206dde..54352bc91e 100644 --- a/release/src/router/smartdns/src/fast_ping.c +++ b/release/src/router/smartdns/src/fast_ping.c @@ -1,1684 +1,1710 @@ -/************************************************************************* - * - * Copyright (C) 2018-2020 Ruilin Peng (Nick) . - * - * smartdns is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * smartdns is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#include "fast_ping.h" -#include "atomic.h" -#include "hashtable.h" -#include "tlog.h" -#include "util.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define PING_MAX_EVENTS 128 -#define PING_MAX_HOSTLEN 128 -#define ICMP_PACKET_SIZE (1024 * 64) -#define ICMP_INPACKET_SIZE 1024 -#define IPV4_ADDR_LEN 4 -#define IPV6_ADDR_LEN 16 -#define SOCKET_PRIORITY (6) - -#ifndef ICMP_FILTER -#define ICMP_FILTER 1 -struct icmp_filter { - uint32_t data; -}; -#endif - -struct ping_dns_head { - unsigned short id; - unsigned short flag; - unsigned short qdcount; - unsigned short ancount; - unsigned short aucount; - unsigned short adcount; -} __attribute__((packed)); - -typedef enum FAST_PING_TYPE { - FAST_PING_ICMP = 1, - FAST_PING_ICMP6 = 2, - FAST_PING_TCP, - FAST_PING_UDP, - FAST_PING_UDP6, - FAST_PING_END, -} FAST_PING_TYPE; - -struct fast_ping_packet_msg { - struct timeval tv; - unsigned int sid; - unsigned int seq; - unsigned int cookie; -}; - -struct fast_ping_packet { - union { - struct icmp icmp; - struct icmp6_hdr icmp6; - }; - unsigned int ttl; - struct fast_ping_packet_msg msg; -}; - -struct ping_host_struct { - atomic_t ref; - atomic_t notified; - struct hlist_node addr_node; - struct list_head action_list; - FAST_PING_TYPE type; - - void *userptr; - fast_ping_result ping_callback; - char host[PING_MAX_HOSTLEN]; - - int fd; - unsigned int seq; - int ttl; - struct timeval last; - int interval; - int timeout; - int count; - int send; - int run; - unsigned int cookie; - unsigned int sid; - unsigned short port; - unsigned short ss_family; - union { - struct sockaddr addr; - struct sockaddr_in6 in6; - struct sockaddr_in in; - }; - socklen_t addr_len; - struct fast_ping_packet packet; -}; - -struct fast_ping_struct { - int run; - pthread_t tid; - pthread_mutex_t lock; - unsigned short ident; - - int epoll_fd; - int fd_icmp; - struct ping_host_struct icmp_host; - int fd_icmp6; - struct ping_host_struct icmp6_host; - int fd_udp; - struct ping_host_struct udp_host; - int fd_udp6; - struct ping_host_struct udp6_host; - - pthread_mutex_t map_lock; - DECLARE_HASHTABLE(addrmap, 6); -}; - -static struct fast_ping_struct ping; -static atomic_t ping_sid = ATOMIC_INIT(0); -static int bool_print_log = 1; - -static uint16_t _fast_ping_checksum(uint16_t *header, size_t len) -{ - uint32_t sum = 0; - int i; - - for (i = 0; i < len / sizeof(uint16_t); i++) { - sum += ntohs(header[i]); - } - - return htons(~((sum >> 16) + (sum & 0xffff))); -} - -static void _fast_ping_install_filter_v6(int sock) -{ - struct icmp6_filter icmp6_filter; - ICMP6_FILTER_SETBLOCKALL(&icmp6_filter); - ICMP6_FILTER_SETPASS(ICMP6_ECHO_REPLY, &icmp6_filter); - setsockopt(sock, IPPROTO_ICMPV6, ICMP6_FILTER, &icmp6_filter, sizeof(struct icmp6_filter)); - - static int once; - static struct sock_filter insns[] = { - BPF_STMT(BPF_LD | BPF_H | BPF_ABS, 4), /* Load icmp echo ident */ - BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0xAAAA, 0, 1), /* Ours? */ - BPF_STMT(BPF_RET | BPF_K, ~0U), /* Yes, it passes. */ - BPF_STMT(BPF_LD | BPF_B | BPF_ABS, 0), /* Load icmp type */ - BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, ICMP6_ECHO_REPLY, 1, 0), /* Echo? */ - BPF_STMT(BPF_RET | BPF_K, ~0U), /* No. It passes. This must not happen. */ - BPF_STMT(BPF_RET | BPF_K, 0), /* Echo with wrong ident. Reject. */ - }; - static struct sock_fprog filter = {sizeof insns / sizeof(insns[0]), insns}; - - if (once) { - return; - } - once = 1; - - /* Patch bpflet for current identifier. */ - insns[1] = (struct sock_filter)BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, htons(ping.ident), 0, 1); - - if (setsockopt(sock, SOL_SOCKET, SO_ATTACH_FILTER, &filter, sizeof(filter))) { - perror("WARNING: failed to install socket filter\n"); - } -} - -static void _fast_ping_install_filter_v4(int sock) -{ - static int once; - static struct sock_filter insns[] = { - BPF_STMT(BPF_LDX | BPF_B | BPF_MSH, 0), /* Skip IP header. F..g BSD... Look into ping6. */ - BPF_STMT(BPF_LD | BPF_H | BPF_IND, 4), /* Load icmp echo ident */ - BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0xAAAA, 0, 1), /* Ours? */ - BPF_STMT(BPF_RET | BPF_K, ~0U), /* Yes, it passes. */ - BPF_STMT(BPF_LD | BPF_B | BPF_IND, 0), /* Load icmp type */ - BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, ICMP_ECHOREPLY, 1, 0), /* Echo? */ - BPF_STMT(BPF_RET | BPF_K, 0xFFFFFFF), /* No. It passes. */ - BPF_STMT(BPF_RET | BPF_K, 0) /* Echo with wrong ident. Reject. */ - }; - - static struct sock_fprog filter = {sizeof insns / sizeof(insns[0]), insns}; - - if (once) { - return; - } - once = 1; - - /* Patch bpflet for current identifier. */ - insns[2] = (struct sock_filter)BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, htons(ping.ident), 0, 1); - - if (setsockopt(sock, SOL_SOCKET, SO_ATTACH_FILTER, &filter, sizeof(filter))) { - perror("WARNING: failed to install socket filter\n"); - } -} - -static int _fast_ping_sockaddr_ip_cmp(struct sockaddr *first_addr, socklen_t first_addr_len, struct sockaddr *second_addr, socklen_t second_addr_len) -{ - if (first_addr_len != second_addr_len) { - return -1; - } - - if (first_addr->sa_family != second_addr->sa_family) { - return -1; - } - - switch (first_addr->sa_family) { - case AF_INET: { - struct sockaddr_in *first_addr_in = (struct sockaddr_in *)first_addr; - struct sockaddr_in *second_addr_in = (struct sockaddr_in *)second_addr; - if (memcmp(&first_addr_in->sin_addr.s_addr, &second_addr_in->sin_addr.s_addr, IPV4_ADDR_LEN) != 0) { - return -1; - } - } break; - case AF_INET6: { - struct sockaddr_in6 *first_addr_in6 = (struct sockaddr_in6 *)first_addr; - struct sockaddr_in6 *second_addr_in6 = (struct sockaddr_in6 *)second_addr; - if (memcmp(&first_addr_in6->sin6_addr.s6_addr, &second_addr_in6->sin6_addr.s6_addr, IPV4_ADDR_LEN) != 0) { - return -1; - } - } break; - default: - return -1; - } - - return 0; -} - -static uint32_t _fast_ping_hash_key(unsigned int sid, struct sockaddr *addr) -{ - uint32_t key = 0; - void *sin_addr = NULL; - unsigned int sin_addr_len = 0; - - switch (addr->sa_family) { - case AF_INET: { - struct sockaddr_in *addr_in; - addr_in = (struct sockaddr_in *)addr; - sin_addr = &addr_in->sin_addr.s_addr; - sin_addr_len = IPV4_ADDR_LEN; - } break; - case AF_INET6: { - struct sockaddr_in6 *addr_in6; - addr_in6 = (struct sockaddr_in6 *)addr; - if (IN6_IS_ADDR_V4MAPPED(&addr_in6->sin6_addr)) { - sin_addr = addr_in6->sin6_addr.s6_addr + 12; - sin_addr_len = IPV4_ADDR_LEN; - } else { - sin_addr = addr_in6->sin6_addr.s6_addr; - sin_addr_len = IPV6_ADDR_LEN; - } - } break; - default: - goto errout; - break; - } - if (sin_addr == NULL) { - return -1; - } - - key = jhash(sin_addr, sin_addr_len, 0); - key = jhash(&sid, sizeof(sid), key); - - return key; -errout: - return -1; -} - -static struct addrinfo *_fast_ping_getaddr(const char *host, const char *port, int type, int protocol) -{ - struct addrinfo hints; - struct addrinfo *result = NULL; - int errcode = 0; - - memset(&hints, 0, sizeof(hints)); - hints.ai_family = AF_UNSPEC; - hints.ai_socktype = type; - hints.ai_protocol = protocol; - errcode = getaddrinfo(host, port, &hints, &result); - if (errcode != 0) { - tlog(TLOG_ERROR, "get addr info failed. host:%s, port: %s, error %s\n", host, port, gai_strerror(errcode)); - goto errout; - } - - return result; -errout: - if (result) { - freeaddrinfo(result); - } - return NULL; -} - -static int _fast_ping_getdomain(const char *host) -{ - struct addrinfo hints; - struct addrinfo *result = NULL; - int domain = -1; - - memset(&hints, 0, sizeof(hints)); - hints.ai_family = AF_UNSPEC; - hints.ai_socktype = SOCK_STREAM; - hints.ai_protocol = 0; - if (getaddrinfo(host, NULL, &hints, &result) != 0) { - tlog(TLOG_ERROR, "get addr info failed. %s\n", strerror(errno)); - goto errout; - } - - domain = result->ai_family; - - freeaddrinfo(result); - - return domain; -errout: - if (result) { - freeaddrinfo(result); - } - return -1; -} - -static void _fast_ping_host_get(struct ping_host_struct *ping_host) -{ - if (atomic_inc_return(&ping_host->ref) <= 0) { - tlog(TLOG_ERROR, "BUG: ping host ref is invalid, host: %s", ping_host->host); - abort(); - } -} - -static void _fast_ping_close_host_sock(struct ping_host_struct *ping_host) -{ - if (ping_host->fd < 0) { - return; - } - struct epoll_event *event; - event = (struct epoll_event *)1; - epoll_ctl(ping.epoll_fd, EPOLL_CTL_DEL, ping_host->fd, event); - close(ping_host->fd); - ping_host->fd = -1; -} - -static void _fast_ping_host_put(struct ping_host_struct *ping_host) -{ - if (!atomic_dec_and_test(&ping_host->ref)) { - return; - } - - _fast_ping_close_host_sock(ping_host); - - pthread_mutex_lock(&ping.map_lock); - hash_del(&ping_host->addr_node); - pthread_mutex_unlock(&ping.map_lock); - - if (atomic_inc_return(&ping_host->notified) == 1) { - struct timeval tv; - tv.tv_sec = 0; - tv.tv_usec = 0; - - ping_host->ping_callback(ping_host, ping_host->host, PING_RESULT_END, &ping_host->addr, ping_host->addr_len, ping_host->seq, ping_host->ttl, &tv, - ping_host->userptr); - } - - tlog(TLOG_DEBUG, "ping end, id %d", ping_host->sid); - // memset(ping_host, 0, sizeof(*ping_host)); - ping_host->type = FAST_PING_END; - free(ping_host); -} - -static void _fast_ping_host_remove(struct ping_host_struct *ping_host) -{ - _fast_ping_close_host_sock(ping_host); - - pthread_mutex_lock(&ping.map_lock); - if (!hash_hashed(&ping_host->addr_node)) { - pthread_mutex_unlock(&ping.map_lock); - return; - } - hash_del(&ping_host->addr_node); - - pthread_mutex_unlock(&ping.map_lock); - - if (atomic_inc_return(&ping_host->notified) == 1) { - struct timeval tv; - tv.tv_sec = 0; - tv.tv_usec = 0; - - ping_host->ping_callback(ping_host, ping_host->host, PING_RESULT_END, &ping_host->addr, ping_host->addr_len, ping_host->seq, ping_host->ttl, &tv, - ping_host->userptr); - } - - _fast_ping_host_put(ping_host); -} - -static int _fast_ping_sendping_v6(struct ping_host_struct *ping_host) -{ - struct fast_ping_packet *packet = &ping_host->packet; - struct icmp6_hdr *icmp6 = &packet->icmp6; - int len = 0; - - ping_host->seq++; - memset(icmp6, 0, sizeof(*icmp6)); - icmp6->icmp6_type = ICMP6_ECHO_REQUEST; - icmp6->icmp6_code = 0; - icmp6->icmp6_cksum = 0; - icmp6->icmp6_id = ping.ident; - icmp6->icmp6_seq = htons(ping_host->seq); - - gettimeofday(&packet->msg.tv, NULL); - gettimeofday(&ping_host->last, NULL); - packet->msg.sid = ping_host->sid; - packet->msg.cookie = ping_host->cookie; - packet->msg.seq = ping_host->seq; - icmp6->icmp6_cksum = _fast_ping_checksum((void *)packet, sizeof(struct fast_ping_packet)); - - len = sendto(ping.fd_icmp6, &ping_host->packet, sizeof(struct fast_ping_packet), 0, (struct sockaddr *)&ping_host->addr, ping_host->addr_len); - if (len < 0 || len != sizeof(struct fast_ping_packet)) { - int err = errno; - if (errno == ENETUNREACH || errno == EINVAL) { - goto errout; - } - - if (errno == EACCES) { - if (bool_print_log == 0) { - goto errout; - } - bool_print_log = 0; - } - - char ping_host_name[PING_MAX_HOSTLEN]; - tlog(TLOG_ERROR, "sendto %s, id %d, %s", gethost_by_addr(ping_host_name, sizeof(ping_host_name), (struct sockaddr *)&ping_host->addr), ping_host->sid, - strerror(err)); - goto errout; - } - - return 0; - -errout: - return -1; -} - -static int _fast_ping_sendping_v4(struct ping_host_struct *ping_host) -{ - struct fast_ping_packet *packet = &ping_host->packet; - struct icmp *icmp = &packet->icmp; - int len; - - ping_host->seq++; - memset(icmp, 0, sizeof(*icmp)); - icmp->icmp_type = ICMP_ECHO; - icmp->icmp_code = 0; - icmp->icmp_cksum = 0; - icmp->icmp_id = ping.ident; - icmp->icmp_seq = htons(ping_host->seq); - - gettimeofday(&packet->msg.tv, NULL); - gettimeofday(&ping_host->last, NULL); - packet->msg.sid = ping_host->sid; - packet->msg.seq = ping_host->seq; - packet->msg.cookie = ping_host->cookie; - icmp->icmp_cksum = _fast_ping_checksum((void *)packet, sizeof(struct fast_ping_packet)); - - len = sendto(ping.fd_icmp, packet, sizeof(struct fast_ping_packet), 0, (struct sockaddr *)&ping_host->addr, ping_host->addr_len); - if (len < 0 || len != sizeof(struct fast_ping_packet)) { - int err = errno; - if (errno == ENETUNREACH || errno == EINVAL) { - goto errout; - } - char ping_host_name[PING_MAX_HOSTLEN]; - tlog(TLOG_ERROR, "sendto %s, id %d, %s", gethost_by_addr(ping_host_name, sizeof(ping_host_name), (struct sockaddr *)&ping_host->addr), ping_host->sid, - strerror(err)); - goto errout; - } - - return 0; - -errout: - return -1; -} - -static int _fast_ping_sendping_udp(struct ping_host_struct *ping_host) -{ - struct ping_dns_head dns_head; - int len; - int flag = 0; - int fd = 0; - - flag |= (0 << 15) & 0x8000; - flag |= (2 << 11) & 0x7800; - flag |= (0 << 10) & 0x0400; - flag |= (0 << 9) & 0x0200; - flag |= (0 << 8) & 0x0100; - flag |= (0 << 7) & 0x0080; - flag |= (0 << 0) & 0x000F; - - if (ping_host->type == FAST_PING_UDP) { - fd = ping.fd_udp; - } else if (ping_host->type == FAST_PING_UDP6) { - fd = ping.fd_udp6; - } else { - return -1; - } - - ping_host->seq++; - memset(&dns_head, 0, sizeof(dns_head)); - dns_head.id = htons(ping_host->sid); - dns_head.flag = flag; - gettimeofday(&ping_host->last, NULL); - len = sendto(fd, &dns_head, sizeof(dns_head), 0, (struct sockaddr *)&ping_host->addr, ping_host->addr_len); - if (len < 0 || len != sizeof(dns_head)) { - int err = errno; - if (errno == ENETUNREACH || errno == EINVAL) { - goto errout; - } - char ping_host_name[PING_MAX_HOSTLEN]; - tlog(TLOG_ERROR, "sendto %s, id %d, %s", gethost_by_addr(ping_host_name, sizeof(ping_host_name), (struct sockaddr *)&ping_host->addr), ping_host->sid, - strerror(err)); - goto errout; - } - - return 0; - -errout: - return -1; -} - -static int _fast_ping_sendping_tcp(struct ping_host_struct *ping_host) -{ - struct epoll_event event; - int flags; - int fd = -1; - int yes = 1; - const int priority = SOCKET_PRIORITY; - const int ip_tos = IP_TOS; - - _fast_ping_close_host_sock(ping_host); - - fd = socket(ping_host->ss_family, SOCK_STREAM, 0); - if (fd < 0) { - goto errout; - } - - flags = fcntl(fd, F_GETFL, 0); - fcntl(fd, F_SETFL, flags | O_NONBLOCK); - setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(yes)); - setsockopt(fd, SOL_SOCKET, SO_PRIORITY, &priority, sizeof(priority)); - setsockopt(fd, IPPROTO_IP, IP_TOS, &ip_tos, sizeof(ip_tos)); - - ping_host->seq++; - if (connect(fd, (struct sockaddr *)&ping_host->addr, ping_host->addr_len) != 0) { - if (errno != EINPROGRESS) { - char ping_host_name[PING_MAX_HOSTLEN]; - if (errno == ENETUNREACH || errno == EINVAL) { - goto errout; - } - - if (errno == EACCES) { - if (bool_print_log == 0) { - goto errout; - } - bool_print_log = 0; - } - - tlog(TLOG_ERROR, "connect %s, id %d, %s", gethost_by_addr(ping_host_name, sizeof(ping_host_name), (struct sockaddr *)&ping_host->addr), - ping_host->sid, strerror(errno)); - goto errout; - } - } - - gettimeofday(&ping_host->last, NULL); - ping_host->fd = fd; - memset(&event, 0, sizeof(event)); - event.events = EPOLLIN | EPOLLOUT | EPOLLERR; - event.data.ptr = ping_host; - if (epoll_ctl(ping.epoll_fd, EPOLL_CTL_ADD, fd, &event) != 0) { - ping_host->fd = -1; - goto errout; - } - - return 0; - -errout: - if (fd > 0) { - close(fd); - ping_host->fd = -1; - } - return -1; -} - -static int _fast_ping_sendping(struct ping_host_struct *ping_host) -{ - int ret = -1; - gettimeofday(&ping_host->last, NULL); - - if (ping_host->type == FAST_PING_ICMP) { - ret = _fast_ping_sendping_v4(ping_host); - } else if (ping_host->type == FAST_PING_ICMP6) { - ret = _fast_ping_sendping_v6(ping_host); - } else if (ping_host->type == FAST_PING_TCP) { - ret = _fast_ping_sendping_tcp(ping_host); - } else if (ping_host->type == FAST_PING_UDP || ping_host->type == FAST_PING_UDP6) { - ret = _fast_ping_sendping_udp(ping_host); - } - - ping_host->send = 1; - - if (ret != 0) { - return ret; - } - - return 0; -} - -static int _fast_ping_create_icmp_sock(FAST_PING_TYPE type) -{ - int fd = -1; - struct ping_host_struct *icmp_host = NULL; - struct epoll_event event; - int buffsize = 64 * 1024; - socklen_t optlen = sizeof(buffsize); - const int val = 255; - const int on = 1; - const int ip_tos = (IPTOS_LOWDELAY | IPTOS_RELIABILITY); - - switch (type) { - case FAST_PING_ICMP: - fd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); - if (fd < 0) { - tlog(TLOG_ERROR, "create icmp socket failed, %s\n", strerror(errno)); - goto errout; - } - _fast_ping_install_filter_v4(fd); - icmp_host = &ping.icmp_host; - break; - case FAST_PING_ICMP6: - fd = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6); - if (fd < 0) { - tlog(TLOG_ERROR, "create icmp socket failed, %s\n", strerror(errno)); - goto errout; - } - _fast_ping_install_filter_v6(fd); - setsockopt(fd, IPPROTO_IPV6, IPV6_RECVHOPLIMIT, &on, sizeof(on)); - setsockopt(fd, IPPROTO_IPV6, IPV6_2292HOPLIMIT, &on, sizeof(on)); - setsockopt(fd, IPPROTO_IPV6, IPV6_HOPLIMIT, &on, sizeof(on)); - icmp_host = &ping.icmp6_host; - break; - default: - return -1; - } - - struct icmp_filter filt; - filt.data = ~((1 << ICMP_SOURCE_QUENCH) | (1 << ICMP_DEST_UNREACH) | (1 << ICMP_TIME_EXCEEDED) | (1 << ICMP_PARAMETERPROB) | (1 << ICMP_REDIRECT) | - (1 << ICMP_ECHOREPLY)); - setsockopt(fd, SOL_RAW, ICMP_FILTER, &filt, sizeof filt); - setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const char *)&buffsize, optlen); - setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (const char *)&buffsize, optlen); - setsockopt(fd, SOL_IP, IP_TTL, &val, sizeof(val)); - setsockopt(fd, IPPROTO_IP, IP_TOS, &ip_tos, sizeof(ip_tos)); - - memset(&event, 0, sizeof(event)); - event.events = EPOLLIN; - event.data.ptr = icmp_host; - if (epoll_ctl(ping.epoll_fd, EPOLL_CTL_ADD, fd, &event) != 0) { - goto errout; - } - - icmp_host->fd = fd; - icmp_host->type = type; - return fd; - -errout: - close(fd); - return -1; -} - -static int _fast_ping_create_icmp(FAST_PING_TYPE type) -{ - int fd = 0; - int *set_fd = NULL; - - pthread_mutex_lock(&ping.lock); - switch (type) { - case FAST_PING_ICMP: - set_fd = &ping.fd_icmp; - break; - case FAST_PING_ICMP6: - set_fd = &ping.fd_icmp6; - break; - default: - goto errout; - break; - } - - if (*set_fd > 0) { - goto out; - } - - fd = _fast_ping_create_icmp_sock(type); - if (fd < 0) { - goto errout; - } - - *set_fd = fd; -out: - pthread_mutex_unlock(&ping.lock); - return *set_fd; -errout: - if (fd > 0) { - close(fd); - } - pthread_mutex_unlock(&ping.lock); - return -1; -} - -static int _fast_ping_create_udp_sock(FAST_PING_TYPE type) -{ - int fd = -1; - struct ping_host_struct *udp_host = NULL; - struct epoll_event event; - const int val = 255; - const int on = 1; - const int ip_tos = (IPTOS_LOWDELAY | IPTOS_RELIABILITY); - - switch (type) { - case FAST_PING_UDP: - fd = socket(AF_INET, SOCK_DGRAM, 0); - if (fd < 0) { - tlog(TLOG_ERROR, "create udp socket failed, %s\n", strerror(errno)); - goto errout; - } - - udp_host = &ping.udp_host; - udp_host->type = FAST_PING_UDP; - break; - case FAST_PING_UDP6: - fd = socket(AF_INET6, SOCK_DGRAM, 0); - if (fd < 0) { - tlog(TLOG_ERROR, "create udp socket failed, %s\n", strerror(errno)); - goto errout; - } - - udp_host = &ping.udp6_host; - udp_host->type = FAST_PING_UDP6; - setsockopt(fd, IPPROTO_IPV6, IPV6_RECVHOPLIMIT, &on, sizeof(on)); - setsockopt(fd, IPPROTO_IPV6, IPV6_2292HOPLIMIT, &on, sizeof(on)); - setsockopt(fd, IPPROTO_IPV6, IPV6_HOPLIMIT, &on, sizeof(on)); - break; - default: - return -1; - } - - setsockopt(fd, SOL_IP, IP_TTL, &val, sizeof(val)); - setsockopt(fd, IPPROTO_IP, IP_RECVTTL, &on, sizeof(on)); - setsockopt(fd, IPPROTO_IP, IP_TOS, &ip_tos, sizeof(ip_tos)); - - memset(&event, 0, sizeof(event)); - event.events = EPOLLIN; - event.data.ptr = udp_host; - if (epoll_ctl(ping.epoll_fd, EPOLL_CTL_ADD, fd, &event) != 0) { - goto errout; - } - - udp_host->fd = fd; - return fd; - -errout: - close(fd); - return -1; -} - -static int _fast_ping_create_udp(FAST_PING_TYPE type) -{ - int fd = 0; - int *set_fd = NULL; - - pthread_mutex_lock(&ping.lock); - switch (type) { - case FAST_PING_UDP: - set_fd = &ping.fd_udp; - break; - case FAST_PING_UDP6: - set_fd = &ping.fd_udp6; - break; - default: - goto errout; - break; - } - - if (*set_fd > 0) { - goto out; - } - - fd = _fast_ping_create_udp_sock(type); - if (fd < 0) { - goto errout; - } - - *set_fd = fd; -out: - pthread_mutex_unlock(&ping.lock); - return *set_fd; -errout: - if (fd > 0) { - close(fd); - } - pthread_mutex_unlock(&ping.lock); - return -1; -} - -static void _fast_ping_print_result(struct ping_host_struct *ping_host, const char *host, FAST_PING_RESULT result, struct sockaddr *addr, socklen_t addr_len, - int seqno, int ttl, struct timeval *tv, void *userptr) -{ - if (result == PING_RESULT_RESPONSE) { - double rtt = tv->tv_sec * 1000.0 + tv->tv_usec / 1000.0; - tlog(TLOG_INFO, "from %15s: seq=%d ttl=%d time=%.3f\n", host, seqno, ttl, rtt); - } else if (result == PING_RESULT_TIMEOUT) { - tlog(TLOG_INFO, "from %15s: seq=%d timeout\n", host, seqno); - } else if (result == PING_RESULT_END) { - fast_ping_stop(ping_host); - } -} - -static int _fast_ping_get_addr_by_icmp(const char *ip_str, int port, struct addrinfo **out_gai, FAST_PING_TYPE *out_ping_type) -{ - struct addrinfo *gai = NULL; - int socktype = 0; - int domain = -1; - FAST_PING_TYPE ping_type; - int sockproto = 0; - char *service = NULL; - - socktype = SOCK_RAW; - domain = _fast_ping_getdomain(ip_str); - if (domain < 0) { - goto errout; - } - - switch (domain) { - case AF_INET: - sockproto = IPPROTO_ICMP; - ping_type = FAST_PING_ICMP; - break; - case AF_INET6: - sockproto = IPPROTO_ICMPV6; - ping_type = FAST_PING_ICMP6; - break; - default: - goto errout; - break; - } - - if (_fast_ping_create_icmp(ping_type) < 0) { - goto errout; - } - - gai = _fast_ping_getaddr(ip_str, service, socktype, sockproto); - if (gai == NULL) { - goto errout; - } - - *out_gai = gai; - *out_ping_type = ping_type; - - return 0; -errout: - if (gai) { - freeaddrinfo(gai); - } - return -1; -} - -static int _fast_ping_get_addr_by_tcp(const char *ip_str, int port, struct addrinfo **out_gai, FAST_PING_TYPE *out_ping_type) -{ - struct addrinfo *gai = NULL; - int socktype = 0; - FAST_PING_TYPE ping_type; - int sockproto = 0; - char *service = NULL; - char port_str[MAX_IP_LEN]; - - if (port <= 0) { - port = 80; - } - - sockproto = 0; - socktype = SOCK_STREAM; - snprintf(port_str, MAX_IP_LEN, "%d", port); - service = port_str; - ping_type = FAST_PING_TCP; - - gai = _fast_ping_getaddr(ip_str, service, socktype, sockproto); - if (gai == NULL) { - goto errout; - } - - *out_gai = gai; - *out_ping_type = ping_type; - - return 0; -errout: - if (gai) { - freeaddrinfo(gai); - } - return -1; -} - -static int _fast_ping_get_addr_by_dns(const char *ip_str, int port, struct addrinfo **out_gai, FAST_PING_TYPE *out_ping_type) -{ - struct addrinfo *gai = NULL; - int socktype = 0; - FAST_PING_TYPE ping_type; - int sockproto = 0; - char port_str[MAX_IP_LEN]; - int domain = -1; - char *service = NULL; - - if (port <= 0) { - port = 53; - } - - domain = _fast_ping_getdomain(ip_str); - if (domain < 0) { - goto errout; - } - - switch (domain) { - case AF_INET: - ping_type = FAST_PING_UDP; - break; - case AF_INET6: - ping_type = FAST_PING_UDP6; - break; - default: - goto errout; - break; - } - - sockproto = 0; - socktype = SOCK_DGRAM; - snprintf(port_str, MAX_IP_LEN, "%d", port); - service = port_str; - - if (_fast_ping_create_udp(ping_type) < 0) { - goto errout; - } - - gai = _fast_ping_getaddr(ip_str, service, socktype, sockproto); - if (gai == NULL) { - goto errout; - } - - *out_gai = gai; - *out_ping_type = ping_type; - - return 0; -errout: - if (gai) { - freeaddrinfo(gai); - } - return -1; -} - -static int _fast_ping_get_addr_by_type(PING_TYPE type, const char *ip_str, int port, struct addrinfo **out_gai, FAST_PING_TYPE *out_ping_type) -{ - switch (type) { - case PING_TYPE_ICMP: - return _fast_ping_get_addr_by_icmp(ip_str, port, out_gai, out_ping_type); - break; - case PING_TYPE_TCP: - return _fast_ping_get_addr_by_tcp(ip_str, port, out_gai, out_ping_type); - break; - case PING_TYPE_DNS: - return _fast_ping_get_addr_by_dns(ip_str, port, out_gai, out_ping_type); - break; - default: - break; - } - - return -1; -} - -struct ping_host_struct *fast_ping_start(PING_TYPE type, const char *host, int count, int interval, int timeout, fast_ping_result ping_callback, void *userptr) -{ - struct ping_host_struct *ping_host = NULL; - struct addrinfo *gai = NULL; - uint32_t addrkey; - char ip_str[PING_MAX_HOSTLEN]; - int port = -1; - FAST_PING_TYPE ping_type; - unsigned int seed; - int ret = 0; - - if (parse_ip(host, ip_str, &port) != 0) { - goto errout; - } - - ret = _fast_ping_get_addr_by_type(type, ip_str, port, &gai, &ping_type); - if (ret != 0) { - tlog(TLOG_ERROR, "get addr by type failed, host: %s", host); - goto errout; - } - - ping_host = malloc(sizeof(*ping_host)); - if (ping_host == NULL) { - goto errout; - } - - memset(ping_host, 0, sizeof(*ping_host)); - safe_strncpy(ping_host->host, host, PING_MAX_HOSTLEN); - ping_host->fd = -1; - ping_host->timeout = timeout; - ping_host->count = count; - ping_host->type = ping_type; - ping_host->userptr = userptr; - atomic_set(&ping_host->ref, 0); - atomic_set(&ping_host->notified, 0); - ping_host->sid = atomic_inc_return(&ping_sid); - seed = ping_host->sid; - ping_host->cookie = rand_r(&seed); - ping_host->run = 0; - if (ping_callback) { - ping_host->ping_callback = ping_callback; - } else { - ping_host->ping_callback = _fast_ping_print_result; - } - ping_host->interval = (timeout > interval) ? timeout : interval; - ping_host->addr_len = gai->ai_addrlen; - ping_host->port = port; - ping_host->ss_family = gai->ai_family; - if (gai->ai_addrlen > sizeof(struct sockaddr_in6)) { - goto errout; - } - memcpy(&ping_host->addr, gai->ai_addr, gai->ai_addrlen); - - tlog(TLOG_DEBUG, "ping %s, id = %d", host, ping_host->sid); - - addrkey = _fast_ping_hash_key(ping_host->sid, &ping_host->addr); - pthread_mutex_lock(&ping.map_lock); - _fast_ping_host_get(ping_host); - hash_add(ping.addrmap, &ping_host->addr_node, addrkey); - pthread_mutex_unlock(&ping.map_lock); - - _fast_ping_host_get(ping_host); - if (_fast_ping_sendping(ping_host) != 0) { - goto errout_remove; - } - - ping_host->run = 1; - freeaddrinfo(gai); - return ping_host; -errout_remove: - fast_ping_stop(ping_host); - ping_host = NULL; -errout: - if (gai) { - freeaddrinfo(gai); - } - - if (ping_host) { - free(ping_host); - } - - return NULL; -} - -int fast_ping_stop(struct ping_host_struct *ping_host) -{ - if (ping_host == NULL) { - return 0; - } - - atomic_inc_return(&ping_host->notified); - _fast_ping_host_remove(ping_host); - _fast_ping_host_put(ping_host); - return 0; -} - -static void tv_sub(struct timeval *out, struct timeval *in) -{ - if ((out->tv_usec -= in->tv_usec) < 0) { /* out -= in */ - --out->tv_sec; - out->tv_usec += 1000000; - } - out->tv_sec -= in->tv_sec; -} - -static struct fast_ping_packet *_fast_ping_icmp6_packet(struct ping_host_struct *ping_host, struct msghdr *msg, u_char *packet_data, int data_len) -{ - int icmp_len; - struct fast_ping_packet *packet = (struct fast_ping_packet *)packet_data; - struct icmp6_hdr *icmp6 = &packet->icmp6; - struct cmsghdr *c; - int hops = 0; - - for (c = CMSG_FIRSTHDR(msg); c; c = CMSG_NXTHDR(msg, c)) { - if (c->cmsg_level != IPPROTO_IPV6) - continue; - switch (c->cmsg_type) { - case IPV6_HOPLIMIT: -#ifdef IPV6_2292HOPLIMIT - case IPV6_2292HOPLIMIT: -#endif - if (c->cmsg_len < CMSG_LEN(sizeof(int))) - continue; - memcpy(&hops, CMSG_DATA(c), sizeof(hops)); - } - } - - packet->ttl = hops; - if (icmp6->icmp6_type != ICMP6_ECHO_REPLY) { - tlog(TLOG_DEBUG, "icmp6 type faild, %d:%d", icmp6->icmp6_type, ICMP6_ECHO_REPLY); - return NULL; - } - - icmp_len = data_len; - if (icmp_len < 16) { - tlog(TLOG_ERROR, "length is invalid, %d", icmp_len); - return NULL; - } - - if (icmp6->icmp6_id != ping.ident) { - tlog(TLOG_ERROR, "ident failed, %d:%d", icmp6->icmp6_id, ping.ident); - return NULL; - } - - return packet; -} - -static struct fast_ping_packet *_fast_ping_icmp_packet(struct ping_host_struct *ping_host, struct msghdr *msg, u_char *packet_data, int data_len) -{ - struct ip *ip = (struct ip *)packet_data; - struct fast_ping_packet *packet; - struct icmp *icmp; - int hlen; - int icmp_len; - - if (ip->ip_p != IPPROTO_ICMP) { - tlog(TLOG_ERROR, "ip type faild, %d:%d", ip->ip_p, IPPROTO_ICMP); - return NULL; - } - - hlen = ip->ip_hl << 2; - packet = (struct fast_ping_packet *)(packet_data + hlen); - icmp = &packet->icmp; - icmp_len = data_len - hlen; - packet->ttl = ip->ip_ttl; - - if (icmp_len < 16) { - tlog(TLOG_ERROR, "length is invalid, %d", icmp_len); - return NULL; - } - - if (icmp->icmp_type != ICMP_ECHOREPLY) { - tlog(TLOG_DEBUG, "icmp type faild, %d:%d", icmp->icmp_type, ICMP_ECHOREPLY); - return NULL; - } - - if (icmp->icmp_id != ping.ident) { - tlog(TLOG_ERROR, "ident failed, %d:%d", icmp->icmp_id, ping.ident); - return NULL; - } - - return packet; -} - -static struct fast_ping_packet *_fast_ping_recv_packet(struct ping_host_struct *ping_host, struct msghdr *msg, u_char *inpacket, int len, - struct timeval *tvrecv) -{ - struct fast_ping_packet *packet = NULL; - - if (ping_host->type == FAST_PING_ICMP6) { - packet = _fast_ping_icmp6_packet(ping_host, msg, inpacket, len); - if (packet == NULL) { - goto errout; - } - } else if (ping_host->type == FAST_PING_ICMP) { - packet = _fast_ping_icmp_packet(ping_host, msg, inpacket, len); - if (packet == NULL) { - goto errout; - } - } else { - tlog(TLOG_ERROR, "ping host type is invalid, %d", ping_host->type); - goto errout; - } - - return packet; -errout: - return NULL; -} - -static int _fast_ping_process_icmp(struct ping_host_struct *ping_host, struct timeval *now) -{ - int len; - u_char inpacket[ICMP_INPACKET_SIZE]; - struct sockaddr_storage from; - struct ping_host_struct *recv_ping_host; - struct fast_ping_packet *packet = NULL; - socklen_t from_len = sizeof(from); - uint32_t addrkey; - struct timeval tvresult = *now; - struct timeval *tvsend = NULL; - unsigned int sid; - unsigned int seq; - unsigned int cookie; - struct msghdr msg; - struct iovec iov; - char ans_data[4096]; - - memset(&msg, 0, sizeof(msg)); - iov.iov_base = (char *)inpacket; - iov.iov_len = sizeof(inpacket); - msg.msg_name = &from; - msg.msg_namelen = sizeof(from); - msg.msg_iov = &iov; - msg.msg_iovlen = 1; - msg.msg_control = ans_data; - msg.msg_controllen = sizeof(ans_data); - - len = recvmsg(ping_host->fd, &msg, MSG_DONTWAIT); - if (len < 0) { - tlog(TLOG_ERROR, "recvfrom failed, %s\n", strerror(errno)); - goto errout; - } - - from_len = msg.msg_namelen; - packet = _fast_ping_recv_packet(ping_host, &msg, inpacket, len, now); - if (packet == NULL) { - char name[PING_MAX_HOSTLEN]; - tlog(TLOG_DEBUG, "recv ping packet from %s failed.", gethost_by_addr(name, sizeof(name), (struct sockaddr *)&from)); - goto errout; - } - - tvsend = &packet->msg.tv; - sid = packet->msg.sid; - seq = packet->msg.seq; - cookie = packet->msg.cookie; - addrkey = _fast_ping_hash_key(sid, (struct sockaddr *)&from); - pthread_mutex_lock(&ping.map_lock); - hash_for_each_possible(ping.addrmap, recv_ping_host, addr_node, addrkey) - { - if (_fast_ping_sockaddr_ip_cmp(&recv_ping_host->addr, recv_ping_host->addr_len, (struct sockaddr *)&from, from_len) == 0 && - recv_ping_host->sid == sid && recv_ping_host->cookie == cookie) { - _fast_ping_host_get(recv_ping_host); - break; - } - } - - pthread_mutex_unlock(&ping.map_lock); - - if (recv_ping_host == NULL) { - return -1; - } - - if (recv_ping_host->seq != seq) { - tlog(TLOG_ERROR, "seq num mismatch, expect %u, real %u", recv_ping_host->seq, seq); - _fast_ping_host_put(recv_ping_host); - return -1; - } - - recv_ping_host->ttl = packet->ttl; - tv_sub(&tvresult, tvsend); - if (recv_ping_host->ping_callback) { - recv_ping_host->ping_callback(recv_ping_host, recv_ping_host->host, PING_RESULT_RESPONSE, &recv_ping_host->addr, recv_ping_host->addr_len, - recv_ping_host->seq, recv_ping_host->ttl, &tvresult, recv_ping_host->userptr); - } - - recv_ping_host->send = 0; - - if (recv_ping_host->count == 1) { - _fast_ping_host_remove(recv_ping_host); - } - - _fast_ping_host_put(recv_ping_host); - return 0; -errout: - return -1; -} - -static int _fast_ping_process_tcp(struct ping_host_struct *ping_host, struct epoll_event *event, struct timeval *now) -{ - struct timeval tvresult = *now; - struct timeval *tvsend = &ping_host->last; - int connect_error = 0; - socklen_t len = sizeof(connect_error); - - if (event->events & EPOLLIN || event->events & EPOLLERR) { - if (getsockopt(ping_host->fd, SOL_SOCKET, SO_ERROR, (char *)&connect_error, &len) != 0) { - goto errout; - } - - if (connect_error != 0 && connect_error != ECONNREFUSED) { - goto errout; - } - } - tv_sub(&tvresult, tvsend); - if (ping_host->ping_callback) { - ping_host->ping_callback(ping_host, ping_host->host, PING_RESULT_RESPONSE, &ping_host->addr, ping_host->addr_len, ping_host->seq, ping_host->ttl, - &tvresult, ping_host->userptr); - } - - ping_host->send = 0; - - _fast_ping_close_host_sock(ping_host); - - if (ping_host->count == 1) { - _fast_ping_host_remove(ping_host); - } - return 0; -errout: - _fast_ping_host_remove(ping_host); - - return -1; -} - -static int _fast_ping_process_udp(struct ping_host_struct *ping_host, struct timeval *now) -{ - int len; - u_char inpacket[ICMP_INPACKET_SIZE]; - struct sockaddr_storage from; - struct ping_host_struct *recv_ping_host; - struct ping_dns_head *dns_head = NULL; - socklen_t from_len = sizeof(from); - uint32_t addrkey; - struct timeval tvresult = *now; - struct timeval *tvsend = NULL; - unsigned int sid; - struct msghdr msg; - struct iovec iov; - char ans_data[4096]; - struct cmsghdr *cmsg; - int ttl = 0; - - memset(&msg, 0, sizeof(msg)); - iov.iov_base = (char *)inpacket; - iov.iov_len = sizeof(inpacket); - msg.msg_name = &from; - msg.msg_namelen = sizeof(from); - msg.msg_iov = &iov; - msg.msg_iovlen = 1; - msg.msg_control = ans_data; - msg.msg_controllen = sizeof(ans_data); - - len = recvmsg(ping_host->fd, &msg, MSG_DONTWAIT); - if (len < 0) { - tlog(TLOG_ERROR, "recvfrom failed, %s\n", strerror(errno)); - goto errout; - } - - for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) { - if (cmsg->cmsg_level == SOL_IP && cmsg->cmsg_type == IP_TTL) { - if (cmsg->cmsg_len >= sizeof(int)) { - int *ttlPtr = (int *)CMSG_DATA(cmsg); - ttl = *ttlPtr; - } - } else if (cmsg->cmsg_level == IPPROTO_IPV6 && cmsg->cmsg_type == IPV6_HOPLIMIT) { - if (cmsg->cmsg_len >= sizeof(int)) { - int *ttlPtr = (int *)CMSG_DATA(cmsg); - ttl = *ttlPtr; - } - } - } - - from_len = msg.msg_namelen; - dns_head = (struct ping_dns_head *)inpacket; - if (len < sizeof(*dns_head)) { - goto errout; - } - - sid = ntohs(dns_head->id); - addrkey = _fast_ping_hash_key(sid, (struct sockaddr *)&from); - pthread_mutex_lock(&ping.map_lock); - hash_for_each_possible(ping.addrmap, recv_ping_host, addr_node, addrkey) - { - if (_fast_ping_sockaddr_ip_cmp(&recv_ping_host->addr, recv_ping_host->addr_len, (struct sockaddr *)&from, from_len) == 0 && - recv_ping_host->sid == sid) { - _fast_ping_host_get(recv_ping_host); - break; - } - } - - pthread_mutex_unlock(&ping.map_lock); - - if (recv_ping_host == NULL) { - return -1; - } - - recv_ping_host->ttl = ttl; - tvsend = &recv_ping_host->last; - tv_sub(&tvresult, tvsend); - if (recv_ping_host->ping_callback) { - recv_ping_host->ping_callback(recv_ping_host, recv_ping_host->host, PING_RESULT_RESPONSE, &recv_ping_host->addr, recv_ping_host->addr_len, - recv_ping_host->seq, recv_ping_host->ttl, &tvresult, recv_ping_host->userptr); - } - - recv_ping_host->send = 0; - - if (recv_ping_host->count == 1) { - _fast_ping_host_remove(recv_ping_host); - } - - _fast_ping_host_put(recv_ping_host); - - return 0; -errout: - return -1; -} - -static int _fast_ping_process(struct ping_host_struct *ping_host, struct epoll_event *event, struct timeval *now) -{ - int ret = -1; - - switch (ping_host->type) { - case FAST_PING_ICMP6: - case FAST_PING_ICMP: - ret = _fast_ping_process_icmp(ping_host, now); - break; - case FAST_PING_TCP: - ret = _fast_ping_process_tcp(ping_host, event, now); - break; - case FAST_PING_UDP6: - case FAST_PING_UDP: - ret = _fast_ping_process_udp(ping_host, now); - break; - default: - tlog(TLOG_ERROR, "BUG: type error : %p, %d, %s, %d", ping_host, ping_host->sid, ping_host->host, ping_host->fd); - abort(); - break; - } - - return ret; -} - -static void _fast_ping_remove_all(void) -{ - struct ping_host_struct *ping_host = NULL; - struct ping_host_struct *ping_host_tmp = NULL; - struct hlist_node *tmp = NULL; - int i; - - LIST_HEAD(remove_list); - - pthread_mutex_lock(&ping.map_lock); - hash_for_each_safe(ping.addrmap, i, tmp, ping_host, addr_node) - { - list_add_tail(&ping_host->action_list, &remove_list); - } - pthread_mutex_unlock(&ping.map_lock); - - list_for_each_entry_safe(ping_host, ping_host_tmp, &remove_list, action_list) - { - _fast_ping_host_remove(ping_host); - } -} - -static void _fast_ping_period_run(void) -{ - struct ping_host_struct *ping_host = NULL; - struct ping_host_struct *ping_host_tmp = NULL; - struct hlist_node *tmp = NULL; - int i = 0; - struct timeval now; - struct timezone tz; - struct timeval interval; - int64_t millisecond; - gettimeofday(&now, &tz); - LIST_HEAD(action); - - pthread_mutex_lock(&ping.map_lock); - hash_for_each_safe(ping.addrmap, i, tmp, ping_host, addr_node) - { - if (ping_host->run == 0) { - continue; - } - - interval = now; - tv_sub(&interval, &ping_host->last); - millisecond = interval.tv_sec * 1000 + interval.tv_usec / 1000; - if (millisecond >= ping_host->timeout && ping_host->send == 1) { - list_add_tail(&ping_host->action_list, &action); - _fast_ping_host_get(ping_host); - continue; - } - - if (millisecond < ping_host->interval) { - continue; - } - - list_add_tail(&ping_host->action_list, &action); - _fast_ping_host_get(ping_host); - } - pthread_mutex_unlock(&ping.map_lock); - - list_for_each_entry_safe(ping_host, ping_host_tmp, &action, action_list) - { - interval = now; - tv_sub(&interval, &ping_host->last); - millisecond = interval.tv_sec * 1000 + interval.tv_usec / 1000; - if (millisecond >= ping_host->timeout && ping_host->send == 1) { - ping_host->ping_callback(ping_host, ping_host->host, PING_RESULT_TIMEOUT, &ping_host->addr, ping_host->addr_len, ping_host->seq, ping_host->ttl, - &interval, ping_host->userptr); - ping_host->send = 0; - } - - if (millisecond < ping_host->interval) { - list_del(&ping_host->action_list); - _fast_ping_host_put(ping_host); - continue; - } - - if (ping_host->count > 0) { - if (ping_host->count == 1) { - _fast_ping_host_remove(ping_host); - list_del(&ping_host->action_list); - _fast_ping_host_put(ping_host); - continue; - } - ping_host->count--; - } - - _fast_ping_sendping(ping_host); - list_del(&ping_host->action_list); - _fast_ping_host_put(ping_host); - } -} - -static void *_fast_ping_work(void *arg) -{ - struct epoll_event events[PING_MAX_EVENTS + 1]; - int num; - int i; - unsigned long now = {0}; - struct timeval tvnow = {0}; - int sleep = 100; - int sleep_time = 0; - unsigned long expect_time = 0; - - sleep_time = sleep; - now = get_tick_count() - sleep; - expect_time = now + sleep; - while (ping.run) { - now = get_tick_count(); - if (now >= expect_time) { - _fast_ping_period_run(); - sleep_time = sleep - (now - expect_time); - if (sleep_time < 0) { - sleep_time = 0; - expect_time = now; - } - expect_time += sleep; - } - - num = epoll_wait(ping.epoll_fd, events, PING_MAX_EVENTS, sleep_time); - if (num < 0) { - usleep(100000); - continue; - } - - if (num == 0) { - continue; - } - - gettimeofday(&tvnow, NULL); - for (i = 0; i < num; i++) { - struct epoll_event *event = &events[i]; - struct ping_host_struct *ping_host = (struct ping_host_struct *)event->data.ptr; - _fast_ping_process(ping_host, event, &tvnow); - } - } - - close(ping.epoll_fd); - ping.epoll_fd = -1; - - return NULL; -} - -int fast_ping_init(void) -{ - pthread_attr_t attr; - int epollfd = -1; - int ret; - bool_print_log = 1; - - if (ping.epoll_fd > 0) { - return -1; - } - - memset(&ping, 0, sizeof(ping)); - pthread_attr_init(&attr); - - epollfd = epoll_create1(EPOLL_CLOEXEC); - if (epollfd < 0) { - tlog(TLOG_ERROR, "create epoll failed, %s\n", strerror(errno)); - goto errout; - } - - pthread_mutex_init(&ping.map_lock, NULL); - pthread_mutex_init(&ping.lock, NULL); - hash_init(ping.addrmap); - ping.epoll_fd = epollfd; - ping.ident = (getpid() & 0XFFFF); - ping.run = 1; - ret = pthread_create(&ping.tid, &attr, _fast_ping_work, NULL); - if (ret != 0) { - tlog(TLOG_ERROR, "create ping work thread failed, %s\n", strerror(errno)); - goto errout; - } - - return 0; -errout: - if (ping.tid > 0) { - void *retval = NULL; - ping.run = 0; - pthread_join(ping.tid, &retval); - } - - if (epollfd) { - close(epollfd); - } - - pthread_mutex_destroy(&ping.lock); - pthread_mutex_destroy(&ping.map_lock); - - return -1; -} - -static void _fast_ping_close_fds(void) -{ - if (ping.fd_icmp > 0) { - close(ping.fd_icmp); - ping.fd_icmp = -1; - } - - if (ping.fd_icmp6 > 0) { - close(ping.fd_icmp6); - ping.fd_icmp6 = -1; - } - - if (ping.fd_udp > 0) { - close(ping.fd_udp); - ping.fd_udp = -1; - } - - if (ping.fd_udp6 > 0) { - close(ping.fd_udp6); - ping.fd_udp6 = -1; - } -} - -void fast_ping_exit(void) -{ - if (ping.tid > 0) { - void *ret = NULL; - ping.run = 0; - pthread_join(ping.tid, &ret); - } - - _fast_ping_close_fds(); - _fast_ping_remove_all(); - - pthread_mutex_destroy(&ping.lock); - pthread_mutex_destroy(&ping.map_lock); -} +/************************************************************************* + * + * Copyright (C) 2018-2020 Ruilin Peng (Nick) . + * + * smartdns is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * smartdns is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "fast_ping.h" +#include "atomic.h" +#include "hashtable.h" +#include "tlog.h" +#include "util.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define PING_MAX_EVENTS 128 +#define PING_MAX_HOSTLEN 128 +#define ICMP_PACKET_SIZE (1024 * 64) +#define ICMP_INPACKET_SIZE 1024 +#define IPV4_ADDR_LEN 4 +#define IPV6_ADDR_LEN 16 +#define SOCKET_PRIORITY (6) + +#ifndef ICMP_FILTER +#define ICMP_FILTER 1 +struct icmp_filter { + uint32_t data; +}; +#endif + +struct ping_dns_head { + unsigned short id; + unsigned short flag; + unsigned short qdcount; + unsigned short ancount; + unsigned short aucount; + unsigned short adcount; +} __attribute__((packed)); + +typedef enum FAST_PING_TYPE { + FAST_PING_ICMP = 1, + FAST_PING_ICMP6 = 2, + FAST_PING_TCP, + FAST_PING_UDP, + FAST_PING_UDP6, + FAST_PING_END, +} FAST_PING_TYPE; + +struct fast_ping_packet_msg { + struct timeval tv; + unsigned int sid; + unsigned int seq; + unsigned int cookie; +}; + +struct fast_ping_packet { + union { + struct icmp icmp; + struct icmp6_hdr icmp6; + }; + unsigned int ttl; + struct fast_ping_packet_msg msg; +}; + +struct ping_host_struct { + atomic_t ref; + atomic_t notified; + struct hlist_node addr_node; + struct list_head action_list; + FAST_PING_TYPE type; + + void *userptr; + fast_ping_result ping_callback; + char host[PING_MAX_HOSTLEN]; + + int fd; + unsigned int seq; + int ttl; + struct timeval last; + int interval; + int timeout; + int count; + int send; + int run; + unsigned int cookie; + unsigned int sid; + unsigned short port; + unsigned short ss_family; + union { + struct sockaddr addr; + struct sockaddr_in6 in6; + struct sockaddr_in in; + }; + socklen_t addr_len; + struct fast_ping_packet packet; +}; + +struct fast_ping_struct { + int run; + pthread_t tid; + pthread_mutex_t lock; + unsigned short ident; + + int epoll_fd; + int fd_icmp; + struct ping_host_struct icmp_host; + int fd_icmp6; + struct ping_host_struct icmp6_host; + int fd_udp; + struct ping_host_struct udp_host; + int fd_udp6; + struct ping_host_struct udp6_host; + + pthread_mutex_t map_lock; + DECLARE_HASHTABLE(addrmap, 6); +}; + +static struct fast_ping_struct ping; +static atomic_t ping_sid = ATOMIC_INIT(0); +static int bool_print_log = 1; + +static uint16_t _fast_ping_checksum(uint16_t *header, size_t len) +{ + uint32_t sum = 0; + int i; + + for (i = 0; i < len / sizeof(uint16_t); i++) { + sum += ntohs(header[i]); + } + + return htons(~((sum >> 16) + (sum & 0xffff))); +} + +static void _fast_ping_install_filter_v6(int sock) +{ + struct icmp6_filter icmp6_filter; + ICMP6_FILTER_SETBLOCKALL(&icmp6_filter); + ICMP6_FILTER_SETPASS(ICMP6_ECHO_REPLY, &icmp6_filter); + setsockopt(sock, IPPROTO_ICMPV6, ICMP6_FILTER, &icmp6_filter, sizeof(struct icmp6_filter)); + + static int once; + static struct sock_filter insns[] = { + BPF_STMT(BPF_LD | BPF_H | BPF_ABS, 4), /* Load icmp echo ident */ + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0xAAAA, 0, 1), /* Ours? */ + BPF_STMT(BPF_RET | BPF_K, ~0U), /* Yes, it passes. */ + BPF_STMT(BPF_LD | BPF_B | BPF_ABS, 0), /* Load icmp type */ + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, ICMP6_ECHO_REPLY, 1, 0), /* Echo? */ + BPF_STMT(BPF_RET | BPF_K, ~0U), /* No. It passes. This must not happen. */ + BPF_STMT(BPF_RET | BPF_K, 0), /* Echo with wrong ident. Reject. */ + }; + static struct sock_fprog filter = {sizeof insns / sizeof(insns[0]), insns}; + + if (once) { + return; + } + once = 1; + + /* Patch bpflet for current identifier. */ + insns[1] = (struct sock_filter)BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, htons(ping.ident), 0, 1); + + if (setsockopt(sock, SOL_SOCKET, SO_ATTACH_FILTER, &filter, sizeof(filter))) { + perror("WARNING: failed to install socket filter\n"); + } +} + +static void _fast_ping_install_filter_v4(int sock) +{ + static int once; + static struct sock_filter insns[] = { + BPF_STMT(BPF_LDX | BPF_B | BPF_MSH, 0), /* Skip IP header. F..g BSD... Look into ping6. */ + BPF_STMT(BPF_LD | BPF_H | BPF_IND, 4), /* Load icmp echo ident */ + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0xAAAA, 0, 1), /* Ours? */ + BPF_STMT(BPF_RET | BPF_K, ~0U), /* Yes, it passes. */ + BPF_STMT(BPF_LD | BPF_B | BPF_IND, 0), /* Load icmp type */ + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, ICMP_ECHOREPLY, 1, 0), /* Echo? */ + BPF_STMT(BPF_RET | BPF_K, 0xFFFFFFF), /* No. It passes. */ + BPF_STMT(BPF_RET | BPF_K, 0) /* Echo with wrong ident. Reject. */ + }; + + static struct sock_fprog filter = {sizeof insns / sizeof(insns[0]), insns}; + + if (once) { + return; + } + once = 1; + + /* Patch bpflet for current identifier. */ + insns[2] = (struct sock_filter)BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, htons(ping.ident), 0, 1); + + if (setsockopt(sock, SOL_SOCKET, SO_ATTACH_FILTER, &filter, sizeof(filter))) { + perror("WARNING: failed to install socket filter\n"); + } +} + +static int _fast_ping_sockaddr_ip_cmp(struct sockaddr *first_addr, socklen_t first_addr_len, + struct sockaddr *second_addr, socklen_t second_addr_len) +{ + if (first_addr_len != second_addr_len) { + return -1; + } + + if (first_addr->sa_family != second_addr->sa_family) { + return -1; + } + + switch (first_addr->sa_family) { + case AF_INET: { + struct sockaddr_in *first_addr_in = (struct sockaddr_in *)first_addr; + struct sockaddr_in *second_addr_in = (struct sockaddr_in *)second_addr; + if (memcmp(&first_addr_in->sin_addr.s_addr, &second_addr_in->sin_addr.s_addr, IPV4_ADDR_LEN) != 0) { + return -1; + } + } break; + case AF_INET6: { + struct sockaddr_in6 *first_addr_in6 = (struct sockaddr_in6 *)first_addr; + struct sockaddr_in6 *second_addr_in6 = (struct sockaddr_in6 *)second_addr; + if (memcmp(&first_addr_in6->sin6_addr.s6_addr, &second_addr_in6->sin6_addr.s6_addr, IPV4_ADDR_LEN) != 0) { + return -1; + } + } break; + default: + return -1; + } + + return 0; +} + +static uint32_t _fast_ping_hash_key(unsigned int sid, struct sockaddr *addr) +{ + uint32_t key = 0; + void *sin_addr = NULL; + unsigned int sin_addr_len = 0; + + switch (addr->sa_family) { + case AF_INET: { + struct sockaddr_in *addr_in; + addr_in = (struct sockaddr_in *)addr; + sin_addr = &addr_in->sin_addr.s_addr; + sin_addr_len = IPV4_ADDR_LEN; + } break; + case AF_INET6: { + struct sockaddr_in6 *addr_in6; + addr_in6 = (struct sockaddr_in6 *)addr; + if (IN6_IS_ADDR_V4MAPPED(&addr_in6->sin6_addr)) { + sin_addr = addr_in6->sin6_addr.s6_addr + 12; + sin_addr_len = IPV4_ADDR_LEN; + } else { + sin_addr = addr_in6->sin6_addr.s6_addr; + sin_addr_len = IPV6_ADDR_LEN; + } + } break; + default: + goto errout; + break; + } + if (sin_addr == NULL) { + return -1; + } + + key = jhash(sin_addr, sin_addr_len, 0); + key = jhash(&sid, sizeof(sid), key); + + return key; +errout: + return -1; +} + +static struct addrinfo *_fast_ping_getaddr(const char *host, const char *port, int type, int protocol) +{ + struct addrinfo hints; + struct addrinfo *result = NULL; + int errcode = 0; + + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = type; + hints.ai_protocol = protocol; + errcode = getaddrinfo(host, port, &hints, &result); + if (errcode != 0) { + tlog(TLOG_ERROR, "get addr info failed. host:%s, port: %s, error %s\n", host, port, gai_strerror(errcode)); + goto errout; + } + + return result; +errout: + if (result) { + freeaddrinfo(result); + } + return NULL; +} + +static int _fast_ping_getdomain(const char *host) +{ + struct addrinfo hints; + struct addrinfo *result = NULL; + int domain = -1; + + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + hints.ai_protocol = 0; + if (getaddrinfo(host, NULL, &hints, &result) != 0) { + tlog(TLOG_ERROR, "get addr info failed. %s\n", strerror(errno)); + goto errout; + } + + domain = result->ai_family; + + freeaddrinfo(result); + + return domain; +errout: + if (result) { + freeaddrinfo(result); + } + return -1; +} + +static void _fast_ping_host_get(struct ping_host_struct *ping_host) +{ + if (atomic_inc_return(&ping_host->ref) <= 0) { + tlog(TLOG_ERROR, "BUG: ping host ref is invalid, host: %s", ping_host->host); + abort(); + } +} + +static void _fast_ping_close_host_sock(struct ping_host_struct *ping_host) +{ + if (ping_host->fd < 0) { + return; + } + struct epoll_event *event; + event = (struct epoll_event *)1; + epoll_ctl(ping.epoll_fd, EPOLL_CTL_DEL, ping_host->fd, event); + close(ping_host->fd); + ping_host->fd = -1; +} + +static void _fast_ping_host_put(struct ping_host_struct *ping_host) +{ + if (!atomic_dec_and_test(&ping_host->ref)) { + return; + } + + _fast_ping_close_host_sock(ping_host); + + pthread_mutex_lock(&ping.map_lock); + hash_del(&ping_host->addr_node); + pthread_mutex_unlock(&ping.map_lock); + + if (atomic_inc_return(&ping_host->notified) == 1) { + struct timeval tv; + tv.tv_sec = 0; + tv.tv_usec = 0; + + ping_host->ping_callback(ping_host, ping_host->host, PING_RESULT_END, &ping_host->addr, ping_host->addr_len, + ping_host->seq, ping_host->ttl, &tv, ping_host->userptr); + } + + tlog(TLOG_DEBUG, "ping end, id %d", ping_host->sid); + // memset(ping_host, 0, sizeof(*ping_host)); + ping_host->type = FAST_PING_END; + free(ping_host); +} + +static void _fast_ping_host_remove(struct ping_host_struct *ping_host) +{ + _fast_ping_close_host_sock(ping_host); + + pthread_mutex_lock(&ping.map_lock); + if (!hash_hashed(&ping_host->addr_node)) { + pthread_mutex_unlock(&ping.map_lock); + return; + } + hash_del(&ping_host->addr_node); + + pthread_mutex_unlock(&ping.map_lock); + + if (atomic_inc_return(&ping_host->notified) == 1) { + struct timeval tv; + tv.tv_sec = 0; + tv.tv_usec = 0; + + ping_host->ping_callback(ping_host, ping_host->host, PING_RESULT_END, &ping_host->addr, ping_host->addr_len, + ping_host->seq, ping_host->ttl, &tv, ping_host->userptr); + } + + _fast_ping_host_put(ping_host); +} + +static int _fast_ping_sendping_v6(struct ping_host_struct *ping_host) +{ + struct fast_ping_packet *packet = &ping_host->packet; + struct icmp6_hdr *icmp6 = &packet->icmp6; + int len = 0; + + ping_host->seq++; + memset(icmp6, 0, sizeof(*icmp6)); + icmp6->icmp6_type = ICMP6_ECHO_REQUEST; + icmp6->icmp6_code = 0; + icmp6->icmp6_cksum = 0; + icmp6->icmp6_id = ping.ident; + icmp6->icmp6_seq = htons(ping_host->seq); + + gettimeofday(&packet->msg.tv, NULL); + gettimeofday(&ping_host->last, NULL); + packet->msg.sid = ping_host->sid; + packet->msg.cookie = ping_host->cookie; + packet->msg.seq = ping_host->seq; + icmp6->icmp6_cksum = _fast_ping_checksum((void *)packet, sizeof(struct fast_ping_packet)); + + len = sendto(ping.fd_icmp6, &ping_host->packet, sizeof(struct fast_ping_packet), 0, + (struct sockaddr *)&ping_host->addr, ping_host->addr_len); + if (len < 0 || len != sizeof(struct fast_ping_packet)) { + int err = errno; + if (errno == ENETUNREACH || errno == EINVAL) { + goto errout; + } + + if (errno == EACCES) { + if (bool_print_log == 0) { + goto errout; + } + bool_print_log = 0; + } + + char ping_host_name[PING_MAX_HOSTLEN]; + tlog(TLOG_ERROR, "sendto %s, id %d, %s", + gethost_by_addr(ping_host_name, sizeof(ping_host_name), (struct sockaddr *)&ping_host->addr), + ping_host->sid, strerror(err)); + goto errout; + } + + return 0; + +errout: + return -1; +} + +static int _fast_ping_sendping_v4(struct ping_host_struct *ping_host) +{ + struct fast_ping_packet *packet = &ping_host->packet; + struct icmp *icmp = &packet->icmp; + int len; + + ping_host->seq++; + memset(icmp, 0, sizeof(*icmp)); + icmp->icmp_type = ICMP_ECHO; + icmp->icmp_code = 0; + icmp->icmp_cksum = 0; + icmp->icmp_id = ping.ident; + icmp->icmp_seq = htons(ping_host->seq); + + gettimeofday(&packet->msg.tv, NULL); + gettimeofday(&ping_host->last, NULL); + packet->msg.sid = ping_host->sid; + packet->msg.seq = ping_host->seq; + packet->msg.cookie = ping_host->cookie; + icmp->icmp_cksum = _fast_ping_checksum((void *)packet, sizeof(struct fast_ping_packet)); + + len = sendto(ping.fd_icmp, packet, sizeof(struct fast_ping_packet), 0, (struct sockaddr *)&ping_host->addr, + ping_host->addr_len); + if (len < 0 || len != sizeof(struct fast_ping_packet)) { + int err = errno; + if (errno == ENETUNREACH || errno == EINVAL) { + goto errout; + } + char ping_host_name[PING_MAX_HOSTLEN]; + tlog(TLOG_ERROR, "sendto %s, id %d, %s", + gethost_by_addr(ping_host_name, sizeof(ping_host_name), (struct sockaddr *)&ping_host->addr), + ping_host->sid, strerror(err)); + goto errout; + } + + return 0; + +errout: + return -1; +} + +static int _fast_ping_sendping_udp(struct ping_host_struct *ping_host) +{ + struct ping_dns_head dns_head; + int len; + int flag = 0; + int fd = 0; + + flag |= (0 << 15) & 0x8000; + flag |= (2 << 11) & 0x7800; + flag |= (0 << 10) & 0x0400; + flag |= (0 << 9) & 0x0200; + flag |= (0 << 8) & 0x0100; + flag |= (0 << 7) & 0x0080; + flag |= (0 << 0) & 0x000F; + + if (ping_host->type == FAST_PING_UDP) { + fd = ping.fd_udp; + } else if (ping_host->type == FAST_PING_UDP6) { + fd = ping.fd_udp6; + } else { + return -1; + } + + ping_host->seq++; + memset(&dns_head, 0, sizeof(dns_head)); + dns_head.id = htons(ping_host->sid); + dns_head.flag = flag; + gettimeofday(&ping_host->last, NULL); + len = sendto(fd, &dns_head, sizeof(dns_head), 0, (struct sockaddr *)&ping_host->addr, ping_host->addr_len); + if (len < 0 || len != sizeof(dns_head)) { + int err = errno; + if (errno == ENETUNREACH || errno == EINVAL) { + goto errout; + } + char ping_host_name[PING_MAX_HOSTLEN]; + tlog(TLOG_ERROR, "sendto %s, id %d, %s", + gethost_by_addr(ping_host_name, sizeof(ping_host_name), (struct sockaddr *)&ping_host->addr), + ping_host->sid, strerror(err)); + goto errout; + } + + return 0; + +errout: + return -1; +} + +static int _fast_ping_sendping_tcp(struct ping_host_struct *ping_host) +{ + struct epoll_event event; + int flags; + int fd = -1; + int yes = 1; + const int priority = SOCKET_PRIORITY; + const int ip_tos = IP_TOS; + + _fast_ping_close_host_sock(ping_host); + + fd = socket(ping_host->ss_family, SOCK_STREAM, 0); + if (fd < 0) { + goto errout; + } + + flags = fcntl(fd, F_GETFL, 0); + fcntl(fd, F_SETFL, flags | O_NONBLOCK); + setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(yes)); + setsockopt(fd, SOL_SOCKET, SO_PRIORITY, &priority, sizeof(priority)); + setsockopt(fd, IPPROTO_IP, IP_TOS, &ip_tos, sizeof(ip_tos)); + set_sock_keepalive(fd, 0, 0, 0); + /* Set the socket lingering so we will RST connections instead of wasting + * bandwidth with the four-step close + */ + set_sock_lingertime(fd, 0); + + ping_host->seq++; + if (connect(fd, (struct sockaddr *)&ping_host->addr, ping_host->addr_len) != 0) { + if (errno != EINPROGRESS) { + char ping_host_name[PING_MAX_HOSTLEN]; + if (errno == ENETUNREACH || errno == EINVAL) { + goto errout; + } + + if (errno == EACCES) { + if (bool_print_log == 0) { + goto errout; + } + bool_print_log = 0; + } + + tlog(TLOG_ERROR, "connect %s, id %d, %s", + gethost_by_addr(ping_host_name, sizeof(ping_host_name), (struct sockaddr *)&ping_host->addr), + ping_host->sid, strerror(errno)); + goto errout; + } + } + + gettimeofday(&ping_host->last, NULL); + ping_host->fd = fd; + memset(&event, 0, sizeof(event)); + event.events = EPOLLIN | EPOLLOUT | EPOLLERR; + event.data.ptr = ping_host; + if (epoll_ctl(ping.epoll_fd, EPOLL_CTL_ADD, fd, &event) != 0) { + ping_host->fd = -1; + goto errout; + } + + return 0; + +errout: + if (fd > 0) { + close(fd); + ping_host->fd = -1; + } + return -1; +} + +static int _fast_ping_sendping(struct ping_host_struct *ping_host) +{ + int ret = -1; + gettimeofday(&ping_host->last, NULL); + + if (ping_host->type == FAST_PING_ICMP) { + ret = _fast_ping_sendping_v4(ping_host); + } else if (ping_host->type == FAST_PING_ICMP6) { + ret = _fast_ping_sendping_v6(ping_host); + } else if (ping_host->type == FAST_PING_TCP) { + ret = _fast_ping_sendping_tcp(ping_host); + } else if (ping_host->type == FAST_PING_UDP || ping_host->type == FAST_PING_UDP6) { + ret = _fast_ping_sendping_udp(ping_host); + } + + ping_host->send = 1; + + if (ret != 0) { + return ret; + } + + return 0; +} + +static int _fast_ping_create_icmp_sock(FAST_PING_TYPE type) +{ + int fd = -1; + struct ping_host_struct *icmp_host = NULL; + struct epoll_event event; + int buffsize = 64 * 1024; + socklen_t optlen = sizeof(buffsize); + const int val = 255; + const int on = 1; + const int ip_tos = (IPTOS_LOWDELAY | IPTOS_RELIABILITY); + + switch (type) { + case FAST_PING_ICMP: + fd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); + if (fd < 0) { + tlog(TLOG_ERROR, "create icmp socket failed, %s\n", strerror(errno)); + goto errout; + } + _fast_ping_install_filter_v4(fd); + icmp_host = &ping.icmp_host; + break; + case FAST_PING_ICMP6: + fd = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6); + if (fd < 0) { + tlog(TLOG_ERROR, "create icmp socket failed, %s\n", strerror(errno)); + goto errout; + } + _fast_ping_install_filter_v6(fd); + setsockopt(fd, IPPROTO_IPV6, IPV6_RECVHOPLIMIT, &on, sizeof(on)); + setsockopt(fd, IPPROTO_IPV6, IPV6_2292HOPLIMIT, &on, sizeof(on)); + setsockopt(fd, IPPROTO_IPV6, IPV6_HOPLIMIT, &on, sizeof(on)); + icmp_host = &ping.icmp6_host; + break; + default: + return -1; + } + + struct icmp_filter filt; + filt.data = ~((1 << ICMP_SOURCE_QUENCH) | (1 << ICMP_DEST_UNREACH) | (1 << ICMP_TIME_EXCEEDED) | + (1 << ICMP_PARAMETERPROB) | (1 << ICMP_REDIRECT) | (1 << ICMP_ECHOREPLY)); + setsockopt(fd, SOL_RAW, ICMP_FILTER, &filt, sizeof filt); + setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const char *)&buffsize, optlen); + setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (const char *)&buffsize, optlen); + setsockopt(fd, SOL_IP, IP_TTL, &val, sizeof(val)); + setsockopt(fd, IPPROTO_IP, IP_TOS, &ip_tos, sizeof(ip_tos)); + + memset(&event, 0, sizeof(event)); + event.events = EPOLLIN; + event.data.ptr = icmp_host; + if (epoll_ctl(ping.epoll_fd, EPOLL_CTL_ADD, fd, &event) != 0) { + goto errout; + } + + icmp_host->fd = fd; + icmp_host->type = type; + return fd; + +errout: + close(fd); + return -1; +} + +static int _fast_ping_create_icmp(FAST_PING_TYPE type) +{ + int fd = 0; + int *set_fd = NULL; + + pthread_mutex_lock(&ping.lock); + switch (type) { + case FAST_PING_ICMP: + set_fd = &ping.fd_icmp; + break; + case FAST_PING_ICMP6: + set_fd = &ping.fd_icmp6; + break; + default: + goto errout; + break; + } + + if (*set_fd > 0) { + goto out; + } + + fd = _fast_ping_create_icmp_sock(type); + if (fd < 0) { + goto errout; + } + + *set_fd = fd; +out: + pthread_mutex_unlock(&ping.lock); + return *set_fd; +errout: + if (fd > 0) { + close(fd); + } + pthread_mutex_unlock(&ping.lock); + return -1; +} + +static int _fast_ping_create_udp_sock(FAST_PING_TYPE type) +{ + int fd = -1; + struct ping_host_struct *udp_host = NULL; + struct epoll_event event; + const int val = 255; + const int on = 1; + const int ip_tos = (IPTOS_LOWDELAY | IPTOS_RELIABILITY); + + switch (type) { + case FAST_PING_UDP: + fd = socket(AF_INET, SOCK_DGRAM, 0); + if (fd < 0) { + tlog(TLOG_ERROR, "create udp socket failed, %s\n", strerror(errno)); + goto errout; + } + + udp_host = &ping.udp_host; + udp_host->type = FAST_PING_UDP; + break; + case FAST_PING_UDP6: + fd = socket(AF_INET6, SOCK_DGRAM, 0); + if (fd < 0) { + tlog(TLOG_ERROR, "create udp socket failed, %s\n", strerror(errno)); + goto errout; + } + + udp_host = &ping.udp6_host; + udp_host->type = FAST_PING_UDP6; + setsockopt(fd, IPPROTO_IPV6, IPV6_RECVHOPLIMIT, &on, sizeof(on)); + setsockopt(fd, IPPROTO_IPV6, IPV6_2292HOPLIMIT, &on, sizeof(on)); + setsockopt(fd, IPPROTO_IPV6, IPV6_HOPLIMIT, &on, sizeof(on)); + break; + default: + return -1; + } + + setsockopt(fd, SOL_IP, IP_TTL, &val, sizeof(val)); + setsockopt(fd, IPPROTO_IP, IP_RECVTTL, &on, sizeof(on)); + setsockopt(fd, IPPROTO_IP, IP_TOS, &ip_tos, sizeof(ip_tos)); + + memset(&event, 0, sizeof(event)); + event.events = EPOLLIN; + event.data.ptr = udp_host; + if (epoll_ctl(ping.epoll_fd, EPOLL_CTL_ADD, fd, &event) != 0) { + goto errout; + } + + udp_host->fd = fd; + return fd; + +errout: + close(fd); + return -1; +} + +static int _fast_ping_create_udp(FAST_PING_TYPE type) +{ + int fd = 0; + int *set_fd = NULL; + + pthread_mutex_lock(&ping.lock); + switch (type) { + case FAST_PING_UDP: + set_fd = &ping.fd_udp; + break; + case FAST_PING_UDP6: + set_fd = &ping.fd_udp6; + break; + default: + goto errout; + break; + } + + if (*set_fd > 0) { + goto out; + } + + fd = _fast_ping_create_udp_sock(type); + if (fd < 0) { + goto errout; + } + + *set_fd = fd; +out: + pthread_mutex_unlock(&ping.lock); + return *set_fd; +errout: + if (fd > 0) { + close(fd); + } + pthread_mutex_unlock(&ping.lock); + return -1; +} + +static void _fast_ping_print_result(struct ping_host_struct *ping_host, const char *host, FAST_PING_RESULT result, + struct sockaddr *addr, socklen_t addr_len, int seqno, int ttl, struct timeval *tv, + void *userptr) +{ + if (result == PING_RESULT_RESPONSE) { + double rtt = tv->tv_sec * 1000.0 + tv->tv_usec / 1000.0; + tlog(TLOG_INFO, "from %15s: seq=%d ttl=%d time=%.3f\n", host, seqno, ttl, rtt); + } else if (result == PING_RESULT_TIMEOUT) { + tlog(TLOG_INFO, "from %15s: seq=%d timeout\n", host, seqno); + } else if (result == PING_RESULT_END) { + fast_ping_stop(ping_host); + } +} + +static int _fast_ping_get_addr_by_icmp(const char *ip_str, int port, struct addrinfo **out_gai, + FAST_PING_TYPE *out_ping_type) +{ + struct addrinfo *gai = NULL; + int socktype = 0; + int domain = -1; + FAST_PING_TYPE ping_type; + int sockproto = 0; + char *service = NULL; + + socktype = SOCK_RAW; + domain = _fast_ping_getdomain(ip_str); + if (domain < 0) { + goto errout; + } + + switch (domain) { + case AF_INET: + sockproto = IPPROTO_ICMP; + ping_type = FAST_PING_ICMP; + break; + case AF_INET6: + sockproto = IPPROTO_ICMPV6; + ping_type = FAST_PING_ICMP6; + break; + default: + goto errout; + break; + } + + if (_fast_ping_create_icmp(ping_type) < 0) { + goto errout; + } + + gai = _fast_ping_getaddr(ip_str, service, socktype, sockproto); + if (gai == NULL) { + goto errout; + } + + *out_gai = gai; + *out_ping_type = ping_type; + + return 0; +errout: + if (gai) { + freeaddrinfo(gai); + } + return -1; +} + +static int _fast_ping_get_addr_by_tcp(const char *ip_str, int port, struct addrinfo **out_gai, + FAST_PING_TYPE *out_ping_type) +{ + struct addrinfo *gai = NULL; + int socktype = 0; + FAST_PING_TYPE ping_type; + int sockproto = 0; + char *service = NULL; + char port_str[MAX_IP_LEN]; + + if (port <= 0) { + port = 80; + } + + sockproto = 0; + socktype = SOCK_STREAM; + snprintf(port_str, MAX_IP_LEN, "%d", port); + service = port_str; + ping_type = FAST_PING_TCP; + + gai = _fast_ping_getaddr(ip_str, service, socktype, sockproto); + if (gai == NULL) { + goto errout; + } + + *out_gai = gai; + *out_ping_type = ping_type; + + return 0; +errout: + if (gai) { + freeaddrinfo(gai); + } + return -1; +} + +static int _fast_ping_get_addr_by_dns(const char *ip_str, int port, struct addrinfo **out_gai, + FAST_PING_TYPE *out_ping_type) +{ + struct addrinfo *gai = NULL; + int socktype = 0; + FAST_PING_TYPE ping_type; + int sockproto = 0; + char port_str[MAX_IP_LEN]; + int domain = -1; + char *service = NULL; + + if (port <= 0) { + port = 53; + } + + domain = _fast_ping_getdomain(ip_str); + if (domain < 0) { + goto errout; + } + + switch (domain) { + case AF_INET: + ping_type = FAST_PING_UDP; + break; + case AF_INET6: + ping_type = FAST_PING_UDP6; + break; + default: + goto errout; + break; + } + + sockproto = 0; + socktype = SOCK_DGRAM; + snprintf(port_str, MAX_IP_LEN, "%d", port); + service = port_str; + + if (_fast_ping_create_udp(ping_type) < 0) { + goto errout; + } + + gai = _fast_ping_getaddr(ip_str, service, socktype, sockproto); + if (gai == NULL) { + goto errout; + } + + *out_gai = gai; + *out_ping_type = ping_type; + + return 0; +errout: + if (gai) { + freeaddrinfo(gai); + } + return -1; +} + +static int _fast_ping_get_addr_by_type(PING_TYPE type, const char *ip_str, int port, struct addrinfo **out_gai, + FAST_PING_TYPE *out_ping_type) +{ + switch (type) { + case PING_TYPE_ICMP: + return _fast_ping_get_addr_by_icmp(ip_str, port, out_gai, out_ping_type); + break; + case PING_TYPE_TCP: + return _fast_ping_get_addr_by_tcp(ip_str, port, out_gai, out_ping_type); + break; + case PING_TYPE_DNS: + return _fast_ping_get_addr_by_dns(ip_str, port, out_gai, out_ping_type); + break; + default: + break; + } + + return -1; +} + +struct ping_host_struct *fast_ping_start(PING_TYPE type, const char *host, int count, int interval, int timeout, + fast_ping_result ping_callback, void *userptr) +{ + struct ping_host_struct *ping_host = NULL; + struct addrinfo *gai = NULL; + uint32_t addrkey; + char ip_str[PING_MAX_HOSTLEN]; + int port = -1; + FAST_PING_TYPE ping_type = FAST_PING_END; + unsigned int seed; + int ret = 0; + + if (parse_ip(host, ip_str, &port) != 0) { + goto errout; + } + + ret = _fast_ping_get_addr_by_type(type, ip_str, port, &gai, &ping_type); + if (ret != 0) { + tlog(TLOG_ERROR, "get addr by type failed, host: %s", host); + goto errout; + } + + ping_host = malloc(sizeof(*ping_host)); + if (ping_host == NULL) { + goto errout; + } + + memset(ping_host, 0, sizeof(*ping_host)); + safe_strncpy(ping_host->host, host, PING_MAX_HOSTLEN); + ping_host->fd = -1; + ping_host->timeout = timeout; + ping_host->count = count; + ping_host->type = ping_type; + ping_host->userptr = userptr; + atomic_set(&ping_host->ref, 0); + atomic_set(&ping_host->notified, 0); + ping_host->sid = atomic_inc_return(&ping_sid); + seed = ping_host->sid; + ping_host->cookie = rand_r(&seed); + ping_host->run = 0; + if (ping_callback) { + ping_host->ping_callback = ping_callback; + } else { + ping_host->ping_callback = _fast_ping_print_result; + } + ping_host->interval = (timeout > interval) ? timeout : interval; + ping_host->addr_len = gai->ai_addrlen; + ping_host->port = port; + ping_host->ss_family = gai->ai_family; + if (gai->ai_addrlen > sizeof(struct sockaddr_in6)) { + goto errout; + } + memcpy(&ping_host->addr, gai->ai_addr, gai->ai_addrlen); + + tlog(TLOG_DEBUG, "ping %s, id = %d", host, ping_host->sid); + + addrkey = _fast_ping_hash_key(ping_host->sid, &ping_host->addr); + pthread_mutex_lock(&ping.map_lock); + _fast_ping_host_get(ping_host); + hash_add(ping.addrmap, &ping_host->addr_node, addrkey); + pthread_mutex_unlock(&ping.map_lock); + + _fast_ping_host_get(ping_host); + if (_fast_ping_sendping(ping_host) != 0) { + goto errout_remove; + } + + ping_host->run = 1; + freeaddrinfo(gai); + return ping_host; +errout_remove: + fast_ping_stop(ping_host); + ping_host = NULL; +errout: + if (gai) { + freeaddrinfo(gai); + } + + if (ping_host) { + free(ping_host); + } + + return NULL; +} + +int fast_ping_stop(struct ping_host_struct *ping_host) +{ + if (ping_host == NULL) { + return 0; + } + + atomic_inc_return(&ping_host->notified); + _fast_ping_host_remove(ping_host); + _fast_ping_host_put(ping_host); + return 0; +} + +static void tv_sub(struct timeval *out, struct timeval *in) +{ + if ((out->tv_usec -= in->tv_usec) < 0) { /* out -= in */ + --out->tv_sec; + out->tv_usec += 1000000; + } + out->tv_sec -= in->tv_sec; +} + +static struct fast_ping_packet *_fast_ping_icmp6_packet(struct ping_host_struct *ping_host, struct msghdr *msg, + u_char *packet_data, int data_len) +{ + int icmp_len; + struct fast_ping_packet *packet = (struct fast_ping_packet *)packet_data; + struct icmp6_hdr *icmp6 = &packet->icmp6; + struct cmsghdr *c; + int hops = 0; + + for (c = CMSG_FIRSTHDR(msg); c; c = CMSG_NXTHDR(msg, c)) { + if (c->cmsg_level != IPPROTO_IPV6) + continue; + switch (c->cmsg_type) { + case IPV6_HOPLIMIT: +#ifdef IPV6_2292HOPLIMIT + case IPV6_2292HOPLIMIT: +#endif + if (c->cmsg_len < CMSG_LEN(sizeof(int))) + continue; + memcpy(&hops, CMSG_DATA(c), sizeof(hops)); + } + } + + packet->ttl = hops; + if (icmp6->icmp6_type != ICMP6_ECHO_REPLY) { + tlog(TLOG_DEBUG, "icmp6 type faild, %d:%d", icmp6->icmp6_type, ICMP6_ECHO_REPLY); + return NULL; + } + + icmp_len = data_len; + if (icmp_len < 16) { + tlog(TLOG_ERROR, "length is invalid, %d", icmp_len); + return NULL; + } + + if (icmp6->icmp6_id != ping.ident) { + tlog(TLOG_ERROR, "ident failed, %d:%d", icmp6->icmp6_id, ping.ident); + return NULL; + } + + return packet; +} + +static struct fast_ping_packet *_fast_ping_icmp_packet(struct ping_host_struct *ping_host, struct msghdr *msg, + u_char *packet_data, int data_len) +{ + struct ip *ip = (struct ip *)packet_data; + struct fast_ping_packet *packet; + struct icmp *icmp; + int hlen; + int icmp_len; + + if (ip->ip_p != IPPROTO_ICMP) { + tlog(TLOG_ERROR, "ip type faild, %d:%d", ip->ip_p, IPPROTO_ICMP); + return NULL; + } + + hlen = ip->ip_hl << 2; + packet = (struct fast_ping_packet *)(packet_data + hlen); + icmp = &packet->icmp; + icmp_len = data_len - hlen; + packet->ttl = ip->ip_ttl; + + if (icmp_len < 16) { + tlog(TLOG_ERROR, "length is invalid, %d", icmp_len); + return NULL; + } + + if (icmp->icmp_type != ICMP_ECHOREPLY) { + tlog(TLOG_DEBUG, "icmp type faild, %d:%d", icmp->icmp_type, ICMP_ECHOREPLY); + return NULL; + } + + if (icmp->icmp_id != ping.ident) { + tlog(TLOG_ERROR, "ident failed, %d:%d", icmp->icmp_id, ping.ident); + return NULL; + } + + return packet; +} + +static struct fast_ping_packet *_fast_ping_recv_packet(struct ping_host_struct *ping_host, struct msghdr *msg, + u_char *inpacket, int len, struct timeval *tvrecv) +{ + struct fast_ping_packet *packet = NULL; + + if (ping_host->type == FAST_PING_ICMP6) { + packet = _fast_ping_icmp6_packet(ping_host, msg, inpacket, len); + if (packet == NULL) { + goto errout; + } + } else if (ping_host->type == FAST_PING_ICMP) { + packet = _fast_ping_icmp_packet(ping_host, msg, inpacket, len); + if (packet == NULL) { + goto errout; + } + } else { + tlog(TLOG_ERROR, "ping host type is invalid, %d", ping_host->type); + goto errout; + } + + return packet; +errout: + return NULL; +} + +static int _fast_ping_process_icmp(struct ping_host_struct *ping_host, struct timeval *now) +{ + int len; + u_char inpacket[ICMP_INPACKET_SIZE]; + struct sockaddr_storage from; + struct ping_host_struct *recv_ping_host; + struct fast_ping_packet *packet = NULL; + socklen_t from_len = sizeof(from); + uint32_t addrkey; + struct timeval tvresult = *now; + struct timeval *tvsend = NULL; + unsigned int sid; + unsigned int seq; + unsigned int cookie; + struct msghdr msg; + struct iovec iov; + char ans_data[4096]; + + memset(&msg, 0, sizeof(msg)); + iov.iov_base = (char *)inpacket; + iov.iov_len = sizeof(inpacket); + msg.msg_name = &from; + msg.msg_namelen = sizeof(from); + msg.msg_iov = &iov; + msg.msg_iovlen = 1; + msg.msg_control = ans_data; + msg.msg_controllen = sizeof(ans_data); + + len = recvmsg(ping_host->fd, &msg, MSG_DONTWAIT); + if (len < 0) { + tlog(TLOG_ERROR, "recvfrom failed, %s\n", strerror(errno)); + goto errout; + } + + from_len = msg.msg_namelen; + packet = _fast_ping_recv_packet(ping_host, &msg, inpacket, len, now); + if (packet == NULL) { + char name[PING_MAX_HOSTLEN]; + tlog(TLOG_DEBUG, "recv ping packet from %s failed.", + gethost_by_addr(name, sizeof(name), (struct sockaddr *)&from)); + goto errout; + } + + tvsend = &packet->msg.tv; + sid = packet->msg.sid; + seq = packet->msg.seq; + cookie = packet->msg.cookie; + addrkey = _fast_ping_hash_key(sid, (struct sockaddr *)&from); + pthread_mutex_lock(&ping.map_lock); + hash_for_each_possible(ping.addrmap, recv_ping_host, addr_node, addrkey) + { + if (_fast_ping_sockaddr_ip_cmp(&recv_ping_host->addr, recv_ping_host->addr_len, (struct sockaddr *)&from, + from_len) == 0 && + recv_ping_host->sid == sid && recv_ping_host->cookie == cookie) { + _fast_ping_host_get(recv_ping_host); + break; + } + } + + pthread_mutex_unlock(&ping.map_lock); + + if (recv_ping_host == NULL) { + return -1; + } + + if (recv_ping_host->seq != seq) { + tlog(TLOG_ERROR, "seq num mismatch, expect %u, real %u", recv_ping_host->seq, seq); + _fast_ping_host_put(recv_ping_host); + return -1; + } + + recv_ping_host->ttl = packet->ttl; + tv_sub(&tvresult, tvsend); + if (recv_ping_host->ping_callback) { + recv_ping_host->ping_callback(recv_ping_host, recv_ping_host->host, PING_RESULT_RESPONSE, &recv_ping_host->addr, + recv_ping_host->addr_len, recv_ping_host->seq, recv_ping_host->ttl, &tvresult, + recv_ping_host->userptr); + } + + recv_ping_host->send = 0; + + if (recv_ping_host->count == 1) { + _fast_ping_host_remove(recv_ping_host); + } + + _fast_ping_host_put(recv_ping_host); + return 0; +errout: + return -1; +} + +static int _fast_ping_process_tcp(struct ping_host_struct *ping_host, struct epoll_event *event, struct timeval *now) +{ + struct timeval tvresult = *now; + struct timeval *tvsend = &ping_host->last; + int connect_error = 0; + socklen_t len = sizeof(connect_error); + + if (event->events & EPOLLIN || event->events & EPOLLERR) { + if (getsockopt(ping_host->fd, SOL_SOCKET, SO_ERROR, (char *)&connect_error, &len) != 0) { + goto errout; + } + + if (connect_error != 0 && connect_error != ECONNREFUSED) { + goto errout; + } + } + tv_sub(&tvresult, tvsend); + if (ping_host->ping_callback) { + ping_host->ping_callback(ping_host, ping_host->host, PING_RESULT_RESPONSE, &ping_host->addr, + ping_host->addr_len, ping_host->seq, ping_host->ttl, &tvresult, ping_host->userptr); + } + + ping_host->send = 0; + + _fast_ping_close_host_sock(ping_host); + + if (ping_host->count == 1) { + _fast_ping_host_remove(ping_host); + } + return 0; +errout: + _fast_ping_host_remove(ping_host); + + return -1; +} + +static int _fast_ping_process_udp(struct ping_host_struct *ping_host, struct timeval *now) +{ + int len; + u_char inpacket[ICMP_INPACKET_SIZE]; + struct sockaddr_storage from; + struct ping_host_struct *recv_ping_host; + struct ping_dns_head *dns_head = NULL; + socklen_t from_len = sizeof(from); + uint32_t addrkey; + struct timeval tvresult = *now; + struct timeval *tvsend = NULL; + unsigned int sid; + struct msghdr msg; + struct iovec iov; + char ans_data[4096]; + struct cmsghdr *cmsg; + int ttl = 0; + + memset(&msg, 0, sizeof(msg)); + iov.iov_base = (char *)inpacket; + iov.iov_len = sizeof(inpacket); + msg.msg_name = &from; + msg.msg_namelen = sizeof(from); + msg.msg_iov = &iov; + msg.msg_iovlen = 1; + msg.msg_control = ans_data; + msg.msg_controllen = sizeof(ans_data); + + len = recvmsg(ping_host->fd, &msg, MSG_DONTWAIT); + if (len < 0) { + tlog(TLOG_ERROR, "recvfrom failed, %s\n", strerror(errno)); + goto errout; + } + + for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) { + if (cmsg->cmsg_level == SOL_IP && cmsg->cmsg_type == IP_TTL) { + if (cmsg->cmsg_len >= sizeof(int)) { + int *ttlPtr = (int *)CMSG_DATA(cmsg); + ttl = *ttlPtr; + } + } else if (cmsg->cmsg_level == IPPROTO_IPV6 && cmsg->cmsg_type == IPV6_HOPLIMIT) { + if (cmsg->cmsg_len >= sizeof(int)) { + int *ttlPtr = (int *)CMSG_DATA(cmsg); + ttl = *ttlPtr; + } + } + } + + from_len = msg.msg_namelen; + dns_head = (struct ping_dns_head *)inpacket; + if (len < sizeof(*dns_head)) { + goto errout; + } + + sid = ntohs(dns_head->id); + addrkey = _fast_ping_hash_key(sid, (struct sockaddr *)&from); + pthread_mutex_lock(&ping.map_lock); + hash_for_each_possible(ping.addrmap, recv_ping_host, addr_node, addrkey) + { + if (_fast_ping_sockaddr_ip_cmp(&recv_ping_host->addr, recv_ping_host->addr_len, (struct sockaddr *)&from, + from_len) == 0 && + recv_ping_host->sid == sid) { + _fast_ping_host_get(recv_ping_host); + break; + } + } + + pthread_mutex_unlock(&ping.map_lock); + + if (recv_ping_host == NULL) { + return -1; + } + + recv_ping_host->ttl = ttl; + tvsend = &recv_ping_host->last; + tv_sub(&tvresult, tvsend); + if (recv_ping_host->ping_callback) { + recv_ping_host->ping_callback(recv_ping_host, recv_ping_host->host, PING_RESULT_RESPONSE, &recv_ping_host->addr, + recv_ping_host->addr_len, recv_ping_host->seq, recv_ping_host->ttl, &tvresult, + recv_ping_host->userptr); + } + + recv_ping_host->send = 0; + + if (recv_ping_host->count == 1) { + _fast_ping_host_remove(recv_ping_host); + } + + _fast_ping_host_put(recv_ping_host); + + return 0; +errout: + return -1; +} + +static int _fast_ping_process(struct ping_host_struct *ping_host, struct epoll_event *event, struct timeval *now) +{ + int ret = -1; + + switch (ping_host->type) { + case FAST_PING_ICMP6: + case FAST_PING_ICMP: + ret = _fast_ping_process_icmp(ping_host, now); + break; + case FAST_PING_TCP: + ret = _fast_ping_process_tcp(ping_host, event, now); + break; + case FAST_PING_UDP6: + case FAST_PING_UDP: + ret = _fast_ping_process_udp(ping_host, now); + break; + default: + tlog(TLOG_ERROR, "BUG: type error : %p, %d, %s, %d", ping_host, ping_host->sid, ping_host->host, ping_host->fd); + abort(); + break; + } + + return ret; +} + +static void _fast_ping_remove_all(void) +{ + struct ping_host_struct *ping_host = NULL; + struct ping_host_struct *ping_host_tmp = NULL; + struct hlist_node *tmp = NULL; + int i; + + LIST_HEAD(remove_list); + + pthread_mutex_lock(&ping.map_lock); + hash_for_each_safe(ping.addrmap, i, tmp, ping_host, addr_node) + { + list_add_tail(&ping_host->action_list, &remove_list); + } + pthread_mutex_unlock(&ping.map_lock); + + list_for_each_entry_safe(ping_host, ping_host_tmp, &remove_list, action_list) + { + _fast_ping_host_remove(ping_host); + } +} + +static void _fast_ping_period_run(void) +{ + struct ping_host_struct *ping_host = NULL; + struct ping_host_struct *ping_host_tmp = NULL; + struct hlist_node *tmp = NULL; + int i = 0; + struct timeval now; + struct timezone tz; + struct timeval interval; + int64_t millisecond; + gettimeofday(&now, &tz); + LIST_HEAD(action); + + pthread_mutex_lock(&ping.map_lock); + hash_for_each_safe(ping.addrmap, i, tmp, ping_host, addr_node) + { + if (ping_host->run == 0) { + continue; + } + + interval = now; + tv_sub(&interval, &ping_host->last); + millisecond = interval.tv_sec * 1000 + interval.tv_usec / 1000; + if (millisecond >= ping_host->timeout && ping_host->send == 1) { + list_add_tail(&ping_host->action_list, &action); + _fast_ping_host_get(ping_host); + continue; + } + + if (millisecond < ping_host->interval) { + continue; + } + + list_add_tail(&ping_host->action_list, &action); + _fast_ping_host_get(ping_host); + } + pthread_mutex_unlock(&ping.map_lock); + + list_for_each_entry_safe(ping_host, ping_host_tmp, &action, action_list) + { + interval = now; + tv_sub(&interval, &ping_host->last); + millisecond = interval.tv_sec * 1000 + interval.tv_usec / 1000; + if (millisecond >= ping_host->timeout && ping_host->send == 1) { + ping_host->ping_callback(ping_host, ping_host->host, PING_RESULT_TIMEOUT, &ping_host->addr, + ping_host->addr_len, ping_host->seq, ping_host->ttl, &interval, + ping_host->userptr); + ping_host->send = 0; + } + + if (millisecond < ping_host->interval) { + list_del(&ping_host->action_list); + _fast_ping_host_put(ping_host); + continue; + } + + if (ping_host->count > 0) { + if (ping_host->count == 1) { + _fast_ping_host_remove(ping_host); + list_del(&ping_host->action_list); + _fast_ping_host_put(ping_host); + continue; + } + ping_host->count--; + } + + _fast_ping_sendping(ping_host); + list_del(&ping_host->action_list); + _fast_ping_host_put(ping_host); + } +} + +static void *_fast_ping_work(void *arg) +{ + struct epoll_event events[PING_MAX_EVENTS + 1]; + int num; + int i; + unsigned long now = {0}; + struct timeval tvnow = {0}; + int sleep = 100; + int sleep_time = 0; + unsigned long expect_time = 0; + + sleep_time = sleep; + now = get_tick_count() - sleep; + expect_time = now + sleep; + while (ping.run) { + now = get_tick_count(); + if (now >= expect_time) { + _fast_ping_period_run(); + sleep_time = sleep - (now - expect_time); + if (sleep_time < 0) { + sleep_time = 0; + expect_time = now; + } + expect_time += sleep; + } + + num = epoll_wait(ping.epoll_fd, events, PING_MAX_EVENTS, sleep_time); + if (num < 0) { + usleep(100000); + continue; + } + + if (num == 0) { + continue; + } + + gettimeofday(&tvnow, NULL); + for (i = 0; i < num; i++) { + struct epoll_event *event = &events[i]; + struct ping_host_struct *ping_host = (struct ping_host_struct *)event->data.ptr; + _fast_ping_process(ping_host, event, &tvnow); + } + } + + close(ping.epoll_fd); + ping.epoll_fd = -1; + + return NULL; +} + +int fast_ping_init(void) +{ + pthread_attr_t attr; + int epollfd = -1; + int ret; + bool_print_log = 1; + + if (ping.epoll_fd > 0) { + return -1; + } + + memset(&ping, 0, sizeof(ping)); + pthread_attr_init(&attr); + + epollfd = epoll_create1(EPOLL_CLOEXEC); + if (epollfd < 0) { + tlog(TLOG_ERROR, "create epoll failed, %s\n", strerror(errno)); + goto errout; + } + + pthread_mutex_init(&ping.map_lock, NULL); + pthread_mutex_init(&ping.lock, NULL); + hash_init(ping.addrmap); + ping.epoll_fd = epollfd; + ping.ident = (getpid() & 0XFFFF); + ping.run = 1; + ret = pthread_create(&ping.tid, &attr, _fast_ping_work, NULL); + if (ret != 0) { + tlog(TLOG_ERROR, "create ping work thread failed, %s\n", strerror(errno)); + goto errout; + } + + return 0; +errout: + if (ping.tid > 0) { + void *retval = NULL; + ping.run = 0; + pthread_join(ping.tid, &retval); + } + + if (epollfd) { + close(epollfd); + } + + pthread_mutex_destroy(&ping.lock); + pthread_mutex_destroy(&ping.map_lock); + + return -1; +} + +static void _fast_ping_close_fds(void) +{ + if (ping.fd_icmp > 0) { + close(ping.fd_icmp); + ping.fd_icmp = -1; + } + + if (ping.fd_icmp6 > 0) { + close(ping.fd_icmp6); + ping.fd_icmp6 = -1; + } + + if (ping.fd_udp > 0) { + close(ping.fd_udp); + ping.fd_udp = -1; + } + + if (ping.fd_udp6 > 0) { + close(ping.fd_udp6); + ping.fd_udp6 = -1; + } +} + +void fast_ping_exit(void) +{ + if (ping.tid > 0) { + void *ret = NULL; + ping.run = 0; + pthread_join(ping.tid, &ret); + } + + _fast_ping_close_fds(); + _fast_ping_remove_all(); + + pthread_mutex_destroy(&ping.lock); + pthread_mutex_destroy(&ping.map_lock); +} diff --git a/release/src/router/smartdns/src/fast_ping.h b/release/src/router/smartdns/src/fast_ping.h index 16821068bd..b9124c3670 100644 --- a/release/src/router/smartdns/src/fast_ping.h +++ b/release/src/router/smartdns/src/fast_ping.h @@ -1,58 +1,60 @@ -/************************************************************************* - * - * Copyright (C) 2018-2020 Ruilin Peng (Nick) . - * - * smartdns is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * smartdns is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#ifndef FAST_PING_H -#define FAST_PING_H - -#include -#include -#ifdef __cpluscplus -extern "C" { -#endif - -typedef enum { - PING_TYPE_ICMP = 1, - PING_TYPE_TCP = 2, - PING_TYPE_DNS = 3, -} PING_TYPE; - -typedef enum { - PING_RESULT_RESPONSE = 1, - PING_RESULT_TIMEOUT = 2, - PING_RESULT_END = 3, -} FAST_PING_RESULT; - -struct ping_host_struct; -typedef void (*fast_ping_result)(struct ping_host_struct *ping_host, const char *host, FAST_PING_RESULT result, struct sockaddr *addr, socklen_t addr_len, - int seqno, int ttl, struct timeval *tv, void *userptr); - -/* start ping */ -struct ping_host_struct *fast_ping_start(PING_TYPE type, const char *host, int count, int interval, int timeout, fast_ping_result ping_callback, void *userptr); - -/* stop ping */ -int fast_ping_stop(struct ping_host_struct *ping_host); - -int fast_ping_init(void); - -void fast_ping_exit(void); - -#ifdef __cpluscplus -} -#endif - -#endif // !FAST_PING_H +/************************************************************************* + * + * Copyright (C) 2018-2020 Ruilin Peng (Nick) . + * + * smartdns is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * smartdns is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef FAST_PING_H +#define FAST_PING_H + +#include +#include +#ifdef __cpluscplus +extern "C" { +#endif + +typedef enum { + PING_TYPE_ICMP = 1, + PING_TYPE_TCP = 2, + PING_TYPE_DNS = 3, +} PING_TYPE; + +typedef enum { + PING_RESULT_RESPONSE = 1, + PING_RESULT_TIMEOUT = 2, + PING_RESULT_END = 3, +} FAST_PING_RESULT; + +struct ping_host_struct; +typedef void (*fast_ping_result)(struct ping_host_struct *ping_host, const char *host, FAST_PING_RESULT result, + struct sockaddr *addr, socklen_t addr_len, int seqno, int ttl, struct timeval *tv, + void *userptr); + +/* start ping */ +struct ping_host_struct *fast_ping_start(PING_TYPE type, const char *host, int count, int interval, int timeout, + fast_ping_result ping_callback, void *userptr); + +/* stop ping */ +int fast_ping_stop(struct ping_host_struct *ping_host); + +int fast_ping_init(void); + +void fast_ping_exit(void); + +#ifdef __cpluscplus +} +#endif + +#endif // !FAST_PING_H diff --git a/release/src/router/smartdns/src/http_parse.c b/release/src/router/smartdns/src/http_parse.c index 9aa7707d7f..57564c7b68 100644 --- a/release/src/router/smartdns/src/http_parse.c +++ b/release/src/router/smartdns/src/http_parse.c @@ -1,463 +1,463 @@ -/************************************************************************* - * - * Copyright (C) 2018-2020 Ruilin Peng (Nick) . - * - * smartdns is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * smartdns is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#include "http_parse.h" -#include "hash.h" -#include "hashtable.h" -#include "jhash.h" -#include "list.h" -#include -#include -#include - -struct http_head_fields { - struct hlist_node node; - struct list_head list; - - char *name; - char *value; -}; - -struct http_head { - HTTP_HEAD_TYPE head_type; - HTTP_METHOD method; - char *url; - char *version; - int code; - char *code_msg; - int buff_size; - int buff_len; - char *buff; - int head_ok; - int head_len; - char *data; - int data_len; - int expect_data_len; - struct http_head_fields field_head; - DECLARE_HASHTABLE(field_map, 4); -}; - -/* - * Returns: - * >=0 - success http data len - * -1 - Incomplete request - * -2 - parse failed - */ -struct http_head *http_head_init(int buffsize) -{ - struct http_head *http_head = NULL; - char *buffer = NULL; - - http_head = malloc(sizeof(*http_head)); - if (http_head == NULL) { - goto errout; - } - memset(http_head, 0, sizeof(*http_head)); - INIT_LIST_HEAD(&http_head->field_head.list); - hash_init(http_head->field_map); - - buffer = malloc(buffsize); - if (buffer == NULL) { - goto errout; - } - - http_head->buff = buffer; - http_head->buff_size = buffsize; - - return http_head; - -errout: - if (buffer) { - free(buffer); - } - - if (http_head) { - free(http_head); - } - - return NULL; -} - -struct http_head_fields *http_head_first_fields(struct http_head *http_head) -{ - struct http_head_fields *first = NULL; - first = list_first_entry(&http_head->field_head.list, struct http_head_fields, list); - - if (first->name == NULL && first->value == NULL) { - return NULL; - } - - return first; -} - -const char *http_head_get_fields_value(struct http_head *http_head, const char *name) -{ - unsigned long key; - struct http_head_fields *filed; - - key = hash_string(name); - hash_for_each_possible(http_head->field_map, filed, node, key) - { - if (strncmp(filed->name, name, 128) == 0) { - return filed->value; - } - } - - return NULL; -} - -struct http_head_fields *http_head_next_fields(struct http_head_fields *fields) -{ - struct http_head_fields *next = NULL; - next = list_next_entry(fields, list); - - if (next->name == NULL && next->value == NULL) { - return NULL; - } - - return next; -} - -int http_head_lookup_fields(struct http_head_fields *fields, const char **name, const char **value) -{ - if (fields == NULL) { - return -1; - } - - if (name) { - *name = fields->name; - } - - if (value) { - *value = fields->value; - } - - return 0; -} - -HTTP_METHOD http_head_get_method(struct http_head *http_head) -{ - return http_head->method; -} - -const char *http_head_get_url(struct http_head *http_head) -{ - return http_head->url; -} - -const char *http_head_get_httpversion(struct http_head *http_head) -{ - return http_head->version; -} - -int http_head_get_httpcode(struct http_head *http_head) -{ - return http_head->code; -} - -char *http_head_get_httpcode_msg(struct http_head *http_head) -{ - return http_head->code_msg; -} - -HTTP_HEAD_TYPE http_head_get_head_type(struct http_head *http_head) -{ - return http_head->head_type; -} - -char *http_head_get_data(struct http_head *http_head) -{ - return http_head->data; -} - -int http_head_get_data_len(struct http_head *http_head) -{ - return http_head->data_len; -} - -static int _http_head_add_fields(struct http_head *http_head, char *name, char *value) -{ - unsigned long key = 0; - struct http_head_fields *fields = NULL; - fields = malloc(sizeof(*fields)); - if (fields == NULL) { - return -1; - } - memset(fields, 0, sizeof(*fields)); - - fields->name = name; - fields->value = value; - - list_add_tail(&fields->list, &http_head->field_head.list); - key = hash_string(name); - hash_add(http_head->field_map, &fields->node, key); - - return 0; -} - -static int _http_head_parse_response(struct http_head *http_head, char *key, char *value) -{ - char *field_start = NULL; - char *tmp_ptr = NULL; - char *result = NULL; - char *ret_code = NULL; - - if (strstr(key, "HTTP/") == NULL) { - return -1; - } - - for (tmp_ptr = value; *tmp_ptr != 0; tmp_ptr++) { - if (field_start == NULL) { - field_start = tmp_ptr; - } - - if (*tmp_ptr == ' ') { - *tmp_ptr = '\0'; - if (ret_code == NULL) { - ret_code = field_start; - } else if (result == NULL) { - result = field_start; - break; - } - - field_start = NULL; - } - } - - if (field_start && result == NULL) { - result = field_start; - } - - if (ret_code == NULL || result == NULL) { - return -1; - } - - http_head->code = atol(ret_code); - http_head->code_msg = result; - http_head->version = key; - http_head->head_type = HTTP_HEAD_RESPONSE; - - return 0; -} - -static int _http_head_parse_request(struct http_head *http_head, char *key, char *value) -{ - int method = HTTP_METHOD_INVALID; - char *url = NULL; - char *version = NULL; - char *tmp_ptr = value; - char *field_start = NULL; - - if (strncmp(key, "GET", sizeof("GET")) == 0) { - method = HTTP_METHOD_GET; - } else if (strncmp(key, "POST", sizeof("POST")) == 0) { - method = HTTP_METHOD_POST; - } else if (strncmp(key, "PUT", sizeof("PUT")) == 0) { - method = HTTP_METHOD_PUT; - } else if (strncmp(key, "DELETE", sizeof("DELETE")) == 0) { - method = HTTP_METHOD_DELETE; - } else if (strncmp(key, "TRACE", sizeof("TRACE")) == 0) { - method = HTTP_METHOD_TRACE; - } else if (strncmp(key, "CONNECT", sizeof("CONNECT")) == 0) { - method = HTTP_METHOD_CONNECT; - } else { - return _http_head_parse_response(http_head, key, value); - } - - for (tmp_ptr = value; *tmp_ptr != 0; tmp_ptr++) { - if (field_start == NULL) { - field_start = tmp_ptr; - } - if (*tmp_ptr == ' ') { - *tmp_ptr = '\0'; - if (url == NULL) { - url = field_start; - } - - field_start = NULL; - } - } - - if (field_start && version == NULL) { - version = field_start; - } - - http_head->method = method; - http_head->url = url; - http_head->version = version; - http_head->head_type = HTTP_HEAD_REQUEST; - - return 0; -} - -static int _http_head_parse(struct http_head *http_head) -{ - int i = 0; - char *key = NULL; - char *value = NULL; - char *data; - int has_first_line = 0; - - int inkey = 1; - int invalue = 0; - - data = http_head->buff; - for (i = 0; i < http_head->head_len; i++, data++) { - if (inkey) { - if (key == NULL && *data != ' ' && *data != '\r' && *data != '\n') { - key = data; - continue; - } - - if (*data == ':' || *data == ' ') { - *data = '\0'; - inkey = 0; - invalue = 1; - continue; - } - } - - if (invalue) { - if (value == NULL && *data != ' ') { - value = data; - continue; - } - - if (*data == '\r' || *data == '\n') { - *data = '\0'; - inkey = 1; - invalue = 0; - } - } - - if (key && value && invalue == 0) { - if (has_first_line == 0) { - if (_http_head_parse_request(http_head, key, value) != 0) { - return -2; - } - - has_first_line = 1; - } else { - if (_http_head_add_fields(http_head, key, value) != 0) { - return -2; - } - } - - key = NULL; - value = NULL; - inkey = 1; - invalue = 0; - } - } - - return 0; -} - -int http_head_parse(struct http_head *http_head, const char *data, int data_len) -{ - int i = 0; - char *buff_end = NULL; - int left_size = 0; - int process_data_len = 0; - - left_size = http_head->buff_size - http_head->buff_len; - - if (left_size < data_len) { - return -3; - } - - buff_end = http_head->buff + http_head->buff_len; - if (http_head->head_ok == 0) { - for (i = 0; i < data_len; i++, data++) { - *(buff_end + i) = *data; - if (*data == '\n') { - if (http_head->buff_len + i < 2) { - continue; - } - - if (*(buff_end + i - 2) == '\n') { - http_head->head_ok = 1; - http_head->head_len = http_head->buff_len + i - 2; - i++; - buff_end += i; - data_len -= i; - data++; - if (_http_head_parse(http_head) != 0) { - return -2; - } - - const char *content_len = NULL; - content_len = http_head_get_fields_value(http_head, "Content-Length"); - if (content_len) { - http_head->expect_data_len = atol(content_len); - } else { - http_head->expect_data_len = 0; - } - - if (http_head->expect_data_len < 0) { - return -2; - } - - break; - } - } - } - - process_data_len += i; - if (http_head->head_ok == 0) { - // Read data again */ - http_head->buff_len += process_data_len; - return -1; - } - } - - if (http_head->head_ok == 1) { - int get_data_len = (http_head->expect_data_len > data_len) ? data_len : http_head->expect_data_len; - if (http_head->data == NULL) { - http_head->data = buff_end; - } - - memcpy(buff_end, data, get_data_len); - process_data_len += get_data_len; - http_head->data_len += get_data_len; - } - - http_head->buff_len += process_data_len; - if (http_head->data_len < http_head->expect_data_len) { - return -1; - } - - return process_data_len; -} - -void http_head_destroy(struct http_head *http_head) -{ - struct http_head_fields *fields, *tmp; - - list_for_each_entry_safe(fields, tmp, &http_head->field_head.list, list) - { - list_del(&fields->list); - free(fields); - } - - if (http_head->buff) { - free(http_head->buff); - } - - free(http_head); -} +/************************************************************************* + * + * Copyright (C) 2018-2020 Ruilin Peng (Nick) . + * + * smartdns is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * smartdns is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "http_parse.h" +#include "hash.h" +#include "hashtable.h" +#include "jhash.h" +#include "list.h" +#include +#include +#include + +struct http_head_fields { + struct hlist_node node; + struct list_head list; + + char *name; + char *value; +}; + +struct http_head { + HTTP_HEAD_TYPE head_type; + HTTP_METHOD method; + char *url; + char *version; + int code; + char *code_msg; + int buff_size; + int buff_len; + char *buff; + int head_ok; + int head_len; + char *data; + int data_len; + int expect_data_len; + struct http_head_fields field_head; + DECLARE_HASHTABLE(field_map, 4); +}; + +/* + * Returns: + * >=0 - success http data len + * -1 - Incomplete request + * -2 - parse failed + */ +struct http_head *http_head_init(int buffsize) +{ + struct http_head *http_head = NULL; + char *buffer = NULL; + + http_head = malloc(sizeof(*http_head)); + if (http_head == NULL) { + goto errout; + } + memset(http_head, 0, sizeof(*http_head)); + INIT_LIST_HEAD(&http_head->field_head.list); + hash_init(http_head->field_map); + + buffer = malloc(buffsize); + if (buffer == NULL) { + goto errout; + } + + http_head->buff = buffer; + http_head->buff_size = buffsize; + + return http_head; + +errout: + if (buffer) { + free(buffer); + } + + if (http_head) { + free(http_head); + } + + return NULL; +} + +struct http_head_fields *http_head_first_fields(struct http_head *http_head) +{ + struct http_head_fields *first = NULL; + first = list_first_entry(&http_head->field_head.list, struct http_head_fields, list); + + if (first->name == NULL && first->value == NULL) { + return NULL; + } + + return first; +} + +const char *http_head_get_fields_value(struct http_head *http_head, const char *name) +{ + unsigned long key; + struct http_head_fields *filed; + + key = hash_string(name); + hash_for_each_possible(http_head->field_map, filed, node, key) + { + if (strncmp(filed->name, name, 128) == 0) { + return filed->value; + } + } + + return NULL; +} + +struct http_head_fields *http_head_next_fields(struct http_head_fields *fields) +{ + struct http_head_fields *next = NULL; + next = list_next_entry(fields, list); + + if (next->name == NULL && next->value == NULL) { + return NULL; + } + + return next; +} + +int http_head_lookup_fields(struct http_head_fields *fields, const char **name, const char **value) +{ + if (fields == NULL) { + return -1; + } + + if (name) { + *name = fields->name; + } + + if (value) { + *value = fields->value; + } + + return 0; +} + +HTTP_METHOD http_head_get_method(struct http_head *http_head) +{ + return http_head->method; +} + +const char *http_head_get_url(struct http_head *http_head) +{ + return http_head->url; +} + +const char *http_head_get_httpversion(struct http_head *http_head) +{ + return http_head->version; +} + +int http_head_get_httpcode(struct http_head *http_head) +{ + return http_head->code; +} + +char *http_head_get_httpcode_msg(struct http_head *http_head) +{ + return http_head->code_msg; +} + +HTTP_HEAD_TYPE http_head_get_head_type(struct http_head *http_head) +{ + return http_head->head_type; +} + +char *http_head_get_data(struct http_head *http_head) +{ + return http_head->data; +} + +int http_head_get_data_len(struct http_head *http_head) +{ + return http_head->data_len; +} + +static int _http_head_add_fields(struct http_head *http_head, char *name, char *value) +{ + unsigned long key = 0; + struct http_head_fields *fields = NULL; + fields = malloc(sizeof(*fields)); + if (fields == NULL) { + return -1; + } + memset(fields, 0, sizeof(*fields)); + + fields->name = name; + fields->value = value; + + list_add_tail(&fields->list, &http_head->field_head.list); + key = hash_string(name); + hash_add(http_head->field_map, &fields->node, key); + + return 0; +} + +static int _http_head_parse_response(struct http_head *http_head, char *key, char *value) +{ + char *field_start = NULL; + char *tmp_ptr = NULL; + char *result = NULL; + char *ret_code = NULL; + + if (strstr(key, "HTTP/") == NULL) { + return -1; + } + + for (tmp_ptr = value; *tmp_ptr != 0; tmp_ptr++) { + if (field_start == NULL) { + field_start = tmp_ptr; + } + + if (*tmp_ptr == ' ') { + *tmp_ptr = '\0'; + if (ret_code == NULL) { + ret_code = field_start; + } else if (result == NULL) { + result = field_start; + break; + } + + field_start = NULL; + } + } + + if (field_start && result == NULL) { + result = field_start; + } + + if (ret_code == NULL || result == NULL) { + return -1; + } + + http_head->code = atol(ret_code); + http_head->code_msg = result; + http_head->version = key; + http_head->head_type = HTTP_HEAD_RESPONSE; + + return 0; +} + +static int _http_head_parse_request(struct http_head *http_head, char *key, char *value) +{ + int method = HTTP_METHOD_INVALID; + char *url = NULL; + char *version = NULL; + char *tmp_ptr = value; + char *field_start = NULL; + + if (strncmp(key, "GET", sizeof("GET")) == 0) { + method = HTTP_METHOD_GET; + } else if (strncmp(key, "POST", sizeof("POST")) == 0) { + method = HTTP_METHOD_POST; + } else if (strncmp(key, "PUT", sizeof("PUT")) == 0) { + method = HTTP_METHOD_PUT; + } else if (strncmp(key, "DELETE", sizeof("DELETE")) == 0) { + method = HTTP_METHOD_DELETE; + } else if (strncmp(key, "TRACE", sizeof("TRACE")) == 0) { + method = HTTP_METHOD_TRACE; + } else if (strncmp(key, "CONNECT", sizeof("CONNECT")) == 0) { + method = HTTP_METHOD_CONNECT; + } else { + return _http_head_parse_response(http_head, key, value); + } + + for (tmp_ptr = value; *tmp_ptr != 0; tmp_ptr++) { + if (field_start == NULL) { + field_start = tmp_ptr; + } + if (*tmp_ptr == ' ') { + *tmp_ptr = '\0'; + if (url == NULL) { + url = field_start; + } + + field_start = NULL; + } + } + + if (field_start && version == NULL) { + version = field_start; + } + + http_head->method = method; + http_head->url = url; + http_head->version = version; + http_head->head_type = HTTP_HEAD_REQUEST; + + return 0; +} + +static int _http_head_parse(struct http_head *http_head) +{ + int i = 0; + char *key = NULL; + char *value = NULL; + char *data; + int has_first_line = 0; + + int inkey = 1; + int invalue = 0; + + data = http_head->buff; + for (i = 0; i < http_head->head_len; i++, data++) { + if (inkey) { + if (key == NULL && *data != ' ' && *data != '\r' && *data != '\n') { + key = data; + continue; + } + + if (*data == ':' || *data == ' ') { + *data = '\0'; + inkey = 0; + invalue = 1; + continue; + } + } + + if (invalue) { + if (value == NULL && *data != ' ') { + value = data; + continue; + } + + if (*data == '\r' || *data == '\n') { + *data = '\0'; + inkey = 1; + invalue = 0; + } + } + + if (key && value && invalue == 0) { + if (has_first_line == 0) { + if (_http_head_parse_request(http_head, key, value) != 0) { + return -2; + } + + has_first_line = 1; + } else { + if (_http_head_add_fields(http_head, key, value) != 0) { + return -2; + } + } + + key = NULL; + value = NULL; + inkey = 1; + invalue = 0; + } + } + + return 0; +} + +int http_head_parse(struct http_head *http_head, const char *data, int data_len) +{ + int i = 0; + char *buff_end = NULL; + int left_size = 0; + int process_data_len = 0; + + left_size = http_head->buff_size - http_head->buff_len; + + if (left_size < data_len) { + return -3; + } + + buff_end = http_head->buff + http_head->buff_len; + if (http_head->head_ok == 0) { + for (i = 0; i < data_len; i++, data++) { + *(buff_end + i) = *data; + if (*data == '\n') { + if (http_head->buff_len + i < 2) { + continue; + } + + if (*(buff_end + i - 2) == '\n') { + http_head->head_ok = 1; + http_head->head_len = http_head->buff_len + i - 2; + i++; + buff_end += i; + data_len -= i; + data++; + if (_http_head_parse(http_head) != 0) { + return -2; + } + + const char *content_len = NULL; + content_len = http_head_get_fields_value(http_head, "Content-Length"); + if (content_len) { + http_head->expect_data_len = atol(content_len); + } else { + http_head->expect_data_len = 0; + } + + if (http_head->expect_data_len < 0) { + return -2; + } + + break; + } + } + } + + process_data_len += i; + if (http_head->head_ok == 0) { + // Read data again */ + http_head->buff_len += process_data_len; + return -1; + } + } + + if (http_head->head_ok == 1) { + int get_data_len = (http_head->expect_data_len > data_len) ? data_len : http_head->expect_data_len; + if (http_head->data == NULL) { + http_head->data = buff_end; + } + + memcpy(buff_end, data, get_data_len); + process_data_len += get_data_len; + http_head->data_len += get_data_len; + } + + http_head->buff_len += process_data_len; + if (http_head->data_len < http_head->expect_data_len) { + return -1; + } + + return process_data_len; +} + +void http_head_destroy(struct http_head *http_head) +{ + struct http_head_fields *fields, *tmp; + + list_for_each_entry_safe(fields, tmp, &http_head->field_head.list, list) + { + list_del(&fields->list); + free(fields); + } + + if (http_head->buff) { + free(http_head->buff); + } + + free(http_head); +} diff --git a/release/src/router/smartdns/src/http_parse.h b/release/src/router/smartdns/src/http_parse.h index 250969e7d9..8aa66ae05c 100644 --- a/release/src/router/smartdns/src/http_parse.h +++ b/release/src/router/smartdns/src/http_parse.h @@ -1,87 +1,87 @@ -/************************************************************************* - * - * Copyright (C) 2018-2020 Ruilin Peng (Nick) . - * - * smartdns is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * smartdns is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#ifndef HTTP_PARSER_H -#define HTTP_PARSER_H - -#ifdef __cpluscplus -extern "C" { -#endif - -struct http_head; -struct http_head_fields; - -typedef enum HTTP_METHOD { - HTTP_METHOD_INVALID = 0, - HTTP_METHOD_GET, - HTTP_METHOD_HEAD, - HTTP_METHOD_POST, - HTTP_METHOD_PUT, - HTTP_METHOD_DELETE, - HTTP_METHOD_TRACE, - HTTP_METHOD_CONNECT, -} HTTP_METHOD; - -typedef enum HTTP_HEAD_TYPE { - HTTP_HEAD_INVALID = 0, - HTTP_HEAD_REQUEST = 1, - HTTP_HEAD_RESPONSE = 2, -} HTTP_HEAD_TYPE; - -struct http_head *http_head_init(int buffsize); - -HTTP_HEAD_TYPE http_head_get_head_type(struct http_head *http_head); - -HTTP_METHOD http_head_get_method(struct http_head *http_head); - -const char *http_head_get_url(struct http_head *http_head); - -const char *http_head_get_httpversion(struct http_head *http_head); - -int http_head_get_httpcode(struct http_head *http_head); - -char *http_head_get_httpcode_msg(struct http_head *http_head); - -char *http_head_get_data(struct http_head *http_head); - -int http_head_get_data_len(struct http_head *http_head); - -struct http_head_fields *http_head_first_fields(struct http_head *http_head); - -struct http_head_fields *http_head_next_fields(struct http_head_fields *fields); - -const char *http_head_get_fields_value(struct http_head *http_head, const char *name); - -int http_head_lookup_fields(struct http_head_fields *fields, const char **name, const char **value); - -/* - * Returns: - * >=0 - success http data len - * -1 - Incomplete request - * -2 - parse failed - * -3 - buffer is small - */ -int http_head_parse(struct http_head *http_head, const char *data, int data_len); - -void http_head_destroy(struct http_head *http_head); - -#ifdef __cpluscplus -} -#endif - -#endif // !HTTP_PARSER_H +/************************************************************************* + * + * Copyright (C) 2018-2020 Ruilin Peng (Nick) . + * + * smartdns is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * smartdns is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef HTTP_PARSER_H +#define HTTP_PARSER_H + +#ifdef __cpluscplus +extern "C" { +#endif + +struct http_head; +struct http_head_fields; + +typedef enum HTTP_METHOD { + HTTP_METHOD_INVALID = 0, + HTTP_METHOD_GET, + HTTP_METHOD_HEAD, + HTTP_METHOD_POST, + HTTP_METHOD_PUT, + HTTP_METHOD_DELETE, + HTTP_METHOD_TRACE, + HTTP_METHOD_CONNECT, +} HTTP_METHOD; + +typedef enum HTTP_HEAD_TYPE { + HTTP_HEAD_INVALID = 0, + HTTP_HEAD_REQUEST = 1, + HTTP_HEAD_RESPONSE = 2, +} HTTP_HEAD_TYPE; + +struct http_head *http_head_init(int buffsize); + +HTTP_HEAD_TYPE http_head_get_head_type(struct http_head *http_head); + +HTTP_METHOD http_head_get_method(struct http_head *http_head); + +const char *http_head_get_url(struct http_head *http_head); + +const char *http_head_get_httpversion(struct http_head *http_head); + +int http_head_get_httpcode(struct http_head *http_head); + +char *http_head_get_httpcode_msg(struct http_head *http_head); + +char *http_head_get_data(struct http_head *http_head); + +int http_head_get_data_len(struct http_head *http_head); + +struct http_head_fields *http_head_first_fields(struct http_head *http_head); + +struct http_head_fields *http_head_next_fields(struct http_head_fields *fields); + +const char *http_head_get_fields_value(struct http_head *http_head, const char *name); + +int http_head_lookup_fields(struct http_head_fields *fields, const char **name, const char **value); + +/* + * Returns: + * >=0 - success http data len + * -1 - Incomplete request + * -2 - parse failed + * -3 - buffer is small + */ +int http_head_parse(struct http_head *http_head, const char *data, int data_len); + +void http_head_destroy(struct http_head *http_head); + +#ifdef __cpluscplus +} +#endif + +#endif // !HTTP_PARSER_H diff --git a/release/src/router/smartdns/src/include/art.h b/release/src/router/smartdns/src/include/art.h index eb9ccf4f6f..fbdf307b4d 100644 --- a/release/src/router/smartdns/src/include/art.h +++ b/release/src/router/smartdns/src/include/art.h @@ -1,251 +1,251 @@ -/* -Copyright (c) 2012, Armon Dadgar -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the organization nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL ARMON DADGAR BE LIABLE FOR ANY -DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include -#ifndef ART_H -#define ART_H - -#ifdef __cplusplus -extern "C" { -#endif - -#define NODE4 1 -#define NODE16 2 -#define NODE48 3 -#define NODE256 4 - -#define MAX_PREFIX_LEN 10 - -#if defined(__GNUC__) && !defined(__clang__) -# if __STDC_VERSION__ >= 199901L && 402 == (__GNUC__ * 100 + __GNUC_MINOR__) -/* - * GCC 4.2.2's C99 inline keyword support is pretty broken; avoid. Introduced in - * GCC 4.2.something, fixed in 4.3.0. So checking for specific major.minor of - * 4.2 is fine. - */ -# define BROKEN_GCC_C99_INLINE -# endif -#endif - -typedef int(*art_callback)(void *data, const unsigned char *key, uint32_t key_len, void *value); - -/** - * This struct is included as part - * of all the various node sizes - */ -typedef struct { - uint8_t type; - uint8_t num_children; - uint32_t partial_len; - unsigned char partial[MAX_PREFIX_LEN]; -} art_node; - -/** - * Small node with only 4 children - */ -typedef struct { - art_node n; - unsigned char keys[4]; - art_node *children[4]; -} art_node4; - -/** - * Node with 16 children - */ -typedef struct { - art_node n; - unsigned char keys[16]; - art_node *children[16]; -} art_node16; - -/** - * Node with 48 children, but - * a full 256 byte field. - */ -typedef struct { - art_node n; - unsigned char keys[256]; - art_node *children[48]; -} art_node48; - -/** - * Full node with 256 children - */ -typedef struct { - art_node n; - art_node *children[256]; -} art_node256; - -/** - * Represents a leaf. These are - * of arbitrary size, as they include the key. - */ -typedef struct { - void *value; - uint32_t key_len; - unsigned char key[0]; -} art_leaf; - -/** - * Main struct, points to root. - */ -typedef struct { - art_node *root; - uint64_t size; -} art_tree; - -/** - * Initializes an ART tree - * @return 0 on success. - */ -int art_tree_init(art_tree *t); - -/** - * DEPRECATED - * Initializes an ART tree - * @return 0 on success. - */ -#define init_art_tree(...) art_tree_init(__VA_ARGS__) - -/** - * Destroys an ART tree - * @return 0 on success. - */ -int art_tree_destroy(art_tree *t); - -/** - * DEPRECATED - * Initializes an ART tree - * @return 0 on success. - */ -#define destroy_art_tree(...) art_tree_destroy(__VA_ARGS__) - -/** - * Returns the size of the ART tree. - */ -#ifdef BROKEN_GCC_C99_INLINE -# define art_size(t) ((t)->size) -#else -static inline uint64_t art_size(art_tree *t) { - return t->size; -} -#endif - -/** - * Inserts a new value into the ART tree - * @arg t The tree - * @arg key The key - * @arg key_len The length of the key - * @arg value Opaque value. - * @return NULL if the item was newly inserted, otherwise - * the old value pointer is returned. - */ -void* art_insert(art_tree *t, const unsigned char *key, int key_len, void *value); - -/** - * Deletes a value from the ART tree - * @arg t The tree - * @arg key The key - * @arg key_len The length of the key - * @return NULL if the item was not found, otherwise - * the value pointer is returned. - */ -void* art_delete(art_tree *t, const unsigned char *key, int key_len); - -/** - * Searches for a value in the ART tree - * @arg t The tree - * @arg key The key - * @arg key_len The length of the key - * @return NULL if the item was not found, otherwise - * the value pointer is returned. - */ -void* art_search(const art_tree *t, const unsigned char *key, int key_len); - -/** - * Searches substring for a value in the ART tree - * @arg t The tree - * @arg str The key - * @arg str_len The length of the key - * @return NULL if the item was not found, otherwise - * the value pointer is returned. - */ -void *art_substring(const art_tree *t, const unsigned char *str, int str_len, unsigned char *key, int *key_len); - -/** - * Wakk substring for a value in the ART tree - * @arg t The tree - * @arg str The key - * @arg str_len The length of the key - * @return NULL if the item was not found, otherwise - * the value pointer is returned. - */ -typedef int (*walk_func)(unsigned char *key, uint32_t key_len, void *value, void *arg); -void art_substring_walk(const art_tree *t, const unsigned char *str, int str_len, walk_func func, void *arg); - -/** - * Returns the minimum valued leaf - * @return The minimum leaf or NULL - */ -art_leaf* art_minimum(art_tree *t); - -/** - * Returns the maximum valued leaf - * @return The maximum leaf or NULL - */ -art_leaf* art_maximum(art_tree *t); - -/** - * Iterates through the entries pairs in the map, - * invoking a callback for each. The call back gets a - * key, value for each and returns an integer stop value. - * If the callback returns non-zero, then the iteration stops. - * @arg t The tree to iterate over - * @arg cb The callback function to invoke - * @arg data Opaque handle passed to the callback - * @return 0 on success, or the return of the callback. - */ -int art_iter(art_tree *t, art_callback cb, void *data); - -/** - * Iterates through the entries pairs in the map, - * invoking a callback for each that matches a given prefix. - * The call back gets a key, value for each and returns an integer stop value. - * If the callback returns non-zero, then the iteration stops. - * @arg t The tree to iterate over - * @arg prefix The prefix of keys to read - * @arg prefix_len The length of the prefix - * @arg cb The callback function to invoke - * @arg data Opaque handle passed to the callback - * @return 0 on success, or the return of the callback. - */ -int art_iter_prefix(art_tree *t, const unsigned char *prefix, int prefix_len, art_callback cb, void *data); - -#ifdef __cplusplus -} -#endif - -#endif +/* +Copyright (c) 2012, Armon Dadgar +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the organization nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL ARMON DADGAR BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include +#ifndef ART_H +#define ART_H + +#ifdef __cplusplus +extern "C" { +#endif + +#define NODE4 1 +#define NODE16 2 +#define NODE48 3 +#define NODE256 4 + +#define MAX_PREFIX_LEN 10 + +#if defined(__GNUC__) && !defined(__clang__) +# if __STDC_VERSION__ >= 199901L && 402 == (__GNUC__ * 100 + __GNUC_MINOR__) +/* + * GCC 4.2.2's C99 inline keyword support is pretty broken; avoid. Introduced in + * GCC 4.2.something, fixed in 4.3.0. So checking for specific major.minor of + * 4.2 is fine. + */ +# define BROKEN_GCC_C99_INLINE +# endif +#endif + +typedef int(*art_callback)(void *data, const unsigned char *key, uint32_t key_len, void *value); + +/** + * This struct is included as part + * of all the various node sizes + */ +typedef struct { + uint8_t type; + uint8_t num_children; + uint32_t partial_len; + unsigned char partial[MAX_PREFIX_LEN]; +} art_node; + +/** + * Small node with only 4 children + */ +typedef struct { + art_node n; + unsigned char keys[4]; + art_node *children[4]; +} art_node4; + +/** + * Node with 16 children + */ +typedef struct { + art_node n; + unsigned char keys[16]; + art_node *children[16]; +} art_node16; + +/** + * Node with 48 children, but + * a full 256 byte field. + */ +typedef struct { + art_node n; + unsigned char keys[256]; + art_node *children[48]; +} art_node48; + +/** + * Full node with 256 children + */ +typedef struct { + art_node n; + art_node *children[256]; +} art_node256; + +/** + * Represents a leaf. These are + * of arbitrary size, as they include the key. + */ +typedef struct { + void *value; + uint32_t key_len; + unsigned char key[0]; +} art_leaf; + +/** + * Main struct, points to root. + */ +typedef struct { + art_node *root; + uint64_t size; +} art_tree; + +/** + * Initializes an ART tree + * @return 0 on success. + */ +int art_tree_init(art_tree *t); + +/** + * DEPRECATED + * Initializes an ART tree + * @return 0 on success. + */ +#define init_art_tree(...) art_tree_init(__VA_ARGS__) + +/** + * Destroys an ART tree + * @return 0 on success. + */ +int art_tree_destroy(art_tree *t); + +/** + * DEPRECATED + * Initializes an ART tree + * @return 0 on success. + */ +#define destroy_art_tree(...) art_tree_destroy(__VA_ARGS__) + +/** + * Returns the size of the ART tree. + */ +#ifdef BROKEN_GCC_C99_INLINE +# define art_size(t) ((t)->size) +#else +static inline uint64_t art_size(art_tree *t) { + return t->size; +} +#endif + +/** + * Inserts a new value into the ART tree + * @arg t The tree + * @arg key The key + * @arg key_len The length of the key + * @arg value Opaque value. + * @return NULL if the item was newly inserted, otherwise + * the old value pointer is returned. + */ +void* art_insert(art_tree *t, const unsigned char *key, int key_len, void *value); + +/** + * Deletes a value from the ART tree + * @arg t The tree + * @arg key The key + * @arg key_len The length of the key + * @return NULL if the item was not found, otherwise + * the value pointer is returned. + */ +void* art_delete(art_tree *t, const unsigned char *key, int key_len); + +/** + * Searches for a value in the ART tree + * @arg t The tree + * @arg key The key + * @arg key_len The length of the key + * @return NULL if the item was not found, otherwise + * the value pointer is returned. + */ +void* art_search(const art_tree *t, const unsigned char *key, int key_len); + +/** + * Searches substring for a value in the ART tree + * @arg t The tree + * @arg str The key + * @arg str_len The length of the key + * @return NULL if the item was not found, otherwise + * the value pointer is returned. + */ +void *art_substring(const art_tree *t, const unsigned char *str, int str_len, unsigned char *key, int *key_len); + +/** + * Wakk substring for a value in the ART tree + * @arg t The tree + * @arg str The key + * @arg str_len The length of the key + * @return NULL if the item was not found, otherwise + * the value pointer is returned. + */ +typedef int (*walk_func)(unsigned char *key, uint32_t key_len, void *value, void *arg); +void art_substring_walk(const art_tree *t, const unsigned char *str, int str_len, walk_func func, void *arg); + +/** + * Returns the minimum valued leaf + * @return The minimum leaf or NULL + */ +art_leaf* art_minimum(art_tree *t); + +/** + * Returns the maximum valued leaf + * @return The maximum leaf or NULL + */ +art_leaf* art_maximum(art_tree *t); + +/** + * Iterates through the entries pairs in the map, + * invoking a callback for each. The call back gets a + * key, value for each and returns an integer stop value. + * If the callback returns non-zero, then the iteration stops. + * @arg t The tree to iterate over + * @arg cb The callback function to invoke + * @arg data Opaque handle passed to the callback + * @return 0 on success, or the return of the callback. + */ +int art_iter(art_tree *t, art_callback cb, void *data); + +/** + * Iterates through the entries pairs in the map, + * invoking a callback for each that matches a given prefix. + * The call back gets a key, value for each and returns an integer stop value. + * If the callback returns non-zero, then the iteration stops. + * @arg t The tree to iterate over + * @arg prefix The prefix of keys to read + * @arg prefix_len The length of the prefix + * @arg cb The callback function to invoke + * @arg data Opaque handle passed to the callback + * @return 0 on success, or the return of the callback. + */ +int art_iter_prefix(art_tree *t, const unsigned char *prefix, int prefix_len, art_callback cb, void *data); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/release/src/router/smartdns/src/include/conf.h b/release/src/router/smartdns/src/include/conf.h index 81159361b7..d0c73f9e32 100644 --- a/release/src/router/smartdns/src/include/conf.h +++ b/release/src/router/smartdns/src/include/conf.h @@ -1,142 +1,141 @@ -/************************************************************************* - * - * Copyright (C) 2018-2020 Ruilin Peng (Nick) . - * - * smartdns is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * smartdns is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - -#ifndef _GENERIC_CONF_H -#define _GENERIC_CONF_H - -#include - -#define MAX_LINE_LEN 1024 -#define MAX_KEY_LEN 64 -#define CONF_INT_MAX (~(1 << 31)) -#define CONF_INT_MIN (1 << 31) - -#define CONF_RET_OK 0 -#define CONF_RET_ERR -1 -#define CONF_RET_WARN -2 -#define CONF_RET_NOENT -3 - -struct config_item { - const char *item; - int (*item_func)(const char *item, void *data, int argc, char *argv[]); - void *data; -}; - -struct config_item_custom { - void *custom_data; - int (*custom_func)(void *data, int argc, char *argv[]); -}; - -struct config_item_int { - int *data; - int min; - int max; -}; - -struct config_item_string { - char *data; - size_t size; -}; - -struct config_item_yesno { - int *data; -}; - -struct config_item_size { - size_t *data; - size_t min; - size_t max; -}; - -#define CONF_INT(key, value, min_value, max_value) \ - { \ - key, conf_int, &(struct config_item_int) \ - { \ - .data = value, .min = min_value, .max = max_value \ - } \ - } -#define CONF_STRING(key, value, len_value) \ - { \ - key, conf_string, &(struct config_item_string) \ - { \ - .data = value, .size = len_value \ - } \ - } -#define CONF_YESNO(key, value) \ - { \ - key, conf_yesno, &(struct config_item_yesno) \ - { \ - .data = value \ - } \ - } -#define CONF_SIZE(key, value, min_value, max_value) \ - { \ - key, conf_size, &(struct config_item_size) \ - { \ - .data = value, .min = min_value, .max = max_value \ - } \ - } -/* - * func: int (*func)(void *data, int argc, char *argv[]); - */ -#define CONF_CUSTOM(key, func, data) \ - { \ - key, conf_custom, &(struct config_item_custom) \ - { \ - .custom_data = data, .custom_func = func \ - } \ - } - -#define CONF_END() \ - { \ - NULL, NULL, NULL \ - } - -extern int conf_custom(const char *item, void *data, int argc, char *argv[]); - -extern int conf_int(const char *item, void *data, int argc, char *argv[]); - -extern int conf_string(const char *item, void *data, int argc, char *argv[]); - -extern int conf_yesno(const char *item, void *data, int argc, char *argv[]); - -extern int conf_size(const char *item, void *data, int argc, char *argv[]); - -/* - * Example: - * int num = 0; - * - * struct config_item itmes [] = { - * CONF_INT("CONF_NUM", &num, -1, 10), - * CONF_END(); - * } - * - * load_conf(file, items); - * - */ - -typedef int(conf_error_handler)(const char *file, int lineno, int ret); - -int load_conf(const char *file, struct config_item items[], conf_error_handler handler); - -void load_exit(void); - -const char *conf_get_conf_file(void); - -#endif // !_GENERIC_CONF_H +/************************************************************************* + * + * Copyright (C) 2018-2020 Ruilin Peng (Nick) . + * + * smartdns is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * smartdns is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef _GENERIC_CONF_H +#define _GENERIC_CONF_H + +#include + +#define MAX_LINE_LEN 1024 +#define MAX_KEY_LEN 64 +#define CONF_INT_MAX (~(1 << 31)) +#define CONF_INT_MIN (1 << 31) + +#define CONF_RET_OK 0 +#define CONF_RET_ERR -1 +#define CONF_RET_WARN -2 +#define CONF_RET_NOENT -3 + +struct config_item { + const char *item; + int (*item_func)(const char *item, void *data, int argc, char *argv[]); + void *data; +}; + +struct config_item_custom { + void *custom_data; + int (*custom_func)(void *data, int argc, char *argv[]); +}; + +struct config_item_int { + int *data; + int min; + int max; +}; + +struct config_item_string { + char *data; + size_t size; +}; + +struct config_item_yesno { + int *data; +}; + +struct config_item_size { + size_t *data; + size_t min; + size_t max; +}; + +#define CONF_INT(key, value, min_value, max_value) \ + { \ + key, conf_int, &(struct config_item_int) \ + { \ + .data = value, .min = min_value, .max = max_value \ + } \ + } +#define CONF_STRING(key, value, len_value) \ + { \ + key, conf_string, &(struct config_item_string) \ + { \ + .data = value, .size = len_value \ + } \ + } +#define CONF_YESNO(key, value) \ + { \ + key, conf_yesno, &(struct config_item_yesno) \ + { \ + .data = value \ + } \ + } +#define CONF_SIZE(key, value, min_value, max_value) \ + { \ + key, conf_size, &(struct config_item_size) \ + { \ + .data = value, .min = min_value, .max = max_value \ + } \ + } +/* + * func: int (*func)(void *data, int argc, char *argv[]); + */ +#define CONF_CUSTOM(key, func, data) \ + { \ + key, conf_custom, &(struct config_item_custom) \ + { \ + .custom_data = data, .custom_func = func \ + } \ + } + +#define CONF_END() \ + { \ + NULL, NULL, NULL \ + } + +extern int conf_custom(const char *item, void *data, int argc, char *argv[]); + +extern int conf_int(const char *item, void *data, int argc, char *argv[]); + +extern int conf_string(const char *item, void *data, int argc, char *argv[]); + +extern int conf_yesno(const char *item, void *data, int argc, char *argv[]); + +extern int conf_size(const char *item, void *data, int argc, char *argv[]); + +/* + * Example: + * int num = 0; + * + * struct config_item itmes [] = { + * CONF_INT("CONF_NUM", &num, -1, 10), + * CONF_END(); + * } + * + * load_conf(file, items); + * + */ + +typedef int(conf_error_handler)(const char *file, int lineno, int ret); + +int load_conf(const char *file, struct config_item items[], conf_error_handler handler); + +void load_exit(void); + +const char *conf_get_conf_file(void); + +#endif // !_GENERIC_CONF_H diff --git a/release/src/router/smartdns/src/include/radix.h b/release/src/router/smartdns/src/include/radix.h index adb5ab1278..a8bdbe765e 100644 --- a/release/src/router/smartdns/src/include/radix.h +++ b/release/src/router/smartdns/src/include/radix.h @@ -1,162 +1,162 @@ -/* - * Copyright (c) 1999-2000 - * - * The Regents of the University of Michigan ("The Regents") and - * Merit Network, Inc. All rights reserved. Redistribution and use - * in source and binary forms, with or without modification, are - * permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above - * copyright notice, this list of conditions and the - * following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the - * following disclaimer in the documentation and/or other - * materials provided with the distribution. - * - * 3. All advertising materials mentioning features or use of - * this software must display the following acknowledgement: - * - * This product includes software developed by the University of - * Michigan, Merit Network, Inc., and their contributors. - * - * 4. Neither the name of the University, Merit Network, nor the - * names of their contributors may be used to endorse or - * promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A - * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL TH E REGENTS - * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF - * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HO WEVER CAUSED - * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN - * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -/* - * Portions Copyright (c) 2004,2005 Damien Miller - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -/* $Id: radix.h,v 1.9 2007/10/24 06:03:08 djm Exp $ */ - -#ifndef _RADIX_H -#define _RADIX_H - -#if defined(_MSC_VER) -#include -#include -#else -# include -# include -# include -# include -# include -#endif - -#if defined(_MSC_VER) -# define snprintf _snprintf -typedef unsigned __int8 u_int8_t; -typedef unsigned __int16 u_int16_t; -typedef unsigned __int32 u_int32_t; -const char *inet_ntop(int af, const void *src, char *dst, size_t size); -size_t strlcpy(char *dst, const char *src, size_t size); -#endif - -/* - * Originally from MRT include/mrt.h - * $MRTId: mrt.h,v 1.1.1.1 2000/08/14 18:46:10 labovit Exp $ - */ -typedef struct _prefix_t { - u_int family; /* AF_INET | AF_INET6 */ - u_int bitlen; /* same as mask? */ - int ref_count; /* reference count */ - union { - struct in_addr sin; - struct in6_addr sin6; - } add; -} prefix_t; - -void Deref_Prefix(prefix_t *prefix); - -/* - * Originally from MRT include/radix.h - * $MRTId: radix.h,v 1.1.1.1 2000/08/14 18:46:10 labovit Exp $ - */ -typedef struct _radix_node_t { - u_int bit; /* flag if this node used */ - prefix_t *prefix; /* who we are in radix tree */ - struct _radix_node_t *l, *r; /* left and right children */ - struct _radix_node_t *parent; /* may be used */ - void *data; /* pointer to data */ -} radix_node_t; - -typedef struct _radix_tree_t { - radix_node_t *head; - u_int maxbits; /* for IP, 32 bit addresses */ - int num_active_node; /* for debug purpose */ -} radix_tree_t; - -/* Type of callback function */ -typedef void (*rdx_cb_t)(radix_node_t *, void *); - -radix_tree_t *New_Radix(void); -void Destroy_Radix(radix_tree_t *radix, rdx_cb_t func, void *cbctx); -radix_node_t *radix_lookup(radix_tree_t *radix, prefix_t *prefix); -void radix_remove(radix_tree_t *radix, radix_node_t *node); -radix_node_t *radix_search_exact(radix_tree_t *radix, prefix_t *prefix); -radix_node_t *radix_search_best(radix_tree_t *radix, prefix_t *prefix); -void radix_process(radix_tree_t *radix, rdx_cb_t func, void *cbctx); - -#define RADIX_MAXBITS 128 - -#define RADIX_WALK(Xhead, Xnode) \ - do { \ - radix_node_t *Xstack[RADIX_MAXBITS+1]; \ - radix_node_t **Xsp = Xstack; \ - radix_node_t *Xrn = (Xhead); \ - while ((Xnode = Xrn)) { \ - if (Xnode->prefix) - -#define RADIX_WALK_END \ - if (Xrn->l) { \ - if (Xrn->r) { \ - *Xsp++ = Xrn->r; \ - } \ - Xrn = Xrn->l; \ - } else if (Xrn->r) { \ - Xrn = Xrn->r; \ - } else if (Xsp != Xstack) { \ - Xrn = *(--Xsp); \ - } else { \ - Xrn = (radix_node_t *) 0; \ - } \ - } \ - } while (0) - -/* Local additions */ - -prefix_t *prefix_pton(const char *string, long len, prefix_t *prefix, const char **errmsg); -prefix_t *prefix_from_blob(unsigned char *blob, int len, int prefixlen, prefix_t *prefix); -const char *prefix_addr_ntop(prefix_t *prefix, char *buf, size_t len); -const char *prefix_ntop(prefix_t *prefix, char *buf, size_t len); - -#endif /* _RADIX_H */ - +/* + * Copyright (c) 1999-2000 + * + * The Regents of the University of Michigan ("The Regents") and + * Merit Network, Inc. All rights reserved. Redistribution and use + * in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above + * copyright notice, this list of conditions and the + * following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other + * materials provided with the distribution. + * + * 3. All advertising materials mentioning features or use of + * this software must display the following acknowledgement: + * + * This product includes software developed by the University of + * Michigan, Merit Network, Inc., and their contributors. + * + * 4. Neither the name of the University, Merit Network, nor the + * names of their contributors may be used to endorse or + * promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL TH E REGENTS + * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HO WEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +/* + * Portions Copyright (c) 2004,2005 Damien Miller + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +/* $Id: radix.h,v 1.9 2007/10/24 06:03:08 djm Exp $ */ + +#ifndef _RADIX_H +#define _RADIX_H + +#if defined(_MSC_VER) +#include +#include +#else +# include +# include +# include +# include +# include +#endif + +#if defined(_MSC_VER) +# define snprintf _snprintf +typedef unsigned __int8 u_int8_t; +typedef unsigned __int16 u_int16_t; +typedef unsigned __int32 u_int32_t; +const char *inet_ntop(int af, const void *src, char *dst, size_t size); +size_t strlcpy(char *dst, const char *src, size_t size); +#endif + +/* + * Originally from MRT include/mrt.h + * $MRTId: mrt.h,v 1.1.1.1 2000/08/14 18:46:10 labovit Exp $ + */ +typedef struct _prefix_t { + u_int family; /* AF_INET | AF_INET6 */ + u_int bitlen; /* same as mask? */ + int ref_count; /* reference count */ + union { + struct in_addr sin; + struct in6_addr sin6; + } add; +} prefix_t; + +void Deref_Prefix(prefix_t *prefix); + +/* + * Originally from MRT include/radix.h + * $MRTId: radix.h,v 1.1.1.1 2000/08/14 18:46:10 labovit Exp $ + */ +typedef struct _radix_node_t { + u_int bit; /* flag if this node used */ + prefix_t *prefix; /* who we are in radix tree */ + struct _radix_node_t *l, *r; /* left and right children */ + struct _radix_node_t *parent; /* may be used */ + void *data; /* pointer to data */ +} radix_node_t; + +typedef struct _radix_tree_t { + radix_node_t *head; + u_int maxbits; /* for IP, 32 bit addresses */ + int num_active_node; /* for debug purpose */ +} radix_tree_t; + +/* Type of callback function */ +typedef void (*rdx_cb_t)(radix_node_t *, void *); + +radix_tree_t *New_Radix(void); +void Destroy_Radix(radix_tree_t *radix, rdx_cb_t func, void *cbctx); +radix_node_t *radix_lookup(radix_tree_t *radix, prefix_t *prefix); +void radix_remove(radix_tree_t *radix, radix_node_t *node); +radix_node_t *radix_search_exact(radix_tree_t *radix, prefix_t *prefix); +radix_node_t *radix_search_best(radix_tree_t *radix, prefix_t *prefix); +void radix_process(radix_tree_t *radix, rdx_cb_t func, void *cbctx); + +#define RADIX_MAXBITS 128 + +#define RADIX_WALK(Xhead, Xnode) \ + do { \ + radix_node_t *Xstack[RADIX_MAXBITS+1]; \ + radix_node_t **Xsp = Xstack; \ + radix_node_t *Xrn = (Xhead); \ + while ((Xnode = Xrn)) { \ + if (Xnode->prefix) + +#define RADIX_WALK_END \ + if (Xrn->l) { \ + if (Xrn->r) { \ + *Xsp++ = Xrn->r; \ + } \ + Xrn = Xrn->l; \ + } else if (Xrn->r) { \ + Xrn = Xrn->r; \ + } else if (Xsp != Xstack) { \ + Xrn = *(--Xsp); \ + } else { \ + Xrn = (radix_node_t *) 0; \ + } \ + } \ + } while (0) + +/* Local additions */ + +prefix_t *prefix_pton(const char *string, long len, prefix_t *prefix, const char **errmsg); +prefix_t *prefix_from_blob(unsigned char *blob, int len, int prefixlen, prefix_t *prefix); +const char *prefix_addr_ntop(prefix_t *prefix, char *buf, size_t len); +const char *prefix_ntop(prefix_t *prefix, char *buf, size_t len); + +#endif /* _RADIX_H */ + diff --git a/release/src/router/smartdns/src/include/rbtree.h b/release/src/router/smartdns/src/include/rbtree.h index c89e8ee845..96a49c57fa 100644 --- a/release/src/router/smartdns/src/include/rbtree.h +++ b/release/src/router/smartdns/src/include/rbtree.h @@ -1,305 +1,305 @@ -/************************************************************************* - * - * Copyright (C) 2018-2020 Ruilin Peng (Nick) . - * - * smartdns is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * smartdns is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#ifndef _GENERIC_RBTREE_H -#define _GENERIC_RBTREE_H - -#include - -struct rb_node { - unsigned long __rb_parent_color; - struct rb_node *rb_right; - struct rb_node *rb_left; -} __attribute__((aligned(sizeof(long)))); -/* The alignment might seem pointless, but allegedly CRIS needs it */ - -struct rb_root { - struct rb_node *rb_node; -}; - -#define rb_parent(r) ((struct rb_node *)((r)->__rb_parent_color & ~3)) - -#define RB_ROOT \ - (struct rb_root) \ - { \ - NULL, \ - } -#define rb_entry(ptr, type, member) container_of(ptr, type, member) - -#define RB_EMPTY_ROOT(root) ((root)->rb_node == NULL) - -/* 'empty' nodes are nodes that are known not to be inserted in an rbtree */ -#define RB_EMPTY_NODE(node) ((node)->__rb_parent_color == (unsigned long)(node)) -#define RB_CLEAR_NODE(node) ((node)->__rb_parent_color = (unsigned long)(node)) - -extern void rb_insert_color(struct rb_node *, struct rb_root *); -extern void rb_erase(struct rb_node *, struct rb_root *); - -/* Find logical next and previous nodes in a tree */ -extern struct rb_node *rb_next(const struct rb_node *); -extern struct rb_node *rb_prev(const struct rb_node *); -extern struct rb_node *rb_first(const struct rb_root *); -extern struct rb_node *rb_last(const struct rb_root *); - -/* Postorder iteration - always visit the parent after its children */ -extern struct rb_node *rb_first_postorder(const struct rb_root *); -extern struct rb_node *rb_next_postorder(const struct rb_node *); - -/* Fast replacement of a single node without remove/rebalance/add/rebalance */ -extern void rb_replace_node(struct rb_node *victim, struct rb_node *new_node, struct rb_root *root); - -static inline void rb_link_node(struct rb_node *node, struct rb_node *parent, struct rb_node **rb_link) -{ - node->__rb_parent_color = (unsigned long)parent; - node->rb_left = node->rb_right = NULL; - - *rb_link = node; -} - -#define rb_entry_safe(ptr, type, member) \ - ({ \ - typeof(ptr) ____ptr = (ptr); \ - ____ptr ? rb_entry(____ptr, type, member) : NULL; \ - }) - -/* - * Handy for checking that we are not deleting an entry that is - * already in a list, found in block/{blk-throttle,cfq-iosched}.c, - * probably should be moved to lib/rbtree.c... - */ -static inline void rb_erase_init(struct rb_node *n, struct rb_root *root) -{ - rb_erase(n, root); - RB_CLEAR_NODE(n); -} - - -/* - * Please note - only struct rb_augment_callbacks and the prototypes for - * rb_insert_augmented() and rb_erase_augmented() are intended to be public. - * The rest are implementation details you are not expected to depend on. - * - * See Documentation/rbtree.txt for documentation and samples. - */ - -struct rb_augment_callbacks { - void (*propagate)(struct rb_node *node, struct rb_node *stop); - void (*copy)(struct rb_node *old_node, struct rb_node *new_node); - void (*rotate)(struct rb_node *old_node, struct rb_node *new_node); -}; - -extern void __rb_insert_augmented(struct rb_node *node, struct rb_root *root, - void (*augment_rotate)(struct rb_node *old_node, struct rb_node *new_node)); -/* - * Fixup the rbtree and update the augmented information when rebalancing. - * - * On insertion, the user must update the augmented information on the path - * leading to the inserted node, then call rb_link_node() as usual and - * rb_augment_inserted() instead of the usual rb_insert_color() call. - * If rb_augment_inserted() rebalances the rbtree, it will callback into - * a user provided function to update the augmented information on the - * affected subtrees. - */ -static inline void -rb_insert_augmented(struct rb_node *node, struct rb_root *root, - const struct rb_augment_callbacks *augment) -{ - __rb_insert_augmented(node, root, augment->rotate); -} - -#define RB_DECLARE_CALLBACKS(rbstatic, rbname, rbstruct, rbfield, \ - rbtype, rbaugmented, rbcompute) \ -static inline void \ -rbname ## _propagate(struct rb_node *rb, struct rb_node *stop) \ -{ \ - while (rb != stop) { \ - rbstruct *node = rb_entry(rb, rbstruct, rbfield); \ - rbtype augmented = rbcompute(node); \ - if (node->rbaugmented == augmented) \ - break; \ - node->rbaugmented = augmented; \ - rb = rb_parent(&node->rbfield); \ - } \ -} \ -static inline void \ -rbname ## _copy(struct rb_node *rb_old, struct rb_node *rb_new) \ -{ \ - rbstruct *old_node = rb_entry(rb_old, rbstruct, rbfield); \ - rbstruct *new_node = rb_entry(rb_new, rbstruct, rbfield); \ - new_node->rbaugmented = old_node->rbaugmented; \ -} \ -static void \ -rbname ## _rotate(struct rb_node *rb_old, struct rb_node *rb_new) \ -{ \ - rbstruct *old_node = rb_entry(rb_old, rbstruct, rbfield); \ - rbstruct *new_node = rb_entry(rb_new, rbstruct, rbfield); \ - new_node->rbaugmented = old_node->rbaugmented; \ - old_node->rbaugmented = rbcompute(old_node); \ -} \ -rbstatic const struct rb_augment_callbacks rbname = { \ - rbname ## _propagate, rbname ## _copy, rbname ## _rotate \ -}; - - -#define RB_RED 0 -#define RB_BLACK 1 - -#define __rb_parent(pc) ((struct rb_node *)(pc & ~3)) - -#define __rb_color(pc) ((pc) & 1) -#define __rb_is_black(pc) __rb_color(pc) -#define __rb_is_red(pc) (!__rb_color(pc)) -#define rb_color(rb) __rb_color((rb)->__rb_parent_color) -#define rb_is_red(rb) __rb_is_red((rb)->__rb_parent_color) -#define rb_is_black(rb) __rb_is_black((rb)->__rb_parent_color) - -static inline void rb_set_parent(struct rb_node *rb, struct rb_node *p) -{ - rb->__rb_parent_color = rb_color(rb) | (unsigned long)p; -} - -static inline void rb_set_parent_color(struct rb_node *rb, - struct rb_node *p, int color) -{ - rb->__rb_parent_color = (unsigned long)p | color; -} - -static inline void -__rb_change_child(struct rb_node *old_node, struct rb_node *new_node, - struct rb_node *parent, struct rb_root *root) -{ - if (parent) { - if (parent->rb_left == old_node) - parent->rb_left = new_node; - else - parent->rb_right = new_node; - } else - root->rb_node = new_node; -} - -extern void __rb_erase_color(struct rb_node *parent, struct rb_root *root, - void (*augment_rotate)(struct rb_node *old_node, struct rb_node *new_node)); - -static inline struct rb_node * -__rb_erase_augmented(struct rb_node *node, struct rb_root *root, - const struct rb_augment_callbacks *augment) -{ - struct rb_node *child = node->rb_right, *tmp = node->rb_left; - struct rb_node *parent, *rebalance; - unsigned long pc; - - if (!tmp) { - /* - * Case 1: node to erase has no more than 1 child (easy!) - * - * Note that if there is one child it must be red due to 5) - * and node must be black due to 4). We adjust colors locally - * so as to bypass __rb_erase_color() later on. - */ - pc = node->__rb_parent_color; - parent = __rb_parent(pc); - __rb_change_child(node, child, parent, root); - if (child) { - child->__rb_parent_color = pc; - rebalance = NULL; - } else - rebalance = __rb_is_black(pc) ? parent : NULL; - tmp = parent; - } else if (!child) { - /* Still case 1, but this time the child is node->rb_left */ - tmp->__rb_parent_color = pc = node->__rb_parent_color; - parent = __rb_parent(pc); - __rb_change_child(node, tmp, parent, root); - rebalance = NULL; - tmp = parent; - } else { - struct rb_node *successor = child, *child2; - tmp = child->rb_left; - if (!tmp) { - /* - * Case 2: node's successor is its right child - * - * (n) (s) - * / \ / \ - * (x) (s) -> (x) (c) - * \ - * (c) - */ - parent = successor; - child2 = successor->rb_right; - augment->copy(node, successor); - } else { - /* - * Case 3: node's successor is leftmost under - * node's right child subtree - * - * (n) (s) - * / \ / \ - * (x) (y) -> (x) (y) - * / / - * (p) (p) - * / / - * (s) (c) - * \ - * (c) - */ - do { - parent = successor; - successor = tmp; - tmp = tmp->rb_left; - } while (tmp); - parent->rb_left = child2 = successor->rb_right; - successor->rb_right = child; - rb_set_parent(child, successor); - augment->copy(node, successor); - augment->propagate(parent, successor); - } - - successor->rb_left = tmp = node->rb_left; - rb_set_parent(tmp, successor); - - pc = node->__rb_parent_color; - tmp = __rb_parent(pc); - __rb_change_child(node, successor, tmp, root); - if (child2) { - successor->__rb_parent_color = pc; - rb_set_parent_color(child2, parent, RB_BLACK); - rebalance = NULL; - } else { - unsigned long pc2 = successor->__rb_parent_color; - successor->__rb_parent_color = pc; - rebalance = __rb_is_black(pc2) ? parent : NULL; - } - tmp = successor; - } - - augment->propagate(tmp, NULL); - return rebalance; -} - -static inline void -rb_erase_augmented(struct rb_node *node, struct rb_root *root, - const struct rb_augment_callbacks *augment) -{ - struct rb_node *rebalance = __rb_erase_augmented(node, root, augment); - if (rebalance) - __rb_erase_color(rebalance, root, augment->rotate); -} - -#endif /* _GENERIC_RBTREE_H */ - +/************************************************************************* + * + * Copyright (C) 2018-2020 Ruilin Peng (Nick) . + * + * smartdns is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * smartdns is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef _GENERIC_RBTREE_H +#define _GENERIC_RBTREE_H + +#include + +struct rb_node { + unsigned long __rb_parent_color; + struct rb_node *rb_right; + struct rb_node *rb_left; +} __attribute__((aligned(sizeof(long)))); +/* The alignment might seem pointless, but allegedly CRIS needs it */ + +struct rb_root { + struct rb_node *rb_node; +}; + +#define rb_parent(r) ((struct rb_node *)((r)->__rb_parent_color & ~3)) + +#define RB_ROOT \ + (struct rb_root) \ + { \ + NULL, \ + } +#define rb_entry(ptr, type, member) container_of(ptr, type, member) + +#define RB_EMPTY_ROOT(root) ((root)->rb_node == NULL) + +/* 'empty' nodes are nodes that are known not to be inserted in an rbtree */ +#define RB_EMPTY_NODE(node) ((node)->__rb_parent_color == (unsigned long)(node)) +#define RB_CLEAR_NODE(node) ((node)->__rb_parent_color = (unsigned long)(node)) + +extern void rb_insert_color(struct rb_node *, struct rb_root *); +extern void rb_erase(struct rb_node *, struct rb_root *); + +/* Find logical next and previous nodes in a tree */ +extern struct rb_node *rb_next(const struct rb_node *); +extern struct rb_node *rb_prev(const struct rb_node *); +extern struct rb_node *rb_first(const struct rb_root *); +extern struct rb_node *rb_last(const struct rb_root *); + +/* Postorder iteration - always visit the parent after its children */ +extern struct rb_node *rb_first_postorder(const struct rb_root *); +extern struct rb_node *rb_next_postorder(const struct rb_node *); + +/* Fast replacement of a single node without remove/rebalance/add/rebalance */ +extern void rb_replace_node(struct rb_node *victim, struct rb_node *new_node, struct rb_root *root); + +static inline void rb_link_node(struct rb_node *node, struct rb_node *parent, struct rb_node **rb_link) +{ + node->__rb_parent_color = (unsigned long)parent; + node->rb_left = node->rb_right = NULL; + + *rb_link = node; +} + +#define rb_entry_safe(ptr, type, member) \ + ({ \ + typeof(ptr) ____ptr = (ptr); \ + ____ptr ? rb_entry(____ptr, type, member) : NULL; \ + }) + +/* + * Handy for checking that we are not deleting an entry that is + * already in a list, found in block/{blk-throttle,cfq-iosched}.c, + * probably should be moved to lib/rbtree.c... + */ +static inline void rb_erase_init(struct rb_node *n, struct rb_root *root) +{ + rb_erase(n, root); + RB_CLEAR_NODE(n); +} + + +/* + * Please note - only struct rb_augment_callbacks and the prototypes for + * rb_insert_augmented() and rb_erase_augmented() are intended to be public. + * The rest are implementation details you are not expected to depend on. + * + * See Documentation/rbtree.txt for documentation and samples. + */ + +struct rb_augment_callbacks { + void (*propagate)(struct rb_node *node, struct rb_node *stop); + void (*copy)(struct rb_node *old_node, struct rb_node *new_node); + void (*rotate)(struct rb_node *old_node, struct rb_node *new_node); +}; + +extern void __rb_insert_augmented(struct rb_node *node, struct rb_root *root, + void (*augment_rotate)(struct rb_node *old_node, struct rb_node *new_node)); +/* + * Fixup the rbtree and update the augmented information when rebalancing. + * + * On insertion, the user must update the augmented information on the path + * leading to the inserted node, then call rb_link_node() as usual and + * rb_augment_inserted() instead of the usual rb_insert_color() call. + * If rb_augment_inserted() rebalances the rbtree, it will callback into + * a user provided function to update the augmented information on the + * affected subtrees. + */ +static inline void +rb_insert_augmented(struct rb_node *node, struct rb_root *root, + const struct rb_augment_callbacks *augment) +{ + __rb_insert_augmented(node, root, augment->rotate); +} + +#define RB_DECLARE_CALLBACKS(rbstatic, rbname, rbstruct, rbfield, \ + rbtype, rbaugmented, rbcompute) \ +static inline void \ +rbname ## _propagate(struct rb_node *rb, struct rb_node *stop) \ +{ \ + while (rb != stop) { \ + rbstruct *node = rb_entry(rb, rbstruct, rbfield); \ + rbtype augmented = rbcompute(node); \ + if (node->rbaugmented == augmented) \ + break; \ + node->rbaugmented = augmented; \ + rb = rb_parent(&node->rbfield); \ + } \ +} \ +static inline void \ +rbname ## _copy(struct rb_node *rb_old, struct rb_node *rb_new) \ +{ \ + rbstruct *old_node = rb_entry(rb_old, rbstruct, rbfield); \ + rbstruct *new_node = rb_entry(rb_new, rbstruct, rbfield); \ + new_node->rbaugmented = old_node->rbaugmented; \ +} \ +static void \ +rbname ## _rotate(struct rb_node *rb_old, struct rb_node *rb_new) \ +{ \ + rbstruct *old_node = rb_entry(rb_old, rbstruct, rbfield); \ + rbstruct *new_node = rb_entry(rb_new, rbstruct, rbfield); \ + new_node->rbaugmented = old_node->rbaugmented; \ + old_node->rbaugmented = rbcompute(old_node); \ +} \ +rbstatic const struct rb_augment_callbacks rbname = { \ + rbname ## _propagate, rbname ## _copy, rbname ## _rotate \ +}; + + +#define RB_RED 0 +#define RB_BLACK 1 + +#define __rb_parent(pc) ((struct rb_node *)(pc & ~3)) + +#define __rb_color(pc) ((pc) & 1) +#define __rb_is_black(pc) __rb_color(pc) +#define __rb_is_red(pc) (!__rb_color(pc)) +#define rb_color(rb) __rb_color((rb)->__rb_parent_color) +#define rb_is_red(rb) __rb_is_red((rb)->__rb_parent_color) +#define rb_is_black(rb) __rb_is_black((rb)->__rb_parent_color) + +static inline void rb_set_parent(struct rb_node *rb, struct rb_node *p) +{ + rb->__rb_parent_color = rb_color(rb) | (unsigned long)p; +} + +static inline void rb_set_parent_color(struct rb_node *rb, + struct rb_node *p, int color) +{ + rb->__rb_parent_color = (unsigned long)p | color; +} + +static inline void +__rb_change_child(struct rb_node *old_node, struct rb_node *new_node, + struct rb_node *parent, struct rb_root *root) +{ + if (parent) { + if (parent->rb_left == old_node) + parent->rb_left = new_node; + else + parent->rb_right = new_node; + } else + root->rb_node = new_node; +} + +extern void __rb_erase_color(struct rb_node *parent, struct rb_root *root, + void (*augment_rotate)(struct rb_node *old_node, struct rb_node *new_node)); + +static inline struct rb_node * +__rb_erase_augmented(struct rb_node *node, struct rb_root *root, + const struct rb_augment_callbacks *augment) +{ + struct rb_node *child = node->rb_right, *tmp = node->rb_left; + struct rb_node *parent, *rebalance; + unsigned long pc; + + if (!tmp) { + /* + * Case 1: node to erase has no more than 1 child (easy!) + * + * Note that if there is one child it must be red due to 5) + * and node must be black due to 4). We adjust colors locally + * so as to bypass __rb_erase_color() later on. + */ + pc = node->__rb_parent_color; + parent = __rb_parent(pc); + __rb_change_child(node, child, parent, root); + if (child) { + child->__rb_parent_color = pc; + rebalance = NULL; + } else + rebalance = __rb_is_black(pc) ? parent : NULL; + tmp = parent; + } else if (!child) { + /* Still case 1, but this time the child is node->rb_left */ + tmp->__rb_parent_color = pc = node->__rb_parent_color; + parent = __rb_parent(pc); + __rb_change_child(node, tmp, parent, root); + rebalance = NULL; + tmp = parent; + } else { + struct rb_node *successor = child, *child2; + tmp = child->rb_left; + if (!tmp) { + /* + * Case 2: node's successor is its right child + * + * (n) (s) + * / \ / \ + * (x) (s) -> (x) (c) + * \ + * (c) + */ + parent = successor; + child2 = successor->rb_right; + augment->copy(node, successor); + } else { + /* + * Case 3: node's successor is leftmost under + * node's right child subtree + * + * (n) (s) + * / \ / \ + * (x) (y) -> (x) (y) + * / / + * (p) (p) + * / / + * (s) (c) + * \ + * (c) + */ + do { + parent = successor; + successor = tmp; + tmp = tmp->rb_left; + } while (tmp); + parent->rb_left = child2 = successor->rb_right; + successor->rb_right = child; + rb_set_parent(child, successor); + augment->copy(node, successor); + augment->propagate(parent, successor); + } + + successor->rb_left = tmp = node->rb_left; + rb_set_parent(tmp, successor); + + pc = node->__rb_parent_color; + tmp = __rb_parent(pc); + __rb_change_child(node, successor, tmp, root); + if (child2) { + successor->__rb_parent_color = pc; + rb_set_parent_color(child2, parent, RB_BLACK); + rebalance = NULL; + } else { + unsigned long pc2 = successor->__rb_parent_color; + successor->__rb_parent_color = pc; + rebalance = __rb_is_black(pc2) ? parent : NULL; + } + tmp = successor; + } + + augment->propagate(tmp, NULL); + return rebalance; +} + +static inline void +rb_erase_augmented(struct rb_node *node, struct rb_root *root, + const struct rb_augment_callbacks *augment) +{ + struct rb_node *rebalance = __rb_erase_augmented(node, root, augment); + if (rebalance) + __rb_erase_color(rebalance, root, augment->rotate); +} + +#endif /* _GENERIC_RBTREE_H */ + diff --git a/release/src/router/smartdns/src/include/stringutil.h b/release/src/router/smartdns/src/include/stringutil.h index 4d6ea6be57..626a58c8db 100644 --- a/release/src/router/smartdns/src/include/stringutil.h +++ b/release/src/router/smartdns/src/include/stringutil.h @@ -1,42 +1,42 @@ -/************************************************************************* - * - * Copyright (C) 2018-2020 Ruilin Peng (Nick) . - * - * smartdns is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * smartdns is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#ifndef _GENERIC_STRING_UITL_H -#define _GENERIC_STRING_UITL_H - -#include -#include - -static inline char *safe_strncpy(char *dest, const char *src, size_t n) -{ -#if __GNUC__ > 7 -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wstringop-truncation" -#endif - char *ret = strncpy(dest, src, n - 1); - if (n > 0) { - dest[n - 1] = '\0'; - } -#if __GNUC__ > 7 -#pragma GCC diagnostic pop -#endif - return ret; -} - - -#endif +/************************************************************************* + * + * Copyright (C) 2018-2020 Ruilin Peng (Nick) . + * + * smartdns is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * smartdns is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef _GENERIC_STRING_UITL_H +#define _GENERIC_STRING_UITL_H + +#include +#include + +static inline char *safe_strncpy(char *dest, const char *src, size_t n) +{ +#if __GNUC__ > 7 +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wstringop-truncation" +#endif + char *ret = strncpy(dest, src, n - 1); + if (n > 0) { + dest[n - 1] = '\0'; + } +#if __GNUC__ > 7 +#pragma GCC diagnostic pop +#endif + return ret; +} + + +#endif diff --git a/release/src/router/smartdns/src/lib/art.c b/release/src/router/smartdns/src/lib/art.c index be5a672056..d4308e3f96 100644 --- a/release/src/router/smartdns/src/lib/art.c +++ b/release/src/router/smartdns/src/lib/art.c @@ -1,1129 +1,1129 @@ -/* -Copyright (c) 2012, Armon Dadgar -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the organization nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL ARMON DADGAR BE LIABLE FOR ANY -DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include -#include -#include -#include -#include -#include "art.h" - -// #ifdef __i386__ -// #include -// #else -#ifdef __amd64__ - #include -#endif -// #endif - -/** - * Macros to manipulate pointer tags - */ -#define IS_LEAF(x) (((uintptr_t)x & 1)) -#define SET_LEAF(x) ((void*)((uintptr_t)x | 1)) -#define LEAF_RAW(x) ((art_leaf*)((void*)((uintptr_t)x & ~1))) - -/** - * Allocates a node of the given type, - * initializes to zero and sets the type. - */ -static art_node* alloc_node(uint8_t type) { - art_node* n; - void *mem = NULL; - switch (type) { - case NODE4: - mem = (art_node*)calloc(1, sizeof(art_node4)); - break; - case NODE16: - mem = (art_node*)calloc(1, sizeof(art_node16)); - break; - case NODE48: - mem = (art_node*)calloc(1, sizeof(art_node48)); - break; - case NODE256: - mem = (art_node*)calloc(1, sizeof(art_node256)); - break; - default: - abort(); - } - if (mem == NULL) { - abort(); - } - n = mem; - n->type = type; - return n; -} - -/** - * Initializes an ART tree - * @return 0 on success. - */ -int art_tree_init(art_tree *t) { - t->root = NULL; - t->size = 0; - return 0; -} - -// Recursively destroys the tree -static void destroy_node(art_node *n) { - // Break if null - if (!n) return; - - // Special case leafs - if (IS_LEAF(n)) { - free(LEAF_RAW(n)); - return; - } - - // Handle each node type - int i, idx; - union { - art_node4 *p1; - art_node16 *p2; - art_node48 *p3; - art_node256 *p4; - } p; - switch (n->type) { - case NODE4: - p.p1 = (art_node4*)n; - for (i=0;inum_children;i++) { - destroy_node(p.p1->children[i]); - } - break; - - case NODE16: - p.p2 = (art_node16*)n; - for (i=0;inum_children;i++) { - destroy_node(p.p2->children[i]); - } - break; - - case NODE48: - p.p3 = (art_node48*)n; - for (i=0;i<256;i++) { - idx = ((art_node48*)n)->keys[i]; - if (!idx) continue; - destroy_node(p.p3->children[idx-1]); - } - break; - - case NODE256: - p.p4 = (art_node256*)n; - for (i=0;i<256;i++) { - if (p.p4->children[i]) - destroy_node(p.p4->children[i]); - } - break; - - default: - abort(); - } - - // Free ourself on the way up - free(n); -} - -/** - * Destroys an ART tree - * @return 0 on success. - */ -int art_tree_destroy(art_tree *t) { - destroy_node(t->root); - return 0; -} - -/** - * Returns the size of the ART tree. - */ - -#ifndef BROKEN_GCC_C99_INLINE -extern inline uint64_t art_size(art_tree *t); -#endif - -static art_node** find_child(art_node *n, unsigned char c) { - int i, mask, bitfield; - union { - art_node4 *p1; - art_node16 *p2; - art_node48 *p3; - art_node256 *p4; - } p; - switch (n->type) { - case NODE4: - p.p1 = (art_node4*)n; - for (i=0 ; i < n->num_children; i++) { - /* this cast works around a bug in gcc 5.1 when unrolling loops - * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=59124 - */ - if (((unsigned char*)p.p1->keys)[i] == c) - return &p.p1->children[i]; - } - break; - - { - case NODE16: - p.p2 = (art_node16*)n; - - // support non-86 architectures - - // #ifdef __i386__ - // // Compare the key to all 16 stored keys - // __m128i cmp; - // cmp = _mm_cmpeq_epi8(_mm_set1_epi8(c), - // _mm_loadu_si128((__m128i*)p.p2->keys)); - - // // Use a mask to ignore children that don't exist - // mask = (1 << n->num_children) - 1; - // bitfield = _mm_movemask_epi8(cmp) & mask; - // #else - #ifdef __amd64__ - // Compare the key to all 16 stored keys - __m128i cmp; - cmp = _mm_cmpeq_epi8(_mm_set1_epi8(c), - _mm_loadu_si128((__m128i*)p.p2->keys)); - - // Use a mask to ignore children that don't exist - mask = (1 << n->num_children) - 1; - bitfield = _mm_movemask_epi8(cmp) & mask; - #else - // Compare the key to all 16 stored keys - bitfield = 0; - for (i = 0; i < 16; ++i) { - if (p.p2->keys[i] == c) - bitfield |= (1 << i); - } - - // Use a mask to ignore children that don't exist - mask = (1 << n->num_children) - 1; - bitfield &= mask; - #endif - // #endif - - /* - * If we have a match (any bit set) then we can - * return the pointer match using ctz to get - * the index. - */ - if (bitfield) - return &p.p2->children[__builtin_ctz(bitfield)]; - break; - } - - case NODE48: - p.p3 = (art_node48*)n; - i = p.p3->keys[c]; - if (i) - return &p.p3->children[i-1]; - break; - - case NODE256: - p.p4 = (art_node256*)n; - if (p.p4->children[c]) - return &p.p4->children[c]; - break; - - default: - abort(); - } - return NULL; -} - -// Simple inlined if -static inline int min(int a, int b) { - return (a < b) ? a : b; -} - -/** - * Returns the number of prefix characters shared between - * the key and node. - */ -static int check_prefix(const art_node *n, const unsigned char *key, int key_len, int depth) { - int max_cmp = min(min(n->partial_len, MAX_PREFIX_LEN), key_len - depth); - int idx; - for (idx=0; idx < max_cmp; idx++) { - if (n->partial[idx] != key[depth+idx]) - return idx; - } - return idx; -} - -/** - * Checks if a leaf matches - * @return 0 on success. - */ -static int leaf_matches(const art_leaf *n, const unsigned char *key, int key_len, int depth) { - (void)depth; - // Fail if the key lengths are different - if (n->key_len != (uint32_t)key_len) return 1; - - // Compare the keys starting at the depth - return memcmp(n->key, key, key_len); -} - -/** - * Searches for a value in the ART tree - * @arg t The tree - * @arg key The key - * @arg key_len The length of the key - * @return NULL if the item was not found, otherwise - * the value pointer is returned. - */ -void* art_search(const art_tree *t, const unsigned char *key, int key_len) { - art_node **child; - art_node *n = t->root; - int prefix_len, depth = 0; - while (n) { - // Might be a leaf - if (IS_LEAF(n)) { - n = (art_node*)LEAF_RAW(n); - // Check if the expanded path matches - if (!leaf_matches((art_leaf*)n, key, key_len, depth)) { - return ((art_leaf*)n)->value; - } - return NULL; - } - - // Bail if the prefix does not match - if (n->partial_len) { - prefix_len = check_prefix(n, key, key_len, depth); - if (prefix_len != min(MAX_PREFIX_LEN, n->partial_len)) - return NULL; - depth = depth + n->partial_len; - } - - // Recursively search - child = find_child(n, key[depth]); - n = (child) ? *child : NULL; - depth++; - } - return NULL; -} - -// Find the minimum leaf under a node -static art_leaf* minimum(const art_node *n) { - // Handle base cases - if (!n) return NULL; - if (IS_LEAF(n)) return LEAF_RAW(n); - - int idx; - switch (n->type) { - case NODE4: - return minimum(((const art_node4*)n)->children[0]); - case NODE16: - return minimum(((const art_node16*)n)->children[0]); - case NODE48: - idx=0; - while (!((const art_node48*)n)->keys[idx]) idx++; - idx = ((const art_node48*)n)->keys[idx] - 1; - return minimum(((const art_node48*)n)->children[idx]); - case NODE256: - idx=0; - while (!((const art_node256*)n)->children[idx]) idx++; - return minimum(((const art_node256*)n)->children[idx]); - default: - abort(); - } -} - -// Find the maximum leaf under a node -static art_leaf* maximum(const art_node *n) { - // Handle base cases - if (!n) return NULL; - if (IS_LEAF(n)) return LEAF_RAW(n); - - int idx; - switch (n->type) { - case NODE4: - return maximum(((const art_node4*)n)->children[n->num_children-1]); - case NODE16: - return maximum(((const art_node16*)n)->children[n->num_children-1]); - case NODE48: - idx=255; - while (!((const art_node48*)n)->keys[idx]) idx--; - idx = ((const art_node48*)n)->keys[idx] - 1; - return maximum(((const art_node48*)n)->children[idx]); - case NODE256: - idx=255; - while (!((const art_node256*)n)->children[idx]) idx--; - return maximum(((const art_node256*)n)->children[idx]); - default: - abort(); - } -} - -/** - * Returns the minimum valued leaf - */ -art_leaf* art_minimum(art_tree *t) { - return minimum((art_node*)t->root); -} - -/** - * Returns the maximum valued leaf - */ -art_leaf* art_maximum(art_tree *t) { - return maximum((art_node*)t->root); -} - -static art_leaf* make_leaf(const unsigned char *key, int key_len, void *value) { - art_leaf *l = (art_leaf*)calloc(1, sizeof(art_leaf)+key_len+1); - if (l == NULL) { - return NULL; - } - - l->value = value; - l->key_len = key_len; - memcpy(l->key, key, key_len); - return l; -} - -static int longest_common_prefix(art_leaf *l1, art_leaf *l2, int depth) { - int max_cmp = min(l1->key_len, l2->key_len) - depth; - int idx; - for (idx=0; idx < max_cmp; idx++) { - if (l1->key[depth+idx] != l2->key[depth+idx]) - return idx; - } - return idx; -} - -static void copy_header(art_node *dest, art_node *src) { - dest->num_children = src->num_children; - dest->partial_len = src->partial_len; - memcpy(dest->partial, src->partial, min(MAX_PREFIX_LEN, src->partial_len)); -} - -static void add_child256(art_node256 *n, art_node **ref, unsigned char c, void *child) { - (void)ref; - n->n.num_children++; - n->children[c] = (art_node*)child; -} - -static void add_child48(art_node48 *n, art_node **ref, unsigned char c, void *child) { - if (n->n.num_children < 48) { - int pos = 0; - while (n->children[pos]) pos++; - n->children[pos] = (art_node*)child; - n->keys[c] = pos + 1; - n->n.num_children++; - } else { - art_node256 *new_node = (art_node256*)alloc_node(NODE256); - int i; - for (i=0;i<256;i++) { - if (n->keys[i]) { - new_node->children[i] = n->children[n->keys[i] - 1]; - } - } - copy_header((art_node*)new_node, (art_node*)n); - *ref = (art_node*)new_node; - free(n); - add_child256(new_node, ref, c, child); - } -} - -static void add_child16(art_node16 *n, art_node **ref, unsigned char c, void *child) { - if (n->n.num_children < 16) { - unsigned mask = (1 << n->n.num_children) - 1; - - // support non-x86 architectures - // #ifdef __i386__ - // __m128i cmp; - - // // Compare the key to all 16 stored keys - // cmp = _mm_cmplt_epi8(_mm_set1_epi8(c), - // _mm_loadu_si128((__m128i*)n->keys)); - - // // Use a mask to ignore children that don't exist - // unsigned bitfield = _mm_movemask_epi8(cmp) & mask; - // #else - #ifdef __amd64__ - __m128i cmp; - - // Compare the key to all 16 stored keys - cmp = _mm_cmplt_epi8(_mm_set1_epi8(c), - _mm_loadu_si128((__m128i*)n->keys)); - - // Use a mask to ignore children that don't exist - unsigned bitfield = _mm_movemask_epi8(cmp) & mask; - #else - // Compare the key to all 16 stored keys - unsigned bitfield = 0; - int i; - for (i = 0; i < 16; ++i) { - if (c < n->keys[i]) - bitfield |= (1 << i); - } - - // Use a mask to ignore children that don't exist - bitfield &= mask; - #endif - // #endif - - // Check if less than any - unsigned idx; - if (bitfield) { - idx = __builtin_ctz(bitfield); - memmove(n->keys+idx+1,n->keys+idx,n->n.num_children-idx); - memmove(n->children+idx+1,n->children+idx, - (n->n.num_children-idx)*sizeof(void*)); - } else - idx = n->n.num_children; - - // Set the child - n->keys[idx] = c; - n->children[idx] = (art_node*)child; - n->n.num_children++; - - } else { - art_node48 *new_node = (art_node48*)alloc_node(NODE48); - int i; - - // Copy the child pointers and populate the key map - memcpy(new_node->children, n->children, - sizeof(void*)*n->n.num_children); - for (i=0;in.num_children;i++) { - new_node->keys[n->keys[i]] = i + 1; - } - copy_header((art_node*)new_node, (art_node*)n); - *ref = (art_node*)new_node; - free(n); - add_child48(new_node, ref, c, child); - } -} - -static void add_child4(art_node4 *n, art_node **ref, unsigned char c, void *child) { - if (n->n.num_children < 4) { - int idx; - for (idx=0; idx < n->n.num_children; idx++) { - if (c < n->keys[idx]) break; - } - - // Shift to make room - memmove(n->keys+idx+1, n->keys+idx, n->n.num_children - idx); - memmove(n->children+idx+1, n->children+idx, - (n->n.num_children - idx)*sizeof(void*)); - - // Insert element - n->keys[idx] = c; - n->children[idx] = (art_node*)child; - n->n.num_children++; - - } else { - art_node16 *new_node = (art_node16*)alloc_node(NODE16); - - // Copy the child pointers and the key map - memcpy(new_node->children, n->children, - sizeof(void*)*n->n.num_children); - memcpy(new_node->keys, n->keys, - sizeof(unsigned char)*n->n.num_children); - copy_header((art_node*)new_node, (art_node*)n); - *ref = (art_node*)new_node; - free(n); - add_child16(new_node, ref, c, child); - } -} - -static void add_child(art_node *n, art_node **ref, unsigned char c, void *child) { - switch (n->type) { - case NODE4: - return add_child4((art_node4*)n, ref, c, child); - case NODE16: - return add_child16((art_node16*)n, ref, c, child); - case NODE48: - return add_child48((art_node48*)n, ref, c, child); - case NODE256: - return add_child256((art_node256*)n, ref, c, child); - default: - abort(); - } -} - -/** - * Calculates the index at which the prefixes mismatch - */ -static int prefix_mismatch(const art_node *n, const unsigned char *key, int key_len, int depth) { - int max_cmp = min(min(MAX_PREFIX_LEN, n->partial_len), key_len - depth); - int idx; - for (idx=0; idx < max_cmp; idx++) { - if (n->partial[idx] != key[depth+idx]) - return idx; - } - - // If the prefix is short we can avoid finding a leaf - if (n->partial_len > MAX_PREFIX_LEN) { - // Prefix is longer than what we've checked, find a leaf - art_leaf *l = minimum(n); - max_cmp = min(l->key_len, key_len)- depth; - for (; idx < max_cmp; idx++) { - if (l->key[idx+depth] != key[depth+idx]) - return idx; - } - } - return idx; -} - -static void* recursive_insert(art_node *n, art_node **ref, const unsigned char *key, int key_len, void *value, int depth, int *old) { - // If we are at a NULL node, inject a leaf - if (!n) { - *ref = (art_node*)SET_LEAF(make_leaf(key, key_len, value)); - return NULL; - } - - // If we are at a leaf, we need to replace it with a node - if (IS_LEAF(n)) { - art_leaf *l = LEAF_RAW(n); - - // Check if we are updating an existing value - if (!leaf_matches(l, key, key_len, depth)) { - *old = 1; - void *old_val = l->value; - l->value = value; - return old_val; - } - - // New value, we must split the leaf into a node4 - art_node4 *new_node = (art_node4*)alloc_node(NODE4); - - // Create a new leaf - art_leaf *l2 = make_leaf(key, key_len, value); - - // Determine longest prefix - int longest_prefix = longest_common_prefix(l, l2, depth); - new_node->n.partial_len = longest_prefix; - memcpy(new_node->n.partial, key+depth, min(MAX_PREFIX_LEN, longest_prefix)); - // Add the leafs to the new node4 - *ref = (art_node*)new_node; - add_child4(new_node, ref, l->key[depth+longest_prefix], SET_LEAF(l)); - add_child4(new_node, ref, l2->key[depth+longest_prefix], SET_LEAF(l2)); - return NULL; - } - - // Check if given node has a prefix - if (n->partial_len) { - // Determine if the prefixes differ, since we need to split - int prefix_diff = prefix_mismatch(n, key, key_len, depth); - if ((uint32_t)prefix_diff >= n->partial_len) { - depth += n->partial_len; - goto RECURSE_SEARCH; - } - - // Create a new node - art_node4 *new_node = (art_node4*)alloc_node(NODE4); - *ref = (art_node*)new_node; - new_node->n.partial_len = prefix_diff; - memcpy(new_node->n.partial, n->partial, min(MAX_PREFIX_LEN, prefix_diff)); - - // Adjust the prefix of the old node - if (n->partial_len <= MAX_PREFIX_LEN) { - add_child4(new_node, ref, n->partial[prefix_diff], n); - n->partial_len -= (prefix_diff+1); - memmove(n->partial, n->partial+prefix_diff+1, - min(MAX_PREFIX_LEN, n->partial_len)); - } else { - n->partial_len -= (prefix_diff+1); - art_leaf *l = minimum(n); - add_child4(new_node, ref, l->key[depth+prefix_diff], n); - memcpy(n->partial, l->key+depth+prefix_diff+1, - min(MAX_PREFIX_LEN, n->partial_len)); - } - - // Insert the new leaf - art_leaf *l = make_leaf(key, key_len, value); - add_child4(new_node, ref, key[depth+prefix_diff], SET_LEAF(l)); - return NULL; - } - -RECURSE_SEARCH:; - - // Find a child to recurse to - art_node **child = find_child(n, key[depth]); - if (child) { - return recursive_insert(*child, child, key, key_len, value, depth+1, old); - } - - // No child, node goes within us - art_leaf *l = make_leaf(key, key_len, value); - add_child(n, ref, key[depth], SET_LEAF(l)); - return NULL; -} - -/** - * Inserts a new value into the ART tree - * @arg t The tree - * @arg key The key - * @arg key_len The length of the key - * @arg value Opaque value. - * @return NULL if the item was newly inserted, otherwise - * the old value pointer is returned. - */ -void* art_insert(art_tree *t, const unsigned char *key, int key_len, void *value) { - int old_val = 0; - void *old = recursive_insert(t->root, &t->root, key, key_len, value, 0, &old_val); - if (!old_val) t->size++; - return old; -} - -static void remove_child256(art_node256 *n, art_node **ref, unsigned char c) { - n->children[c] = NULL; - n->n.num_children--; - - // Resize to a node48 on underflow, not immediately to prevent - // trashing if we sit on the 48/49 boundary - if (n->n.num_children == 37) { - art_node48 *new_node = (art_node48*)alloc_node(NODE48); - *ref = (art_node*)new_node; - copy_header((art_node*)new_node, (art_node*)n); - - int pos = 0; - int i; - for (i=0;i<256;i++) { - if (n->children[i]) { - new_node->children[pos] = n->children[i]; - new_node->keys[i] = pos + 1; - pos++; - } - } - free(n); - } -} - -static void remove_child48(art_node48 *n, art_node **ref, unsigned char c) { - int pos = n->keys[c]; - n->keys[c] = 0; - n->children[pos-1] = NULL; - n->n.num_children--; - - if (n->n.num_children == 12) { - art_node16 *new_node = (art_node16*)alloc_node(NODE16); - *ref = (art_node*)new_node; - copy_header((art_node*)new_node, (art_node*)n); - - int child = 0; - int i; - for (i=0;i<256;i++) { - pos = n->keys[i]; - if (pos) { - new_node->keys[child] = i; - new_node->children[child] = n->children[pos - 1]; - child++; - } - } - free(n); - } -} - -static void remove_child16(art_node16 *n, art_node **ref, art_node **l) { - int pos = l - n->children; - memmove(n->keys+pos, n->keys+pos+1, n->n.num_children - 1 - pos); - memmove(n->children+pos, n->children+pos+1, (n->n.num_children - 1 - pos)*sizeof(void*)); - n->n.num_children--; - - if (n->n.num_children == 3) { - art_node4 *new_node = (art_node4*)alloc_node(NODE4); - *ref = (art_node*)new_node; - copy_header((art_node*)new_node, (art_node*)n); - memcpy(new_node->keys, n->keys, 4); - memcpy(new_node->children, n->children, 4*sizeof(void*)); - free(n); - } -} - -static void remove_child4(art_node4 *n, art_node **ref, art_node **l) { - int pos = l - n->children; - memmove(n->keys+pos, n->keys+pos+1, n->n.num_children - 1 - pos); - memmove(n->children+pos, n->children+pos+1, (n->n.num_children - 1 - pos)*sizeof(void*)); - n->n.num_children--; - - // Remove nodes with only a single child - if (n->n.num_children == 1) { - art_node *child = n->children[0]; - if (!IS_LEAF(child)) { - // Concatenate the prefixes - int prefix = n->n.partial_len; - if (prefix < MAX_PREFIX_LEN) { - n->n.partial[prefix] = n->keys[0]; - prefix++; - } - if (prefix < MAX_PREFIX_LEN) { - int sub_prefix = min(child->partial_len, MAX_PREFIX_LEN - prefix); - memcpy(n->n.partial+prefix, child->partial, sub_prefix); - prefix += sub_prefix; - } - - // Store the prefix in the child - memcpy(child->partial, n->n.partial, min(prefix, MAX_PREFIX_LEN)); - child->partial_len += n->n.partial_len + 1; - } - *ref = child; - free(n); - } -} - -static void remove_child(art_node *n, art_node **ref, unsigned char c, art_node **l) { - switch (n->type) { - case NODE4: - return remove_child4((art_node4*)n, ref, l); - case NODE16: - return remove_child16((art_node16*)n, ref, l); - case NODE48: - return remove_child48((art_node48*)n, ref, c); - case NODE256: - return remove_child256((art_node256*)n, ref, c); - default: - abort(); - } -} - -static art_leaf* recursive_delete(art_node *n, art_node **ref, const unsigned char *key, int key_len, int depth) { - // Search terminated - if (!n) return NULL; - - // Handle hitting a leaf node - if (IS_LEAF(n)) { - art_leaf *l = LEAF_RAW(n); - if (!leaf_matches(l, key, key_len, depth)) { - *ref = NULL; - return l; - } - return NULL; - } - - // Bail if the prefix does not match - if (n->partial_len) { - int prefix_len = check_prefix(n, key, key_len, depth); - if (prefix_len != min(MAX_PREFIX_LEN, n->partial_len)) { - return NULL; - } - depth = depth + n->partial_len; - } - - // Find child node - art_node **child = find_child(n, key[depth]); - if (!child) return NULL; - - // If the child is leaf, delete from this node - if (IS_LEAF(*child)) { - art_leaf *l = LEAF_RAW(*child); - if (!leaf_matches(l, key, key_len, depth)) { - remove_child(n, ref, key[depth], child); - return l; - } - return NULL; - - // Recurse - } else { - return recursive_delete(*child, child, key, key_len, depth+1); - } -} - -/** - * Deletes a value from the ART tree - * @arg t The tree - * @arg key The key - * @arg key_len The length of the key - * @return NULL if the item was not found, otherwise - * the value pointer is returned. - */ -void* art_delete(art_tree *t, const unsigned char *key, int key_len) { - art_leaf *l = recursive_delete(t->root, &t->root, key, key_len, 0); - if (l) { - t->size--; - void *old = l->value; - free(l); - return old; - } - return NULL; -} - -// Recursively iterates over the tree -static int recursive_iter(art_node *n, art_callback cb, void *data) { - // Handle base cases - if (!n) return 0; - if (IS_LEAF(n)) { - art_leaf *l = LEAF_RAW(n); - return cb(data, (const unsigned char*)l->key, l->key_len, l->value); - } - - int idx, res; - int i; - switch (n->type) { - case NODE4: - for (i=0; i < n->num_children; i++) { - res = recursive_iter(((art_node4*)n)->children[i], cb, data); - if (res) return res; - } - break; - - case NODE16: - for (i=0; i < n->num_children; i++) { - res = recursive_iter(((art_node16*)n)->children[i], cb, data); - if (res) return res; - } - break; - - case NODE48: - for (i=0; i < 256; i++) { - idx = ((art_node48*)n)->keys[i]; - if (!idx) continue; - - res = recursive_iter(((art_node48*)n)->children[idx-1], cb, data); - if (res) return res; - } - break; - - case NODE256: - for (i=0; i < 256; i++) { - if (!((art_node256*)n)->children[i]) continue; - res = recursive_iter(((art_node256*)n)->children[i], cb, data); - if (res) return res; - } - break; - - default: - abort(); - } - return 0; -} - -/** - * Iterates through the entries pairs in the map, - * invoking a callback for each. The call back gets a - * key, value for each and returns an integer stop value. - * If the callback returns non-zero, then the iteration stops. - * @arg t The tree to iterate over - * @arg cb The callback function to invoke - * @arg data Opaque handle passed to the callback - * @return 0 on success, or the return of the callback. - */ -int art_iter(art_tree *t, art_callback cb, void *data) { - return recursive_iter(t->root, cb, data); -} - -/** - * Checks if a leaf prefix matches - * @return 0 on success. - */ -static int leaf_prefix_matches(const art_leaf *n, const unsigned char *prefix, int prefix_len) { - // Fail if the key length is too short - if (n->key_len < (uint32_t)prefix_len) return 1; - - // Compare the keys - return memcmp(n->key, prefix, prefix_len); -} - -/** - * Iterates through the entries pairs in the map, - * invoking a callback for each that matches a given prefix. - * The call back gets a key, value for each and returns an integer stop value. - * If the callback returns non-zero, then the iteration stops. - * @arg t The tree to iterate over - * @arg prefix The prefix of keys to read - * @arg prefix_len The length of the prefix - * @arg cb The callback function to invoke - * @arg data Opaque handle passed to the callback - * @return 0 on success, or the return of the callback. - */ -int art_iter_prefix(art_tree *t, const unsigned char *key, int key_len, art_callback cb, void *data) { - art_node **child; - art_node *n = t->root; - int prefix_len, depth = 0; - while (n) { - // Might be a leaf - if (IS_LEAF(n)) { - n = (art_node*)LEAF_RAW(n); - // Check if the expanded path matches - if (!leaf_prefix_matches((art_leaf*)n, key, key_len)) { - art_leaf *l = (art_leaf*)n; - return cb(data, (const unsigned char*)l->key, l->key_len, l->value); - } - return 0; - } - - // If the depth matches the prefix, we need to handle this node - if (depth == key_len) { - art_leaf *l = minimum(n); - if (!leaf_prefix_matches(l, key, key_len)) - return recursive_iter(n, cb, data); - return 0; - } - - // Bail if the prefix does not match - if (n->partial_len) { - prefix_len = prefix_mismatch(n, key, key_len, depth); - - // Guard if the mis-match is longer than the MAX_PREFIX_LEN - if ((uint32_t)prefix_len > n->partial_len) { - prefix_len = n->partial_len; - } - - // If there is no match, search is terminated - if (!prefix_len) { - return 0; - - // If we've matched the prefix, iterate on this node - } else if (depth + prefix_len == key_len) { - return recursive_iter(n, cb, data); - } - - // if there is a full match, go deeper - depth = depth + n->partial_len; - } - - // Recursively search - child = find_child(n, key[depth]); - n = (child) ? *child : NULL; - depth++; - } - return 0; -} - -static int str_prefix_matches(const art_leaf *n, const unsigned char *str, int str_len) { - // Fail if the key length is too short - if (n->key_len > (uint32_t)str_len) return 1; - - // Compare the keys - return memcmp(str, n->key, n->key_len); -} - -static void art_copy_key(art_leaf *leaf, unsigned char *key, int *key_len) -{ - int len; - - if (key == NULL || key_len == NULL) { - return; - } - - len = leaf->key_len > *key_len ? *key_len : leaf->key_len; - memcpy(key, leaf->key, len); - *key_len = len; -} - -void *art_substring(const art_tree *t, const unsigned char *str, int str_len, unsigned char *key, int *key_len) -{ - art_node **child; - art_node *n = t->root; - art_node *m; - art_leaf *found = NULL; - int prefix_len, depth = 0; - - while (n) { - // Might be a leaf - if (IS_LEAF(n)) { - n = (art_node*)LEAF_RAW(n); - // Check if the expanded path matches - if (!str_prefix_matches((art_leaf*)n, str, str_len)) { - found = (art_leaf*)n; - } - break; - } - - // Check if current is leaf - child = find_child(n, 0); - m = (child) ? *child : NULL; - if (m && IS_LEAF(m)) { - m = (art_node*)LEAF_RAW(m); - // Check if the expanded path matches - if (!str_prefix_matches((art_leaf*)m, str, str_len)) { - found = (art_leaf*)m; - } - } - - // Bail if the prefix does not match - if (n->partial_len) { - prefix_len = check_prefix(n, str, str_len, depth); - if (prefix_len != min(MAX_PREFIX_LEN, n->partial_len)) - break; - depth = depth + n->partial_len; - } - - // Recursively search - child = find_child(n, str[depth]); - n = (child) ? *child : NULL; - depth++; - } - - if (found == NULL) { - return NULL; - } - - art_copy_key(found, key, key_len); - - return found->value; -} - -void art_substring_walk(const art_tree *t, const unsigned char *str, int str_len, walk_func func, void *arg) -{ - art_node **child; - art_node *n = t->root; - art_node *m; - art_leaf *found = NULL; - int prefix_len, depth = 0; - int stop_search = 0; - - while (n && stop_search == 0) { - // Might be a leaf - if (IS_LEAF(n)) { - n = (art_node*)LEAF_RAW(n); - // Check if the expanded path matches - if (!str_prefix_matches((art_leaf*)n, str, str_len)) { - found = (art_leaf*)n; - stop_search = func(found->key, found->key_len, found->value, arg); - } - break; - } - - // Check if current is leaf - child = find_child(n, 0); - m = (child) ? *child : NULL; - if (m && IS_LEAF(m)) { - m = (art_node*)LEAF_RAW(m); - // Check if the expanded path matches - if (!str_prefix_matches((art_leaf*)m, str, str_len)) { - found = (art_leaf*)m; - stop_search = func(found->key, found->key_len, found->value, arg); - } - } - - // Bail if the prefix does not match - if (n->partial_len) { - prefix_len = check_prefix(n, str, str_len, depth); - if (prefix_len != min(MAX_PREFIX_LEN, n->partial_len)) - break; - depth = depth + n->partial_len; - } - - // Recursively search - child = find_child(n, str[depth]); - n = (child) ? *child : NULL; - depth++; - } - - if (found == NULL) { - return ; - } - - return ; -} +/* +Copyright (c) 2012, Armon Dadgar +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the organization nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL ARMON DADGAR BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include +#include +#include +#include +#include +#include "art.h" + +// #ifdef __i386__ +// #include +// #else +#ifdef __amd64__ + #include +#endif +// #endif + +/** + * Macros to manipulate pointer tags + */ +#define IS_LEAF(x) (((uintptr_t)x & 1)) +#define SET_LEAF(x) ((void*)((uintptr_t)x | 1)) +#define LEAF_RAW(x) ((art_leaf*)((void*)((uintptr_t)x & ~1))) + +/** + * Allocates a node of the given type, + * initializes to zero and sets the type. + */ +static art_node* alloc_node(uint8_t type) { + art_node* n; + void *mem = NULL; + switch (type) { + case NODE4: + mem = (art_node*)calloc(1, sizeof(art_node4)); + break; + case NODE16: + mem = (art_node*)calloc(1, sizeof(art_node16)); + break; + case NODE48: + mem = (art_node*)calloc(1, sizeof(art_node48)); + break; + case NODE256: + mem = (art_node*)calloc(1, sizeof(art_node256)); + break; + default: + abort(); + } + if (mem == NULL) { + abort(); + } + n = mem; + n->type = type; + return n; +} + +/** + * Initializes an ART tree + * @return 0 on success. + */ +int art_tree_init(art_tree *t) { + t->root = NULL; + t->size = 0; + return 0; +} + +// Recursively destroys the tree +static void destroy_node(art_node *n) { + // Break if null + if (!n) return; + + // Special case leafs + if (IS_LEAF(n)) { + free(LEAF_RAW(n)); + return; + } + + // Handle each node type + int i, idx; + union { + art_node4 *p1; + art_node16 *p2; + art_node48 *p3; + art_node256 *p4; + } p; + switch (n->type) { + case NODE4: + p.p1 = (art_node4*)n; + for (i=0;inum_children;i++) { + destroy_node(p.p1->children[i]); + } + break; + + case NODE16: + p.p2 = (art_node16*)n; + for (i=0;inum_children;i++) { + destroy_node(p.p2->children[i]); + } + break; + + case NODE48: + p.p3 = (art_node48*)n; + for (i=0;i<256;i++) { + idx = ((art_node48*)n)->keys[i]; + if (!idx) continue; + destroy_node(p.p3->children[idx-1]); + } + break; + + case NODE256: + p.p4 = (art_node256*)n; + for (i=0;i<256;i++) { + if (p.p4->children[i]) + destroy_node(p.p4->children[i]); + } + break; + + default: + abort(); + } + + // Free ourself on the way up + free(n); +} + +/** + * Destroys an ART tree + * @return 0 on success. + */ +int art_tree_destroy(art_tree *t) { + destroy_node(t->root); + return 0; +} + +/** + * Returns the size of the ART tree. + */ + +#ifndef BROKEN_GCC_C99_INLINE +extern inline uint64_t art_size(art_tree *t); +#endif + +static art_node** find_child(art_node *n, unsigned char c) { + int i, mask, bitfield; + union { + art_node4 *p1; + art_node16 *p2; + art_node48 *p3; + art_node256 *p4; + } p; + switch (n->type) { + case NODE4: + p.p1 = (art_node4*)n; + for (i=0 ; i < n->num_children; i++) { + /* this cast works around a bug in gcc 5.1 when unrolling loops + * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=59124 + */ + if (((unsigned char*)p.p1->keys)[i] == c) + return &p.p1->children[i]; + } + break; + + { + case NODE16: + p.p2 = (art_node16*)n; + + // support non-86 architectures + + // #ifdef __i386__ + // // Compare the key to all 16 stored keys + // __m128i cmp; + // cmp = _mm_cmpeq_epi8(_mm_set1_epi8(c), + // _mm_loadu_si128((__m128i*)p.p2->keys)); + + // // Use a mask to ignore children that don't exist + // mask = (1 << n->num_children) - 1; + // bitfield = _mm_movemask_epi8(cmp) & mask; + // #else + #ifdef __amd64__ + // Compare the key to all 16 stored keys + __m128i cmp; + cmp = _mm_cmpeq_epi8(_mm_set1_epi8(c), + _mm_loadu_si128((__m128i*)p.p2->keys)); + + // Use a mask to ignore children that don't exist + mask = (1 << n->num_children) - 1; + bitfield = _mm_movemask_epi8(cmp) & mask; + #else + // Compare the key to all 16 stored keys + bitfield = 0; + for (i = 0; i < 16; ++i) { + if (p.p2->keys[i] == c) + bitfield |= (1 << i); + } + + // Use a mask to ignore children that don't exist + mask = (1 << n->num_children) - 1; + bitfield &= mask; + #endif + // #endif + + /* + * If we have a match (any bit set) then we can + * return the pointer match using ctz to get + * the index. + */ + if (bitfield) + return &p.p2->children[__builtin_ctz(bitfield)]; + break; + } + + case NODE48: + p.p3 = (art_node48*)n; + i = p.p3->keys[c]; + if (i) + return &p.p3->children[i-1]; + break; + + case NODE256: + p.p4 = (art_node256*)n; + if (p.p4->children[c]) + return &p.p4->children[c]; + break; + + default: + abort(); + } + return NULL; +} + +// Simple inlined if +static inline int min(int a, int b) { + return (a < b) ? a : b; +} + +/** + * Returns the number of prefix characters shared between + * the key and node. + */ +static int check_prefix(const art_node *n, const unsigned char *key, int key_len, int depth) { + int max_cmp = min(min(n->partial_len, MAX_PREFIX_LEN), key_len - depth); + int idx; + for (idx=0; idx < max_cmp; idx++) { + if (n->partial[idx] != key[depth+idx]) + return idx; + } + return idx; +} + +/** + * Checks if a leaf matches + * @return 0 on success. + */ +static int leaf_matches(const art_leaf *n, const unsigned char *key, int key_len, int depth) { + (void)depth; + // Fail if the key lengths are different + if (n->key_len != (uint32_t)key_len) return 1; + + // Compare the keys starting at the depth + return memcmp(n->key, key, key_len); +} + +/** + * Searches for a value in the ART tree + * @arg t The tree + * @arg key The key + * @arg key_len The length of the key + * @return NULL if the item was not found, otherwise + * the value pointer is returned. + */ +void* art_search(const art_tree *t, const unsigned char *key, int key_len) { + art_node **child; + art_node *n = t->root; + int prefix_len, depth = 0; + while (n) { + // Might be a leaf + if (IS_LEAF(n)) { + n = (art_node*)LEAF_RAW(n); + // Check if the expanded path matches + if (!leaf_matches((art_leaf*)n, key, key_len, depth)) { + return ((art_leaf*)n)->value; + } + return NULL; + } + + // Bail if the prefix does not match + if (n->partial_len) { + prefix_len = check_prefix(n, key, key_len, depth); + if (prefix_len != min(MAX_PREFIX_LEN, n->partial_len)) + return NULL; + depth = depth + n->partial_len; + } + + // Recursively search + child = find_child(n, key[depth]); + n = (child) ? *child : NULL; + depth++; + } + return NULL; +} + +// Find the minimum leaf under a node +static art_leaf* minimum(const art_node *n) { + // Handle base cases + if (!n) return NULL; + if (IS_LEAF(n)) return LEAF_RAW(n); + + int idx; + switch (n->type) { + case NODE4: + return minimum(((const art_node4*)n)->children[0]); + case NODE16: + return minimum(((const art_node16*)n)->children[0]); + case NODE48: + idx=0; + while (!((const art_node48*)n)->keys[idx]) idx++; + idx = ((const art_node48*)n)->keys[idx] - 1; + return minimum(((const art_node48*)n)->children[idx]); + case NODE256: + idx=0; + while (!((const art_node256*)n)->children[idx]) idx++; + return minimum(((const art_node256*)n)->children[idx]); + default: + abort(); + } +} + +// Find the maximum leaf under a node +static art_leaf* maximum(const art_node *n) { + // Handle base cases + if (!n) return NULL; + if (IS_LEAF(n)) return LEAF_RAW(n); + + int idx; + switch (n->type) { + case NODE4: + return maximum(((const art_node4*)n)->children[n->num_children-1]); + case NODE16: + return maximum(((const art_node16*)n)->children[n->num_children-1]); + case NODE48: + idx=255; + while (!((const art_node48*)n)->keys[idx]) idx--; + idx = ((const art_node48*)n)->keys[idx] - 1; + return maximum(((const art_node48*)n)->children[idx]); + case NODE256: + idx=255; + while (!((const art_node256*)n)->children[idx]) idx--; + return maximum(((const art_node256*)n)->children[idx]); + default: + abort(); + } +} + +/** + * Returns the minimum valued leaf + */ +art_leaf* art_minimum(art_tree *t) { + return minimum((art_node*)t->root); +} + +/** + * Returns the maximum valued leaf + */ +art_leaf* art_maximum(art_tree *t) { + return maximum((art_node*)t->root); +} + +static art_leaf* make_leaf(const unsigned char *key, int key_len, void *value) { + art_leaf *l = (art_leaf*)calloc(1, sizeof(art_leaf)+key_len+1); + if (l == NULL) { + return NULL; + } + + l->value = value; + l->key_len = key_len; + memcpy(l->key, key, key_len); + return l; +} + +static int longest_common_prefix(art_leaf *l1, art_leaf *l2, int depth) { + int max_cmp = min(l1->key_len, l2->key_len) - depth; + int idx; + for (idx=0; idx < max_cmp; idx++) { + if (l1->key[depth+idx] != l2->key[depth+idx]) + return idx; + } + return idx; +} + +static void copy_header(art_node *dest, art_node *src) { + dest->num_children = src->num_children; + dest->partial_len = src->partial_len; + memcpy(dest->partial, src->partial, min(MAX_PREFIX_LEN, src->partial_len)); +} + +static void add_child256(art_node256 *n, art_node **ref, unsigned char c, void *child) { + (void)ref; + n->n.num_children++; + n->children[c] = (art_node*)child; +} + +static void add_child48(art_node48 *n, art_node **ref, unsigned char c, void *child) { + if (n->n.num_children < 48) { + int pos = 0; + while (n->children[pos]) pos++; + n->children[pos] = (art_node*)child; + n->keys[c] = pos + 1; + n->n.num_children++; + } else { + art_node256 *new_node = (art_node256*)alloc_node(NODE256); + int i; + for (i=0;i<256;i++) { + if (n->keys[i]) { + new_node->children[i] = n->children[n->keys[i] - 1]; + } + } + copy_header((art_node*)new_node, (art_node*)n); + *ref = (art_node*)new_node; + free(n); + add_child256(new_node, ref, c, child); + } +} + +static void add_child16(art_node16 *n, art_node **ref, unsigned char c, void *child) { + if (n->n.num_children < 16) { + unsigned mask = (1 << n->n.num_children) - 1; + + // support non-x86 architectures + // #ifdef __i386__ + // __m128i cmp; + + // // Compare the key to all 16 stored keys + // cmp = _mm_cmplt_epi8(_mm_set1_epi8(c), + // _mm_loadu_si128((__m128i*)n->keys)); + + // // Use a mask to ignore children that don't exist + // unsigned bitfield = _mm_movemask_epi8(cmp) & mask; + // #else + #ifdef __amd64__ + __m128i cmp; + + // Compare the key to all 16 stored keys + cmp = _mm_cmplt_epi8(_mm_set1_epi8(c), + _mm_loadu_si128((__m128i*)n->keys)); + + // Use a mask to ignore children that don't exist + unsigned bitfield = _mm_movemask_epi8(cmp) & mask; + #else + // Compare the key to all 16 stored keys + unsigned bitfield = 0; + int i; + for (i = 0; i < 16; ++i) { + if (c < n->keys[i]) + bitfield |= (1 << i); + } + + // Use a mask to ignore children that don't exist + bitfield &= mask; + #endif + // #endif + + // Check if less than any + unsigned idx; + if (bitfield) { + idx = __builtin_ctz(bitfield); + memmove(n->keys+idx+1,n->keys+idx,n->n.num_children-idx); + memmove(n->children+idx+1,n->children+idx, + (n->n.num_children-idx)*sizeof(void*)); + } else + idx = n->n.num_children; + + // Set the child + n->keys[idx] = c; + n->children[idx] = (art_node*)child; + n->n.num_children++; + + } else { + art_node48 *new_node = (art_node48*)alloc_node(NODE48); + int i; + + // Copy the child pointers and populate the key map + memcpy(new_node->children, n->children, + sizeof(void*)*n->n.num_children); + for (i=0;in.num_children;i++) { + new_node->keys[n->keys[i]] = i + 1; + } + copy_header((art_node*)new_node, (art_node*)n); + *ref = (art_node*)new_node; + free(n); + add_child48(new_node, ref, c, child); + } +} + +static void add_child4(art_node4 *n, art_node **ref, unsigned char c, void *child) { + if (n->n.num_children < 4) { + int idx; + for (idx=0; idx < n->n.num_children; idx++) { + if (c < n->keys[idx]) break; + } + + // Shift to make room + memmove(n->keys+idx+1, n->keys+idx, n->n.num_children - idx); + memmove(n->children+idx+1, n->children+idx, + (n->n.num_children - idx)*sizeof(void*)); + + // Insert element + n->keys[idx] = c; + n->children[idx] = (art_node*)child; + n->n.num_children++; + + } else { + art_node16 *new_node = (art_node16*)alloc_node(NODE16); + + // Copy the child pointers and the key map + memcpy(new_node->children, n->children, + sizeof(void*)*n->n.num_children); + memcpy(new_node->keys, n->keys, + sizeof(unsigned char)*n->n.num_children); + copy_header((art_node*)new_node, (art_node*)n); + *ref = (art_node*)new_node; + free(n); + add_child16(new_node, ref, c, child); + } +} + +static void add_child(art_node *n, art_node **ref, unsigned char c, void *child) { + switch (n->type) { + case NODE4: + return add_child4((art_node4*)n, ref, c, child); + case NODE16: + return add_child16((art_node16*)n, ref, c, child); + case NODE48: + return add_child48((art_node48*)n, ref, c, child); + case NODE256: + return add_child256((art_node256*)n, ref, c, child); + default: + abort(); + } +} + +/** + * Calculates the index at which the prefixes mismatch + */ +static int prefix_mismatch(const art_node *n, const unsigned char *key, int key_len, int depth) { + int max_cmp = min(min(MAX_PREFIX_LEN, n->partial_len), key_len - depth); + int idx; + for (idx=0; idx < max_cmp; idx++) { + if (n->partial[idx] != key[depth+idx]) + return idx; + } + + // If the prefix is short we can avoid finding a leaf + if (n->partial_len > MAX_PREFIX_LEN) { + // Prefix is longer than what we've checked, find a leaf + art_leaf *l = minimum(n); + max_cmp = min(l->key_len, key_len)- depth; + for (; idx < max_cmp; idx++) { + if (l->key[idx+depth] != key[depth+idx]) + return idx; + } + } + return idx; +} + +static void* recursive_insert(art_node *n, art_node **ref, const unsigned char *key, int key_len, void *value, int depth, int *old) { + // If we are at a NULL node, inject a leaf + if (!n) { + *ref = (art_node*)SET_LEAF(make_leaf(key, key_len, value)); + return NULL; + } + + // If we are at a leaf, we need to replace it with a node + if (IS_LEAF(n)) { + art_leaf *l = LEAF_RAW(n); + + // Check if we are updating an existing value + if (!leaf_matches(l, key, key_len, depth)) { + *old = 1; + void *old_val = l->value; + l->value = value; + return old_val; + } + + // New value, we must split the leaf into a node4 + art_node4 *new_node = (art_node4*)alloc_node(NODE4); + + // Create a new leaf + art_leaf *l2 = make_leaf(key, key_len, value); + + // Determine longest prefix + int longest_prefix = longest_common_prefix(l, l2, depth); + new_node->n.partial_len = longest_prefix; + memcpy(new_node->n.partial, key+depth, min(MAX_PREFIX_LEN, longest_prefix)); + // Add the leafs to the new node4 + *ref = (art_node*)new_node; + add_child4(new_node, ref, l->key[depth+longest_prefix], SET_LEAF(l)); + add_child4(new_node, ref, l2->key[depth+longest_prefix], SET_LEAF(l2)); + return NULL; + } + + // Check if given node has a prefix + if (n->partial_len) { + // Determine if the prefixes differ, since we need to split + int prefix_diff = prefix_mismatch(n, key, key_len, depth); + if ((uint32_t)prefix_diff >= n->partial_len) { + depth += n->partial_len; + goto RECURSE_SEARCH; + } + + // Create a new node + art_node4 *new_node = (art_node4*)alloc_node(NODE4); + *ref = (art_node*)new_node; + new_node->n.partial_len = prefix_diff; + memcpy(new_node->n.partial, n->partial, min(MAX_PREFIX_LEN, prefix_diff)); + + // Adjust the prefix of the old node + if (n->partial_len <= MAX_PREFIX_LEN) { + add_child4(new_node, ref, n->partial[prefix_diff], n); + n->partial_len -= (prefix_diff+1); + memmove(n->partial, n->partial+prefix_diff+1, + min(MAX_PREFIX_LEN, n->partial_len)); + } else { + n->partial_len -= (prefix_diff+1); + art_leaf *l = minimum(n); + add_child4(new_node, ref, l->key[depth+prefix_diff], n); + memcpy(n->partial, l->key+depth+prefix_diff+1, + min(MAX_PREFIX_LEN, n->partial_len)); + } + + // Insert the new leaf + art_leaf *l = make_leaf(key, key_len, value); + add_child4(new_node, ref, key[depth+prefix_diff], SET_LEAF(l)); + return NULL; + } + +RECURSE_SEARCH:; + + // Find a child to recurse to + art_node **child = find_child(n, key[depth]); + if (child) { + return recursive_insert(*child, child, key, key_len, value, depth+1, old); + } + + // No child, node goes within us + art_leaf *l = make_leaf(key, key_len, value); + add_child(n, ref, key[depth], SET_LEAF(l)); + return NULL; +} + +/** + * Inserts a new value into the ART tree + * @arg t The tree + * @arg key The key + * @arg key_len The length of the key + * @arg value Opaque value. + * @return NULL if the item was newly inserted, otherwise + * the old value pointer is returned. + */ +void* art_insert(art_tree *t, const unsigned char *key, int key_len, void *value) { + int old_val = 0; + void *old = recursive_insert(t->root, &t->root, key, key_len, value, 0, &old_val); + if (!old_val) t->size++; + return old; +} + +static void remove_child256(art_node256 *n, art_node **ref, unsigned char c) { + n->children[c] = NULL; + n->n.num_children--; + + // Resize to a node48 on underflow, not immediately to prevent + // trashing if we sit on the 48/49 boundary + if (n->n.num_children == 37) { + art_node48 *new_node = (art_node48*)alloc_node(NODE48); + *ref = (art_node*)new_node; + copy_header((art_node*)new_node, (art_node*)n); + + int pos = 0; + int i; + for (i=0;i<256;i++) { + if (n->children[i]) { + new_node->children[pos] = n->children[i]; + new_node->keys[i] = pos + 1; + pos++; + } + } + free(n); + } +} + +static void remove_child48(art_node48 *n, art_node **ref, unsigned char c) { + int pos = n->keys[c]; + n->keys[c] = 0; + n->children[pos-1] = NULL; + n->n.num_children--; + + if (n->n.num_children == 12) { + art_node16 *new_node = (art_node16*)alloc_node(NODE16); + *ref = (art_node*)new_node; + copy_header((art_node*)new_node, (art_node*)n); + + int child = 0; + int i; + for (i=0;i<256;i++) { + pos = n->keys[i]; + if (pos) { + new_node->keys[child] = i; + new_node->children[child] = n->children[pos - 1]; + child++; + } + } + free(n); + } +} + +static void remove_child16(art_node16 *n, art_node **ref, art_node **l) { + int pos = l - n->children; + memmove(n->keys+pos, n->keys+pos+1, n->n.num_children - 1 - pos); + memmove(n->children+pos, n->children+pos+1, (n->n.num_children - 1 - pos)*sizeof(void*)); + n->n.num_children--; + + if (n->n.num_children == 3) { + art_node4 *new_node = (art_node4*)alloc_node(NODE4); + *ref = (art_node*)new_node; + copy_header((art_node*)new_node, (art_node*)n); + memcpy(new_node->keys, n->keys, 4); + memcpy(new_node->children, n->children, 4*sizeof(void*)); + free(n); + } +} + +static void remove_child4(art_node4 *n, art_node **ref, art_node **l) { + int pos = l - n->children; + memmove(n->keys+pos, n->keys+pos+1, n->n.num_children - 1 - pos); + memmove(n->children+pos, n->children+pos+1, (n->n.num_children - 1 - pos)*sizeof(void*)); + n->n.num_children--; + + // Remove nodes with only a single child + if (n->n.num_children == 1) { + art_node *child = n->children[0]; + if (!IS_LEAF(child)) { + // Concatenate the prefixes + int prefix = n->n.partial_len; + if (prefix < MAX_PREFIX_LEN) { + n->n.partial[prefix] = n->keys[0]; + prefix++; + } + if (prefix < MAX_PREFIX_LEN) { + int sub_prefix = min(child->partial_len, MAX_PREFIX_LEN - prefix); + memcpy(n->n.partial+prefix, child->partial, sub_prefix); + prefix += sub_prefix; + } + + // Store the prefix in the child + memcpy(child->partial, n->n.partial, min(prefix, MAX_PREFIX_LEN)); + child->partial_len += n->n.partial_len + 1; + } + *ref = child; + free(n); + } +} + +static void remove_child(art_node *n, art_node **ref, unsigned char c, art_node **l) { + switch (n->type) { + case NODE4: + return remove_child4((art_node4*)n, ref, l); + case NODE16: + return remove_child16((art_node16*)n, ref, l); + case NODE48: + return remove_child48((art_node48*)n, ref, c); + case NODE256: + return remove_child256((art_node256*)n, ref, c); + default: + abort(); + } +} + +static art_leaf* recursive_delete(art_node *n, art_node **ref, const unsigned char *key, int key_len, int depth) { + // Search terminated + if (!n) return NULL; + + // Handle hitting a leaf node + if (IS_LEAF(n)) { + art_leaf *l = LEAF_RAW(n); + if (!leaf_matches(l, key, key_len, depth)) { + *ref = NULL; + return l; + } + return NULL; + } + + // Bail if the prefix does not match + if (n->partial_len) { + int prefix_len = check_prefix(n, key, key_len, depth); + if (prefix_len != min(MAX_PREFIX_LEN, n->partial_len)) { + return NULL; + } + depth = depth + n->partial_len; + } + + // Find child node + art_node **child = find_child(n, key[depth]); + if (!child) return NULL; + + // If the child is leaf, delete from this node + if (IS_LEAF(*child)) { + art_leaf *l = LEAF_RAW(*child); + if (!leaf_matches(l, key, key_len, depth)) { + remove_child(n, ref, key[depth], child); + return l; + } + return NULL; + + // Recurse + } else { + return recursive_delete(*child, child, key, key_len, depth+1); + } +} + +/** + * Deletes a value from the ART tree + * @arg t The tree + * @arg key The key + * @arg key_len The length of the key + * @return NULL if the item was not found, otherwise + * the value pointer is returned. + */ +void* art_delete(art_tree *t, const unsigned char *key, int key_len) { + art_leaf *l = recursive_delete(t->root, &t->root, key, key_len, 0); + if (l) { + t->size--; + void *old = l->value; + free(l); + return old; + } + return NULL; +} + +// Recursively iterates over the tree +static int recursive_iter(art_node *n, art_callback cb, void *data) { + // Handle base cases + if (!n) return 0; + if (IS_LEAF(n)) { + art_leaf *l = LEAF_RAW(n); + return cb(data, (const unsigned char*)l->key, l->key_len, l->value); + } + + int idx, res; + int i; + switch (n->type) { + case NODE4: + for (i=0; i < n->num_children; i++) { + res = recursive_iter(((art_node4*)n)->children[i], cb, data); + if (res) return res; + } + break; + + case NODE16: + for (i=0; i < n->num_children; i++) { + res = recursive_iter(((art_node16*)n)->children[i], cb, data); + if (res) return res; + } + break; + + case NODE48: + for (i=0; i < 256; i++) { + idx = ((art_node48*)n)->keys[i]; + if (!idx) continue; + + res = recursive_iter(((art_node48*)n)->children[idx-1], cb, data); + if (res) return res; + } + break; + + case NODE256: + for (i=0; i < 256; i++) { + if (!((art_node256*)n)->children[i]) continue; + res = recursive_iter(((art_node256*)n)->children[i], cb, data); + if (res) return res; + } + break; + + default: + abort(); + } + return 0; +} + +/** + * Iterates through the entries pairs in the map, + * invoking a callback for each. The call back gets a + * key, value for each and returns an integer stop value. + * If the callback returns non-zero, then the iteration stops. + * @arg t The tree to iterate over + * @arg cb The callback function to invoke + * @arg data Opaque handle passed to the callback + * @return 0 on success, or the return of the callback. + */ +int art_iter(art_tree *t, art_callback cb, void *data) { + return recursive_iter(t->root, cb, data); +} + +/** + * Checks if a leaf prefix matches + * @return 0 on success. + */ +static int leaf_prefix_matches(const art_leaf *n, const unsigned char *prefix, int prefix_len) { + // Fail if the key length is too short + if (n->key_len < (uint32_t)prefix_len) return 1; + + // Compare the keys + return memcmp(n->key, prefix, prefix_len); +} + +/** + * Iterates through the entries pairs in the map, + * invoking a callback for each that matches a given prefix. + * The call back gets a key, value for each and returns an integer stop value. + * If the callback returns non-zero, then the iteration stops. + * @arg t The tree to iterate over + * @arg prefix The prefix of keys to read + * @arg prefix_len The length of the prefix + * @arg cb The callback function to invoke + * @arg data Opaque handle passed to the callback + * @return 0 on success, or the return of the callback. + */ +int art_iter_prefix(art_tree *t, const unsigned char *key, int key_len, art_callback cb, void *data) { + art_node **child; + art_node *n = t->root; + int prefix_len, depth = 0; + while (n) { + // Might be a leaf + if (IS_LEAF(n)) { + n = (art_node*)LEAF_RAW(n); + // Check if the expanded path matches + if (!leaf_prefix_matches((art_leaf*)n, key, key_len)) { + art_leaf *l = (art_leaf*)n; + return cb(data, (const unsigned char*)l->key, l->key_len, l->value); + } + return 0; + } + + // If the depth matches the prefix, we need to handle this node + if (depth == key_len) { + art_leaf *l = minimum(n); + if (!leaf_prefix_matches(l, key, key_len)) + return recursive_iter(n, cb, data); + return 0; + } + + // Bail if the prefix does not match + if (n->partial_len) { + prefix_len = prefix_mismatch(n, key, key_len, depth); + + // Guard if the mis-match is longer than the MAX_PREFIX_LEN + if ((uint32_t)prefix_len > n->partial_len) { + prefix_len = n->partial_len; + } + + // If there is no match, search is terminated + if (!prefix_len) { + return 0; + + // If we've matched the prefix, iterate on this node + } else if (depth + prefix_len == key_len) { + return recursive_iter(n, cb, data); + } + + // if there is a full match, go deeper + depth = depth + n->partial_len; + } + + // Recursively search + child = find_child(n, key[depth]); + n = (child) ? *child : NULL; + depth++; + } + return 0; +} + +static int str_prefix_matches(const art_leaf *n, const unsigned char *str, int str_len) { + // Fail if the key length is too short + if (n->key_len > (uint32_t)str_len) return 1; + + // Compare the keys + return memcmp(str, n->key, n->key_len); +} + +static void art_copy_key(art_leaf *leaf, unsigned char *key, int *key_len) +{ + int len; + + if (key == NULL || key_len == NULL) { + return; + } + + len = leaf->key_len > *key_len ? *key_len : leaf->key_len; + memcpy(key, leaf->key, len); + *key_len = len; +} + +void *art_substring(const art_tree *t, const unsigned char *str, int str_len, unsigned char *key, int *key_len) +{ + art_node **child; + art_node *n = t->root; + art_node *m; + art_leaf *found = NULL; + int prefix_len, depth = 0; + + while (n) { + // Might be a leaf + if (IS_LEAF(n)) { + n = (art_node*)LEAF_RAW(n); + // Check if the expanded path matches + if (!str_prefix_matches((art_leaf*)n, str, str_len)) { + found = (art_leaf*)n; + } + break; + } + + // Check if current is leaf + child = find_child(n, 0); + m = (child) ? *child : NULL; + if (m && IS_LEAF(m)) { + m = (art_node*)LEAF_RAW(m); + // Check if the expanded path matches + if (!str_prefix_matches((art_leaf*)m, str, str_len)) { + found = (art_leaf*)m; + } + } + + // Bail if the prefix does not match + if (n->partial_len) { + prefix_len = check_prefix(n, str, str_len, depth); + if (prefix_len != min(MAX_PREFIX_LEN, n->partial_len)) + break; + depth = depth + n->partial_len; + } + + // Recursively search + child = find_child(n, str[depth]); + n = (child) ? *child : NULL; + depth++; + } + + if (found == NULL) { + return NULL; + } + + art_copy_key(found, key, key_len); + + return found->value; +} + +void art_substring_walk(const art_tree *t, const unsigned char *str, int str_len, walk_func func, void *arg) +{ + art_node **child; + art_node *n = t->root; + art_node *m; + art_leaf *found = NULL; + int prefix_len, depth = 0; + int stop_search = 0; + + while (n && stop_search == 0) { + // Might be a leaf + if (IS_LEAF(n)) { + n = (art_node*)LEAF_RAW(n); + // Check if the expanded path matches + if (!str_prefix_matches((art_leaf*)n, str, str_len)) { + found = (art_leaf*)n; + stop_search = func(found->key, found->key_len, found->value, arg); + } + break; + } + + // Check if current is leaf + child = find_child(n, 0); + m = (child) ? *child : NULL; + if (m && IS_LEAF(m)) { + m = (art_node*)LEAF_RAW(m); + // Check if the expanded path matches + if (!str_prefix_matches((art_leaf*)m, str, str_len)) { + found = (art_leaf*)m; + stop_search = func(found->key, found->key_len, found->value, arg); + } + } + + // Bail if the prefix does not match + if (n->partial_len) { + prefix_len = check_prefix(n, str, str_len, depth); + if (prefix_len != min(MAX_PREFIX_LEN, n->partial_len)) + break; + depth = depth + n->partial_len; + } + + // Recursively search + child = find_child(n, str[depth]); + n = (child) ? *child : NULL; + depth++; + } + + if (found == NULL) { + return ; + } + + return ; +} diff --git a/release/src/router/smartdns/src/lib/conf.c b/release/src/router/smartdns/src/lib/conf.c index 23f244079b..88a89034b0 100644 --- a/release/src/router/smartdns/src/lib/conf.c +++ b/release/src/router/smartdns/src/lib/conf.c @@ -1,311 +1,311 @@ -/************************************************************************* - * - * Copyright (C) 2018-2020 Ruilin Peng (Nick) . - * - * smartdns is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * smartdns is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#include "conf.h" -#include -#include -#include -#include -#include - -static const char *currrent_conf_file = NULL; - -const char *conf_get_conf_file(void) -{ - return currrent_conf_file; -} - -int conf_custom(const char *item, void *data, int argc, char *argv[]) -{ - struct config_item_custom *item_custom = data; - return item_custom->custom_func(item_custom->custom_data, argc, argv); -} - -int conf_int(const char *item, void *data, int argc, char *argv[]) -{ - struct config_item_int *item_int = data; - int value = 0; - if (argc < 2) { - return -1; - } - - value = atoi(argv[1]); - - if (value < item_int->min) { - value = item_int->min; - } else if (value > item_int->max) { - value = item_int->max; - } - - *(item_int->data) = value; - - return 0; -} - -int conf_string(const char *item, void *data, int argc, char *argv[]) -{ - struct config_item_string *item_string = data; - - if (argc < 2) { - return -1; - } - - strncpy(item_string->data, argv[1], item_string->size); - - return 0; -} - -int conf_yesno(const char *item, void *data, int argc, char *argv[]) -{ - struct config_item_yesno *item_yesno = data; - int yes = 0; - - if (argc < 2) { - return -1; - } - - char *value = argv[1]; - if (strncmp("auto", value, sizeof("auto")) == 0 || strncmp("AUTO", value, sizeof("AUTO")) == 0) { - return 0; - } - - if (strncmp("yes", value, sizeof("yes")) == 0 || strncmp("YES", value, sizeof("YES")) == 0) { - yes = 1; - } else if (strncmp("no", value, sizeof("no")) == 0 || strncmp("NO", value, sizeof("NO")) == 0) { - yes = 0; - } - - *(item_yesno->data) = yes; - - return 0; -} - -int conf_size(const char *item, void *data, int argc, char *argv[]) -{ - /* read dns cache size */ - int base = 1; - size_t size = 0; - int num = 0; - struct config_item_size *item_size = data; - char *value = argv[1]; - - if (strstr(value, "k") || strstr(value, "K")) { - base = 1024; - } else if (strstr(value, "m") || strstr(value, "M")) { - base = 1024 * 1024; - } else if (strstr(value, "g") || strstr(value, "G")) { - base = 1024 * 1024 * 1024; - } - - num = atoi(value); - if (num < 0) { - return -1; - } - - size = num * base; - if (size > item_size->max) { - size = item_size->max; - } else if (size < item_size->min) { - size = item_size->min; - } - - *(item_size->data) = size; - - return 0; -} - -void conf_getopt_reset(void) -{ - static struct option long_options[] = {{"-", 0, 0, 0}, {0, 0, 0, 0}}; - int argc = 2; - char *argv[3] = {"reset", "", 0}; - - optind = 0; - opterr = 0; - optopt = 0; - getopt_long(argc, argv, "", long_options, NULL); - optind = 0; - opterr = 0; - optopt = 0; -} - -int conf_parse_args(char *key, char *value, int *argc, char **argv) -{ - char *start = NULL; - char *ptr = value; - int count = 0; - int sep_flag = ' '; - - argv[0] = key; - count++; - - while (*ptr != '\0') { - if (*ptr == '\\') { - char *tmp = ptr + 1; - while (*tmp != '\0') { - *(tmp - 1) = *tmp; - tmp++; - } - ptr++; - continue; - } - - if (*ptr == '"' && start == NULL) { - sep_flag = '"'; - start = NULL; - } - - if (*ptr != sep_flag && start == NULL) { - start = ptr; - ptr++; - continue; - } - - if (*ptr == sep_flag && start == NULL) { - ptr++; - continue; - } - - if (*ptr == sep_flag && start) { - argv[count] = start; - *ptr = '\0'; - ptr++; - count++; - sep_flag = ' '; - start = NULL; - continue; - } - - ptr++; - } - - if (start != ptr && start) { - argv[count] = start; - count++; - } - - *argc = count; - argv[count] = 0; - - return 0; -} - -void load_exit(void) -{ - return; -} - -int load_conf_printf(const char *file, int lineno, int ret) -{ - if (ret != CONF_RET_OK) { - printf("process config file '%s' failed at line %d.", file, lineno); - if (ret == CONF_RET_ERR || ret == CONF_RET_NOENT) { - return -1; - } - - return 0; - } - - return 0; -} - -int load_conf_file(const char *file, struct config_item *items, conf_error_handler handler) -{ - FILE *fp = NULL; - char line[MAX_LINE_LEN]; - char key[MAX_KEY_LEN]; - char value[MAX_LINE_LEN]; - int filed_num = 0; - int i; - int argc; - char *argv[1024]; - int ret = 0; - int call_ret = 0; - int line_no = 0; - - if (handler == NULL) { - handler = load_conf_printf; - } - - fp = fopen(file, "r"); - if (fp == NULL) { - return -1; - } - - line_no = 0; - while (fgets(line, MAX_LINE_LEN, fp)) { - line_no++; - filed_num = sscanf(line, "%63s %1023[^\r\n]s", key, value); - if (filed_num <= 0) { - continue; - } - - /* comment, skip */ - if (key[0] == '#') { - continue; - } - - /* if field format is not key = value, error */ - if (filed_num != 2) { - goto errout; - } - - for (i = 0;; i++) { - if (items[i].item == NULL) { - handler(file, line_no, CONF_RET_NOENT); - break; - } - - if (strncmp(items[i].item, key, MAX_KEY_LEN) != 0) { - continue; - } - - if (conf_parse_args(key, value, &argc, argv) != 0) { - continue; - } - - conf_getopt_reset(); - /* call item function */ - currrent_conf_file = file; - call_ret = items[i].item_func(items[i].item, items[i].data, argc, argv); - ret = handler(file, line_no, call_ret); - if (ret != 0) { - conf_getopt_reset(); - goto errout; - } - - conf_getopt_reset(); - - break; - } - } - - fclose(fp); - - return 0; -errout: - if (fp) { - fclose(fp); - } - return -1; -} - -int load_conf(const char *file, struct config_item items[], conf_error_handler handler) -{ - return load_conf_file(file, items, handler); -} +/************************************************************************* + * + * Copyright (C) 2018-2020 Ruilin Peng (Nick) . + * + * smartdns is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * smartdns is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "conf.h" +#include +#include +#include +#include +#include + +static const char *currrent_conf_file = NULL; + +const char *conf_get_conf_file(void) +{ + return currrent_conf_file; +} + +int conf_custom(const char *item, void *data, int argc, char *argv[]) +{ + struct config_item_custom *item_custom = data; + return item_custom->custom_func(item_custom->custom_data, argc, argv); +} + +int conf_int(const char *item, void *data, int argc, char *argv[]) +{ + struct config_item_int *item_int = data; + int value = 0; + if (argc < 2) { + return -1; + } + + value = atoi(argv[1]); + + if (value < item_int->min) { + value = item_int->min; + } else if (value > item_int->max) { + value = item_int->max; + } + + *(item_int->data) = value; + + return 0; +} + +int conf_string(const char *item, void *data, int argc, char *argv[]) +{ + struct config_item_string *item_string = data; + + if (argc < 2) { + return -1; + } + + strncpy(item_string->data, argv[1], item_string->size); + + return 0; +} + +int conf_yesno(const char *item, void *data, int argc, char *argv[]) +{ + struct config_item_yesno *item_yesno = data; + int yes = 0; + + if (argc < 2) { + return -1; + } + + char *value = argv[1]; + if (strncmp("auto", value, sizeof("auto")) == 0 || strncmp("AUTO", value, sizeof("AUTO")) == 0) { + return 0; + } + + if (strncmp("yes", value, sizeof("yes")) == 0 || strncmp("YES", value, sizeof("YES")) == 0) { + yes = 1; + } else if (strncmp("no", value, sizeof("no")) == 0 || strncmp("NO", value, sizeof("NO")) == 0) { + yes = 0; + } + + *(item_yesno->data) = yes; + + return 0; +} + +int conf_size(const char *item, void *data, int argc, char *argv[]) +{ + /* read dns cache size */ + int base = 1; + size_t size = 0; + int num = 0; + struct config_item_size *item_size = data; + char *value = argv[1]; + + if (strstr(value, "k") || strstr(value, "K")) { + base = 1024; + } else if (strstr(value, "m") || strstr(value, "M")) { + base = 1024 * 1024; + } else if (strstr(value, "g") || strstr(value, "G")) { + base = 1024 * 1024 * 1024; + } + + num = atoi(value); + if (num < 0) { + return -1; + } + + size = num * base; + if (size > item_size->max) { + size = item_size->max; + } else if (size < item_size->min) { + size = item_size->min; + } + + *(item_size->data) = size; + + return 0; +} + +void conf_getopt_reset(void) +{ + static struct option long_options[] = {{"-", 0, 0, 0}, {0, 0, 0, 0}}; + int argc = 2; + char *argv[3] = {"reset", "", 0}; + + optind = 0; + opterr = 0; + optopt = 0; + getopt_long(argc, argv, "", long_options, NULL); + optind = 0; + opterr = 0; + optopt = 0; +} + +int conf_parse_args(char *key, char *value, int *argc, char **argv) +{ + char *start = NULL; + char *ptr = value; + int count = 0; + int sep_flag = ' '; + + argv[0] = key; + count++; + + while (*ptr != '\0') { + if (*ptr == '\\') { + char *tmp = ptr + 1; + while (*tmp != '\0') { + *(tmp - 1) = *tmp; + tmp++; + } + ptr++; + continue; + } + + if (*ptr == '"' && start == NULL) { + sep_flag = '"'; + start = NULL; + } + + if (*ptr != sep_flag && start == NULL) { + start = ptr; + ptr++; + continue; + } + + if (*ptr == sep_flag && start == NULL) { + ptr++; + continue; + } + + if (*ptr == sep_flag && start) { + argv[count] = start; + *ptr = '\0'; + ptr++; + count++; + sep_flag = ' '; + start = NULL; + continue; + } + + ptr++; + } + + if (start != ptr && start) { + argv[count] = start; + count++; + } + + *argc = count; + argv[count] = 0; + + return 0; +} + +void load_exit(void) +{ + return; +} + +int load_conf_printf(const char *file, int lineno, int ret) +{ + if (ret != CONF_RET_OK) { + printf("process config file '%s' failed at line %d.", file, lineno); + if (ret == CONF_RET_ERR || ret == CONF_RET_NOENT) { + return -1; + } + + return 0; + } + + return 0; +} + +int load_conf_file(const char *file, struct config_item *items, conf_error_handler handler) +{ + FILE *fp = NULL; + char line[MAX_LINE_LEN]; + char key[MAX_KEY_LEN]; + char value[MAX_LINE_LEN]; + int filed_num = 0; + int i; + int argc; + char *argv[1024]; + int ret = 0; + int call_ret = 0; + int line_no = 0; + + if (handler == NULL) { + handler = load_conf_printf; + } + + fp = fopen(file, "r"); + if (fp == NULL) { + return -1; + } + + line_no = 0; + while (fgets(line, MAX_LINE_LEN, fp)) { + line_no++; + filed_num = sscanf(line, "%63s %1023[^\r\n]s", key, value); + if (filed_num <= 0) { + continue; + } + + /* comment, skip */ + if (key[0] == '#') { + continue; + } + + /* if field format is not key = value, error */ + if (filed_num != 2) { + goto errout; + } + + for (i = 0;; i++) { + if (items[i].item == NULL) { + handler(file, line_no, CONF_RET_NOENT); + break; + } + + if (strncmp(items[i].item, key, MAX_KEY_LEN) != 0) { + continue; + } + + if (conf_parse_args(key, value, &argc, argv) != 0) { + continue; + } + + conf_getopt_reset(); + /* call item function */ + currrent_conf_file = file; + call_ret = items[i].item_func(items[i].item, items[i].data, argc, argv); + ret = handler(file, line_no, call_ret); + if (ret != 0) { + conf_getopt_reset(); + goto errout; + } + + conf_getopt_reset(); + + break; + } + } + + fclose(fp); + + return 0; +errout: + if (fp) { + fclose(fp); + } + return -1; +} + +int load_conf(const char *file, struct config_item items[], conf_error_handler handler) +{ + return load_conf_file(file, items, handler); +} diff --git a/release/src/router/smartdns/src/lib/radix.c b/release/src/router/smartdns/src/lib/radix.c index 20dcd1e23a..7ffbd042c9 100644 --- a/release/src/router/smartdns/src/lib/radix.c +++ b/release/src/router/smartdns/src/lib/radix.c @@ -1,676 +1,676 @@ -/* - * Copyright (c) 1999-2000 - * - * The Regents of the University of Michigan ("The Regents") and - * Merit Network, Inc. All rights reserved. Redistribution and use - * in source and binary forms, with or without modification, are - * permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above - * copyright notice, this list of conditions and the - * following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the - * following disclaimer in the documentation and/or other - * materials provided with the distribution. - * - * 3. All advertising materials mentioning features or use of - * this software must display the following acknowledgement: - * - * This product includes software developed by the University of - * Michigan, Merit Network, Inc., and their contributors. - * - * 4. Neither the name of the University, Merit Network, nor the - * names of their contributors may be used to endorse or - * promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A - * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL TH E REGENTS - * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF - * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HO WEVER CAUSED - * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN - * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -/* - * Portions Copyright (c) 2004,2005 Damien Miller - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#include -#include -#include -#include - -#include "radix.h" - -/* $Id: radix.c,v 1.17 2007/10/24 06:04:31 djm Exp $ */ - -/* - * Originally from MRT include/defs.h - * $MRTId: defs.h,v 1.1.1.1 2000/08/14 18:46:10 labovit Exp $ - */ -#define BIT_TEST(f, b) ((f) & (b)) - -/* - * Originally from MRT include/mrt.h - * $MRTId: mrt.h,v 1.1.1.1 2000/08/14 18:46:10 labovit Exp $ - */ -#define prefix_tochar(prefix) ((char *)&(prefix)->add) -#define prefix_touchar(prefix) ((unsigned char *)&(prefix)->add) - -/* - * Originally from MRT lib/mrt/prefix.c - * $MRTId: prefix.c,v 1.1.1.1 2000/08/14 18:46:11 labovit Exp $ - */ - -static int -comp_with_mask(unsigned char *addr, unsigned char *dest, unsigned int mask) -{ - if (memcmp(addr, dest, mask / 8) == 0) { - unsigned int n = mask / 8; - unsigned int m = ((~0) << (8 - (mask % 8))); - - if (mask % 8 == 0 || (addr[n] & m) == (dest[n] & m)) - return (1); - } - return (0); -} - -static prefix_t -*New_Prefix2(int family, void *dest, int bitlen, prefix_t *prefix) -{ - int dynamic_allocated = 0; - int default_bitlen = 32; - - if (family == AF_INET6) { - default_bitlen = 128; - if (prefix == NULL) { - if ((prefix = malloc(sizeof(*prefix))) == NULL) - return (NULL); - memset(prefix, '\0', sizeof(*prefix)); - dynamic_allocated++; - } - memcpy(&prefix->add.sin6, dest, 16); - } else if (family == AF_INET) { - if (prefix == NULL) { - if ((prefix = malloc(sizeof(*prefix))) == NULL) - return (NULL); - memset(prefix, '\0', sizeof(*prefix)); - dynamic_allocated++; - } - memcpy(&prefix->add.sin, dest, 4); - } else - return (NULL); - - prefix->bitlen = (bitlen >= 0) ? bitlen : default_bitlen; - prefix->family = family; - prefix->ref_count = 0; - if (dynamic_allocated) - prefix->ref_count++; - return (prefix); -} - - -static prefix_t -*Ref_Prefix(prefix_t *prefix) -{ - if (prefix == NULL) - return (NULL); - if (prefix->ref_count == 0) { - /* make a copy in case of a static prefix */ - return (New_Prefix2(prefix->family, &prefix->add, - prefix->bitlen, NULL)); - } - prefix->ref_count++; - return (prefix); -} - - -void -Deref_Prefix(prefix_t *prefix) -{ - if (prefix == NULL) - return; - prefix->ref_count--; - if (prefix->ref_count <= 0) { - free(prefix); - return; - } -} - -/* - * Originally from MRT lib/radix/radix.c - * $MRTId: radix.c,v 1.1.1.1 2000/08/14 18:46:13 labovit Exp $ - */ - -/* these routines support continuous mask only */ - -radix_tree_t -*New_Radix(void) -{ - radix_tree_t *radix; - - if ((radix = malloc(sizeof(*radix))) == NULL) - return (NULL); - memset(radix, '\0', sizeof(*radix)); - - radix->maxbits = 128; - radix->head = NULL; - radix->num_active_node = 0; - return (radix); -} - -/* - * if func is supplied, it will be called as func(node->data) - * before deleting the node - */ -static void -Clear_Radix(radix_tree_t *radix, rdx_cb_t func, void *cbctx) -{ - if (radix->head) { - radix_node_t *Xstack[RADIX_MAXBITS + 1]; - radix_node_t **Xsp = Xstack; - radix_node_t *Xrn = radix->head; - - while (Xrn) { - radix_node_t *l = Xrn->l; - radix_node_t *r = Xrn->r; - - if (Xrn->prefix) { - Deref_Prefix(Xrn->prefix); - if (Xrn->data && func) - func(Xrn, cbctx); - } - free(Xrn); - radix->num_active_node--; - - if (l) { - if (r) - *Xsp++ = r; - Xrn = l; - } else if (r) { - Xrn = r; - } else if (Xsp != Xstack) { - Xrn = *(--Xsp); - } else { - Xrn = (radix_node_t *) 0; - } - } - } -} - -void -Destroy_Radix(radix_tree_t *radix, rdx_cb_t func, void *cbctx) -{ - if (radix == NULL) { - return; - } - Clear_Radix(radix, func, cbctx); - free(radix); -} - -/* - * if func is supplied, it will be called as func(node->prefix, node->data) - */ -void -radix_process(radix_tree_t *radix, rdx_cb_t func, void *cbctx) -{ - radix_node_t *node; - - RADIX_WALK(radix->head, node) { - func(node, cbctx); - } RADIX_WALK_END; -} - -radix_node_t -*radix_search_exact(radix_tree_t *radix, prefix_t *prefix) -{ - radix_node_t *node; - unsigned char *addr; - unsigned int bitlen; - - if (radix->head == NULL) - return (NULL); - - node = radix->head; - addr = prefix_touchar(prefix); - bitlen = prefix->bitlen; - - while (node->bit < bitlen) { - if (BIT_TEST(addr[node->bit >> 3], 0x80 >> (node->bit & 0x07))) - node = node->r; - else - node = node->l; - - if (node == NULL) - return (NULL); - } - - if (node->bit > bitlen || node->prefix == NULL) - return (NULL); - - if (comp_with_mask(prefix_touchar(node->prefix), - prefix_touchar(prefix), bitlen)) - return (node); - - return (NULL); -} - - -/* if inclusive != 0, "best" may be the given prefix itself */ -static radix_node_t -*radix_search_best2(radix_tree_t *radix, prefix_t *prefix, int inclusive) -{ - radix_node_t *node; - radix_node_t *stack[RADIX_MAXBITS + 1] = {0}; - unsigned char *addr; - unsigned int bitlen; - int cnt = 0; - - if (radix->head == NULL) - return (NULL); - - node = radix->head; - addr = prefix_touchar(prefix); - bitlen = prefix->bitlen; - - while (node->bit < bitlen) { - if (node->prefix) - stack[cnt++] = node; - if (BIT_TEST(addr[node->bit >> 3], 0x80 >> (node->bit & 0x07))) - node = node->r; - else - node = node->l; - - if (node == NULL) - break; - } - - if (inclusive && node && node->prefix) - stack[cnt++] = node; - - - if (cnt <= 0) - return (NULL); - - while (--cnt >= 0) { - node = stack[cnt]; - if (comp_with_mask(prefix_touchar(node->prefix), - prefix_touchar(prefix), node->prefix->bitlen)) - return (node); - } - return (NULL); -} - - -radix_node_t -*radix_search_best(radix_tree_t *radix, prefix_t *prefix) -{ - return (radix_search_best2(radix, prefix, 1)); -} - - -radix_node_t -*radix_lookup(radix_tree_t *radix, prefix_t *prefix) -{ - radix_node_t *node, *new_node, *parent, *glue; - unsigned char *addr, *test_addr; - unsigned int bitlen, check_bit, differ_bit; - unsigned int i, j, r; - - if (radix->head == NULL) { - if ((node = malloc(sizeof(*node))) == NULL) - return (NULL); - memset(node, '\0', sizeof(*node)); - node->bit = prefix->bitlen; - node->prefix = Ref_Prefix(prefix); - node->parent = NULL; - node->l = node->r = NULL; - node->data = NULL; - radix->head = node; - radix->num_active_node++; - return (node); - } - addr = prefix_touchar(prefix); - bitlen = prefix->bitlen; - node = radix->head; - - while (node->bit < bitlen || node->prefix == NULL) { - if (node->bit < radix->maxbits && BIT_TEST(addr[node->bit >> 3], - 0x80 >> (node->bit & 0x07))) { - if (node->r == NULL) - break; - node = node->r; - } else { - if (node->l == NULL) - break; - node = node->l; - } - } - - test_addr = prefix_touchar(node->prefix); - /* find the first bit different */ - check_bit = (node->bit < bitlen) ? node->bit : bitlen; - differ_bit = 0; - for (i = 0; i * 8 < check_bit; i++) { - if ((r = (addr[i] ^ test_addr[i])) == 0) { - differ_bit = (i + 1) * 8; - continue; - } - /* I know the better way, but for now */ - for (j = 0; j < 8; j++) { - if (BIT_TEST(r, (0x80 >> j))) - break; - } - /* must be found */ - differ_bit = i * 8 + j; - break; - } - if (differ_bit > check_bit) - differ_bit = check_bit; - - parent = node->parent; - while (parent && parent->bit >= differ_bit) { - node = parent; - parent = node->parent; - } - - if (differ_bit == bitlen && node->bit == bitlen) { - if (node->prefix == NULL) - node->prefix = Ref_Prefix(prefix); - return (node); - } - if ((new_node = malloc(sizeof(*new_node))) == NULL) - return (NULL); - memset(new_node, '\0', sizeof(*new_node)); - new_node->bit = prefix->bitlen; - new_node->prefix = Ref_Prefix(prefix); - new_node->parent = NULL; - new_node->l = new_node->r = NULL; - new_node->data = NULL; - radix->num_active_node++; - - if (node->bit == differ_bit) { - new_node->parent = node; - if (node->bit < radix->maxbits && BIT_TEST(addr[node->bit >> 3], - 0x80 >> (node->bit & 0x07))) - node->r = new_node; - else - node->l = new_node; - - return (new_node); - } - if (bitlen == differ_bit) { - if (bitlen < radix->maxbits && BIT_TEST(test_addr[bitlen >> 3], - 0x80 >> (bitlen & 0x07))) - new_node->r = node; - else - new_node->l = node; - - new_node->parent = node->parent; - if (node->parent == NULL) - radix->head = new_node; - else if (node->parent->r == node) - node->parent->r = new_node; - else - node->parent->l = new_node; - - node->parent = new_node; - } else { - if ((glue = malloc(sizeof(*glue))) == NULL) - return (NULL); - memset(glue, '\0', sizeof(*glue)); - glue->bit = differ_bit; - glue->prefix = NULL; - glue->parent = node->parent; - glue->data = NULL; - radix->num_active_node++; - if (differ_bit < radix->maxbits && - BIT_TEST(addr[differ_bit >> 3], - 0x80 >> (differ_bit & 0x07))) { - glue->r = new_node; - glue->l = node; - } else { - glue->r = node; - glue->l = new_node; - } - new_node->parent = glue; - - if (node->parent == NULL) - radix->head = glue; - else if (node->parent->r == node) - node->parent->r = glue; - else - node->parent->l = glue; - - node->parent = glue; - } - return (new_node); -} - - -void -radix_remove(radix_tree_t *radix, radix_node_t *node) -{ - radix_node_t *parent, *child; - - if (node->r && node->l) { - /* - * this might be a placeholder node -- have to check and make - * sure there is a prefix aossciated with it ! - */ - if (node->prefix != NULL) - Deref_Prefix(node->prefix); - node->prefix = NULL; - /* Also I needed to clear data pointer -- masaki */ - node->data = NULL; - return; - } - if (node->r == NULL && node->l == NULL) { - parent = node->parent; - Deref_Prefix(node->prefix); - free(node); - radix->num_active_node--; - - if (parent == NULL) { - radix->head = NULL; - return; - } - if (parent->r == node) { - parent->r = NULL; - child = parent->l; - } else { - parent->l = NULL; - child = parent->r; - } - - if (parent->prefix) - return; - - /* we need to remove parent too */ - if (parent->parent == NULL) - radix->head = child; - else if (parent->parent->r == parent) - parent->parent->r = child; - else - parent->parent->l = child; - - child->parent = parent->parent; - free(parent); - radix->num_active_node--; - return; - } - if (node->r) - child = node->r; - else - child = node->l; - - parent = node->parent; - child->parent = parent; - - Deref_Prefix(node->prefix); - free(node); - radix->num_active_node--; - - if (parent == NULL) { - radix->head = child; - return; - } - if (parent->r == node) - parent->r = child; - else - parent->l = child; -} - -/* Local additions */ -static void -sanitise_mask(unsigned char *addr, unsigned int masklen, unsigned int maskbits) -{ - unsigned int i = masklen / 8; - unsigned int j = masklen % 8; - - if (j != 0) { - addr[i] &= (~0) << (8 - j); - i++; - } - for (; i < maskbits / 8; i++) - addr[i] = 0; -} - -prefix_t -*prefix_pton(const char *string, long len, prefix_t *prefix, const char **errmsg) -{ - char save[256], *cp, *ep; - struct addrinfo hints, *ai; - void *addr; - prefix_t *ret; - size_t slen; - int r; - - ret = NULL; - - /* Copy the string to parse, because we modify it */ - if ((slen = strlen(string) + 1) > sizeof(save)) { - *errmsg = "string too long"; - return (NULL); - } - memcpy(save, string, slen); - - if ((cp = strchr(save, '/')) != NULL) { - if (len != -1 ) { - *errmsg = "masklen specified twice"; - return (NULL); - } - *cp++ = '\0'; - len = strtol(cp, &ep, 10); - if (*cp == '\0' || *ep != '\0' || len < 0) { - *errmsg = "could not parse masklen"; - return (NULL); - } - /* More checks below */ - } - memset(&hints, '\0', sizeof(hints)); - hints.ai_flags = AI_NUMERICHOST; - - if ((r = getaddrinfo(save, NULL, &hints, &ai)) != 0) { - snprintf(save, sizeof(save), "getaddrinfo: %s:", - gai_strerror(r)); - *errmsg = save; - return NULL; - } - if (ai == NULL || ai->ai_addr == NULL) { - *errmsg = "getaddrinfo returned no result"; - goto out; - } - switch (ai->ai_addr->sa_family) { - case AF_INET: - if (len == -1) - len = 32; - else if (len < 0 || len > 32) - goto out; - addr = &((struct sockaddr_in *) ai->ai_addr)->sin_addr; - sanitise_mask(addr, len, 32); - break; - case AF_INET6: - if (len == -1) - len = 128; - else if (len < 0 || len > 128) - goto out; - addr = &((struct sockaddr_in6 *) ai->ai_addr)->sin6_addr; - sanitise_mask(addr, len, 128); - break; - default: - goto out; - } - - ret = New_Prefix2(ai->ai_addr->sa_family, addr, len, prefix); - if (ret == NULL) - *errmsg = "New_Prefix2 failed"; -out: - freeaddrinfo(ai); - return (ret); -} - -prefix_t -*prefix_from_blob(unsigned char *blob, int len, int prefixlen, prefix_t *prefix) -{ - int family, maxprefix; - - switch (len) { - case 4: - /* Assume AF_INET */ - family = AF_INET; - maxprefix = 32; - break; - case 16: - /* Assume AF_INET6 */ - family = AF_INET6; - maxprefix = 128; - break; - default: - /* Who knows? */ - return NULL; - } - if (prefixlen == -1) - prefixlen = maxprefix; - if (prefixlen < 0 || prefixlen > maxprefix) - return NULL; - return (New_Prefix2(family, blob, prefixlen, prefix)); -} - -const char * -prefix_addr_ntop(prefix_t *prefix, char *buf, size_t len) -{ - return (inet_ntop(prefix->family, &prefix->add, buf, len)); -} - -const char * -prefix_ntop(prefix_t *prefix, char *buf, size_t len) -{ - char addrbuf[128]; - - if (prefix_addr_ntop(prefix, addrbuf, sizeof(addrbuf)) == NULL) - return (NULL); - snprintf(buf, len, "%s/%d", addrbuf, prefix->bitlen); - - return (buf); -} +/* + * Copyright (c) 1999-2000 + * + * The Regents of the University of Michigan ("The Regents") and + * Merit Network, Inc. All rights reserved. Redistribution and use + * in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above + * copyright notice, this list of conditions and the + * following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other + * materials provided with the distribution. + * + * 3. All advertising materials mentioning features or use of + * this software must display the following acknowledgement: + * + * This product includes software developed by the University of + * Michigan, Merit Network, Inc., and their contributors. + * + * 4. Neither the name of the University, Merit Network, nor the + * names of their contributors may be used to endorse or + * promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL TH E REGENTS + * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HO WEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +/* + * Portions Copyright (c) 2004,2005 Damien Miller + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#include +#include +#include +#include + +#include "radix.h" + +/* $Id: radix.c,v 1.17 2007/10/24 06:04:31 djm Exp $ */ + +/* + * Originally from MRT include/defs.h + * $MRTId: defs.h,v 1.1.1.1 2000/08/14 18:46:10 labovit Exp $ + */ +#define BIT_TEST(f, b) ((f) & (b)) + +/* + * Originally from MRT include/mrt.h + * $MRTId: mrt.h,v 1.1.1.1 2000/08/14 18:46:10 labovit Exp $ + */ +#define prefix_tochar(prefix) ((char *)&(prefix)->add) +#define prefix_touchar(prefix) ((unsigned char *)&(prefix)->add) + +/* + * Originally from MRT lib/mrt/prefix.c + * $MRTId: prefix.c,v 1.1.1.1 2000/08/14 18:46:11 labovit Exp $ + */ + +static int +comp_with_mask(unsigned char *addr, unsigned char *dest, unsigned int mask) +{ + if (memcmp(addr, dest, mask / 8) == 0) { + unsigned int n = mask / 8; + unsigned int m = ((~0) << (8 - (mask % 8))); + + if (mask % 8 == 0 || (addr[n] & m) == (dest[n] & m)) + return (1); + } + return (0); +} + +static prefix_t +*New_Prefix2(int family, void *dest, int bitlen, prefix_t *prefix) +{ + int dynamic_allocated = 0; + int default_bitlen = 32; + + if (family == AF_INET6) { + default_bitlen = 128; + if (prefix == NULL) { + if ((prefix = malloc(sizeof(*prefix))) == NULL) + return (NULL); + memset(prefix, '\0', sizeof(*prefix)); + dynamic_allocated++; + } + memcpy(&prefix->add.sin6, dest, 16); + } else if (family == AF_INET) { + if (prefix == NULL) { + if ((prefix = malloc(sizeof(*prefix))) == NULL) + return (NULL); + memset(prefix, '\0', sizeof(*prefix)); + dynamic_allocated++; + } + memcpy(&prefix->add.sin, dest, 4); + } else + return (NULL); + + prefix->bitlen = (bitlen >= 0) ? bitlen : default_bitlen; + prefix->family = family; + prefix->ref_count = 0; + if (dynamic_allocated) + prefix->ref_count++; + return (prefix); +} + + +static prefix_t +*Ref_Prefix(prefix_t *prefix) +{ + if (prefix == NULL) + return (NULL); + if (prefix->ref_count == 0) { + /* make a copy in case of a static prefix */ + return (New_Prefix2(prefix->family, &prefix->add, + prefix->bitlen, NULL)); + } + prefix->ref_count++; + return (prefix); +} + + +void +Deref_Prefix(prefix_t *prefix) +{ + if (prefix == NULL) + return; + prefix->ref_count--; + if (prefix->ref_count <= 0) { + free(prefix); + return; + } +} + +/* + * Originally from MRT lib/radix/radix.c + * $MRTId: radix.c,v 1.1.1.1 2000/08/14 18:46:13 labovit Exp $ + */ + +/* these routines support continuous mask only */ + +radix_tree_t +*New_Radix(void) +{ + radix_tree_t *radix; + + if ((radix = malloc(sizeof(*radix))) == NULL) + return (NULL); + memset(radix, '\0', sizeof(*radix)); + + radix->maxbits = 128; + radix->head = NULL; + radix->num_active_node = 0; + return (radix); +} + +/* + * if func is supplied, it will be called as func(node->data) + * before deleting the node + */ +static void +Clear_Radix(radix_tree_t *radix, rdx_cb_t func, void *cbctx) +{ + if (radix->head) { + radix_node_t *Xstack[RADIX_MAXBITS + 1]; + radix_node_t **Xsp = Xstack; + radix_node_t *Xrn = radix->head; + + while (Xrn) { + radix_node_t *l = Xrn->l; + radix_node_t *r = Xrn->r; + + if (Xrn->prefix) { + Deref_Prefix(Xrn->prefix); + if (Xrn->data && func) + func(Xrn, cbctx); + } + free(Xrn); + radix->num_active_node--; + + if (l) { + if (r) + *Xsp++ = r; + Xrn = l; + } else if (r) { + Xrn = r; + } else if (Xsp != Xstack) { + Xrn = *(--Xsp); + } else { + Xrn = (radix_node_t *) 0; + } + } + } +} + +void +Destroy_Radix(radix_tree_t *radix, rdx_cb_t func, void *cbctx) +{ + if (radix == NULL) { + return; + } + Clear_Radix(radix, func, cbctx); + free(radix); +} + +/* + * if func is supplied, it will be called as func(node->prefix, node->data) + */ +void +radix_process(radix_tree_t *radix, rdx_cb_t func, void *cbctx) +{ + radix_node_t *node; + + RADIX_WALK(radix->head, node) { + func(node, cbctx); + } RADIX_WALK_END; +} + +radix_node_t +*radix_search_exact(radix_tree_t *radix, prefix_t *prefix) +{ + radix_node_t *node; + unsigned char *addr; + unsigned int bitlen; + + if (radix->head == NULL) + return (NULL); + + node = radix->head; + addr = prefix_touchar(prefix); + bitlen = prefix->bitlen; + + while (node->bit < bitlen) { + if (BIT_TEST(addr[node->bit >> 3], 0x80 >> (node->bit & 0x07))) + node = node->r; + else + node = node->l; + + if (node == NULL) + return (NULL); + } + + if (node->bit > bitlen || node->prefix == NULL) + return (NULL); + + if (comp_with_mask(prefix_touchar(node->prefix), + prefix_touchar(prefix), bitlen)) + return (node); + + return (NULL); +} + + +/* if inclusive != 0, "best" may be the given prefix itself */ +static radix_node_t +*radix_search_best2(radix_tree_t *radix, prefix_t *prefix, int inclusive) +{ + radix_node_t *node; + radix_node_t *stack[RADIX_MAXBITS + 1] = {0}; + unsigned char *addr; + unsigned int bitlen; + int cnt = 0; + + if (radix->head == NULL) + return (NULL); + + node = radix->head; + addr = prefix_touchar(prefix); + bitlen = prefix->bitlen; + + while (node->bit < bitlen) { + if (node->prefix) + stack[cnt++] = node; + if (BIT_TEST(addr[node->bit >> 3], 0x80 >> (node->bit & 0x07))) + node = node->r; + else + node = node->l; + + if (node == NULL) + break; + } + + if (inclusive && node && node->prefix) + stack[cnt++] = node; + + + if (cnt <= 0) + return (NULL); + + while (--cnt >= 0) { + node = stack[cnt]; + if (comp_with_mask(prefix_touchar(node->prefix), + prefix_touchar(prefix), node->prefix->bitlen)) + return (node); + } + return (NULL); +} + + +radix_node_t +*radix_search_best(radix_tree_t *radix, prefix_t *prefix) +{ + return (radix_search_best2(radix, prefix, 1)); +} + + +radix_node_t +*radix_lookup(radix_tree_t *radix, prefix_t *prefix) +{ + radix_node_t *node, *new_node, *parent, *glue; + unsigned char *addr, *test_addr; + unsigned int bitlen, check_bit, differ_bit; + unsigned int i, j, r; + + if (radix->head == NULL) { + if ((node = malloc(sizeof(*node))) == NULL) + return (NULL); + memset(node, '\0', sizeof(*node)); + node->bit = prefix->bitlen; + node->prefix = Ref_Prefix(prefix); + node->parent = NULL; + node->l = node->r = NULL; + node->data = NULL; + radix->head = node; + radix->num_active_node++; + return (node); + } + addr = prefix_touchar(prefix); + bitlen = prefix->bitlen; + node = radix->head; + + while (node->bit < bitlen || node->prefix == NULL) { + if (node->bit < radix->maxbits && BIT_TEST(addr[node->bit >> 3], + 0x80 >> (node->bit & 0x07))) { + if (node->r == NULL) + break; + node = node->r; + } else { + if (node->l == NULL) + break; + node = node->l; + } + } + + test_addr = prefix_touchar(node->prefix); + /* find the first bit different */ + check_bit = (node->bit < bitlen) ? node->bit : bitlen; + differ_bit = 0; + for (i = 0; i * 8 < check_bit; i++) { + if ((r = (addr[i] ^ test_addr[i])) == 0) { + differ_bit = (i + 1) * 8; + continue; + } + /* I know the better way, but for now */ + for (j = 0; j < 8; j++) { + if (BIT_TEST(r, (0x80 >> j))) + break; + } + /* must be found */ + differ_bit = i * 8 + j; + break; + } + if (differ_bit > check_bit) + differ_bit = check_bit; + + parent = node->parent; + while (parent && parent->bit >= differ_bit) { + node = parent; + parent = node->parent; + } + + if (differ_bit == bitlen && node->bit == bitlen) { + if (node->prefix == NULL) + node->prefix = Ref_Prefix(prefix); + return (node); + } + if ((new_node = malloc(sizeof(*new_node))) == NULL) + return (NULL); + memset(new_node, '\0', sizeof(*new_node)); + new_node->bit = prefix->bitlen; + new_node->prefix = Ref_Prefix(prefix); + new_node->parent = NULL; + new_node->l = new_node->r = NULL; + new_node->data = NULL; + radix->num_active_node++; + + if (node->bit == differ_bit) { + new_node->parent = node; + if (node->bit < radix->maxbits && BIT_TEST(addr[node->bit >> 3], + 0x80 >> (node->bit & 0x07))) + node->r = new_node; + else + node->l = new_node; + + return (new_node); + } + if (bitlen == differ_bit) { + if (bitlen < radix->maxbits && BIT_TEST(test_addr[bitlen >> 3], + 0x80 >> (bitlen & 0x07))) + new_node->r = node; + else + new_node->l = node; + + new_node->parent = node->parent; + if (node->parent == NULL) + radix->head = new_node; + else if (node->parent->r == node) + node->parent->r = new_node; + else + node->parent->l = new_node; + + node->parent = new_node; + } else { + if ((glue = malloc(sizeof(*glue))) == NULL) + return (NULL); + memset(glue, '\0', sizeof(*glue)); + glue->bit = differ_bit; + glue->prefix = NULL; + glue->parent = node->parent; + glue->data = NULL; + radix->num_active_node++; + if (differ_bit < radix->maxbits && + BIT_TEST(addr[differ_bit >> 3], + 0x80 >> (differ_bit & 0x07))) { + glue->r = new_node; + glue->l = node; + } else { + glue->r = node; + glue->l = new_node; + } + new_node->parent = glue; + + if (node->parent == NULL) + radix->head = glue; + else if (node->parent->r == node) + node->parent->r = glue; + else + node->parent->l = glue; + + node->parent = glue; + } + return (new_node); +} + + +void +radix_remove(radix_tree_t *radix, radix_node_t *node) +{ + radix_node_t *parent, *child; + + if (node->r && node->l) { + /* + * this might be a placeholder node -- have to check and make + * sure there is a prefix aossciated with it ! + */ + if (node->prefix != NULL) + Deref_Prefix(node->prefix); + node->prefix = NULL; + /* Also I needed to clear data pointer -- masaki */ + node->data = NULL; + return; + } + if (node->r == NULL && node->l == NULL) { + parent = node->parent; + Deref_Prefix(node->prefix); + free(node); + radix->num_active_node--; + + if (parent == NULL) { + radix->head = NULL; + return; + } + if (parent->r == node) { + parent->r = NULL; + child = parent->l; + } else { + parent->l = NULL; + child = parent->r; + } + + if (parent->prefix) + return; + + /* we need to remove parent too */ + if (parent->parent == NULL) + radix->head = child; + else if (parent->parent->r == parent) + parent->parent->r = child; + else + parent->parent->l = child; + + child->parent = parent->parent; + free(parent); + radix->num_active_node--; + return; + } + if (node->r) + child = node->r; + else + child = node->l; + + parent = node->parent; + child->parent = parent; + + Deref_Prefix(node->prefix); + free(node); + radix->num_active_node--; + + if (parent == NULL) { + radix->head = child; + return; + } + if (parent->r == node) + parent->r = child; + else + parent->l = child; +} + +/* Local additions */ +static void +sanitise_mask(unsigned char *addr, unsigned int masklen, unsigned int maskbits) +{ + unsigned int i = masklen / 8; + unsigned int j = masklen % 8; + + if (j != 0) { + addr[i] &= (~0) << (8 - j); + i++; + } + for (; i < maskbits / 8; i++) + addr[i] = 0; +} + +prefix_t +*prefix_pton(const char *string, long len, prefix_t *prefix, const char **errmsg) +{ + char save[256], *cp, *ep; + struct addrinfo hints, *ai; + void *addr; + prefix_t *ret; + size_t slen; + int r; + + ret = NULL; + + /* Copy the string to parse, because we modify it */ + if ((slen = strlen(string) + 1) > sizeof(save)) { + *errmsg = "string too long"; + return (NULL); + } + memcpy(save, string, slen); + + if ((cp = strchr(save, '/')) != NULL) { + if (len != -1 ) { + *errmsg = "masklen specified twice"; + return (NULL); + } + *cp++ = '\0'; + len = strtol(cp, &ep, 10); + if (*cp == '\0' || *ep != '\0' || len < 0) { + *errmsg = "could not parse masklen"; + return (NULL); + } + /* More checks below */ + } + memset(&hints, '\0', sizeof(hints)); + hints.ai_flags = AI_NUMERICHOST; + + if ((r = getaddrinfo(save, NULL, &hints, &ai)) != 0) { + snprintf(save, sizeof(save), "getaddrinfo: %s:", + gai_strerror(r)); + *errmsg = save; + return NULL; + } + if (ai == NULL || ai->ai_addr == NULL) { + *errmsg = "getaddrinfo returned no result"; + goto out; + } + switch (ai->ai_addr->sa_family) { + case AF_INET: + if (len == -1) + len = 32; + else if (len < 0 || len > 32) + goto out; + addr = &((struct sockaddr_in *) ai->ai_addr)->sin_addr; + sanitise_mask(addr, len, 32); + break; + case AF_INET6: + if (len == -1) + len = 128; + else if (len < 0 || len > 128) + goto out; + addr = &((struct sockaddr_in6 *) ai->ai_addr)->sin6_addr; + sanitise_mask(addr, len, 128); + break; + default: + goto out; + } + + ret = New_Prefix2(ai->ai_addr->sa_family, addr, len, prefix); + if (ret == NULL) + *errmsg = "New_Prefix2 failed"; +out: + freeaddrinfo(ai); + return (ret); +} + +prefix_t +*prefix_from_blob(unsigned char *blob, int len, int prefixlen, prefix_t *prefix) +{ + int family, maxprefix; + + switch (len) { + case 4: + /* Assume AF_INET */ + family = AF_INET; + maxprefix = 32; + break; + case 16: + /* Assume AF_INET6 */ + family = AF_INET6; + maxprefix = 128; + break; + default: + /* Who knows? */ + return NULL; + } + if (prefixlen == -1) + prefixlen = maxprefix; + if (prefixlen < 0 || prefixlen > maxprefix) + return NULL; + return (New_Prefix2(family, blob, prefixlen, prefix)); +} + +const char * +prefix_addr_ntop(prefix_t *prefix, char *buf, size_t len) +{ + return (inet_ntop(prefix->family, &prefix->add, buf, len)); +} + +const char * +prefix_ntop(prefix_t *prefix, char *buf, size_t len) +{ + char addrbuf[128]; + + if (prefix_addr_ntop(prefix, addrbuf, sizeof(addrbuf)) == NULL) + return (NULL); + snprintf(buf, len, "%s/%d", addrbuf, prefix->bitlen); + + return (buf); +} diff --git a/release/src/router/smartdns/src/lib/rbtree.c b/release/src/router/smartdns/src/lib/rbtree.c index 8426cbebbb..87d0f276f0 100644 --- a/release/src/router/smartdns/src/lib/rbtree.c +++ b/release/src/router/smartdns/src/lib/rbtree.c @@ -1,524 +1,524 @@ -/************************************************************************* - * - * Copyright (C) 2018-2020 Ruilin Peng (Nick) . - * - * smartdns is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * smartdns is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#include "rbtree.h" -#include - -static inline void rb_set_black(struct rb_node *rb) -{ - rb->__rb_parent_color |= RB_BLACK; -} - -static inline struct rb_node *rb_red_parent(struct rb_node *red) -{ - return (struct rb_node *)red->__rb_parent_color; -} - -/* - * Helper function for rotations: - * - old's parent and color get assigned to new - * - old gets assigned new as a parent and 'color' as a color. - */ -static inline void -__rb_rotate_set_parents(struct rb_node *old, struct rb_node *new, - struct rb_root *root, int color) -{ - struct rb_node *parent = rb_parent(old); - new->__rb_parent_color = old->__rb_parent_color; - rb_set_parent_color(old, new, color); - __rb_change_child(old, new, parent, root); -} - -static inline void -__rb_insert(struct rb_node *node, struct rb_root *root, - void (*augment_rotate)(struct rb_node *old, struct rb_node *new)) -{ - struct rb_node *parent = rb_red_parent(node), *gparent, *tmp; - - while (true) { - /* - * Loop invariant: node is red - * - * If there is a black parent, we are done. - * Otherwise, take some corrective action as we don't - * want a red root or two consecutive red nodes. - */ - if (!parent) { - rb_set_parent_color(node, NULL, RB_BLACK); - break; - } else if (rb_is_black(parent)) - break; - - gparent = rb_red_parent(parent); - - tmp = gparent->rb_right; - if (parent != tmp) { /* parent == gparent->rb_left */ - if (tmp && rb_is_red(tmp)) { - /* - * Case 1 - color flips - * - * G g - * / \ / \ - * p u --> P U - * / / - * n n - * - * However, since g's parent might be red, and - * 4) does not allow this, we need to recurse - * at g. - */ - rb_set_parent_color(tmp, gparent, RB_BLACK); - rb_set_parent_color(parent, gparent, RB_BLACK); - node = gparent; - parent = rb_parent(node); - rb_set_parent_color(node, parent, RB_RED); - continue; - } - - tmp = parent->rb_right; - if (node == tmp) { - /* - * Case 2 - left rotate at parent - * - * G G - * / \ / \ - * p U --> n U - * \ / - * n p - * - * This still leaves us in violation of 4), the - * continuation into Case 3 will fix that. - */ - parent->rb_right = tmp = node->rb_left; - node->rb_left = parent; - if (tmp) - rb_set_parent_color(tmp, parent, - RB_BLACK); - rb_set_parent_color(parent, node, RB_RED); - augment_rotate(parent, node); - parent = node; - tmp = node->rb_right; - } - - /* - * Case 3 - right rotate at gparent - * - * G P - * / \ / \ - * p U --> n g - * / \ - * n U - */ - gparent->rb_left = tmp; /* == parent->rb_right */ - parent->rb_right = gparent; - if (tmp) - rb_set_parent_color(tmp, gparent, RB_BLACK); - __rb_rotate_set_parents(gparent, parent, root, RB_RED); - augment_rotate(gparent, parent); - break; - } else { - tmp = gparent->rb_left; - if (tmp && rb_is_red(tmp)) { - /* Case 1 - color flips */ - rb_set_parent_color(tmp, gparent, RB_BLACK); - rb_set_parent_color(parent, gparent, RB_BLACK); - node = gparent; - parent = rb_parent(node); - rb_set_parent_color(node, parent, RB_RED); - continue; - } - - tmp = parent->rb_left; - if (node == tmp) { - /* Case 2 - right rotate at parent */ - parent->rb_left = tmp = node->rb_right; - node->rb_right = parent; - if (tmp) - rb_set_parent_color(tmp, parent, - RB_BLACK); - rb_set_parent_color(parent, node, RB_RED); - augment_rotate(parent, node); - parent = node; - tmp = node->rb_left; - } - - /* Case 3 - left rotate at gparent */ - gparent->rb_right = tmp; /* == parent->rb_left */ - parent->rb_left = gparent; - if (tmp) - rb_set_parent_color(tmp, gparent, RB_BLACK); - __rb_rotate_set_parents(gparent, parent, root, RB_RED); - augment_rotate(gparent, parent); - break; - } - } -} - -/* - * Inline version for rb_erase() use - we want to be able to inline - * and eliminate the dummy_rotate callback there - */ -static inline void -____rb_erase_color(struct rb_node *parent, struct rb_root *root, - void (*augment_rotate)(struct rb_node *old, struct rb_node *new)) -{ - struct rb_node *node = NULL, *sibling, *tmp1, *tmp2; - - while (true) { - /* - * Loop invariants: - * - node is black (or NULL on first iteration) - * - node is not the root (parent is not NULL) - * - All leaf paths going through parent and node have a - * black node count that is 1 lower than other leaf paths. - */ - sibling = parent->rb_right; - if (node != sibling) { /* node == parent->rb_left */ - if (rb_is_red(sibling)) { - /* - * Case 1 - left rotate at parent - * - * P S - * / \ / \ - * N s --> p Sr - * / \ / \ - * Sl Sr N Sl - */ - parent->rb_right = tmp1 = sibling->rb_left; - sibling->rb_left = parent; - rb_set_parent_color(tmp1, parent, RB_BLACK); - __rb_rotate_set_parents(parent, sibling, root, - RB_RED); - augment_rotate(parent, sibling); - sibling = tmp1; - } - tmp1 = sibling->rb_right; - if (!tmp1 || rb_is_black(tmp1)) { - tmp2 = sibling->rb_left; - if (!tmp2 || rb_is_black(tmp2)) { - /* - * Case 2 - sibling color flip - * (p could be either color here) - * - * (p) (p) - * / \ / \ - * N S --> N s - * / \ / \ - * Sl Sr Sl Sr - * - * This leaves us violating 5) which - * can be fixed by flipping p to black - * if it was red, or by recursing at p. - * p is red when coming from Case 1. - */ - rb_set_parent_color(sibling, parent, - RB_RED); - if (rb_is_red(parent)) - rb_set_black(parent); - else { - node = parent; - parent = rb_parent(node); - if (parent) - continue; - } - break; - } - /* - * Case 3 - right rotate at sibling - * (p could be either color here) - * - * (p) (p) - * / \ / \ - * N S --> N Sl - * / \ \ - * sl Sr s - * \ - * Sr - */ - sibling->rb_left = tmp1 = tmp2->rb_right; - tmp2->rb_right = sibling; - parent->rb_right = tmp2; - if (tmp1) - rb_set_parent_color(tmp1, sibling, - RB_BLACK); - augment_rotate(sibling, tmp2); - tmp1 = sibling; - sibling = tmp2; - } - /* - * Case 4 - left rotate at parent + color flips - * (p and sl could be either color here. - * After rotation, p becomes black, s acquires - * p's color, and sl keeps its color) - * - * (p) (s) - * / \ / \ - * N S --> P Sr - * / \ / \ - * (sl) sr N (sl) - */ - parent->rb_right = tmp2 = sibling->rb_left; - sibling->rb_left = parent; - rb_set_parent_color(tmp1, sibling, RB_BLACK); - if (tmp2) - rb_set_parent(tmp2, parent); - __rb_rotate_set_parents(parent, sibling, root, - RB_BLACK); - augment_rotate(parent, sibling); - break; - } else { - sibling = parent->rb_left; - if (rb_is_red(sibling)) { - /* Case 1 - right rotate at parent */ - parent->rb_left = tmp1 = sibling->rb_right; - sibling->rb_right = parent; - rb_set_parent_color(tmp1, parent, RB_BLACK); - __rb_rotate_set_parents(parent, sibling, root, - RB_RED); - augment_rotate(parent, sibling); - sibling = tmp1; - } - tmp1 = sibling->rb_left; - if (!tmp1 || rb_is_black(tmp1)) { - tmp2 = sibling->rb_right; - if (!tmp2 || rb_is_black(tmp2)) { - /* Case 2 - sibling color flip */ - rb_set_parent_color(sibling, parent, - RB_RED); - if (rb_is_red(parent)) - rb_set_black(parent); - else { - node = parent; - parent = rb_parent(node); - if (parent) - continue; - } - break; - } - /* Case 3 - right rotate at sibling */ - sibling->rb_right = tmp1 = tmp2->rb_left; - tmp2->rb_left = sibling; - parent->rb_left = tmp2; - if (tmp1) - rb_set_parent_color(tmp1, sibling, - RB_BLACK); - augment_rotate(sibling, tmp2); - tmp1 = sibling; - sibling = tmp2; - } - /* Case 4 - left rotate at parent + color flips */ - parent->rb_left = tmp2 = sibling->rb_right; - sibling->rb_right = parent; - rb_set_parent_color(tmp1, sibling, RB_BLACK); - if (tmp2) - rb_set_parent(tmp2, parent); - __rb_rotate_set_parents(parent, sibling, root, - RB_BLACK); - augment_rotate(parent, sibling); - break; - } - } -} - -/* Non-inline version for rb_erase_augmented() use */ -void __rb_erase_color(struct rb_node *parent, struct rb_root *root, - void (*augment_rotate)(struct rb_node *old, struct rb_node *new)) -{ - ____rb_erase_color(parent, root, augment_rotate); -} - -/* - * Non-augmented rbtree manipulation functions. - * - * We use dummy augmented callbacks here, and have the compiler optimize them - * out of the rb_insert_color() and rb_erase() function definitions. - */ - -static inline void dummy_propagate(struct rb_node *node, struct rb_node *stop) {} -static inline void dummy_copy(struct rb_node *old, struct rb_node *new) {} -static inline void dummy_rotate(struct rb_node *old, struct rb_node *new) {} - -static const struct rb_augment_callbacks dummy_callbacks = { - dummy_propagate, dummy_copy, dummy_rotate -}; - -void rb_insert_color(struct rb_node *node, struct rb_root *root) -{ - __rb_insert(node, root, dummy_rotate); -} - -void rb_erase(struct rb_node *node, struct rb_root *root) -{ - struct rb_node *rebalance; - rebalance = __rb_erase_augmented(node, root, &dummy_callbacks); - if (rebalance) - ____rb_erase_color(rebalance, root, dummy_rotate); -} - -/* - * Augmented rbtree manipulation functions. - * - * This instantiates the same inline functions as in the non-augmented - * case, but this time with user-defined callbacks. - */ - -void __rb_insert_augmented(struct rb_node *node, struct rb_root *root, - void (*augment_rotate)(struct rb_node *old, struct rb_node *new)) -{ - __rb_insert(node, root, augment_rotate); -} - -/* - * This function returns the first node (in sort order) of the tree. - */ -struct rb_node *rb_first(const struct rb_root *root) -{ - struct rb_node *n; - - n = root->rb_node; - if (!n) - return NULL; - while (n->rb_left) - n = n->rb_left; - return n; -} - -struct rb_node *rb_last(const struct rb_root *root) -{ - struct rb_node *n; - - n = root->rb_node; - if (!n) - return NULL; - while (n->rb_right) - n = n->rb_right; - return n; -} - -struct rb_node *rb_next(const struct rb_node *node) -{ - struct rb_node *parent; - - if (RB_EMPTY_NODE(node)) - return NULL; - - /* - * If we have a right-hand child, go down and then left as far - * as we can. - */ - if (node->rb_right) { - node = node->rb_right; - while (node->rb_left) - node=node->rb_left; - return (struct rb_node *)node; - } - - /* - * No right-hand children. Everything down and left is smaller than us, - * so any 'next' node must be in the general direction of our parent. - * Go up the tree; any time the ancestor is a right-hand child of its - * parent, keep going up. First time it's a left-hand child of its - * parent, said parent is our 'next' node. - */ - while ((parent = rb_parent(node)) && node == parent->rb_right) - node = parent; - - return parent; -} - -struct rb_node *rb_prev(const struct rb_node *node) -{ - struct rb_node *parent; - - if (RB_EMPTY_NODE(node)) - return NULL; - - /* - * If we have a left-hand child, go down and then right as far - * as we can. - */ - if (node->rb_left) { - node = node->rb_left; - while (node->rb_right) - node=node->rb_right; - return (struct rb_node *)node; - } - - /* - * No left-hand children. Go up till we find an ancestor which - * is a right-hand child of its parent. - */ - while ((parent = rb_parent(node)) && node == parent->rb_left) - node = parent; - - return parent; -} - -void rb_replace_node(struct rb_node *victim, struct rb_node *new, - struct rb_root *root) -{ - struct rb_node *parent = rb_parent(victim); - - /* Set the surrounding nodes to point to the replacement */ - __rb_change_child(victim, new, parent, root); - if (victim->rb_left) - rb_set_parent(victim->rb_left, new); - if (victim->rb_right) - rb_set_parent(victim->rb_right, new); - - /* Copy the pointers/colour from the victim to the replacement */ - *new = *victim; -} - -static struct rb_node *rb_left_deepest_node(const struct rb_node *node) -{ - for (;;) { - if (node->rb_left) - node = node->rb_left; - else if (node->rb_right) - node = node->rb_right; - else - return (struct rb_node *)node; - } -} - -struct rb_node *rb_next_postorder(const struct rb_node *node) -{ - const struct rb_node *parent; - if (!node) - return NULL; - parent = rb_parent(node); - - /* If we're sitting on node, we've already seen our children */ - if (parent && node == parent->rb_left && parent->rb_right) { - /* If we are the parent's left node, go to the parent's right - * node then all the way down to the left */ - return rb_left_deepest_node(parent->rb_right); - } else - /* Otherwise we are the parent's right node, and the parent - * should be next */ - return (struct rb_node *)parent; -} - -struct rb_node *rb_first_postorder(const struct rb_root *root) -{ - if (!root->rb_node) - return NULL; - - return rb_left_deepest_node(root->rb_node); -} +/************************************************************************* + * + * Copyright (C) 2018-2020 Ruilin Peng (Nick) . + * + * smartdns is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * smartdns is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "rbtree.h" +#include + +static inline void rb_set_black(struct rb_node *rb) +{ + rb->__rb_parent_color |= RB_BLACK; +} + +static inline struct rb_node *rb_red_parent(struct rb_node *red) +{ + return (struct rb_node *)red->__rb_parent_color; +} + +/* + * Helper function for rotations: + * - old's parent and color get assigned to new + * - old gets assigned new as a parent and 'color' as a color. + */ +static inline void +__rb_rotate_set_parents(struct rb_node *old, struct rb_node *new, + struct rb_root *root, int color) +{ + struct rb_node *parent = rb_parent(old); + new->__rb_parent_color = old->__rb_parent_color; + rb_set_parent_color(old, new, color); + __rb_change_child(old, new, parent, root); +} + +static inline void +__rb_insert(struct rb_node *node, struct rb_root *root, + void (*augment_rotate)(struct rb_node *old, struct rb_node *new)) +{ + struct rb_node *parent = rb_red_parent(node), *gparent, *tmp; + + while (true) { + /* + * Loop invariant: node is red + * + * If there is a black parent, we are done. + * Otherwise, take some corrective action as we don't + * want a red root or two consecutive red nodes. + */ + if (!parent) { + rb_set_parent_color(node, NULL, RB_BLACK); + break; + } else if (rb_is_black(parent)) + break; + + gparent = rb_red_parent(parent); + + tmp = gparent->rb_right; + if (parent != tmp) { /* parent == gparent->rb_left */ + if (tmp && rb_is_red(tmp)) { + /* + * Case 1 - color flips + * + * G g + * / \ / \ + * p u --> P U + * / / + * n n + * + * However, since g's parent might be red, and + * 4) does not allow this, we need to recurse + * at g. + */ + rb_set_parent_color(tmp, gparent, RB_BLACK); + rb_set_parent_color(parent, gparent, RB_BLACK); + node = gparent; + parent = rb_parent(node); + rb_set_parent_color(node, parent, RB_RED); + continue; + } + + tmp = parent->rb_right; + if (node == tmp) { + /* + * Case 2 - left rotate at parent + * + * G G + * / \ / \ + * p U --> n U + * \ / + * n p + * + * This still leaves us in violation of 4), the + * continuation into Case 3 will fix that. + */ + parent->rb_right = tmp = node->rb_left; + node->rb_left = parent; + if (tmp) + rb_set_parent_color(tmp, parent, + RB_BLACK); + rb_set_parent_color(parent, node, RB_RED); + augment_rotate(parent, node); + parent = node; + tmp = node->rb_right; + } + + /* + * Case 3 - right rotate at gparent + * + * G P + * / \ / \ + * p U --> n g + * / \ + * n U + */ + gparent->rb_left = tmp; /* == parent->rb_right */ + parent->rb_right = gparent; + if (tmp) + rb_set_parent_color(tmp, gparent, RB_BLACK); + __rb_rotate_set_parents(gparent, parent, root, RB_RED); + augment_rotate(gparent, parent); + break; + } else { + tmp = gparent->rb_left; + if (tmp && rb_is_red(tmp)) { + /* Case 1 - color flips */ + rb_set_parent_color(tmp, gparent, RB_BLACK); + rb_set_parent_color(parent, gparent, RB_BLACK); + node = gparent; + parent = rb_parent(node); + rb_set_parent_color(node, parent, RB_RED); + continue; + } + + tmp = parent->rb_left; + if (node == tmp) { + /* Case 2 - right rotate at parent */ + parent->rb_left = tmp = node->rb_right; + node->rb_right = parent; + if (tmp) + rb_set_parent_color(tmp, parent, + RB_BLACK); + rb_set_parent_color(parent, node, RB_RED); + augment_rotate(parent, node); + parent = node; + tmp = node->rb_left; + } + + /* Case 3 - left rotate at gparent */ + gparent->rb_right = tmp; /* == parent->rb_left */ + parent->rb_left = gparent; + if (tmp) + rb_set_parent_color(tmp, gparent, RB_BLACK); + __rb_rotate_set_parents(gparent, parent, root, RB_RED); + augment_rotate(gparent, parent); + break; + } + } +} + +/* + * Inline version for rb_erase() use - we want to be able to inline + * and eliminate the dummy_rotate callback there + */ +static inline void +____rb_erase_color(struct rb_node *parent, struct rb_root *root, + void (*augment_rotate)(struct rb_node *old, struct rb_node *new)) +{ + struct rb_node *node = NULL, *sibling, *tmp1, *tmp2; + + while (true) { + /* + * Loop invariants: + * - node is black (or NULL on first iteration) + * - node is not the root (parent is not NULL) + * - All leaf paths going through parent and node have a + * black node count that is 1 lower than other leaf paths. + */ + sibling = parent->rb_right; + if (node != sibling) { /* node == parent->rb_left */ + if (rb_is_red(sibling)) { + /* + * Case 1 - left rotate at parent + * + * P S + * / \ / \ + * N s --> p Sr + * / \ / \ + * Sl Sr N Sl + */ + parent->rb_right = tmp1 = sibling->rb_left; + sibling->rb_left = parent; + rb_set_parent_color(tmp1, parent, RB_BLACK); + __rb_rotate_set_parents(parent, sibling, root, + RB_RED); + augment_rotate(parent, sibling); + sibling = tmp1; + } + tmp1 = sibling->rb_right; + if (!tmp1 || rb_is_black(tmp1)) { + tmp2 = sibling->rb_left; + if (!tmp2 || rb_is_black(tmp2)) { + /* + * Case 2 - sibling color flip + * (p could be either color here) + * + * (p) (p) + * / \ / \ + * N S --> N s + * / \ / \ + * Sl Sr Sl Sr + * + * This leaves us violating 5) which + * can be fixed by flipping p to black + * if it was red, or by recursing at p. + * p is red when coming from Case 1. + */ + rb_set_parent_color(sibling, parent, + RB_RED); + if (rb_is_red(parent)) + rb_set_black(parent); + else { + node = parent; + parent = rb_parent(node); + if (parent) + continue; + } + break; + } + /* + * Case 3 - right rotate at sibling + * (p could be either color here) + * + * (p) (p) + * / \ / \ + * N S --> N Sl + * / \ \ + * sl Sr s + * \ + * Sr + */ + sibling->rb_left = tmp1 = tmp2->rb_right; + tmp2->rb_right = sibling; + parent->rb_right = tmp2; + if (tmp1) + rb_set_parent_color(tmp1, sibling, + RB_BLACK); + augment_rotate(sibling, tmp2); + tmp1 = sibling; + sibling = tmp2; + } + /* + * Case 4 - left rotate at parent + color flips + * (p and sl could be either color here. + * After rotation, p becomes black, s acquires + * p's color, and sl keeps its color) + * + * (p) (s) + * / \ / \ + * N S --> P Sr + * / \ / \ + * (sl) sr N (sl) + */ + parent->rb_right = tmp2 = sibling->rb_left; + sibling->rb_left = parent; + rb_set_parent_color(tmp1, sibling, RB_BLACK); + if (tmp2) + rb_set_parent(tmp2, parent); + __rb_rotate_set_parents(parent, sibling, root, + RB_BLACK); + augment_rotate(parent, sibling); + break; + } else { + sibling = parent->rb_left; + if (rb_is_red(sibling)) { + /* Case 1 - right rotate at parent */ + parent->rb_left = tmp1 = sibling->rb_right; + sibling->rb_right = parent; + rb_set_parent_color(tmp1, parent, RB_BLACK); + __rb_rotate_set_parents(parent, sibling, root, + RB_RED); + augment_rotate(parent, sibling); + sibling = tmp1; + } + tmp1 = sibling->rb_left; + if (!tmp1 || rb_is_black(tmp1)) { + tmp2 = sibling->rb_right; + if (!tmp2 || rb_is_black(tmp2)) { + /* Case 2 - sibling color flip */ + rb_set_parent_color(sibling, parent, + RB_RED); + if (rb_is_red(parent)) + rb_set_black(parent); + else { + node = parent; + parent = rb_parent(node); + if (parent) + continue; + } + break; + } + /* Case 3 - right rotate at sibling */ + sibling->rb_right = tmp1 = tmp2->rb_left; + tmp2->rb_left = sibling; + parent->rb_left = tmp2; + if (tmp1) + rb_set_parent_color(tmp1, sibling, + RB_BLACK); + augment_rotate(sibling, tmp2); + tmp1 = sibling; + sibling = tmp2; + } + /* Case 4 - left rotate at parent + color flips */ + parent->rb_left = tmp2 = sibling->rb_right; + sibling->rb_right = parent; + rb_set_parent_color(tmp1, sibling, RB_BLACK); + if (tmp2) + rb_set_parent(tmp2, parent); + __rb_rotate_set_parents(parent, sibling, root, + RB_BLACK); + augment_rotate(parent, sibling); + break; + } + } +} + +/* Non-inline version for rb_erase_augmented() use */ +void __rb_erase_color(struct rb_node *parent, struct rb_root *root, + void (*augment_rotate)(struct rb_node *old, struct rb_node *new)) +{ + ____rb_erase_color(parent, root, augment_rotate); +} + +/* + * Non-augmented rbtree manipulation functions. + * + * We use dummy augmented callbacks here, and have the compiler optimize them + * out of the rb_insert_color() and rb_erase() function definitions. + */ + +static inline void dummy_propagate(struct rb_node *node, struct rb_node *stop) {} +static inline void dummy_copy(struct rb_node *old, struct rb_node *new) {} +static inline void dummy_rotate(struct rb_node *old, struct rb_node *new) {} + +static const struct rb_augment_callbacks dummy_callbacks = { + dummy_propagate, dummy_copy, dummy_rotate +}; + +void rb_insert_color(struct rb_node *node, struct rb_root *root) +{ + __rb_insert(node, root, dummy_rotate); +} + +void rb_erase(struct rb_node *node, struct rb_root *root) +{ + struct rb_node *rebalance; + rebalance = __rb_erase_augmented(node, root, &dummy_callbacks); + if (rebalance) + ____rb_erase_color(rebalance, root, dummy_rotate); +} + +/* + * Augmented rbtree manipulation functions. + * + * This instantiates the same inline functions as in the non-augmented + * case, but this time with user-defined callbacks. + */ + +void __rb_insert_augmented(struct rb_node *node, struct rb_root *root, + void (*augment_rotate)(struct rb_node *old, struct rb_node *new)) +{ + __rb_insert(node, root, augment_rotate); +} + +/* + * This function returns the first node (in sort order) of the tree. + */ +struct rb_node *rb_first(const struct rb_root *root) +{ + struct rb_node *n; + + n = root->rb_node; + if (!n) + return NULL; + while (n->rb_left) + n = n->rb_left; + return n; +} + +struct rb_node *rb_last(const struct rb_root *root) +{ + struct rb_node *n; + + n = root->rb_node; + if (!n) + return NULL; + while (n->rb_right) + n = n->rb_right; + return n; +} + +struct rb_node *rb_next(const struct rb_node *node) +{ + struct rb_node *parent; + + if (RB_EMPTY_NODE(node)) + return NULL; + + /* + * If we have a right-hand child, go down and then left as far + * as we can. + */ + if (node->rb_right) { + node = node->rb_right; + while (node->rb_left) + node=node->rb_left; + return (struct rb_node *)node; + } + + /* + * No right-hand children. Everything down and left is smaller than us, + * so any 'next' node must be in the general direction of our parent. + * Go up the tree; any time the ancestor is a right-hand child of its + * parent, keep going up. First time it's a left-hand child of its + * parent, said parent is our 'next' node. + */ + while ((parent = rb_parent(node)) && node == parent->rb_right) + node = parent; + + return parent; +} + +struct rb_node *rb_prev(const struct rb_node *node) +{ + struct rb_node *parent; + + if (RB_EMPTY_NODE(node)) + return NULL; + + /* + * If we have a left-hand child, go down and then right as far + * as we can. + */ + if (node->rb_left) { + node = node->rb_left; + while (node->rb_right) + node=node->rb_right; + return (struct rb_node *)node; + } + + /* + * No left-hand children. Go up till we find an ancestor which + * is a right-hand child of its parent. + */ + while ((parent = rb_parent(node)) && node == parent->rb_left) + node = parent; + + return parent; +} + +void rb_replace_node(struct rb_node *victim, struct rb_node *new, + struct rb_root *root) +{ + struct rb_node *parent = rb_parent(victim); + + /* Set the surrounding nodes to point to the replacement */ + __rb_change_child(victim, new, parent, root); + if (victim->rb_left) + rb_set_parent(victim->rb_left, new); + if (victim->rb_right) + rb_set_parent(victim->rb_right, new); + + /* Copy the pointers/colour from the victim to the replacement */ + *new = *victim; +} + +static struct rb_node *rb_left_deepest_node(const struct rb_node *node) +{ + for (;;) { + if (node->rb_left) + node = node->rb_left; + else if (node->rb_right) + node = node->rb_right; + else + return (struct rb_node *)node; + } +} + +struct rb_node *rb_next_postorder(const struct rb_node *node) +{ + const struct rb_node *parent; + if (!node) + return NULL; + parent = rb_parent(node); + + /* If we're sitting on node, we've already seen our children */ + if (parent && node == parent->rb_left && parent->rb_right) { + /* If we are the parent's left node, go to the parent's right + * node then all the way down to the left */ + return rb_left_deepest_node(parent->rb_right); + } else + /* Otherwise we are the parent's right node, and the parent + * should be next */ + return (struct rb_node *)parent; +} + +struct rb_node *rb_first_postorder(const struct rb_root *root) +{ + if (!root->rb_node) + return NULL; + + return rb_left_deepest_node(root->rb_node); +} diff --git a/release/src/router/smartdns/src/lib/stringutil.c b/release/src/router/smartdns/src/lib/stringutil.c index 0e3c82b801..6923a38165 100644 --- a/release/src/router/smartdns/src/lib/stringutil.c +++ b/release/src/router/smartdns/src/lib/stringutil.c @@ -1,17 +1,17 @@ -/************************************************************************* - * - * Copyright (C) 2018-2020 Ruilin Peng (Nick) . - * - * smartdns is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * smartdns is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . +/************************************************************************* + * + * Copyright (C) 2018-2020 Ruilin Peng (Nick) . + * + * smartdns is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * smartdns is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . */ \ No newline at end of file diff --git a/release/src/router/smartdns/src/smartdns.c b/release/src/router/smartdns/src/smartdns.c index a763840240..52674d3c88 100644 --- a/release/src/router/smartdns/src/smartdns.c +++ b/release/src/router/smartdns/src/smartdns.c @@ -1,443 +1,456 @@ -/************************************************************************* - * - * Copyright (C) 2018-2020 Ruilin Peng (Nick) . - * - * smartdns is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * smartdns is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#define _GNU_SOURCE -#include "art.h" -#include "atomic.h" -#include "dns_client.h" -#include "dns_conf.h" -#include "dns_server.h" -#include "fast_ping.h" -#include "hashtable.h" -#include "list.h" -#include "rbtree.h" -#include "tlog.h" -#include "util.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define RESOLVE_FILE "/etc/resolv.conf" -#define MAX_LINE_LEN 1024 -#define MAX_KEY_LEN 64 -#define SMARTDNS_PID_FILE "/var/run/smartdns.pid" -#define TMP_BUFF_LEN_32 32 - -static int verbose_screen; - -static void _help(void) -{ - /* clang-format off */ - char *help = "" - "Usage: smartdns [OPTION]...\n" - "Start smartdns server.\n" - " -f run forground.\n" - " -c [conf] config file.\n" - " -p [pid] pid file path\n" - " -S ignore segment fault signal.\n" - " -x verbose screen.\n" - " -v dispaly version.\n" - " -h show this help message.\n" - - "Online help: http://pymumu.github.io/smartdns\n" - "Copyright (C) Nick Peng \n" - ; - /* clang-format on */ - printf("%s", help); -} - -static void _show_version(void) -{ - char str_ver[256] = {0}; -#ifdef SMARTDNS_VERION - const char *ver = SMARTDNS_VERION; - snprintf(str_ver, sizeof(str_ver), "%s", ver); -#else - struct tm tm; - get_compiled_time(&tm); - snprintf(str_ver, sizeof(str_ver), "1.%.4d%.2d%.2d-%.2d%.2d", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min); -#endif - printf("smartdns %s\n", str_ver); -} - -static int _smartdns_load_from_resolv(void) -{ - FILE *fp = NULL; - char line[MAX_LINE_LEN]; - char key[MAX_KEY_LEN]; - char value[MAX_LINE_LEN]; - char ns_ip[DNS_MAX_IPLEN]; - int port = PORT_NOT_DEFINED; - int ret = -1; - - int filed_num = 0; - int line_num = 0; - - fp = fopen(RESOLVE_FILE, "r"); - if (fp == NULL) { - tlog(TLOG_ERROR, "open %s failed, %s", RESOLVE_FILE, strerror(errno)); - return -1; - } - - while (fgets(line, MAX_LINE_LEN, fp)) { - line_num++; - filed_num = sscanf(line, "%63s %1023[^\r\n]s", key, value); - - if (filed_num != 2) { - continue; - } - - if (strncmp(key, "nameserver", MAX_KEY_LEN) != 0) { - continue; - } - - if (parse_ip(value, ns_ip, &port) != 0) { - continue; - } - - if (port == PORT_NOT_DEFINED) { - port = DEFAULT_DNS_PORT; - } - - safe_strncpy(dns_conf_servers[dns_conf_server_num].server, ns_ip, DNS_MAX_IPLEN); - dns_conf_servers[dns_conf_server_num].port = port; - dns_conf_servers[dns_conf_server_num].type = DNS_SERVER_UDP; - dns_conf_server_num++; - ret = 0; - } - - fclose(fp); - - return ret; -} - -static int _smartdns_add_servers(void) -{ - int i = 0; - int j = 0; - int ret = 0; - struct dns_server_groups *group = NULL; - struct dns_servers *server = NULL; - struct client_dns_server_flags flags; - - for (i = 0; i < dns_conf_server_num; i++) { - memset(&flags, 0, sizeof(flags)); - switch (dns_conf_servers[i].type) { - case DNS_SERVER_UDP: { - struct client_dns_server_flag_udp *flag_udp = &flags.udp; - flag_udp->ttl = dns_conf_servers[i].ttl; - } break; - case DNS_SERVER_HTTPS: { - struct client_dns_server_flag_https *flag_http = &flags.https; - flag_http->spi_len = dns_client_spki_decode(dns_conf_servers[i].spki, (unsigned char *)flag_http->spki); - safe_strncpy(flag_http->hostname, dns_conf_servers[i].hostname, sizeof(flag_http->hostname)); - safe_strncpy(flag_http->path, dns_conf_servers[i].path, sizeof(flag_http->path)); - safe_strncpy(flag_http->httphost, dns_conf_servers[i].httphost, sizeof(flag_http->httphost)); - safe_strncpy(flag_http->tls_host_verify, dns_conf_servers[i].tls_host_verify, sizeof(flag_http->tls_host_verify)); - } break; - case DNS_SERVER_TLS: { - struct client_dns_server_flag_tls *flag_tls = &flags.tls; - flag_tls->spi_len = dns_client_spki_decode(dns_conf_servers[i].spki, (unsigned char *)flag_tls->spki); - safe_strncpy(flag_tls->hostname, dns_conf_servers[i].hostname, sizeof(flag_tls->hostname)); - safe_strncpy(flag_tls->tls_host_verify, dns_conf_servers[i].tls_host_verify, sizeof(flag_tls->tls_host_verify)); - } break; - case DNS_SERVER_TCP: - break; - default: - return -1; - break; - } - - flags.type = dns_conf_servers[i].type; - flags.server_flag = dns_conf_servers[i].server_flag; - flags.result_flag = dns_conf_servers[i].result_flag; - ret = dns_client_add_server(dns_conf_servers[i].server, dns_conf_servers[i].port, dns_conf_servers[i].type, &flags); - if (ret != 0) { - tlog(TLOG_ERROR, "add server failed, %s:%d", dns_conf_servers[i].server, dns_conf_servers[i].port); - return -1; - } - } - - hash_for_each(dns_group_table.group, i, group, node) - { - ret = dns_client_add_group(group->group_name); - if (ret != 0) { - tlog(TLOG_ERROR, "add group failed, %s", group->group_name); - return -1; - } - - for (j = 0; j < group->server_num; j++) { - server = group->servers[j]; - if (server == NULL) { - continue; - } - ret = dns_client_add_to_group(group->group_name, server->server, server->port, server->type); - if (ret != 0) { - tlog(TLOG_ERROR, "add server %s to group %s failed", server->server, group->group_name); - return -1; - } - } - } - - return 0; -} - -static int _smartdns_set_ecs_ip(void) -{ - int ret = 0; - if (dns_conf_ipv4_ecs.enable) { - ret |= dns_client_set_ecs(dns_conf_ipv4_ecs.ip, dns_conf_ipv4_ecs.subnet); - } - - if (dns_conf_ipv6_ecs.enable) { - ret |= dns_client_set_ecs(dns_conf_ipv6_ecs.ip, dns_conf_ipv6_ecs.subnet); - } - - return ret; -} - -static int _smartdns_init_ssl(void) -{ - SSL_load_error_strings(); - SSL_library_init(); - OpenSSL_add_all_algorithms(); - SSL_CRYPTO_thread_setup(); - - return 0; -} - -static int _smartdns_destroy_ssl(void) -{ - SSL_CRYPTO_thread_cleanup(); - ERR_free_strings(); - EVP_cleanup(); - - return 0; -} - -static int _smartdns_init(void) -{ - int ret; - char *logfile = SMARTDNS_LOG_FILE; - - if (dns_conf_log_file[0] != 0) { - logfile = dns_conf_log_file; - } - - ret = tlog_init(logfile, dns_conf_log_size, dns_conf_log_num, 0, 0); - if (ret != 0) { - tlog(TLOG_ERROR, "start tlog failed.\n"); - goto errout; - } - - tlog_setlogscreen(verbose_screen); - tlog_setlevel(dns_conf_log_level); - - tlog(TLOG_NOTICE, "smartdns starting...(Copyright (C) Nick Peng , build:%s %s)", __DATE__, __TIME__); - - if (_smartdns_init_ssl() != 0) { - tlog(TLOG_ERROR, "init ssl failed."); - goto errout; - } - - if (dns_conf_server_num <= 0) { - if (_smartdns_load_from_resolv() != 0) { - tlog(TLOG_ERROR, "load dns from resolv failed."); - goto errout; - } - } - - ret = fast_ping_init(); - if (ret != 0) { - tlog(TLOG_ERROR, "start ping failed.\n"); - goto errout; - } - - ret = dns_server_init(); - if (ret != 0) { - tlog(TLOG_ERROR, "start dns server failed.\n"); - goto errout; - } - - ret = dns_client_init(); - if (ret != 0) { - tlog(TLOG_ERROR, "start dns client failed.\n"); - goto errout; - } - ret = _smartdns_add_servers(); - if (ret != 0) { - tlog(TLOG_ERROR, "add servers failed."); - goto errout; - } - - ret = _smartdns_set_ecs_ip(); - if (ret != 0) { - tlog(TLOG_WARN, "set ecs ip address failed."); - } - - return 0; -errout: - - return -1; -} - -static int _smartdns_run(void) -{ - return dns_server_run(); -} - -static void _smartdns_exit(void) -{ - dns_server_exit(); - dns_client_exit(); - fast_ping_exit(); - _smartdns_destroy_ssl(); - tlog_exit(); - dns_server_load_exit(); -} - -static void _sig_exit(int signo) -{ - dns_server_stop(); -} - -static void _sig_error_exit(int signo, siginfo_t *siginfo, void *ct) -{ - unsigned long PC = 0; - ucontext_t *context = ct; -#if defined(__i386__) - int *pgregs = (int *)(&(context->uc_mcontext.gregs)); - PC = pgregs[REG_EIP]; -#elif defined(__x86_64__) - int *pgregs = (int *)(&(context->uc_mcontext.gregs)); - PC = pgregs[REG_RIP]; -#elif defined(__arm__) - PC = context->uc_mcontext.arm_pc; -#elif defined(__aarch64__) - PC = context->uc_mcontext.pc; -#elif defined(__mips__) - PC = context->uc_mcontext.pc; -#endif - tlog(TLOG_FATAL, "process exit with signal %d, code = %d, errno = %d, pid = %d, self = %d, pc = %#lx, addr = %#lx, build(%s %s)\n", signo, siginfo->si_code, - siginfo->si_errno, siginfo->si_pid, getpid(), PC, (unsigned long)siginfo->si_addr, __DATE__, __TIME__); - - sleep(1); - _exit(0); -} - -static int sig_list[] = {SIGSEGV, SIGABRT, SIGBUS, SIGILL, SIGFPE}; - -static int sig_num = sizeof(sig_list) / sizeof(int); - -static void _reg_signal(void) -{ - struct sigaction act, old; - int i = 0; - act.sa_sigaction = _sig_error_exit; - sigemptyset(&act.sa_mask); - act.sa_flags = SA_RESTART | SA_SIGINFO; - - for (i = 0; i < sig_num; i++) { - sigaction(sig_list[i], &act, &old); - } -} - -int main(int argc, char *argv[]) -{ - int ret; - int is_forground = 0; - int opt; - char config_file[MAX_LINE_LEN]; - char pid_file[MAX_LINE_LEN]; - int signal_ignore = 0; - - safe_strncpy(config_file, SMARTDNS_CONF_FILE, MAX_LINE_LEN); - safe_strncpy(pid_file, SMARTDNS_PID_FILE, MAX_LINE_LEN); - - while ((opt = getopt(argc, argv, "fhc:p:Svx")) != -1) { - switch (opt) { - case 'f': - is_forground = 1; - break; - case 'c': - snprintf(config_file, sizeof(config_file), "%s", optarg); - break; - case 'p': - snprintf(pid_file, sizeof(pid_file), "%s", optarg); - break; - case 'S': - signal_ignore = 1; - break; - case 'x': - verbose_screen = 1; - break; - case 'v': - _show_version(); - return 0; - break; - case 'h': - _help(); - return 1; - } - } - - if (is_forground == 0) { - if (daemon(0, 0) < 0) { - fprintf(stderr, "run daemon process failed, %s\n", strerror(errno)); - return 1; - } - } - - if (signal_ignore == 0) { - _reg_signal(); - } - - if (create_pid_file(pid_file) != 0) { - goto errout; - } - - if (dns_server_load_conf(config_file) != 0) { - fprintf(stderr, "load config failed.\n"); - goto errout; - } - - ret = _smartdns_init(); - if (ret != 0) { - usleep(100000); - goto errout; - } - - signal(SIGINT, _sig_exit); - signal(SIGPIPE, SIG_IGN); - atexit(_smartdns_exit); - - return _smartdns_run(); - -errout: - - return 1; -} +/************************************************************************* + * + * Copyright (C) 2018-2020 Ruilin Peng (Nick) . + * + * smartdns is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * smartdns is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#define _GNU_SOURCE +#include "art.h" +#include "atomic.h" +#include "dns_client.h" +#include "dns_conf.h" +#include "dns_server.h" +#include "fast_ping.h" +#include "hashtable.h" +#include "list.h" +#include "rbtree.h" +#include "tlog.h" +#include "util.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define RESOLVE_FILE "/etc/resolv.conf" +#define MAX_LINE_LEN 1024 +#define MAX_KEY_LEN 64 +#define SMARTDNS_PID_FILE "/var/run/smartdns.pid" +#define TMP_BUFF_LEN_32 32 + +static int verbose_screen; + +static void _help(void) +{ + /* clang-format off */ + char *help = "" + "Usage: smartdns [OPTION]...\n" + "Start smartdns server.\n" + " -f run forground.\n" + " -c [conf] config file.\n" + " -p [pid] pid file path\n" + " -S ignore segment fault signal.\n" + " -x verbose screen.\n" + " -v dispaly version.\n" + " -h show this help message.\n" + + "Online help: http://pymumu.github.io/smartdns\n" + "Copyright (C) Nick Peng \n" + ; + /* clang-format on */ + printf("%s", help); +} + +static void _show_version(void) +{ + char str_ver[256] = {0}; +#ifdef SMARTDNS_VERION + const char *ver = SMARTDNS_VERION; + snprintf(str_ver, sizeof(str_ver), "%s", ver); +#else + struct tm tm; + get_compiled_time(&tm); + snprintf(str_ver, sizeof(str_ver), "1.%.4d%.2d%.2d-%.2d%.2d", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, + tm.tm_hour, tm.tm_min); +#endif + printf("smartdns %s\n", str_ver); +} + +static int _smartdns_load_from_resolv(void) +{ + FILE *fp = NULL; + char line[MAX_LINE_LEN]; + char key[MAX_KEY_LEN]; + char value[MAX_LINE_LEN]; + char ns_ip[DNS_MAX_IPLEN]; + int port = PORT_NOT_DEFINED; + int ret = -1; + + int filed_num = 0; + int line_num = 0; + + fp = fopen(RESOLVE_FILE, "r"); + if (fp == NULL) { + tlog(TLOG_ERROR, "open %s failed, %s", RESOLVE_FILE, strerror(errno)); + return -1; + } + + while (fgets(line, MAX_LINE_LEN, fp)) { + line_num++; + filed_num = sscanf(line, "%63s %1023[^\r\n]s", key, value); + + if (filed_num != 2) { + continue; + } + + if (strncmp(key, "nameserver", MAX_KEY_LEN) != 0) { + continue; + } + + if (parse_ip(value, ns_ip, &port) != 0) { + continue; + } + + if (port == PORT_NOT_DEFINED) { + port = DEFAULT_DNS_PORT; + } + + safe_strncpy(dns_conf_servers[dns_conf_server_num].server, ns_ip, DNS_MAX_IPLEN); + dns_conf_servers[dns_conf_server_num].port = port; + dns_conf_servers[dns_conf_server_num].type = DNS_SERVER_UDP; + dns_conf_server_num++; + ret = 0; + } + + fclose(fp); + + return ret; +} + +static int _smartdns_add_servers(void) +{ + int i = 0; + int j = 0; + int ret = 0; + struct dns_server_groups *group = NULL; + struct dns_servers *server = NULL; + struct client_dns_server_flags flags; + + for (i = 0; i < dns_conf_server_num; i++) { + memset(&flags, 0, sizeof(flags)); + switch (dns_conf_servers[i].type) { + case DNS_SERVER_UDP: { + struct client_dns_server_flag_udp *flag_udp = &flags.udp; + flag_udp->ttl = dns_conf_servers[i].ttl; + } break; + case DNS_SERVER_HTTPS: { + struct client_dns_server_flag_https *flag_http = &flags.https; + flag_http->spi_len = dns_client_spki_decode(dns_conf_servers[i].spki, (unsigned char *)flag_http->spki); + safe_strncpy(flag_http->hostname, dns_conf_servers[i].hostname, sizeof(flag_http->hostname)); + safe_strncpy(flag_http->path, dns_conf_servers[i].path, sizeof(flag_http->path)); + safe_strncpy(flag_http->httphost, dns_conf_servers[i].httphost, sizeof(flag_http->httphost)); + safe_strncpy(flag_http->tls_host_verify, dns_conf_servers[i].tls_host_verify, + sizeof(flag_http->tls_host_verify)); + flag_http->skip_check_cert = dns_conf_servers[i].skip_check_cert; + } break; + case DNS_SERVER_TLS: { + struct client_dns_server_flag_tls *flag_tls = &flags.tls; + flag_tls->spi_len = dns_client_spki_decode(dns_conf_servers[i].spki, (unsigned char *)flag_tls->spki); + safe_strncpy(flag_tls->hostname, dns_conf_servers[i].hostname, sizeof(flag_tls->hostname)); + safe_strncpy(flag_tls->tls_host_verify, dns_conf_servers[i].tls_host_verify, + sizeof(flag_tls->tls_host_verify)); + flag_tls->skip_check_cert = dns_conf_servers[i].skip_check_cert; + + } break; + case DNS_SERVER_TCP: + break; + default: + return -1; + break; + } + + flags.type = dns_conf_servers[i].type; + flags.server_flag = dns_conf_servers[i].server_flag; + flags.result_flag = dns_conf_servers[i].result_flag; + ret = dns_client_add_server(dns_conf_servers[i].server, dns_conf_servers[i].port, dns_conf_servers[i].type, + &flags); + if (ret != 0) { + tlog(TLOG_ERROR, "add server failed, %s:%d", dns_conf_servers[i].server, dns_conf_servers[i].port); + return -1; + } + } + + hash_for_each(dns_group_table.group, i, group, node) + { + ret = dns_client_add_group(group->group_name); + if (ret != 0) { + tlog(TLOG_ERROR, "add group failed, %s", group->group_name); + return -1; + } + + for (j = 0; j < group->server_num; j++) { + server = group->servers[j]; + if (server == NULL) { + continue; + } + ret = dns_client_add_to_group(group->group_name, server->server, server->port, server->type); + if (ret != 0) { + tlog(TLOG_ERROR, "add server %s to group %s failed", server->server, group->group_name); + return -1; + } + } + } + + return 0; +} + +static int _smartdns_set_ecs_ip(void) +{ + int ret = 0; + if (dns_conf_ipv4_ecs.enable) { + ret |= dns_client_set_ecs(dns_conf_ipv4_ecs.ip, dns_conf_ipv4_ecs.subnet); + } + + if (dns_conf_ipv6_ecs.enable) { + ret |= dns_client_set_ecs(dns_conf_ipv6_ecs.ip, dns_conf_ipv6_ecs.subnet); + } + + return ret; +} + +static int _smartdns_init_ssl(void) +{ +#if OPENSSL_API_COMPAT < 0x10100000L + SSL_load_error_strings(); + SSL_library_init(); + OpenSSL_add_all_algorithms(); + SSL_CRYPTO_thread_setup(); +#endif + return 0; +} + +static int _smartdns_destroy_ssl(void) +{ +#if OPENSSL_API_COMPAT < 0x10100000L + SSL_CRYPTO_thread_cleanup(); + ERR_free_strings(); + EVP_cleanup(); +#endif + return 0; +} + +static int _smartdns_init(void) +{ + int ret; + char *logfile = SMARTDNS_LOG_FILE; + + if (dns_conf_log_file[0] != 0) { + logfile = dns_conf_log_file; + } + + ret = tlog_init(logfile, dns_conf_log_size, dns_conf_log_num, 0, 0); + if (ret != 0) { + tlog(TLOG_ERROR, "start tlog failed.\n"); + goto errout; + } + + tlog_setlogscreen(verbose_screen); + tlog_setlevel(dns_conf_log_level); + + tlog(TLOG_NOTICE, "smartdns starting...(Copyright (C) Nick Peng , build:%s %s)", __DATE__, + __TIME__); + + if (_smartdns_init_ssl() != 0) { + tlog(TLOG_ERROR, "init ssl failed."); + goto errout; + } + + if (dns_conf_server_num <= 0) { + if (_smartdns_load_from_resolv() != 0) { + tlog(TLOG_ERROR, "load dns from resolv failed."); + goto errout; + } + } + + ret = fast_ping_init(); + if (ret != 0) { + tlog(TLOG_ERROR, "start ping failed.\n"); + goto errout; + } + + ret = dns_server_init(); + if (ret != 0) { + tlog(TLOG_ERROR, "start dns server failed.\n"); + goto errout; + } + + ret = dns_client_init(); + if (ret != 0) { + tlog(TLOG_ERROR, "start dns client failed.\n"); + goto errout; + } + ret = _smartdns_add_servers(); + if (ret != 0) { + tlog(TLOG_ERROR, "add servers failed."); + goto errout; + } + + ret = _smartdns_set_ecs_ip(); + if (ret != 0) { + tlog(TLOG_WARN, "set ecs ip address failed."); + } + + return 0; +errout: + + return -1; +} + +static int _smartdns_run(void) +{ + return dns_server_run(); +} + +static void _smartdns_exit(void) +{ + dns_server_exit(); + dns_client_exit(); + fast_ping_exit(); + _smartdns_destroy_ssl(); + tlog_exit(); + dns_server_load_exit(); +} + +static void _sig_exit(int signo) +{ + dns_server_stop(); +} + +static void _sig_error_exit(int signo, siginfo_t *siginfo, void *ct) +{ + unsigned long PC = 0; + ucontext_t *context = ct; +#if defined(__i386__) + int *pgregs = (int *)(&(context->uc_mcontext.gregs)); + PC = pgregs[REG_EIP]; +#elif defined(__x86_64__) + int *pgregs = (int *)(&(context->uc_mcontext.gregs)); + PC = pgregs[REG_RIP]; +#elif defined(__arm__) + PC = context->uc_mcontext.arm_pc; +#elif defined(__aarch64__) + PC = context->uc_mcontext.pc; +#elif defined(__mips__) + PC = context->uc_mcontext.pc; +#endif + tlog(TLOG_FATAL, + "process exit with signal %d, code = %d, errno = %d, pid = %d, self = %d, pc = %#lx, addr = %#lx, build(%s " + "%s)\n", + signo, siginfo->si_code, siginfo->si_errno, siginfo->si_pid, getpid(), PC, (unsigned long)siginfo->si_addr, + __DATE__, __TIME__); + + sleep(1); + _exit(0); +} + +static int sig_list[] = {SIGSEGV, SIGABRT, SIGBUS, SIGILL, SIGFPE}; + +static int sig_num = sizeof(sig_list) / sizeof(int); + +static void _reg_signal(void) +{ + struct sigaction act, old; + int i = 0; + act.sa_sigaction = _sig_error_exit; + sigemptyset(&act.sa_mask); + act.sa_flags = SA_RESTART | SA_SIGINFO; + + for (i = 0; i < sig_num; i++) { + sigaction(sig_list[i], &act, &old); + } +} + +int main(int argc, char *argv[]) +{ + int ret; + int is_forground = 0; + int opt; + char config_file[MAX_LINE_LEN]; + char pid_file[MAX_LINE_LEN]; + int signal_ignore = 0; + + safe_strncpy(config_file, SMARTDNS_CONF_FILE, MAX_LINE_LEN); + safe_strncpy(pid_file, SMARTDNS_PID_FILE, MAX_LINE_LEN); + + while ((opt = getopt(argc, argv, "fhc:p:Svx")) != -1) { + switch (opt) { + case 'f': + is_forground = 1; + break; + case 'c': + snprintf(config_file, sizeof(config_file), "%s", optarg); + break; + case 'p': + snprintf(pid_file, sizeof(pid_file), "%s", optarg); + break; + case 'S': + signal_ignore = 1; + break; + case 'x': + verbose_screen = 1; + break; + case 'v': + _show_version(); + return 0; + break; + case 'h': + _help(); + return 1; + } + } + + if (is_forground == 0) { + if (daemon(0, 0) < 0) { + fprintf(stderr, "run daemon process failed, %s\n", strerror(errno)); + return 1; + } + } + + if (signal_ignore == 0) { + _reg_signal(); + } + + if (create_pid_file(pid_file) != 0) { + goto errout; + } + + if (dns_server_load_conf(config_file) != 0) { + fprintf(stderr, "load config failed.\n"); + goto errout; + } + + ret = _smartdns_init(); + if (ret != 0) { + usleep(100000); + goto errout; + } + + signal(SIGINT, _sig_exit); + signal(SIGPIPE, SIG_IGN); + atexit(_smartdns_exit); + + return _smartdns_run(); + +errout: + + return 1; +} diff --git a/release/src/router/smartdns/src/util.c b/release/src/router/smartdns/src/util.c index f26ec779d5..8d0c39a1c1 100644 --- a/release/src/router/smartdns/src/util.c +++ b/release/src/router/smartdns/src/util.c @@ -24,20 +24,20 @@ #include #include #include -#include +#include #include +#include +#include #include #include #include -#include #include #include +#include #include #include #include #include -#include -#include #define TMP_BUFF_LEN_32 32 @@ -285,14 +285,14 @@ int parse_ip(const char *value, char *ip, int *port) return 0; } -static int _check_is_ipv4(const char *ip) +static int _check_is_ipv4(const char *ip) { const char *ptr = ip; char c = 0; int dot_num = 0; int dig_num = 0; - while ( (c = *ptr++) != '\0') { + while ((c = *ptr++) != '\0') { if (c == '.') { dot_num++; dig_num = 0; @@ -326,7 +326,7 @@ static int _check_is_ipv6(const char *ip) int colon_num = 0; int dig_num = 0; - while ( (c = *ptr++) != '\0') { + while ((c = *ptr++) != '\0') { if (c == '[' || c == ']') { continue; } @@ -420,7 +420,7 @@ int parse_uri(char *value, char *scheme, char *host, int *port, char *path) if (path) { strncpy(path, process_ptr, PATH_MAX); - } + } return 0; } @@ -456,8 +456,8 @@ char *reverse_string(char *output, const char *input, int len, int to_lower_case if (to_lower_case) { if (*output >= 'A' && *output <= 'Z') { /* To lower case */ - *output = *output + 32; - } + *output = *output + 32; + } } output++; len--; @@ -502,7 +502,8 @@ static int _ipset_support_timeout(const char *ipsetname) return -1; } -static int _ipset_operate(const char *ipsetname, const unsigned char addr[], int addr_len, unsigned long timeout, int operate) +static int _ipset_operate(const char *ipsetname, const unsigned char addr[], int addr_len, unsigned long timeout, + int operate) { struct nlmsghdr *netlink_head; struct ipset_netlink_msg *netlink_msg; @@ -560,7 +561,9 @@ static int _ipset_operate(const char *ipsetname, const unsigned char addr[], int netlink_head->nlmsg_len += NETLINK_ALIGN(sizeof(struct ipset_netlink_attr)); nested[1]->type = NLA_F_NESTED | IPSET_ATTR_IP; - _ipset_add_attr(netlink_head, (af == AF_INET ? IPSET_ATTR_IPADDR_IPV4 : IPSET_ATTR_IPADDR_IPV6) | NLA_F_NET_BYTEORDER, addr_len, addr); + _ipset_add_attr(netlink_head, + (af == AF_INET ? IPSET_ATTR_IPADDR_IPV4 : IPSET_ATTR_IPADDR_IPV6) | NLA_F_NET_BYTEORDER, addr_len, + addr); nested[1]->len = (void *)buffer + NETLINK_ALIGN(netlink_head->nlmsg_len) - (void *)nested[1]; if (timeout > 0 && _ipset_support_timeout(ipsetname) == 0) { @@ -687,6 +690,7 @@ int create_pid_file(const char *pid_file) return -1; } +#if OPENSSL_API_COMPAT < 0x10100000 #define THREAD_STACK_SIZE (16 * 1024) static pthread_mutex_t *lock_cs; static long *lock_count; @@ -743,6 +747,7 @@ void SSL_CRYPTO_thread_cleanup(void) OPENSSL_free(lock_cs); OPENSSL_free(lock_count); } +#endif #define SERVER_NAME_LEN 256 #define TLS_HEADER_LEN 5 @@ -923,20 +928,20 @@ static int parse_server_name_extension(const char *data, size_t data_len, char * return -2; } -void get_compiled_time(struct tm *tm) -{ - char s_month[5]; - int month, day, year; +void get_compiled_time(struct tm *tm) +{ + char s_month[5]; + int month, day, year; int hour, min, sec; - static const char *month_names = "JanFebMarAprMayJunJulAugSepOctNovDec"; + static const char *month_names = "JanFebMarAprMayJunJulAugSepOctNovDec"; - sscanf(__DATE__, "%5s %d %d", s_month, &day, &year); - month = (strstr(month_names, s_month) - month_names) / 3; + sscanf(__DATE__, "%5s %d %d", s_month, &day, &year); + month = (strstr(month_names, s_month) - month_names) / 3; sscanf(__TIME__, "%d:%d:%d", &hour, &min, &sec); - tm->tm_year = year - 1900; - tm->tm_mon = month; - tm->tm_mday = day; - tm->tm_isdst = -1; + tm->tm_year = year - 1900; + tm->tm_mon = month; + tm->tm_mday = day; + tm->tm_isdst = -1; tm->tm_hour = hour; tm->tm_min = min; tm->tm_sec = sec; @@ -956,7 +961,7 @@ int has_network_raw_cap(void) int set_sock_keepalive(int fd, int keepidle, int keepinterval, int keepcnt) { const int yes = 1; - if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &yes, sizeof(yes))!= 0) { + if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &yes, sizeof(yes)) != 0) { return -1; } @@ -964,5 +969,19 @@ int set_sock_keepalive(int fd, int keepidle, int keepinterval, int keepcnt) setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &keepinterval, sizeof(keepinterval)); setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &keepcnt, sizeof(keepcnt)); + return 0; +} + +int set_sock_lingertime(int fd, int time) +{ + struct linger l; + + l.l_onoff = 1; + l.l_linger = 0; + + if (setsockopt(fd, SOL_SOCKET, SO_LINGER, (const char *)&l, sizeof(l)) != 0) { + return -1; + } + return 0; } \ No newline at end of file diff --git a/release/src/router/smartdns/src/util.h b/release/src/router/smartdns/src/util.h index 95cc9d2aec..1c581ae04e 100644 --- a/release/src/router/smartdns/src/util.h +++ b/release/src/router/smartdns/src/util.h @@ -19,23 +19,27 @@ #ifndef SMART_DNS_UTIL_H #define SMART_DNS_UTIL_H +#include "stringutil.h" #include #include -#include "stringutil.h" #ifdef __cplusplus extern "C" { #endif /*__cplusplus */ +#ifndef TCP_FASTOPEN +#define TCP_FASTOPEN 23 +#endif + #ifndef TCP_FASTOPEN_CONNECT #define TCP_FASTOPEN_CONNECT 30 #endif #ifndef TCP_THIN_LINEAR_TIMEOUTS -#define TCP_THIN_LINEAR_TIMEOUTS 16 +#define TCP_THIN_LINEAR_TIMEOUTS 16 #endif #ifndef TCP_THIN_DUPACK -#define TCP_THIN_DUPACK 17 +#define TCP_THIN_DUPACK 17 #endif #define PORT_NOT_DEFINED -1 @@ -98,6 +102,8 @@ int has_network_raw_cap(void); int set_sock_keepalive(int fd, int keepidle, int keepinterval, int keepcnt); +int set_sock_lingertime(int fd, int time); + #ifdef __cplusplus } #endif /*__cplusplus */ diff --git a/release/src/router/smartdns/systemd/smartdns.service.in b/release/src/router/smartdns/systemd/smartdns.service.in new file mode 100644 index 0000000000..052d9ea052 --- /dev/null +++ b/release/src/router/smartdns/systemd/smartdns.service.in @@ -0,0 +1,18 @@ +[Unit] +Description=smart dns server +After=network.target +StartLimitBurst=0 +StartLimitIntervalSec=60 + +[Service] +Type=forking +PIDFile=@RUNSTATEDIR@/smartdns.pid +EnvironmentFile=@SYSCONFDIR@/default/smartdns +ExecStart=@SBINDIR@/smartdns -p @RUNSTATEDIR@/smartdns.pid $SMART_DNS_OPTS +KillMode=process +Restart=always +RestartSec=2 + +[Install] +WantedBy=multi-user.target +Alias=smartdns.service diff --git a/release/src/router/softcenter/Makefile b/release/src/router/softcenter/Makefile index 3e3018fe6d..832aa729e3 100644 --- a/release/src/router/softcenter/Makefile +++ b/release/src/router/softcenter/Makefile @@ -24,8 +24,10 @@ install: install -d $(INSTALLDIR)/usr/bin install -d $(INSTALLDIR)/usr/share install -d $(INSTALLDIR)/usr/lib +ifeq ($(MERLINR_NAME), $(filter $(MERLINR_NAME), K3 XWR3100)) ifeq ($(MERLINR_NAME), $(filter $(MERLINR_NAME), K3)) install -d $(INSTALLDIR)/mcu +endif install -d $(INSTALLDIR)/rom/cfe/ endif install -d $(INSTALLDIR)/rom/etc @@ -38,6 +40,7 @@ else install -d $(INSTALLDIR)/www/js install -d $(INSTALLDIR)/www/res endif + install -d $(INSTALLDIR)/rom/etc/softcenter install -d $(INSTALLDIR)/rom/etc/softcenter/bin install -d $(INSTALLDIR)/rom/etc/softcenter/res install -d $(INSTALLDIR)/rom/etc/softcenter/res/layer @@ -50,20 +53,19 @@ endif install -d $(INSTALLDIR)/rom/etc/softcenter/scripts install -d $(INSTALLDIR)/rom/etc/softcenter/perp/.boot install -d $(INSTALLDIR)/rom/etc/softcenter/perp/.control -ifeq ($(BUILD_NAME), $(filter $(BUILD_NAME), GT-AC2900 GT-AC5300)) +ifeq ($(BUILD_NAME), $(filter $(BUILD_NAME), GT-AC2900 GT-AC5300 TUF-AX3000)) install -d $(INSTALLDIR)/rom/etc/softcenter/ROG/res - install -d $(INSTALLDIR)/rom/etc/softcenter/ROG/webs -else ifeq ($(BUILD_NAME), $(filter $(BUILD_NAME), TUF-AX3000)) - install -d $(INSTALLDIR)/rom/etc/softcenter/TUF/res - install -d $(INSTALLDIR)/rom/etc/softcenter/TUF/webs endif # softcenter + install -m 0755 softcenter/automount.sh $(INSTALLDIR)/rom/etc/softcenter install -m 0755 softcenter/bin/base64_encode $(INSTALLDIR)/rom/etc/softcenter/bin install -m 0755 softcenter/bin/jq $(INSTALLDIR)/rom/etc/softcenter/bin install -m 0755 softcenter/bin/softcenter.sh $(INSTALLDIR)/rom/etc/softcenter/bin install -m 0755 softcenter/bin/softcenter-mount.sh $(INSTALLDIR)/rom/etc/softcenter/bin install -m 0755 softcenter/bin/softcenter-net.sh $(INSTALLDIR)/rom/etc/softcenter/bin install -m 0755 softcenter/bin/softcenter-wan.sh $(INSTALLDIR)/rom/etc/softcenter/bin + install -m 0755 softcenter/bin/softcenter-services.sh $(INSTALLDIR)/rom/etc/softcenter/bin + install -m 0755 softcenter/bin/softcenter-unmount.sh $(INSTALLDIR)/rom/etc/softcenter/bin install -m 0755 softcenter/bin/perpboot $(INSTALLDIR)/rom/etc/softcenter/bin install -m 0755 softcenter/bin/perpctl $(INSTALLDIR)/rom/etc/softcenter/bin install -m 0755 softcenter/bin/perpd $(INSTALLDIR)/rom/etc/softcenter/bin @@ -74,7 +76,11 @@ endif install -m 0755 softcenter/bin/sissylog $(INSTALLDIR)/rom/etc/softcenter/bin install -m 0755 softcenter/bin/tinylog $(INSTALLDIR)/rom/etc/softcenter/bin install -m 0755 softcenter/bin/versioncmp $(INSTALLDIR)/rom/etc/softcenter/bin + install -m 0755 softcenter/res/sc1CN.json $(INSTALLDIR)/rom/etc/softcenter/res + install -m 0755 softcenter/res/sc1EN.json $(INSTALLDIR)/rom/etc/softcenter/res + install -m 0755 softcenter/res/sc1TW.json $(INSTALLDIR)/rom/etc/softcenter/res install -m 0755 softcenter/res/icon-default.png $(INSTALLDIR)/rom/etc/softcenter/res + install -m 0755 softcenter/res/merlinr.png $(INSTALLDIR)/rom/etc/softcenter/res install -m 0755 softcenter/res/upgrade.png $(INSTALLDIR)/rom/etc/softcenter/res install -m 0755 softcenter/res/softcenter.js $(INSTALLDIR)/rom/etc/softcenter/res install -m 0755 softcenter/res/softcenter.css $(INSTALLDIR)/rom/etc/softcenter/res @@ -96,19 +102,13 @@ endif install -m 0755 softcenter/perp/.control/perpd.pid $(INSTALLDIR)/rom/etc/softcenter/perp/.control install -m 0755 softcenter/scripts/base.sh $(INSTALLDIR)/rom/etc/softcenter/scripts install -m 0755 softcenter/scripts/ks_app_install.sh $(INSTALLDIR)/rom/etc/softcenter/scripts - install -m 0755 softcenter/scripts/ks_tar_intall.sh $(INSTALLDIR)/rom/etc/softcenter/scripts + install -m 0755 softcenter/scripts/ks_tar_install.sh $(INSTALLDIR)/rom/etc/softcenter/scripts #install -m 0755 softcenter/scripts/pluginbase.sh $(INSTALLDIR)/rom/etc/softcenter/scripts ifeq ($(MERLINR_NAME), $(filter $(MERLINR_NAME), K3C)) install -m 0755 mtd $(INSTALLDIR)/sbin endif -ifeq ($(BUILD_NAME), $(filter $(BUILD_NAME), GT-AC2900 GT-AC5300)) +ifeq ($(BUILD_NAME), $(filter $(BUILD_NAME), GT-AC2900 GT-AC5300 TUF-AX3000)) install -m 0755 softcenter/ROG/res/softcenter.css $(INSTALLDIR)/rom/etc/softcenter/ROG/res - install -m 0755 softcenter/ROG/webs/Main_Soft_center.asp $(INSTALLDIR)/rom/etc/softcenter/ROG/webs - install -m 0755 softcenter/ROG/webs/Main_Soft_setting.asp $(INSTALLDIR)/rom/etc/softcenter/ROG/webs -else ifeq ($(BUILD_NAME), $(filter $(BUILD_NAME), TUF-AX3000)) - install -m 0755 softcenter/TUF/res/softcenter.css $(INSTALLDIR)/rom/etc/softcenter/TUF/res - install -m 0755 softcenter/TUF/webs/Main_Soft_center.asp $(INSTALLDIR)/rom/etc/softcenter/TUF/webs - install -m 0755 softcenter/TUF/webs/Main_Soft_setting.asp $(INSTALLDIR)/rom/etc/softcenter/TUF/webs endif install -m 0755 jffsinit.sh $(INSTALLDIR)/usr/sbin ifeq ($(MERLINR_NAME), $(filter $(MERLINR_NAME), K3)) @@ -118,14 +118,16 @@ ifeq ($(MERLINR_NAME), $(filter $(MERLINR_NAME), K3)) install -m 0644 mcu/app.1.1.116.hex $(INSTALLDIR)/mcu install -m 0755 phi_speed $(INSTALLDIR)/usr/sbin install -m 0755 libwlcr.so $(INSTALLDIR)/usr/share - install -m 0644 cfe.bin $(INSTALLDIR)/rom/cfe/ install -m 0755 uhmi $(INSTALLDIR)/usr/sbin install -m 0755 weather $(INSTALLDIR)/usr/sbin install -m 0755 wl_cr $(INSTALLDIR)/usr/sbin + install -m 0644 cfe.bin $(INSTALLDIR)/rom/cfe/ +endif +ifeq ($(MERLINR_NAME), $(filter $(MERLINR_NAME), XWR3100)) + install -m 0644 xwr.bin $(INSTALLDIR)/rom/cfe/ endif install -m 0755 plugin.sh $(INSTALLDIR)/usr/sbin install -m 0755 helper.sh $(INSTALLDIR)/usr/sbin - ifeq ($(HND_ROUTER), y) install -m 0755 i18n.js $(INSTALLDIR)/www/www/js install -m 0755 scCN.json $(INSTALLDIR)/www/www/res @@ -138,6 +140,9 @@ else install -m 0755 scEN.json $(INSTALLDIR)/www/res install -m 0755 scTW.json $(INSTALLDIR)/www/res install -m 0755 Softcenter.asp $(INSTALLDIR)/www +ifeq ($(MERLINR_NAME), $(filter $(MERLINR_NAME), SBRAC1900P SBRAC3200P)) + install -m 0755 key.asp $(INSTALLDIR)/www +endif endif ifeq ($(or $(RTCONFIG_LANTIQ),$(RTCONFIG_QCA),$(RTCONFIG_RALINK)),y) install -m 0755 sysinfo/lantiq/Tools_Sysinfo.asp $(INSTALLDIR)/www/ diff --git a/release/src/router/softcenter/Softcenter.asp b/release/src/router/softcenter/Softcenter.asp index 1ea0d28cdd..175ad21841 100644 --- a/release/src/router/softcenter/Softcenter.asp +++ b/release/src/router/softcenter/Softcenter.asp @@ -31,7 +31,7 @@ - - - - - - - - - - - - - -
- - -
- - - - - - - - - "/> - "/> - "> - "> - - - - - - -
  - - - - - - - - - -
- - - - -
-
 
-
jffs extended settings
-
-
-
jffs extended settings
-
-
  • Support EXT/FAT/NTFS partitions.
  • -
  • No less than 1GB of free space.
  • -
  • Must unmount the current partition before mounting other partitions.
  • -
    - - - - - - - - - - - - - - - -
    Setting
    Enable -
    -
    Select a partition to mount - -
    -
    - - -
    -
    -
    - webui by: paldier
    -
    - -
    -
    -
    -
    - - - - diff --git a/release/src/router/softcenter/jffsinit.sh b/release/src/router/softcenter/jffsinit.sh index 5ce25f16a0..d3c1630d7c 100644 --- a/release/src/router/softcenter/jffsinit.sh +++ b/release/src/router/softcenter/jffsinit.sh @@ -3,12 +3,13 @@ SPACE_AVAL=$(df|grep jffs | awk '{print $2}') MODEL=`nvram get productid` - -if [ $SPACE_AVAL -gt 51200 -a "$(nvram get sc_mount)" == 0 ];then -if [ ! -d /jffs/softcenter ]; then - mkdir -p /jffs/softcenter - cp -rf /rom/etc/softcenter/* /jffs/softcenter/ +if [ "$MODEL" == "GT-AC5300" ] || [ "$MODEL" == "GT-AX11000" ] || [ "$MODEL" == "GT-AC2900" ] || [ "$(nvram get merlinr_rog)" == "1" ];then + ROG=1 +elif [ "$MODEL" == "TUF-AX3000" ] || [ "$(nvram get merlinr_tuf)" == "1" ] ;then + TUF=1 fi + +if [ $SPACE_AVAL -gt 40960 -a "$(nvram get sc_mount)" == 0 ];then mkdir -p /jffs/softcenter/init.d mkdir -p /jffs/softcenter/bin mkdir -p /jffs/softcenter/etc @@ -23,33 +24,30 @@ else if [ "$(nvram get sc_mount)" == 1 ];then mdisk=`nvram get sc_disk` usb_disk="/tmp/mnt/$mdisk" - if [ "$MODEL" == "BLUECAVE" ];then - [ -n "$(mount |grep $usb_disk |grep tfat)" ] && logger "Unsupport TFAT!" && exit 1 - fi + [ -n "$(mount |grep $usb_disk |grep tfat)" ] && logger "Unsupport TFAT!" && exit 1 if [ ! -e "$usb_disk" ]; then nvram set sc_mount="0" nvram commit logger "USB flash drive not detected!/没有找到可用的USB磁盘!" exit 1 else - if [ ! -f "/jffs/softcenter/webs/Main_Soft_center.asp" ] ;then - mkdir -p /jffs/softcenter - mkdir -p $usb_disk/bin - mkdir -p $usb_disk/res - mkdir -p $usb_disk/webs - mkdir -p $usb_disk/scripts - mkdir -p $usb_disk/lib - mkdir -p /jffs/softcenter/etc - mkdir -p /jffs/softcenter/init.d - mkdir -p /jffs/softcenter/configs - mkdir -p /jffs/softcenter/ss - mkdir -p /jffs/softcenter/perp - ln -sf $usb_disk/bin /jffs/softcenter/bin - ln -sf $usb_disk/res /jffs/softcenter/res - ln -sf $usb_disk/webs /jffs/softcenter/webs - ln -sf $usb_disk/scripts /jffs/softcenter/scripts - ln -sf $usb_disk/lib /jffs/softcenter/lib - fi + mkdir -p /jffs/softcenter + mkdir -p $usb_disk/bin + mkdir -p $usb_disk/res + mkdir -p $usb_disk/webs + mkdir -p $usb_disk/scripts + mkdir -p $usb_disk/lib + mkdir -p /jffs/softcenter/etc + mkdir -p /jffs/softcenter/init.d + mkdir -p /jffs/softcenter/configs + mkdir -p /jffs/softcenter/ss + mkdir -p /jffs/softcenter/perp + ln -sf $usb_disk/bin /jffs/softcenter/ + ln -sf $usb_disk/res /jffs/softcenter/ + ln -sf $usb_disk/webs /jffs/softcenter/ + ln -sf $usb_disk/scripts /jffs/softcenter/ + ln -sf $usb_disk/lib /jffs/softcenter/ + cd $usb_disk && touch .sc_installed fi else logger "Not enough free space for JFFS!/当前jffs分区剩余空间不足!" @@ -62,8 +60,15 @@ cp -rf /rom/etc/softcenter/res/* /jffs/softcenter/res/ cp -rf /rom/etc/softcenter/webs/* /jffs/softcenter/webs/ cp -rf /rom/etc/softcenter/bin/* /jffs/softcenter/bin/ cp -rf /rom/etc/softcenter/perp /jffs/softcenter/ -ln -sf /jffs/softcenter/bin/base64_encode /jffs/softcenter/bin/base64_decode -ln -sf /jffs/softcenter/scripts/ks_app_install.sh /jffs/softcenter/scripts/ks_app_remove.sh +cp -rf /rom/etc/softcenter/automount.sh /jffs/softcenter/ +if [ "$ROG" == "1" ]; then + cp -rf /rom/etc/softcenter/ROG/res/* /jffs/softcenter/res/ +elif [ "$TUF" == "1" ]; then + cp -rf /rom/etc/softcenter/ROG/res/* /jffs/softcenter/res/ + sed -i 's/3e030d/3e2902/g;s/91071f/92650F/g;s/680516/D0982C/g;s/cf0a2c/c58813/g;s/700618/74500b/g;s/530412/92650F/g' /jffs/softcenter/res/*.css >/dev/null 2>&1 +fi +[ ! -L "/jffs/softcenter/bin/base64_decode" ] && cd /jffs/softcenter/bin && ln -sf base64_encode base64_decode +[ ! -L "/jffs/softcenter/scripts/ks_app_remove.sh" ] && cd /jffs/softcenter/scripts && ln -sf ks_app_install.sh ks_app_remove.sh chmod 755 /jffs/softcenter/scripts/*.sh chmod 755 /jffs/softcenter/configs/*.sh chmod 755 /jffs/softcenter/bin/* @@ -71,8 +76,13 @@ chmod 755 /jffs/softcenter/init.d/* chmod 755 /jffs/softcenter/perp/* chmod 755 /jffs/softcenter/perp/.boot/* chmod 755 /jffs/softcenter/perp/.control/* -echo 1.2.0 > /jffs/softcenter/.soft_ver +chmod 755 /jffs/softcenter/automount.sh +echo 1.2.7 > /jffs/softcenter/.soft_ver +dbus set softcenter_api="1.1" +dbus set softcenter_version=`cat /jffs/softcenter/.soft_ver` dbus set softcenter_firmware_version=`nvram get extendno|cut -d "_" -f2|cut -d "-" -f1|cut -c2-6` +nvram set sc_installed=1 +nvram commit ARCH=`uname -m` KVER=`uname -r` if [ "$ARCH" == "armv7l" ]; then @@ -81,41 +91,25 @@ if [ "$ARCH" == "armv7l" ]; then else dbus set softcenter_arch="$ARCH" fi +elif [ "$KVER" == "3.10.14" ];then + dbus set softcenter_arch="mipsle" else - if [ "$KVER" == "3.10.14" ];then - dbus set softcenter_arch="mipsle" - else - dbus set softcenter_arch="$ARCH" - fi + dbus set softcenter_arch="$ARCH" fi -dbus set softcenter_api=`cat /jffs/softcenter/.soft_ver` -if [ "$MODEL" == "GT-AC5300" ] || [ "$MODEL" == "GT-AC2900" ];then - cp -rf /rom/etc/softcenter/ROG/webs/* /jffs/softcenter/webs/ - cp -rf /rom/etc/softcenter/ROG/res/* /jffs/softcenter/res/ -elif [ "$MODEL" == "TUF-AX3000" ] ;then - cp -rf /rom/etc/softcenter/TUF/webs/* /jffs/softcenter/webs/ - cp -rf /rom/etc/softcenter/TUF/res/* /jffs/softcenter/res/ +if [ -z "$(dbus get softcenter_server_tcode)" ]; then + modelname=`nvram get modelname` + if [ "$modelname" == "K3" -o "$modelname" == "XWR3100" ]; then + dbus set softcenter_server_tcode=CN + elif [ "$modelname" == "SBRAC1900P" -o "$modelname" == "SBR-AC1900P" -o "$modelname" == "SBRAC3200P" -o "$modelname" == "SBR-AC3200P" -o "$modelname" == "R7900P" -o "$modelname" == "R8000P" -o "$modelname" == "R7000P" ]; then + dbus set softcenter_server_tcode=ALI + else + dbus set softcenter_server_tcode=`nvram get territory_code |cut -c 1-2` + [ -z "$(dbus get softcenter_server_tcode)" ] && dbus set softcenter_server_tcode=GB + fi fi -nvram set sc_installed=1 -nvram commit -# creat wan-start file mkdir -p /jffs/scripts - if [ -z "$(dbus get softcenter_server_tcode)" ]; then - modelname=`nvram get modelname` - if [ "$modelname" == "K3" ]; then - dbus set softcenter_server_tcode=CN - elif [ "$modelname" == "SBRAC1900P" -o "$modelname" == "SBR-AC1900P" -o "$modelname" == "SBRAC3200P" -o "$modelname" == "SBR-AC3200P" -o "$modelname" == "R7900P" -o "$modelname" == "R8000P" ]; then - dbus set softcenter_server_tcode=ALI - elif [ "$modelname" == "GTAC2900" -o "$modelname" == "GTAC5300" -o "$modelname" == "RTAC86U" -o "$modelname" == "RTAX86U" -o "$modelname" == "RTAX68U" -o "$modelname" == "RTAX58U" -o "$modelname" == "RTAX82U" -o "$modelname" == "TUFAX3000" -o "$modelname" == "RTACRH17" -o "$modelname" == "RTAX56U" ]; then - dbus set softcenter_server_tcode=CN1 - else - dbus set softcenter_server_tcode=`nvram get territory_code |cut -c 1-2` - [ -z "$(dbus get softcenter_server_tcode)" ] && dbus set softcenter_server_tcode=GB - fi - fi - # creat profile file if [ ! -f /jffs/configs/profile.add ]; then cat > /jffs/configs/profile.add < - - - - - - - - -Merlin software center - - - - - - - - - - - - - - - - - - - -
    - - - - - - - - -
      - - - - - - - - -
    -
    - - - - -
    -
     
    -
    -
    - -
    - - - - - - - - - - - - - - - - - - - - - - - -
    -
    -

    - - - - -
    - -
    -
    -
    - - -
    -
    更新中...
    -
    -
    论坛技术支持: koolshare.cn -
    Github项目: github.com/koolshare -
    Shell & Web by: sadoneli , Xiaobao -
    修改版 by: paldier -
    Github项目: https://github.com/paldier -
    -
    -
    -
    -
    - - - - diff --git a/release/src/router/softcenter/softcenter/ROG/webs/Main_Soft_setting.asp b/release/src/router/softcenter/softcenter/ROG/webs/Main_Soft_setting.asp deleted file mode 100644 index 7b55eafd42..0000000000 --- a/release/src/router/softcenter/softcenter/ROG/webs/Main_Soft_setting.asp +++ /dev/null @@ -1,217 +0,0 @@ - - - - - - - - - -软件中心 - 离线安装 - - - - - - - - - - - - - - - - - - - - -
    - - -
    - - - - - - - - - "/> - "/> - - - - - - - -
      - - - - - - - - - -
    - - - - -
    -
     
    -
    软件中心,离线安装页面
    -
    -
    -
    -
    -
  • 通过本页面,你可以上传插件的离线安装包来安装插件;
  • -
  • 离线安装会自动解压tar.gz后缀的压缩包,识别压缩包一级目录下的install.sh文件并执行;
  • -
  • 建议开发者将插件版本号,md5等信息在install.sh文件内进行写入;
  • -
  • 注意离线安装包对应的cpu架构,上传错误的安装包会无法运行;
  • -
    -
    - - - - - - - - - - -
    软件中心 - 高级设置
    离线安装插件 - - - - -
    -
    - -
    -
    -
    论坛技术支持: www.koolshare.cn
    - 后台技术支持: Xiaobao
    - Shell, Web by: Sadoneli
    -
    修改版 by: paldier -
    -
    -
    -
    -
    - - - - - diff --git a/release/src/router/softcenter/softcenter/TUF/res/softcenter.css b/release/src/router/softcenter/softcenter/TUF/res/softcenter.css deleted file mode 100644 index a3698c00ab..0000000000 --- a/release/src/router/softcenter/softcenter/TUF/res/softcenter.css +++ /dev/null @@ -1,108 +0,0 @@ -/* For software center */ -.KoolshareBottom { - width: 230px; - height: 100px; - background: url(/res/koolshare.png) 0px 3px no-repeat; - text-align: left; - padding-left:150px; - padding-top:8px; - margin-top:20px; - float:right; -} - -.input_ss_table{ - margin-left:2px; - padding-left:0.4em; - height:21px; - width:158.2px; - line-height:23px \9; /*IE*/ - font-size:13px; - font-family: Lucida Console; - background-image:none; - background-color: transparent; - background-color: #92650F; - border:1px solid #fcb33a; - color:#FFFFFF; -} - -.FormTitle i { - color: #FC0; - font-style: normal; -} -.FormTitle em { - color: #00ffe4; - font-style: normal; -} -.FormTitle b { - color: #1cfe16; - font-style: normal; - font-weight:normal; -} -.FormTitle_firefox i { - color: #FC0; - font-style: normal; -} -.FormTitle_firefox em { - color: #00ffe4; - font-style: normal; -} -.FormTitle_firefox b { - color: #1cfe16; - font-style: normal; - font-weight:normal; -} -.SimpleNote { padding:5px 10px;} -.NoteButton { padding:5px 10px; margin:10px 0} -#NoteBox { padding:10px} -.FormTable h2,#NoteBox h2 { font-size:16px; border-bottom:1px #AAA dashed; height:26px; color:#1cfe16; margin-top:20px;} -.FormTable h3,#NoteBox h3, -.FormTable h4,#NoteBox h4 { color:#FC0;} -.IE8HACK{ - display: none \9; -} -.splitLine{ - background: #CEC1C7; - background: -webkit-linear-gradient(#CEC1C7 0%, #CEC1C7 20%, #766D71 80%, #766D71 100%); - background: -o-linear-gradient(#CEC1C7 0%, #CEC1C7 20%, #766D71 80%, #766D71 100%); - background: linear-gradient(#CEC1C7 0%, #CEC1C7 20%, #766D71 80%,#766D71 100%); - height: 2px; - width: 740px; - margin: 1px 0; -} - -[bgcolor="#4D595D"]{ - background: rgba(0, 0, 0, 0.5); -} -.submenuBlock{ - width:735px; - margin-top:-140px; - margin-bottom: -3px; -} -.tab{ - cursor:pointer; - background: #92650F; - color: White; - float: left; - height: 30px; - margin-left: -3px; - margin-right: 2px; - text-align:center; - text-decoration: none; - font-family: Verdana; - font-size: 12px; - border-radius: 5px 5px 0px 0px; -} -.tabClicked{ - cursor:pointer; - background: rgba(0, 0, 0, 0.5); - color: White; - float: left; - height: 30px; - margin-left: -3px; - margin-right: 2px; - text-align:center; - text-decoration: none; - font-family: Verdana; - font-size: 12px; - border-radius: 5px 5px 0px 0px; -} diff --git a/release/src/router/softcenter/softcenter/TUF/webs/Main_Soft_center.asp b/release/src/router/softcenter/softcenter/TUF/webs/Main_Soft_center.asp deleted file mode 100644 index 35b3bf5698..0000000000 --- a/release/src/router/softcenter/softcenter/TUF/webs/Main_Soft_center.asp +++ /dev/null @@ -1,784 +0,0 @@ - - - - - - - - - -Merlin software center - - - - - - - - - - - - - - - - - - - -
    - - - - - - - - -
      - - - - - - - - -
    -
    - - - - -
    -
     
    -
    -
    - -
    - - - - - - - - - - - - - - - - - - - - - - - -
    -
    -

    - - - - -
    - -
    -
    -
    - - -
    -
    更新中...
    -
    -
    论坛技术支持: koolshare.cn -
    Github项目: github.com/koolshare -
    Shell & Web by: sadoneli , Xiaobao -
    修改版 by: paldier -
    Github项目: https://github.com/paldier -
    -
    -
    -
    -
    - - - - diff --git a/release/src/router/softcenter/softcenter/TUF/webs/Main_Soft_setting.asp b/release/src/router/softcenter/softcenter/TUF/webs/Main_Soft_setting.asp deleted file mode 100644 index 70a59ff89f..0000000000 --- a/release/src/router/softcenter/softcenter/TUF/webs/Main_Soft_setting.asp +++ /dev/null @@ -1,217 +0,0 @@ - - - - - - - - - -软件中心 - 离线安装 - - - - - - - - - - - - - - - - - - - - -
    - - -
    - - - - - - - - - "/> - "/> - - - - - - - -
      - - - - - - - - - -
    - - - - -
    -
     
    -
    软件中心,离线安装页面
    -
    -
    -
    -
    -
  • 通过本页面,你可以上传插件的离线安装包来安装插件;
  • -
  • 离线安装会自动解压tar.gz后缀的压缩包,识别压缩包一级目录下的install.sh文件并执行;
  • -
  • 建议开发者将插件版本号,md5等信息在install.sh文件内进行写入;
  • -
  • 注意离线安装包对应的cpu架构,上传错误的安装包会无法运行;
  • -
    -
    - - - - - - - - - - -
    软件中心 - 高级设置
    离线安装插件 - - - - -
    -
    - -
    -
    -
    论坛技术支持: www.koolshare.cn
    - 后台技术支持: Xiaobao
    - Shell, Web by: Sadoneli
    -
    修改版 by: paldier -
    -
    -
    -
    -
    - - - - - diff --git a/release/src/router/softcenter/softcenter/automount.sh b/release/src/router/softcenter/softcenter/automount.sh new file mode 100644 index 0000000000..adea87def9 --- /dev/null +++ b/release/src/router/softcenter/softcenter/automount.sh @@ -0,0 +1,13 @@ +#!/bin/sh + +mdisk=`nvram get sc_disk` +cd /tmp/mnt +if [ ! -d "$mdisk" ]; then + list_disk=`ls /tmp/mnt` + for cur_disk in $list_disk do + if [ -f "$cur_disk/.sc_installed" ]; then + ln -sf $cur_disk $mdisk + fi + done +fi + diff --git a/release/src/router/softcenter/softcenter/bin/softcenter-services.sh b/release/src/router/softcenter/softcenter/bin/softcenter-services.sh new file mode 100644 index 0000000000..0742079348 --- /dev/null +++ b/release/src/router/softcenter/softcenter/bin/softcenter-services.sh @@ -0,0 +1,30 @@ +#!/bin/sh + +source /jffs/softcenter/scripts/base.sh +ACTION=$1 + +if [ $# -lt 1 ]; then + printf "Usage: $0 {start|stop|restart|reconfigure|check|kill}\n" >&2 + exit 1 +fi + +for i in $(find /jffs/softcenter/init.d/ -name 'V*' | sort) ; +do + case "$i" in + V* | *.sh ) + # Source shell script for speed. + trap "" INT QUIT TSTP EXIT + #set $1 + logger -t "SOFTCENTER" "plugin_service_log_1 $i" + if [ -r "$i" ]; then + $i $ACTION + fi + ;; + *) + # No sh extension, so fork subprocess. + logger -t "SOFTCENTER" "plugin_service_start_2 $i" + . $i $ACTION + ;; + esac +done + diff --git a/release/src/router/softcenter/softcenter/bin/softcenter-unmount.sh b/release/src/router/softcenter/softcenter/bin/softcenter-unmount.sh new file mode 100644 index 0000000000..7fe3a6a881 --- /dev/null +++ b/release/src/router/softcenter/softcenter/bin/softcenter-unmount.sh @@ -0,0 +1,26 @@ +#!/bin/sh + +source /jffs/softcenter/scripts/base.sh + +ACTION=$1 + + +for i in $(find /jffs/softcenter/init.d/ -name 'U*' | sort -n ) ; +do + case "$i" in + U* | *.sh ) + # Source shell script for speed. + trap "" INT QUIT TSTP EXIT + #set $1 + logger -t "SOFTCENTER" "plugin_mount_start_1 $i" + if [ -r "$i" ]; then + $i $ACTION + fi + ;; + *) + # No sh extension, so fork subprocess. + logger -t "SOFTCENTER" "plugin_mount_start_2 $i" + . $i $ACTION + ;; + esac +done diff --git a/release/src/router/softcenter/softcenter/bin/softcenter.sh b/release/src/router/softcenter/softcenter/bin/softcenter.sh index 0b4e037e60..f0ef3ed932 100644 --- a/release/src/router/softcenter/softcenter/bin/softcenter.sh +++ b/release/src/router/softcenter/softcenter/bin/softcenter.sh @@ -2,51 +2,8 @@ # this scripts used for .asusrouer to start softcenter source /jffs/softcenter/scripts/base.sh -sh /jffs/softcenter/perp/perp.sh start nvram set jffs2_scripts=1 nvram commit +dbus set softcenter_firmware_version=`nvram get extendno|cut -d "_" -f2|cut -d "-" -f1|cut -c2-6` -#============================================ -# check start up scripts -if [ ! -f "/jffs/scripts/wan-start" ];then - cat > /jffs/scripts/wan-start <<-EOF - #!/bin/sh - /jffs/softcenter/bin/softcenter-wan.sh start - EOF - chmod +x /jffs/scripts/wan-start -else - STARTCOMAND1=`cat /jffs/scripts/wan-start | grep -c "/jffs/softcenter/bin/softcenter-wan.sh start"` - [ "$STARTCOMAND1" -gt "1" ] && sed -i '/softcenter-wan.sh/d' /jffs/scripts/wan-start && sed -i '1a /jffs/softcenter/bin/softcenter-wan.sh start' /jffs/scripts/wan-start - [ "$STARTCOMAND1" == "0" ] && sed -i '1a /jffs/softcenter/bin/softcenter-wan.sh start' /jffs/scripts/wan-start -fi - -if [ -f "/jffs/scripts/service-start" ];then - STARTCOMAND=`cat /jffs/scripts/service-start | grep -c "watchdog"` - [ "$STARTCOMAND" -gt "1" ] && sed -i '/watchdog/d' /jffs/scripts/service-start && reboot -fi - -if [ ! -f "/jffs/scripts/nat-start" ];then - cat > /jffs/scripts/nat-start <<-EOF - #!/bin/sh - /jffs/softcenter/bin/softcenter-net.sh start_nat - EOF - chmod +x /jffs/scripts/nat-start -else - STARTCOMAND2=`cat /jffs/scripts/nat-start | grep -c "/jffs/softcenter/bin/softcenter-net.sh start"` - [ "$STARTCOMAND2" -gt "1" ] && sed -i '/softcenter-net.sh/d' /jffs/scripts/nat-start && sed -i '1a /jffs/softcenter/bin/softcenter-net.sh start_nat' /jffs/scripts/nat-start - [ "$STARTCOMAND2" == "0" ] && sed -i '1a /jffs/softcenter/bin/softcenter-net.sh start_nat' /jffs/scripts/nat-start -fi - -if [ ! -f "/jffs/scripts/post-mount" ];then - cat > /jffs/scripts/post-mount <<-EOF - #!/bin/sh - /jffs/softcenter/bin/softcenter-mount.sh start - EOF - chmod +x /jffs/scripts/post-mount -else - STARTCOMAND3=`cat /jffs/scripts/post-mount | grep -c "/jffs/softcenter/bin/softcenter-mount.sh start"` - [ "$STARTCOMAND3" -gt "1" ] && sed -i '/softcenter-mount.sh/d' /jffs/scripts/post-mount && sed -i '1a /jffs/softcenter/bin/softcenter-mount.sh start' /jffs/scripts/post-mount - [ "$STARTCOMAND3" == "0" ] && sed -i '1a /jffs/softcenter/bin/softcenter-mount.sh start' /jffs/scripts/post-mount -fi -#============================================ diff --git a/release/src/router/softcenter/softcenter/res/sc1CN.json b/release/src/router/softcenter/softcenter/res/sc1CN.json new file mode 100644 index 0000000000..ef1876fb2d --- /dev/null +++ b/release/src/router/softcenter/softcenter/res/sc1CN.json @@ -0,0 +1,21 @@ +{ + "Software Center": "软件中心", + "Software Center, Offline installation": "软件中心,离线安装页面", + "On this page, you can upload the plugin's offline installation package for manual installation;": "通过本页面,你可以上传插件的离线安装包来安装插件;", + "Offline installation will automatically decompress the tar.gz suffix archived package, then find out the install.sh file in the first level folder of the archived package and execute it;": "离线安装会自动解压tar.gz后缀的压缩包,识别压缩包一级目录下的install.sh文件并执行;", + "It is recommended to write the plugin version, md5 and other information to the install.sh file;": "建议开发者将插件版本号,md5等信息在install.sh文件内进行写入;", + "Note : You should choose offline installation package of the supported CPU architectures to install, otherwise it will not run;": "注意离线安装包对应的cpu架构,上传错误的安装包会无法运行;", + "Offline installation": "离线安装", + "Upload": "上传并安装", + "Done": "完成", + "Install": "安装", + "Update": "更新", + "Uninstall": "卸载", + "Installed": "已安装", + "Online": "未安装", + "Current version:": "当前版本:", + "Latest version:": "在线版本:", + "loading...": "更新中...", + "Softcenter - Offline installation": "软件中心 - 离线安装" +} + diff --git a/release/src/router/softcenter/softcenter/res/sc1EN.json b/release/src/router/softcenter/softcenter/res/sc1EN.json new file mode 100644 index 0000000000..01076aa037 --- /dev/null +++ b/release/src/router/softcenter/softcenter/res/sc1EN.json @@ -0,0 +1,21 @@ +{ + "Software Center": "Software Center", + "Software Center, Offline installation": "Software Center, Offline installation", + "On this page, you can upload the plugin's offline installation package for manual installation;": "On this page, you can upload the plugin's offline installation package for manual installation;", + "Offline installation will automatically decompress the tar.gz suffix archived package, then find out the install.sh file in the first level folder of the archived package and execute it;": "Offline installation will automatically decompress the tar.gz suffix archived package, then find out the install.sh file in the first level folder of the archived package and execute it;", + "It is recommended to write the plugin version, md5 and other information to the install.sh file;": "It is recommended to write the plugin version, md5 and other information to the install.sh file;", + "Note : You should choose offline installation package of the supported CPU architectures to install, otherwise it will not run;": "Note : You should choose offline installation package of the supported CPU architectures to install, otherwise it will not run;", + "Offline installation": "Offline installation", + "Upload": "Upload", + "Done": "Done", + "Install": "Install", + "Update": "Update", + "Uninstall": "Uninstall", + "Installed": "Installed", + "Online": "Online", + "Current version:": "Current version:", + "Latest version:": "Latest version:", + "loading...": "loading...", + "Softcenter - Offline installation": "Software Center - Offline installation" +} + diff --git a/release/src/router/softcenter/softcenter/res/sc1TW.json b/release/src/router/softcenter/softcenter/res/sc1TW.json new file mode 100644 index 0000000000..3102f5a57e --- /dev/null +++ b/release/src/router/softcenter/softcenter/res/sc1TW.json @@ -0,0 +1,21 @@ +{ + "Software Center": "軟體中心", + "Software Center, Offline installation": "軟體中心,離線安裝", + "On this page, you can upload the plugin's offline installation package for manual installation;": "通過本頁面,你可以上載插件的離線安裝包來安裝插件;", + "Offline installation will automatically decompress the tar.gz suffix archived package, then find out the install.sh file in the first level folder of the archived package and execute it;": "離線安裝會自動解壓tar.gz後綴的壓縮包,自動識別壓縮包一級目錄下的install.sh文件並執行;", + "It is recommended to write the plugin version, md5 and other information to the install.sh file;": "建議開發者將插件版本號,md5等信息寫入到install.sh文件內;", + "Note : You should choose offline installation package of the supported CPU architectures to install, otherwise it will not run;": "注意選擇正確cpu架構的離線安裝包,否則插件會無法運行;", + "Offline installation": "離線安裝", + "Upload": "上載並安裝", + "Done": "完成", + "Install": "安裝", + "Update": "更新", + "Uninstall": "卸載", + "Installed": "已安裝", + "Online": "未安裝", + "Current version:": "當前版本:", + "Latest version:": "在線版本:", + "loading...": "更新中...", + "Softcenter - Offline installation": "軟體中心 - 離線安裝" +} + diff --git a/release/src/router/softcenter/softcenter/res/softcenter.css b/release/src/router/softcenter/softcenter/res/softcenter.css index e00ed9f1f5..eec75934b3 100644 --- a/release/src/router/softcenter/softcenter/res/softcenter.css +++ b/release/src/router/softcenter/softcenter/res/softcenter.css @@ -68,3 +68,22 @@ width: 740px; margin: 1px 0; } +.show-install-btn, .show-uninstall-btn { + border: none; + background: #444; + color: #fff; + padding: 10px 20px; + border-radius: 5px 5px 0px 0px; +} +.active { + background: #444f53; + border: 1px solid #444f53; +} +#log_content1 { + width:99%; + font-family:'Lucida Console'; + font-size:12px; + background:#475A5F; + color:#FFFFFF; +} + diff --git a/release/src/router/softcenter/softcenter/scripts/ks_app_install.sh b/release/src/router/softcenter/softcenter/scripts/ks_app_install.sh index eedc55df9f..e9103fe581 100644 --- a/release/src/router/softcenter/softcenter/scripts/ks_app_install.sh +++ b/release/src/router/softcenter/softcenter/scripts/ks_app_install.sh @@ -29,6 +29,8 @@ export PERP_BASE=/jffs/softcenter/perp #softcenter_installing_status=13 #然而并没有更新! #softcenter_installing_status=14 #正在检查是否有更新~ #softcenter_installing_status=15 #检测更新错误! +#softcenter_installing_status=16 #下载错误,代码:! +#softcenter_installing_status=17 #卸载失败!请关闭插件后重试! softcenter_home_url=`dbus get softcenter_home_url` CURR_TICK=`date +%s` @@ -56,10 +58,15 @@ fi if [ "$KVER" == "3.10.14" ];then ARCH_SUFFIX="mipsle" fi -VER_SUFFIX=_version -MD5_SUFFIX=_md5 -INSTALL_SUFFIX=_install -UNINSTALL_SUFFIX=_uninstall + +MODEL=$(nvram get productid) +if [ "$MODEL" == "GT-AC5300" ] || [ "$MODEL" == "GT-AC2900" ] || [ "$MODEL" == "GT-AX11000" ] || [ "$(nvram get merlinr_rog)" == "1" ];then + ROG=1 +fi + +if [ "$(nvram get productid)" == "TUF-AX3000" ] || [ "$(nvram get merlinr_tuf)" == "1" ];then + TUF=1 +fi LOGGER() { # echo $1 @@ -95,25 +102,21 @@ install_module() { dbus save softcenter_installing_ URL_SPLIT="/" - #OLD_MD5=`dbus get softcenter_module_$softcenter_installing_module$MD5_SUFFIX` - OLD_VERSION=`dbus get softcenter_module_$softcenter_installing_module$VER_SUFFIX` + #OLD_MD5=`dbus get softcenter_module_${softcenter_installing_module}_md5` + OLD_VERSION=`dbus get softcenter_module_${softcenter_installing_module}_version` if [ -z "$(dbus get softcenter_server_tcode)" ]; then modelname=`nvram get modelname` - if [ "$modelname" == "K3" ]; then + if [ "$modelname" == "K3" ] || [ "$modelname" == "GTAC2900" ] || [ "$modelname" == "GTAC5300" ] || [ "$modelname" == "RTAC86U" ] || [ "$modelname" == "RTAX86U" ] || [ "$modelname" == "RTAX68U" ] || [ "$modelname" == "RTAX82U" ] || [ "$modelname" == "TUFAX3000" ] || [ "$modelname" == "RTACRH17" ] || [ "$modelname" == "XWR3100" ]; then dbus set softcenter_server_tcode=CN - elif [ "$modelname" == "SBRAC1900P" -o "$modelname" == "SBR-AC1900P" -o "$modelname" == "SBRAC3200P" -o "$modelname" == "SBR-AC3200P" -o "$modelname" == "R7900P" -o "$modelname" == "R8000P" ]; then + elif [ "$modelname" == "SBRAC1900P" ] || [ "$modelname" == "SBR-AC1900P" ] || [ "$modelname" == "SBRAC3200P" ] || [ "$modelname" == "SBR-AC3200P" ] || [ "$modelname" == "R7900P" ] || [ "$modelname" == "R8000P" ] || [ "$modelname" == "R7000P" ]; then dbus set softcenter_server_tcode=ALI - elif [ "$modelname" == "GTAC2900" -o "$modelname" == "GTAC5300" -o "$modelname" == "RTAC86U" -o "$modelname" == "RTAX86U" -o "$modelname" == "RTAX68U" -o "$modelname" == "RTAX58U" -o "$modelname" == "RTAX82U" -o "$modelname" == "TUFAX3000" -o "$modelname" == "RTACRH17" ]; then - dbus set softcenter_server_tcode=CN1 else dbus set softcenter_server_tcode=`nvram get territory_code |cut -c 1-2` [ -z "$(dbus get softcenter_server_tcode)" ] && dbus set softcenter_server_tcode=GB fi fi eval `dbus export softcenter_server_tcode` - if [ "$softcenter_server_tcode" == "CN" ]; then - HOME_URL="http://update.wifi.com.cn/$ARCH_SUFFIX" - elif [ "$softcenter_server_tcode" == "CN1" ]; then + if [ "$softcenter_server_tcode" == "CN" ] || [ "$softcenter_server_tcode" == "CN1" ]; then HOME_URL="https://sc.softcenter.site/$ARCH_SUFFIX" elif [ "$softcenter_server_tcode" == "ALI" ]; then HOME_URL="https://wufan.softcenter.site/$ARCH_SUFFIX" @@ -121,8 +124,7 @@ install_module() { HOME_URL="https://sc.paldier.com/$ARCH_SUFFIX" fi - #HOME_URL=`dbus get softcenter_home_url` - TAR_URL=$HOME_URL$URL_SPLIT$softcenter_installing_tar_url + TAR_URL=${HOME_URL}${URL_SPLIT}${softcenter_installing_tar_url} FNAME=`basename $softcenter_installing_tar_url` if [ "$OLD_VERSION" = "" ]; then @@ -130,7 +132,7 @@ install_module() { fi CMP=`versioncmp $softcenter_installing_version $OLD_VERSION` - if [ -f /jffs/softcenter/webs/Module_$softcenter_installing_module.sh -o "$softcenter_installing_todo" = "softcenter" ]; then + if [ -f "/jffs/softcenter/webs/Module_$softcenter_installing_module.sh" -o "$softcenter_installing_todo" = "softcenter" ]; then CMP="-1" fi if [ "$CMP" = "-1" ]; then @@ -140,17 +142,17 @@ install_module() { rm -rf "/tmp/$softcenter_installing_module" dbus set softcenter_installing_status="3" sleep 1 - wget --no-check-certificate --tries=1 --timeout=15 $TAR_URL + wget -t 2 -T 20 --dns-timeout=15 --no-check-certificate -q ${TAR_URL} RETURN_CODE=$? if [ "$RETURN_CODE" != "0" ]; then - dbus set softcenter_installing_status="12" - sleep 2 + dbus set softcenter_installing_status="16" + sleep 3 dbus set softcenter_installing_status="0" dbus set softcenter_installing_module="" dbus set softcenter_installing_todo="" LOGGER "wget $TAR_URL error, $RETURN_CODE" - exit 4 + exit $RETURN_CODE fi md5sum_gz=$(md5sum /tmp/$FNAME | sed 's/ /\n/g'| sed -n 1p) @@ -158,7 +160,7 @@ install_module() { LOGGER "md5 not equal $md5sum_gz" dbus set softcenter_installing_status="12" rm -f $FNAME - sleep 2 + sleep 3 dbus set softcenter_installing_status="0" dbus set softcenter_installing_module="" @@ -171,7 +173,7 @@ install_module() { tar -zxf $FNAME dbus set softcenter_installing_status="4" - if [ ! -f /tmp/$softcenter_installing_module/install.sh ]; then + if [ ! -f "/tmp/$softcenter_installing_module/install.sh" ]; then dbus set softcenter_installing_status="0" dbus set softcenter_installing_module="" dbus set softcenter_installing_todo="" @@ -183,26 +185,36 @@ install_module() { exit 5 fi - if [ -f /tmp/$softcenter_installing_module/uninstall.sh ]; then + if [ -f "/tmp/$softcenter_installing_module/uninstall.sh" ]; then chmod 755 /tmp/$softcenter_installing_module/uninstall.sh - mv /tmp/$softcenter_installing_module/uninstall.sh /jffs/softcenter/scripts/uninstall_$softcenter_installing_todo.sh + #mv /tmp/$softcenter_installing_module/uninstall.sh /jffs/softcenter/scripts/uninstall_$softcenter_installing_todo.sh fi + if [ -d /tmp/${softcenter_installing_module}/ROG -a "$ROG" == "1" ]; then + cp -rf /tmp/${softcenter_installing_module}/ROG/* /tmp/${softcenter_installing_module}/ + fi + + if [ -d /tmp/${softcenter_installing_module}/ROG -a "$TUF" == "1" ]; then + # 骚红变橙色 + find /tmp/${softcenter_installing_module}/ROG/ -name "*.asp" | xargs sed -i 's/3e030d/3e2902/g;s/91071f/92650F/g;s/680516/D0982C/g;s/cf0a2c/c58813/g;s/700618/74500b/g;s/530412/92650F/g' + find /tmp/${softcenter_installing_module}/ROG/ -name "*.css" | xargs sed -i 's/3e030d/3e2902/g;s/91071f/92650F/g;s/680516/D0982C/g;s/cf0a2c/c58813/g;s/700618/74500b/g;s/530412/92650F/g' + cp -rf /tmp/${softcenter_installing_module}/ROG/* /tmp/${softcenter_installing_module}/ + fi chmod a+x /tmp/$softcenter_installing_module/install.sh sh /tmp/$softcenter_installing_module/install.sh - sleep 2 + sleep 3 rm -f $FNAME rm -rf "/tmp/$softcenter_installing_module" if [ "$softcenter_installing_module" != "softcenter" ]; then - dbus set "softcenter_module_$softcenter_installing_module$MD5_SUFFIX=$softcenter_installing_md5" - dbus set "softcenter_module_$softcenter_installing_module$VER_SUFFIX=$softcenter_installing_version" - dbus set "softcenter_module_$softcenter_installing_module$INSTALL_SUFFIX=1" - dbus set "$softcenter_installing_module$VER_SUFFIX=$softcenter_installing_version" + dbus set softcenter_module_${softcenter_installing_module}_md5=${softcenter_installing_md5} + dbus set softcenter_module_${softcenter_installing_module}_version=${softcenter_installing_version} + dbus set softcenter_module_${softcenter_installing_module}_install=1 + dbus set ${softcenter_installing_module}_version=${softcenter_installing_version} else - dbus set softcenter_version=$softcenter_installing_version; - dbus set softcenter_md5=$softcenter_installing_md5 + dbus set softcenter_version=${softcenter_installing_version}; + dbus set softcenter_md5=${softcenter_installing_md5} fi dbus set softcenter_installing_module="" dbus set softcenter_installing_todo="" @@ -236,9 +248,12 @@ uninstall_module() { exit 3 fi - ENABLED=`dbus get "$softcenter_installing_todo""_enable"` + local ENABLED=`dbus get ${softcenter_installing_todo}_enable` if [ "$ENABLED" = "1" ]; then - LOGGER "please disable this module than try again" + LOGGER "please disable ${softcenter_installing_module} then try again" + dbus set softcenter_installing_status="17" + sleep 3 + dbus set softcenter_installing_status="0" exit 4 fi @@ -248,11 +263,14 @@ uninstall_module() { export softcenter_installing_status="6" dbus save softcenter_installing_ - dbus remove "softcenter_module_$softcenter_installing_module$MD5_SUFFIX" - dbus remove "softcenter_module_$softcenter_installing_module$VER_SUFFIX" - dbus remove "softcenter_module_$softcenter_installing_module$INSTALL_SUFFIX" + dbus remove softcenter_module_${softcenter_installing_module}_md5 + dbus remove softcenter_module_${softcenter_installing_module}_version + dbus remove softcenter_module_${softcenter_installing_module}_install + dbus remove softcenter_module_${softcenter_installing_module}_description + dbus remove softcenter_module_${softcenter_installing_module}_name + dbus remove softcenter_module_${softcenter_installing_module}_title - txt=`dbus list $softcenter_installing_todo` + txt=`dbus list ${softcenter_installing_todo}` printf "%s\n" "$txt" | while IFS= read -r line; do line2="${line%=*}" @@ -267,21 +285,25 @@ uninstall_module() { dbus set softcenter_installing_todo="" #try to call uninstall script - if [ -f "/jffs/softcenter/scripts/$softcenter_installing_todo$UNINSTALL_SUFFIX.sh"]; then - sh /jffs/softcenter/scripts/$softcenter_installing_todo$UNINSTALL_SUFFIX.sh - elif [ -f "/jffs/softcenter/scripts/uninstall_$softcenter_installing_todo.sh" ]; then - sh /jffs/softcenter/scripts/uninstall_$softcenter_installing_todo.sh + if [ -f "/jffs/softcenter/scripts/${softcenter_installing_todo}_uninstall.sh" ]; then + sh /jffs/softcenter/scripts/${softcenter_installing_todo}_uninstall.sh + elif [ -f "/jffs/softcenter/scripts/uninstall_${softcenter_installing_todo}.sh" ]; then + sh /jffs/softcenter/scripts/uninstall_${softcenter_installing_todo}.sh else - rm -f /jffs/softcenter/webs/Module_$softcenter_installing_todo.asp - rm -f /jffs/softcenter/init.d/S*$softcenter_installing_todo.sh + if [ -n "${softcenter_installing_todo}" ]; then + rm -rf /jffs/softcenter/${softcenter_installing_todo} + rm -rf /jffs/softcenter/bin/${softcenter_installing_todo} + rm -rf /jffs/softcenter/init.d/*${softcenter_installing_todo}* + rm -rf /jffs/softcenter/scripts/${softcenter_installing_todo}*.sh + rm -rf /jffs/softcenter/res/icon-${softcenter_installing_todo}.png + rm -rf /jffs/softcenter/webs/Module_${softcenter_installing_todo}.asp + fi fi } #LOGGER $BIN_NAME case $BIN_NAME in start) - sh /jffs/softcenter/perp/perp.sh stop - sh /jffs/softcenter/perp/perp.sh start dbus set softcenter_installing_status=1 ;; update) @@ -301,4 +323,3 @@ ks_app_remove) ;; esac - diff --git a/release/src/router/softcenter/softcenter/scripts/ks_tar_intall.sh b/release/src/router/softcenter/softcenter/scripts/ks_tar_install.sh similarity index 87% rename from release/src/router/softcenter/softcenter/scripts/ks_tar_intall.sh rename to release/src/router/softcenter/softcenter/scripts/ks_tar_install.sh index e7937d7e44..429df0d864 100644 --- a/release/src/router/softcenter/softcenter/scripts/ks_tar_intall.sh +++ b/release/src/router/softcenter/softcenter/scripts/ks_tar_install.sh @@ -15,7 +15,23 @@ clean(){ dbus remove soft_name } +detect_package(){ + local TEST="$1" + local KEYWORDS="ss|ssr|shadowsocks|shadowsocksr|v2ray|trojan|clash|wireguard|koolss|brook" + local KEY_MATCH=$(echo "${TEST}" | grep -Eo "$KEYWORDS") + if [ -n "$KEY_MATCH" ]; then + echo_date ======================================================= + echo_date "检测到离线安装包:${soft_name} 含非法关键词!!!" + echo_date "根据法律规定,软件中心将不会安装此插件!!!" + echo_date "删除相关文件并退出..." + echo_date ======================================================= + clean + exit 1 + fi +} install_tar(){ + #do the right thing + detect_package "$soft_name" name=`echo "$soft_name"|sed 's/.tar.gz//g'|awk -F "_" '{print $1}'|awk -F "-" '{print $1}'` INSTALL_SUFFIX=_install VER_SUFFIX=_version diff --git a/release/src/router/softcenter/softcenter/webs/Main_Soft_center.asp b/release/src/router/softcenter/softcenter/webs/Main_Soft_center.asp index 6a1c4d602c..fdcd04810b 100644 --- a/release/src/router/softcenter/softcenter/webs/Main_Soft_center.asp +++ b/release/src/router/softcenter/softcenter/webs/Main_Soft_center.asp @@ -7,7 +7,7 @@ -Merlin software center +Software Center @@ -23,6 +23,7 @@ +