Compare commits

..

85 Commits

Author SHA1 Message Date
Nick Peng
7cbd926ede optimize log 2019-12-15 01:28:16 +08:00
Nick Peng
fb3b0a7245 disable ping when smartdns run as non-root user 2019-12-15 01:28:15 +08:00
Nick Peng
64abad4077 Fix rule search issue. 2019-12-15 01:28:14 +08:00
Nick Peng
c3501923db fix /address/# not working when dualstack enabled 2019-12-15 01:28:13 +08:00
Nick Peng
721c56cbec socket ip priority optimize 2019-12-15 01:28:11 +08:00
Nick Peng
9213f898c3 Fix CNAME buff too short issue 2019-12-15 01:28:07 +08:00
Nick Peng
65e8cd5e61 optimize code 2019-12-15 01:28:04 +08:00
Nick Peng
e05d1f9d17 Enable audit-log SOA 2019-12-15 01:28:02 +08:00
Nick Peng
c4b99a99e7 UI support second DNS server. 2019-12-15 01:27:52 +08:00
Nick Peng
8c96081807 Update readme 2019-12-15 01:27:51 +08:00
Nick Peng
640efd7b86 Fix tcp local address issue 2019-12-15 01:27:50 +08:00
Nick Peng
add8eecead Fix crash issue caused by unknown http response 2019-12-15 01:27:46 +08:00
Nick Peng
da9ef34588 optimize log 2019-12-15 01:27:46 +08:00
Nick Peng
87f04571b1 minor optimize 2019-12-15 01:27:44 +08:00
Nick Peng
6291c17d6a Fix tcpping ipv6 address issue 2019-12-15 01:27:40 +08:00
Nick Peng
f801023569 Optimize prefetch hitime 2019-12-15 01:27:39 +08:00
Nick Peng
4e11c13ec0 Support no-soa, no-dualstack-selection for bind flags 2019-12-15 01:27:39 +08:00
Nick Peng
273c2d5100 Fix lint issue 2019-12-15 01:27:37 +08:00
Nick Peng
5082f1ae55 Update tlog 2019-12-15 01:27:36 +08:00
Nick Peng
3f7bc30f65 Support verify TLS hostname 2019-12-15 01:27:35 +08:00
Nick Peng
77bce2e7c6 Fix tcpidle close bind socket issue 2019-12-15 01:27:33 +08:00
Nick Peng
9a23bf6113 optimize code 2019-12-15 01:27:32 +08:00
Nick Peng
1f6e447f86 format code sytle 2019-12-15 01:27:30 +08:00
Nick Peng
b1eafb6491 Support listen multi ip addresses, and support server flags 2019-12-15 01:27:29 +08:00
Nick Peng
81468a3c4f Optimize answer process function 2019-12-15 01:27:27 +08:00
Nick Peng
9e928983e0 Support config speed-check-mode 2019-12-15 01:27:26 +08:00
Nick Peng
9b8d7de6d3 fix restart dnsmasq issue 2019-12-15 01:27:25 +08:00
Nick Peng
46742fc1d7 refactoring fast_ping.c 2019-12-15 01:27:25 +08:00
Nick Peng
358994e431 force restart dnsmasq when start smartdns 2019-12-15 01:27:24 +08:00
Nick Peng
7427d39476 Update tlog 2019-12-15 01:27:24 +08:00
Nick Peng
751c1e3a98 Fix dnsmasq not found issue 2019-12-15 01:27:23 +08:00
Nick Peng
90d5c7e396 Update tlog 2019-12-15 01:27:22 +08:00
Nick Peng
0a0d0f001e fix dns_server_query issue 2019-12-15 01:27:20 +08:00
Nick Peng
bc953d0c9b Minor code optimize 2019-12-15 01:27:19 +08:00
Nick Peng
44c854dfec _dns_server_recv function refactoring 2019-12-15 01:27:18 +08:00
Nick Peng
301a60f6ed Fix get opt issue 2019-12-15 01:27:17 +08:00
Nick Peng
4db61f2677 Fix TimeZone issue when static compile 2019-12-15 01:27:14 +08:00
Nick Peng
7746ecb46d Fix script issue on padavan 2019-12-15 01:27:13 +08:00
Nick Peng
4357847641 Add display version 2019-12-15 01:27:12 +08:00
Nick Peng
e7e0a5d4af Fix openssl version issue 2019-12-15 01:27:11 +08:00
Nick Peng
57aa9c013d Fix optware startup script issue 2019-12-15 01:27:10 +08:00
Nick Peng
7216dcf526 Update ReadMe.md 2019-12-15 01:27:09 +08:00
Nick Peng
41e2067628 Fix build issue 2019-12-15 01:27:06 +08:00
Nick Peng
dda785ec5f Support TLS 1.3 2019-12-15 01:27:05 +08:00
Nick Peng
99972c36ad Fix ps bug 2019-12-15 01:27:04 +08:00
Nick Peng
ef50ea9c5e Change rule domain to lowercase 2019-12-15 01:27:03 +08:00
Nick Peng
cb3656cb57 Change config accept-ip to whitelist-ip 2019-12-15 01:27:02 +08:00
Nick Peng
3ef325d75d Support GCC 8.x and support static compile 2019-12-15 01:27:02 +08:00
Nick Peng
a09e63d333 Support IP accept list 2019-12-15 01:27:01 +08:00
Nick Peng
9a067e99c7 Fix group pending add issue 2019-12-15 01:27:00 +08:00
Nick Peng
1e88305df8 Support Delay DNS server bootstrap 2019-12-15 01:26:59 +08:00
Nick Peng
93d9ef4095 Remove checkedns 2019-12-15 01:26:58 +08:00
Nick Peng
2f4bcd8201 Update ReadMe.md 2019-12-15 01:26:58 +08:00
Nick Peng
04fbb51a7b Update ReadMe.md add server SNI support 2019-12-15 01:26:56 +08:00
Nick Peng
01f94b4816 Fix address name too long segment issue 2019-12-15 01:26:50 +08:00
Nick Peng
bf52a0afbf Support custom TLS hostname, and http host 2019-12-15 01:26:48 +08:00
Nick Peng
94ab84444a optimize tcp log 2019-12-15 01:26:38 +08:00
Nick Peng
2da93e6420 Remove unused install script 2019-12-15 01:26:36 +08:00
Nick Peng
8345f92bd1 Update ReadMe.md 2019-12-15 01:26:35 +08:00
Nick Peng
d9eb2a063d when service pause for a long time, force invalidate cache after system resume 2019-12-15 01:26:34 +08:00
Nick Peng
2d01ed8a04 Support DNS Over HTTPS 2019-12-15 01:26:32 +08:00
Nick Peng
5501bfb6a3 Remove unused install script 2019-12-15 01:26:31 +08:00
Nick Peng
dcede4ffaa Avoid udp server reuse port 2019-12-15 01:26:30 +08:00
Nick Peng
4f89cb6b0f Update ReadMe.md 2019-12-15 01:26:30 +08:00
Nick Peng
915e6251b4 Update architecture.png 2019-12-15 01:26:29 +08:00
Nick Peng
63db66546c Fix cache leak issue 2019-12-15 01:26:28 +08:00
Nick Peng
7c51259dff Update ReadMe 2019-12-15 01:26:27 +08:00
Nick Peng
cddc511e6b Fix prefetch issue 2019-12-15 01:26:27 +08:00
Nick Peng
c94fafb026 Add query retry feature 2019-12-15 01:26:26 +08:00
Nick Peng
76367847d1 optimize dualstack selection feature 2019-12-15 01:26:25 +08:00
Nick Peng
bb9dfc6a33 Update ReadMe_zh-CN.md 2019-12-15 01:26:25 +08:00
Nick Peng
e0af4e4339 Support Armbian arm64 2019-12-15 01:26:24 +08:00
Nick Peng
7ee15e4075 Update ReadMe.md 2019-12-15 01:26:14 +08:00
Nick Peng
5c02f06844 Add FAQ 2019-12-15 01:26:10 +08:00
Nick Peng
c62ea93ba6 Support relative conf-path 2019-12-15 01:26:08 +08:00
Nick Peng
ef3a2196a0 Some document optimizations 2019-12-15 01:26:06 +08:00
Nick Peng
8e1b404ba0 Fix message issue 2019-12-15 01:26:04 +08:00
Nick Peng
02213de0ee Add support EDNS TCP-keep-alive 2019-12-15 01:26:03 +08:00
Nick Peng
7c2df9c96b LUCI support SPKI 2019-12-15 01:26:02 +08:00
Nick Peng
7828f0ec27 code lint and optimize code style 2019-12-15 01:26:01 +08:00
Nick Peng
c0c6fde39d Fix clang-tidy warning 2019-12-15 01:26:00 +08:00
Nick Peng
85b0eed3a2 Support TLS SPKI verify 2019-12-15 01:25:59 +08:00
Nick Peng
4465ce798a Support nameserver feature 2019-12-15 01:25:58 +08:00
Nick Peng
0df8c07103 Fix addr to string ip issue 2019-12-15 01:25:57 +08:00
Nick Peng
fbbbc80d20 Support auto configuration 2019-12-15 01:25:55 +08:00
55 changed files with 7807 additions and 2522 deletions

590
ReadMe.md Executable file → Normal file
View File

