From aa7237f770b48c4a8192a97a367715ad51a68ccc Mon Sep 17 00:00:00 2001 From: Nick Peng Date: Tue, 21 Jan 2020 19:53:40 +0800 Subject: [PATCH] Codesytle: replace CRLF with LF --- .clang-format | 18 +- ReadMe.md | 1410 +++--- ReadMe_en.md | 1404 +++--- package/build-pkg.sh | 6 +- .../luci/files/luci/i18n/smartdns.zh-cn.po | 564 +-- package/openwrt/address.conf | 32 +- package/openwrt/blacklist-ip.conf | 6 +- package/openwrt/custom.conf | 26 +- src/Makefile | 98 +- src/dns.c | 4008 ++++++++--------- src/dns_cache.c | 772 ++-- src/dns_cache.h | 174 +- src/dns_conf.c | 2724 +++++------ src/dns_conf.h | 494 +- src/fast_ping.c | 3368 +++++++------- src/fast_ping.h | 116 +- src/http_parse.c | 926 ++-- src/http_parse.h | 174 +- src/include/art.h | 502 +-- src/include/conf.h | 284 +- src/include/radix.h | 324 +- src/include/rbtree.h | 610 +-- src/include/stringutil.h | 84 +- src/lib/art.c | 2258 +++++----- src/lib/conf.c | 622 +-- src/lib/radix.c | 1352 +++--- src/lib/rbtree.c | 1048 ++--- src/lib/stringutil.c | 32 +- src/smartdns.c | 886 ++-- 29 files changed, 12161 insertions(+), 12161 deletions(-) diff --git a/.clang-format b/.clang-format index 5924a68..e35d26f 100755 --- a/.clang-format +++ b/.clang-format @@ -1,9 +1,9 @@ -#http://clang.llvm.org/docs/ClangFormatStyleOptions.html - -BasedOnStyle: LLVM -IndentWidth: 4 -TabWidth: 4 -UseTab: ForContinuationAndIndentation -MaxEmptyLinesToKeep: 1 -AllowShortFunctionsOnASingleLine: Empty -BreakBeforeBraces: Linux +#http://clang.llvm.org/docs/ClangFormatStyleOptions.html + +BasedOnStyle: LLVM +IndentWidth: 4 +TabWidth: 4 +UseTab: ForContinuationAndIndentation +MaxEmptyLinesToKeep: 1 +AllowShortFunctionsOnASingleLine: Empty +BreakBeforeBraces: Linux diff --git a/ReadMe.md b/ReadMe.md index a8e10a2..e99df86 100644 --- a/ReadMe.md +++ b/ReadMe.md @@ -1,705 +1,705 @@ -# 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 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/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 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_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 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证书主机名校验。
`[-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.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 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/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 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_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 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证书主机名校验。
`[-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协议开源。 diff --git a/ReadMe_en.md b/ReadMe_en.md index 499ef17..dbceea5 100755 --- a/ReadMe_en.md +++ b/ReadMe_en.md @@ -1,702 +1,702 @@ -# 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 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/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 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.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.
`[-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.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 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/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 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.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.
`[-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. diff --git a/package/build-pkg.sh b/package/build-pkg.sh index bb9c5aa..46266a8 100644 --- a/package/build-pkg.sh +++ b/package/build-pkg.sh @@ -14,7 +14,7 @@ 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 " --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:" @@ -27,7 +27,7 @@ showhelp() echo " build luci:" echo " $0 --platform luci" 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,7 +35,7 @@ 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() diff --git a/package/luci/files/luci/i18n/smartdns.zh-cn.po b/package/luci/files/luci/i18n/smartdns.zh-cn.po index 106f1c6..7a91f8b 100644 --- a/package/luci/files/luci/i18n/smartdns.zh-cn.po +++ b/package/luci/files/luci/i18n/smartdns.zh-cn.po @@ -1,282 +1,282 @@ -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." -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 "捐助" - - - - +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." +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/package/openwrt/address.conf b/package/openwrt/address.conf index 592b3ca..0f41344 100644 --- a/package/openwrt/address.conf +++ b/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/package/openwrt/blacklist-ip.conf b/package/openwrt/blacklist-ip.conf index ddb0965..7d26a7f 100644 --- a/package/openwrt/blacklist-ip.conf +++ b/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/package/openwrt/custom.conf b/package/openwrt/custom.conf index 3713dfa..0d14630 100644 --- a/package/openwrt/custom.conf +++ b/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/src/Makefile b/src/Makefile index 1a512a8..d510205 100644 --- a/src/Makefile +++ b/src/Makefile @@ -1,49 +1,49 @@ - -# 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 . - -BIN=smartdns -OBJS_LIB=lib/rbtree.o lib/art.o lib/bitops.o lib/radix.o lib/conf.o -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) - -# cflags -ifndef CFLAGS -CFLAGS =-O2 -g -Wall -Wstrict-prototypes -fno-omit-frame-pointer -Wstrict-aliasing -endif -override CFLAGS +=-Iinclude -override CFLAGS += -DBASE_FILE_NAME=\"$(notdir $<)\" -ifdef VER -override CFLAGS += -DSMARTDNS_VERION=\"$(VER)\" -endif - -CXXFLAGS=-O2 -g -Wall -std=c++11 -override CXXFLAGS +=-Iinclude - -# ldflags -ifeq ($(STATIC), yes) -override LDFLAGS += -lssl -lcrypto -Wl,--whole-archive -lpthread -Wl,--no-whole-archive -ldl -static -else -override LDFLAGS += -lssl -lcrypto -lpthread -endif - -.PHONY: all - -all: $(BIN) - -$(BIN) : $(OBJS) - $(CC) $(OBJS) -o $@ $(LDFLAGS) - -clean: - $(RM) $(OBJS) $(BIN) + +# 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 . + +BIN=smartdns +OBJS_LIB=lib/rbtree.o lib/art.o lib/bitops.o lib/radix.o lib/conf.o +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) + +# cflags +ifndef CFLAGS +CFLAGS =-O2 -g -Wall -Wstrict-prototypes -fno-omit-frame-pointer -Wstrict-aliasing +endif +override CFLAGS +=-Iinclude +override CFLAGS += -DBASE_FILE_NAME=\"$(notdir $<)\" +ifdef VER +override CFLAGS += -DSMARTDNS_VERION=\"$(VER)\" +endif + +CXXFLAGS=-O2 -g -Wall -std=c++11 +override CXXFLAGS +=-Iinclude + +# ldflags +ifeq ($(STATIC), yes) +override LDFLAGS += -lssl -lcrypto -Wl,--whole-archive -lpthread -Wl,--no-whole-archive -ldl -static +else +override LDFLAGS += -lssl -lcrypto -lpthread +endif + +.PHONY: all + +all: $(BIN) + +$(BIN) : $(OBJS) + $(CC) $(OBJS) -o $@ $(LDFLAGS) + +clean: + $(RM) $(OBJS) $(BIN) diff --git a/src/dns.c b/src/dns.c index 7f040c3..12b708d 100644 --- a/src/dns.c +++ b/src/dns.c @@ -1,2004 +1,2004 @@ -/************************************************************************* - * - * 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 "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 diff --git a/src/dns_cache.c b/src/dns_cache.c index 679d1bd..abff89e 100644 --- a/src/dns_cache.c +++ b/src/dns_cache.c @@ -1,386 +1,386 @@ -/************************************************************************* - * - * 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; + 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); +} diff --git a/src/dns_cache.h b/src/dns_cache.h index cb11955..91b1018 100644 --- a/src/dns_cache.h +++ b/src/dns_cache.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 _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 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/src/dns_conf.c b/src/dns_conf.c index cdf90cf..2eb770c 100644 --- a/src/dns_conf.c +++ b/src/dns_conf.c @@ -1,1362 +1,1362 @@ -/************************************************************************* - * - * 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; + +/* 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; +} diff --git a/src/dns_conf.h b/src/dns_conf.h index c02e3cb..1ed6350 100644 --- a/src/dns_conf.h +++ b/src/dns_conf.h @@ -1,247 +1,247 @@ -/************************************************************************* - * - * 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_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 diff --git a/src/fast_ping.c b/src/fast_ping.c index 85f5206..830a440 100644 --- a/src/fast_ping.c +++ b/src/fast_ping.c @@ -1,1684 +1,1684 @@ -/************************************************************************* - * - * 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)); + + 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); +} diff --git a/src/fast_ping.h b/src/fast_ping.h index 1682106..f1bf716 100644 --- a/src/fast_ping.h +++ b/src/fast_ping.h @@ -1,58 +1,58 @@ -/************************************************************************* - * - * 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/src/http_parse.c b/src/http_parse.c index 9aa7707..57564c7 100644 --- a/src/http_parse.c +++ b/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/src/http_parse.h b/src/http_parse.h index 250969e..8aa66ae 100644 --- a/src/http_parse.h +++ b/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/src/include/art.h b/src/include/art.h index eb9ccf4..fbdf307 100644 --- a/src/include/art.h +++ b/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/src/include/conf.h b/src/include/conf.h index 8115936..04ac58a 100644 --- a/src/include/conf.h +++ b/src/include/conf.h @@ -1,142 +1,142 @@ -/************************************************************************* - * - * 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/src/include/radix.h b/src/include/radix.h index adb5ab1..a8bdbe7 100644 --- a/src/include/radix.h +++ b/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/src/include/rbtree.h b/src/include/rbtree.h index c89e8ee..96a49c5 100644 --- a/src/include/rbtree.h +++ b/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/src/include/stringutil.h b/src/include/stringutil.h index 4d6ea6b..626a58c 100644 --- a/src/include/stringutil.h +++ b/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/src/lib/art.c b/src/lib/art.c index be5a672..d4308e3 100644 --- a/src/lib/art.c +++ b/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/src/lib/conf.c b/src/lib/conf.c index 23f2440..88a8903 100644 --- a/src/lib/conf.c +++ b/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/src/lib/radix.c b/src/lib/radix.c index 20dcd1e..7ffbd04 100644 --- a/src/lib/radix.c +++ b/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/src/lib/rbtree.c b/src/lib/rbtree.c index 8426cbe..87d0f27 100644 --- a/src/lib/rbtree.c +++ b/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/src/lib/stringutil.c b/src/lib/stringutil.c index 0e3c82b..6923a38 100644 --- a/src/lib/stringutil.c +++ b/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/src/smartdns.c b/src/smartdns.c index a763840..3a915a9 100644 --- a/src/smartdns.c +++ b/src/smartdns.c @@ -1,443 +1,443 @@ -/************************************************************************* - * - * 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)); + } 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; +}