Compare commits

..

72 Commits

Author SHA1 Message Date
Nick Peng
cc93156ee3 Add package build script 2019-12-15 01:28:37 +08:00
Nick Peng
8433729186 Update ReadMe.md 2019-12-15 01:28:37 +08:00
Nick Peng
4464bb982e update makefile for openwrt 2019-12-15 01:28:36 +08:00
Nick Peng
371aab6d4b support override CFLAGS and CXXFLAGS 2019-12-15 01:28:35 +08:00
Nick Peng
01e4140722 Add license 2019-12-15 01:28:32 +08:00
Nick Peng
2b08ffee98 Add some log, fix tlog issue 2019-12-15 01:28:31 +08:00
Nick Peng
9f27bb9b70 Fix compile error 2019-12-15 01:28:30 +08:00
Nick Peng
528d5c6ccc Update tlog 2019-12-15 01:28:30 +08:00
Nick Peng
6bf6315a6d Fix ssl crash issue 2019-12-15 01:28:29 +08:00
Nick Peng
aaca1c013b Fix byte alignment issue 2019-12-15 01:28:27 +08:00
Nick Peng
25c6cab4a8 Fix installation issue on arch-linux 2019-12-15 01:28:26 +08:00
Nick Peng
408c199564 create pid before load config file to avoid systemd complain 2019-12-15 01:28:24 +08:00
Nick Peng
044536aef6 optimize tcp connection lag 2019-12-15 01:28:22 +08:00
Nick Peng
1fb5cbbcd9 Fix ignore flags not working issue 2019-12-15 01:28:18 +08:00
Nick Peng
4e0cbc50b3 Update ReadMe.md 2019-12-15 01:28:17 +08:00
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
67 changed files with 6398 additions and 2664 deletions

618
ReadMe.md Executable file → Normal file
View File