@@ -1,16 +1,35 @@
# SmartDNS
**[English](ReadMe_en.md)**
![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.
SmartDNS是一个运行在本地的DNS服务器SmartDNS接受本地客户端的DNS查询请求从多个上游DNS服务器获取DNS查询结果并将访问速度最快的结果返回给客户端提高网络访问速度。
同时支持指定特定域名IP地址并高性匹配达到过滤广告的效果。
dnsmasqall-servers不同,smartdns返回的是访问速度最快的解析结果。 (详细差异请看[FAQ](#faq))
Support Raspberry Pi, openwrt, ASUS router and other devices.
支持树莓派openwrt华硕路由器windows等设备。
## Software Show
## 目录
**Ali DNS**
Use Ali DNS to query Baidu's IP and test the results.
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. [声明](#声明)
1. [FAQ](#faq)
## 软件效果展示
**阿里DNS**
使用阿里DNS查询百度IP并检测结果。
```shell
pi@raspberrypi:~/code/smartdns_build $ nslookup www.baidu.com 223.5.5.5
@@ -43,7 +62,7 @@ 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.
使用SmartDNS查询百度IP并检测结果。
```shell
pi@raspberrypi:~/code/smartdns_build $ nslookup www.baidu.com
@@ -66,126 +85,176 @@ 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.
从对比看出smartdns找到访问www.baidu.com最快的IP地址这样访问百度比阿里DNS速度快5倍。
## 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.
1. **多DNS上游服务器**
支持配置多个上游DNS服务器并同时进行查询即使其中有DNS服务器异常也不会影响查询。
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.
1. **返回最快IP地址**
支持从域名所属IP地址列表中查找到访问速度最快的IP地址并返回给客户端提高网络访问速度。
3. **Support for multiple query protocols**
Support UDP, TCP, TLS queries, and non-53 port queries, effectively avoiding DNS pollution.
1. **支持多种查询协议**
支持UDPTCPTLS, HTTPS查询以及非53端口查询。
4. **Domain IP address specification**
Support configuring IP address of specific domain to achieve the effect of advertising filtering, and avoid malicious websites.
1. **特定域名IP地址指定**
支持指定域名的IP地址达到广告过滤效果避免恶意网站的效果。
5. **Domain name high performance rule filtering**
Support domain name suffix matching mode, simplify filtering configuration, filter 200,000 recording and take time <1ms.
1. **域名高性能后缀匹配**
支持域名后缀匹配模式简化过滤配置过滤20万条记录时间<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).
1. **域名分流**
支持域名分流不同类型的域名到不同的DNS服务器查询。
7. **Support IPV4, IPV6 dual stack**
Support IPV4, IPV6 network, support query A, AAAA record, dual-stack IP selection.
1. **Linux/Windows多平台支持**
支持标准Linux系统树莓派openwrt系统各种固件华硕路由器原生固件。以及支持Windows 10 WSL (Windows Subsystem for Linux)。
8. **High performance, low resource consumption**
Multi-threaded asynchronous IO mode, cache cache query results.
1. **支持IPV4, IPV6双栈**
支持IPV4IPV6网络支持查询A, AAAA记录支持双栈IP速度优化并支持完全禁用IPV6 AAAA解析。
## Architecture
1. **高性能,占用资源少**
多线程异步IO模式cache缓存查询结果。
## 架构
![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.
1. SmartDNS接收本地网络设备的DNS查询请求如PC手机的查询请求。
2. SmartDNS将查询请求发送到多个上游DNS服务器可采用标准UDP查询非标准端口UDP查询及TCP查询。
3. 上游DNS服务器返回域名对应的Server IP地址列表。SmartDNS检测与本地网络访问速度最快的Server IP。
4. 将访问速度最快的Server IP返回给本地客户端。
## Usage
## 使用
### Download the package
### 下载配套安装包
--------------
Download the matching version of the SmartDNS installation package. The corresponding installation package is as follows.
下载配套版本的SmartDNS安装包对应安装包配套关系如下。
|system |package|Description
|系统 |安装包|说明
|-----|-----|-----
|Standard Linux system (Raspberry Pi)| smartdns.xxxxxxxx.armhf.deb|Support Raspberry Pi Raspbian 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
|标准Linux系统(树莓派)| smartdns.xxxxxxxx.armhf.deb|支持树莓派Raspbian stretchDebian 9系统。
|标准Linux系统(Armbian arm64)| smartdns.xxxxxxxx.arm64.deb|支持ARM64的Debian stretchDebian 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管理统一界面
* 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
* 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
```
Please download it from the Release page: [Download here](https://github.com/pymumu/smartdns/releases)
* 或ssh登录系统后通过如下命令查询软件架构
### Standard Linux system installation (Raspberry Pi, X86_64 system)
* **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. Installation
1. 安装
Download the installation package like `smartdns.xxxxxxxx.armhf.deb` and upload it to the Linux system. Run the following command to install
下载配套安装包`smartdns.xxxxxxxx.armhf.deb`并上传到Linux系统中。 执行如下命令安装
```shell
dpkg -i smartdns.xxxxxxxx.armhf.deb
```
1. Configuration
x86系统下载配套安装包`smartdns.xxxxxxxx.x86-64.tar.gz`, 并上传到Linux系统中。 执行如下命令安装
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
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. Start Service
1. 启动服务
```shell
systemctl enable smartdns
systemctl start smartdns
```
1. Forwarding DNS request to SmartDNS
1. 将DNS请求转发的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.
修改本地路由器的DNS服务器将DNS服务器配置为SmartDNS
* 登录到本地网络的路由器中配置树莓派分配静态IP地址。
* 修改WAN口或者DHCP DNS为树莓派IP地址。
注意:
I. 每款路由器配置方法不尽相同,请百度搜索相关的配置方法。
II.华为等路由器可能不支持配置DNS为本地IP请修改PC端手机端DNS服务器为树莓派IP。
1. Check if the service is configured successfully
1. 检测服务是否配置成功。
Query domain name with `nslookup -querytype=ptr 0.0.0.0`
Check if the `name` item in the command result is displayed as `smartdns` or `hostname`, such as `smartdns`
使用`nslookup -querytype=ptr 0.0.0.0`查询域名
看命令结果中的`name`项目是否显示为`smartdns`或`主机名`,如`smartdns`则表示生效
```shell
pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr 0.0.0.0
@@ -200,36 +269,36 @@ Download the matching version of the SmartDNS installation package. The correspo
--------------
1. Installation
1. 安装
Upload the software to the /root directory of the router with winscp or other tool, and execute the following command to install it.
将软件使用winscp上传到路由器的/root目录执行如下命令安装
```shell
opkg install smartdns.xxxxxxxx.xxxx.ipk
opkg install luci-app-smartdns.xxxxxxxx.xxxx.all.ipk
```
1. Configuration
1. 修改配置
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.
登录openwrt管理页面打开`Services`->`SmartDNS`进行配置。
* 在`Upstream Servers`增加上游DNS服务器配置建议配置多个国内外DNS服务器。
* 在`Domain Address`指定特定域名的IP地址可用于广告屏蔽。
1. Start Service
1. 启用服务
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.
SmartDNS服务生效方法有两种`一种是直接作为主DNS服务``另一种是作为dnsmasq的上游`
默认情况下SmartDNS采用第一种方式。如下两种方式根据需求选择即可。
1. Method 1: SmartDNS as primary DNS Server (default scheme)
1. 启用方法一作为主DNS(默认方案)
* **Enable SmartDNS port 53 port redirection**
* **启用smartdns的53端口重定向**
Log in to the router, click on `Services`->`SmartDNS`->`redirect`, select `Redirect 53 port to SmartDNS` option to enable port 53 forwarding.
登录路由器,点击`Services`->`SmartDNS`->`redirect`,选择`重定向53端口到SmartDNS`启用53端口转发。
* **Check if the service is configured successfully**
* **检测转发服务是否配置成功**
Query domain name with `nslookup -querytype=ptr 0.0.0.0`
See if the `name` item in the command result is displayed as `smartdns` or `hostname`, such as `smartdns`
使用`nslookup -querytype=ptr 0.0.0.0`查询域名
看命令结果中的`name`项目是否显示为`smartdns`或`主机名`,如`smartdns`则表示生效
```shell
pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr 0.0.0.0
@@ -240,28 +309,29 @@ Download the matching version of the SmartDNS installation package. The correspo
0.0.0.0.in-addr.arpa name = smartdns.
```
* **The interface prompts that the redirect failed**
* **界面提示重定向失败**
* Check if iptable, ip6table command is installed correctly.
* The openwrt 15.01 system does not support IPV6 redirection. If the network needs to support IPV6, please change DNSMASQ upstream to smartdns, or change the smartdns port to 53, and disable dnsmasq.
* After LEDE system, please install IPV6 nat forwarding driver. Click `system`->`Software`, click `update lists` to update the software list, install `ip6tables-mod-nat`
* Use the following command to check whether the routing rule takes effect.
* 检查iptableip6table命令是否正确安装。
* openwrt 15.01系统不支持IPV6重定向如网络需要支持IPV6请将DNSMASQ上游改为smartdns或者将smartdns的端口改为53并停用dnsmasq
* LEDE之后系统请安装IPV6nat转发驱动。点击`system`->`Software`,点击`update lists`更新软件列表后,安装`ip6tables-mod-nat`
* 使用如下命令检查路由规则是否生效。
```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
* 如转发功能不正常,请使用方法二:作为DNSMASQ的上游。
* **Forward dnsmasq's request to SmartDNS**
1. 方法二作为DNSMASQ的上游
Log in to the router, click on `Services`->`SmartDNS`->`redirect`, select `Run as dnsmasq upstream server` option to forwarding dnsmasq request to Smartdns.
* **将dnsmasq的请求发送到smartdns**
* **Check if the service is configured successfully**
登录路由器,点击`Services`->`SmartDNS`->`redirect`,选择`作为dnsmasq的上游服务器`设置dnsmasq的上游服务器为smartdns。
* 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`
* **检测上游服务是否配置成功**
* 方法一:使用`nslookup -querytype=ptr 0.0.0.0`查询域名
看命令结果中的`name`项目是否显示为`smartdns`或`主机名`,如`smartdns`则表示生效
```shell
pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr 0.0.0.0
@@ -272,7 +342,7 @@ Download the matching version of the SmartDNS installation package. The correspo
0.0.0.0.in-addr.arpa name = smartdns.
```
* Method 2: Use `nslookup` to query the `www.baidu.com` domain name to see if the IP address of Baidu in the result is `only one. If there are multiple IP addresses returned, it means that it is not valid. Please try to check several domain names.
* 方法二:使用`nslookup`查询`www.baidu.com`域名查看结果中百度的IP地址是否`只有一个`如有多个IP地址返回则表示未生效请多尝试几个域名检查。
```shell
pi@raspberrypi:~ $ nslookup www.baidu.com 192.168.1.1
@@ -285,47 +355,47 @@ Download the matching version of the SmartDNS installation package. The correspo
Address: 14.215.177.38
```
1. Start Service
1. 启动服务
Check the `Enable' in the configuration page to start SmartDNS server.
勾选配置页面中的`Enable(启用)`来启动SmartDNS
1. Note
1. 注意:
* 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.
* 如已经安装chinaDNS,建议将chinaDNS的上游配置为SmartDNS
* SmartDNS默认情况将53端口的请求转发到SmartDNS的本地端口由`Redirect`配置选项控制。
### 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.
说明:梅林固件派生自华硕固件,理论上可以直接使用华硕配套的安装包使用。但目前未经验证,如有问题,请提交issue
1. Prepare
1. 准备
When using this software, you need to confirm whether the router supports U disk and prepare a USB disk.
在使用此软件时需要确认路由器是否支持U盘并准备好U盘一个。
1. Enable SSH login
1. 启用SSH登录
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.
登录管理界面,点击`系统管理`->点击`系统设置`,配置`Enable SSH`为`Lan Only`。
SSH登录用户名密码与管理界面相同。
1. Insstall `Download Master`
1. 下载`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.
在管理界面点击`USB相关应用`->点击`Download Master`下载。
下载完成后,启用`Download Master`,如果不需要下载功能,此处可以卸载`Download Master`但要保证卸载前Download Master是启用的。
1. Install SmartDNS
1. 安装SmartDNS
Upload the software to the router's `/tmp/mnt/sda1` directory using winscp. (or copy the network neighborhood to the sda1 shared directory)
将软件使用winscp上传到路由器的`/tmp/mnt/sda1`目录。或网上邻居复制到sda1共享目录
```shell
ipkg install smartdns.xxxxxxx.mipsbig.ipk
```
1. Restart router
1. 重启路由器生效服务
After the router is started, use `nslookup -querytype=ptr 0.0.0.0` to query the domain name.
See if the `name` item in the command result is displayed as `smartdns` or `hostname`, such as `smartdns`
待路由器启动后,使用`nslookup -querytype=ptr 0.0.0.0`查询域名
看命令结果中的`name`项目是否显示为`smartdns`或`主机名`,如`smartdns`则表示生效
```shell
pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr 0.0.0.0
@@ -336,13 +406,13 @@ Note: Merlin firmware is derived from ASUS firmware and can theoretically be use
0.0.0.0.in-addr.arpa name = smartdns.
```
1. Note
1. 额外说明
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)
上述过程smartdns将安装到U盘根目录采用optware的模式运行。
其目录结构如下: 此处仅列出smartdns相关文件
```shell
USB DISK
U
└── asusware.mipsbig
├── bin
├── etc
@@ -358,29 +428,73 @@ Note: Merlin firmware is derived from ASUS firmware and can theoretically be use
....
```
To modify the configuration, you can use ssh to login to the router and use the vi command to modify it.
如要修改配置可以ssh登录路由器使用vi命令修改
```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.
也可以通过网上邻居修改,网上邻居共享目录`sda1`看不到`asusware.mipsbig`目录,但可以直接在`文件管理器`中输入`asusware.mipsbig\etc\init.d`访问
```shell
\\192.168.1.1\sda1\asusware.mipsbig\etc\init.d
```
### Windows 10 WSL InstallationWSL ubuntu
### optware/entware
--------------
1. Install Windows 10 WSL ubuntu
1. 准备
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
在使用此软件时需要确认路由器是否支持U盘并准备好U盘一个。
1. Install smartdns
1. 安装SmartDNS
download install package `smartdns.xxxxxxxx.x86_64.tar.gz`and unzip to the `D:\` directory, after decompression, the directory is as follows:
将软件使用winscp上传到路由器的`/tmp`目录。
```shell
ipkg install smartdns.xxxxxxx.mipsbig.ipk
```
1. 修改smartdns配置
```shell
vi /opt/etc/smartdns/smartdns.conf
```
另外如需支持IPV6可设置工作模式为`2`将dnsmasq的DNS服务禁用smartdns为主用DNS服务器。将文件`/opt/etc/smartdns/smartdns-opt.conf`,中的`SMARTDNS_WORKMODE`修改为2.
```shell
SMARTDNS_WORKMODE="2"
```
1. 重启路由器生效服务
待路由器启动后,使用`nslookup -querytype=ptr 0.0.0.0`查询域名
看命令结果中的`name`项目是否显示为`smartdns`或`主机名`,如`smartdns`则表示生效
```shell
pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr 0.0.0.0
Server: 192.168.1.1
Address: 192.168.1.1#53
Non-authoritative answer:
0.0.0.0.in-addr.arpa name = smartdns.
```
注意若服务没有自动启动则需要设置optwre/entware自动启动具体方法参考optware/entware的文档。
### Windows 10 WSL安装/WSL ubuntu
--------------
1. 安装Windows 10 WSL ubuntu系统
安装Windows 10 WSL运行环境发行版本选择ubuntu系统。安装步骤请参考[WSL安装说明](https://docs.microsoft.com/en-us/windows/wsl/install-win10)
1. 安装smartdns
下载安装包`smartdns.xxxxxxxx.x86_64.tar.gz`并解压到D盘根目录。解压后目录如下
```shell
D:\SMARTDNS
@@ -395,26 +509,26 @@ Note: Merlin firmware is derived from ASUS firmware and can theoretically be use
```
Double-click `install.bat` in the `D:\smartdns\package\windows` directory for installation. Please enter the password for `WLS ubuntu` when input password.
双击`D:\smartdns\package\windows`目录下的`install.bat`进行安装。要求输入密码时,请输入`WLS ubuntu`的密码。
1. Configuration
1. 修改配置
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.
记事本打开`D:\smartdns\etc\smartdns`目录中的`smartdns.conf`配置文件配置smartdns。具体配置参数参考`配置参数`说明。
一般情况下,只需要增加`server [IP]:port`, `server-tcp [IP]:port`配置项,
尽可能配置多个上游DNS服务器包括国内外的服务器。配置参数请查看`配置参数`章节。
1. Start Service
1. 重新加载配置
Double-click `reload.bat` in the `D:\smartdns\package\windows` directory for reload.
双击`D:\smartdns\package\windows`目录下的`reload.bat`进行安装。要求输入密码时,请输入`WLS ubuntu`的密码。
1. Forwarding DNS request to SmartDNS
1. 将DNS请求转发的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)
将Windows的默认DNS服务器修改为`127.0.0.1`,具体步骤参考[IP配置](https://support.microsoft.com/zh-cn/help/15089/windows-change-tcp-ip-settings)
1. Check if the service is configured successfully
1. 检测服务是否配置成功。
Query domain name with `nslookup -querytype=ptr 0.0.0.0`
Check if the `name` item in the command result is displayed as `smartdns` or `hostname`, such as `smartdns`
使用`nslookup -querytype=ptr 0.0.0.0`查询域名
看命令结果中的`name`项目是否显示为`smartdns`或`主机名`,如`smartdns`则表示生效
```shell
pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr 0.0.0.0
@@ -425,64 +539,158 @@ Note: Merlin firmware is derived from ASUS firmware and can theoretically be use
0.0.0.0.in-addr.arpa name = smartdns.
```
## Configuration parameter
## 配置参数
|parameter|Parameter function|Default value|Value type|Example|
|参数| 功能 |默认值|配置值|例子|
|--|--|--|--|--|
|server-name|DNS name|host name/smartdns|any string like hosname|server-name smartdns
|bind|DNS bind port|[::]:53|IP:PORT|bind 192.168.1.1:53
|bind-tcp|TCP mode DNS bind port|[::]:53|IP:PORT|bind-tcp 192.168.1.1: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|error,warn,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|[ip][:port] [-blacklist-ip][-check-edns], Repeatable, blacklist-ip parameter represents filtering the result of IPs with blacklist-ip configuration.| server 8.8.8.8:53 -blacklist-ip -check-edns
|server-tcp|Upstream TCP DNS server|None|[IP][:port] [-blacklist-ip][-check-edns], Repeatable, blacklist-ip parameter represents filtering the result of IPs with blacklist-ip configuration.| server-tcp 8.8.8.8:53
|server-tls|Upstream TLS DNS server|None|[IP][:port] [-blacklist-ip][-check-edns], Repeatable, blacklist-ip parameter represents filtering the result of IPs with blacklist-ip configuration.| server-tls 8.8.8.8:853
|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
|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
|blacklist-ip|ip blacklist|None|[ip/subnet], RepeatableWhen 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
|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]
|server-name|DNS服务器名称|操作系统主机名/smartdns|符合主机名规格的字符串|server-name smartdns
|bind|DNS监听端口号|[::]:53|可绑定多个端口<br>`IP:PORT`: 服务器IP端口号。<br>`[-group]`: 请求时使用的DNS服务器组。<br>`[-no-rule-addr]`跳过address规则。<br>`[-no-rule-nameserver]`跳过Nameserver规则。<br>`[-no-rule-ipset]`跳过Ipset规则。<br>`[no-rule-soa]`跳过SOA(#)规则.<br>`[no-dualstack-selection]`:停用双栈测速。<br>`[-no-speed-check]`:停用测速。<br>`[-no-cache]`:停止缓存|bind :53
|bind|TCP DNS监听端口号|[::]:53|可绑定多个端口<br>`IP:PORT`: 服务器IP端口号。<br>`[-group]`: 请求时使用的DNS服务器组。<br>`[-no-rule-addr]`跳过address规则。<br>`[-no-rule-nameserver]`跳过Nameserver规则。<br>`[-no-rule-ipset]`跳过Ipset规则。<br>`[no-rule-soa]`跳过SOA(#)规则.<br>`[no-dualstack-selection]`:停用双栈测速。<br>`[-no-speed-check]`:停用测速。<br>`[-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|无|可重复<br>`[ip][:port]`服务器IP端口可选。<br>`[-blacklist-ip]`blacklist-ip参数指定使用blacklist-ip配置IP过滤结果。<br>`[-whitelist-ip]`whitelist-ip参数指定仅接受whitelist-ip中配置IP范围。<br>`[-group [group] ...]`DNS服务器所属组比如office, foreign和nameserver配套使用。<br>`[-exclude-default-group]`将DNS服务器从默认组中排除| server 8.8.8.8:53 -blacklist-ip -group g1
|server-tcp|上游TCP DNS|无|可重复<br>`[ip][:port]`服务器IP端口可选。<br>`[-blacklist-ip]`blacklist-ip参数指定使用blacklist-ip配置IP过滤结果。<br>`[-whitelist-ip]`whitelist-ip参数指定仅接受whitelist-ip中配置IP范围。<br>`[-group [group] ...]`DNS服务器所属组比如office, foreign和nameserver配套使用。<br>`[-exclude-default-group]`将DNS服务器从默认组中排除| server-tcp 8.8.8.8:53
|server-tls|上游TLS DNS|无|可重复<br>`[ip][:port]`服务器IP端口可选。<br>`[-spki-pin [sha256-pin]]`: TLS合法性校验SPKI值base64编码的sha256 SPKI pin值<br>`[-host-name]`TLS SNI名称。<br>`[-tls-host-verify]`: TLS证书主机名校验。<br>`[-blacklist-ip]`blacklist-ip参数指定使用blacklist-ip配置IP过滤结果。<br>`[-whitelist-ip]`whitelist-ip参数指定仅接受whitelist-ip中配置IP范围。<br>`[-group [group] ...]`DNS服务器所属组比如office, foreign和nameserver配套使用。<br>`[-exclude-default-group]`将DNS服务器从默认组中排除| server-tls 8.8.8.8:853
|server-https|上游HTTPS DNS|无|可重复<br>`https://[host][:port]/path`服务器IP端口可选。<br>`[-spki-pin [sha256-pin]]`: TLS合法性校验SPKI值base64编码的sha256 SPKI pin值<br>`[-host-name]`TLS SNI名称<br>`[-http-host]`http协议头主机名。<br>`[-tls-host-verify]`: TLS证书主机名校验。<br>`[-blacklist-ip]`blacklist-ip参数指定使用blacklist-ip配置IP过滤结果。<br>`[-whitelist-ip]`whitelist-ip参数指定仅接受whitelist-ip中配置IP范围。<br>`[-group [group] ...]`DNS服务器所属组比如office, foreign和nameserver配套使用。<br>`[-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] <br>`-`表示忽略 <br>`#`表示返回SOA <br>`4`表示IPV4 <br>`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]
## [Donate](#Donate)
## FAQ
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.
1. SmartDNS和DNSMASQ有什么区别
SMARTDNS在设计上并不是替换DNSMASQ的SMARTDNS主要功能集中在DNS解析增强上增强部分有
* 多上游服务器并发请求,对结果进行测速后,返回最佳结果;
* addressipset域名匹配采用高效算法查询匹配更加快速高效路由器设备依然高效。
* 域名匹配支持忽略特定域名可单独匹配IPv4 IPV6支持多样化定制。
* 针对广告屏蔽功能做增强返回SOA屏蔽广告效果更佳
* IPV4IPV6双栈IP优选机制在双网情况下选择最快的网络通讯。
* 支持最新的TLS, HTTPS协议提供安全的DNS查询能力。
* ECS支持是查询结果更佳准确。
* IP黑名单忽略IP机制使域名查询更佳准确。
* 域名预查询,访问常用网站更加快速。
* 域名TTL可指定使访问更快速。
* 高速缓存机制,使访问更快速。
* 异步日志审计机制在记录信息的同时不影响DNS查询性能。
* 域名组group机制特定域名使用特定上游服务器组查询避免隐私泄漏。
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解析分流
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时间设置为一个合理值延长缓存时间。
建议是超时时间设置在1030分钟避免服务器域名变化时查询到失效域名。
* 开启域名预获取功能
通过`prefetch-domain yes`来启用域名预先获取功能,提高查询命中率。
配合上述ttl超时时间smartdns将在域名ttl即将超时使再次发送查询请求并缓存查询结果供后续使用。频繁访问的域名将会持续缓存。此功能将在空闲时消耗更多的CPU。
## 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 支付宝
![alipay](doc/alipay_donate.jpg)
### Wechat
### Wechat 微信
![wechat](doc/wechat_donate.jpg)
## Statement
## 声明
* `SmartDNS` copyright belongs to Nick Peng (pymumu at gmail.com).
* `SmartDNS` is free software, users can copy and use `SmartDNS` non-commercially.
* It is forbidden to use `SmartDNS` for commercial purposes.
* The use of the software is at the user's own risk and, to the fullest extent permitted by applicable law, damages and risks resulting from the use of this product, including but not limited to direct or indirect personal damage, loss of commercial profit, trade disruption No loss of business information or any other financial loss.
* This software does not collect any user information without the user's consent.
* `SmartDNS`著作权归属Nick Peng (pymumu at gmail.com)
* `SmartDNS`为免费软件,用户可以非商业性地复制和使用`SmartDNS`。
* 禁止将 `SmartDNS` 用于商业用途。
* 使用本软件的风险由用户自行承担,在适用法律允许的最大范围内,对因使用本产品所产生的损害及风险,包括但不限于直接或间接的个人损害、商业赢利的丧失、贸易中断、商业信息的丢失或任何其它经济损失,不承担任何责任。
* 本软件不会未经用户同意收集任何用户信息。
## Additional information
## 说明
Currently the code is not open source, and subsequent open source according to the situation.
目前代码未开源,后续根据情况开源。

691
ReadMe_en.md Executable file
View File

@@ -0,0 +1,691 @@
# 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. [Statement](#Statement)
1. [FAQ](#FAQ)
## Software Show
**Ali DNS**
Use Ali DNS to query Baidu's IP and test the results.
```shell
pi@raspberrypi:~/code/smartdns_build $ nslookup www.baidu.com 223.5.5.5
Server: 223.5.5.5
Address: 223.5.5.5#53
Non-authoritative answer:
www.baidu.com canonical name = www.a.shifen.com.
Name: www.a.shifen.com
Address: 180.97.33.108
Name: www.a.shifen.com
Address: 180.97.33.107
pi@raspberrypi:~/code/smartdns_build $ ping 180.97.33.107 -c 2
PING 180.97.33.107 (180.97.33.107) 56(84) bytes of data.
64 bytes from 180.97.33.107: icmp_seq=1 ttl=55 time=24.3 ms
64 bytes from 180.97.33.107: icmp_seq=2 ttl=55 time=24.2 ms
--- 180.97.33.107 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 24.275/24.327/24.380/0.164 ms
pi@raspberrypi:~/code/smartdns_build $ ping 180.97.33.108 -c 2
PING 180.97.33.108 (180.97.33.108) 56(84) bytes of data.
64 bytes from 180.97.33.108: icmp_seq=1 ttl=55 time=31.1 ms
64 bytes from 180.97.33.108: icmp_seq=2 ttl=55 time=31.0 ms
--- 180.97.33.108 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 31.014/31.094/31.175/0.193 ms
```
**smartdns**
Use SmartDNS to query Baidu IP and test the results.
```shell
pi@raspberrypi:~/code/smartdns_build $ nslookup www.baidu.com
Server: 192.168.1.1
Address: 192.168.1.1#53
Non-authoritative answer:
www.baidu.com canonical name = www.a.shifen.com.
Name: www.a.shifen.com
Address: 14.215.177.39
pi@raspberrypi:~/code/smartdns_build $ ping 14.215.177.39 -c 2
PING 14.215.177.39 (14.215.177.39) 56(84) bytes of data.
64 bytes from 14.215.177.39: icmp_seq=1 ttl=56 time=6.31 ms
64 bytes from 14.215.177.39: icmp_seq=2 ttl=56 time=5.95 ms
--- 14.215.177.39 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 5.954/6.133/6.313/0.195 ms
```
From the comparison, smartdns found the fastest IP address to visit www.baidu.com, so accessing Baidu's DNS is 5 times faster than Ali DNS.
## Features
1. **Multiple upstream DNS servers**
Support configuring multiple upstream DNS servers and query at the same time.the query will not be affected, Even if there is a DNS server exception.
2. **Return the fastest IP address**
Supports finding the fastest access IP address from the IP address list of the domain name and returning it to the client to avoid DNS pollution and improve network access speed.
3. **Support for multiple query protocols**
Support UDP, TCP, TLS, HTTPS queries, and non-53 port queries, effectively avoiding DNS pollution.
4. **Domain IP address specification**
Support configuring IP address of specific domain to achieve the effect of advertising filtering, and avoid malicious websites.
5. **Domain name high performance rule filtering**
Support domain name suffix matching mode, simplify filtering configuration, filter 200,000 recording and take time <1ms.
6. **Linux/Windows multi-platform support**
Support standard Linux system (Raspberry Pi), openwrt system various firmware, ASUS router native firmware. Support Windows 10 WSL (Windows Subsystem for Linux).
7. **Support IPV4, IPV6 dual stack**
Support IPV4, IPV6 network, support query A, AAAA record, dual-stack IP selection, and disale IPV6 AAAA record.
8. **High performance, low resource consumption**
Multi-threaded asynchronous IO mode, cache cache query results.
## Architecture
![Architecture](doc/architecture.png)
1. SmartDNS receives DNS query requests from local network devices, such as PCs and mobile phone query requests.
2. SmartDNS sends query requests to multiple upstream DNS servers, using standard UDP queries, non-standard port UDP queries, and TCP queries.
3. The upstream DNS server returns a list of Server IP addresses corresponding to the domain name. SmartDNS detects the fastest Server IP with local network access.
4. Return the fastest accessed Server IP to the local client.
## Usage
### Download the package
--------------
Download the matching version of the SmartDNS installation package. The corresponding installation package is as follows.
|system |package|Description
|-----|-----|-----
|Standard Linux system (Raspberry Pi)| smartdns.xxxxxxxx.armhf.deb|Support Raspberry Pi Raspbian stretch, Debian 9 system.
|Standard Linux system (Armbian arm64)| smartdns.xxxxxxxx.arm64.deb|Support Armbian debian stretch, Debian 9 system.
|Standard Linux system (x86_64)| smartdns.xxxxxxxx.x86_64.tar.gz|Support for x86_64 Linux systems.
|Windows 10 WSL (Ubuntu)| smartdns.xxxxxxxx.x86_64.tar.gz|Windows 10 WSL ubuntu.
|Standard Linux system (x86)| smartdns.xxxxxxxx.x86.tar.gz|Support for x86_64 systems.
|ASUS native firmware (optware)|smartdns.xxxxxxx.mipsbig.ipk|Systems that support the MIPS big-end architecture, such as RT-AC55U, RT-AC66U.
|ASUS native firmware (optware)|smartdns.xxxxxxx.mipsel.ipk|System that supports the MIPS little endian architecture.
|ASUS native firmware (optware)|smartdns.xxxxxxx.arm.ipk|System that supports the ARM small endian architecture, such as the RT-AC88U, RT-AC68U.
|Padavan|smartdns.xxxxxxx.mipselsf.ipk|padavan Firmware.
|openwrt 15.01|smartdns.xxxxxxxx.ar71xx.ipk|Support AR71XX MIPS system.
|openwrt 15.01|smartdns.xxxxxxxx.ramips_24kec.ipk|Support small-end routers such as MT762X
|openwrt 15.01(Pandora)|smartdns.xxxxxxxx.mipsel_24kec_dsp.ipk|Support for Pandora firmware of MT7620 series
|openwrt 15.01(Pandora)|smartdns.xxxxxxxx.mips_74kc_dsp2.ipk|Support for Pandora firmware of AR71xx series
|openwrt 18.06|smartdns.xxxxxxxx.mips_24kc.ipk|Support AR71XX MIPS system.
|openwrt 18.06|smartdns.xxxxxxxx.mipsel_24kc.ipk|Support small-end routers such as MT726X
|openwrt 18.06|smartdns.xxxxxxxx.x86_64.ipk|Support x86_64 router
|openwrt 18.06|smartdns.xxxxxxxx.i386_pentium4.ipk|Support x86_64 router
|openwrt 18.06|smartdns.xxxxxxxxxxx.arm_cortex-a9.ipk|Router supporting arm A9 core CPU
|openwrt 18.06|smartdns.xxxxxxxxx.arm_cortex-a7_neon-vfpv4.ipk|Router supporting arm A7 core CPU
|openwrt LUCI|luci-app-smartdns.xxxxxxxxx.xxxx.all.ipk|Openwrt management interface
* The openwrt system supports a lot of CPU architecture. The above table does not list all the supported systems. Please check the CPU architecture and download it.
* The merlin Merlin firmware theory is the same as the ASUS firmware, so install the corresponding ipk package according to the hardware type. (Merlin is not verified yet, and has a problem to submit an issue)
* The CPU architecture can be found in the router management interface:
Log in to the router, click `System`->`Software`, click the `Configuration` tab page, and find the corresponding software architecture in the opkg installation source. The download path can be found, as follows, the architecture is ar71xx
```shell
src/gz chaos_calmer_base http://downloads.openwrt.org/chaos_calmer/15.05/ar71xx/generic/packages/base
```
* Or after login to the system, you can query the architecture with the following commands:
* **Openwrt series commands**
```shell
opkg print_architecture
```
* **Optiware series commands**
```shell
ipkg print_architecture
```
* **Dedebian Series Order**
```shell
dpkg -- print-architecture
```
* **for example**
The following query result `arch ar71xx 10` represents the ar71xx series architecture, so select the `smartdns.xxxxxxx.ar71xx.ipk` installation package.
```shell
Root@OpenWrt:# opkg print_architecture
Arch all 1
Arch noarch 1
Arch ar71xx 10
```
* **Please download from the Release page: [Download here](https://github.com/pymu/smartdns/releases)**
```shell
https://github.com/pymumu/smartdns/releases
```
* For the installation procedure, please refer to the following sections.
### Standard Linux system installation/Raspberry Pi, X86_64 system
--------------
1. Installation
Download the installation package like `smartdns.xxxxxxxx.armhf.deb` and upload it to the Linux system. Run the following command to install
```shell
dpkg -i smartdns.xxxxxxxx.armhf.deb
```
For X86-64 system, download the installation package like `smartdns.xxxxxxxx.x86-64.tar.gz` and upload it to the Linux system. Run the following command to install
```shell
tar zxf smartdns.xxxxxxxx.x86-64.tar.gz
cd smartdns
chmod +x ./install
./install -i
```
1. Configuration
After the installation is complete, you can configure the upstream server to smartdns. Refer to the `Configuration Parameters` for specific configuration parameters.
In general, you only need to add `server [IP]:port`, `server-tcp [IP]:port` configuration items.
Configure as many upstream DNS servers as possible, including servers at home and abroad. Please refer to the `Configuration Parameters` section for configuration parameters.
```shell
vi /etc/smartdns/smartdns.conf
```
1. Start Service
```shell
systemctl enable smartdns
systemctl start smartdns
```
1. Forwarding DNS request to SmartDNS
Modify the DNS server of the local router and configure the DNS server as SmartDNS.
* Log in to the router on the local network and configure the Raspberry Pi to assign a static IP address.
* Modify the WAN port or DHCP DNS to the Raspberry Pi IP address.
Note:
I. Each router configuration method is different. Please search Baidu for related configuration methods.
II. some routers may not support configuring custom DNS server. in this case, please modify the PC's, mobile phone's DNS server to the ip of Raspberry Pi.
1. Check if the service is configured successfully
Query domain name with `nslookup -querytype=ptr 0.0.0.0`
Check if the `name` item in the command result is displayed as `smartdns` or `hostname`, such as `smartdns`
```shell
pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr 0.0.0.0
Server: 192.168.1.1
Address: 192.168.1.1#53
Non-authoritative answer:
0.0.0.0.in-addr.arpa name = smartdns.
```
### openwrt/LEDE
--------------
1. Installation
Upload the software to the /root directory of the router with winscp or other tool, and execute the following command to install it.
```shell
opkg install smartdns.xxxxxxxx.xxxx.ipk
opkg install luci-app-smartdns.xxxxxxxx.xxxx.all.ipk
```
1. Configuration
Log in to the openwrt management page and open `Services`->`SmartDNS` to configure SmartDNS.
* Add upstream DNS server configuration to `Upstream Servers`. It is recommended to configure multiple DNS servers at home and abroad.
* Specify the IP address of a specific domain name in `Domain Address`, which can be used for ad blocking.
1. Start Service
There are two ways to use the SmartDNS service, `one is directly as the primary DNS service`, `the other is as the upstream of dnsmasq`.
By default, SmartDNS uses the first method. You can choose according to your needs in the following two ways.
1. Method 1: SmartDNS as primary DNS Server (default scheme)
* **Enable SmartDNS port 53 port redirection**
Log in to the router, click on `Services`->`SmartDNS`->`redirect`, select `Redirect 53 port to SmartDNS` option to enable port 53 forwarding.
* **Check if the service is configured successfully**
Query domain name with `nslookup -querytype=ptr 0.0.0.0`
See if the `name` item in the command result is displayed as `smartdns` or `hostname`, such as `smartdns`
```shell
pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr 0.0.0.0
Server: 192.168.1.1
Address: 192.168.1.1#53
Non-authoritative answer:
0.0.0.0.in-addr.arpa name = smartdns.
```
* **The interface prompts that the redirect failed**
* Check if iptable, ip6table command is installed correctly.
* The openwrt 15.01 system does not support IPV6 redirection. If the network needs to support IPV6, please change DNSMASQ upstream to smartdns, or change the smartdns port to 53, and disable dnsmasq.
* After LEDE system, please install IPV6 nat forwarding driver. Click `system`->`Software`, click `update lists` to update the software list, install `ip6tables-mod-nat`
* Use the following command to check whether the routing rule takes effect.
```shell
iptables -t nat -L PREROUTING | grep REDIRECT
```
* If the forwarding function is abnormal, please use Method 2: As the upstream of DNSMASQ.
1. Method 2: SmartDNS as upstream DNS Server of DNSMASQ
* **Forward dnsmasq's request to SmartDNS**
Log in to the router, click on `Services`->`SmartDNS`->`redirect`, select `Run as dnsmasq upstream server` option to forwarding dnsmasq request to Smartdns.
* **Check if the service is configured successfully**
* Method 1: Query domain name with `nslookup -querytype=ptr 0.0.0.1`
See if the `name` item in the command result is displayed as `smartdns` or `hostname`, such as `smartdns`
```shell
pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr 0.0.0.0
Server: 192.168.1.1
Address: 192.168.1.1#53
Non-authoritative answer:
0.0.0.0.in-addr.arpa name = smartdns.
```
* Method 2: Use `nslookup` to query the `www.baidu.com` domain name to see if the IP address of Baidu in the result is `only one. If there are multiple IP addresses returned, it means that it is not valid. Please try to check several domain names.
```shell
pi@raspberrypi:~ $ nslookup www.baidu.com 192.168.1.1
Server: 192.168.1.1
Address: 192.168.1.1#53
Non-authoritative answer:
www.baidu.com canonical name = www.a.shifen.com.
Name: www.a.shifen.com
Address: 14.215.177.38
```
1. Start Service
Check the `Enable' in the configuration page to start SmartDNS server.
1. Note
* If chinaDNS is already installed, it is recommended to configure the upstream of chinaDNS as SmartDNS.
* SmartDNS defaults to forwarding port 53 requests to the local port of SmartDNS, controlled by the `Redirect` configuration option.
### ASUS router native firmware / Merlin firmware
--------------
Note: Merlin firmware is derived from ASUS firmware and can theoretically be used directly with the ASUS package. However, it is currently unverified. If you have any questions, please submit an issue.
1. Prepare
When using this software, you need to confirm whether the router supports U disk and prepare a USB disk.
1. Enable SSH login
Log in to the management interface, click `System Management`-> Click `System Settings` and configure `Enable SSH` to `Lan Only`.
The SSH login username and password are the same as the management interface.
1. Insstall `Download Master`
In the management interface, click `USB related application`-> click `Download Master` to download.
After the download is complete, enable `Download Master`. If you do not need the download function, you can uninstall `Download Master` here, but make sure that Download Master is enabled before uninstalling.
1. Install SmartDNS
Upload the software to the router's `/tmp/mnt/sda1` directory using winscp. (or copy the network neighborhood to the sda1 shared directory)
```shell
ipkg install smartdns.xxxxxxx.mipsbig.ipk
```
1. Restart router
After the router is started, use `nslookup -querytype=ptr 0.0.0.0` to query the domain name.
See if the `name` item in the command result is displayed as `smartdns` or `hostname`, such as `smartdns`
```shell
pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr 0.0.0.0
Server: 192.168.1.1
Address: 192.168.1.1#53
Non-authoritative answer:
0.0.0.0.in-addr.arpa name = smartdns.
```
1. Note
In the above process, smartdns will be installed to the root directory of the U disk and run in optware mode.
Its directory structure is as follows: (only smartdns related files are listed here)
```shell
USB DISK
└── asusware.mipsbig
├── bin
├── etc
| ├── smartdns
| | └── smartdns.conf
| └── init.d
| └── S50smartdns
├── lib
├── sbin
├── usr
| └── sbin
| └── smartdns
....
```
To modify the configuration, you can use ssh to login to the router and use the vi command to modify it.
```shell
vi /opt/etc/smartdns/smartdns.conf
```
It can also be modified from Network Neighborhood. From the neighbor sharing directory `sda1` you can't see the `asusware.mipsbig` directory, but you can directly enter `asusware.mipsbig\etc\init.d` in `File Manager` to modify it.
```shell
\\192.168.1.1\sda1\asusware.mipsbig\etc\init.d
```
### optware/entware
--------------
1. Prepare
When using this software, you need to confirm whether the router supports USB disk and prepare a USB disk.
1. Install SmartDNS
Upload the software to `/tmp` directory of the router using winscp, and run the flollowing command to install.
```shell
ipkg install smartdns.xxxxxxx.mipsbig.ipk
```
1. Modify the smartdns configuration
```shell
Vi /opt/etc/smartdns/smartdns.conf
```
Note: if you need to support IPV6, you can set the worke-mode to `2`, this will disable the DNS service of dnsmasq, and smartdns run as the primary DNS server. Change `SMARTDNS_WORKMODE` in the file `/opt/etc/smartdns/smartdns-opt.conf` to 2.
```shell
SMARTDNS_WORKMODE="2"
```
1. Restart the router to take effect
After the router is started, use `nslookup -querytype=ptr 0.0.0.0` to query the domain name.
See if the `name` item in the command result is displayed as `smartdns` or `hostname`, such as `smartdns`
```shell
Pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr 0.0.0.0
Server: 192.168.1.1
Address: 192.168.1.1#53
Non-authoritative answer:
0.0.0.0.in-addr.arpa name = smartdns.
```
Note: If the service does not start automatically, you need to set optwre/entware to start automatically. For details, see the optware/entware documentation.
### Windows 10 WSL Installation/WSL ubuntu
--------------
1. Install Windows 10 WSL ubuntu
Install the Windows 10 WSL environment and select Ubuntu as default distribution. Please refer to [WSL installation instructions](https://docs.microsoft.com/en-us/windows/wsl/install-win10) for installation steps
1. Install smartdns
download install package `smartdns.xxxxxxxx.x86_64.tar.gz`and unzip to the `D:\` directory, after decompression, the directory is as follows:
```shell
D:\SMARTDNS
├─etc
│ ├─default
│ ├─init.d
│ └─smartdns
├─package
│ └─windows
├─src
└─systemd
```
Double-click `install.bat` in the `D:\smartdns\package\windows` directory for installation. Please enter the password for `WLS ubuntu` when input password.
1. Configuration
Edit `smartdns.conf` configuration file in `D:\smartdns\etc\smartdns` directory, you can configure the upstream server to smartdns. Refer to the `Configuration Parameters` for specific configuration parameters.
In general, you only need to add `server [IP]:port`, `server-tcp [IP]:port` configuration items.
Configure as many upstream DNS servers as possible, including servers at home and abroad. Please refer to the `Configuration Parameters` section for configuration parameters.
1. Start Service
Double-click `reload.bat` in the `D:\smartdns\package\windows` directory for reload.
1. Forwarding DNS request to SmartDNS
Modify the default DNS server for Windows to `127.0.0.1`, with these steps referred to [IP configuration](https://support.microsoft.com/en-us/help/15089/windows-change-tcp-ip-settings)
1. Check if the service is configured successfully
Query domain name with `nslookup -querytype=ptr 0.0.0.0`
Check if the `name` item in the command result is displayed as `smartdns` or `hostname`, such as `smartdns`
```shell
pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr 0.0.0.0
Server: 192.168.1.1
Address: 192.168.1.1#53
Non-authoritative answer:
0.0.0.0.in-addr.arpa name = smartdns.
```
## Configuration parameter
|parameter|Parameter function|Default value|Value type|Example|
|--|--|--|--|--|
|server-name|DNS name|host name/smartdns|any string like hosname|server-name smartdns
|bind|DNS listening port number|[::]:53|Support binding multiple ports<br>`IP:PORT`: server IP, port number. <br>`[-group]`: The DNS server group used when requesting. <br>`[-no-rule-addr]`: Skip the address rule. <br>`[-no-rule-nameserver]`: Skip the Nameserver rule. <br>`[-no-rule-ipset]`: Skip the Ipset rule. <br>`[-no-rule-soa]`: Skip address SOA(#) rules.<br>`[-no-dualstack-selection]`: Disable dualstack ip selection.<br>`[-no-speed-check]`: Disable speed measurement. <br>`[-no-cache]`: stop caching |bind :53
|bind-tcp|TCP mode DNS listening port number|[::]:53|Support binding multiple ports<br>`IP:PORT`: server IP, port number. <br>`[-group]`: The DNS server group used when requesting. <br>`[-no-rule-addr]`: Skip the address rule. <br>`[-no-rule-nameserver]`: Skip the Nameserver rule. <br>`[-no-rule-ipset]`: Skip the Ipset rule. <br>`[-no-rule-soa]`: Skip address SOA(#) rules.<br>`[-no-dualstack-selection]`: Disable dualstack ip selection.<br>`[-no-speed-check]`: Disable speed measurement. <br>`[-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 <br>`[ip][:port]`: Server IP, port optional. <br>`[-blacklist-ip]`: The "-blacklist-ip" parameter is to filtering IPs which is configured by "blacklist-ip". <br>`[-whitelist-ip]`: whitelist-ip parameter specifies that only the IP range configured in whitelist-ip is accepted. <br>`[-group [group] ...]`: The group to which the DNS server belongs, such as office, foreign, use with nameserver. <br>`[-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 <br>`[ip][:port]`: Server IP, port optional. <br>`[-blacklist-ip]`: The "-blacklist-ip" parameter is to filtering IPs which is configured by "blacklist-ip". <br>`[-whitelist-ip]`: whitelist-ip parameter specifies that only the IP range configured in whitelist-ip is accepted. <br>`[-group [group] ...]`: The group to which the DNS server belongs, such as office, foreign, use with nameserver. <br>`[-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 <br>`[ip][:port]`: Server IP, port optional. <br>`[-spki-pin [sha256-pin]]`: TLS verify SPKI value, a base64 encoded SHA256 hash<br>`[-host-name]`:TLS Server name. <br>`[-tls-host-verify]`: TLS cert hostname to verify.<br>`[-blacklist-ip]`: The "-blacklist-ip" parameter is to filtering IPs which is configured by "blacklist-ip". <br>`[-whitelist-ip]`: whitelist-ip parameter specifies that only the IP range configured in whitelist-ip is accepted. <br>`[-group [group] ...]`: The group to which the DNS server belongs, such as office, foreign, use with nameserver. <br>`[-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 <br>`https://[host][:port]/path`: Server IP, port optional. <br>`[-spki-pin [sha256-pin]]`: TLS verify SPKI value, a base64 encoded SHA256 hash<br>`[-host-name]`:TLS Server name<br>`[-http-host]`http header host. <br>`[-tls-host-verify]`: TLS cert hostname to verify.<br>`[-blacklist-ip]`: The "-blacklist-ip" parameter is to filtering IPs which is configured by "blacklist-ip". <br>`[-whitelist-ip]`: whitelist-ip parameter specifies that only the IP range configured in whitelist-ip is accepted. <br>`[-group [group] ...]`: The group to which the DNS server belongs, such as office, foreign, use with nameserver. <br>`[-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], RepeatableWhen 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], RepeatableWhen 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.
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
```
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.
## [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)
## Statement
* `SmartDNS` copyright belongs to Nick Peng (pymumu at gmail.com).
* `SmartDNS` is free software, users can copy and use `SmartDNS` non-commercially.
* It is forbidden to use `SmartDNS` for commercial purposes.
* The use of the software is at the user's own risk and, to the fullest extent permitted by applicable law, damages and risks resulting from the use of this product, including but not limited to direct or indirect personal damage, loss of commercial profit, trade disruption No loss of business information or any other financial loss.
* This software does not collect any user information without the user's consent.
## Additional information
Currently the code is not open source, and subsequent open source according to the situation.

View File

@@ -1,489 +0,0 @@
# SmartDNS
![SmartDNS](doc/smartdns-banner.png)
SmartDNS是一个运行在本地的DNS服务器SmartDNS接受本地客户端的DNS查询请求从多个上游DNS服务器获取DNS查询结果并将访问速度最快的结果返回给客户端避免DNS污染提高网络访问速度。
同时支持指定特定域名IP地址并高性匹配达到过滤广告的效果。
与dnsmasq的all-servers不同smartdns返回的是访问速度最快的解析结果。
支持树莓派openwrt华硕路由器等设备。
## 软件效果展示
**阿里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服务器异常也不会影响查询。
2. **返回最快IP地址**
支持从域名所属IP地址列表中查找到访问速度最快的IP地址并返回给客户端避免DNS污染提高网络访问速度。
3. **支持多种查询协议**
支持UDPTCPTLS查询以及非53端口查询有效避免DNS污染。
4. **特定域名IP地址指定**
支持指定域名的IP地址达到广告过滤效果避免恶意网站的效果。
5. **域名高性能后缀匹配**
支持域名后缀匹配模式简化过滤配置过滤20万条记录时间<1ms
6. **Linux/Windows多平台支持**
支持标准Linux系统树莓派openwrt系统各种固件华硕路由器原生固件。以及支持Windows 10 WSL (Windows Subsystem for Linux)。
7. **支持IPV4, IPV6双栈**
支持IPV4IPV6网络支持查询A, AAAA记录支持双栈IP速度优化。
8. **高性能,占用资源少**
多线程异步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 stretchDebian 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
```
请在Release页面下载[此处下载](https://github.com/pymumu/smartdns/releases)
### 标准Linux系统安装树莓派, X86_64系统
--------------
1. 安装
下载配套安装包`smartdns.xxxxxxxx.armhf.deb`并上传到Linux系统中。 执行如下命令安装
```shell
dpkg -i smartdns.xxxxxxxx.armhf.deb
```
1. 修改配置
安装完成后可配置smartdns的上游服务器信息。具体配置参数参考`配置参数`说明。
一般情况下,只需要增加`server [IP]:port`, `server-tcp [IP]:port`配置项,
尽可能配置多个上游DNS服务器包括国内外的服务器。配置参数请查看`配置参数`章节。
```shell
vi /etc/smartdns/smartdns.conf
```
1. 启动服务
```shell
systemctl enable smartdns
systemctl start smartdns
```
1. 将DNS请求转发的SmartDNS解析。
修改本地路由器的DNS服务器将DNS服务器配置为SmartDNS。
* 登录到本地网络的路由器中配置树莓派分配静态IP地址。
* 修改WAN口或者DHCP DNS为树莓派IP地址。
注意:
I. 每款路由器配置方法不尽相同,请百度搜索相关的配置方法。
II.华为等路由器可能不支持配置DNS为本地IP请修改PC端手机端DNS服务器为树莓派IP。
1. 检测服务是否配置成功。
使用`nslookup -querytype=ptr 0.0.0.0`查询域名
看命令结果中的`name`项目是否显示为`smartdns`或`主机名`,如`smartdns`则表示生效
```shell
pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr 0.0.0.0
Server: 192.168.1.1
Address: 192.168.1.1#53
Non-authoritative answer:
0.0.0.0.in-addr.arpa name = smartdns.
```
### openwrt/LEDE
--------------
1. 安装
将软件使用winscp上传到路由器的/root目录执行如下命令安装
```shell
opkg install smartdns.xxxxxxxx.xxxx.ipk
opkg install luci-app-smartdns.xxxxxxxx.xxxx.all.ipk
```
1. 修改配置
登录openwrt管理页面打开`Services`->`SmartDNS`进行配置。
* 在`Upstream Servers`增加上游DNS服务器配置建议配置多个国内外DNS服务器。
* 在`Domain Address`指定特定域名的IP地址可用于广告屏蔽。
1. 启用服务
SmartDNS服务生效方法有两种`一种是直接作为主DNS服务``另一种是作为dnsmasq的上游`。
默认情况下SmartDNS采用第一种方式。如下两种方式根据需求选择即可。
1. 启用方法一作为主DNS(默认方案)
* **启用smartdns的53端口重定向**
登录路由器,点击`Services`->`SmartDNS`->`redirect`,选择`重定向53端口到SmartDNS`启用53端口转发。
* **检测转发服务是否配置成功**
使用`nslookup -querytype=ptr 0.0.0.0`查询域名
看命令结果中的`name`项目是否显示为`smartdns`或`主机名`,如`smartdns`则表示生效
```shell
pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr 0.0.0.0
Server: 192.168.1.1
Address: 192.168.1.1#53
Non-authoritative answer:
0.0.0.0.in-addr.arpa name = smartdns.
```
* **界面提示重定向失败**
* 检查iptableip6table命令是否正确安装。
* openwrt 15.01系统不支持IPV6重定向如网络需要支持IPV6请将DNSMASQ上游改为smartdns或者将smartdns的端口改为53并停用dnsmasq。
* LEDE之后系统请安装IPV6的nat转发驱动。点击`system`->`Software`,点击`update lists`更新软件列表后,安装`ip6tables-mod-nat`
* 使用如下命令检查路由规则是否生效。
```shell
iptables -t nat -L PREROUTING | grep REDIRECT
```
* 如转发功能不正常请使用方法二作为DNSMASQ的上游。
1. 方法二作为DNSMASQ的上游
* **将dnsmasq的请求发送到smartdns**
登录路由器,点击`Services`->`SmartDNS`->`redirect`,选择`作为dnsmasq的上游服务器`设置dnsmasq的上游服务器为smartdns。
* **检测上游服务是否配置成功**
* 方法一:使用`nslookup -querytype=ptr 0.0.0.0`查询域名
看命令结果中的`name`项目是否显示为`smartdns`或`主机名`,如`smartdns`则表示生效
```shell
pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr 0.0.0.0
Server: 192.168.1.1
Address: 192.168.1.1#53
Non-authoritative answer:
0.0.0.0.in-addr.arpa name = smartdns.
```
* 方法二:使用`nslookup`查询`www.baidu.com`域名查看结果中百度的IP地址是否`只有一个`如有多个IP地址返回则表示未生效请多尝试几个域名检查。
```shell
pi@raspberrypi:~ $ nslookup www.baidu.com 192.168.1.1
Server: 192.168.1.1
Address: 192.168.1.1#53
Non-authoritative answer:
www.baidu.com canonical name = www.a.shifen.com.
Name: www.a.shifen.com
Address: 14.215.177.38
```
1. 启动服务
勾选配置页面中的`Enable(启用)`来启动SmartDNS
1. 注意:
* 如已经安装chinaDNS建议将chinaDNS的上游配置为SmartDNS。
* SmartDNS默认情况将53端口的请求转发到SmartDNS的本地端口由`Redirect`配置选项控制。
### 华硕路由器原生固件/梅林固件
--------------
说明梅林固件派生自华硕固件理论上可以直接使用华硕配套的安装包使用。但目前未经验证如有问题请提交issue。
1. 准备
在使用此软件时需要确认路由器是否支持U盘并准备好U盘一个。
1. 启用SSH登录
登录管理界面,点击`系统管理`->点击`系统设置`,配置`Enable SSH`为`Lan Only`。
SSH登录用户名密码与管理界面相同。
1. 下载`Download Master`
在管理界面点击`USB相关应用`->点击`Download Master`下载。
下载完成后,启用`Download Master`,如果不需要下载功能,此处可以卸载`Download Master`但要保证卸载前Download Master是启用的。
1. 安装SmartDNS
将软件使用winscp上传到路由器的`/tmp/mnt/sda1`目录。或网上邻居复制到sda1共享目录
```shell
ipkg install smartdns.xxxxxxx.mipsbig.ipk
```
1. 重启路由器生效服务
待路由器启动后,使用`nslookup -querytype=ptr 0.0.0.0`查询域名
看命令结果中的`name`项目是否显示为`smartdns`或`主机名`,如`smartdns`则表示生效
```shell
pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr 0.0.0.0
Server: 192.168.1.1
Address: 192.168.1.1#53
Non-authoritative answer:
0.0.0.0.in-addr.arpa name = smartdns.
```
1. 额外说明
上述过程smartdns将安装到U盘根目录采用optware的模式运行。
其目录结构如下: 此处仅列出smartdns相关文件
```shell
U盘
└── asusware.mipsbig
├── bin
├── etc
| ├── smartdns
| | └── smartdns.conf
| └── init.d
| └── S50smartdns
├── lib
├── sbin
├── usr
| └── sbin
| └── smartdns
....
```
如要修改配置可以ssh登录路由器使用vi命令修改
```shell
vi /opt/etc/smartdns/smartdns.conf
```
也可以通过网上邻居修改,网上邻居共享目录`sda1`看不到`asusware.mipsbig`目录,但可以直接在`文件管理器`中输入`asusware.mipsbig\etc\init.d`访问
```shell
\\192.168.1.1\sda1\asusware.mipsbig\etc\init.d
```
### Windows 10 WSL安装WSL ubuntu
--------------
1. 安装Windows 10 WSL ubuntu系统
安装Windows 10 WSL运行环境发行版本选择ubuntu系统。安装步骤请参考[WSL安装说明](https://docs.microsoft.com/en-us/windows/wsl/install-win10)
1. 安装smartdns
下载安装包`smartdns.xxxxxxxx.x86_64.tar.gz`并解压到D盘根目录。解压后目录如下
```shell
D:\SMARTDNS
├─etc
│ ├─default
│ ├─init.d
│ └─smartdns
├─package
│ └─windows
├─src
└─systemd
```
双击`D:\smartdns\package\windows`目录下的`install.bat`进行安装。要求输入密码时,请输入`WLS ubuntu`的密码。
1. 修改配置
记事本打开`D:\smartdns\etc\smartdns`目录中的`smartdns.conf`配置文件配置smartdns。具体配置参数参考`配置参数`说明。
一般情况下,只需要增加`server [IP]:port`, `server-tcp [IP]:port`配置项,
尽可能配置多个上游DNS服务器包括国内外的服务器。配置参数请查看`配置参数`章节。
1. 重新加载配置
双击`D:\smartdns\package\windows`目录下的`reload.bat`进行安装。要求输入密码时,请输入`WLS ubuntu`的密码。
1. 将DNS请求转发的SmartDNS解析。
将Windows的默认DNS服务器修改为`127.0.0.1`,具体步骤参考[IP配置](https://support.microsoft.com/zh-cn/help/15089/windows-change-tcp-ip-settings)
1. 检测服务是否配置成功。
使用`nslookup -querytype=ptr 0.0.0.0`查询域名
看命令结果中的`name`项目是否显示为`smartdns`或`主机名`,如`smartdns`则表示生效
```shell
pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr 0.0.0.0
Server: 192.168.1.1
Address: 192.168.1.1#53
Non-authoritative answer:
0.0.0.0.in-addr.arpa name = smartdns.
```
## 配置参数
|参数|功能|默认值|配置值|例子|
|--|--|--|--|--|
|server-name|DNS服务器名称|操作系统主机名/smartdns|符合主机名规格的字符串|server-name smartdns
|bind|DNS监听端口号|[::]:53|IP:PORT|bind 192.168.1.1:53
|bind-tcp|TCP模式DNS监听端口号|[::]:53|IP:PORT|bind-tcp 192.168.1.1: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|error,warn,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] [-blacklist-ip][-check-edns]可重复blacklist-ip参数指定使用blacklist-ip配置IP过滤结果| server 8.8.8.8:53 -blacklist-ip -check-edns
|server-tcp|上游TCP DNS|无|[IP][:port] [-blacklist-ip][-check-edns]可重复blacklist-ip参数指定使用blacklist-ip配置IP过滤结果| server-tcp 8.8.8.8:53
|server-tls|上游TLS DNS|无|[IP][:port] [-blacklist-ip][-check-edns]可重复blacklist-ip参数指定使用blacklist-ip配置IP过滤结果| server-tls 8.8.8.8:853
|address|指定域名IP地址|无|address /domain/[ip\|-\|-4\|-6\|#\|#4\|#6], `-`表示忽略, `#`表示返回SOA, `4`表示IPV4, `6`表示IPV6| address /www.example.com/1.2.3.4
|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
|blacklist-ip|黑名单IP地址|无|[ip/subnet],可重复| blacklist-ip 1.2.3.4/16
|force-AAAA-SOA|强制AAAA地址返回SOA|no|[yes\|no]|force-AAAA-SOA yes
|dualstack-ip-selection|双栈IP优选|no|[yes\|no]|dualstack-ip-selection yes
|dualstack-ip-selection-threshold|双栈IP优选阈值|30ms|毫秒|dualstack-ip-selection-threshold [0-1000]
## [Donate](#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`著作权归属Nick Peng (pymumu at gmail.com)。
* `SmartDNS`为免费软件,用户可以非商业性地复制和使用`SmartDNS`。
* 禁止将 `SmartDNS` 用于商业用途。
* 使用本软件的风险由用户自行承担,在适用法律允许的最大范围内,对因使用本产品所产生的损害及风险,包括但不限于直接或间接的个人损害、商业赢利的丧失、贸易中断、商业信息的丢失或任何其它经济损失,不承担任何责任。
* 本软件不会未经用户同意收集任何用户信息。
## 说明
目前代码未开源,后续根据情况开源。

Binary file not shown.

Before

Width:  |  Height:  |  Size: 65 KiB

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

View File

@@ -8,14 +8,27 @@
# conf-file [file]
# conf-file blacklist-ip.conf
# dns server bind ip and port, default dns server port is 53.
# bind [IP]:port, udp server
# bind-tcp [IP]:port, tcp server
# dns server bind ip and port, default dns server port is 53, support binding multi ip and port
# bind udp server
# bind [IP]:[port] [-group [group]] [-no-rule-addr] [-no-rule-nameserver] [-no-rule-ipset] [-no-speed-check] [-no-cache] [-no-rule-soa] [-no-dualstack-selection]
# bind tcp server
# bind-tcp [IP]:[port] [-group [group]] [-no-rule-addr] [-no-rule-nameserver] [-no-rule-ipset] [-no-speed-check] [-no-cache] [-no-rule-soa] [-no-dualstack-selection]
# option:
# -group: set domain request to use the appropriate server group.
# -no-rule-addr: skip address rule.
# -no-rule-nameserver: skip nameserver rule.
# -no-rule-ipset: skip ipset rule.
# -no-speed-check: do not check speed.
# -no-cache: skip cache.
# -no-rule-soa: Skip address SOA(#) rules.
# -no-dualstack-selection: Disable dualstack ip selection.
# example:
# IPV4: :53
# IPV6 [::]:53
# bind-tcp [::]:53
# IPV4:
# bind :53
# bind :6053 -group office -no-speed-check
# IPV6:
# bind [::]:53
# bind-tcp [::]:53
bind [::]:53
# tcp connection idle timeout
@@ -36,9 +49,19 @@ cache-size 512
# List of IPs that will be filtered when nameserver is configured -blacklist-ip parameter
# blacklist-ip [ip/subnet]
# List of IPs that will be accepted when nameserver is configured -whitelist-ip parameter
# whitelist-ip [ip/subnet]
# List of IPs that will be ignored
# ignore-ip [ip/subnet]
# speed check mode
# speed-check-mode [ping|tcp:port|none|,]
# example:
# speed-check-mode ping,tcp:80
# speed-check-mode tcp:443,ping
# speed-check-mode none
# force AAAA query return SOA
# force-AAAA-SOA [yes|no]
@@ -62,7 +85,7 @@ cache-size 512
# rr-ttl-max 86400
# set log level
# log-level: [level], level=error, warn, info, debug
# log-level: [level], level=fatal, error, warn, notice, info, debug
# log-file: file path of log file.
# log-size: size of each log file, support k,m,g
# log-num: number of logs
@@ -72,30 +95,54 @@ log-level info
# log-num 2
# dns audit
# audit-enable: enable or disable audit [yes|no]
# audit-enable [yes|no]: enable or disable audit.
# audit-enable yes
# audit-SOA [yes|no]: enable or disalbe log soa result.
# audit-size size of each audit file, support k,m,g
# audit-file /var/log/smartdns-audit.log
# audit-size 128k
# audit-num 2
# remote udp dns server list
# server [IP]:[PORT] [-blacklist-ip] [-check-edns]
# server [IP]:[PORT] [-blacklist-ip] [-whitelist-ip] [-check-edns] [-group [group] ...] [-exclude-default-group]
# default port is 53
# -blacklist-ip: filter result with blacklist ip
# -whitelist-ip: filter result whth whitelist ip, result in whitelist-ip will be accepted.
# -check-edns: result must exist edns RR, or discard result.
# server 8.8.8.8 -blacklist-ip -check-edns
# -group [group]: set server to group, use with nameserver /domain/group.
# -exclude-default-group: exclude this server from default group.
# server 8.8.8.8 -blacklist-ip -check-edns -group g1 -group g2
# remote tcp dns server list
# server-tcp [IP]:[PORT] [-blacklist-ip]
# server-tcp [IP]:[PORT] [-blacklist-ip] [-whitelist-ip] [-group [group] ...] [-exclude-default-group]
# default port is 53
# server-tcp 8.8.8.8
# remote tls dns server list
# server-tls [IP]:[PORT] [-blacklist-ip] [-check-edns]
# server-tls [IP]:[PORT] [-blacklist-ip] [-whitelist-ip] [-spki-pin [sha256-pin]] [-group [group] ...] [-exclude-default-group]
# -spki-pin: TLS spki pin to verify.
# -tls-host-check: cert hostname to verify.
# -hostname: TLS sni hostname.
# Get SPKI with this command:
# echo | openssl s_client -connect '[ip]:853' | openssl x509 -pubkey -noout | openssl pkey -pubin -outform der | openssl dgst -sha256 -binary | openssl enc -base64
# default port is 853
# server-tls 8.8.8.8
# server-tls 1.0.0.1
# remote https dns server list
# server-https https://[host]:[port]/path [-blacklist-ip] [-whitelist-ip] [-spki-pin [sha256-pin]] [-group [group] ...] [-exclude-default-group]
# -spki-pin: TLS spki pin to verify.
# -tls-host-check: cert hostname to verify.
# -hostname: TLS sni hostname.
# -http-host: http host.
# default port is 443
# server-https https://cloudflare-dns.com/dns-query
# 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
# specific address to domain
# address /domain/[ip|-|-4|-6|#|#4|#6]
# address /www.example.com/1.2.3.4, return ip 1.2.3.4 to client
@@ -108,4 +155,4 @@ log-level info
# 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
# ipset /www.example.com/-, ignore this domain

View File

@@ -39,14 +39,14 @@ build()
cp $SMARTDNS_DIR/src/smartdns $ROOT/usr/sbin
chmod +x $ROOT/usr/sbin/smartdns
dpkg -b $ROOT $OUTPUTDIR/smartdns.$VER.$ARCH.deb
dpkg -b $ROOT $OUTPUTDIR/smartdns.$VER.$FILEARCH.deb
rm -fr $ROOT/
}
main()
{
OPTS=`getopt -o o:h --long arch:,ver: \
OPTS=`getopt -o o:h --long arch:,ver:,filearch: \
-n "" -- "$@"`
if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi
@@ -59,6 +59,9 @@ main()
--arch)
ARCH="$2"
shift 2;;
--filearch)
FILEARCH="$2"
shift 2;;
--ver)
VER="$2"
shift 2;;
@@ -79,6 +82,10 @@ main()
return 1;
fi
if [ -z "$FILEARCH" ]; then
FILEARCH=$ARCH
fi
if [ -z "$OUTPUTDIR" ]; then
OUTPUTDIR=$CURR_DIR;
fi

View File

@@ -11,7 +11,7 @@ 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支持广告过滤。"
msgstr "SmartDNS是一个本地高性能DNS服务器支持返回最快IP支持广告过滤。"
msgid "Custom Settings"
msgstr "自定义设置"
@@ -112,6 +112,60 @@ 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 "上游服务器"
@@ -139,18 +193,54 @@ msgstr "协议类型"
msgid "Domain Address"
msgstr "域名地址"
msgid "TLS Hostname Verify"
msgstr "校验TLS主机名"
msgid "Set TLS hostname to verify."
msgstr "设置校验TLS主机名。"
msgid "TLS SNI name"
msgstr "TLS SNI名称"
msgid "HTTP Host"
msgstr "HTTP主机"
msgid "Sets the server name indication for query."
msgstr "设置查询时使用的服务器SNI名称。"
msgid "Set the HTTP host used for the query. Use this parameter when the host of the URL address is an IP address."
msgstr "设置查询时使用的HTTP主机当URL地址的host是IP地址时使用此参数。"
msgid "Server Group"
msgstr "服务器组"
msgid "DNS Server group belongs to, used with nameserver, such as office, home."
msgsr "DNS服务器所属组 配合nameserver使用例如officehome。"
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"
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服务器配置"

View File

@@ -16,6 +16,7 @@ s = m:section(TypedSection, "smartdns", translate("Settings"), translate("Genera
s.anonymous = true
s:tab("settings", translate("General Settings"))
s:tab("seconddns", translate("Second Server Settings"))
s:tab("custom", translate("Custom Settings"))
---- Eanble
@@ -92,10 +93,92 @@ o.placeholder = "300"
o.default = 300
o.optional = true
---- second dns server
---- rr-ttl-max
o = s:taboption("settings", Value, "rr_ttl_max", translate("Domain TTL Max"), translate("Maximum TTL for all domain result."))
o.rempty = true
---- Eanble
o = s:taboption("seconddns", Flag, "seconddns_enabled", translate("Enable"), translate("Enable or disable second DNS server."))
o.default = o.disabled
o.rempty = false
---- Port
o = s:taboption("seconddns", Value, "seconddns_port", translate("Local Port"), translate("Smartdns local server port"))
o.placeholder = 7053
o.default = 7053
o.datatype = "port"
o.rempty = false
---- Enable TCP server
o = s:taboption("seconddns", Flag, "seconddns_tcp_server", translate("TCP Server"), translate("Enable TCP DNS Server"))
o.rmempty = false
o.default = o.enabled
o.cfgvalue = function(...)
return Flag.cfgvalue(...) or "1"
end
o = s:taboption("seconddns", Flag, "seconddns_no_speed_check", translate("Skip Speed Check"), translate("Do not check speed."))
o.rmempty = false
o.default = o.disabled
o.cfgvalue = function(...)
return Flag.cfgvalue(...) or "0"
end
---- dns server group
o = s:taboption("seconddns", Value, "seconddns_server_group", translate("Server Group"), translate("Query DNS through specific dns server group, such as office, home."))
o.rmempty = true
o.placeholder = "default"
o.datatype = "hostname"
o.rempty = true
---- skip address rules
o = s:taboption("seconddns", Flag, "seconddns_no_rule_addr", translate("Skip Address Rules"), translate("Skip address rules."))
o.rmempty = false
o.default = o.disabled
o.cfgvalue = function(...)
return Flag.cfgvalue(...) or "0"
end
---- skip name server rules
o = s:taboption("seconddns", Flag, "seconddns_no_rule_nameserver", translate("Skip Nameserver Rule"), translate("Skip nameserver rules."))
o.rmempty = false
o.default = o.disabled
o.cfgvalue = function(...)
return Flag.cfgvalue(...) or "0"
end
---- skip ipset rules
o = s:taboption("seconddns", Flag, "seconddns_no_rule_ipset", translate("Skip Ipset Rule"), translate("Skip ipset rules."))
o.rmempty = false
o.default = o.disabled
o.cfgvalue = function(...)
return Flag.cfgvalue(...) or "0"
end
---- skip soa address rule
o = s:taboption("seconddns", Flag, "seconddns_no_rule_soa", translate("Skip SOA Address Rule"), translate("Skip SOA address rules."))
o.rmempty = false
o.default = o.disabled
o.cfgvalue = function(...)
return Flag.cfgvalue(...) or "0"
end
o = s:taboption("seconddns", Flag, "seconddns_no_dualstack_selection", translate("Skip Dualstack Selection"), translate("Skip Sualstack Selection."))
o.rmempty = false
o.default = o.disabled
o.cfgvalue = function(...)
return Flag.cfgvalue(...) or "0"
end
---- skip cache
o = s:taboption("seconddns", Flag, "seconddns_no_cache", translate("Skip Cache"), translate("Skip Cache."))
o.rmempty = false
o.default = o.disabled
o.cfgvalue = function(...)
return Flag.cfgvalue(...) or "0"
end
----- custom settings
custom = s:taboption("custom", Value, "Custom Settings",
translate(""),
@@ -142,13 +225,16 @@ s:option(Value, "name", translate("DNS Server Name"), translate("DNS Server Name
---- IP address
o = s:option(Value, "ip", translate("ip"), translate("DNS Server ip"))
o.datatype = "ipaddr"
o.datatype = "or(ipaddr, string)"
o.rmempty = false
---- port
o = s:option(Value, "port", translate("port"), translate("DNS Server port"))
o.placeholder = "default"
o.datatype = "port"
o.rempty = true
o:depends("type", "udp")
o:depends("type", "tcp")
o:depends("type", "tls")
---- type
o = s:option(ListValue, "type", translate("type"), translate("DNS Server type"))
@@ -156,6 +242,7 @@ o.placeholder = "udp"
o:value("udp", translate("udp"))
o:value("tcp", translate("tcp"))
o:value("tls", translate("tls"))
o:value("https", translate("https"))
o.default = "udp"
o.rempty = false

View File

@@ -13,6 +13,62 @@ s = m:section(NamedSection, sid, "server")
s.anonymous = true
s.addremove = false
---- name
s:option(Value, "name", translate("DNS Server Name"), translate("DNS Server Name"))
---- IP address
o = s:option(Value, "ip", translate("ip"), translate("DNS Server ip"))
o.datatype = "or(host, string)"
o.rmempty = false
---- port
o = s:option(Value, "port", translate("port"), translate("DNS Server port"))
o.placeholder = "default"
o.datatype = "port"
o.rempty = true
o:depends("type", "udp")
o:depends("type", "tcp")
o:depends("type", "tls")
---- type
o = s:option(ListValue, "type", translate("type"), translate("DNS Server type"))
o.placeholder = "udp"
o:value("udp", translate("udp"))
o:value("tcp", translate("tcp"))
o:value("tls", translate("tls"))
o:value("https", translate("https"))
o.default = "udp"
o.rempty = false
---- TLS host verify
o = s:option(Value, "tls_host_verify", translate("TLS Hostname Verify"), translate("Set TLS hostname to verify."))
o.default = ""
o.datatype = "string"
o.rempty = true
o:depends("type", "tls")
o:depends("type", "https")
---- SNI host name
o = s:option(Value, "host_name", translate("TLS SNI name"), translate("Sets the server name indication for query."))
o.default = ""
o.datatype = "hostname"
o.rempty = true
o:depends("type", "tls")
o:depends("type", "https")
---- http host
o = s:option(Value, "http_host", translate("HTTP Host"), translate("Set the HTTP host used for the query. Use this parameter when the host of the URL address is an IP address."))
o.default = ""
o.datatype = "hostname"
o.rempty = true
o:depends("type", "https")
---- server group
o = s:option(Value, "server_group", translate("Server Group"), translate("DNS Server group belongs to, used with nameserver, such as office, home."))
o.rmempty = true
o.placeholder = "default"
o.datatype = "hostname"
o.rempty = true
---- blacklist_ip
o = s:option(Flag, "blacklist_ip", translate("IP Blacklist Filtering"), translate("Filtering IP with blacklist"))
o.rmempty = false
@@ -22,11 +78,27 @@ o.cfgvalue = function(...)
end
---- anti-Answer-Forgery
o = s:option(Flag, "check_edns", translate("Anti Answer Forgery"), translate("anti answer forgery, if DNS does not work properly after enabling, please turn off this feature"))
o.rmempty = false
o.default = o.disabled
o.cfgvalue = function(...)
return Flag.cfgvalue(...) or "0"
end
-- o = s:option(Flag, "check_edns", translate("Anti Answer Forgery"), translate("Anti answer forgery, if DNS does not work properly after enabling, please turn off this feature"))
-- o.rmempty = false
-- o.default = o.disabled
-- o:depends("type", "udp")
-- o.cfgvalue = function(...)
-- return Flag.cfgvalue(...) or "0"
-- end
---- SPKI pin
o = s:option(Value, "spki_pin", translate("TLS SPKI Pinning"), translate("Used to verify the validity of the TLS server, The value is Base64 encoded SPKI fingerprint, leaving blank to indicate that the validity of TLS is not verified."))
o.default = ""
o.datatype = "string"
o.rempty = true
o:depends("type", "tls")
o:depends("type", "https")
---- other args
o = s:option(Value, "addition_arg", translate("Additional Server Args"), translate("Additional Args for upstream dns servers"))
o.default = ""
o.rempty = true
o.optional = true
return m

View File

@@ -61,14 +61,14 @@ build()
cd $ROOT
tar zcf $ROOT/data.tar.gz -C root .
tar zcf $OUTPUTDIR/luci-app-smartdns.$VER.$ARCH.ipk control.tar.gz data.tar.gz debian-binary
tar zcf $OUTPUTDIR/luci-app-smartdns.$VER.$FILEARCH.ipk control.tar.gz data.tar.gz debian-binary
rm -fr $ROOT/
}
main()
{
OPTS=`getopt -o o:h --long arch:,ver: \
OPTS=`getopt -o o:h --long arch:,ver:,filearch: \
-n "" -- "$@"`
if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi
@@ -81,6 +81,9 @@ main()
--arch)
ARCH="$2"
shift 2;;
--filearch)
FILEARCH="$2"
shift 2;;
--ver)
VER="$2"
shift 2;;
@@ -101,6 +104,10 @@ main()
return 1;
fi
if [ -z "$FILEARCH" ]; then
FILEARCH=$ARCH
fi
if [ -z "$OUTPUTDIR" ]; then
OUTPUTDIR=$CURR_DIR;
fi

View File

@@ -8,4 +8,9 @@
# 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
# 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

View File

@@ -5,19 +5,6 @@ chmod +x /etc/init.d/smartdns
mkdir -p /var/etc/smartdns/
[ "${IPKG_NO_SCRIPT}" = "1" ] && exit 0
if [ ! -f "/var/etc/smartdns/address.conf" ]; then
cp /etc/smartdns/address.conf /var/etc/smartdns/address.conf
fi
if [ ! -f "/var/etc/smartdns/blacklist-ip.conf" ]; then
cp /etc/smartdns/blacklist-ip.conf /var/etc/smartdns/blacklist-ip.conf
fi
if [ ! -f "/var/etc/smartdns/custom.conf" ]; then
cp /etc/smartdns/custom.conf /var/etc/smartdns/custom.conf
fi
. ${IPKG_INSTROOT}/lib/functions.sh
default_postinst $0 $@
ret=$?

View File

@@ -1,7 +1,7 @@
# Add custom settings here.
# set log level
# log-level [level], level=error, warn, info, debug
# log-level [level], level=fatal, error, warn, notice, info, debug
# log-level error
# log-size k,m,g

View File

@@ -126,6 +126,30 @@ conf_append()
echo "$1 $2" >> $SMARTDNS_CONF_TMP
}
get_tz()
{
SET_TZ=""
if [ -e "/etc/localtime" ]; then
return
fi
for tzfile in /etc/TZ /var/etc/TZ
do
if [ ! -e "$tzfile" ]; then
continue
fi
tz="`cat $tzfile 2>/dev/null`"
done
if [ -z "$tz" ]; then
return
fi
SET_TZ=$tz
}
load_server()
{
local section="$1"
@@ -136,8 +160,14 @@ load_server()
config_get "port" "$section" "port" ""
config_get "type" "$section" "type" "udp"
config_get "ip" "$section" "ip" ""
config_get "tls_host_verify" "$section" "tls_host_verify" ""
config_get "host_name" "$section" "host_name" ""
config_get "http_host" "$section" "http_host" ""
config_get "server_group" "$section" "server_group" ""
config_get "blacklist_ip" "$section" "blacklist_ip" "0"
config_get "check_edns" "$section" "check_edns" "0"
config_get "spki_pin" "$section" "spki_pin" ""
config_get "addition_arg" "$section" "addition_arg" ""
if [ "$enabled" = "0" ]; then
return
@@ -152,14 +182,32 @@ load_server()
SERVER="server-tcp"
elif [ "$type" = "tls" ]; then
SERVER="server-tls"
elif [ "$type" = "https" ]; then
SERVER="server-https"
fi
if [ ! -z "`echo $ip | grep ":"`" ]; then
if [ ! -z "`echo $ip | grep ":" | grep -v "https://"`" ]; then
if [ -z "`echo $ip | grep "\["`" ]; then
ip="[$ip]"
fi
fi
if [ ! -z "$tls_host_verify" ]; then
ADDITIONAL_ARGS="$ADDITIONAL_ARGS -tls-host-verify $tls_host_verify"
fi
if [ ! -z "$host_name" ]; then
ADDITIONAL_ARGS="$ADDITIONAL_ARGS -host-name $host_name"
fi
if [ ! -z "$http_host" ]; then
ADDITIONAL_ARGS="$ADDITIONAL_ARGS -http-host $http_host"
fi
if [ ! -z "$server_group" ]; then
ADDITIONAL_ARGS="$ADDITIONAL_ARGS -group $server_group"
fi
if [ "$blacklist_ip" != "0" ]; then
ADDITIONAL_ARGS="$ADDITIONAL_ARGS -blacklist-ip"
fi
@@ -168,16 +216,92 @@ load_server()
ADDITIONAL_ARGS="$ADDITIONAL_ARGS -check-edns"
fi
if [ ! -z "$spki_pin" ]; then
ADDITIONAL_ARGS="$ADDITIONAL_ARGS -spki-pin $spki_pin"
fi
if [ ! -z "$port" ]; then
DNS_ADDRESS="$ip:$port"
else
DNS_ADDRESS="$ip"
fi
conf_append "$SERVER" "$DNS_ADDRESS $ADDITIONAL_ARGS"
if [ "$type" = "https" ]; then
DNS_ADDRESS="$ip"
fi
conf_append "$SERVER" "$DNS_ADDRESS $ADDITIONAL_ARGS $addition_arg"
}
load_service() {
load_second_server()
{
local section="$1"
local ARGS=""
local ADDR=""
config_get_bool "seconddns_enabled" "$section" "seconddns_enabled" "0"
if [ "$seconddns_enabled" = "0" ]; then
return
fi
config_get "seconddns_port" "$section" "seconddns_port" "7053"
config_get_bool "seconddns_no_speed_check" "$section" "seconddns_no_speed_check" "0"
if [ "$seconddns_no_speed_check" = "1" ]; then
ARGS="$ARGS -no-speed-check"
fi
config_get "seconddns_server_group" "$section" "seconddns_server_group" ""
if [ ! -z "$seconddns_server_group" ]; then
ARGS="$ARGS -group $seconddns_server_group"
fi
config_get_bool "seconddns_no_rule_addr" "$section" "seconddns_no_rule_addr" "0"
if [ "$seconddns_no_rule_addr" = "1" ]; then
ARGS="$ARGS -no-rule-addr"
fi
config_get_bool "seconddns_no_rule_nameserver" "$section" "seconddns_no_rule_nameserver" "0"
if [ "$seconddns_no_rule_nameserver" = "1" ]; then
ARGS="$ARGS -no-rule-nameserver"
fi
config_get_bool "seconddns_no_rule_ipset" "$section" "seconddns_no_rule_ipset" "0"
if [ "$seconddns_no_rule_ipset" = "1" ]; then
ARGS="$ARGS -no-rule-ipset"
fi
config_get_bool "seconddns_no_rule_soa" "$section" "seconddns_no_rule_soa" "0"
if [ "$seconddns_no_rule_soa" = "1" ]; then
ARGS="$ARGS -no-rule-soa"
fi
config_get_bool "seconddns_no_dualstack_selection" "$section" "seconddns_no_dualstack_selection" "0"
if [ "$seconddns_no_dualstack_selection" = "1" ]; then
ARGS="$ARGS -no-dualstack-selection"
fi
config_get_bool "seconddns_no_cache" "$section" "seconddns_no_cache" "0"
if [ "$seconddns_no_cache" = "1" ]; then
ARGS="$ARGS -no-cache"
fi
config_get "ipv6_server" "$section" "ipv6_server" "1"
if [ "$ipv6_server" = "1" ]; then
ADDR="[::]"
else
ADDR=""
fi
conf_append "bind" "$ADDR:$seconddns_port $ARGS"
config_get_bool "seconddns_tcp_server" "$section" "seconddns_tcp_server" "1"
if [ "$seconddns_tcp_server" = "1" ]; then
conf_append "bind-tcp" "$ADDR:$seconddns_port $ARGS"
fi
}
load_service()
{
local section="$1"
args=""
@@ -296,6 +420,8 @@ load_service() {
set_forward_dnsmasq "$SMARTDNS_PORT"
fi
load_second_server $section
config_foreach load_server "server"
echo "conf-file $ADDRESS_CONF" >> $SMARTDNS_CONF_TMP
@@ -309,6 +435,11 @@ load_service() {
procd_set_param limits core="unlimited"
fi
get_tz
if [ ! -z "$SET_TZ" ]; then
procd_set_param env TZ="$SET_TZ"
fi
procd_set_param command /usr/sbin/smartdns -f -c $SMARTDNS_CONF $args
if [ "$RESPAWN" = "1" ]; then
procd_set_param respawn ${respawn_threshold:-3600} ${respawn_timeout:-5} ${respawn_retry:-5}
@@ -317,12 +448,14 @@ load_service() {
procd_close_instance
}
start_service() {
start_service()
{
config_load "smartdns"
config_foreach load_service "smartdns"
}
reload_service(){
reload_service()
{
stop
start
}

View File

@@ -55,13 +55,13 @@ build()
cd $ROOT
tar zcf $ROOT/data.tar.gz -C root --owner=0 --group=0 .
tar zcf $OUTPUTDIR/smartdns.$VER.$ARCH.ipk --owner=0 --group=0 control.tar.gz data.tar.gz debian-binary
tar zcf $OUTPUTDIR/smartdns.$VER.$FILEARCH.ipk --owner=0 --group=0 control.tar.gz data.tar.gz debian-binary
rm -fr $ROOT/
}
main()
{
OPTS=`getopt -o o:h --long arch:,ver: \
OPTS=`getopt -o o:h --long arch:,ver:,filearch: \
-n "" -- "$@"`
if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi
@@ -74,6 +74,9 @@ main()
--arch)
ARCH="$2"
shift 2;;
--filearch)
FILEARCH="$2"
shift 2;;
--ver)
VER="$2"
shift 2;;
@@ -94,6 +97,10 @@ main()
return 1;
fi
if [ -z "$FILEARCH" ]; then
FILEARCH=$ARCH
fi
if [ -z "$OUTPUTDIR" ]; then
OUTPUTDIR=$CURR_DIR;
fi

View File

@@ -2,8 +2,8 @@
SMARTDNS_BIN=/opt/usr/sbin/smartdns
SMARTDNS_CONF=/opt/etc/smartdns/smartdns.conf
DNSMASQ_CONF=/etc/dnsmasq.conf
SMARTDNS_PID="/var/run/smartdns.pid"
DNSMASQ_CONF="/etc/dnsmasq.conf /var/etc/dnsmasq.conf /etc/storage/dnsmasq/dnsmasq.conf"
SMARTDNS_PID=/var/run/smartdns.pid
SMARTDNS_PORT=535
SMARTDNS_OPT=/opt/etc/smartdns/smartdns-opt.conf
# workmode
@@ -50,13 +50,44 @@ clear_iptable()
}
restart_dnsmasq()
get_dnsmasq_cmd()
{
CMD="`ps | grep " dnsmasq" | grep -v grep`"
if [ -z "$CMD" ]; then
CMD="`ps ax | grep dnsmasq | grep -v grep`"
CMD="`ps | grep -e '[a-zA-Z]\{0,2\} \{1,\}dnsmasq' | grep -v grep 2>/dev/null`"
if [ ! -z "$CMD" ]; then
return
fi
CMD="`ps | grep '/usr/sbin/dnsmasq' | grep -v grep 2>/dev/null`"
if [ ! -z "$CMD" ]; then
return
fi
CMD="`ps | grep 'dnsmasq' | grep -v grep 2>/dev/null`"
if [ ! -z "$CMD" ]; then
return
fi
CMD="`ps ax | grep -e '[a-zA-Z]\{0,2\} \{1,\}dnsmasq' | grep -v grep 2>/dev/null`"
if [ ! -z "$CMD" ]; then
return
fi
CMD="`ps ax | grep /usr/sbin/dnsmasq | grep -v grep 2>/dev/null`"
if [ ! -z "$CMD" ]; then
return
fi
CMD="`ps ax | grep 'dnsmasq' | grep -v grep 2>/dev/null`"
if [ ! -z "$CMD" ]; then
return
fi
}
restart_dnsmasq()
{
local CMD=""
get_dnsmasq_cmd
if [ -z "$CMD" ]; then
echo "cannot find dnsmasq"
return 1
@@ -77,6 +108,7 @@ restart_dnsmasq()
get_server_ip()
{
CONF_FILE=$1
IPS="`ifconfig | grep "inet addr" | grep -v ":127" | grep "Bcast" | awk '{print $2}' | awk -F: '{print $2}'`"
LOCAL_SERVER_IP=""
for IP in $IPS
@@ -85,9 +117,9 @@ get_server_ip()
while [ $N -gt 0 ]
do
ADDR=`echo $IP | awk -F. "{for(i=1;i<=$N;i++)printf \\$i\".\"}"`
grep "dhcp-range=" $DNSMASQ_CONF | grep $ADDR >/dev/null 2>&1
grep "dhcp-range=" $CONF_FILE | grep $ADDR >/dev/null 2>&1
if [ $? -eq 0 ]; then
SERVER_TAG="`grep "^dhcp-range *=" $DNSMASQ_CONF | grep $ADDR | awk -F= '{print $2}' | awk -F, '{print $1}'`"
SERVER_TAG="`grep "^dhcp-range *=" $CONF_FILE | grep $ADDR | awk -F= '{print $2}' | awk -F, '{print $1}'`"
LOCAL_SERVER_IP="$IP"
return 0
fi
@@ -98,53 +130,82 @@ get_server_ip()
return 1
}
set_dnsmasq()
set_dnsmasq_conf()
{
local RESTART_DNSMASQ=0
local LOCAL_SERVER_IP=""
local SERVER_TAG=""
get_server_ip
local CONF_FILE=$1
get_server_ip $CONF_FILE
if [ "$LOCAL_SERVER_IP" ] && [ "$SERVER_TAG" ]; then
grep "dhcp-option *=" $DNSMASQ_CONF | grep "$SERVER_TAG,6,$LOCAL_SERVER_IP" > /dev/null 2>&1
grep "dhcp-option *=" $CONF_FILE | grep "$SERVER_TAG,6,$LOCAL_SERVER_IP" > /dev/null 2>&1
if [ $? -ne 0 ]; then
sed -i "/^dhcp-option *=$SERVER_TAG,6,/d" $DNSMASQ_CONF
echo "dhcp-option=$SERVER_TAG,6,$LOCAL_SERVER_IP" >> $DNSMASQ_CONF
sed -i "/^dhcp-option *=$SERVER_TAG,6,/d" $CONF_FILE
echo "dhcp-option=$SERVER_TAG,6,$LOCAL_SERVER_IP" >> $CONF_FILE
RESTART_DNSMASQ=1
fi
fi
grep "^port *=0" $DNSMASQ_CONF > /dev/null 2>&1
grep "^port *=0" $CONF_FILE > /dev/null 2>&1
if [ $? -ne 0 ]; then
sed -i "/^port *=/d" $DNSMASQ_CONF
echo "port=0" >> $DNSMASQ_CONF
sed -i "/^port *=/d" $CONF_FILE
echo "port=0" >> $CONF_FILE
RESTART_DNSMASQ=1
fi
}
set_dnsmasq()
{
local RESTART_DNSMASQ=0
for conf in $DNSMASQ_CONF
do
if [ ! -e "$conf" ]; then
continue
fi
set_dnsmasq_conf $conf
done
if [ $RESTART_DNSMASQ -ne 0 ]; then
restart_dnsmasq
fi
}
clear_dnsmasq_conf()
{
local LOCAL_SERVER_IP=""
local SERVER_TAG=""
local CONF_FILE=$1
get_server_ip $CONF_FILE
if [ "$LOCAL_SERVER_IP" ] && [ "$SERVER_TAG" ]; then
grep "dhcp-option *=" $CONF_FILE | grep "$SERVER_TAG,6,$LOCAL_SERVER_IP" > /dev/null 2>&1
if [ $? -eq 0 ]; then
sed -i "/^dhcp-option *=$SERVER_TAG,6,/d" $CONF_FILE
RESTART_DNSMASQ=1
fi
fi
grep "^port *=" $CONF_FILE > /dev/null 2>&1
if [ $? -eq 0 ]; then
sed -i "/^port *=/d" $CONF_FILE
RESTART_DNSMASQ=1
fi
}
clear_dnsmasq()
{
local RESTART_DNSMASQ=0
local LOCAL_SERVER_IP=""
local SERVER_TAG=""
get_server_ip
if [ "$LOCAL_SERVER_IP" ] && [ "$SERVER_TAG" ]; then
grep "dhcp-option *=" $DNSMASQ_CONF | grep "$SERVER_TAG,6,$LOCAL_SERVER_IP" > /dev/null 2>&1
if [ $? -eq 0 ]; then
sed -i "/^dhcp-option *=$SERVER_TAG,6,/d" $DNSMASQ_CONF
RESTART_DNSMASQ=1
fi
fi
grep "^port *=" $DNSMASQ_CONF > /dev/null 2>&1
if [ $? -eq 0 ]; then
sed -i "/^port *=/d" $DNSMASQ_CONF
RESTART_DNSMASQ=1
fi
for conf in $DNSMASQ_CONF
do
if [ ! -e "$conf" ]; then
continue
fi
clear_dnsmasq_conf $conf
done
if [ $RESTART_DNSMASQ -ne 0 ]; then
restart_dnsmasq
@@ -157,10 +218,10 @@ set_smartdns_port()
return 0
elif [ "$SMARTDNS_WORKMODE" = "1" ]; then
sed -i "s/^\(bind .*\):53 *\(.*\)\$/\1:$SMARTDNS_PORT \2/g" $SMARTDNS_CONF
sed -i "s/^\(bind-tcp .*\):53 *\(.*\)\$/\1:$SMARTDNS_PORT \2/g" $SMARTDNS_CONF
sed -i "s/^\(bind-tcp .*\):53 *\(.*\)\$/\1:$SMARTDNS_PORT \2/g" $SMARTDNS_CONF
elif [ "$SMARTDNS_WORKMODE" = "2" ]; then
sed -i "s/^\(bind .*\):$SMARTDNS_PORT *\(.*\)\$/\1:53 \2/g" $SMARTDNS_CONF
sed -i "s/^\(bind-tcp .*\):$SMARTDNS_PORT *\(.*\)\$/\1:53 \2/g" $SMARTDNS_CONF
sed -i "s/^\(bind-tcp .*\):$SMARTDNS_PORT *\(.*\)\$/\1:53 \2/g" $SMARTDNS_CONF
else
return 1
fi
@@ -198,6 +259,28 @@ clear_rule()
fi
}
get_tz()
{
if [ -e "/etc/localtime" ]; then
return
fi
for tzfile in /etc/TZ /var/etc/TZ
do
if [ ! -e "$tzfile" ]; then
continue
fi
tz="`cat $tzfile 2>/dev/null`"
done
if [ -z "$tz" ]; then
return
fi
export TZ=$tz
}
case "$1" in
start)
set_rule
@@ -206,6 +289,7 @@ case "$1" in
fi
set_smartdns_port
get_tz
$SMARTDNS_BIN -c $SMARTDNS_CONF -p $SMARTDNS_PID
if [ $? -ne 0 ]; then
clear_rule

View File

@@ -44,13 +44,13 @@ build()
cd $ROOT
tar zcf data.tar.gz --owner=0 --group=0 opt
tar zcf $OUTPUTDIR/smartdns.$VER.$ARCH.ipk --owner=0 --group=0 control.tar.gz data.tar.gz debian-binary
tar zcf $OUTPUTDIR/smartdns.$VER.$FILEARCH.ipk --owner=0 --group=0 control.tar.gz data.tar.gz debian-binary
rm -fr $ROOT/
}
main()
{
OPTS=`getopt -o o:h --long arch:,ver: \
OPTS=`getopt -o o:h --long arch:,ver:,filearch: \
-n "" -- "$@"`
if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi
@@ -63,6 +63,9 @@ main()
--arch)
ARCH="$2"
shift 2;;
--filearch)
FILEARCH="$2"
shift 2;;
--ver)
VER="$2"
shift 2;;
@@ -83,6 +86,10 @@ main()
return 1;
fi
if [ -z "$FILEARCH" ]; then
FILEARCH=$ARCH
fi
if [ -z "$OUTPUTDIR" ]; then
OUTPUTDIR=$CURR_DIR;
fi

View File

@@ -1,13 +1,20 @@
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 $(OBJS_LIB)
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 +=-O2 -g -Wall -Wstrict-prototypes -fno-omit-frame-pointer -Wstrict-aliasing
CFLAGS +=-Iinclude
CFLAGS += -DBASE_FILE_NAME=\"$(notdir $<)\"
ifdef VER
CFLAGS += -DSMARTDNS_VERION=\"$(VER)\"
endif
CXXFLAGS=-O2 -g -Wall -std=c++11
CXXFLAGS +=-Iinclude
LDFLAGS += -lpthread -lssl -lcrypto
ifeq ($(STATIC), yes)
LDFLAGS += -lssl -lcrypto -Wl,--whole-archive -lpthread -Wl,--no-whole-archive -ldl -static
else
LDFLAGS += -lssl -lcrypto -lpthread
endif
.PHONY: all

367
src/dns.c
View File

@@ -19,12 +19,14 @@
#define _GNU_SOURCE
#include "dns.h"
#include "tlog.h"
#include "stringutil.h"
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <arpa/inet.h>
#define QR_MASK 0x8000
#define OPCODE_MASK 0x7800
@@ -35,10 +37,13 @@
#define RCODE_MASK 0x000F
#define DNS_RR_END (0XFFFF)
#define UNUSED(expr) do { (void)(expr); } while (0)
#define UNUSED(expr) \
do { \
(void)(expr); \
} while (0)
/* read short and move pointer */
short dns_read_short(unsigned char **buffer)
static short _dns_read_short(unsigned char **buffer)
{
unsigned short value;
@@ -48,14 +53,14 @@ short dns_read_short(unsigned char **buffer)
}
/* write char and move pointer */
void dns_write_char(unsigned char **buffer, unsigned char value)
static __attribute__((unused)) void _dns_write_char(unsigned char **buffer, unsigned char value)
{
**buffer = value;
*buffer += 1;
}
/* read char and move pointer */
unsigned char dns_read_char(unsigned char **buffer)
static unsigned char _dns_read_char(unsigned char **buffer)
{
unsigned char value = **buffer;
*buffer += 1;
@@ -63,7 +68,7 @@ unsigned char dns_read_char(unsigned char **buffer)
}
/* write short and move pointer */
void dns_write_short(unsigned char **buffer, unsigned short value)
static void _dns_write_short(unsigned char **buffer, unsigned short value)
{
value = htons(value);
*((unsigned short *)(*buffer)) = value;
@@ -71,7 +76,7 @@ void dns_write_short(unsigned char **buffer, unsigned short value)
}
/* write int and move pointer */
void dns_write_int(unsigned char **buffer, unsigned int value)
static void _dns_write_int(unsigned char **buffer, unsigned int value)
{
value = htonl(value);
*((unsigned int *)(*buffer)) = value;
@@ -79,7 +84,7 @@ void dns_write_int(unsigned char **buffer, unsigned int value)
}
/* read int and move pointer */
unsigned int dns_read_int(unsigned char **buffer)
static unsigned int _dns_read_int(unsigned char **buffer)
{
unsigned int value;
@@ -113,6 +118,10 @@ struct dns_rrs *dns_get_rrs_start(struct dns_packet *packet, dns_rr_type type, i
*count = head->nrcount;
start = packet->additional;
break;
case DNS_RRS_OPT:
*count = packet->optcount;
start = packet->optional;
break;
default:
return NULL;
break;
@@ -138,7 +147,7 @@ struct dns_rrs *dns_get_rrs_next(struct dns_packet *packet, struct dns_rrs *rrs)
}
/* iterator add rrs begin */
unsigned char *_dns_add_rrs_start(struct dns_packet *packet, int *maxlen)
static unsigned char *_dns_add_rrs_start(struct dns_packet *packet, int *maxlen)
{
struct dns_rrs *rrs;
unsigned char *end = packet->data + packet->len;
@@ -153,7 +162,7 @@ unsigned char *_dns_add_rrs_start(struct dns_packet *packet, int *maxlen)
}
/* iterator add rrs end */
int dns_rr_add_end(struct dns_packet *packet, int type, dns_type_t rtype, int len)
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;
@@ -187,6 +196,7 @@ int dns_rr_add_end(struct dns_packet *packet, int type, dns_type_t rtype, int le
case DNS_RRS_OPT:
count = &packet->optcount;
start = &packet->optional;
break;
default:
return -1;
break;
@@ -220,7 +230,7 @@ static inline int _dns_data_left_len(struct dns_data_context *data_context)
return data_context->maxsize - (data_context->ptr - data_context->data);
}
int _dns_add_qr_head(struct dns_data_context *data_context, char *domain, int qtype, int qclass)
static int _dns_add_qr_head(struct dns_data_context *data_context, char *domain, int qtype, int qclass)
{
/* question head */
/* |domain |
@@ -252,9 +262,10 @@ int _dns_add_qr_head(struct dns_data_context *data_context, char *domain, int qt
return 0;
}
int _dns_get_qr_head(struct dns_data_context *data_context, char *domain, int maxsize, int *qtype, int *qclass)
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 |
@@ -268,6 +279,7 @@ int _dns_get_qr_head(struct dns_data_context *data_context, char *domain, int ma
domain++;
data_context->ptr++;
i++;
is_read_all = 1;
break;
}
*domain = *data_context->ptr;
@@ -276,6 +288,9 @@ int _dns_get_qr_head(struct dns_data_context *data_context, char *domain, int ma
}
*domain = '\0';
if (is_read_all == 0) {
return -1;
}
if (_dns_data_left_len(data_context) < 4) {
return -1;
@@ -290,7 +305,7 @@ int _dns_get_qr_head(struct dns_data_context *data_context, char *domain, int ma
return 0;
}
int _dns_add_rr_head(struct dns_data_context *data_context, char *domain, int qtype, int qclass, int ttl, int rr_len)
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;
@@ -318,7 +333,7 @@ int _dns_add_rr_head(struct dns_data_context *data_context, char *domain, int qt
return 0;
}
int _dns_get_rr_head(struct dns_data_context *data_context, char *domain, int maxsize, int *qtype, int *qclass, int *ttl, int *rr_len)
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;
@@ -343,7 +358,7 @@ int _dns_get_rr_head(struct dns_data_context *data_context, char *domain, int ma
return len;
}
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)
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;
@@ -379,10 +394,10 @@ int dns_add_RAW(struct dns_packet *packet, dns_rr_type rrtype, dns_type_t rtype,
data_context.ptr += raw_len;
len = data_context.ptr - data_context.data;
return dns_rr_add_end(packet, rrtype, rtype, len);
return _dns_rr_add_end(packet, rrtype, rtype, len);
}
int dns_get_RAW(struct dns_rrs *rrs, char *domain, int maxsize, int *ttl, void *raw, int *raw_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;
@@ -420,10 +435,33 @@ int dns_get_RAW(struct dns_rrs *rrs, char *domain, int maxsize, int *ttl, void *
return 0;
}
int dns_add_OPT(struct dns_packet *packet, dns_rr_type type, unsigned short opt_code, unsigned short opt_len, struct dns_opt *opt)
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;
@@ -431,15 +469,15 @@ int dns_add_OPT(struct dns_packet *packet, dns_rr_type type, unsigned short opt_
int ttl = 0;
/*
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
0: | OPTION-CODE |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
2: | OPTION-LENGTH |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
4: | |
/ OPTION-DATA /
/ /
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
/ OPTION-DATA /
/ /
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
*/
unsigned char *data = _dns_add_rrs_start(packet, &maxlen);
if (data == NULL) {
@@ -467,10 +505,10 @@ int dns_add_OPT(struct dns_packet *packet, dns_rr_type type, unsigned short opt_
data_context.ptr += total_len;
len = data_context.ptr - data_context.data;
return dns_rr_add_end(packet, type, DNS_T_OPT, len);
return _dns_rr_add_end(packet, type, DNS_T_OPT, len);
}
int dns_get_OPT(struct dns_rrs *rrs, unsigned short *opt_code, unsigned short *opt_len, struct dns_opt *opt, int *opt_maxlen)
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
@@ -508,63 +546,62 @@ int dns_get_OPT(struct dns_rrs *rrs, unsigned short *opt_code, unsigned short *o
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);
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);
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);
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);
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);
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);
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);
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);
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);
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);
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)
@@ -581,9 +618,9 @@ int dns_add_SOA(struct dns_packet *packet, dns_rr_type type, char *domain, int t
unsigned char data[sizeof(*soa)];
unsigned char *ptr = data;
int len = 0;
strncpy((char *)ptr, soa->mname, DNS_MAX_CNAME_LEN - 1);
safe_strncpy((char *)ptr, soa->mname, DNS_MAX_CNAME_LEN);
ptr += strnlen(soa->mname, DNS_MAX_CNAME_LEN - 1) + 1;
strncpy((char *)ptr, soa->rname, DNS_MAX_CNAME_LEN - 1);
safe_strncpy((char *)ptr, soa->rname, DNS_MAX_CNAME_LEN);
ptr += strnlen(soa->rname, DNS_MAX_CNAME_LEN - 1) + 1;
*((unsigned int *)ptr) = soa->serial;
ptr += 4;
@@ -597,7 +634,7 @@ int dns_add_SOA(struct dns_packet *packet, dns_rr_type type, char *domain, int t
ptr += 4;
len = ptr - data;
return dns_add_RAW(packet, type, DNS_T_SOA, domain, ttl, data, len);
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)
@@ -615,16 +652,16 @@ int dns_get_SOA(struct dns_rrs *rrs, char *domain, int maxsize, int *ttl, struct
*| expire |
*| minimum |
*/
if (dns_get_RAW(rrs, domain, maxsize, ttl, data, &len) != 0) {
if (_dns_get_RAW(rrs, domain, maxsize, ttl, data, &len) != 0) {
return -1;
}
strncpy(soa->mname, (char *)ptr, DNS_MAX_CNAME_LEN - 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;
}
strncpy(soa->rname, (char *)ptr, DNS_MAX_CNAME_LEN - 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;
@@ -673,7 +710,7 @@ int dns_add_OPT_ECS(struct dns_packet *packet, struct dns_opt_ecs *ecs)
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);
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)
@@ -683,7 +720,7 @@ int dns_get_OPT_ECS(struct dns_rrs *rrs, unsigned short *opt_code, unsigned shor
int len = DNS_MAX_OPT_LEN;
int ttl = 0;
if (dns_get_RAW(rrs, 0, 0, &ttl, opt_data, &len) != 0) {
if (_dns_get_RAW(rrs, NULL, 0, &ttl, opt_data, &len) != 0) {
return -1;
}
@@ -700,6 +737,54 @@ int dns_get_OPT_ECS(struct dns_rrs *rrs, unsigned short *opt_code, unsigned shor
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)|
@@ -726,7 +811,7 @@ int dns_add_domain(struct dns_packet *packet, char *domain, int qtype, int qclas
len = data_context.ptr - data_context.data;
return dns_rr_add_end(packet, DNS_RRS_QD, DNS_T_CNAME, len);
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)
@@ -777,8 +862,8 @@ static int _dns_decode_head(struct dns_context *context)
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
*/
head->id = dns_read_short(&context->ptr);
fields = dns_read_short(&context->ptr);
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;
@@ -786,10 +871,10 @@ static int _dns_decode_head(struct dns_context *context)
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);
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;
}
@@ -803,7 +888,7 @@ static int _dns_encode_head(struct dns_context *context)
return -1;
}
dns_write_short(&context->ptr, head->id);
_dns_write_short(&context->ptr, head->id);
int fields = 0;
fields |= (head->qr << 15) & QR_MASK;
@@ -813,12 +898,12 @@ static int _dns_encode_head(struct dns_context *context)
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, 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);
_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;
}
@@ -829,10 +914,10 @@ static int _dns_encode_head_count(struct dns_context *context)
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);
_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;
}
@@ -840,7 +925,7 @@ static int _dns_decode_domain(struct dns_context *context, char *output, int siz
{
int output_len = 0;
int copy_len = 0;
int len = *(context->ptr);
int len = 0;
unsigned char *ptr = context->ptr;
int is_compressed = 0;
int ptr_jump = 0;
@@ -850,7 +935,7 @@ static int _dns_decode_domain(struct dns_context *context, char *output, int siz
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;
@@ -870,13 +955,13 @@ static int _dns_decode_domain(struct dns_context *context, char *output, int siz
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
*/
/* read offset */
len = dns_read_short(&ptr) & 0x3FFF;
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 enouth %u:%ld, %p, %p", context->maxsize, (long)(ptr - context->data), context->ptr, context->data);
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;
@@ -894,7 +979,7 @@ static int _dns_decode_domain(struct dns_context *context, char *output, int siz
}
if (ptr > context->data + context->maxsize) {
tlog(TLOG_DEBUG, "length is not enouth %u:%ld, %p, %p", context->maxsize, (long)(ptr - context->data), context->ptr, context->data);
tlog(TLOG_DEBUG, "length is not enough %u:%ld, %p, %p", context->maxsize, (long)(ptr - context->data), context->ptr, context->data);
return -1;
}
@@ -903,7 +988,7 @@ static int _dns_decode_domain(struct dns_context *context, char *output, int siz
/* 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 enouth %u:%ld, %p, %p", context->maxsize, (long)(ptr - context->data), context->ptr, context->data);
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);
@@ -957,7 +1042,7 @@ static int _dns_decode_qr_head(struct dns_context *context, char *domain, int do
{
int ret = 0;
/*
0 1 2 3 4 5 6 7 8 9 A B C D E F
0 1 2 3 4 5 6 7 8 9 A B C D E F
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| |
/ /
@@ -980,8 +1065,8 @@ static int _dns_decode_qr_head(struct dns_context *context, char *domain, int do
return -1;
}
*qtype = dns_read_short(&context->ptr);
*qclass = dns_read_short(&context->ptr);
*qtype = _dns_read_short(&context->ptr);
*qclass = _dns_read_short(&context->ptr);
return 0;
}
@@ -998,8 +1083,8 @@ static int _dns_encode_qr_head(struct dns_context *context, char *domain, int qt
return -1;
}
dns_write_short(&context->ptr, qtype);
dns_write_short(&context->ptr, qclass);
_dns_write_short(&context->ptr, qtype);
_dns_write_short(&context->ptr, qclass);
return 0;
}
@@ -1019,8 +1104,8 @@ static int _dns_decode_rr_head(struct dns_context *context, char *domain, int do
return -1;
}
*ttl = dns_read_int(&context->ptr);
*rr_len = dns_read_short(&context->ptr);
*ttl = _dns_read_int(&context->ptr);
*rr_len = _dns_read_short(&context->ptr);
return 0;
}
@@ -1037,8 +1122,8 @@ static int _dns_encode_rr_head(struct dns_context *context, char *domain, int qt
return -1;
}
dns_write_int(&context->ptr, ttl);
dns_write_short(&context->ptr, rr_len);
_dns_write_int(&context->ptr, ttl);
_dns_write_short(&context->ptr, rr_len);
return 0;
}
@@ -1053,7 +1138,7 @@ static int _dns_encode_raw(struct dns_context *context, struct dns_rrs *rrs)
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
0 1 2 3 4 5 6 7 8 9 A B C D E F
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| |
/ /
@@ -1110,7 +1195,7 @@ static int _dns_decode_raw(struct dns_context *context, unsigned char *raw, int
return 0;
}
int _dns_decode_CNAME(struct dns_context *context, char *cname, int cname_size)
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);
@@ -1121,7 +1206,7 @@ int _dns_decode_CNAME(struct dns_context *context, char *cname, int cname_size)
return 0;
}
int _dns_encode_CNAME(struct dns_context *context, struct dns_rrs *rrs)
static int _dns_encode_CNAME(struct dns_context *context, struct dns_rrs *rrs)
{
int ret;
int qtype = 0;
@@ -1161,7 +1246,7 @@ int _dns_encode_CNAME(struct dns_context *context, struct dns_rrs *rrs)
return 0;
}
int _dns_decode_SOA(struct dns_context *context, struct dns_soa *soa)
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);
@@ -1178,16 +1263,16 @@ int _dns_decode_SOA(struct dns_context *context, struct dns_soa *soa)
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);
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;
}
int _dns_encode_SOA(struct dns_context *context, struct dns_rrs *rrs)
static int _dns_encode_SOA(struct dns_context *context, struct dns_rrs *rrs)
{
int ret;
int qtype = 0;
@@ -1237,33 +1322,32 @@ int _dns_encode_SOA(struct dns_context *context, struct dns_rrs *rrs)
return -1;
}
dns_write_int(&context->ptr, *(unsigned int *)data_context.ptr);
_dns_write_int(&context->ptr, *(unsigned int *)data_context.ptr);
data_context.ptr += 4;
dns_write_int(&context->ptr, *(unsigned int *)data_context.ptr);
_dns_write_int(&context->ptr, *(unsigned int *)data_context.ptr);
data_context.ptr += 4;
dns_write_int(&context->ptr, *(unsigned int *)data_context.ptr);
_dns_write_int(&context->ptr, *(unsigned int *)data_context.ptr);
data_context.ptr += 4;
dns_write_int(&context->ptr, *(unsigned int *)data_context.ptr);
_dns_write_int(&context->ptr, *(unsigned int *)data_context.ptr);
data_context.ptr += 4;
dns_write_int(&context->ptr, *(unsigned int *)data_context.ptr);
_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);
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;
@@ -1280,7 +1364,7 @@ static int _dns_decode_opt_ecs(struct dns_context *context, struct dns_opt_ecs *
return 0;
}
int _dns_encode_OPT(struct dns_context *context, struct dns_rrs *rrs)
static int _dns_encode_OPT(struct dns_context *context, struct dns_rrs *rrs)
{
int ret;
int opt_code = 0;
@@ -1289,6 +1373,7 @@ int _dns_encode_OPT(struct dns_context *context, struct dns_rrs *rrs)
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;
@@ -1299,19 +1384,29 @@ int _dns_encode_OPT(struct dns_context *context, struct dns_rrs *rrs)
return -1;
}
if (_dns_left_len(context) < (4 + rr_len)) {
if (rr_len < sizeof(*dns_opt)) {
return -1;
}
dns_write_short(&context->ptr, opt_code);
dns_write_short(&context->ptr, rr_len);
memcpy(context->ptr, data_context.ptr, rr_len);
context->ptr += rr_len;
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;
}
int _dns_get_opts_data_len(struct dns_packet *packet, struct dns_rrs *rrs, int count)
static int _dns_get_opts_data_len(struct dns_packet *packet, struct dns_rrs *rrs, int count)
{
int i = 0;
int len = 0;
@@ -1339,7 +1434,7 @@ int _dns_get_opts_data_len(struct dns_packet *packet, struct dns_rrs *rrs, int c
return len;
}
int _dns_encode_opts(struct dns_packet *packet, struct dns_context *context, struct dns_rrs *rrs, int count)
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;
@@ -1381,7 +1476,7 @@ static int _dns_decode_opt(struct dns_context *context, dns_rr_type type, unsign
unsigned short opt_code;
unsigned short opt_len;
unsigned short ercode = (ttl >> 16) & 0xFFFF;
unsigned short ever = (ttl) & 0xFFFF;
unsigned short ever = (ttl)&0xFFFF;
unsigned char *start = context->ptr;
struct dns_packet *packet = context->packet;
int ret = 0;
@@ -1389,46 +1484,46 @@ static int _dns_decode_opt(struct dns_context *context, dns_rr_type type, unsign
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
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 (MSB) +1 (LSB)
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
0: | OPTION-CODE |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
2: | OPTION-LENGTH |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
4: | |
/ OPTION-DATA /
/ /
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
/ OPTION-DATA /
/ /
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
TTL
+0 (MSB) +1 (LSB)
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
+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);
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);
@@ -1440,18 +1535,22 @@ static int _dns_decode_opt(struct dns_context *context, dns_rr_type type, unsign
case DNS_OPT_T_ECS: {
struct dns_opt_ecs ecs;
ret = _dns_decode_opt_ecs(context, &ecs);
if (ret != 0 ) {
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;
@@ -1584,7 +1683,7 @@ static int _dns_decode_an(struct dns_context *context, dns_rr_type type)
}
} break;
case DNS_T_OPT: {
unsigned char *opt_start = context->ptr;
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);
@@ -1870,7 +1969,8 @@ int dns_encode(unsigned char *data, int size, struct dns_packet *packet)
return context.ptr - context.data;
}
void dns_debug(void)
#if 0
static void dns_debug(void)
{
unsigned char data[1024];
int len;
@@ -1894,10 +1994,11 @@ void dns_debug(void)
memset(data, 0, sizeof(data));
len = dns_encode(data, 1024, packet);
if (len < 0) {
tlog(TLOG_ERROR, "encode failed.\n");
tlog(TLOG_ERROR, "encode failed.");
}
fd = open("dns-cmp.bin", O_CREAT | O_TRUNC | O_RDWR);
write(fd, data, len);
close(fd);
}
#endif

View File

@@ -1,11 +1,6 @@
#ifndef _DNS_HEAD_H
#define _DNS_HEAD_H
#include <arpa/inet.h>
#include <linux/filter.h>
#include <netdb.h>
#include <stdint.h>
#define DNS_RR_A_LEN 4
#define DNS_RR_AAAA_LEN 16
#define DNS_MAX_CNAME_LEN 256
@@ -50,9 +45,10 @@ typedef enum dns_type {
DNS_T_ALL = 255
} dns_type_t;
typedef enum dns_opt_code {
DNS_OPT_T_ECS = 8,
DNS_OPT_T_ALL = 255
typedef enum dns_opt_code {
DNS_OPT_T_ECS = 8,
DNS_OPT_T_TCP_KEEPALIVE = 11,
DNS_OPT_T_ALL = 255
} dns_opt_code_t;
typedef enum dns_opcode {
@@ -188,11 +184,17 @@ int dns_get_AAAA(struct dns_rrs *rrs, char *domain, int maxsize, int *ttl, unsig
int dns_add_SOA(struct dns_packet *packet, dns_rr_type type, char *domain, int ttl, struct dns_soa *soa);
int dns_get_SOA(struct dns_rrs *rrs, char *domain, int maxsize, int *ttl, struct dns_soa *soa);
int dns_add_NS(struct dns_packet *packet, dns_rr_type type, char *domain, int ttl, char *cname);
int dns_get_NS(struct dns_rrs *rrs, char *domain, int maxsize, int *ttl, char *cname, int cname_size);
int dns_set_OPT_payload_size(struct dns_packet *packet, int payload_size);
int dns_get_OPT_payload_size(struct dns_packet *packet);
int dns_add_OPT_ECS(struct dns_packet *packet, struct dns_opt_ecs *ecs);
int dns_get_OPT_ECS(struct dns_rrs *rrs, unsigned short *opt_code, unsigned short *opt_len, struct dns_opt_ecs *ecs);
int dns_add_OPT_TCP_KEEYALIVE(struct dns_packet *packet, unsigned short timeout);
int dns_get_OPT_TCP_KEEYALIVE(struct dns_rrs *rrs, unsigned short *opt_code, unsigned short *opt_len, unsigned short *timeout);
/*
* Packet operation
*/

View File

@@ -1,44 +1,49 @@
#include "dns_cache.h"
#include "stringutil.h"
#include "tlog.h"
#include <pthread.h>
#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;
int num;
atomic_t num;
int size;
pthread_mutex_t lock;
};
struct dns_cache_head dns_cache_head;
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);
dns_cache_head.num = 0;
atomic_set(&dns_cache_head.num, 0);
dns_cache_head.size = size;
pthread_mutex_init(&dns_cache_head.lock, 0);
pthread_mutex_init(&dns_cache_head.lock, NULL);
return 0;
}
struct dns_cache *_dns_cache_last(void)
static __attribute__((unused)) struct dns_cache *_dns_cache_last(void)
{
return list_last_entry(&dns_cache_head.cache_list, struct dns_cache, list);
}
struct dns_cache *_dns_cache_first(void)
static struct dns_cache *_dns_cache_first(void)
{
return list_first_entry_or_null(&dns_cache_head.cache_list, struct dns_cache, list);
}
void _dns_cache_delete(struct dns_cache *dns_cache)
static void _dns_cache_delete(struct dns_cache *dns_cache)
{
hash_del(&dns_cache->node);
list_del_init(&dns_cache->list);
dns_cache_head.num--;
atomic_dec(&dns_cache_head.num);
free(dns_cache);
}
@@ -52,6 +57,9 @@ void dns_cache_get(struct dns_cache *dns_cache)
void dns_cache_release(struct dns_cache *dns_cache)
{
if (dns_cache == NULL) {
return;
}
if (!atomic_dec_and_test(&dns_cache->ref)) {
return;
}
@@ -59,14 +67,14 @@ void dns_cache_release(struct dns_cache *dns_cache)
_dns_cache_delete(dns_cache);
}
void _dns_cache_remove(struct dns_cache *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 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;
@@ -74,6 +82,7 @@ int dns_cache_replace(char *domain, char *cname, int cname_ttl, int ttl, dns_typ
return 0;
}
/* lookup existing cache */
dns_cache = dns_cache_lookup(domain, qtype);
if (dns_cache == NULL) {
return 0;
@@ -83,43 +92,46 @@ int dns_cache_replace(char *domain, char *cname, int cname_ttl, int ttl, dns_typ
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);
pthread_mutex_unlock(&dns_cache_head.lock);
if (qtype == DNS_T_A) {
if (addr_len != DNS_RR_A_LEN) {
goto errout;
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;
goto errout_unlock;
}
memcpy(dns_cache->addr, addr, DNS_RR_AAAA_LEN);
} else {
goto errout;
goto errout_unlock;
}
if (cname) {
strncpy(dns_cache->cname, cname, DNS_MAX_CNAME_LEN);
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:
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 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;
@@ -128,6 +140,7 @@ int dns_cache_insert(char *domain, char *cname, int cname_ttl, int ttl, dns_type
return 0;
}
/* if cache already exists, free */
dns_cache = dns_cache_lookup(domain, qtype);
if (dns_cache) {
dns_cache_delete(dns_cache);
@@ -146,12 +159,14 @@ int dns_cache_insert(char *domain, char *cname, int cname_ttl, int ttl, dns_type
key = hash_string(domain);
key = jhash(&qtype, sizeof(qtype), key);
strncpy(dns_cache->domain, domain, DNS_MAX_CNAME_LEN);
safe_strncpy(dns_cache->domain, domain, DNS_MAX_CNAME_LEN);
dns_cache->cname[0] = 0;
dns_cache->qtype = qtype;
dns_cache->ttl = ttl;
dns_cache->hitnum = 2;
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) {
@@ -169,7 +184,7 @@ int dns_cache_insert(char *domain, char *cname, int cname_ttl, int ttl, dns_type
}
if (cname) {
strncpy(dns_cache->cname, cname, DNS_MAX_CNAME_LEN);
safe_strncpy(dns_cache->cname, cname, DNS_MAX_CNAME_LEN);
dns_cache->cname_ttl = cname_ttl;
}
@@ -178,8 +193,8 @@ int dns_cache_insert(char *domain, char *cname, int cname_ttl, int ttl, dns_type
list_add_tail(&dns_cache->list, &dns_cache_head.cache_list);
INIT_LIST_HEAD(&dns_cache->check_list);
dns_cache_head.num++;
if (dns_cache_head.num > dns_cache_head.size) {
/* 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) {
@@ -212,6 +227,7 @@ struct dns_cache *dns_cache_lookup(char *domain, dns_type_t qtype)
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)
{
@@ -228,6 +244,7 @@ struct dns_cache *dns_cache_lookup(char *domain, dns_type_t qtype)
}
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;
@@ -262,13 +279,33 @@ void dns_cache_delete(struct dns_cache *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);
dns_cache->hitnum++;
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);
}
@@ -291,6 +328,7 @@ void dns_cache_invalidate(dns_cache_preinvalid_callback callback, int ttl_pre)
{
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);
@@ -307,6 +345,7 @@ void dns_cache_invalidate(dns_cache_preinvalid_callback callback, int ttl_pre)
list_for_each_entry_safe(dns_cache, tmp, &checklist, check_list)
{
/* run callback */
if (callback) {
callback(dns_cache);
}
@@ -326,4 +365,4 @@ void dns_cache_destroy(void)
pthread_mutex_unlock(&dns_cache_head.lock);
pthread_mutex_destroy(&dns_cache_head.lock);
}
}

View File

@@ -6,8 +6,13 @@
#include "hash.h"
#include "hashtable.h"
#include "list.h"
#include <stdlib.h>
#include <time.h>
#ifdef __cpluscplus
extern "C" {
#endif
#define DNS_CACHE_TTL_MIN 30
struct dns_cache {
@@ -19,7 +24,9 @@ struct dns_cache {
char cname[DNS_MAX_CNAME_LEN];
unsigned int cname_ttl;
unsigned int ttl;
int hitnum;
int speed;
atomic_t hitnum;
int hitnum_update_add;
int del_pending;
time_t insert_time;
dns_type_t qtype;
@@ -32,9 +39,9 @@ struct dns_cache {
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 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 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);
@@ -44,6 +51,8 @@ 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);
@@ -54,4 +63,7 @@ int dns_cache_get_ttl(struct dns_cache *dns_cache);
void dns_cache_destroy(void);
#endif // !_SMARTDNS_CACHE_H
#ifdef __cpluscplus
}
#endif
#endif // !_SMARTDNS_CACHE_H

File diff suppressed because it is too large Load Diff

View File

@@ -3,6 +3,13 @@
#include "dns.h"
#ifdef __cpluscplus
extern "C" {
#endif
#define DNS_SERVER_SPKI_LEN 64
#define DNS_SERVER_GROUP_DEFAULT "default"
typedef enum {
DNS_SERVER_UDP,
DNS_SERVER_TCP,
@@ -18,8 +25,9 @@ typedef enum dns_result_type {
} dns_result_type;
#define DNSSERVER_FLAG_BLACKLIST_IP (0x1 << 0)
#define DNSSERVER_FLAG_CHECK_EDNS (0x1 << 1)
#define DNSSERVER_FLAG_CHECK_TTL (0x1 << 2)
#define DNSSERVER_FLAG_WHITELIST_IP (0x1 << 1)
#define DNSSERVER_FLAG_CHECK_EDNS (0x1 << 2)
#define DNSSERVER_FLAG_CHECK_TTL (0x1 << 3)
int dns_client_init(void);
@@ -30,16 +38,61 @@ typedef int (*dns_client_callback)(char *domain, dns_result_type rtype, unsigned
int inpacket_len, void *user_ptr);
/* query domain */
int dns_client_query(char *domain, int qtype, dns_client_callback callback, void *user_ptr);
int dns_client_query(char *domain, int qtype, dns_client_callback callback, void *user_ptr, const char *group_name);
void dns_client_exit(void);
struct client_dns_server_flag_udp {
int ttl;
};
struct client_dns_server_flag_tls {
char spki[DNS_SERVER_SPKI_LEN];
int spi_len;
char hostname[DNS_MAX_CNAME_LEN];
char tls_host_verify[DNS_MAX_CNAME_LEN];
};
struct client_dns_server_flag_https {
char spki[DNS_SERVER_SPKI_LEN];
int spi_len;
char hostname[DNS_MAX_CNAME_LEN];
char httphost[DNS_MAX_CNAME_LEN];
char path[DNS_MAX_CNAME_LEN];
char tls_host_verify[DNS_MAX_CNAME_LEN];
};
struct client_dns_server_flags {
dns_server_type_t type;
unsigned int server_flag;
unsigned int result_flag;
union {
struct client_dns_server_flag_udp udp;
struct client_dns_server_flag_tls tls;
struct client_dns_server_flag_https https;
};
};
int dns_client_spki_decode(const char *spki, unsigned char *spki_data_out);
/* add remote dns server */
int dns_add_server(char *server_ip, int port, dns_server_type_t server_type, int result_flag, int ttl);
int dns_client_add_server(char *server_ip, int port, dns_server_type_t server_type, struct client_dns_server_flags *flags);
/* remove remote dns server */
int dns_remove_server(char *server_ip, int port, dns_server_type_t server_type);
int dns_client_remove_server(char *server_ip, int port, dns_server_type_t server_type);
int dns_client_add_group(char *group_name);
int dns_client_add_to_group(char *group_name, char *server_ip, int port, dns_server_type_t server_type);
int dns_client_remove_from_group(char *group_name, char *server_ip, int port, dns_server_type_t server_type);
int dns_client_remove_group(char *group_name);
int dns_server_num(void);
#ifdef __cpluscplus
}
#endif
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -10,13 +10,24 @@
#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 DNS_MAX_CONF_CNAME_LEN 128
#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"
@@ -26,16 +37,40 @@ enum domain_rule {
DOMAIN_RULE_ADDRESS_IPV4,
DOMAIN_RULE_ADDRESS_IPV6,
DOMAIN_RULE_IPSET,
DOMAIN_RULE_NAMESERVER,
DOMAIN_RULE_MAX,
};
#define DOMAIN_FLAG_ADDR_SOA (1 << 0)
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_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_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;
@@ -62,12 +97,39 @@ 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 */
@@ -83,12 +145,14 @@ struct dns_bogus_ip_address {
enum address_rule {
ADDRESS_RULE_BLACKLIST = 1,
ADDRESS_RULE_BOGUS = 2,
ADDRESS_RULE_IP_IGNORE = 3,
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;
};
@@ -104,8 +168,16 @@ struct dns_conf_address_rule {
radix_tree_t *ipv6;
};
extern char dns_conf_server_ip[DNS_MAX_IPLEN];
extern char dns_conf_server_tcp_ip[DNS_MAX_IPLEN];
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;
@@ -117,12 +189,18 @@ 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_CONF_CNAME_LEN];
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;
@@ -138,10 +216,14 @@ 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[]);
#endif // !_DNS_CONF
#ifdef __cpluscplus
}
#endif
#endif // !_DNS_CONF

File diff suppressed because it is too large Load Diff

View File

@@ -1,12 +1,29 @@
#ifndef _SMART_DNS_SERVER_H
#define _SMART_DNS_SERVER_H
#include "dns.h"
#ifdef __cpluscplus
extern "C" {
#endif
int dns_server_init(void);
int dns_server_run(void);
int dns_server_start(void);
void dns_server_stop(void);
void dns_server_exit(void);
/* query result notify function */
typedef int (*dns_result_callback)(char *domain, dns_rtcode_t rtcode, dns_type_t addr_type, char *ip, unsigned int ping_time, void *user_ptr);
/* query domain */
int dns_server_query(char *domain, int qtype, dns_result_callback callback, void *user_ptr);
#ifdef __cpluscplus
}
#endif
#endif

View File

@@ -30,6 +30,7 @@
#include <netinet/ip.h>
#include <netinet/ip6.h>
#include <netinet/ip_icmp.h>
#include <netinet/tcp.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
@@ -43,11 +44,14 @@
#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
#define ICMP_FILTER 1
struct icmp_filter {
uint32_t data;
uint32_t data;
};
#endif
@@ -142,7 +146,7 @@ static struct fast_ping_struct ping;
static atomic_t ping_sid = ATOMIC_INIT(0);
static int bool_print_log = 1;
uint16_t _fast_ping_checksum(uint16_t *header, size_t len)
static uint16_t _fast_ping_checksum(uint16_t *header, size_t len)
{
uint32_t sum = 0;
int i;
@@ -154,7 +158,7 @@ uint16_t _fast_ping_checksum(uint16_t *header, size_t len)
return htons(~((sum >> 16) + (sum & 0xffff)));
}
void _fast_ping_install_filter_v6(int sock)
static void _fast_ping_install_filter_v6(int sock)
{
struct icmp6_filter icmp6_filter;
ICMP6_FILTER_SETBLOCKALL(&icmp6_filter);
@@ -186,7 +190,7 @@ void _fast_ping_install_filter_v6(int sock)
}
}
void _fast_ping_install_filter_v4(int sock)
static void _fast_ping_install_filter_v4(int sock)
{
static int once;
static struct sock_filter insns[] = {
@@ -215,17 +219,91 @@ void _fast_ping_install_filter_v4(int sock)
}
}
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;
if (getaddrinfo(host, port, &hints, &result) != 0) {
tlog(TLOG_ERROR, "get addr info failed. %s\n", strerror(errno));
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;
}
@@ -350,8 +428,8 @@ static int _fast_ping_sendping_v6(struct ping_host_struct *ping_host)
icmp6->icmp6_id = ping.ident;
icmp6->icmp6_seq = htons(ping_host->seq);
gettimeofday(&packet->msg.tv, 0);
gettimeofday(&ping_host->last, 0);
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;
@@ -372,7 +450,7 @@ static int _fast_ping_sendping_v6(struct ping_host_struct *ping_host)
}
char ping_host_name[PING_MAX_HOSTLEN];
tlog(TLOG_ERROR, "sendto %s, id %d, %s", gethost_by_addr(ping_host_name, (struct sockaddr *)&ping_host->addr, ping_host->addr_len), ping_host->sid,
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;
}
@@ -397,8 +475,8 @@ static int _fast_ping_sendping_v4(struct ping_host_struct *ping_host)
icmp->icmp_id = ping.ident;
icmp->icmp_seq = htons(ping_host->seq);
gettimeofday(&packet->msg.tv, 0);
gettimeofday(&ping_host->last, 0);
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;
@@ -411,7 +489,7 @@ static int _fast_ping_sendping_v4(struct ping_host_struct *ping_host)
goto errout;
}
char ping_host_name[PING_MAX_HOSTLEN];
tlog(TLOG_ERROR, "sendto %s, id %d, %s", gethost_by_addr(ping_host_name, (struct sockaddr *)&ping_host->addr, ping_host->addr_len), ping_host->sid,
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;
}
@@ -449,7 +527,7 @@ static int _fast_ping_sendping_udp(struct ping_host_struct *ping_host)
memset(&dns_head, 0, sizeof(dns_head));
dns_head.id = htons(ping_host->sid);
dns_head.flag = flag;
gettimeofday(&ping_host->last, 0);
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;
@@ -457,7 +535,7 @@ static int _fast_ping_sendping_udp(struct ping_host_struct *ping_host)
goto errout;
}
char ping_host_name[PING_MAX_HOSTLEN];
tlog(TLOG_ERROR, "sendto %s, id %d, %s", gethost_by_addr(ping_host_name, (struct sockaddr *)&ping_host->addr, ping_host->addr_len), ping_host->sid,
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;
}
@@ -473,6 +551,9 @@ 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);
@@ -483,6 +564,9 @@ static int _fast_ping_sendping_tcp(struct ping_host_struct *ping_host)
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) {
@@ -499,13 +583,13 @@ static int _fast_ping_sendping_tcp(struct ping_host_struct *ping_host)
bool_print_log = 0;
}
tlog(TLOG_ERROR, "connect %s, id %d, %s", gethost_by_addr(ping_host_name, (struct sockaddr *)&ping_host->addr, ping_host->addr_len), ping_host->sid,
strerror(errno));
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, 0);
gettimeofday(&ping_host->last, NULL);
ping_host->fd = fd;
memset(&event, 0, sizeof(event));
event.events = EPOLLIN | EPOLLOUT | EPOLLERR;
@@ -528,7 +612,7 @@ errout:
static int _fast_ping_sendping(struct ping_host_struct *ping_host)
{
int ret = -1;
gettimeofday(&ping_host->last, 0);
gettimeofday(&ping_host->last, NULL);
if (ping_host->type == FAST_PING_ICMP) {
ret = _fast_ping_sendping_v4(ping_host);
@@ -558,6 +642,7 @@ static int _fast_ping_create_icmp_sock(FAST_PING_TYPE type)
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:
@@ -592,6 +677,7 @@ static int _fast_ping_create_icmp_sock(FAST_PING_TYPE type)
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;
@@ -655,6 +741,7 @@ static int _fast_ping_create_udp_sock(FAST_PING_TYPE type)
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:
@@ -686,6 +773,7 @@ static int _fast_ping_create_udp_sock(FAST_PING_TYPE type)
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;
@@ -741,8 +829,8 @@ errout:
return -1;
}
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)
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;
@@ -754,111 +842,184 @@ void fast_ping_print_result(struct ping_host_struct *ping_host, const char *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;
int domain = -1;
int icmp_proto = 0;
uint32_t addrkey;
char ip_str[PING_MAX_HOSTLEN];
char port_str[MAX_IP_LEN];
char *service = NULL;
int port = -1;
FAST_PING_TYPE ping_type;
int socktype = 0;
unsigned int seed;
int ret = 0;
if (parse_ip(host, ip_str, &port) != 0) {
goto errout;
}
switch (type) {
case PING_TYPE_ICMP: {
socktype = SOCK_RAW;
domain = _fast_ping_getdomain(ip_str);
if (domain < 0) {
return NULL;
}
switch (domain) {
case AF_INET:
icmp_proto = IPPROTO_ICMP;
ping_type = FAST_PING_ICMP;
break;
case AF_INET6:
icmp_proto = IPPROTO_ICMPV6;
ping_type = FAST_PING_ICMP6;
break;
default:
return NULL;
break;
}
if (_fast_ping_create_icmp(ping_type) < 0) {
goto errout;
}
gai = _fast_ping_getaddr(ip_str, service, socktype, icmp_proto);
if (gai == NULL) {
goto errout;
}
} break;
case PING_TYPE_TCP: {
if (port <= 0) {
port = 80;
}
icmp_proto = 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, icmp_proto);
if (gai == NULL) {
goto errout;
}
} break;
case PING_TYPE_DNS: {
if (port <= 0) {
port = 53;
}
domain = _fast_ping_getdomain(ip_str);
if (domain < 0) {
return NULL;
}
switch (domain) {
case AF_INET:
ping_type = FAST_PING_UDP;
break;
case AF_INET6:
ping_type = FAST_PING_UDP6;
break;
default:
return NULL;
break;
}
icmp_proto = 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, icmp_proto);
if (gai == NULL) {
goto errout;
}
} break;
default:
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;
break;
}
ping_host = malloc(sizeof(*ping_host));
@@ -867,7 +1028,7 @@ struct ping_host_struct *fast_ping_start(PING_TYPE type, const char *host, int c
}
memset(ping_host, 0, sizeof(*ping_host));
strncpy(ping_host->host, host, PING_MAX_HOSTLEN);
safe_strncpy(ping_host->host, host, PING_MAX_HOSTLEN);
ping_host->fd = -1;
ping_host->timeout = timeout;
ping_host->count = count;
@@ -882,7 +1043,7 @@ struct ping_host_struct *fast_ping_start(PING_TYPE type, const char *host, int c
if (ping_callback) {
ping_host->ping_callback = ping_callback;
} else {
ping_host->ping_callback = fast_ping_print_result;
ping_host->ping_callback = _fast_ping_print_result;
}
ping_host->interval = (timeout > interval) ? timeout : interval;
ping_host->addr_len = gai->ai_addrlen;
@@ -892,26 +1053,26 @@ struct ping_host_struct *fast_ping_start(PING_TYPE type, const char *host, int c
goto errout;
}
memcpy(&ping_host->addr, gai->ai_addr, gai->ai_addrlen);
freeaddrinfo(gai);
tlog(TLOG_DEBUG, "ping %s, id = %d", host, ping_host->sid);
addrkey = jhash(&ping_host->addr, ping_host->addr_len, 0);
addrkey = jhash(&ping_host->sid, sizeof(ping_host->sid), addrkey);
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);
_fast_ping_host_get(ping_host);
if (_fast_ping_sendping(ping_host) != 0) {
goto errout_remove;
}
ping_host->run = 1;
_fast_ping_host_put(ping_host);
freeaddrinfo(gai);
return ping_host;
errout_remove:
fast_ping_stop(ping_host);
ping_host = NULL;
errout:
if (gai) {
freeaddrinfo(gai);
@@ -921,10 +1082,6 @@ errout:
free(ping_host);
}
return NULL;
errout_remove:
fast_ping_stop(ping_host);
_fast_ping_host_put(ping_host);
return NULL;
}
@@ -1028,7 +1185,8 @@ static struct fast_ping_packet *_fast_ping_icmp_packet(struct ping_host_struct *
return packet;
}
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)
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;
@@ -1090,21 +1248,20 @@ static int _fast_ping_process_icmp(struct ping_host_struct *ping_host, struct ti
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, (struct sockaddr *)&from, from_len));
tlog(TLOG_DEBUG, "recv ping packet from %s failed.", gethost_by_addr(name, sizeof(name), (struct sockaddr *)&from));
goto errout;
}
addrkey = jhash(&from, from_len, 0);
tvsend = &packet->msg.tv;
sid = packet->msg.sid;
seq = packet->msg.seq;
cookie = packet->msg.cookie;
addrkey = jhash(&sid, sizeof(sid), addrkey);
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 (recv_ping_host->addr_len == from_len && memcmp(&recv_ping_host->addr, &from, from_len) == 0 && recv_ping_host->sid == sid &&
recv_ping_host->cookie == cookie) {
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;
}
@@ -1117,8 +1274,8 @@ static int _fast_ping_process_icmp(struct ping_host_struct *ping_host, struct ti
}
if (recv_ping_host->seq != seq) {
_fast_ping_host_put(recv_ping_host);
tlog(TLOG_ERROR, "seq num mismatch, expect %u, real %u", recv_ping_host->seq, seq);
_fast_ping_host_put(recv_ping_host);
return -1;
}
@@ -1230,13 +1387,14 @@ static int _fast_ping_process_udp(struct ping_host_struct *ping_host, struct tim
if (len < sizeof(*dns_head)) {
goto errout;
}
addrkey = jhash(&from, from_len, 0);
sid = ntohs(dns_head->id);
addrkey = jhash(&sid, sizeof(sid), addrkey);
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 (recv_ping_host->addr_len == from_len && memcmp(&recv_ping_host->addr, &from, from_len) == 0 && recv_ping_host->sid == sid) {
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;
}
@@ -1323,9 +1481,10 @@ static void _fast_ping_period_run(void)
struct hlist_node *tmp = NULL;
int i = 0;
struct timeval now;
struct timezone tz;
struct timeval interval;
int64_t millisecond;
gettimeofday(&now, 0);
gettimeofday(&now, &tz);
LIST_HEAD(action);
pthread_mutex_lock(&ping.map_lock);
@@ -1422,7 +1581,7 @@ static void *_fast_ping_work(void *arg)
continue;
}
gettimeofday(&tvnow, 0);
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;
@@ -1456,8 +1615,8 @@ int fast_ping_init(void)
goto errout;
}
pthread_mutex_init(&ping.map_lock, 0);
pthread_mutex_init(&ping.lock, 0);
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);
@@ -1486,14 +1645,8 @@ errout:
return -1;
}
void fast_ping_exit(void)
static void _fast_ping_close_fds(void)
{
if (ping.tid > 0) {
void *ret = NULL;
ping.run = 0;
pthread_join(ping.tid, &ret);
}
if (ping.fd_icmp > 0) {
close(ping.fd_icmp);
ping.fd_icmp = -1;
@@ -1504,6 +1657,26 @@ void fast_ping_exit(void)
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);

445
src/http_parse.c Normal file
View File

@@ -0,0 +1,445 @@
#include "http_parse.h"
#include "hash.h"
#include "hashtable.h"
#include "jhash.h"
#include "list.h"
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
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);
}

69
src/http_parse.h Normal file
View File

@@ -0,0 +1,69 @@
#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

View File

@@ -195,6 +195,17 @@ void* art_search(const art_tree *t, const unsigned char *key, int key_len);
*/
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
@@ -237,4 +248,4 @@ int art_iter_prefix(art_tree *t, const unsigned char *prefix, int prefix_len, ar
}
#endif
#endif
#endif

View File

@@ -11,7 +11,7 @@
* Atomic type.
*/
typedef struct {
volatile int counter;
int counter;
} atomic_t;
#define ATOMIC_INIT(i) { (i) }
@@ -154,3 +154,4 @@ static inline int atomic_add_negative( int i, atomic_t *v )
}
#endif

View File

@@ -130,4 +130,4 @@ static inline int bitmap_and(unsigned long *dst, const unsigned long *src1,
return __bitmap_and(dst, src1, src2, nbits);
}
#endif /* _PERF_BITOPS_H */
#endif /* _PERF_BITOPS_H */

View File

@@ -197,4 +197,4 @@ static inline uint32_t rol32(uint32_t word, unsigned int shift)
return (word << shift) | (word >> ((-shift) & 31));
}
#endif
#endif

View File

@@ -86,7 +86,7 @@ struct config_item_size {
#define CONF_END() \
{ \
0, 0, 0 \
NULL, NULL, NULL \
}
extern int conf_custom(const char *item, void *data, int argc, char *argv[]);
@@ -118,4 +118,6 @@ int load_conf(const char *file, struct config_item items[], conf_error_handler h
void load_exit(void);
#endif // !_GENERIC_CONF_H
const char *conf_get_conf_file(void);
#endif // !_GENERIC_CONF_H

View File

@@ -74,4 +74,4 @@ extern unsigned long find_first_bit(const unsigned long *addr,
unsigned long find_first_zero_bit(const unsigned long *addr, unsigned long size);
#endif
#endif /*_TOOLS_LINUX_ASM_GENERIC_BITOPS_FIND_H_ */
#endif /*_TOOLS_LINUX_ASM_GENERIC_BITOPS_FIND_H_ */

View File

@@ -114,4 +114,4 @@
#define round_up(x, y) ((((x)-1) | __round_mask(x, y))+1)
#define round_down(x, y) ((x) & ~__round_mask(x, y))
#endif /* _TOOLS_LINUX_COMPILER_H */
#endif /* _TOOLS_LINUX_COMPILER_H */

View File

@@ -210,4 +210,4 @@ hash_string(const char *str)
return(v);
}
#endif /* _GENERIC_HASH_H */
#endif /* _GENERIC_HASH_H */

View File

@@ -147,4 +147,4 @@ static inline void hash_del(struct hlist_node *node)
hlist_for_each_entry_safe(obj, tmp,\
&name[hash_min(key, HASH_BITS(name))], member)
#endif
#endif

View File

@@ -181,4 +181,4 @@ static inline uint32_t jhash_1word(uint32_t a, uint32_t initval)
return __jhash_nwords(a, 0, 0, initval + JHASH_INITVAL + (1 << 2));
}
#endif /* _JHASH_H */
#endif /* _JHASH_H */

View File

@@ -789,4 +789,4 @@ static inline void list_del_range(struct list_head *begin,
#define list_for_each_from(pos, head) \
for (; pos != (head); pos = pos->next)
#endif /* _GENERIC_LIST_H */
#endif /* _GENERIC_LIST_H */

View File

@@ -159,3 +159,4 @@ 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 */

View File

@@ -285,3 +285,4 @@ rb_erase_augmented(struct rb_node *node, struct rb_root *root,
}
#endif /* _GENERIC_RBTREE_H */

24
src/include/stringutil.h Normal file
View File

@@ -0,0 +1,24 @@
#ifndef _GENERIC_STRING_UITL_H
#define _GENERIC_STRING_UITL_H
#include <stddef.h>
#include <string.h>
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

View File

@@ -52,23 +52,28 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
static art_node* alloc_node(uint8_t type) {
art_node* n;
switch (type) {
void *mem = NULL;
switch (type) {
case NODE4:
n = (art_node*)calloc(1, sizeof(art_node4));
mem = (art_node*)calloc(1, sizeof(art_node4));
break;
case NODE16:
n = (art_node*)calloc(1, sizeof(art_node16));
mem = (art_node*)calloc(1, sizeof(art_node16));
break;
case NODE48:
n = (art_node*)calloc(1, sizeof(art_node48));
mem = (art_node*)calloc(1, sizeof(art_node48));
break;
case NODE256:
n = (art_node*)calloc(1, sizeof(art_node256));
mem = (art_node*)calloc(1, sizeof(art_node256));
break;
default:
abort();
}
n->type = type;
if (mem == NULL) {
abort();
}
n = mem;
n->type = type;
return n;
}
@@ -385,6 +390,10 @@ art_leaf* art_maximum(art_tree *t) {
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);
@@ -1064,3 +1073,57 @@ void *art_substring(const art_tree *t, const unsigned char *str, int str_len, un
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 ;
}

View File

@@ -5,6 +5,13 @@
#include <string.h>
#include <unistd.h>
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;
@@ -55,6 +62,10 @@ int conf_yesno(const char *item, void *data, int argc, char *argv[])
}
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) {
@@ -106,11 +117,13 @@ void conf_getopt_reset(void)
int argc = 2;
char *argv[3] = {"reset", "", 0};
optind = 1;
optind = 0;
opterr = 0;
optopt = 0;
getopt_long(argc, argv, "", long_options, NULL);
optind = 1;
optind = 0;
opterr = 0;
optopt = 0;
}
int conf_parse_args(char *key, char *value, int *argc, char **argv)
@@ -154,7 +167,6 @@ int conf_parse_args(char *key, char *value, int *argc, char **argv)
argv[count] = start;
*ptr = '\0';
ptr++;
start = ptr;
count++;
sep_flag = ' ';
start = NULL;
@@ -170,7 +182,7 @@ int conf_parse_args(char *key, char *value, int *argc, char **argv)
}
*argc = count;
argv[count + 1] = 0;
argv[count] = 0;
return 0;
}
@@ -251,6 +263,7 @@ int load_conf_file(const char *file, struct config_item *items, conf_error_handl
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) {

View File

@@ -281,7 +281,7 @@ 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];
radix_node_t *stack[RADIX_MAXBITS + 1] = {0};
unsigned char *addr;
unsigned int bitlen;
int cnt = 0;