@@ -1,33 +1,34 @@
# 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. [read more](#faq)
SmartDNS是一个运行在本地的DNS服务器SmartDNS接受本地客户端的DNS查询请求从多个上游DNS服务器获取DNS查询结果并将访问速度最快的结果返回给客户端提高网络访问速度。
同时支持指定特定域名IP地址并高性匹配达到过滤广告的效果。
dnsmasqall-servers不同,smartdns返回的是访问速度最快的解析结果。 (详细差异请看[FAQ](#faq))
Support Raspberry Pi, openwrt, ASUS router, Windows and other devices.
支持树莓派openwrt华硕路由器windows等设备。
## 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)
1. [软件效果展示](#软件效果展示)
1. [特性](#特性)
1. [架构](#架构)
1. [使用](#使用)
1. [下载配套安装包](#下载配套安装包)
1. [标准Linux系统安装](#标准linux系统安装树莓派x86_64系统)
1. [openwrt/LEDE](#openwrtlede)
1. [华硕路由器原生固件/梅林固件](#华硕路由器原生固件梅林固件)
1. [optware/entware](#optwareentware)
1. [Windows 10 WSL安装/WSL ubuntu](#windows-10-wsl安装wsl-ubuntu)
1. [配置参数](#配置参数)
1. [捐助](#donate)
1. [FAQ](#faq)
## Software Show
## 软件效果展示
**Ali DNS**
Use Ali DNS to query Baidu's IP and test the results.
**阿里DNS**
使用阿里DNS查询百度IP并检测结果。
```shell
pi@raspberrypi:~/code/smartdns_build $ nslookup www.baidu.com 223.5.5.5
@@ -60,7 +61,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
@@ -83,135 +84,138 @@ 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, HTTPS 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, and disale IPV6 AAAA record.
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 (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
|标准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
```
* Or after login to the system, you can query the architecture with the following commands:
* 或ssh登录系统后通过如下命令查询软件架构
* **Openwrt series commands**
* **openwrt系列命令**
```shell
opkg print_architecture
```
* **Optiware series commands**
* **optware系列命令**
```shell
ipkg print_architecture
```
* **Dedebian Series Order**
* **debian系列命令**
```shell
dpkg -- print-architecture
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.
下面的查询结果`arch ar71xx 10`表示ar71xx系列架构选择`smartdns.xxxxxxxx.ar71xx.ipk`安装包
```shell
Root@OpenWrt:# opkg print_architecture
Arch all 1
Arch noarch 1
Arch ar71xx 10
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)**
* **请在Release页面下载[点击此处下载](https://github.com/pymumu/smartdns/releases)**
```shell
https://github.com/pymu/smartdns/releases
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
### 标准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
```
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
x86系统下载配套安装包`smartdns.xxxxxxxx.x86-64.tar.gz`, 并上传到Linux系统中。 执行如下命令安装
```shell
tar zxf smartdns.xxxxxxxx.x86-64.tar.gz
@@ -220,36 +224,36 @@ https://github.com/pymu/smartdns/releases
./install -i
```
1. Configuration
1. 修改配置
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.
安装完成后可配置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
@@ -264,36 +268,36 @@ https://github.com/pymu/smartdns/releases
--------------
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
@@ -304,29 +308,29 @@ https://github.com/pymu/smartdns/releases
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.
* 如转发功能不正常,请使用方法二:作为DNSMASQ的上游。
1. Method 2: SmartDNS as upstream DNS Server of DNSMASQ
1. 方法二:作为DNSMASQ的上游
* **Forward dnsmasq's request to SmartDNS**
* **将dnsmasq的请求发送到smartdns**
Log in to the router, click on `Services`->`SmartDNS`->`redirect`, select `Run as dnsmasq upstream server` option to forwarding dnsmasq request to Smartdns.
登录路由器,点击`Services`->`SmartDNS`->`redirect`,选择`作为dnsmasq的上游服务器`设置dnsmasq的上游服务器为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`
* 方法一:使用`nslookup -querytype=ptr 0.0.0.0`查询域名
看命令结果中的`name`项目是否显示为`smartdns`或`主机名`,如`smartdns`则表示生效
```shell
pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr 0.0.0.0
@@ -337,7 +341,7 @@ https://github.com/pymu/smartdns/releases
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
@@ -350,47 +354,47 @@ https://github.com/pymu/smartdns/releases
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
@@ -401,13 +405,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
@@ -423,13 +427,13 @@ 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
@@ -439,57 +443,57 @@ Note: Merlin firmware is derived from ASUS firmware and can theoretically be use
--------------
1. Prepare
1. 准备
When using this software, you need to confirm whether the router supports USB disk and prepare a USB disk.
在使用此软件时需要确认路由器是否支持U盘并准备好U盘一个。
1. Install SmartDNS
1. 安装SmartDNS
Upload the software to `/tmp` directory of the router using winscp, and run the flollowing command to install.
将软件使用winscp上传到路由器的`/tmp`目录。
```shell
ipkg install smartdns.xxxxxxx.mipsbig.ipk
```
1. Modify the smartdns configuration
1. 修改smartdns配置
```shell
Vi /opt/etc/smartdns/smartdns.conf
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.
另外如需支持IPV6可设置工作模式为`2`将dnsmasq的DNS服务禁用smartdns为主用DNS服务器。将文件`/opt/etc/smartdns/smartdns-opt.conf`,中的`SMARTDNS_WORKMODE`修改为2.
```shell
SMARTDNS_WORKMODE="2"
```
1. Restart the router to take effect
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
Server: 192.168.1.1
Address: 192.168.1.1#53
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.
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.
注意若服务没有自动启动则需要设置optwre/entware自动启动具体方法参考optware/entware的文档。
### Windows 10 WSL Installation/WSL ubuntu
### Windows 10 WSL安装/WSL ubuntu
--------------
1. Install Windows 10 WSL ubuntu
1. 安装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
安装Windows 10 WSL运行环境发行版本选择ubuntu系统。安装步骤请参考[WSL安装说明](https://docs.microsoft.com/en-us/windows/wsl/install-win10)
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:
下载安装包`smartdns.xxxxxxxx.x86_64.tar.gz`并解压到D盘根目录。解压后目录如下
```shell
D:\SMARTDNS
@@ -504,26 +508,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
@@ -534,156 +538,168 @@ 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|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>`[-check-edns]`: edns filter. <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 -check-edns
|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>`[-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>`[-blacklist-ip]`: The "-blacklist-ip" parameter is to filtering IPs which is configured by "blacklist-ip". <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>`[-blacklist-ip]`: The "-blacklist-ip" parameter is to filtering IPs which is configured by "blacklist-ip". <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
|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
|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]
|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]
## 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. SmartDNSDNSMASQ有什么区别
SMARTDNS在设计上并不是替换DNSMASQ的SMARTDNS主要功能集中在DNS解析增强上增强部分有
* 多上游服务器并发请求,对结果进行测速后,返回最佳结果;
* addressipset域名匹配采用高效算法查询匹配更加快速高效路由器设备依然高效。
* 域名匹配支持忽略特定域名,可单独匹配IPv4 IPV6,支持多样化定制。
* 针对广告屏蔽功能做增强返回SOA屏蔽广告效果更佳
* IPV4IPV6双栈IP优选机制在双网情况下选择最快的网络通讯。
* 支持最新的TLS, HTTPS协议提供安全的DNS查询能力。
* ECS支持是查询结果更佳准确。
* IP黑名单忽略IP机制使域名查询更佳准确。
* 域名预查询,访问常用网站更加快速。
* 域名TTL可指定使访问更快速。
* 高速缓存机制,使访问更快速。
* 异步日志审计机制在记录信息的同时不影响DNS查询性能。
* 域名组group机制特定域名使用特定上游服务器组查询避免隐私泄漏。
* 第二DNS支持自定义更多行为。
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`.
1. 如何配置上游服务器最佳。
smartdns有测速机制在配置上游服务器时建议配置多个上游DNS服务器包含多个不同区域的服务器但总数建议在10个左右。推荐配置
* 运营商DNS
* 国内公共DNS如`119.29.29.29`, `223.5.5.5`
* 国外公共DNS如`8.8.8.8`, `8.8.4.4`。
For specific domain names, if there is a pollution, you can enable the anti-pollution mechanism.
1. 如何启用审计日志
审计日志记录客户端请求的域名记录信息包括请求时间请求IP请求域名请求类型如果要启用审计日志在配置界面配置`audit-enable yes`启用,`audit-size`, `audit-file`, `audit-num`分别配置审计日志文件大小,审计日志文件路径,和审计日志文件个数。审计日志文件将会压缩存储以节省空间。
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. 如何避免隐私泄漏
smartdns默认情况下会将请求发送到所有配置的DNS服务器若上游DNS服务器使用DNS或记录日志将会导致隐私泄漏。为避免隐私泄漏请尽量
* 配置使用可信的DNS服务器。
* 优先使用TLS查询。
* 设置上游DNS服务器组。
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:
1. 如何屏蔽广告
smartdns具备高性能域名匹配算法通过域名方式过滤广告非常高效如要屏蔽广告只需要配置类似如下记录即可屏蔽`*.ad.com`,则配置:
```sh
Address /ad.com/#
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:
域名的使后缀模式,过滤*.ad.com`#`表示返回SOA使屏蔽广告更加高效如果要单独屏蔽IPV4 或IPV6 在`#`后面增加数字,如`#4`表示对IPV4生效。若想忽略特定子域名的屏蔽可配置如下如忽略`pass.ad.com`,可配置如下:
```sh
Address /pass.ad.com/-
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.
1. 如何使用DNS查询分流
某些情况下需要将有些域名使用特定的DNS服务器来查询来做到DNS分流。比如。
```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:
.home 结尾的域名发送到192.168.1.1解析
.office 结尾的域名发送到10.0.0.1解析
其他域名采用默认的模式解析。
这种情况的分流配置如下:
```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
#配置上游,用-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
#Configure the resolved domain name with specific group
Nameserver /.home/home
Nameserver /.office/office
#配置解析的域名
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`.
通过上述配置即可实现DNS解析分流如果需要实现按请求端端口分流可以配置第二DNS服务器bind配置增加--group参数指定分流名称。
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.
```sh
bind :7053 -group office
bind :8053 -group home
```
* 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.
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`。
* Enable domain pre-acquisition
Enable pre-fetching of domain names with `prefetch-domain yes` to improve query hit rate.
by default, Smartdns will send domain query request again before cache expire, and cache the result for the next query. Frequently accessed domain names will continue to be cached. This feature will consume more CPU when idle.
1. 如何提高cache效率加快访问速度
smartdns提供了域名缓存机制对查询的域名进行缓存缓存时间符合DNS TTL规范。为提高缓存命中率可采用如下措施
* 适当增大cache的记录数
通过`cache-size`来设置缓存记录数。
查询压力大的环境下,并且有内存大的机器的情况下,可适当调大。
## [Donate](#Donate)
* 适当设置最小TTL值
通过`rr-ttl-min`将最低DNS TTL时间设置为一个合理值延长缓存时间。
建议是超时时间设置在1030分钟避免服务器域名变化时查询到失效域名。
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.
* 开启域名预获取功能
通过`prefetch-domain yes`来启用域名预先获取功能,提高查询命中率。
配合上述ttl超时时间smartdns将在域名ttl即将超时使再次发送查询请求并缓存查询结果供后续使用。频繁访问的域名将会持续缓存。此功能将在空闲时消耗更多的CPU。
1. 第二DNS如何自定义更多行为
第二DNS可以作为其他DNS服务器的上游提供更多的查询行为通过bind配置支持可以绑定多个端口不同端口可设置不同的标志实现不同的功能
```sh
# 绑定 6053端口6053端口的请求将采用配置office组的上游查询且不对结果进行测速忽略address的配置地址。
bind [::]:6053 -no-speed-check -group office -no-rule-addr
```
## 编译
smartdns包含了编译软件包的脚本支持编译lucidebianopenwrtoptare安装包可执行`package/build-pkg.sh`编译。
## Donate
如果你觉得此项目对你有帮助,请捐助我们,以使项目能持续发展,更加完善。
### PayPal
[![Support via PayPal](https://cdn.rawgit.com/twolfson/paypal-github-button/1.0.0/dist/button.svg)](https://paypal.me/PengNick/)
### Alipay
### Alipay 支付宝
![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.
## Additional information
Currently the code is not open source, and subsequent open source according to the situation.
Smartdns 基于GPL V3协议开源。

702
ReadMe_en.md Executable file
View File

@@ -0,0 +1,702 @@
# SmartDNS
![SmartDNS](doc/smartdns-banner.png)
SmartDNS is a local DNS server. SmartDNS accepts DNS query requests from local clients, obtains DNS query results from multiple upstream DNS servers, and returns the fastest access results to clients.
Avoiding DNS pollution and improving network access speed, supports high-performance ad filtering.
Unlike dnsmasq's all-servers, smartdns returns the fastest access resolution. [read more](#faq)
Support Raspberry Pi, openwrt, ASUS router, Windows and other devices.
## Table Of Content
1. [Software Show](#software-show)
1. [Features](#features)
1. [Architecture](#architecture)
1. [Usage](#usage)
1. [Download the package](#download-the-package)
1. [Standard Linux system installation/Raspberry Pi, X86_64 system](#standard-linux-system-installation/raspberry-pi,-x86_64-system)
1. [openwrt/LEDE](#openwrt/lede)
1. [ASUS router native firmware / Merlin firmware](#asus-router-native-firmware-/-merlin-firmware)
1. [optware/entware](#optware/entware)
1. [Windows 10 WSL Installation/WSL ubuntu](#windows-10-wsl-installation/wsl-ubuntu)
1. [Configuration parameter](#configuration-parameter)
1. [Donate](#Donate)
1. [FAQ](#FAQ)
## Software Show
**Ali DNS**
Use Ali DNS to query Baidu's IP and test the results.
```shell
pi@raspberrypi:~/code/smartdns_build $ nslookup www.baidu.com 223.5.5.5
Server: 223.5.5.5
Address: 223.5.5.5#53
Non-authoritative answer:
www.baidu.com canonical name = www.a.shifen.com.
Name: www.a.shifen.com
Address: 180.97.33.108
Name: www.a.shifen.com
Address: 180.97.33.107
pi@raspberrypi:~/code/smartdns_build $ ping 180.97.33.107 -c 2
PING 180.97.33.107 (180.97.33.107) 56(84) bytes of data.
64 bytes from 180.97.33.107: icmp_seq=1 ttl=55 time=24.3 ms
64 bytes from 180.97.33.107: icmp_seq=2 ttl=55 time=24.2 ms
--- 180.97.33.107 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 24.275/24.327/24.380/0.164 ms
pi@raspberrypi:~/code/smartdns_build $ ping 180.97.33.108 -c 2
PING 180.97.33.108 (180.97.33.108) 56(84) bytes of data.
64 bytes from 180.97.33.108: icmp_seq=1 ttl=55 time=31.1 ms
64 bytes from 180.97.33.108: icmp_seq=2 ttl=55 time=31.0 ms
--- 180.97.33.108 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 31.014/31.094/31.175/0.193 ms
```
**smartdns**
Use SmartDNS to query Baidu IP and test the results.
```shell
pi@raspberrypi:~/code/smartdns_build $ nslookup www.baidu.com
Server: 192.168.1.1
Address: 192.168.1.1#53
Non-authoritative answer:
www.baidu.com canonical name = www.a.shifen.com.
Name: www.a.shifen.com
Address: 14.215.177.39
pi@raspberrypi:~/code/smartdns_build $ ping 14.215.177.39 -c 2
PING 14.215.177.39 (14.215.177.39) 56(84) bytes of data.
64 bytes from 14.215.177.39: icmp_seq=1 ttl=56 time=6.31 ms
64 bytes from 14.215.177.39: icmp_seq=2 ttl=56 time=5.95 ms
--- 14.215.177.39 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 5.954/6.133/6.313/0.195 ms
```
From the comparison, smartdns found the fastest IP address to visit www.baidu.com, so accessing Baidu's DNS is 5 times faster than Ali DNS.
## Features
1. **Multiple upstream DNS servers**
Support configuring multiple upstream DNS servers and query at the same time.the query will not be affected, Even if there is a DNS server exception.
2. **Return the fastest IP address**
Supports finding the fastest access IP address from the IP address list of the domain name and returning it to the client to avoid DNS pollution and improve network access speed.
3. **Support for multiple query protocols**
Support UDP, TCP, TLS, HTTPS queries, and non-53 port queries, effectively avoiding DNS pollution.
4. **Domain IP address specification**
Support configuring IP address of specific domain to achieve the effect of advertising filtering, and avoid malicious websites.
5. **Domain name high performance rule filtering**
Support domain name suffix matching mode, simplify filtering configuration, filter 200,000 recording and take time <1ms.
6. **Linux/Windows multi-platform support**
Support standard Linux system (Raspberry Pi), openwrt system various firmware, ASUS router native firmware. Support Windows 10 WSL (Windows Subsystem for Linux).
7. **Support IPV4, IPV6 dual stack**
Support IPV4, IPV6 network, support query A, AAAA record, dual-stack IP selection, and disale IPV6 AAAA record.
8. **High performance, low resource consumption**
Multi-threaded asynchronous IO mode, cache cache query results.
## Architecture
![Architecture](doc/architecture.png)
1. SmartDNS receives DNS query requests from local network devices, such as PCs and mobile phone query requests.
2. SmartDNS sends query requests to multiple upstream DNS servers, using standard UDP queries, non-standard port UDP queries, and TCP queries.
3. The upstream DNS server returns a list of Server IP addresses corresponding to the domain name. SmartDNS detects the fastest Server IP with local network access.
4. Return the fastest accessed Server IP to the local client.
## Usage
### Download the package
--------------
Download the matching version of the SmartDNS installation package. The corresponding installation package is as follows.
|system |package|Description
|-----|-----|-----
|Standard Linux system (Raspberry Pi)| smartdns.xxxxxxxx.armhf.deb|Support Raspberry Pi Raspbian stretch, Debian 9 system.
|Standard Linux system (Armbian arm64)| smartdns.xxxxxxxx.arm64.deb|Support Armbian debian stretch, Debian 9 system.
|Standard Linux system (x86_64)| smartdns.xxxxxxxx.x86_64.tar.gz|Support for x86_64 Linux systems.
|Windows 10 WSL (Ubuntu)| smartdns.xxxxxxxx.x86_64.tar.gz|Windows 10 WSL ubuntu.
|Standard Linux system (x86)| smartdns.xxxxxxxx.x86.tar.gz|Support for x86_64 systems.
|ASUS native firmware (optware)|smartdns.xxxxxxx.mipsbig.ipk|Systems that support the MIPS big-end architecture, such as RT-AC55U, RT-AC66U.
|ASUS native firmware (optware)|smartdns.xxxxxxx.mipsel.ipk|System that supports the MIPS little endian architecture.
|ASUS native firmware (optware)|smartdns.xxxxxxx.arm.ipk|System that supports the ARM small endian architecture, such as the RT-AC88U, RT-AC68U.
|Padavan|smartdns.xxxxxxx.mipselsf.ipk|padavan Firmware.
|openwrt 15.01|smartdns.xxxxxxxx.ar71xx.ipk|Support AR71XX MIPS system.
|openwrt 15.01|smartdns.xxxxxxxx.ramips_24kec.ipk|Support small-end routers such as MT762X
|openwrt 15.01(Pandora)|smartdns.xxxxxxxx.mipsel_24kec_dsp.ipk|Support for Pandora firmware of MT7620 series
|openwrt 15.01(Pandora)|smartdns.xxxxxxxx.mips_74kc_dsp2.ipk|Support for Pandora firmware of AR71xx series
|openwrt 18.06|smartdns.xxxxxxxx.mips_24kc.ipk|Support AR71XX MIPS system.
|openwrt 18.06|smartdns.xxxxxxxx.mipsel_24kc.ipk|Support small-end routers such as MT726X
|openwrt 18.06|smartdns.xxxxxxxx.x86_64.ipk|Support x86_64 router
|openwrt 18.06|smartdns.xxxxxxxx.i386_pentium4.ipk|Support x86_64 router
|openwrt 18.06|smartdns.xxxxxxxxxxx.arm_cortex-a9.ipk|Router supporting arm A9 core CPU
|openwrt 18.06|smartdns.xxxxxxxxx.arm_cortex-a7_neon-vfpv4.ipk|Router supporting arm A7 core CPU
|openwrt LUCI|luci-app-smartdns.xxxxxxxxx.xxxx.all.ipk|Openwrt management interface
* The openwrt system supports a lot of CPU architecture. The above table does not list all the supported systems. Please check the CPU architecture and download it.
* The merlin Merlin firmware theory is the same as the ASUS firmware, so install the corresponding ipk package according to the hardware type. (Merlin is not verified yet, and has a problem to submit an issue)
* The CPU architecture can be found in the router management interface:
Log in to the router, click `System`->`Software`, click the `Configuration` tab page, and find the corresponding software architecture in the opkg installation source. The download path can be found, as follows, the architecture is ar71xx
```shell
src/gz chaos_calmer_base http://downloads.openwrt.org/chaos_calmer/15.05/ar71xx/generic/packages/base
```
* Or after login to the system, you can query the architecture with the following commands:
* **Openwrt series commands**
```shell
opkg print_architecture
```
* **Optiware series commands**
```shell
ipkg print_architecture
```
* **Dedebian Series Order**
```shell
dpkg -- print-architecture
```
* **for example**
The following query result `arch ar71xx 10` represents the ar71xx series architecture, so select the `smartdns.xxxxxxx.ar71xx.ipk` installation package.
```shell
Root@OpenWrt:# opkg print_architecture
Arch all 1
Arch noarch 1
Arch ar71xx 10
```
* **Please download from the Release page: [Download here](https://github.com/pymu/smartdns/releases)**
```shell
https://github.com/pymumu/smartdns/releases
```
* For the installation procedure, please refer to the following sections.
### Standard Linux system installation/Raspberry Pi, X86_64 system
--------------
1. Installation
Download the installation package like `smartdns.xxxxxxxx.armhf.deb` and upload it to the Linux system. Run the following command to install
```shell
dpkg -i smartdns.xxxxxxxx.armhf.deb
```
For X86-64 system, download the installation package like `smartdns.xxxxxxxx.x86-64.tar.gz` and upload it to the Linux system. Run the following command to install
```shell
tar zxf smartdns.xxxxxxxx.x86-64.tar.gz
cd smartdns
chmod +x ./install
./install -i
```
1. Configuration
After the installation is complete, you can configure the upstream server to smartdns. Refer to the `Configuration Parameters` for specific configuration parameters.
In general, you only need to add `server [IP]:port`, `server-tcp [IP]:port` configuration items.
Configure as many upstream DNS servers as possible, including servers at home and abroad. Please refer to the `Configuration Parameters` section for configuration parameters.
```shell
vi /etc/smartdns/smartdns.conf
```
1. Start Service
```shell
systemctl enable smartdns
systemctl start smartdns
```
1. Forwarding DNS request to SmartDNS
Modify the DNS server of the local router and configure the DNS server as SmartDNS.
* Log in to the router on the local network and configure the Raspberry Pi to assign a static IP address.
* Modify the WAN port or DHCP DNS to the Raspberry Pi IP address.
Note:
I. Each router configuration method is different. Please search Baidu for related configuration methods.
II. some routers may not support configuring custom DNS server. in this case, please modify the PC's, mobile phone's DNS server to the ip of Raspberry Pi.
1. Check if the service is configured successfully
Query domain name with `nslookup -querytype=ptr 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.
* The second DNS supports customizing more behavior.
1. What is the best practices for upstream server configuration?
Smartdns has a speed measurement mechanism. When configuring an upstream server, it is recommended to configure multiple upstream DNS servers, including servers in different regions, but the total number is recommended to be around 10. Recommended configuration
* Carrier DNS.
* Public DNS, such as `8.8.8.8`, `8.8.4.4`, `1.1.1.1`.
For specific domain names, if there is a pollution, you can enable the anti-pollution mechanism.
1. How to enable the audit log
The audit log records the domain name requested by the client. The record information includes the request time, the request IP address, the request domain name, and the request type. If you want to enable the audit log, configure `audit-enable yes` in the configuration file, `audit-size`, `Audit-file`, `audit-num` configure the audit log file size, the audit log file path, and the number of audit log files. The audit log file will be compressed to save space.
1. How to avoid DNS privacy leaks
By default, smartdns will send requests to all configured DNS servers. If the upstream DNS servers record DNS logs, it will result in a DNS privacy leak. To avoid privacy leaks, try the following steps:
* Use trusted DNS servers.
* Use TLS servers.
* Set up an upstream DNS server group.
1. How to block ads
Smartdns has a high-performance domain name matching algorithm. It is very efficient to filter advertisements by domain name. To block ads, you only need to configure records like the following configure. For example, if you block `*.ad.com`, configure as follows:
```sh
Address /ad.com/#
```
The suffix mode of the domain name, filtering *.ad.com, `#` means returning SOA record. If you want to only block IPV4 or IPV6 separately, add a number after `#`, such as `#4` is for IPV4 blocking. If you want to ignore some specific subdomains, you can configure it as follows. e.g., if you ignore `pass.ad.com`, you can configure it as follows:
```sh
Address /pass.ad.com/-
```
1. DNS query diversion
In some cases, some domain names need to be queried using a specific DNS server to do DNS diversion. such as.
```sh
.home -> 192.168.1.1
.office -> 10.0.0.1
```
The domain name ending in .home is sent to 192.168.1.1 for resolving
The domain name ending in .office is sent to 10.0.0.1 for resolving
Other domain names are resolved using the default mode.
The diversion configuration for this case is as follows:
```sh
# Upstream configuration, use -group to specify the group name, and -exclude-default-group to exclude the server from the default group.
Server 192.168.1.1 -group home -exclude-default-group
Server 10.0.0.1 -group office -exclude-default-group
Server 8.8.8.8
#Configure the resolved domain name with specific group
Nameserver /.home/home
Nameserver /.office/office
```
You can use the above configuration to implement DNS resolution and offload. If you need to implement traffic distribution on the requesting port, you can configure the second DNS server. The bind configuration is added. The group parameter specifies the traffic distribution name.
```sh
Bind :7053 -group office
Bind :8053 -group home
```
1. How to use the IPV4, IPV6 dual stack IP optimization feature
At present, IPV6 network is not as fast as IPV4 in some cases. In order to get a better experience in the dual-stack network, SmartDNS provides a dual-stack IP optimization mechanism, the same domain name, and the speed of IPV4. Far faster than IPV6, then SmartDNS will block the resolution of IPV6, let the PC use IPV4, the feature is enabled by `dualstack-ip-selection yes`, `dualstack-ip-selection-threshold [time]` is for threshold. if you want to disable IPV6 AAAA record complete, please try `force-AAAA-SOA yes`.
1. How to improve cache performace
Smartdns provides a domain name caching mechanism to cache the queried domain name, and the caching time is in accordance with the DNS TTL specification. To increase the cache hit rate, the following configuration can be taken:
* Increase the number of cache records appropriately
Set the number of cache records by `cache-size`.
In the case of a query with a high pressure environment and a machine with a large memory, it can be appropriately adjusted.
* Set the minimum TTL value as appropriate
Set the minimum DNS TTL time to a appropriate value by `rr-ttl-min` to extend the cache time.
It is recommended that the timeout period be set to 10 to 30 minutes to avoid then invalid domain names when domain ip changes.
* Enable domain pre-acquisition
Enable pre-fetching of domain names with `prefetch-domain yes` to improve query hit rate.
by default, Smartdns will send domain query request again before cache expire, and cache the result for the next query. Frequently accessed domain names will continue to be cached. This feature will consume more CPU when idle.
1. How does the second DNS customize more behavior?
The second DNS can be used as the upstream of other DNS servers to provide more query behaviors. Bind configuration support can bind multiple ports. Different ports can be set with different flags to implement different functions, such as
```sh
# Binding 6053 port, request for port 6053 will be configured with the upstream query of the office group, and the result will not be measured. The address configuration address is ignored.
bind [::]:6053 -no-speed-check -group office -no-rule-addr
```
## Compile
smartdns contains scripts for compiling packages, supports compiling luci, debian, openwrt, opare installation packages, and can execute `package/build-pkg.sh` compilation.
## [Donate](#Donate)
If you feel that this project is helpful to you, please donate to us so that the project can continue to develop and be more perfect.
### PayPal
[![Support via PayPal](https://cdn.rawgit.com/twolfson/paypal-github-button/1.0.0/dist/button.svg)](https://paypal.me/PengNick/)
### Alipay
![alipay](doc/alipay_donate.jpg)
### Wechat
![wechat](doc/wechat_donate.jpg)
## Open Source License
Smartdns is licensed to the public under the GPL V3 License.

View File

@@ -1,695 +0,0 @@
# SmartDNS
![SmartDNS](doc/smartdns-banner.png)
SmartDNS是一个运行在本地的DNS服务器SmartDNS接受本地客户端的DNS查询请求从多个上游DNS服务器获取DNS查询结果并将访问速度最快的结果返回给客户端避免DNS污染提高网络访问速度。
同时支持指定特定域名IP地址并高性匹配达到过滤广告的效果。
与dnsmasq的all-servers不同smartdns返回的是访问速度最快的解析结果。 (详细差异请看[FAQ](#faq))
支持树莓派openwrt华硕路由器windows等设备。
## 目录
1. [软件效果展示](#软件效果展示)
1. [特性](#特性)
1. [架构](#架构)
1. [使用](#使用)
1. [下载配套安装包](#下载配套安装包)
1. [标准Linux系统安装](#标准linux系统安装树莓派x86_64系统)
1. [openwrt/LEDE](#openwrtlede)
1. [华硕路由器原生固件/梅林固件](#华硕路由器原生固件梅林固件)
1. [optware/entware](#optwareentware)
1. [Windows 10 WSL安装/WSL ubuntu](#windows-10-wsl安装wsl-ubuntu)
1. [配置参数](#配置参数)
1. [捐助](#donate)
1. [声明](#声明)
1. [FAQ](#faq)
## 软件效果展示
**阿里DNS**
使用阿里DNS查询百度IP并检测结果。
```shell
pi@raspberrypi:~/code/smartdns_build $ nslookup www.baidu.com 223.5.5.5
Server: 223.5.5.5
Address: 223.5.5.5#53
Non-authoritative answer:
www.baidu.com canonical name = www.a.shifen.com.
Name: www.a.shifen.com
Address: 180.97.33.108
Name: www.a.shifen.com
Address: 180.97.33.107
pi@raspberrypi:~/code/smartdns_build $ ping 180.97.33.107 -c 2
PING 180.97.33.107 (180.97.33.107) 56(84) bytes of data.
64 bytes from 180.97.33.107: icmp_seq=1 ttl=55 time=24.3 ms
64 bytes from 180.97.33.107: icmp_seq=2 ttl=55 time=24.2 ms
--- 180.97.33.107 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 24.275/24.327/24.380/0.164 ms
pi@raspberrypi:~/code/smartdns_build $ ping 180.97.33.108 -c 2
PING 180.97.33.108 (180.97.33.108) 56(84) bytes of data.
64 bytes from 180.97.33.108: icmp_seq=1 ttl=55 time=31.1 ms
64 bytes from 180.97.33.108: icmp_seq=2 ttl=55 time=31.0 ms
--- 180.97.33.108 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 31.014/31.094/31.175/0.193 ms
```
**smartdns**
使用SmartDNS查询百度IP并检测结果。
```shell
pi@raspberrypi:~/code/smartdns_build $ nslookup www.baidu.com
Server: 192.168.1.1
Address: 192.168.1.1#53
Non-authoritative answer:
www.baidu.com canonical name = www.a.shifen.com.
Name: www.a.shifen.com
Address: 14.215.177.39
pi@raspberrypi:~/code/smartdns_build $ ping 14.215.177.39 -c 2
PING 14.215.177.39 (14.215.177.39) 56(84) bytes of data.
64 bytes from 14.215.177.39: icmp_seq=1 ttl=56 time=6.31 ms
64 bytes from 14.215.177.39: icmp_seq=2 ttl=56 time=5.95 ms
--- 14.215.177.39 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 5.954/6.133/6.313/0.195 ms
```
从对比看出smartdns找到访问www.baidu.com最快的IP地址这样访问百度比阿里DNS速度快5倍。
## 特性
1. **多DNS上游服务器**
支持配置多个上游DNS服务器并同时进行查询即使其中有DNS服务器异常也不会影响查询。
1. **返回最快IP地址**
支持从域名所属IP地址列表中查找到访问速度最快的IP地址并返回给客户端避免DNS污染提高网络访问速度。
1. **支持多种查询协议**
支持UDPTCPTLS, HTTPS查询以及非53端口查询有效避免DNS污染。
1. **特定域名IP地址指定**
支持指定域名的IP地址达到广告过滤效果避免恶意网站的效果。
1. **域名高性能后缀匹配**
支持域名后缀匹配模式简化过滤配置过滤20万条记录时间<1ms
1. **域名分流**
支持域名分流不同类型的域名到不同的DNS服务器查询。
1. **Linux/Windows多平台支持**
支持标准Linux系统树莓派openwrt系统各种固件华硕路由器原生固件。以及支持Windows 10 WSL (Windows Subsystem for Linux)。
1. **支持IPV4, IPV6双栈**
支持IPV4IPV6网络支持查询A, AAAA记录支持双栈IP速度优化并支持完全禁用IPV6 AAAA解析。
1. **高性能,占用资源少**
多线程异步IO模式cache缓存查询结果。
## 架构
![Architecture](doc/architecture.png)
1. SmartDNS接收本地网络设备的DNS查询请求如PC手机的查询请求。
2. SmartDNS将查询请求发送到多个上游DNS服务器可采用标准UDP查询非标准端口UDP查询及TCP查询。
3. 上游DNS服务器返回域名对应的Server IP地址列表。SmartDNS检测与本地网络访问速度最快的Server IP。
4. 将访问速度最快的Server IP返回给本地客户端。
## 使用
### 下载配套安装包
--------------
下载配套版本的SmartDNS安装包对应安装包配套关系如下。
|系统 |安装包|说明
|-----|-----|-----
|标准Linux系统(树莓派)| smartdns.xxxxxxxx.armhf.deb|支持树莓派Raspbian 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管理统一界面
* openwrt系统CPU架构比较多上述表格未列出所有支持系统请查看CPU架构后下载。
* merlin梅林固件理论和华硕固件一致所以根据硬件类型安装相应的ipk包即可。梅林暂时未验证有问题提交issue
* CPU架构可在路由器管理界面找到查看方法
登录路由器,点击`System`->`Software`,点击`Configuration` Tab页面在opkg安装源中可找到对应软件架构下载路径中可找到如下架构为ar71xx
```shell
src/gz chaos_calmer_base http://downloads.openwrt.org/chaos_calmer/15.05/ar71xx/generic/packages/base
```
* 或ssh登录系统后通过如下命令查询软件架构
* **openwrt系列命令**
```shell
opkg print_architecture
```
* **optware系列命令**
```shell
ipkg print_architecture
```
* **debian系列命令**
```shell
dpkg --print-architecture
```
* **例如**
下面的查询结果`arch ar71xx 10`表示ar71xx系列架构选择`smartdns.xxxxxxxx.ar71xx.ipk`安装包
```shell
root@OpenWrt:~# opkg print_architecture
arch all 1
arch noarch 1
arch ar71xx 10
```
* **请在Release页面下载[点击此处下载](https://github.com/pymumu/smartdns/releases)**
```shell
https://github.com/pymumu/smartdns/releases
```
* 各种设备的安装步骤,请参考后面的章节。
### 标准Linux系统安装/树莓派/X86_64系统
--------------
1. 安装
下载配套安装包`smartdns.xxxxxxxx.armhf.deb`并上传到Linux系统中。 执行如下命令安装
```shell
dpkg -i smartdns.xxxxxxxx.armhf.deb
```
x86系统下载配套安装包`smartdns.xxxxxxxx.x86-64.tar.gz`, 并上传到Linux系统中。 执行如下命令安装
```shell
tar zxf smartdns.xxxxxxxx.x86-64.tar.gz
cd smartdns
chmod +x ./install
./install -i
```
1. 修改配置
安装完成后可配置smartdns的上游服务器信息。具体配置参数参考`配置参数`说明。
一般情况下,只需要增加`server [IP]:port`, `server-tcp [IP]:port`配置项,
尽可能配置多个上游DNS服务器包括国内外的服务器。配置参数请查看`配置参数`章节。
```shell
vi /etc/smartdns/smartdns.conf
```
1. 启动服务
```shell
systemctl enable smartdns
systemctl start smartdns
```
1. 将DNS请求转发的SmartDNS解析。
修改本地路由器的DNS服务器将DNS服务器配置为SmartDNS。
* 登录到本地网络的路由器中配置树莓派分配静态IP地址。
* 修改WAN口或者DHCP DNS为树莓派IP地址。
注意:
I. 每款路由器配置方法不尽相同,请百度搜索相关的配置方法。
II.华为等路由器可能不支持配置DNS为本地IP请修改PC端手机端DNS服务器为树莓派IP。
1. 检测服务是否配置成功。
使用`nslookup -querytype=ptr 0.0.0.0`查询域名
看命令结果中的`name`项目是否显示为`smartdns`或`主机名`,如`smartdns`则表示生效
```shell
pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr 0.0.0.0
Server: 192.168.1.1
Address: 192.168.1.1#53
Non-authoritative answer:
0.0.0.0.in-addr.arpa name = smartdns.
```
### openwrt/LEDE
--------------
1. 安装
将软件使用winscp上传到路由器的/root目录执行如下命令安装
```shell
opkg install smartdns.xxxxxxxx.xxxx.ipk
opkg install luci-app-smartdns.xxxxxxxx.xxxx.all.ipk
```
1. 修改配置
登录openwrt管理页面打开`Services`->`SmartDNS`进行配置。
* 在`Upstream Servers`增加上游DNS服务器配置建议配置多个国内外DNS服务器。
* 在`Domain Address`指定特定域名的IP地址可用于广告屏蔽。
1. 启用服务
SmartDNS服务生效方法有两种`一种是直接作为主DNS服务``另一种是作为dnsmasq的上游`。
默认情况下SmartDNS采用第一种方式。如下两种方式根据需求选择即可。
1. 启用方法一作为主DNS(默认方案)
* **启用smartdns的53端口重定向**
登录路由器,点击`Services`->`SmartDNS`->`redirect`,选择`重定向53端口到SmartDNS`启用53端口转发。
* **检测转发服务是否配置成功**
使用`nslookup -querytype=ptr 0.0.0.0`查询域名
看命令结果中的`name`项目是否显示为`smartdns`或`主机名`,如`smartdns`则表示生效
```shell
pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr 0.0.0.0
Server: 192.168.1.1
Address: 192.168.1.1#53
Non-authoritative answer:
0.0.0.0.in-addr.arpa name = smartdns.
```
* **界面提示重定向失败**
* 检查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
```
### optware/entware
--------------
1. 准备
在使用此软件时需要确认路由器是否支持U盘并准备好U盘一个。
1. 安装SmartDNS
将软件使用winscp上传到路由器的`/tmp`目录。
```shell
ipkg install smartdns.xxxxxxx.mipsbig.ipk
```
1. 修改smartdns配置
```shell
vi /opt/etc/smartdns/smartdns.conf
```
另外如需支持IPV6可设置工作模式为`2`将dnsmasq的DNS服务禁用smartdns为主用DNS服务器。将文件`/opt/etc/smartdns/smartdns-opt.conf`,中的`SMARTDNS_WORKMODE`修改为2.
```shell
SMARTDNS_WORKMODE="2"
```
1. 重启路由器生效服务
待路由器启动后,使用`nslookup -querytype=ptr 0.0.0.0`查询域名
看命令结果中的`name`项目是否显示为`smartdns`或`主机名`,如`smartdns`则表示生效
```shell
pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr 0.0.0.0
Server: 192.168.1.1
Address: 192.168.1.1#53
Non-authoritative answer:
0.0.0.0.in-addr.arpa name = smartdns.
```
注意若服务没有自动启动则需要设置optwre/entware自动启动具体方法参考optware/entware的文档。
### Windows 10 WSL安装/WSL ubuntu
--------------
1. 安装Windows 10 WSL ubuntu系统
安装Windows 10 WSL运行环境发行版本选择ubuntu系统。安装步骤请参考[WSL安装说明](https://docs.microsoft.com/en-us/windows/wsl/install-win10)
1. 安装smartdns
下载安装包`smartdns.xxxxxxxx.x86_64.tar.gz`并解压到D盘根目录。解压后目录如下
```shell
D:\SMARTDNS
├─etc
│ ├─default
│ ├─init.d
│ └─smartdns
├─package
│ └─windows
├─src
└─systemd
```
双击`D:\smartdns\package\windows`目录下的`install.bat`进行安装。要求输入密码时,请输入`WLS ubuntu`的密码。
1. 修改配置
记事本打开`D:\smartdns\etc\smartdns`目录中的`smartdns.conf`配置文件配置smartdns。具体配置参数参考`配置参数`说明。
一般情况下,只需要增加`server [IP]:port`, `server-tcp [IP]:port`配置项,
尽可能配置多个上游DNS服务器包括国内外的服务器。配置参数请查看`配置参数`章节。
1. 重新加载配置
双击`D:\smartdns\package\windows`目录下的`reload.bat`进行安装。要求输入密码时,请输入`WLS ubuntu`的密码。
1. 将DNS请求转发的SmartDNS解析。
将Windows的默认DNS服务器修改为`127.0.0.1`,具体步骤参考[IP配置](https://support.microsoft.com/zh-cn/help/15089/windows-change-tcp-ip-settings)
1. 检测服务是否配置成功。
使用`nslookup -querytype=ptr 0.0.0.0`查询域名
看命令结果中的`name`项目是否显示为`smartdns`或`主机名`,如`smartdns`则表示生效
```shell
pi@raspberrypi:~/code/smartdns_build $ nslookup -querytype=ptr 0.0.0.0
Server: 192.168.1.1
Address: 192.168.1.1#53
Non-authoritative answer:
0.0.0.0.in-addr.arpa name = smartdns.
```
## 配置参数
|参数|功能|默认值|配置值|例子|
|--|--|--|--|--|
|server-name|DNS服务器名称|操作系统主机名/smartdns|符合主机名规格的字符串|server-name smartdns
|bind|DNS监听端口号|[::]:53|IP:PORT|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|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>`[-check-edns]`edns过滤。<br>`[-group [group] ...]`DNS服务器所属组比如office, foreign和nameserver配套使用。<br>`[-exclude-default-group]`将DNS服务器从默认组中排除| server 8.8.8.8:53 -blacklist-ip -check-edns -group g1
|server-tcp|上游TCP DNS|无|可重复<br>`[ip][:port]`服务器IP端口可选。<br>`[-blacklist-ip]`blacklist-ip参数指定使用blacklist-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>`[-blacklist-ip]`blacklist-ip参数指定使用blacklist-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>`[-blacklist-ip]`blacklist-ip参数指定使用blacklist-ip配置IP过滤结果。<br>`[-group [group] ...]`DNS服务器所属组比如office, foreign和nameserver配套使用。<br>`[-exclude-default-group]`将DNS服务器从默认组中排除| server-https https://cloudflare-dns.com/dns-query
|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
|blacklist-ip|黑名单IP地址|无|[ip/subnet],可重复| blacklist-ip 1.2.3.4/16
|force-AAAA-SOA|强制AAAA地址返回SOA|no|[yes\|no]|force-AAAA-SOA yes
|prefetch-domain|域名预先获取功能|no|[yes\|no]|prefetch-domain yes
|dualstack-ip-selection|双栈IP优选|no|[yes\|no]|dualstack-ip-selection yes
|dualstack-ip-selection-threshold|双栈IP优选阈值|30ms|毫秒|dualstack-ip-selection-threshold [0-1000]
## FAQ
1. SmartDNS和DNSMASQ有什么区别
SMARTDNS在设计上并不是替换DNSMASQ的SMARTDNS主要功能集中在DNS解析增强上增强部分有
* 多上游服务器并发请求,对结果进行测速后,返回最佳结果;
* addressipset域名匹配采用高效算法查询匹配更加快速高效路由器设备依然高效。
* 域名匹配支持忽略特定域名可单独匹配IPv4 IPV6支持多样化定制。
* 针对广告屏蔽功能做增强返回SOA屏蔽广告效果更佳
* IPV4IPV6双栈IP优选机制在双网情况下选择最快的网络通讯。
* 支持最新的TLS, HTTPS协议提供安全的DNS查询能力。
* DNS防抢答机制及多种机制避免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](doc/alipay_donate.jpg)
### Wechat 微信
![wechat](doc/wechat_donate.jpg)
## 声明
* `SmartDNS`著作权归属Nick Peng (pymumu at gmail.com)。
* `SmartDNS`为免费软件,用户可以非商业性地复制和使用`SmartDNS`。
* 禁止将 `SmartDNS` 用于商业用途。
* 使用本软件的风险由用户自行承担,在适用法律允许的最大范围内,对因使用本产品所产生的损害及风险,包括但不限于直接或间接的个人损害、商业赢利的丧失、贸易中断、商业信息的丢失或任何其它经济损失,不承担任何责任。
* 本软件不会未经用户同意收集任何用户信息。
## 说明
目前代码未开源,后续根据情况开源。

View File

@@ -1,4 +1,19 @@
#!/bin/sh
#
# Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
#
# smartdns is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# smartdns is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
### BEGIN INIT INFO
# Provides: smartdns

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]
@@ -72,39 +95,46 @@ 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] [-group [group] ...] [-exclude-default-group]
# 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.
# -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] [-group [group] ...] [-exclude-default-group]
# 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] [-spki-pin [sha256-pin]] [-group [group] ...] [-exclude-default-group]
# server-tls [IP]:[PORT] [-blacklist-ip] [-whitelist-ip] [-spki-pin [sha256-pin]] [-group [group] ...] [-exclude-default-group]
# -spki-pin: TLS spki pin to verify.
# Get SKPI with this command:
# -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] [-spki-pin [sha256-pin]] [-group [group] ...] [-exclude-default-group]
# 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
@@ -126,4 +156,3 @@ log-level info
# ipset /domain/[ipset|-]
# ipset /www.example.com/block, set ipset with ipset name of block
# ipset /www.example.com/-, ignore this domain

18
install
View File

@@ -1,7 +1,19 @@
#!/bin/sh
#
# Copyright (C) 2018 Ruilin Peng (Nick) <pymumu@gmail.com>
# Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
#
# smartdns is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# smartdns is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
INST_DIR=$(cd $(dirname $0);pwd)
ISWSL=1 # 1 means not WSL, 0 means wsl
@@ -82,7 +94,9 @@ install_files()
install -v -m 0755 -t $SMARTDNS_INIT_DIR etc/init.d/smartdns
if [ $? -ne 0 ]; then
return 1
if [ $ISSYSTEMD -ne 0 ]; then
return 1
fi
fi
if [ $ISSYSTEMD -eq 0 ]; then

180
package/build-pkg.sh Normal file
View File

@@ -0,0 +1,180 @@
#!/bin/sh
# Copyright (C) 2018-2019 Nick Peng (pymumu@gmail.com)
CURR_DIR=$(cd $(dirname $0);pwd)
VER="`date +"1.%Y.%m.%d-%H%M"`"
CODE_DIR="$CURR_DIR/.."
IS_BUILD_SMARTDNS=1
OUTPUTDIR=$CURR_DIR
export CC
export STRIP
showhelp()
{
echo "Usage: $0 [OPTION]"
echo "Options:"
echo " --platform [luci|debian|openwrt|optware|linux] build for platform. "
echo " --arch [all|armhf|arm64|x86_64|...] build for architecture, e.g. "
echo " --cross-tool [cross-tool] cross compiler, e.g. mips-openwrt-linux-"
echo ""
echo "Advance Options:"
echo " --static static link smartdns"
echo " --only-package only package, not build source"
echo " --filearch [arch] output file arch, default: equal --arch"
echo " --outputdir [dir] output package to specific directory"
echo " "
echo "Example:"
echo " build luci:"
echo " $0 --platform luci"
echo " build debian:"
echo " $0 --platform debian --arch x86_64"
echo " build raspbian pi:"
echo " $0 --platform debian --arch armhf"
echo " build optware mips:"
echo " $0 --platform optware --arch mipsbig"
echo " build openwrt mips:"
echo " $0 --platform openwrt --arch mips_24kc"
echo " build generic linux:"
echo " $0 --platform linux --arch x86_64"
}
build_smartdns()
{
if [ "$PLATFORM" != "luci" ]; then
make -C $CODE_DIR/src clean
make -C $CODE_DIR/src all -j8 VER=$VER $MAKE_ARGS
if [ $? -ne 0 ]; then
echo "make smartdns failed"
exit 1
fi
fi
$STRIP -d $CODE_DIR/src/smartdns >/dev/null 2>&1
return 0
}
build()
{
echo "build package for $PLATFORM"
if [ $IS_BUILD_SMARTDNS -eq 1 ]; then
build_smartdns
if [ $? -ne 0 ]; then
return 1
fi
fi
chmod +x $CODE_DIR/package/$PLATFORM/make.sh
$CODE_DIR/package/$PLATFORM/make.sh -o $CURR_DIR --arch $ARCH --ver $VER --filearch $FILEARCH -o $OUTPUTDIR
if [ $? -ne 0 ]; then
echo "build package for $PLATFORM failed"
return 1
fi
echo "build package for $PLATFORM success."
return 0
}
main()
{
OPTS=`getopt -o o:h --long arch:,filearch:,ver:,platform:,cross-tool:,static,only-package,outputdir: \
-n "" -- "$@"`
if [ "$#" -le "1" ]; then
showhelp
exit 1
fi
if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi
# Note the quotes around `$TEMP': they are essential!
eval set -- "$OPTS"
while true; do
case "$1" in
--arch)
ARCH="$2"
shift 2;;
--filearch)
FILEARCH="$2"
shift 2;;
--platform)
PLATFORM="$2"
shift 2;;
--cross-tool)
CROSS_TOOL="$2"
shift 2;;
--static)
export STATIC="yes"
shift 1;;
--only-package)
IS_BUILD_SMARTDNS=0
shift 1;;
--outputdir)
OUTPUTDIR="$2"
shift 2;;
--ver)
VER="$2"
shift 2;;
-h | --help )
showhelp
return 0
shift ;;
-- ) shift; break ;;
* ) break ;;
esac
done
if [ -z "$PLATFORM" ]; then
echo "please input platform"
echo "run $0 -h for help."
return 1
fi
if [ "$PLATFORM" = "luci" ]; then
ARCH="all"
fi
if [ -z "$ARCH" ]; then
echo "please input arch."
echo "run $0 -h for help."
return 1
fi
if [ -z "$FILEARCH" ]; then
FILEARCH="$ARCH"
fi
if [ -z "$OUTPUTDIR" ]; then
OUTPUTDIR=$CURR_DIR
fi
if [ ! -z "$CROSS_TOOL" ]; then
CC="${CROSS_TOOL}gcc"
STRIP="${CROSS_TOOL}strip"
fi
if [ -z "$CC" ]; then
CC="gcc"
fi
if [ -z "$STRIP" ]; then
if [ ! -z "`echo $CC | grep '\-gcc'`" ]; then
STRIP="`echo "$CC" | sed 's/-gcc\$/-strip/g'`"
else
STRIP="strip"
fi
fi
if [ ! -e "`which $CC`" ]; then
echo "Cannot find compiler $CC"
return 1
fi
build
}
main $@
exit $?

View File

@@ -3,5 +3,5 @@ Upstream-Name: smartdns
Source: http://github.com/pymumu/smartdns
Files: *
Copyright: 2018 Nick peng
Copyright: 2018-2019 Nick peng
License: proprietary

View File

@@ -1,5 +1,19 @@
#/bin/sh
#!/bin/sh
#
# Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
#
# smartdns is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# smartdns is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
CURR_DIR=$(cd $(dirname $0);pwd)
VER="`date +"1.%Y.%m.%d-%H%M"`"
SMARTDNS_DIR=$CURR_DIR/../../
@@ -11,42 +25,46 @@ showhelp()
echo "Options:"
echo " -o output directory."
echo " --arch archtecture."
echo " --ver version."
echo " --ver version."
echo " -h show this message."
}
build()
{
ROOT=/tmp/smartdns-deiban
rm -fr $ROOT
mkdir -p $ROOT
cd $ROOT/
ROOT=/tmp/smartdns-deiban
rm -fr $ROOT
mkdir -p $ROOT
cd $ROOT/
cp $CURR_DIR/DEBIAN $ROOT/ -af
CONTROL=$ROOT/DEBIAN/control
mkdir $ROOT/usr/sbin -p
mkdir $ROOT/etc/smartdns/ -p
mkdir $ROOT/etc/default/ -p
mkdir $ROOT/lib/systemd/system/ -p
cp $CURR_DIR/DEBIAN $ROOT/ -af
CONTROL=$ROOT/DEBIAN/control
mkdir $ROOT/usr/sbin -p
mkdir $ROOT/etc/smartdns/ -p
mkdir $ROOT/etc/default/ -p
mkdir $ROOT/lib/systemd/system/ -p
sed -i "s/Version:.*/Version: $VER/" $ROOT/DEBIAN/control
sed -i "s/Architecture:.*/Architecture: $ARCH/" $ROOT/DEBIAN/control
chmod 0755 $ROOT/DEBIAN/prerm
sed -i "s/Version:.*/Version: $VER/" $ROOT/DEBIAN/control
sed -i "s/Architecture:.*/Architecture: $ARCH/" $ROOT/DEBIAN/control
chmod 0755 $ROOT/DEBIAN/prerm
cp $SMARTDNS_DIR/etc/smartdns/smartdns.conf $ROOT/etc/smartdns/
cp $SMARTDNS_DIR/etc/default/smartdns $ROOT/etc/default/
cp $SMARTDNS_DIR/systemd/smartdns.service $ROOT/lib/systemd/system/
cp $SMARTDNS_DIR/src/smartdns $ROOT/usr/sbin
chmod +x $ROOT/usr/sbin/smartdns
cp $SMARTDNS_DIR/etc/smartdns/smartdns.conf $ROOT/etc/smartdns/
cp $SMARTDNS_DIR/etc/default/smartdns $ROOT/etc/default/
cp $SMARTDNS_DIR/systemd/smartdns.service $ROOT/lib/systemd/system/
cp $SMARTDNS_DIR/src/smartdns $ROOT/usr/sbin
if [ $? -ne 0 ]; then
echo "copy smartdns file failed."
return 1
fi
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/
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,31 +77,38 @@ main()
--arch)
ARCH="$2"
shift 2;;
--ver)
VER="$2"
shift 2;;
--filearch)
FILEARCH="$2"
shift 2;;
--ver)
VER="$2"
shift 2;;
-o )
OUTPUTDIR="$2"
shift 2;;
-h | --help )
-h | --help )
showhelp
return 0
shift ;;
-- ) shift; break ;;
* ) break ;;
esac
esac
done
if [ -z "$ARCH" ]; then
echo "please input arch."
return 1;
fi
if [ -z "$ARCH" ]; then
echo "please input arch."
return 1;
fi
if [ -z "$OUTPUTDIR" ]; then
OUTPUTDIR=$CURR_DIR;
fi
if [ -z "$FILEARCH" ]; then
FILEARCH=$ARCH
fi
build
if [ -z "$OUTPUTDIR" ]; then
OUTPUTDIR=$CURR_DIR;
fi
build
}
main $@

98
package/linux/make.sh Normal file
View File

@@ -0,0 +1,98 @@
#!/bin/sh
CURR_DIR=$(cd $(dirname $0);pwd)
VER="`date +"1.%Y.%m.%d-%H%M"`"
SMARTDNS_DIR=$CURR_DIR/../../
SMARTDNS_BIN=$SMARTDNS_DIR/src/smartdns
showhelp()
{
echo "Usage: make [OPTION]"
echo "Options:"
echo " -o output directory."
echo " --arch archtecture."
echo " --ver version."
echo " -h show this message."
}
build()
{
PKG_ROOT=/tmp/smartdns-linux
rm -fr $PKG_ROOT
mkdir -p $PKG_ROOT/smartdns
cd $PKG_ROOT/
# Generic x86_64
mkdir $PKG_ROOT/smartdns/src -p
mkdir $PKG_ROOT/smartdns/package -p
cd $SMARTDNS_DIR
cp package/windows $PKG_ROOT/smartdns/package/ -a
cp etc systemd *.md LICENSE install $PKG_ROOT/smartdns/ -a
cp src/smartdns $PKG_ROOT/smartdns/src -a
if [ $? -ne 0 ]; then
echo "copy smartdns file failed"
rm -fr $PKG_ROOT
exit 1
fi
cd $PKG_ROOT
tar zcf $OUTPUTDIR/smartdns.$VER.$FILEARCH.tar.gz smartdns
if [ $? -ne 0 ]; then
echo "create package failed"
rm -fr $PKG_ROOT
exit 1
fi
cd $CURR_DIR
rm -fr $PKG_ROOT
}
main()
{
OPTS=`getopt -o o:h --long arch:,ver:,filearch: \
-n "" -- "$@"`
if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi
# Note the quotes around `$TEMP': they are essential!
eval set -- "$OPTS"
while true; do
case "$1" in
--arch)
ARCH="$2"
shift 2;;
--filearch)
FILEARCH="$2"
shift 2;;
--ver)
VER="$2"
shift 2;;
-o )
OUTPUTDIR="$2"
shift 2;;
-h | --help )
showhelp
return 0
shift ;;
-- ) shift; break ;;
* ) break ;;
esac
done
if [ -z "$ARCH" ]; then
echo "please input arch."
return 1;
fi
if [ -z "$FILEARCH" ]; then
FILEARCH=$ARCH
fi
if [ -z "$OUTPUTDIR" ]; then
OUTPUTDIR=$CURR_DIR;
fi
build
}
main $@
exit $?

View File

@@ -1,4 +1,20 @@
#!/bin/sh
#
# Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
#
# smartdns is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# smartdns is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
[ "${IPKG_NO_SCRIPT}" = "1" ] && exit 0
[ -x ${IPKG_INSTROOT}/lib/functions.sh ] || exit 0
. ${IPKG_INSTROOT}/lib/functions.sh

View File

@@ -1,4 +1,20 @@
#!/bin/sh
#
# Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
#
# smartdns is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# smartdns is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
[ -x ${IPKG_INSTROOT}/lib/functions.sh ] || exit 0
. ${IPKG_INSTROOT}/lib/functions.sh
default_prerm $0 $@

View File

@@ -1,4 +1,19 @@
#!/bin/sh
#
# Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
#
# smartdns is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# smartdns is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
uci -q batch <<-EOF >/dev/null
delete ucitrack.@smartdns[-1]

View File

@@ -1,4 +1,18 @@
-- Copyright 2018 Nick Peng (pymumu@gmail.com)
--
-- Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
--
-- smartdns is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- smartdns is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
module("luci.controller.smartdns", package.seeall)
local smartdns = require "luci.model.smartdns"

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,10 +193,28 @@ 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 offlce, home."
msgid "DNS Server group belongs to, used with nameserver, such as office, home."
msgsr "DNS服务器所属组 配合nameserver使用例如officehome。"
msgid "IP Blacklist Filtering"

View File

@@ -1,4 +1,18 @@
-- Copyright 2018 Nick Peng (pymumu@gmail.com)
--
-- Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
--
-- smartdns is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- smartdns is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
require ("nixio.fs")
require ("luci.http")
@@ -16,6 +30,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 +107,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(""),

View File

@@ -1,3 +1,19 @@
--
-- Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
--
-- smartdns is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- smartdns is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
local sid = arg[1]
m = Map("smartdns", "%s - %s" %{translate("SmartDNS Server"), translate("Upstream DNS Server Configuration")})
@@ -39,8 +55,31 @@ 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 offlce, home."))
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"
@@ -55,13 +94,13 @@ 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:depends("type", "udp")
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."))
@@ -71,6 +110,7 @@ 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 = ""

View File

@@ -1,4 +1,18 @@
-- Copyright 2018 Nick Peng (pymumu@gmail.com)
--
-- Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
--
-- smartdns is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- smartdns is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
require ("nixio.fs")
require ("luci.http")

View File

@@ -1,5 +1,19 @@
#/bin/sh
#!/bin/sh
#
# Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
#
# smartdns is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# smartdns is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
CURR_DIR=$(cd $(dirname $0);pwd)
VER="`date +"1.%Y.%m.%d-%H%M"`"
@@ -12,63 +26,63 @@ showhelp()
echo "Options:"
echo " -o output directory."
echo " --arch archtecture."
echo " --ver version."
echo " --ver version."
echo " -h show this message."
}
build_tool()
{
make -C $ROOT/tool/po2lmo -j
PO2LMO="$ROOT/tool/po2lmo/src/po2lmo"
make -C $ROOT/tool/po2lmo -j
PO2LMO="$ROOT/tool/po2lmo/src/po2lmo"
}
clean_tool()
{
make -C $ROOT/tool/po2lmo clean
make -C $ROOT/tool/po2lmo clean
}
build()
{
ROOT=/tmp/luci-app-smartdns
rm -fr $ROOT
ROOT=/tmp/luci-app-smartdns
rm -fr $ROOT
mkdir -p $ROOT
cp $CURR_DIR/* $ROOT/ -af
cd $ROOT/
build_tool
mkdir $ROOT/root/usr/lib/lua/ -p
cp $ROOT/files/luci $ROOT/root/usr/lib/lua/ -af
#Generate Language
$PO2LMO $ROOT/files/luci/i18n/smartdns.zh-cn.po $ROOT/root/usr/lib/lua/luci/i18n/smartdns.zh-cn.lmo
rm $ROOT/root/usr/lib/lua/luci/i18n/smartdns.zh-cn.po
mkdir -p $ROOT
cp $CURR_DIR/* $ROOT/ -af
cd $ROOT/
build_tool
mkdir $ROOT/root/usr/lib/lua/ -p
cp $ROOT/files/luci $ROOT/root/usr/lib/lua/ -af
#Generate Language
$PO2LMO $ROOT/files/luci/i18n/smartdns.zh-cn.po $ROOT/root/usr/lib/lua/luci/i18n/smartdns.zh-cn.lmo
rm $ROOT/root/usr/lib/lua/luci/i18n/smartdns.zh-cn.po
cp $ROOT/files/etc $ROOT/root/ -af
INST_SIZE="`du -sb $ROOT/root/ | awk '{print $1}'`"
sed -i "s/^Architecture.*/Architecture: $ARCH/g" $ROOT/control/control
sed -i "s/Version:.*/Version: $VER/" $ROOT/control/control
cp $ROOT/files/etc $ROOT/root/ -af
INST_SIZE="`du -sb $ROOT/root/ | awk '{print $1}'`"
sed -i "s/^Architecture.*/Architecture: all/g" $ROOT/control/control
sed -i "s/Version:.*/Version: $VER/" $ROOT/control/control
if [ ! -z "$INST_SIZE" ]; then
echo "Installed-Size: $INST_SIZE" >> $ROOT/control/control
fi
if [ ! -z "$INST_SIZE" ]; then
echo "Installed-Size: $INST_SIZE" >> $ROOT/control/control
fi
cd $ROOT/control
chmod +x *
tar zcf ../control.tar.gz ./
cd $ROOT
cd $ROOT/control
chmod +x *
tar zcf ../control.tar.gz ./
cd $ROOT
tar zcf $ROOT/data.tar.gz -C root .
tar zcf $OUTPUTDIR/luci-app-smartdns.$VER.$ARCH.ipk control.tar.gz data.tar.gz debian-binary
tar zcf $ROOT/data.tar.gz -C root .
tar zcf $OUTPUTDIR/luci-app-smartdns.$VER.$FILEARCH.ipk control.tar.gz data.tar.gz debian-binary
rm -fr $ROOT/
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,31 +95,38 @@ main()
--arch)
ARCH="$2"
shift 2;;
--ver)
VER="$2"
shift 2;;
--filearch)
FILEARCH="$2"
shift 2;;
--ver)
VER="$2"
shift 2;;
-o )
OUTPUTDIR="$2"
shift 2;;
-h | --help )
-h | --help )
showhelp
return 0
shift ;;
-- ) shift; break ;;
* ) break ;;
esac
esac
done
if [ -z "$ARCH" ]; then
echo "please input arch."
return 1;
fi
if [ -z "$ARCH" ]; then
echo "please input arch."
return 1;
fi
if [ -z "$OUTPUTDIR" ]; then
OUTPUTDIR=$CURR_DIR;
fi
if [ -z "$FILEARCH" ]; then
FILEARCH=$ARCH
fi
build
if [ -z "$OUTPUTDIR" ]; then
OUTPUTDIR=$CURR_DIR;
fi
build
}
main $@

View File

@@ -1,34 +1,75 @@
#
# Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
#
# smartdns is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# smartdns is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
include $(TOPDIR)/rules.mk
PKG_NAME:=smarttdns
PKG_VERSION:=2018.7.1.1607
PKG_RELEASE:=$(PKG_SOURCE_VERSION)
PKG_NAME:=smartdns
PKG_BUILD_DIR := $(BUILD_DIR)/$(PKG_NAME)-$(PKG_VERSION)
PKG_SOURCE_PROTO:=git
PKG_SOURCE_URL:=https://github.com/pymumu/smartdns.git
PKG_REV:=d51f5e6eeba7bfde1b108fe32d540bd429550573
PKG_VERSION:=1.2019.11.02-1102
PKG_RELEASE:=1
PKG_LICENSE:=GPL-3.0
PKG_SOURCE_VERSION:=$(PKG_REV)
PKG_SOURCE_SUBDIR:=$(PKG_NAME)-$(PKG_VERSION)
PKG_SOURCE:=$(PKG_SOURCE_SUBDIR).tar.gz
PKG_BUILD_DIR:=$(BUILD_DIR)/$(PKG_SOURCE_SUBDIR)
include $(INCLUDE_DIR)/package.mk
MAKE_ARGS := CFLAGS="$(TARGET_CFLAGS)" CC=$(TARGET_CC)
define Package/smartdns
SECTION:=net
CATEGORY:=Network
TITLE:=smartdns
URL:=https://github.com/pymumu/smartdns
MAINTAINER:=Nick Peng <pymumu@gmail.com>
DEPENDS:=
SECTION:=net
CATEGORY:=Network
TITLE:=smartdns server
URL:=http://github.com/pymumu/smartdns/
MAINTAINER:=Nick Peng <pymumu@gmail.com>
DEPENDS:=+libopenssl
endef
define Package/smartdns/description
smartdns server, find fastest ip.
SmartDNS is a local DNS server. SmartDNS accepts DNS query requests from local clients, obtains DNS query results from multiple upstream DNS servers, and returns the fastest access results to clients.
endef
define Build/Prepare
mkdir -p $(PKG_BUILD_DIR)
cp -r ../* $(PKG_BUILD_DIR)
define Build/Configure
mkdir -p $(PKG_INSTALL_DIR)
endef
define Build/Compile
$(MAKE) -C $(PKG_BUILD_DIR)/src $(MAKE_ARGS) all
endef
define Package/smartdns/conffiles
/etc/config/smartdns
/etc/smartdns/address.conf
/etc/smartdns/blacklist-ip.conf
/etc/smartdns/custom.conf
endef
define Package/smartdns/install
$(INSTALL_DIR) $(1)/usr/sbin
$(INSTALL_BIN) $(PKG_BUILD_DIR)/smartdns $(1)/usr/sbin
$(INSTALL_DIR) $(1)/usr/sbin $(1)/etc/config $(1)/etc/init.d $(1)/etc/smartdns
$(INSTALL_BIN) $(PKG_BUILD_DIR)/src/smartdns $(1)/usr/sbin/smartdns
$(INSTALL_BIN) $(PKG_BUILD_DIR)/package/openwrt/files/etc/init.d/smartdns $(1)/etc/init.d/smartdns
$(INSTALL_CONF) $(PKG_BUILD_DIR)/package/openwrt/address.conf $(1)/etc/smartdns/address.conf
$(INSTALL_CONF) $(PKG_BUILD_DIR)/package/openwrt/blacklist-ip.conf $(1)/etc/smartdns/blacklist-ip.conf
$(INSTALL_CONF) $(PKG_BUILD_DIR)/package/openwrt/custom.conf $(1)/etc/smartdns/custom.conf
$(INSTALL_CONF) $(PKG_BUILD_DIR)/package/openwrt/files/etc/config/smartdns $(1)/etc/config/smartdns
endef
$(eval $(call BuildPackage, smartdns))
$(eval $(call BuildPackage,smartdns))

View File

@@ -1,4 +1,19 @@
#!/bin/sh
#
# Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
#
# smartdns is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# smartdns is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
chmod +x /usr/sbin/smartdns
chmod +x /etc/init.d/smartdns

View File

@@ -1,4 +1,20 @@
#!/bin/sh
#
# Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
#
# smartdns is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# smartdns is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
. ${IPKG_INSTROOT}/lib/functions.sh
default_prerm $0 $@
rm /var/etc/smartdns.conf -f

View File

@@ -1,5 +1,19 @@
#!/bin/sh /etc/rc.common
# Copyright (C) 2018 Nick Peng (pymumu@gmail.com)
#
# Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
#
# smartdns is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# smartdns is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
START=99
NAME=smartdns
@@ -126,6 +140,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,6 +174,9 @@ 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"
@@ -165,6 +206,18 @@ load_server()
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
@@ -194,7 +247,75 @@ load_server()
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=""
@@ -313,6 +434,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
@@ -326,6 +449,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}
@@ -334,12 +462,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

@@ -1,5 +1,19 @@
#/bin/sh
#!/bin/sh
#
# Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
#
# smartdns is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# smartdns is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
CURR_DIR=$(cd $(dirname $0);pwd)
VER="`date +"1.%Y.%m.%d-%H%M"`"
@@ -16,52 +30,57 @@ showhelp()
echo "Options:"
echo " -o output directory."
echo " --arch archtecture."
echo " --ver version."
echo " --ver version."
echo " -h show this message."
}
build()
{
ROOT=/tmp/smartdns-openwrt
rm -fr $ROOT
ROOT=/tmp/smartdns-openwrt
rm -fr $ROOT
mkdir -p $ROOT
cp $CURR_DIR/* $ROOT/ -af
cd $ROOT/
mkdir $ROOT/root/usr/sbin -p
mkdir $ROOT/root/etc/init.d -p
mkdir $ROOT/root/etc/smartdns/ -p
mkdir -p $ROOT
cp $CURR_DIR/* $ROOT/ -af
cd $ROOT/
mkdir $ROOT/root/usr/sbin -p
mkdir $ROOT/root/etc/init.d -p
mkdir $ROOT/root/etc/smartdns/ -p
cp $SMARTDNS_CONF $ROOT/root/etc/smartdns/
cp $ADDRESS_CONF $ROOT/root/etc/smartdns/
cp $BLACKLIST_IP_CONF $ROOT/root/etc/smartdns/
cp $CUSTOM_CONF $ROOT/root/etc/smartdns/
cp $CURR_DIR/files/etc $ROOT/root/ -af
cp $SMARTDNS_BIN $ROOT/root/usr/sbin
cp $SMARTDNS_CONF $ROOT/root/etc/smartdns/
cp $ADDRESS_CONF $ROOT/root/etc/smartdns/
cp $BLACKLIST_IP_CONF $ROOT/root/etc/smartdns/
cp $CUSTOM_CONF $ROOT/root/etc/smartdns/
cp $CURR_DIR/files/etc $ROOT/root/ -af
cp $SMARTDNS_BIN $ROOT/root/usr/sbin
if [ $? -ne 0 ]; then
echo "copy smartdns file failed."
rm -fr $ROOT/
return 1
fi
chmod +x $ROOT/root/etc/init.d/smartdns
INST_SIZE="`du -sb $ROOT/root/ | awk '{print $1}'`"
chmod +x $ROOT/root/etc/init.d/smartdns
INST_SIZE="`du -sb $ROOT/root/ | awk '{print $1}'`"
sed -i "s/^Architecture.*/Architecture: $ARCH/g" $ROOT/control/control
sed -i "s/Version:.*/Version: $VER/" $ROOT/control/control
sed -i "s/^\(bind .*\):53/\1:6053/g" $ROOT/root/etc/smartdns/smartdns.conf
if [ ! -z "$INST_SIZE" ]; then
echo "Installed-Size: $INST_SIZE" >> $ROOT/control/control
fi
sed -i "s/^Architecture.*/Architecture: $ARCH/g" $ROOT/control/control
sed -i "s/Version:.*/Version: $VER/" $ROOT/control/control
sed -i "s/^\(bind .*\):53/\1:6053/g" $ROOT/root/etc/smartdns/smartdns.conf
if [ ! -z "$INST_SIZE" ]; then
echo "Installed-Size: $INST_SIZE" >> $ROOT/control/control
fi
cd $ROOT/control
chmod +x *
tar zcf ../control.tar.gz --owner=0 --group=0 ./
cd $ROOT
cd $ROOT/control
chmod +x *
tar zcf ../control.tar.gz --owner=0 --group=0 ./
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
rm -fr $ROOT/
tar zcf $ROOT/data.tar.gz -C root --owner=0 --group=0 .
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,31 +93,38 @@ main()
--arch)
ARCH="$2"
shift 2;;
--ver)
VER="$2"
shift 2;;
--filearch)
FILEARCH="$2"
shift 2;;
--ver)
VER="$2"
shift 2;;
-o )
OUTPUTDIR="$2"
shift 2;;
-h | --help )
-h | --help )
showhelp
return 0
shift ;;
-- ) shift; break ;;
* ) break ;;
esac
esac
done
if [ -z "$ARCH" ]; then
echo "please input arch."
return 1;
fi
if [ -z "$ARCH" ]; then
echo "please input arch."
return 1;
fi
if [ -z "$OUTPUTDIR" ]; then
OUTPUTDIR=$CURR_DIR;
fi
if [ -z "$FILEARCH" ]; then
FILEARCH=$ARCH
fi
build
if [ -z "$OUTPUTDIR" ]; then
OUTPUTDIR=$CURR_DIR;
fi
build
}
main $@