0
src/lib/stringutil.c Normal file
View File

View File

@@ -49,7 +49,7 @@
static int verbose_screen;
void help(void)
static void _help(void)
{
/* clang-format off */
char *help = ""
@@ -59,7 +59,8 @@ void help(void)
" -c [conf] config file.\n"
" -p [pid] pid file path\n"
" -S ignore segment fault signal.\n"
" -v verbose screent.\n"
" -x verbose screen.\n"
" -v dispaly version.\n"
" -h show this help message.\n"
"Online help: http://pymumu.github.io/smartdns\n"
@@ -69,7 +70,21 @@ void help(void)
printf("%s", help);
}
int smartdns_load_from_resolv(void)
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];
@@ -108,7 +123,7 @@ int smartdns_load_from_resolv(void)
port = DEFAULT_DNS_PORT;
}
strncpy(dns_conf_servers[dns_conf_server_num].server, ns_ip, DNS_MAX_IPLEN);
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++;
@@ -120,23 +135,78 @@ int smartdns_load_from_resolv(void)
return ret;
}
int smartdns_add_servers(void)
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++) {
ret = dns_add_server(dns_conf_servers[i].server, dns_conf_servers[i].port, dns_conf_servers[i].type, dns_conf_servers[i].result_flag,
dns_conf_servers[i].ttl);
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;
}
int smartdns_set_ecs_ip(void)
static int _smartdns_set_ecs_ip(void)
{
int ret = 0;
if (dns_conf_ipv4_ecs.enable) {
@@ -150,52 +220,7 @@ int smartdns_set_ecs_ip(void)
return ret;
}
int create_pid_file(const char *pid_file)
{
int fd;
int flags;
char buff[TMP_BUFF_LEN_32];
/* create pid file, and lock this file */
fd = open(pid_file, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
if (fd == -1) {
fprintf(stderr, "create pid file failed, %s\n", strerror(errno));
return -1;
}
flags = fcntl(fd, F_GETFD);
if (flags < 0) {
fprintf(stderr, "Could not get flags for PID file %s\n", pid_file);
goto errout;
}
flags |= FD_CLOEXEC;
if (fcntl(fd, F_SETFD, flags) == -1) {
fprintf(stderr, "Could not set flags for PID file %s\n", pid_file);
goto errout;
}
if (lockf(fd, F_TLOCK, 0) < 0) {
fprintf(stderr, "Server is already running.\n");
goto errout;
}
snprintf(buff, TMP_BUFF_LEN_32, "%d\n", getpid());
if (write(fd, buff, strnlen(buff, TMP_BUFF_LEN_32)) < 0) {
fprintf(stderr, "write pid to file failed, %s.\n", strerror(errno));
goto errout;
}
return 0;
errout:
if (fd > 0) {
close(fd);
}
return -1;
}
int smartdns_init_ssl(void)
static int _smartdns_init_ssl(void)
{
SSL_load_error_strings();
SSL_library_init();
@@ -205,7 +230,7 @@ int smartdns_init_ssl(void)
return 0;
}
int smartdns_destroy_ssl(void)
static int _smartdns_destroy_ssl(void)
{
SSL_CRYPTO_thread_cleanup();
ERR_free_strings();
@@ -214,7 +239,7 @@ int smartdns_destroy_ssl(void)
return 0;
}
int smartdns_init(void)
static int _smartdns_init(void)
{
int ret;
char *logfile = SMARTDNS_LOG_FILE;
@@ -223,7 +248,7 @@ int smartdns_init(void)
logfile = dns_conf_log_file;
}
ret = tlog_init(logfile, dns_conf_log_size, dns_conf_log_num, 1, 0, 0);
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;
@@ -234,13 +259,13 @@ int smartdns_init(void)
tlog(TLOG_NOTICE, "smartdns starting...(Copyright (C) Nick Peng <pymumu@gmail.com>, build:%s %s)", __DATE__, __TIME__);
if (smartdns_init_ssl() != 0) {
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) {
if (_smartdns_load_from_resolv() != 0) {
tlog(TLOG_ERROR, "load dns from resolv failed.");
goto errout;
}
@@ -263,13 +288,13 @@ int smartdns_init(void)
tlog(TLOG_ERROR, "start dns client failed.\n");
goto errout;
}
ret = smartdns_add_servers();
ret = _smartdns_add_servers();
if (ret != 0) {
tlog(TLOG_ERROR, "add servers failed.");
goto errout;
}
ret = smartdns_set_ecs_ip();
ret = _smartdns_set_ecs_ip();
if (ret != 0) {
tlog(TLOG_WARN, "set ecs ip address failed.");
}
@@ -280,57 +305,59 @@ errout:
return -1;
}
int smartdns_run(void)
static int _smartdns_run(void)
{
return dns_server_run();
}
void smartdns_exit(void)
static void _smartdns_exit(void)
{
dns_server_exit();
dns_client_exit();
fast_ping_exit();
smartdns_destroy_ssl();
_smartdns_destroy_ssl();
tlog_exit();
dns_server_load_exit();
}
void sig_exit(int signo)
static void _sig_exit(int signo)
{
dns_server_stop();
}
void sig_error_exit(int signo, siginfo_t *siginfo, void *ct)
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(__aarch64__) || defined(__arm__)
PC = context->uc_mcontext.arm_pc;
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;
PC = context->uc_mcontext.pc;
#endif
tlog(TLOG_ERROR, "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__);
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);
}
int sig_list[] = {SIGSEGV, SIGABRT, SIGBUS, SIGILL, SIGFPE};
static int sig_list[] = {SIGSEGV, SIGABRT, SIGBUS, SIGILL, SIGFPE};
int sig_num = sizeof(sig_list) / sizeof(int);
static int sig_num = sizeof(sig_list) / sizeof(int);
void reg_signal(void)
static void _reg_signal(void)
{
struct sigaction act, old;
int i = 0;
act.sa_sigaction = sig_error_exit;
act.sa_sigaction = _sig_error_exit;
sigemptyset(&act.sa_mask);
act.sa_flags = SA_RESTART | SA_SIGINFO;
@@ -348,10 +375,10 @@ int main(int argc, char *argv[])
char pid_file[MAX_LINE_LEN];
int signal_ignore = 0;
strncpy(config_file, SMARTDNS_CONF_FILE, MAX_LINE_LEN);
strncpy(pid_file, SMARTDNS_PID_FILE, MAX_LINE_LEN);
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:Sv")) != -1) {
while ((opt = getopt(argc, argv, "fhc:p:Svx")) != -1) {
switch (opt) {
case 'f':
is_forground = 1;
@@ -365,11 +392,15 @@ int main(int argc, char *argv[])
case 'S':
signal_ignore = 1;
break;
case 'v':
case 'x':
verbose_screen = 1;
break;
case 'v':
_show_version();
return 0;
break;
case 'h':
help();
_help();
return 1;
}
}
@@ -382,7 +413,7 @@ int main(int argc, char *argv[])
}
if (signal_ignore == 0) {
reg_signal();
_reg_signal();
}
if (dns_server_load_conf(config_file) != 0) {
@@ -394,17 +425,17 @@ int main(int argc, char *argv[])
goto errout;
}
ret = smartdns_init();
ret = _smartdns_init();
if (ret != 0) {
usleep(100000);
goto errout;
}
signal(SIGINT, sig_exit);
signal(SIGINT, _sig_exit);
signal(SIGPIPE, SIG_IGN);
atexit(smartdns_exit);
atexit(_smartdns_exit);
return smartdns_run();
return _smartdns_run();
errout:

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
/*
* tinylog
* Copyright (C) 2018 Ruilin Peng (Nick) <pymumu@gmail.com>
* Copyright (C) 2018-2019 Ruilin Peng (Nick) <pymumu@gmail.com>
* https://github.com/pymumu/tinylog
*/
@@ -32,13 +32,36 @@ struct tlog_time {
int usec;
};
#ifndef TLOG_MAX_LINE_LEN
#define TLOG_MAX_LINE_LEN (1024)
#endif
/* TLOG FLAGS LIST */
/* set tlog not compress file when archive */
#define TLOG_NOCOMPRESS (1 << 0)
/* Set the segmentation mode to process the log, Used by the callback function to return a full log*/
#define TLOG_SEGMENT (1 << 1)
/*
multiwrite: enable multi process write mode.
NOTICE: maxlogsize in all prcesses must be same when enable this mode.
*/
#define TLOG_MULTI_WRITE (1 << 2)
/* Not Block if buffer is insufficient. */
#define TLOG_NONBLOCK (1 << 3)
/* enable log to screen */
#define TLOG_SCREEN (1 << 4)
struct tlog_info {
const char *level;
tlog_level level;
const char *file;
const char *func;
int line;
struct tlog_time time;
};
} __attribute__((packed));
/*
Function: Print log
@@ -48,12 +71,15 @@ format: Log formats
#ifndef BASE_FILE_NAME
#define BASE_FILE_NAME __FILE__
#endif
#define tlog(level, format, ...) tlog_ext(level, BASE_FILE_NAME, __LINE__, __func__, 0, format, ##__VA_ARGS__)
#define tlog(level, format, ...) tlog_ext(level, BASE_FILE_NAME, __LINE__, __func__, NULL, format, ##__VA_ARGS__)
extern int tlog_ext(tlog_level level, const char *file, int line, const char *func, void *userptr, const char *format, ...)
__attribute__((format(printf, 6, 7)));
__attribute__((format(printf, 6, 7))) __attribute__((nonnull (6)));
extern int tlog_vext(tlog_level level, const char *file, int line, const char *func, void *userptr, const char *format, va_list ap);
/* write buff to log file */
extern int tlog_write_log(char *buff, int bufflen);
/* set log level */
extern int tlog_setlevel(tlog_level level);
@@ -63,17 +89,18 @@ extern void tlog_setlogscreen(int enable);
/* enalbe early log to screen */
extern void tlog_set_early_printf(int enable);
/* Get log level in string */
extern const char *tlog_get_level_string(tlog_level level);
/*
Function: Initialize log module
logfile: log file.
maxlogsize: The maximum size of a single log file.
maxlogcount: Number of archived logs.
block: Blocked if buffer is not sufficient.
buffsize: Buffer size, zero for default (128K)
multiwrite: enable multi process write mode.
NOTICE: maxlogsize in all prcesses must be same when enable this mode.
flag: read tlog flags
*/
extern int tlog_init(const char *logfile, int maxlogsize, int maxlogcount, int block, int buffsize, int multiwrite);
extern int tlog_init(const char *logfile, int maxlogsize, int maxlogcount, int buffsize, unsigned int flag);
/* flush pending log message, and exit tlog */
extern void tlog_exit(void);
@@ -89,6 +116,12 @@ read _tlog_format for example.
typedef int (*tlog_format_func)(char *buff, int maxlen, struct tlog_info *info, void *userptr, const char *format, va_list ap);
extern int tlog_reg_format_func(tlog_format_func func);
/* register log output callback
Note: info is invalid when flag TLOG_SEGMENT is not set.
*/
typedef int (*tlog_log_output_func)(struct tlog_info *info, char *buff, int bufflen, void *private_data);
extern int tlog_reg_log_output_func(tlog_log_output_func output, void *private_data);
struct tlog_log;
typedef struct tlog_log tlog_log;
/*
@@ -96,15 +129,16 @@ Function: open a new log stream, handler should close by tlog_close
logfile: log file.
maxlogsize: The maximum size of a single log file.
maxlogcount: Number of archived logs.
block: Blocked if buffer is not sufficient.
buffsize: Buffer size, zero for default (128K)
multiwrite: enable multi process write mode.
NOTICE: maxlogsize in all prcesses must be same when enable this mode.
flag: read tlog flags
return: log stream handler.
*/
extern tlog_log *tlog_open(const char *logfile, int maxlogsize, int maxlogcount, int block, int buffsize, int multiwrite);
extern tlog_log *tlog_open(const char *logfile, int maxlogsize, int maxlogcount, int buffsize, unsigned int flag);
/* write buff to log file */
extern int tlog_write(struct tlog_log *log, char *buff, int bufflen);
/* close log stream */
extern void tlog_close(tlog_log *log);
/*
@@ -112,7 +146,7 @@ Function: Print log to log stream
log: log stream
format: Log formats
*/
extern int tlog_printf(tlog_log *log, const char *format, ...) __attribute__((format(printf, 2, 3)));
extern int tlog_printf(tlog_log *log, const char *format, ...) __attribute__((format(printf, 2, 3))) __attribute__((nonnull (1, 2)));
/*
Function: Print log to log stream with ap
@@ -125,6 +159,16 @@ extern int tlog_vprintf(tlog_log *log, const char *format, va_list ap);
/* enalbe log to screen */
extern void tlog_logscreen(tlog_log *log, int enable);
/* register output callback */
typedef int (*tlog_output_func)(struct tlog_log *log, char *buff, int bufflen);
extern int tlog_reg_output_func(tlog_log *log, tlog_output_func output);
/* set private data */
extern void tlog_set_private(tlog_log *log, void *private_data);
/* get private data */
extern void *tlog_get_private(tlog_log *log);
/* get local time */
extern int tlog_localtime(struct tlog_time *tm);