View File

@@ -1,9 +1,24 @@
#! /bin/sh
#!/bin/sh
#
# Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
#
# smartdns is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# smartdns is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
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 +65,44 @@ clear_iptable()
}
restart_dnsmasq()
get_dnsmasq_cmd()
{
CMD="`ps | grep " dnsmasq" | grep -v grep 2>/dev/null`"
if [ -z "$CMD" ]; then
CMD="`ps ax | grep dnsmasq | grep -v grep 2>/dev/null`"
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 +123,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 +132,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 +145,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 +233,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 +274,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 +304,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

@@ -1,4 +1,19 @@
#! /bin/sh
#!/bin/sh
#
# Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
#
# smartdns is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# smartdns is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
chmod +x /opt/usr/sbin/smartdns
chmod +x /opt/etc/init.d/S50smartdns

View File

@@ -1,3 +1,18 @@
#! /bin/sh
#!/bin/sh
#
# Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
#
# smartdns is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# smartdns is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
/opt/etc/init.d/S50smartdns stop

View File

@@ -1,5 +1,19 @@
#/bin/sh
#!/bin/sh
#
# Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
#
# smartdns is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# smartdns is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
CURR_DIR=$(cd $(dirname $0);pwd)
VER="`date +"1.%Y.%m.%d-%H%M"`"
SMARTDNS_DIR=$CURR_DIR/../../
@@ -13,44 +27,49 @@ showhelp()
echo "Options:"
echo " -o output directory."
echo " --arch archtecture."
echo " --ver version."
echo " --ver version."
echo " -h show this message."
}
build()
{
ROOT=/tmp/smartdns-optware
rm -fr $ROOT
ROOT=/tmp/smartdns-optware
rm -fr $ROOT
mkdir -p $ROOT
cp $CURR_DIR/* $ROOT/ -af
cd $ROOT/
mkdir $ROOT/opt/usr/sbin -p
mkdir $ROOT/opt/etc/init.d -p
mkdir $ROOT/opt/etc/smartdns/ -p
mkdir -p $ROOT
cp $CURR_DIR/* $ROOT/ -af
cd $ROOT/
mkdir $ROOT/opt/usr/sbin -p
mkdir $ROOT/opt/etc/init.d -p
mkdir $ROOT/opt/etc/smartdns/ -p
cp $SMARTDNS_CONF $ROOT/opt/etc/smartdns/
cp $SMARTDNS_OPT $ROOT/opt/etc/smartdns/
cp $CURR_DIR/S50smartdns $ROOT/opt/etc/init.d/
cp $SMARTDNS_BIN $ROOT/opt/usr/sbin
cp $SMARTDNS_CONF $ROOT/opt/etc/smartdns/
cp $SMARTDNS_OPT $ROOT/opt/etc/smartdns/
cp $CURR_DIR/S50smartdns $ROOT/opt/etc/init.d/
cp $SMARTDNS_BIN $ROOT/opt/usr/sbin
if [ $? -ne 0 ]; then
echo "copy smartdns file failed."
rm -fr $ROOT/
return 1
fi
sed -i "s/# *server-name smartdns/server-name smartdns/g" $ROOT/opt/etc/smartdns/smartdns.conf
sed -i "s/^Architecture.*/Architecture: $ARCH/g" $ROOT/control/control
sed -i "s/Version:.*/Version: $VER/" $ROOT/control/control
sed -i "s/# *server-name smartdns/server-name smartdns/g" $ROOT/opt/etc/smartdns/smartdns.conf
sed -i "s/^Architecture.*/Architecture: $ARCH/g" $ROOT/control/control
sed -i "s/Version:.*/Version: $VER/" $ROOT/control/control
cd $ROOT/control
chmod +x *
tar zcf ../control.tar.gz --owner=0 --group=0 ./
cd $ROOT
cd $ROOT/control
chmod +x *
tar zcf ../control.tar.gz --owner=0 --group=0 ./
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
rm -fr $ROOT/
tar zcf data.tar.gz --owner=0 --group=0 opt
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,31 +82,38 @@ main()
--arch)
ARCH="$2"
shift 2;;
--ver)
VER="$2"
shift 2;;
--filearch)
FILEARCH="$2"
shift 2;;
--ver)
VER="$2"
shift 2;;
-o )
OUTPUTDIR="$2"
shift 2;;
-h | --help )
-h | --help )
showhelp
return 0
shift ;;
-- ) shift; break ;;
* ) break ;;
esac
esac
done
if [ -z "$ARCH" ]; then
echo "please input arch."
return 1;
fi
if [ -z "$ARCH" ]; then
echo "please input arch."
return 1;
fi
if [ -z "$OUTPUTDIR" ]; then
OUTPUTDIR=$CURR_DIR;
fi
if [ -z "$FILEARCH" ]; then
FILEARCH=$ARCH
fi
build
if [ -z "$OUTPUTDIR" ]; then
OUTPUTDIR=$CURR_DIR;
fi
build
}
main $@

View File

@@ -1,13 +1,35 @@
# Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
#
# smartdns is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# smartdns is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
BIN=smartdns
OBJS_LIB=lib/rbtree.o lib/art.o lib/bitops.o lib/radix.o lib/conf.o
OBJS=smartdns.o fast_ping.o dns_client.o dns_server.o dns.o util.o tlog.o dns_conf.o dns_cache.o http_parse.o $(OBJS_LIB)
CFLAGS +=-O2 -g -Wall -Wstrict-prototypes -fno-omit-frame-pointer -Wstrict-aliasing
CFLAGS +=-Iinclude
CFLAGS += -DBASE_FILE_NAME=\"$(notdir $<)\"
override CFLAGS +=-Iinclude
override CFLAGS += -DBASE_FILE_NAME=\"$(notdir $<)\"
ifdef VER
override CFLAGS += -DSMARTDNS_VERION=\"$(VER)\"
endif
CXXFLAGS=-O2 -g -Wall -std=c++11
CXXFLAGS +=-Iinclude
LDFLAGS += -lpthread -lssl -lcrypto
override CXXFLAGS +=-Iinclude
ifeq ($(STATIC), yes)
LDFLAGS += -lssl -lcrypto -Wl,--whole-archive -lpthread -Wl,--no-whole-archive -ldl -static
else
LDFLAGS += -lssl -lcrypto -lpthread
endif
.PHONY: all