View File

@@ -1,16 +1,26 @@
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include "util.h"
#include "dns_conf.h"
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/netlink.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <linux/capability.h>
#include <openssl/crypto.h>
#include <openssl/ssl.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#include <inttypes.h>
#include <sys/prctl.h>
#define TMP_BUFF_LEN_32 32
#define NFNL_SUBSYS_IPSET 6
@@ -57,6 +67,7 @@ struct ipset_netlink_msg {
};
static int ipset_fd;
static int pidfile_fd;
unsigned long get_tick_count(void)
{
@@ -67,7 +78,7 @@ unsigned long get_tick_count(void)
return (ts.tv_sec * 1000 + ts.tv_nsec / 1000000);
}
char *gethost_by_addr(char *host, struct sockaddr *addr, socklen_t addr_len)
char *gethost_by_addr(char *host, int maxsize, struct sockaddr *addr)
{
struct sockaddr_storage *addr_store = (struct sockaddr_storage *)addr;
host[0] = 0;
@@ -75,7 +86,7 @@ char *gethost_by_addr(char *host, struct sockaddr *addr, socklen_t addr_len)
case AF_INET: {
struct sockaddr_in *addr_in;
addr_in = (struct sockaddr_in *)addr;
inet_ntop(AF_INET, &addr_in->sin_addr, host, addr_len);
inet_ntop(AF_INET, &addr_in->sin_addr, host, maxsize);
} break;
case AF_INET6: {
struct sockaddr_in6 *addr_in6;
@@ -84,9 +95,9 @@ char *gethost_by_addr(char *host, struct sockaddr *addr, socklen_t addr_len)
struct sockaddr_in addr_in4;
memset(&addr_in4, 0, sizeof(addr_in4));
memcpy(&addr_in4.sin_addr.s_addr, addr_in6->sin6_addr.s6_addr + 12, sizeof(addr_in4.sin_addr.s_addr));
inet_ntop(AF_INET, &addr_in4.sin_addr, host, addr_len);
inet_ntop(AF_INET, &addr_in4.sin_addr, host, maxsize);
} else {
inet_ntop(AF_INET6, &addr_in6->sin6_addr, host, addr_len);
inet_ntop(AF_INET6, &addr_in6->sin6_addr, host, maxsize);
}
} break;
default:
@@ -117,6 +128,7 @@ int getaddr_by_host(char *host, struct sockaddr *addr, socklen_t *addr_len)
result->ai_addrlen = *addr_len;
}
addr->sa_family = result->ai_family;
memcpy(addr, result->ai_addr, result->ai_addrlen);
*addr_len = result->ai_addrlen;
@@ -130,6 +142,75 @@ errout:
return -1;
}
int getsocknet_inet(int fd, struct sockaddr *addr, socklen_t *addr_len)
{
struct sockaddr_storage addr_store;
socklen_t addr_store_len = sizeof(addr_store);
if (getsockname(fd, (struct sockaddr *)&addr_store, &addr_store_len) != 0) {
goto errout;
}
switch (addr_store.ss_family) {
case AF_INET: {
struct sockaddr_in *addr_in;
addr_in = (struct sockaddr_in *)addr;
addr_in->sin_family = AF_INET;
*addr_len = sizeof(struct sockaddr_in);
memcpy(addr, addr_in, sizeof(struct sockaddr_in));
} break;
case AF_INET6: {
struct sockaddr_in6 *addr_in6;
addr_in6 = (struct sockaddr_in6 *)addr;
if (IN6_IS_ADDR_V4MAPPED(&addr_in6->sin6_addr)) {
struct sockaddr_in addr_in4;
memset(&addr_in4, 0, sizeof(addr_in4));
memcpy(&addr_in4.sin_addr.s_addr, addr_in6->sin6_addr.s6_addr + 12, sizeof(addr_in4.sin_addr.s_addr));
addr_in4.sin_family = AF_INET;
addr_in4.sin_port = 0;
*addr_len = sizeof(struct sockaddr_in);
memcpy(addr, &addr_in4, sizeof(struct sockaddr_in));
} else {
addr_in6->sin6_family = AF_INET6;
*addr_len = sizeof(struct sockaddr_in6);
memcpy(addr, addr_in6, sizeof(struct sockaddr_in6));
}
} break;
default:
goto errout;
break;
}
return 0;
errout:
return -1;
}
int fill_sockaddr_by_ip(unsigned char *ip, int ip_len, int port, struct sockaddr *addr, socklen_t *addr_len)
{
if (ip == NULL || addr == NULL || addr_len == NULL) {
return -1;
}
if (ip_len == IPV4_ADDR_LEN) {
struct sockaddr_in *addr_in = NULL;
addr->sa_family = AF_INET;
addr_in = (struct sockaddr_in *)addr;
addr_in->sin_port = htons(port);
addr_in->sin_family = AF_INET;
memcpy(&addr_in->sin_addr.s_addr, ip, ip_len);
*addr_len = 16;
} else if (ip_len == IPV6_ADDR_LEN) {
struct sockaddr_in6 *addr_in6 = NULL;
addr->sa_family = AF_INET6;
addr_in6 = (struct sockaddr_in6 *)addr;
addr_in6->sin6_port = htons(port);
addr_in6->sin6_family = AF_INET6;
memcpy(addr_in6->sin6_addr.s6_addr, ip, ip_len);
*addr_len = 28;
}
return -1;
}
int parse_ip(const char *value, char *ip, int *port)
{
int offset = 0;
@@ -185,6 +266,145 @@ int parse_ip(const char *value, char *ip, int *port)
return 0;
}
static int _check_is_ipv4(const char *ip)
{
const char *ptr = ip;
char c = 0;
int dot_num = 0;
int dig_num = 0;
while ( (c = *ptr++) != '\0') {
if (c == '.') {
dot_num++;
dig_num = 0;
continue;
}
/* check number count of one field */
if (dig_num >= 4) {
return -1;
}
if (c >= '0' && c <= '9') {
dig_num++;
continue;
}
return -1;
}
/* check field number */
if (dot_num != 3) {
return -1;
}
return 0;
}
static int _check_is_ipv6(const char *ip)
{
const char *ptr = ip;
char c = 0;
int colon_num = 0;
int dig_num = 0;
while ( (c = *ptr++) != '\0') {
if (c == '[' || c == ']') {
continue;
}
if (c == ':') {
colon_num++;
dig_num = 0;
continue;
}
/* check number count of one field */
if (dig_num >= 5) {
return -1;
}
dig_num++;
if (c >= '0' && c <= '9') {
continue;
}
if (c >= 'a' && c <= 'f') {
continue;
}
if (c >= 'A' && c <= 'F') {
continue;
}
return -1;
}
/* check field number */
if (colon_num > 7) {
return -1;
}
return 0;
}
int check_is_ipaddr(const char *ip)
{
if (strstr(ip, ".")) {
/* IPV4 */
return _check_is_ipv4(ip);
} else if (strstr(ip, ":")) {
/* IPV6 */
return _check_is_ipv6(ip);
}
return -1;
}
int parse_uri(char *value, char *scheme, char *host, int *port, char *path)
{
char *scheme_end = NULL;
int field_len = 0;
char *process_ptr = value;
char host_name[PATH_MAX];
char *host_end = NULL;
scheme_end = strstr(value, "://");
if (scheme_end) {
field_len = scheme_end - value;
if (scheme) {
memcpy(scheme, value, field_len);
scheme[field_len] = 0;
}
process_ptr += field_len + 3;
} else {
if (scheme) {
scheme[0] = '\0';
}
}
host_end = strstr(process_ptr, "/");
if (host_end == NULL) {
return parse_ip(process_ptr, host, port);
};
field_len = host_end - process_ptr;
if (field_len >= sizeof(host_name)) {
return -1;
}
memcpy(host_name, process_ptr, field_len);
host_name[field_len] = 0;
if (parse_ip(host_name, host, port) != 0) {
return -1;
}
process_ptr += field_len;
if (path) {
strncpy(path, process_ptr, PATH_MAX);
}
return 0;
}
int set_fd_nonblock(int fd, int nonblock)
{
int ret;
@@ -203,7 +423,7 @@ int set_fd_nonblock(int fd, int nonblock)
return 0;
}
char *reverse_string(char *output, char *input, int len)
char *reverse_string(char *output, const char *input, int len, int to_lower_case)
{
char *begin = output;
if (len <= 0) {
@@ -214,6 +434,12 @@ char *reverse_string(char *output, char *input, int len)
len--;
while (len >= 0) {
*output = *(input + len);
if (to_lower_case) {
if (*output >= 'A' && *output <= 'Z') {
/* To lower case */
*output = *output + 32;
}
}
output++;
len--;
}
@@ -248,12 +474,12 @@ static int _ipset_socket_init(void)
return 0;
}
static int _ipset_support_timeout(const char *ipsetname)
static int _ipset_support_timeout(const char *ipsetname)
{
if (dns_conf_ipset_timeout_enable) {
return 0;
}
return -1;
}
@@ -326,7 +552,7 @@ static int _ipset_operate(const char *ipsetname, const unsigned char addr[], int
nested[0]->len = (void *)buffer + NETLINK_ALIGN(netlink_head->nlmsg_len) - (void *)nested[0];
for (;;) {
rc = sendto(ipset_fd, buffer, netlink_head->nlmsg_len, 0, (struct sockaddr *)&snl, sizeof(snl));
rc = sendto(ipset_fd, buffer, netlink_head->nlmsg_len, 0, (const struct sockaddr *)&snl, sizeof(snl));
if (rc >= 0) {
break;
}
@@ -353,60 +579,357 @@ int ipset_del(const char *ipsetname, const unsigned char addr[], int addr_len)
return _ipset_operate(ipsetname, addr, addr_len, 0, IPSET_DEL);
}
#define THREAD_STACK_SIZE (16*1024)
unsigned char *SSL_SHA256(const unsigned char *d, size_t n, unsigned char *md)
{
SHA256_CTX c;
static unsigned char m[SHA256_DIGEST_LENGTH];
if (md == NULL)
md = m;
SHA256_Init(&c);
SHA256_Update(&c, d, n);
SHA256_Final(md, &c);
OPENSSL_cleanse(&c, sizeof(c));
return (md);
}
int SSL_base64_decode(const char *in, unsigned char *out)
{
size_t inlen = strlen(in);
int outlen;
if (inlen == 0) {
return 0;
}
outlen = EVP_DecodeBlock(out, (unsigned char *)in, inlen);
if (outlen < 0) {
goto errout;
}
/* Subtract padding bytes from |outlen| */
while (in[--inlen] == '=') {
--outlen;
}
return outlen;
errout:
return -1;
}
int create_pid_file(const char *pid_file)
{
int fd;
int flags;
char buff[TMP_BUFF_LEN_32];
/* create pid file, and lock this file */
fd = open(pid_file, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
if (fd == -1) {
fprintf(stderr, "create pid file failed, %s\n", strerror(errno));
return -1;
}
flags = fcntl(fd, F_GETFD);
if (flags < 0) {
fprintf(stderr, "Could not get flags for PID file %s\n", pid_file);
goto errout;
}
flags |= FD_CLOEXEC;
if (fcntl(fd, F_SETFD, flags) == -1) {
fprintf(stderr, "Could not set flags for PID file %s\n", pid_file);
goto errout;
}
if (lockf(fd, F_TLOCK, 0) < 0) {
fprintf(stderr, "Server is already running.\n");
goto errout;
}
snprintf(buff, TMP_BUFF_LEN_32, "%d\n", getpid());
if (write(fd, buff, strnlen(buff, TMP_BUFF_LEN_32)) < 0) {
fprintf(stderr, "write pid to file failed, %s.\n", strerror(errno));
goto errout;
}
if (pidfile_fd > 0) {
close(pidfile_fd);
}
pidfile_fd = fd;
return 0;
errout:
if (fd > 0) {
close(fd);
}
return -1;
}
#define THREAD_STACK_SIZE (16 * 1024)
static pthread_mutex_t *lock_cs;
static long *lock_count;
void pthreads_locking_callback(int mode, int type, const char *file, int line)
static __attribute__((unused)) void _pthreads_locking_callback(int mode, int type, const char *file, int line)
{
if (mode & CRYPTO_LOCK) {
pthread_mutex_lock(&(lock_cs[type]));
lock_count[type]++;
} else {
pthread_mutex_unlock(&(lock_cs[type]));
}
if (mode & CRYPTO_LOCK) {
pthread_mutex_lock(&(lock_cs[type]));
lock_count[type]++;
} else {
pthread_mutex_unlock(&(lock_cs[type]));
}
}
unsigned long pthreads_thread_id(void)
static __attribute__((unused)) unsigned long _pthreads_thread_id(void)
{
unsigned long ret;
unsigned long ret;
ret = (unsigned long)pthread_self();
return (ret);
ret = (unsigned long)pthread_self();
return (ret);
}
void SSL_CRYPTO_thread_setup(void)
{
int i;
int i;
lock_cs = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
if (!lock_cs || !lock_count) {
/* Nothing we can do about this...void function! */
if (lock_cs)
OPENSSL_free(lock_cs);
if (lock_count)
OPENSSL_free(lock_count);
return;
}
for (i = 0; i < CRYPTO_num_locks(); i++) {
lock_count[i] = 0;
pthread_mutex_init(&(lock_cs[i]), NULL);
}
lock_cs = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
if (!lock_cs || !lock_count) {
/* Nothing we can do about this...void function! */
if (lock_cs)
OPENSSL_free(lock_cs);
if (lock_count)
OPENSSL_free(lock_count);
return;
}
for (i = 0; i < CRYPTO_num_locks(); i++) {
lock_count[i] = 0;
pthread_mutex_init(&(lock_cs[i]), NULL);
}
CRYPTO_set_id_callback(pthreads_thread_id);
CRYPTO_set_locking_callback(pthreads_locking_callback);
CRYPTO_set_id_callback(_pthreads_thread_id);
CRYPTO_set_locking_callback(_pthreads_locking_callback);
}
void SSL_CRYPTO_thread_cleanup(void)
{
int i;
int i;
CRYPTO_set_locking_callback(NULL);
for (i = 0; i < CRYPTO_num_locks(); i++) {
pthread_mutex_destroy(&(lock_cs[i]));
}
OPENSSL_free(lock_cs);
OPENSSL_free(lock_count);
CRYPTO_set_locking_callback(NULL);
for (i = 0; i < CRYPTO_num_locks(); i++) {
pthread_mutex_destroy(&(lock_cs[i]));
}
OPENSSL_free(lock_cs);
OPENSSL_free(lock_count);
}
#define SERVER_NAME_LEN 256
#define TLS_HEADER_LEN 5
#define TLS_HANDSHAKE_CONTENT_TYPE 0x16
#define TLS_HANDSHAKE_TYPE_CLIENT_HELLO 0x01
#ifndef MIN
#define MIN(X, Y) ((X) < (Y) ? (X) : (Y))
#endif
static int parse_extensions(const char *, size_t, char *, const char **);
static int parse_server_name_extension(const char *, size_t, char *, const char **);
/* Parse a TLS packet for the Server Name Indication extension in the client
* hello handshake, returning the first servername found (pointer to static
* array)
*
* Returns:
* >=0 - length of the hostname and updates *hostname
* caller is responsible for freeing *hostname
* -1 - Incomplete request
* -2 - No Host header included in this request
* -3 - Invalid hostname pointer
* -4 - malloc failure
* < -4 - Invalid TLS client hello
*/
int parse_tls_header(const char *data, size_t data_len, char *hostname, const char **hostname_ptr)
{
char tls_content_type;
char tls_version_major;
char tls_version_minor;
size_t pos = TLS_HEADER_LEN;
size_t len;
if (hostname == NULL)
return -3;
/* Check that our TCP payload is at least large enough for a TLS header */
if (data_len < TLS_HEADER_LEN)
return -1;
/* SSL 2.0 compatible Client Hello
*
* High bit of first byte (length) and content type is Client Hello
*
* See RFC5246 Appendix E.2
*/
if (data[0] & 0x80 && data[2] == 1) {
return -2;
}
tls_content_type = data[0];
if (tls_content_type != TLS_HANDSHAKE_CONTENT_TYPE) {
return -5;
}
tls_version_major = data[1];
tls_version_minor = data[2];
if (tls_version_major < 3) {
return -2;
}
/* TLS record length */
len = ((unsigned char)data[3] << 8) + (unsigned char)data[4] + TLS_HEADER_LEN;
data_len = MIN(data_len, len);
/* Check we received entire TLS record length */
if (data_len < len)
return -1;
/*
* Handshake
*/
if (pos + 1 > data_len) {
return -5;
}
if (data[pos] != TLS_HANDSHAKE_TYPE_CLIENT_HELLO) {
return -5;
}
/* Skip past fixed length records:
* 1 Handshake Type
* 3 Length
* 2 Version (again)
* 32 Random
* to Session ID Length
*/
pos += 38;
/* Session ID */
if (pos + 1 > data_len)
return -5;
len = (unsigned char)data[pos];
pos += 1 + len;
/* Cipher Suites */
if (pos + 2 > data_len)
return -5;
len = ((unsigned char)data[pos] << 8) + (unsigned char)data[pos + 1];
pos += 2 + len;
/* Compression Methods */
if (pos + 1 > data_len)
return -5;
len = (unsigned char)data[pos];
pos += 1 + len;
if (pos == data_len && tls_version_major == 3 && tls_version_minor == 0) {
return -2;
}
/* Extensions */
if (pos + 2 > data_len)
return -5;
len = ((unsigned char)data[pos] << 8) + (unsigned char)data[pos + 1];
pos += 2;
if (pos + len > data_len)
return -5;
return parse_extensions(data + pos, len, hostname, hostname_ptr);
}
static int parse_extensions(const char *data, size_t data_len, char *hostname, const char **hostname_ptr)
{
size_t pos = 0;
size_t len;
/* Parse each 4 bytes for the extension header */
while (pos + 4 <= data_len) {
/* Extension Length */
len = ((unsigned char)data[pos + 2] << 8) + (unsigned char)data[pos + 3];
/* Check if it's a server name extension */
if (data[pos] == 0x00 && data[pos + 1] == 0x00) {
/* There can be only one extension of each type, so we break
* our state and move p to beinnging of the extension here */
if (pos + 4 + len > data_len)
return -5;
return parse_server_name_extension(data + pos + 4, len, hostname, hostname_ptr);
}
pos += 4 + len; /* Advance to the next extension header */
}
/* Check we ended where we expected to */
if (pos != data_len)
return -5;
return -2;
}
static int parse_server_name_extension(const char *data, size_t data_len, char *hostname, const char **hostname_ptr)
{
size_t pos = 2; /* skip server name list length */
size_t len;
while (pos + 3 < data_len) {
len = ((unsigned char)data[pos + 1] << 8) + (unsigned char)data[pos + 2];
if (pos + 3 + len > data_len)
return -5;
switch (data[pos]) { /* name type */
case 0x00: /* host_name */
strncpy(hostname, data + pos + 3, len);
if (hostname_ptr) {
*hostname_ptr = data + pos + 3;
}
hostname[len] = '\0';
return len;
default:
break;
}
pos += 3 + len;
}
/* Check we ended where we expected to */
if (pos != data_len)
return -5;
return -2;
}
void get_compiled_time(struct tm *tm)
{
char s_month[5];
int month, day, year;
int hour, min, sec;
static const char *month_names = "JanFebMarAprMayJunJulAugSepOctNovDec";
sscanf(__DATE__, "%5s %d %d", s_month, &day, &year);
month = (strstr(month_names, s_month) - month_names) / 3;
sscanf(__TIME__, "%d:%d:%d", &hour, &min, &sec);
tm->tm_year = year - 1900;
tm->tm_mon = month;
tm->tm_mday = day;
tm->tm_isdst = -1;
tm->tm_hour = hour;
tm->tm_min = min;
tm->tm_sec = sec;
}
int has_network_raw_cap(void)
{
int fd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
if (fd < 0) {
return 0;
}
close(fd);
return 1;
}

View File

@@ -4,21 +4,35 @@
#define SMART_DNS_UTIL_H
#include <netdb.h>
#include <time.h>
#include "stringutil.h"
#ifdef __cplusplus
extern "C" {
#endif /*__cplusplus */
#define PORT_NOT_DEFINED -1
#define MAX_IP_LEN 64
unsigned long get_tick_count(void);
char *gethost_by_addr(char *host, struct sockaddr *addr, socklen_t addr_len);
char *gethost_by_addr(char *host, int maxsize, struct sockaddr *addr);
int getaddr_by_host(char *host, struct sockaddr *addr, socklen_t *addr_len);
int getsocknet_inet(int fd, struct sockaddr *addr, socklen_t *addr_len);
int fill_sockaddr_by_ip(unsigned char *ip, int ip_len, int port, struct sockaddr *addr, socklen_t *addr_len);
int parse_ip(const char *value, char *ip, int *port);
int check_is_ipaddr(const char *ip);
int parse_uri(char *value, char *scheme, char *host, int *port, char *path);
int set_fd_nonblock(int fd, int nonblock);
char *reverse_string(char *output, char *input, int len);
char *reverse_string(char *output, const char *input, int len, int to_lower_case);
void print_stack(void);
@@ -30,4 +44,32 @@ void SSL_CRYPTO_thread_setup(void);
void SSL_CRYPTO_thread_cleanup(void);
#endif
unsigned char *SSL_SHA256(const unsigned char *d, size_t n, unsigned char *md);
int SSL_base64_decode(const char *in, unsigned char *out);
int create_pid_file(const char *pid_file);
/* Parse a TLS packet for the Server Name Indication extension in the client
* hello handshake, returning the first servername found (pointer to static
* array)
*
* Returns:
* >=0 - length of the hostname and updates *hostname
* caller is responsible for freeing *hostname
* -1 - Incomplete request
* -2 - No Host header included in this request
* -3 - Invalid hostname pointer
* -4 - malloc failure
* < -4 - Invalid TLS client hello
*/
int parse_tls_header(const char *data, size_t data_len, char *hostname, const char **hostname_ptr);
void get_compiled_time(struct tm *tm);
int has_network_raw_cap(void);
#ifdef __cplusplus
}
#endif /*__cplusplus */
#endif