View File

@@ -1,6 +1,6 @@
/*************************************************************************
*
* Copyright (C) 2018 Ruilin Peng (Nick) <pymumu@gmail.com>.
* Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
*
* smartdns is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -19,6 +19,7 @@
#define _GNU_SOURCE
#include "dns.h"
#include "tlog.h"
#include "stringutil.h"
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
@@ -264,6 +265,7 @@ static int _dns_add_qr_head(struct dns_data_context *data_context, char *domain,
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 |
@@ -277,6 +279,7 @@ static int _dns_get_qr_head(struct dns_data_context *data_context, char *domain,
domain++;
data_context->ptr++;
i++;
is_read_all = 1;
break;
}
*domain = *data_context->ptr;
@@ -285,6 +288,9 @@ static int _dns_get_qr_head(struct dns_data_context *data_context, char *domain,
}
*domain = '\0';
if (is_read_all == 0) {
return -1;
}
if (_dns_data_left_len(data_context) < 4) {
return -1;
@@ -612,19 +618,19 @@ 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;
memcpy(ptr, &soa->serial, sizeof(unsigned int));
ptr += 4;
*((unsigned int *)ptr) = soa->refresh;
memcpy(ptr, &soa->refresh, sizeof(unsigned int));
ptr += 4;
*((unsigned int *)ptr) = soa->retry;
memcpy(ptr, &soa->retry, sizeof(unsigned int));
ptr += 4;
*((unsigned int *)ptr) = soa->expire;
memcpy(ptr, &soa->expire, sizeof(unsigned int));
ptr += 4;
*((unsigned int *)ptr) = soa->minimum;
memcpy(ptr, &soa->minimum, sizeof(unsigned int));
ptr += 4;
len = ptr - data;
@@ -650,12 +656,12 @@ int dns_get_SOA(struct dns_rrs *rrs, char *domain, int maxsize, int *ttl, struct
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;
@@ -955,7 +961,7 @@ static int _dns_decode_domain(struct dns_context *context, char *output, int siz
}
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;
@@ -973,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;
}
@@ -982,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);

View File

@@ -1,3 +1,21 @@
/*************************************************************************
*
* Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
*
* smartdns is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* smartdns is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _DNS_HEAD_H
#define _DNS_HEAD_H

View File

@@ -1,7 +1,30 @@
/*************************************************************************
*
* Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
*
* smartdns is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* smartdns is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#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;
@@ -24,7 +47,7 @@ int dns_cache_init(int size)
return 0;
}
static __attribute__((unused)) 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);
}
@@ -110,7 +133,7 @@ int dns_cache_replace(char *domain, char *cname, int cname_ttl, int ttl, dns_typ
}
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);
@@ -119,7 +142,7 @@ int dns_cache_replace(char *domain, char *cname, int cname_ttl, int ttl, dns_typ
return 0;
errout_unlock:
pthread_mutex_unlock(&dns_cache_head.lock);
//errout:
// errout:
if (dns_cache) {
dns_cache_release(dns_cache);
}
@@ -154,11 +177,12 @@ 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;
atomic_set(&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);
@@ -178,7 +202,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;
}
@@ -273,13 +297,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);
atomic_inc(&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);
}

View File

@@ -1,3 +1,21 @@
/*************************************************************************
*
* Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
*
* smartdns is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* smartdns is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _SMARTDNS_CACHE_H
#define _SMARTDNS_CACHE_H
@@ -9,6 +27,10 @@
#include <stdlib.h>
#include <time.h>
#ifdef __cpluscplus
extern "C" {
#endif
#define DNS_CACHE_TTL_MIN 30
struct dns_cache {
@@ -19,9 +41,10 @@ struct dns_cache {
char domain[DNS_MAX_CNAME_LEN];
char cname[DNS_MAX_CNAME_LEN];
unsigned int cname_ttl;
unsigned int ttl;;
unsigned int ttl;
int speed;
atomic_t hitnum;
int hitnum_update_add;
int del_pending;
time_t insert_time;
dns_type_t qtype;
@@ -46,6 +69,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);
@@ -56,4 +81,7 @@ int dns_cache_get_ttl(struct dns_cache *dns_cache);
void dns_cache_destroy(void);
#ifdef __cpluscplus
}
#endif
#endif // !_SMARTDNS_CACHE_H

File diff suppressed because it is too large Load Diff

View File

@@ -1,8 +1,31 @@
/*************************************************************************
*
* Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
*
* smartdns is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* smartdns is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _SMART_DNS_CLIENT_H
#define _SMART_DNS_CLIENT_H
#include "dns.h"
#define DNS_SERVER_SPKI_LEN 64
#ifdef __cpluscplus
extern "C" {
#endif
#define DNS_SERVER_SPKI_LEN 64
#define DNS_SERVER_GROUP_DEFAULT "default"
typedef enum {
@@ -20,8 +43,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);
@@ -43,14 +67,17 @@ struct client_dns_server_flag_udp {
struct client_dns_server_flag_tls {
char spki[DNS_SERVER_SPKI_LEN];
int spi_len;
char host[DNS_MAX_CNAME_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 host[DNS_MAX_CNAME_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 {
@@ -83,4 +110,7 @@ int dns_client_remove_group(char *group_name);
int dns_server_num(void);
#ifdef __cpluscplus
}
#endif
#endif

View File

@@ -1,15 +1,33 @@
/*************************************************************************
*
* Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
*
* smartdns is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* smartdns is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "dns_conf.h"
#include "list.h"
#include "rbtree.h"
#include "tlog.h"
#include "util.h"
#include <getopt.h>
#include <libgen.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <unistd.h>
#include <libgen.h>
#define DEFAULT_DNS_CACHE_SIZE 512
@@ -23,8 +41,8 @@ static struct dns_ipset_table dns_ipset_table;
struct dns_group_table dns_group_table;
/* server ip/port */
char dns_conf_server_ip[DNS_MAX_IPLEN];
char dns_conf_server_tcp_ip[DNS_MAX_IPLEN];
struct dns_bind_ip dns_conf_bind_ip[DNS_MAX_BIND_IP];
int dns_conf_bind_ip_num = 0;
int dns_conf_tcp_idle_time = 120;
/* cache */
@@ -33,9 +51,14 @@ int dns_conf_prefetch = 0;
/* upstream servers */
struct dns_servers dns_conf_servers[DNS_MAX_SERVERS];
char dns_conf_server_name[DNS_MAX_CONF_CNAME_LEN];
char dns_conf_server_name[DNS_MAX_SERVER_NAME_LEN];
int dns_conf_server_num;
struct dns_domain_check_order dns_conf_check_order = {
.order = {DOMAIN_CHECK_ICMP, DOMAIN_CHECK_TCP},
.tcp_port = 80,
};
/* logging */
int dns_conf_log_level = TLOG_ERROR;
char dns_conf_log_file[DNS_MAX_PATH];
@@ -44,6 +67,7 @@ int dns_conf_log_num = 8;
/* auditing */
int dns_conf_audit_enable = 0;
int dns_conf_audit_log_SOA;
char dns_conf_audit_file[DNS_MAX_PATH];
size_t dns_conf_audit_size = 1024 * 1024;
int dns_conf_audit_num = 2;
@@ -90,7 +114,7 @@ static struct dns_server_groups *_dns_conf_get_group(const char *group_name)
}
memset(group, 0, sizeof(*group));
strncpy(group->group_name, group_name, DNS_GROUP_NAME_LEN);
safe_strncpy(group->group_name, group_name, DNS_GROUP_NAME_LEN);
hash_add(dns_group_table.group, &group->node, key);
return group;
@@ -168,9 +192,15 @@ static int _config_server(int argc, char *argv[], dns_server_type_t type, int de
/* clang-format off */
static struct option long_options[] = {
{"blacklist-ip", no_argument, NULL, 'b'}, /* filtering with blacklist-ip */
{"whitelist-ip", no_argument, NULL, 'w'}, /* filtering with whitelist-ip */
#ifdef FEATURE_CHECK_EDNS
/* experimental feature */
{"check-edns", no_argument, NULL, 'e'}, /* check edns */
#endif
{"spki-pin", required_argument, NULL, 'p'}, /* check SPKI pin */
{"check-ttl", required_argument, NULL, 't'}, /* check ttl */
{"host-name", required_argument, NULL, 'h'}, /* host name */
{"http-host", required_argument, NULL, 'H'}, /* http host */
{"tls-host-verify", required_argument, NULL, 'V' }, /* verify tls hostname */
{"group", required_argument, NULL, 'g'}, /* add to group */
{"exclude-default-group", no_argument, NULL, 'E'}, /* ecluse this from default group */
{NULL, no_argument, NULL, 0}
@@ -190,6 +220,8 @@ static int _config_server(int argc, char *argv[], dns_server_type_t type, int de
server->spki[0] = '\0';
server->path[0] = '\0';
server->hostname[0] = '\0';
server->httphost[0] = '\0';
server->tls_host_verify[0] = '\0';
ip = argv[1];
@@ -197,9 +229,10 @@ static int _config_server(int argc, char *argv[], dns_server_type_t type, int de
if (parse_uri(ip, NULL, server->server, &port, server->path) != 0) {
return -1;
}
strncpy(server->hostname, server->server, sizeof(server->hostname));
safe_strncpy(server->hostname, server->server, sizeof(server->hostname));
safe_strncpy(server->httphost, server->server, sizeof(server->httphost));
if (server->path[0] == 0) {
strcpy(server->path, "/");
safe_strncpy(server->path, "/", sizeof(server->path));
}
} else {
/* parse ip, port from ip */
@@ -226,25 +259,20 @@ static int _config_server(int argc, char *argv[], dns_server_type_t type, int de
result_flag |= DNSSERVER_FLAG_BLACKLIST_IP;
break;
}
case 'w': {
result_flag |= DNSSERVER_FLAG_WHITELIST_IP;
break;
}
case 'e': {
result_flag |= DNSSERVER_FLAG_CHECK_EDNS;
break;
}
case 't': {
if (DNS_SERVER_UDP != type) {
break;
}
ttl = atoi(optarg);
/* Greater than 0, exact match
Equal to 0, match after check
Less than 0, match in the -N range after inspection
*/
if (ttl < -255 || ttl > 255) {
tlog(TLOG_ERROR, "ttl value is invalid.");
goto errout;
}
result_flag |= DNSSERVER_FLAG_CHECK_TTL;
case 'h': {
safe_strncpy(server->hostname, optarg, DNS_MAX_CNAME_LEN);
break;
}
case 'H': {
safe_strncpy(server->httphost, optarg, DNS_MAX_CNAME_LEN);
break;
}
case 'E': {
@@ -259,7 +287,11 @@ static int _config_server(int argc, char *argv[], dns_server_type_t type, int de
break;
}
case 'p': {
strncpy(server->spki, optarg, DNS_MAX_SPKI_LEN);
safe_strncpy(server->spki, optarg, DNS_MAX_SPKI_LEN);
break;
}
case 'V': {
safe_strncpy(server->tls_host_verify, optarg, DNS_MAX_CNAME_LEN);
break;
}
default:
@@ -338,7 +370,11 @@ static int _config_domain_rule_add(char *domain, enum domain_rule type, void *ru
/* Reverse string, for suffix match */
len = strlen(domain);
reverse_string(domain_key, domain, len);
if (len >= sizeof(domain_key)) {
tlog(TLOG_ERROR, "domain name %s too long", domain);
goto errout;
}
reverse_string(domain_key, domain, len, 1);
domain_key[len] = '.';
len++;
domain_key[len] = 0;
@@ -395,7 +431,11 @@ static int _config_domain_rule_flag_set(char *domain, unsigned int flag)
int len = 0;
len = strlen(domain);
reverse_string(domain_key, domain, len);
if (len >= sizeof(domain_key)) {
tlog(TLOG_ERROR, "domain %s too long", domain);
return -1;
}
reverse_string(domain_key, domain, len, 1);
domain_key[len] = '.';
len++;
domain_key[len] = 0;
@@ -471,7 +511,7 @@ static const char *_dns_conf_get_ipset(const char *ipsetname)
}
key = hash_string(ipsetname);
strncpy(ipset_name->ipsetname, ipsetname, DNS_MAX_IPSET_NAMELEN);
safe_strncpy(ipset_name->ipsetname, ipsetname, DNS_MAX_IPSET_NAMELEN);
hash_add(dns_ipset_table.ipset, &ipset_name->node, key);
return ipset_name->ipsetname;
@@ -487,7 +527,7 @@ static int _config_ipset(void *data, int argc, char *argv[])
{
struct dns_ipset_rule *ipset_rule = NULL;
char domain[DNS_MAX_CONF_CNAME_LEN];
char ipsetname[DNS_MAX_CONF_CNAME_LEN];
char ipsetname[DNS_MAX_IPSET_NAMELEN];
const char *ipset = NULL;
char *begin = NULL;
char *end = NULL;
@@ -518,6 +558,11 @@ static int _config_ipset(void *data, int argc, char *argv[])
/* Get domain */
len = end - begin;
if (len >= sizeof(domain)) {
tlog(TLOG_ERROR, "domain name %s too long", value);
goto errout;
}
memcpy(domain, begin, len);
domain[len] = '\0';
@@ -529,7 +574,7 @@ static int _config_ipset(void *data, int argc, char *argv[])
/* Process domain option */
if (strncmp(end + 1, "-", sizeof("-")) != 0) {
/* new ipset domain */
strncpy(ipsetname, end + 1, DNS_MAX_IPSET_NAMELEN);
safe_strncpy(ipsetname, end + 1, DNS_MAX_IPSET_NAMELEN);
ipset = _dns_conf_get_ipset(ipsetname);
if (ipset == NULL) {
goto errout;
@@ -605,6 +650,12 @@ static int _config_address(void *data, int argc, char *argv[])
/* get domain */
len = end - begin;
if (len >= sizeof(domain)) {
tlog(TLOG_ERROR, "domain name %s too long", value);
goto errout;
}
memcpy(domain, begin, len);
domain[len] = 0;
@@ -706,6 +757,176 @@ errout:
return 0;
}
static int _config_speed_check_mode(void *data, int argc, char *argv[])
{
char mode[DNS_MAX_OPT_LEN];
char *field;
char *ptr;
int order = 0;
int port = 80;
int i = 0;
if (argc <= 1) {
return -1;
}
safe_strncpy(mode, argv[1], sizeof(mode));
ptr = mode;
do {
field = ptr;
ptr = strstr(mode, ",");
if (field == NULL || order >= DOMAIN_CHECK_NUM) {
return 0;
}
if (ptr) {
*ptr = 0;
}
if (strncmp(field, "ping", sizeof("ping")) == 0) {
dns_conf_check_order.order[order] = DOMAIN_CHECK_ICMP;
} else if (strstr(field, "tcp") == field) {
char *port_str = strstr(field, ":");
if (port_str) {
port = atoi(port_str + 1);
if (port <= 0 || port >= 65535) {
port = 80;
}
}
dns_conf_check_order.order[order] = DOMAIN_CHECK_TCP;
dns_conf_check_order.tcp_port = port;
} else if (strncmp(field, "none", sizeof("none")) == 0) {
dns_conf_check_order.order[order] = DOMAIN_CHECK_NONE;
for (i = order + 1; i < DOMAIN_CHECK_NUM; i++) {
dns_conf_check_order.order[i] = DOMAIN_CHECK_NONE;
}
return 0;
}
order++;
if (ptr) {
ptr++;
}
} while (1);
return 0;
}
static int _config_bind_ip(int argc, char *argv[], DNS_BIND_TYPE type)
{
int index = dns_conf_bind_ip_num;
struct dns_bind_ip *bind_ip;
char *ip = NULL;
int opt = 0;
char group_name[DNS_GROUP_NAME_LEN];
const char *group = NULL;
unsigned int server_flag = 0;
/* clang-format off */
static struct option long_options[] = {
{"group", required_argument, NULL, 'g'}, /* add to group */
{"no-rule-addr", no_argument, NULL, 'A'},
{"no-rule-nameserver", no_argument, NULL, 'N'},
{"no-rule-ipset", no_argument, NULL, 'I'},
{"no-rule-sni-proxy", no_argument, NULL, 'P'},
{"no-rule-soa", no_argument, NULL, 'O'},
{"no-speed-check", no_argument, NULL, 'S'},
{"no-cache", no_argument, NULL, 'C'},
{"no-dualstack-selection", no_argument, NULL, 'D'},
{NULL, no_argument, NULL, 0}
};
/* clang-format on */
if (argc <= 1) {
tlog(TLOG_ERROR, "invalid parameter.");
goto errout;
}
if (index >= DNS_MAX_SERVERS) {
tlog(TLOG_WARN, "exceeds max server number, %s", ip);
return 0;
}
bind_ip = &dns_conf_bind_ip[index];
bind_ip->type = type;
bind_ip->flags = 0;
ip = argv[1];
safe_strncpy(bind_ip->ip, ip, DNS_MAX_IPLEN);
/* process extra options */
optind = 1;
while (1) {
opt = getopt_long_only(argc, argv, "", long_options, NULL);
if (opt == -1) {
break;
}
switch (opt) {
case 'g': {
safe_strncpy(group_name, optarg, DNS_GROUP_NAME_LEN);
group = _dns_conf_get_group_name(group_name);
break;
}
case 'A': {
server_flag |= BIND_FLAG_NO_RULE_ADDR;
break;
}
case 'N': {
server_flag |= BIND_FLAG_NO_RULE_NAMESERVER;
break;
}
case 'I': {
server_flag |= BIND_FLAG_NO_RULE_IPSET;
break;
}
case 'P': {
server_flag |= BIND_FLAG_NO_RULE_SNIPROXY;
break;
}
case 'S': {
server_flag |= BIND_FLAG_NO_SPEED_CHECK;
break;
}
case 'C': {
server_flag |= BIND_FLAG_NO_CACHE;
break;
}
case 'O': {
server_flag |= BIND_FLAG_NO_RULE_SOA;
break;
}
case 'D': {
server_flag |= BIND_FLAG_NO_DUALSTACK_SELECTION;
break;
}
default:
break;
}
}
/* add new server */
bind_ip->flags = server_flag;
bind_ip->group = group;
dns_conf_bind_ip_num++;
tlog(TLOG_DEBUG, "bind ip %s, type:%d, flag: %X", ip, type, server_flag);
return 0;
errout:
return -1;
}
static int _config_bind_ip_udp(void *data, int argc, char *argv[])
{
return _config_bind_ip(argc, argv, DNS_BIND_TYPE_UDP);
}
static int _config_bind_ip_tcp(void *data, int argc, char *argv[])
{
return _config_bind_ip(argc, argv, DNS_BIND_TYPE_TCP);
}
static int _config_server_udp(void *data, int argc, char *argv[])
{
return _config_server(argc, argv, DNS_SERVER_UDP, DEFAULT_DNS_PORT);
@@ -763,6 +984,12 @@ static int _config_nameserver(void *data, int argc, char *argv[])
}
len = end - begin;
if (len >= sizeof(domain)) {
tlog(TLOG_ERROR, "domain name %s too long", value);
goto errout;
}
memcpy(domain, begin, len);
domain[len] = '\0';
@@ -772,7 +999,7 @@ static int _config_nameserver(void *data, int argc, char *argv[])
}
if (strncmp(end + 1, "-", sizeof("-")) != 0) {
strncpy(group_name, end + 1, DNS_GROUP_NAME_LEN);
safe_strncpy(group_name, end + 1, DNS_GROUP_NAME_LEN);
group = _dns_conf_get_group_name(group_name);
if (group == NULL) {
goto errout;
@@ -859,11 +1086,17 @@ static int _config_iplist_rule(char *subnet, enum address_rule rule)
case ADDRESS_RULE_BLACKLIST:
ip_rule->blacklist = 1;
break;
case ADDRESS_RULE_WHITELIST:
ip_rule->whitelist = 1;
break;
case ADDRESS_RULE_BOGUS:
ip_rule->bogus = 1;
break;
case ADDRESS_RULE_IP_IGNORE:
ip_rule->ip_ignore = 1;
break;
default:
return -1;
}
return 0;
@@ -896,6 +1129,15 @@ static int _conf_ip_ignore(void *data, int argc, char *argv[])
return _config_iplist_rule(argv[1], ADDRESS_RULE_IP_IGNORE);
}
static int _conf_whitelist_ip(void *data, int argc, char *argv[])
{
if (argc <= 1) {
return -1;
}
return _config_iplist_rule(argv[1], ADDRESS_RULE_WHITELIST);
}
static int _conf_edns_client_subnet(void *data, int argc, char *argv[])
{
char *slash = NULL;
@@ -936,7 +1178,7 @@ static int _conf_edns_client_subnet(void *data, int argc, char *argv[])
goto errout;
}
strncpy(ecs->ip, value, DNS_MAX_IPLEN);
safe_strncpy(ecs->ip, value, DNS_MAX_IPLEN);
ecs->subnet = subnet;
ecs->enable = 1;
@@ -963,7 +1205,7 @@ static int _config_log_level(void *data, int argc, char *argv[])
dns_conf_log_level = TLOG_ERROR;
} else if (strncmp("fatal", value, MAX_LINE_LEN) == 0) {
dns_conf_log_level = TLOG_FATAL;
}else {
} else {
return -1;
}
@@ -971,9 +1213,9 @@ static int _config_log_level(void *data, int argc, char *argv[])
}
static struct config_item _config_item[] = {
CONF_STRING("server-name", (char *)dns_conf_server_name, DNS_MAX_CONF_CNAME_LEN),
CONF_STRING("bind", dns_conf_server_ip, DNS_MAX_IPLEN),
CONF_STRING("bind-tcp", dns_conf_server_tcp_ip, DNS_MAX_IPLEN),
CONF_STRING("server-name", (char *)dns_conf_server_name, DNS_MAX_SERVER_NAME_LEN),
CONF_CUSTOM("bind", _config_bind_ip_udp, NULL),
CONF_CUSTOM("bind-tcp", _config_bind_ip_tcp, NULL),
CONF_CUSTOM("server", _config_server_udp, NULL),
CONF_CUSTOM("server-tcp", _config_server_tcp, NULL),
CONF_CUSTOM("server-tls", _config_server_tls, NULL),
@@ -982,6 +1224,7 @@ static struct config_item _config_item[] = {
CONF_CUSTOM("address", _config_address, NULL),
CONF_YESNO("ipset-timeout", &dns_conf_ipset_timeout_enable),
CONF_CUSTOM("ipset", _config_ipset, NULL),
CONF_CUSTOM("speed-check-mode", _config_speed_check_mode, NULL),
CONF_INT("tcp-idle-time", &dns_conf_tcp_idle_time, 0, 3600),
CONF_INT("cache-size", &dns_conf_cachesize, 0, CONF_INT_MAX),
CONF_YESNO("prefetch-domain", &dns_conf_prefetch),
@@ -992,6 +1235,7 @@ static struct config_item _config_item[] = {
CONF_SIZE("log-size", &dns_conf_log_size, 0, 1024 * 1024 * 1024),
CONF_INT("log-num", &dns_conf_log_num, 0, 1024),
CONF_YESNO("audit-enable", &dns_conf_audit_enable),
CONF_YESNO("audit-SOA", &dns_conf_audit_log_SOA),
CONF_STRING("audit-file", (char *)&dns_conf_audit_file, DNS_MAX_PATH),
CONF_SIZE("audit-size", &dns_conf_audit_size, 0, 1024 * 1024 * 1024),
CONF_INT("audit-num", &dns_conf_audit_num, 0, 1024),
@@ -1000,6 +1244,7 @@ static struct config_item _config_item[] = {
CONF_INT("rr-ttl-max", &dns_conf_rr_ttl_max, 0, CONF_INT_MAX),
CONF_YESNO("force-AAAA-SOA", &dns_conf_force_AAAA_SOA),
CONF_CUSTOM("blacklist-ip", _config_blacklist_ip, NULL),
CONF_CUSTOM("whitelist-ip", _conf_whitelist_ip, NULL),
CONF_CUSTOM("bogus-nxdomain", _conf_bogus_nxdomain, NULL),
CONF_CUSTOM("ignore-ip", _conf_ip_ignore, NULL),
CONF_CUSTOM("edns-client-subnet", _conf_edns_client_subnet, NULL),
@@ -1029,11 +1274,13 @@ int config_addtional_file(void *data, int argc, char *argv[])
char file_path_dir[DNS_MAX_PATH];
if (conf_file[0] != '/') {
strncpy(file_path_dir, conf_get_conf_file(), DNS_MAX_PATH);
safe_strncpy(file_path_dir, conf_get_conf_file(), DNS_MAX_PATH);
dirname(file_path_dir);
snprintf(file_path, DNS_MAX_PATH, "%s/%s", file_path_dir, conf_file);
if (snprintf(file_path, DNS_MAX_PATH, "%s/%s", file_path_dir, conf_file) < 0) {
return -1;
}
} else {
strncpy(file_path, conf_file, DNS_MAX_PATH);
safe_strncpy(file_path, conf_file, DNS_MAX_PATH);
}
if (access(file_path, R_OK) != 0) {
@@ -1071,6 +1318,38 @@ void dns_server_load_exit(void)
_config_group_table_destroy();
}
static int _dns_conf_speed_check_mode_verify(void)
{
int i, j;
int has_cap = has_network_raw_cap();
int print_log = 0;
if (has_cap == 1) {
return 0;
}
for (i = 0; i < DOMAIN_CHECK_NUM; i++) {
if (dns_conf_check_order.order[i] == DOMAIN_CHECK_ICMP) {
for (j = i + 1; j < DOMAIN_CHECK_NUM; j++) {
dns_conf_check_order.order[j - 1] = dns_conf_check_order.order[j];
}
dns_conf_check_order.order[j - 1] = DOMAIN_CHECK_NONE;
print_log = 1;
}
}
if (print_log) {
tlog(TLOG_WARN, "speed check by ping is disabled because smartdns does not have network raw privileges");
}
return 0;
}
static int _dns_conf_load_post(void)
{
_dns_conf_speed_check_mode_verify();
return 0;
}
int dns_server_load_conf(const char *file)
{
int ret = 0;
@@ -1078,5 +1357,6 @@ int dns_server_load_conf(const char *file)
openlog("smartdns", LOG_CONS | LOG_NDELAY, LOG_LOCAL1);
ret = load_conf(file, _config_item, _conf_printf);
closelog();
_dns_conf_load_post();
return ret;
}

View File

@@ -1,3 +1,21 @@
/*************************************************************************
*
* Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
*
* smartdns is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* smartdns is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _DNS_CONF
#define _DNS_CONF
@@ -10,7 +28,13 @@
#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
@@ -21,7 +45,7 @@
#define DEFAULT_DNS_PORT 53
#define DEFAULT_DNS_TLS_PORT 853
#define DEFAULT_DNS_HTTPS_PORT 443
#define DNS_MAX_CONF_CNAME_LEN 128
#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"
@@ -35,6 +59,17 @@ enum domain_rule {
DOMAIN_RULE_MAX,
};
typedef enum {
DNS_BIND_TYPE_UDP,
DNS_BIND_TYPE_TCP,
DNS_BIND_TYPE_TLS,
} DNS_BIND_TYPE;
#define DOMAIN_CHECK_NONE 0
#define DOMAIN_CHECK_ICMP 1
#define DOMAIN_CHECK_TCP 2
#define DOMAIN_CHECK_NUM 2
#define DOMAIN_FLAG_ADDR_SOA (1 << 0)
#define DOMAIN_FLAG_ADDR_IPV4_SOA (1 << 1)
#define DOMAIN_FLAG_ADDR_IPV6_SOA (1 << 2)
@@ -46,6 +81,15 @@ enum domain_rule {
#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;
};
@@ -82,6 +126,11 @@ struct dns_server_groups {
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);
};
@@ -96,6 +145,8 @@ struct dns_servers {
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];
};
@@ -112,12 +163,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;
};
@@ -133,8 +186,15 @@ 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;
@@ -147,15 +207,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;
@@ -178,5 +241,7 @@ void dns_server_load_exit(void);
int dns_server_load_conf(const char *file);
extern int config_addtional_file(void *data, int argc, char *argv[]);
#ifdef __cpluscplus
}
#endif
#endif // !_DNS_CONF

File diff suppressed because it is too large Load Diff

View File

@@ -1,3 +1,21 @@
/*************************************************************************
*
* Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
*
* smartdns is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* smartdns is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _SMART_DNS_SERVER_H
#define _SMART_DNS_SERVER_H
@@ -18,7 +36,7 @@ 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, void *user_ptr);
typedef int (*dns_result_callback)(char *domain, dns_rtcode_t rtcode, dns_type_t addr_type, char *ip, unsigned int ping_time, void *user_ptr);
/* query domain */
int dns_server_query(char *domain, int qtype, dns_result_callback callback, void *user_ptr);

View File

@@ -1,6 +1,6 @@
/*************************************************************************
*
* Copyright (C) 2018 Ruilin Peng (Nick) <pymumu@gmail.com>.
* Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
*
* smartdns is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -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,6 +44,9 @@
#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
@@ -215,17 +219,91 @@ static 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;
}
@@ -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) {
@@ -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;
}
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)
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 @@ static void _fast_ping_print_result(struct ping_host_struct *ping_host, const ch
}
}
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;
@@ -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;
}
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)
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;
@@ -1094,17 +1252,16 @@ static int _fast_ping_process_icmp(struct ping_host_struct *ping_host, struct ti
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, NULL);
gettimeofday(&now, &tz);
LIST_HEAD(action);
pthread_mutex_lock(&ping.map_lock);
@@ -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);

View File

@@ -1,3 +1,21 @@
/*************************************************************************
*
* Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
*
* smartdns is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* smartdns is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef FAST_PING_H
#define FAST_PING_H

View File

@@ -1,3 +1,21 @@
/*************************************************************************
*
* Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
*
* smartdns is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* smartdns is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "http_parse.h"
#include "hash.h"
#include "hashtable.h"
@@ -137,12 +155,12 @@ 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)
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)
const char *http_head_get_httpversion(struct http_head *http_head)
{
return http_head->version;
}
@@ -162,7 +180,7 @@ 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)
char *http_head_get_data(struct http_head *http_head)
{
return http_head->data;
}
@@ -232,7 +250,7 @@ static int _http_head_parse_response(struct http_head *http_head, char *key, cha
http_head->code = atol(ret_code);
http_head->code_msg = result;
http_head->version = key;
http_head->head_type = HTTP_HEAD_RESPONSE;
http_head->head_type = HTTP_HEAD_RESPONSE;
return 0;
}

View File

@@ -1,3 +1,21 @@
/*************************************************************************
*
* Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
*
* smartdns is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* smartdns is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef HTTP_PARSER_H
#define 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

View File

@@ -1,3 +1,22 @@
/*************************************************************************
*
* Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
*
* smartdns is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* smartdns is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _GENERIC_ATOMIC_H
#define _GENERIC_ATOMIC_H

View File

@@ -1,3 +1,22 @@
/*************************************************************************
*
* Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
*
* smartdns is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* smartdns is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _PERF_BITOPS_H
#define _PERF_BITOPS_H

View File

@@ -1,3 +1,22 @@
/*************************************************************************
*
* Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
*
* smartdns is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* smartdns is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _GENERIC_BITOPS_H_
#define _GENERIC_BITOPS_H_

View File

@@ -1,3 +1,22 @@
/*************************************************************************
*
* Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
*
* smartdns is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* smartdns is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _GENERIC_CONF_H
#define _GENERIC_CONF_H

View File

@@ -1,5 +1,24 @@
#ifndef _TOOLS_LINUX_ASM_GENERIC_BITOPS_FIND_H_
#define _TOOLS_LINUX_ASM_GENERIC_BITOPS_FIND_H_
/*************************************************************************
*
* Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
*
* smartdns is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* smartdns is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _TOOLS_GENERIC_BITOPS_FIND_H_
#define _TOOLS_GENERIC_BITOPS_FIND_H_
#ifndef find_next_bit
/**
@@ -74,4 +93,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_GENERIC_BITOPS_FIND_H_ */

View File

@@ -1,3 +1,22 @@
/*************************************************************************
*
* Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
*
* smartdns is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* smartdns is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _TOOLS_LINUX_COMPILER_H_
#define _TOOLS_LINUX_COMPILER_H_

View File

@@ -1,3 +1,22 @@
/*************************************************************************
*
* Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
*
* smartdns is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* smartdns is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _GENERIC_HASH_H
#define _GENERIC_HASH_H

View File

@@ -1,6 +1,19 @@
/*
* Statically sized hash table implementation
* (C) 2012 Sasha Levin <levinsasha928@gmail.com>
/*************************************************************************
*
* Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
*
* smartdns is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* smartdns is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _GENERIC_HASHTABLE_H

View File

@@ -1,3 +1,21 @@
/*************************************************************************
*
* Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
*
* smartdns is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* smartdns is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _JHASH_H
#define _JHASH_H

View File

@@ -1,3 +1,20 @@
/*************************************************************************
*
* Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
*
* smartdns is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* smartdns is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _GENERIC_LIST_H
#define _GENERIC_LIST_H

View File

@@ -1,3 +1,20 @@
/*************************************************************************
*
* Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
*
* smartdns is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* smartdns is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _GENERIC_RBTREE_H
#define _GENERIC_RBTREE_H

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

@@ -0,0 +1,42 @@
/*************************************************************************
*
* Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
*
* smartdns is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* smartdns is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#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

@@ -1,3 +1,20 @@
/*************************************************************************
*
* Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
*
* smartdns is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* smartdns is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "bitmap.h"
#include "bitops.h"

View File

@@ -1,3 +1,21 @@
/*************************************************************************
*
* Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
*
* smartdns is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* smartdns is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "conf.h"
#include <getopt.h>
#include <stdio.h>
@@ -117,11 +135,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)
@@ -165,7 +185,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;
@@ -181,7 +200,7 @@ int conf_parse_args(char *key, char *value, int *argc, char **argv)
}
*argc = count;
argv[count + 1] = 0;
argv[count] = 0;
return 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;

View File

@@ -1,3 +1,20 @@
/*************************************************************************
*
* Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
*
* smartdns is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* smartdns is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "rbtree.h"
#include <stdbool.h>

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

@@ -0,0 +1,17 @@
/*************************************************************************
*
* Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
*
* smartdns is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* smartdns is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

View File

@@ -1,6 +1,6 @@
/*************************************************************************
*
* Copyright (C) 2018 Ruilin Peng (Nick) <pymumu@gmail.com>.
* Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
*
* smartdns is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -59,7 +59,8 @@ static 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,6 +70,20 @@ static void _help(void)
printf("%s", help);
}
static void _show_version(void)
{
char str_ver[256] = {0};
#ifdef SMARTDNS_VERION
const char *ver = SMARTDNS_VERION;
snprintf(str_ver, sizeof(str_ver), "%s", ver);
#else
struct tm tm;
get_compiled_time(&tm);
snprintf(str_ver, sizeof(str_ver), "1.%.4d%.2d%.2d-%.2d%.2d", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min);
#endif
printf("smartdns %s\n", str_ver);
}
static int _smartdns_load_from_resolv(void)
{
FILE *fp = NULL;
@@ -108,7 +123,7 @@ static 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++;
@@ -139,15 +154,17 @@ static int _smartdns_add_servers(void)
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);
strncpy(flag_http->host, dns_conf_servers[i].hostname, sizeof(flag_http->host));
strncpy(flag_http->path, dns_conf_servers[i].path, sizeof(flag_http->path));
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);
strncpy(flag_tls->host, dns_conf_servers[i].hostname, sizeof(flag_tls->host));
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;
break;
case DNS_SERVER_TCP:
break;
default:
@@ -231,7 +248,7 @@ static 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;
@@ -358,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;
@@ -375,9 +392,13 @@ 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();
return 1;
@@ -395,12 +416,12 @@ int main(int argc, char *argv[])
_reg_signal();
}
if (dns_server_load_conf(config_file) != 0) {
fprintf(stderr, "load config failed.\n");
if (create_pid_file(pid_file) != 0) {
goto errout;
}
if (create_pid_file(pid_file) != 0) {
if (dns_server_load_conf(config_file) != 0) {
fprintf(stderr, "load config failed.\n");
goto 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-2020 Ruilin Peng (Nick) <pymumu@gmail.com>
* https://github.com/pymumu/tinylog
*/
@@ -24,21 +24,44 @@ typedef enum {
struct tlog_time {
int year;
int mon;
int mday;
int hour;
int min;
int sec;
int usec;
};
unsigned int usec;
unsigned char mon;
unsigned char mday;
unsigned char hour;
unsigned char min;
unsigned char sec;
} __attribute__((packed));
#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
@@ -51,9 +74,12 @@ format: Log formats
#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,3 +1,21 @@
/*************************************************************************
*
* Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
*
* smartdns is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* smartdns is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
@@ -7,9 +25,11 @@
#include <errno.h>
#include <fcntl.h>
#include <linux/netlink.h>
#include <linux/capability.h>
#include <openssl/crypto.h>
#include <openssl/ssl.h>
#include <pthread.h>
#include <netinet/tcp.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
@@ -17,6 +37,7 @@
#include <time.h>
#include <unistd.h>
#include <inttypes.h>
#include <sys/prctl.h>
#define TMP_BUFF_LEN_32 32
@@ -65,6 +86,7 @@ struct ipset_netlink_msg {
};
static int ipset_fd;
static int pidfile_fd;
unsigned long get_tick_count(void)
{
@@ -125,6 +147,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;
@@ -138,6 +161,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;
@@ -193,6 +285,98 @@ 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;
@@ -207,7 +391,7 @@ int parse_uri(char *value, char *scheme, char *host, int *port, char *path)
field_len = scheme_end - value;
if (scheme) {
memcpy(scheme, value, field_len);
scheme[field_len + 1] = 0;
scheme[field_len] = 0;
}
process_ptr += field_len + 3;
} else {
@@ -226,7 +410,7 @@ int parse_uri(char *value, char *scheme, char *host, int *port, char *path)
return -1;
}
memcpy(host_name, process_ptr, field_len);
host_name[field_len + 1] = 0;
host_name[field_len] = 0;
if (parse_ip(host_name, host, port) != 0) {
return -1;
@@ -235,7 +419,7 @@ int parse_uri(char *value, char *scheme, char *host, int *port, char *path)
process_ptr += field_len;
if (path) {
strcpy(path, process_ptr);
strncpy(path, process_ptr, PATH_MAX);
}
return 0;
}
@@ -258,7 +442,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) {
@@ -269,6 +453,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--;
}
@@ -381,7 +571,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;
}
@@ -483,6 +673,12 @@ int create_pid_file(const char *pid_file)
goto errout;
}
if (pidfile_fd > 0) {
close(pidfile_fd);
}
pidfile_fd = fd;
return 0;
errout:
if (fd > 0) {
@@ -555,25 +751,10 @@ void SSL_CRYPTO_thread_cleanup(void)
#ifndef MIN
#define MIN(X, Y) ((X) < (Y) ? (X) : (Y))
#endif
typedef struct Protocol {
const char *const name;
const uint16_t default_port;
int (*const parse_packet)(const char*, size_t, char *, const char **);
const char *const abort_message;
const size_t abort_message_len;
} protocol_t;
static int parse_extensions(const char *, size_t, char *, const char **);
static int parse_server_name_extension(const char *, size_t, char *, const char **);
const struct Protocol *const tls_protocol;
static const protocol_t tls_protocol_st = {
.default_port = 443,
.parse_packet = &parse_tls_header,
};
const protocol_t *const tls_protocol = &tls_protocol_st;
/* Parse a TLS packet for the Server Name Indication extension in the client
* hello handshake, returning the first servername found (pointer to static
* array)
@@ -741,3 +922,47 @@ static int parse_server_name_extension(const char *data, size_t data_len, char *
return -2;
}
void get_compiled_time(struct tm *tm)
{
char s_month[5];
int month, day, year;
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;
}
int set_sock_keepalive(int fd, int keepidle, int keepinterval, int keepcnt)
{
const int yes = 1;
if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &yes, sizeof(yes))!= 0) {
return -1;
}
setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &keepidle, sizeof(keepidle));
setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &keepinterval, sizeof(keepinterval));
setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &keepcnt, sizeof(keepcnt));
return 0;
}

View File

@@ -1,9 +1,42 @@
/*************************************************************************
*
* Copyright (C) 2018-2020 Ruilin Peng (Nick) <pymumu@gmail.com>.
*
* smartdns is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* smartdns is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef SMART_DNS_UTIL_H
#define SMART_DNS_UTIL_H
#include <netdb.h>
#include <time.h>
#include "stringutil.h"
#ifdef __cplusplus
extern "C" {
#endif /*__cplusplus */
#ifndef TCP_FASTOPEN_CONNECT
#define TCP_FASTOPEN_CONNECT 30
#endif
#ifndef TCP_THIN_LINEAR_TIMEOUTS
#define TCP_THIN_LINEAR_TIMEOUTS 16
#endif
#ifndef TCP_THIN_DUPACK
#define TCP_THIN_DUPACK 17
#endif
#define PORT_NOT_DEFINED -1
#define MAX_IP_LEN 64
@@ -14,13 +47,19 @@ 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);
@@ -53,4 +92,13 @@ int create_pid_file(const char *pid_file);
*/
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);
int set_sock_keepalive(int fd, int keepidle, int keepinterval, int keepcnt);
#ifdef __cplusplus
}
#endif /*__cplusplus */
#endif