Compare commits

...

53 Commits

Author SHA1 Message Date
Nick Peng
bb9dfc6a33 Update ReadMe_zh-CN.md 2019-12-15 01:26:25 +08:00
Nick Peng
e0af4e4339 Support Armbian arm64 2019-12-15 01:26:24 +08:00
Nick Peng
7ee15e4075 Update ReadMe.md 2019-12-15 01:26:14 +08:00
Nick Peng
5c02f06844 Add FAQ 2019-12-15 01:26:10 +08:00
Nick Peng
c62ea93ba6 Support relative conf-path 2019-12-15 01:26:08 +08:00
Nick Peng
ef3a2196a0 Some document optimizations 2019-12-15 01:26:06 +08:00
Nick Peng
8e1b404ba0 Fix message issue 2019-12-15 01:26:04 +08:00
Nick Peng
02213de0ee Add support EDNS TCP-keep-alive 2019-12-15 01:26:03 +08:00
Nick Peng
7c2df9c96b LUCI support SPKI 2019-12-15 01:26:02 +08:00
Nick Peng
7828f0ec27 code lint and optimize code style 2019-12-15 01:26:01 +08:00
Nick Peng
c0c6fde39d Fix clang-tidy warning 2019-12-15 01:26:00 +08:00
Nick Peng
85b0eed3a2 Support TLS SPKI verify 2019-12-15 01:25:59 +08:00
Nick Peng
4465ce798a Support nameserver feature 2019-12-15 01:25:58 +08:00
Nick Peng
0df8c07103 Fix addr to string ip issue 2019-12-15 01:25:57 +08:00
Nick Peng
fbbbc80d20 Support auto configuration 2019-12-15 01:25:55 +08:00
Nick Peng
21ba047075 Fix PTR issue 2019-12-15 01:25:53 +08:00
Nick Peng
9f3926e048 Support Windows Subsystem for Linux 2019-12-15 01:25:50 +08:00
Nick Peng
e8b920fb18 Fix cache issue 2019-12-15 01:25:49 +08:00
Nick Peng
a1150a7ceb ipset bugfix and add timeout feature 2019-12-15 01:25:46 +08:00
Nick Peng
e1ffe29fca Fix segment fault issue 2019-12-15 01:25:44 +08:00
Nick Peng
d9dd02c9b0 Fix SSL crash issue: tcp-nodelay ? 2019-12-15 01:25:43 +08:00
Nick Peng
c7d304423e Fix bug 2019-12-15 01:25:42 +08:00
Nick Peng
87d8739ecd Resolve tls mode multi-thread issue. 2019-12-15 01:25:42 +08:00
Nick Peng
452438a0af Fix possible out of rage issue. 2019-12-15 01:25:41 +08:00
Nick Peng
0085abdfdd Fix tcp connection timeout issue 2019-12-15 01:25:40 +08:00
Nick Peng
46d3acdb8f Enable ssl session reuse 2019-12-15 01:25:39 +08:00
Nick Peng
36ddca0491 Add domain prefetch, fix ping issue 2019-12-15 01:25:38 +08:00
Nick Peng
f02dffdf95 cleanup 2019-12-15 01:25:37 +08:00
Nick Peng
10ea3e6f3f Fix address bug 2019-12-15 01:25:36 +08:00
Nick Peng
7add2b82ae code enhancement 2019-12-15 01:25:35 +08:00
Nick Peng
05a24264aa unexpected data process crash bug fix 2019-12-15 01:25:35 +08:00
Nick Peng
8e73eea8ec cache bug fix 2019-12-15 01:25:34 +08:00
Nick Peng
c3ac0c2f17 Stack corrupted on mipsbig BugFix 2019-12-15 01:25:32 +08:00
Nick Peng
210e0a9a6f BugFix 2019-12-15 01:25:30 +08:00
Nick Peng
9092d9f683 Fix SIGPIPE issue 2019-12-15 01:25:28 +08:00
Nick Peng
5057a8e45d Fix ipsub net issue: ipv4 matching ipv6 rule 2019-12-15 01:25:27 +08:00
Nick Peng
1600eaed1f Fix ssl read error 2019-12-15 01:25:26 +08:00
Nick Peng
65ede47cf7 Fix crash bug 2019-12-15 01:25:25 +08:00
Nick Peng
6e5fc54439 Fix dnsmasq replacement issue 2019-12-15 01:25:24 +08:00
Nick Peng
71e110748b Add config load error log 2019-12-15 01:25:23 +08:00
Nick Peng
0112d12693 Add ignore-ip feature 2019-12-15 01:25:21 +08:00
Nick Peng
0a236acc56 Fix dhcp issue when replace dnsmasq 2019-12-15 01:25:19 +08:00
Nick Peng
050aedadd4 Add dnsmasq replacement support for optware package 2019-12-15 01:25:18 +08:00
Nick Peng
7241b24a57 Fix dualstack select issue 2019-12-15 01:25:16 +08:00
Nick Peng
5e12611157 Modify ReadMe.md 2019-12-15 01:25:14 +08:00
Nick Peng
7f5e0ef4e0 Fix ttl bug 2019-12-15 01:25:14 +08:00
Nick Peng
bb1c4d2bfa optimize prefetch feature 2019-12-15 01:25:13 +08:00
Nick Peng
dd4372a961 optimize for selecting best ip address
Signed-off-by: Nick Peng <pymumu@gmail.com>
2019-12-15 01:25:12 +08:00
Nick Peng
73d4e9f822 Optimize tls code 2019-12-15 01:25:12 +08:00
Nick Peng
95a5b1e5e3 bugfix 2019-12-15 01:25:11 +08:00
Nick Peng
143d82ce1a Add Domain RULE flags feature. 2019-12-15 01:25:09 +08:00
Nick Peng
4028887167 Support TTL range value, optimize some logs 2019-12-15 01:25:08 +08:00
Nick Peng
1674c3d8c9 Fix typo 2019-12-15 01:25:08 +08:00
52 changed files with 3553 additions and 1076 deletions

243
ReadMe.md
View File

@@ -5,7 +5,24 @@ SmartDNS is a local DNS server. SmartDNS accepts DNS query requests from local c
Avoiding DNS pollution and improving network access speed, supports high-performance ad filtering.
Unlike dnsmasq's all-servers, smartdns returns the fastest access resolution.
Support Raspberry Pi, openwrt, ASUS router and other devices.
Support Raspberry Pi, openwrt, ASUS router, Windows and other devices.
## Table Of Content
1. [Software Show](#software-show)
1. [Features](#features)
1. [Architecture](#architecture)
1. [Usage](#usage)
1. [Download the package](#download-the-package)
1. [Standard Linux system installation/Raspberry Pi, X86_64 system](#standard-linux-system-installation/raspberry-pi,-x86_64-system)
1. [openwrt/LEDE](#openwrt/lede)
1. [ASUS router native firmware / Merlin firmware](#asus-router-native-firmware-/-merlin-firmware)
1. [optware/entware](#optware/entware)
1. [Windows 10 WSL Installation/WSL ubuntu](#windows-10-wsl-installation/wsl-ubuntu)
1. [Configuration parameter](#configuration-parameter)
1. [Donate](#Donate)
1. [Statement](#Statement)
1. [FAQ](#FAQ)
## Software Show
@@ -85,8 +102,8 @@ From the comparison, smartdns found the fastest IP address to visit www.baidu.co
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 multi-platform support**
Support standard Linux system (Raspberry Pi), openwrt system various firmware, ASUS router native firmware.
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.
@@ -114,14 +131,18 @@ Download the matching version of the SmartDNS installation package. The correspo
|system |package|Description
|-----|-----|-----
|Standard Linux system (Raspberry Pi)| smartdns.xxxxxxxx.armhf.deb|Support Raspberry Pi Raspbian stretch, Debian 9 system.
|Standard Linux system (x86_64)| smartdns.xxxxxxxx.x86_64.tar.gz|Support for x86_64 systems.
|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, such as the RT-AC68U.
|ASUS native firmware (optware)|smartdns.xxxxxxx.arm.ipk|System that supports the ARM small endian architecture, such as the RT-AC88U.
|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
@@ -140,8 +161,9 @@ Download the matching version of the SmartDNS installation package. The correspo
```
Please download it from the Release page: [Download here](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)
### Standard Linux system installation/Raspberry Pi, X86_64 system
--------------
@@ -247,6 +269,7 @@ Download the matching version of the SmartDNS installation package. The correspo
```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
@@ -367,6 +390,105 @@ Note: Merlin firmware is derived from ASUS firmware and can theoretically be use
\\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|
@@ -379,7 +501,7 @@ Note: Merlin firmware is derived from ASUS firmware and can theoretically be use
|rr-ttl|Domain name TTL|Remote query result|number greater than 0|rr-ttl 600
|rr-ttl-min|Domain name Minimum TTL|Remote query result|number greater than 0|rr-ttl-min 60
|rr-ttl-max|Domain name Maximum TTL|Remote query result|number greater than 0|rr-ttl-max 600
|log-level|log level|error|error,warn,info,debug|log-level error
|log-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
@@ -388,16 +510,109 @@ Note: Merlin firmware is derived from ASUS firmware and can theoretically be use
|audit-size|audit log size|128K|number+K,M,G|audit-size 128K
|audit-num|archived audit log number|2|Integer|audit-num 2
|conf-file|additional conf file|None|File path|conf-file /etc/smartdns/smartdns.more.conf
|server|Upstream UDP DNS server|None|[ip][:port] [-blacklist-ip][-check-edns], Repeatable, blacklist-ip parameter represents filtering the result of IPs with blacklist-ip configuration.| server 8.8.8.8:53 -blacklist-ip -check-edns
|server-tcp|Upstream TCP DNS server|None|[IP][:port] [-blacklist-ip][-check-edns], Repeatable, blacklist-ip parameter represents filtering the result of IPs with blacklist-ip configuration.| server-tcp 8.8.8.8:53
|server-tls|Upstream TLS DNS server|None|[IP][:port] [-blacklist-ip][-check-edns], Repeatable, blacklist-ip parameter represents filtering the result of IPs with blacklist-ip configuration.| server-tls 8.8.8.8:853
|address|Domain IP address|None|address /domain/ip| address /www.example.com/1.2.3.4
|ipset|Domain IPSet|None|ipset /domain/ipset|ipset /www.example.com/pass
|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
|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|100ms|millisecond|dualstack-ip-selection-threshold [1-1000]
|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 protocol and provides secure DNS query capabilities.
* DNS anti-poison mechanism, and a variety of mechanisms to avoid DNS pollution.
* ECS support, the query results are better and more accurate.
* IP blacklist support, ignoring the blacklist IP to make domain name queries better and more accurate.
* Domain name pre-fetch, more faster to access popular websites.
* Domain name TTL can be specified to make access faster.
* Cache mechanism to make access faster.
* Asynchronous log, audit log mechanism, does not affect DNS query performance while recording information.
* Domain group mechanism, specific domain names use specific upstream server group queries to avoid privacy leakage.
1. What is the best practices for upstream server configuration?
Smartdns has a speed measurement mechanism. When configuring an upstream server, it is recommended to configure multiple upstream DNS servers, including servers in different regions, but the total number is recommended to be around 10. Recommended configuration
* Carrier DNS.
* Public DNS, such as `8.8.8.8`, `8.8.4.4`, `1.1.1.1`.
For specific domain names, if there is a pollution, you can enable the anti-pollution mechanism.
1. How to enable the audit log
The audit log records the domain name requested by the client. The record information includes the request time, the request IP address, the request domain name, and the request type. If you want to enable the audit log, configure `audit-enable yes` in the configuration file, `audit-size`, `Audit-file`, `audit-num` configure the audit log file size, the audit log file path, and the number of audit log files. The audit log file will be compressed to save space.
1. How to avoid DNS privacy leaks
By default, smartdns will send requests to all configured DNS servers. If the upstream DNS servers record DNS logs, it will result in a DNS privacy leak. To avoid privacy leaks, try the following steps:
* Use trusted DNS servers.
* Use TLS servers.
* Set up an upstream DNS server group.
1. How to block ads
Smartdns has a high-performance domain name matching algorithm. It is very efficient to filter advertisements by domain name. To block ads, you only need to configure records like the following configure. For example, if you block `*.ad.com`, configure as follows:
```sh
Address /ad.com/#
```
The suffix mode of the domain name, filtering *.ad.com, `#` means returning SOA record. If you want to only block IPV4 or IPV6 separately, add a number after `#`, such as `#4` is for IPV4 blocking. If you want to ignore some specific subdomains, you can configure it as follows. e.g., if you ignore `pass.ad.com`, you can configure it as follows:
```sh
Address /pass.ad.com/-
```
1. DNS query diversion
In some cases, some domain names need to be queried using a specific DNS server to do DNS diversion. such as.
```sh
.home -> 192.168.1.1
.office -> 10.0.0.1
```
The domain name ending in .home is sent to 192.168.1.1 for resolving
The domain name ending in .office is sent to 10.0.0.1 for resolving
Other domain names are resolved using the default mode.
The diversion configuration for this case is as follows:
```sh
# Upstream configuration, use -group to specify the group name, and -exclude-default-group to exclude the server from the default group.
Server 192.168.1.1 -group home -exclude-default-group
Server 10.0.0.1 -group office -exclude-default-group
Server 8.8.8.8
#Configure the resolved domain name with specific group
Nameserver /.home/home
Nameserver /.office/office
```
1. How to use the 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.
1. How to improve cache performace
Smartdns provides a domain name caching mechanism to cache the queried domain name, and the caching time is in accordance with the DNS TTL specification. To increase the cache hit rate, the following configuration can be taken:
* Increase the number of cache records appropriately
Set the number of cache records by `cache-size`.
In the case of a query with a high pressure environment and a machine with a large memory, it can be appropriately adjusted.
* Set the minimum TTL value as appropriate
Set the minimum DNS TTL time to a appropriate value by `rr-ttl-min` to extend the cache time.
It is recommended that the timeout period be set to 10 to 30 minutes to avoid then invalid domain names when domain ip changes.
* Enable domain pre-acquisition
Enable pre-fetching of domain names with `prefetch-domain yes` to improve query hit rate.
by default, Smartdns will send domain query request again before cache expire, and cache the result for the next query. Frequently accessed domain names will continue to be cached. This feature will consume more CPU when idle.
## [Donate](#Donate)

View File

@@ -1,11 +1,28 @@
# SmartDNS
![SmartDNS](doc/smartdns-banner.png)
SmartDNS是一个运行在本地的DNS服务器SmartDNS接受本地客户端的DNS查询请求从多个上游DNS服务器获取DNS查询结果并将访问速度最快的结果返回客户端避免DNS污染提高网络访问速度。
SmartDNS是一个运行在本地的DNS服务器SmartDNS接受本地客户端的DNS查询请求从多个上游DNS服务器获取DNS查询结果并将访问速度最快的结果返回客户端避免DNS污染提高网络访问速度。
同时支持指定特定域名IP地址并高性匹配达到过滤广告的效果。
与dnsmasq的all-servers不同smartdns返回的是访问速度最快的解析结果。
支持树莓派openwrt华硕路由器等设备。
支持树莓派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)
## 软件效果展示
@@ -73,25 +90,28 @@ rtt min/avg/max/mdev = 5.954/6.133/6.313/0.195 ms
1. **多DNS上游服务器**
支持配置多个上游DNS服务器并同时进行查询即使其中有DNS服务器异常也不会影响查询。
2. **返回最快IP地址**
1. **返回最快IP地址**
支持从域名所属IP地址列表中查找到访问速度最快的IP地址并返回给客户端避免DNS污染提高网络访问速度。
3. **支持多种查询协议**
1. **支持多种查询协议**
支持UDPTCPTLS查询以及非53端口查询有效避免DNS污染。
4. **特定域名IP地址指定**
1. **特定域名IP地址指定**
支持指定域名的IP地址达到广告过滤效果避免恶意网站的效果。
5. **域名高性能后缀匹配**
1. **域名高性能后缀匹配**
支持域名后缀匹配模式简化过滤配置过滤20万条记录时间<1ms
6. **Linux多平台支持**
支持标准Linux系统树莓派openwrt系统各种固件华硕路由器原生固件
1. **域名分流**
支持域名分流不同类型的域名到不同的DNS服务器查询
7. **支持IPV4, IPV6双栈**
1. **Linux/Windows多平台支持**
支持标准Linux系统树莓派openwrt系统各种固件华硕路由器原生固件。以及支持Windows 10 WSL (Windows Subsystem for Linux)。
1. **支持IPV4, IPV6双栈**
支持IPV4IPV6网络支持查询A, AAAA记录支持双栈IP速度优化。
8. **高性能,占用资源少**
1. **高性能,占用资源少**
多线程异步IO模式cache缓存查询结果。
## 架构
@@ -114,14 +134,18 @@ rtt min/avg/max/mdev = 5.954/6.133/6.313/0.195 ms
|系统 |安装包|说明
|-----|-----|-----
|标准Linux系统(树莓派)| smartdns.xxxxxxxx.armhf.deb|支持树莓派Raspbian stretchDebian 9系统。
|标准Linux系统(x86_64)| smartdns.xxxxxxxx.x86_64.tar.gz|支持x86_64系统。
|标准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小端架构的系统如RT-AC68U
|华硕原生固件(optware)|smartdns.xxxxxxx.arm.ipk|支持arm小端架构的系统如RT-AC88U。
|华硕原生固件(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路由器
@@ -140,8 +164,9 @@ rtt min/avg/max/mdev = 5.954/6.133/6.313/0.195 ms
```
请在Release页面下载[此处下载](https://github.com/pymumu/smartdns/releases)
* 各种设备的安装步骤,请参考后面的章节。
### 标准Linux系统安装树莓派, X86_64系统
### 标准Linux系统安装/树莓派/X86_64系统
--------------
@@ -247,6 +272,7 @@ rtt min/avg/max/mdev = 5.954/6.133/6.313/0.195 ms
```shell
iptables -t nat -L PREROUTING | grep REDIRECT
```
* 如转发功能不正常请使用方法二作为DNSMASQ的上游。
1. 方法二作为DNSMASQ的上游
@@ -367,6 +393,105 @@ rtt min/avg/max/mdev = 5.954/6.133/6.313/0.195 ms
\\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.
```
## 配置参数
|参数|功能|默认值|配置值|例子|
@@ -379,7 +504,7 @@ rtt min/avg/max/mdev = 5.954/6.133/6.313/0.195 ms
|rr-ttl|域名结果TTL|远程查询结果|大于0的数字|rr-ttl 600
|rr-ttl-min|允许的最小TTL值|远程查询结果|大于0的数字|rr-ttl-min 60
|rr-ttl-max|允许的最大TTL值|远程查询结果|大于0的数字|rr-ttl-max 600
|log-level|设置日志级别|error|error,warn,info,debug|log-level error
|log-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
@@ -388,18 +513,114 @@ rtt min/avg/max/mdev = 5.954/6.133/6.313/0.195 ms
|audit-size|审计大小|128K|数字+K,M,G|audit-size 128K
|audit-num|审计归档个数|2|数字|audit-num 2
|conf-file|附加配置文件|无|文件路径|conf-file /etc/smartdns/smartdns.more.conf
|server|上游UDP DNS|无|[ip][:port] [-blacklist-ip][-check-edns]可重复blacklist-ip参数指定使用blacklist-ip配置IP过滤结果| server 8.8.8.8:53 -blacklist-ip -check-edns
|server-tcp|上游TCP DNS|无|[IP][:port] [-blacklist-ip][-check-edns]可重复blacklist-ip参数指定使用blacklist-ip配置IP过滤结果| server-tcp 8.8.8.8:53
|server-tls|上游TLS DNS|无|[IP][:port] [-blacklist-ip][-check-edns]可重复blacklist-ip参数指定使用blacklist-ip配置IP过滤结果| server-tls 8.8.8.8:853
|address|指定域名IP地址|无|address /domain/ip| address /www.example.com/1.2.3.4
|ipset|域名IPSET|None|ipset /domain/ipset|ipset /www.example.com/pass
|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
|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优选阈值|100ms|毫秒|dualstack-ip-selection-threshold [1-1000]
|dualstack-ip-selection-threshold|双栈IP优选阈值|30ms|毫秒|dualstack-ip-selection-threshold [0-1000]
## [Donate](#Donate)
## FAQ
1. SmartDNS和DNSMASQ有什么区别
SMARTDNS在设计上并不是替换DNSMASQ的MARTDNS主要功能集中在DNS解析增强上增强部分有
* 多上游服务器并发请求,对结果进行测速后,返回最佳结果;
* addressipset域名匹配采用高效算法查询匹配更加快速高效路由器设备依然高效。
* 域名匹配支持忽略特定域名可单独匹配IPv4 IPV6支持多样化定制。
* 针对广告屏蔽功能做增强返回SOA屏蔽广告效果更佳
* IPV4IPV6双栈IP优选机制在双网情况下选择最快的网络通讯。
* 支持最新的TLS协议提供安全的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. 双栈IP优选功能如何使用
目前IPV6已经开始普及但IPV6网络在速度上某些情况下还不如IPV4为在双栈网络下获得较好的体验smartdns提供来双栈IP优选机制同一个域名若IPV4的速度远快与IPV6那么smartdns就会阻止IPV6的解析让PC使用IPV4访问具体配置文件通过`dualstack-ip-selection yes`启用此功能,通过`dualstack-ip-selection-threshold [time]`来修改阈值。
1. 如何提高cache效率加快访问速度
smartdns提供了域名缓存机制对查询的域名进行缓存缓存时间符合DNS TTL规范。为提高缓存命中率可采用如下措施
* 适当增大cache的记录数
通过`cache-size`来设置缓存记录数。
查询压力大的环境下,并且有内存大的机器的情况下,可适当调大。
* 适当设置最小TTL值
通过`rr-ttl-min`将最低DNS TTL时间设置为一个合理值延长缓存时间。
建议是超时时间设置在1030分钟避免服务器域名变化时查询到失效域名。
* 开启域名预获取功能
通过`prefetch-domain yes`来启用域名预先获取功能,提高查询命中率。
配合上述ttl超时时间smartdns将在域名ttl即将超时使再次发送查询请求并缓存查询结果供后续使用。频繁访问的域名将会持续缓存。此功能将在空闲时消耗更多的CPU。
## Donate
如果你觉得此项目对你有帮助,请捐助我们,以使项目能持续发展,更加完善。

View File

@@ -36,18 +36,21 @@ 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 ignored
# ignore-ip [ip/subnet]
# force AAAA query return SOA
# force-AAAA-SOA [yes|no]
# Enable IPV4, IPV6 dual stack IP optimization selection strategy
# dualstack-ip-selection-threshold [num] (1~1000)
# dualstack-ip-selection-threshold [num] (0~1000)
# dualstack-ip-selection [yes|no]
# dualstack-ip-selection yes
# edns client subnet
# edns-client-subnet-ipv4 [ip/subnet]
# edns-client-subnet-ipv6 [ip/subnet]
# edns-client-subnet-ipv4 192.168.1.1/24
# edns-client-subnet [ip/subnet]
# edns-client-subnet 192.168.1.1/24
# edns-client-subnet [8::8]/56
# ttl for all resource record
# rr-ttl: ttl for all record
@@ -59,7 +62,7 @@ cache-size 512
# rr-ttl-max 86400
# set log level
# log-level: [level], level=error, warn, info, debug
# log-level: [level], level=fatal, error, warn, notice, info, debug
# log-file: file path of log file.
# log-size: size of each log file, support k,m,g
# log-num: number of logs
@@ -70,33 +73,50 @@ log-level info
# dns audit
# audit-enable: enable or disable audit [yes|no]
# audit-enable yes
# audit-size size of each audit file, support k,m,g
# audit-file /var/log/smartdns-audit.log
# audit-size 128k
# audit-num 2
# remote udp dns server list
# server [IP]:[PORT] [-blacklist-ip] [-check-edns]
# server [IP]:[PORT] [-blacklist-ip] [-check-edns] [-group [group] ...] [-exclude-default-group]
# default port is 53
# -blacklist-ip: filter result with blacklist ip
# -check-edns: result must exist edns RR, or discard result.
# server 8.8.8.8 -blacklist-ip -check-edns
# -group [group]: set server to group, use with nameserver /domain/group.
# -exclude-default-group: exclude this server from default group.
# server 8.8.8.8 -blacklist-ip -check-edns -group g1 -group g2
# remote tcp dns server list
# server-tcp [IP]:[PORT] [-blacklist-ip]
# server-tcp [IP]:[PORT] [-blacklist-ip] [-group [group] ...] [-exclude-default-group]
# default port is 53
# server-tcp 8.8.8.8
# remote tls dns server list
# server-tls [IP]:[PORT] [-blacklist-ip] [-check-edns]
# server-tls [IP]:[PORT] [-blacklist-ip] [-spki-pin [sha256-pin]] [-group [group] ...] [-exclude-default-group]
# -spki-pin: TLS spki pin to verify.
# Get SKPI 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
# specific nameserver to domain
# nameserver /domain/[group|-]
# nameserver /www.example.com/office, Set the domain name to use the appropriate server group.
# nameserver /www.example.com/-, ignore this domain
# specific address to domain
# address /domain/ip
# address /www.example.com/1.2.3.4
# address /domain/[ip|-|-4|-6|#|#4|#6]
# address /www.example.com/1.2.3.4, return ip 1.2.3.4 to client
# address /www.example.com/-, ignore address, query from upstream, suffix 4, for ipv4, 6 for ipv6, none for all
# address /www.example.com/#, return SOA to client, suffix 4, for ipv4, 6 for ipv6, none for all
# enable ipset timeout by ttl feature
# ipset-timeout [yes]
# specific ipset to domain
# ipset /domain/ipset
# ipset /www.example.com/block
# ipset /domain/[ipset|-]
# ipset /www.example.com/block, set ipset with ipset name of block
# ipset /www.example.com/-, ignore this domain

40
install
View File

@@ -4,6 +4,7 @@
#
INST_DIR=$(cd $(dirname $0);pwd)
ISWSL=1 # 1 means not WSL, 0 means wsl
showhelp()
{
@@ -18,7 +19,7 @@ showhelp()
start_service()
{
if [ $ISSYSTEMD -ne 0 ]; then
chkconfig smartdns on
chkconfig smartdns on >/dev/null 2>&1
service smartdns start
return $?
fi
@@ -32,7 +33,7 @@ stop_service()
{
if [ $ISSYSTEMD -ne 0 ]; then
service smartdns stop
chkconfig smartdns off
chkconfig smartdns off >/dev/null 2>&1
return 0
fi
@@ -101,13 +102,17 @@ install_files()
uninstall_smartdns()
{
if [ -z "$PREFIX" ]; then
stop_service
stop_service 2>/dev/null
fi
rm -f $PREFIX$SMARTDNS_CONF_DIR/smartdns.conf
rmdir $PREFIX$SMARTDNS_CONF_DIR
rmdir $PREFIX$SMARTDNS_CONF_DIR 2>/dev/null
rm -f $PREFIX/usr/sbin/smartdns
rm -f $PREFIX/etc/default/smartdns
if [ $ISWSL -eq 0 ]; then
sed -i '\#%sudo ALL=NOPASSWD: /etc/init.d/smartdns#d' /etc/sudoers 2>/dev/null
fi
if [ $ISSYSTEMD -eq 0 ]; then
SYSTEM_UNIT_PATH="`get_systemd_path`"
if [ ! -z "$SYSTEM_UNIT_PATH" ]; then
@@ -125,6 +130,12 @@ install_smartdns()
{
local ret
which smartdns >/dev/null 2>&1
if [ $? -eq 0 ]; then
echo "Already installed."
return 1
fi
install_files
ret=$?
if [ $ret -ne 0 ]; then
@@ -136,17 +147,34 @@ install_smartdns()
start_service
fi
if [ $ISWSL -eq 0 ]; then
grep "%sudo ALL=NOPASSWD: /etc/init.d/smartdns" /etc/sudoers >/dev/null 2>&1
if [ $? -ne 0 ]; then
echo "%sudo ALL=NOPASSWD: /etc/init.d/smartdns" >> /etc/sudoers
fi
fi
return 0
}
init_dir()
{
local ID=`id -u`
if [ $ID -ne 0 ]; then
echo "Please run as root."
return 1
fi
SMARTDNS_CONF_DIR=$PREFIX/etc/smartdns
SMARTDNS_INIT_DIR=$PREFIX/etc/init.d
which systemctl >/dev/null 2>&1
ISSYSTEMD="$?"
# Running under WSL (Windows Subsystem for Linux)?
cat /proc/version | grep Microsoft >/dev/null 2>&1;
if [ $? -eq 0 ]; then
ISSYSTEMD=1
ISWSL=0
fi
cd $INST_DIR
}

View File

@@ -67,6 +67,12 @@ msgstr "双栈IP优选"
msgid "Enable IP selection between IPV4 and IPV6"
msgstr "启用或禁用IPV4IPV6间的IP优选策略。"
msgid "Domain prefetch"
msgstr "域名预加载"
msgid "Enable domain prefetch, accelerate domain response speed."
msgstr "启用域名预加载,加速域名响应速度。"
msgid "Redirect"
msgstr "重定向"
@@ -133,18 +139,36 @@ msgstr "协议类型"
msgid "Domain Address"
msgstr "域名地址"
msgid "Server Group"
msgstr "服务器组"
msgid "DNS Server group belongs to, used with nameserver, such as offlce, home."
msgsr "DNS服务器所属组 配合nameserver使用例如officehome。"
msgid "IP Blacklist Filtering"
msgstr "IP黑名单过滤"
msgid "Anti Answer Forgery"
msgstr "反回答伪造"
msgid "anti answer forgery, if DNS does not work properly after enabling, please turn off this feature"
msgid "Anti answer forgery, if DNS does not work properly after enabling, please turn off this feature"
msgstr "反回答伪造如果启用后DNS工作不正常请关闭此功能。"
msgid "Filtering IP with blacklist"
msgstr "使用IP黑名单过滤"
msgid "TLS SPKI Pinning"
msgstr "TLS SPKI 指纹"
msgid "Used to verify the validity of the TLS server, The value is Base64 encoded SPKI fingerprint, leaving blank to indicate that the validity of TLS is not verified."
msgstr "用于校验TLS服务器的有效性数值为Base64编码的SPKI指纹, 留空表示不验证TLS的合法性"
msgid "Additional Server Args"
msgstr "额外的服务器参数"
msgid "Additional Args for upstream dns servers"
msgstr "额外的上游DNS服务器参数"
msgid "Upstream DNS Server Configuration"
msgstr "上游DNS服务器配置"

View File

@@ -60,6 +60,14 @@ o.cfgvalue = function(...)
return Flag.cfgvalue(...) or "0"
end
---- Domain prefetch load
o = s:taboption("settings", Flag, "prefetch_domain", translate("Domain prefetch"), translate("Enable domain prefetch, accelerate domain response speed."))
o.rmempty = false
o.default = o.disabled
o.cfgvalue = function(...)
return Flag.cfgvalue(...) or "0"
end
---- Redirect
o = s:taboption("settings", ListValue, "redirect", translate("Redirect"), translate("SmartDNS redirect mode"))
o.placeholder = "none"

View File

@@ -13,6 +13,35 @@ s = m:section(NamedSection, sid, "server")
s.anonymous = true
s.addremove = false
---- name
s:option(Value, "name", translate("DNS Server Name"), translate("DNS Server Name"))
---- IP address
o = s:option(Value, "ip", translate("ip"), translate("DNS Server ip"))
o.datatype = "ipaddr"
o.rmempty = false
---- port
o = s:option(Value, "port", translate("port"), translate("DNS Server port"))
o.placeholder = "default"
o.datatype = "port"
o.rempty = true
---- type
o = s:option(ListValue, "type", translate("type"), translate("DNS Server type"))
o.placeholder = "udp"
o:value("udp", translate("udp"))
o:value("tcp", translate("tcp"))
o:value("tls", translate("tls"))
o.default = "udp"
o.rempty = false
---- server group
o = s:option(Value, "server_group", translate("Server Group"), translate("DNS Server group belongs to, used with nameserver, such as offlce, home."))
o.rmempty = true
o.placeholder = "default"
o.datatype = "hostname"
o.rempty = true
---- blacklist_ip
o = s:option(Flag, "blacklist_ip", translate("IP Blacklist Filtering"), translate("Filtering IP with blacklist"))
o.rmempty = false
@@ -22,11 +51,23 @@ 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 = s:option(Flag, "check_edns", translate("Anti Answer Forgery"), translate("Anti answer forgery, if DNS does not work properly after enabling, please turn off this feature"))
o.rmempty = false
o.default = o.disabled
o.cfgvalue = function(...)
return Flag.cfgvalue(...) or "0"
end
---- SPKI pin
o = s:option(Value, "spki_pin", translate("TLS SPKI Pinning"), translate("Used to verify the validity of the TLS server, The value is Base64 encoded SPKI fingerprint, leaving blank to indicate that the validity of TLS is not verified."))
o.default = ""
o.datatype = "wpakey"
o.rempty = true
---- other args
o = s:option(Value, "addition_arg", translate("Additional Server Args"), translate("Additional Args for upstream dns servers"))
o.default = ""
o.rempty = true
o.optional = true
return m

View File

@@ -63,7 +63,7 @@ build()
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
#rm -fr $ROOT/
rm -fr $ROOT/
}
main()

View File

@@ -1,3 +1,16 @@
# Add domains which you want to force to an IP address here.
# The example below send any host in example.com to a local webserver.
# address /example.com/127.0.0.1
# address /domain/[ip|-|-4|-6|#|#4|#6]
# address /www.example.com/1.2.3.4, return ip 1.2.3.4 to client
# address /www.example.com/-, ignore address, query from upstream, suffix 4, for ipv4, 6 for ipv6, none for all
# address /www.example.com/#, return SOA to client, suffix 4, for ipv4, 6 for ipv6, none for all
# specific ipset to domain
# ipset /domain/[ipset|-]
# ipset /www.example.com/block, set ipset with ipset name of block
# ipset /www.example.com/-, ignore this domain
# specific nameserver to domain
# nameserver /domain/[group|-]
# nameserver /www.example.com/office, Set the domain name to use the appropriate server group.
# nameserver /www.example.com/-, ignore this domain

View File

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

View File

@@ -136,8 +136,11 @@ load_server()
config_get "port" "$section" "port" ""
config_get "type" "$section" "type" "udp"
config_get "ip" "$section" "ip" ""
config_get "server_group" "$section" "server_group" ""
config_get "blacklist_ip" "$section" "blacklist_ip" "0"
config_get "check_edns" "$section" "check_edns" "0"
config_get "spki_pin" "$section" "spki_pin" ""
config_get "addition_arg" "$section" "addition_arg" ""
if [ "$enabled" = "0" ]; then
return
@@ -160,6 +163,10 @@ load_server()
fi
fi
if [ ! -z "$server_group" ]; then
ADDITIONAL_ARGS="$ADDITIONAL_ARGS -group $server_group"
fi
if [ "$blacklist_ip" != "0" ]; then
ADDITIONAL_ARGS="$ADDITIONAL_ARGS -blacklist-ip"
fi
@@ -168,13 +175,17 @@ load_server()
ADDITIONAL_ARGS="$ADDITIONAL_ARGS -check-edns"
fi
if [ ! -z "$spki_pin" ]; then
ADDITIONAL_ARGS="$ADDITIONAL_ARGS -spki-pin $spki_pin"
fi
if [ ! -z "$port" ]; then
DNS_ADDRESS="$ip:$port"
else
DNS_ADDRESS="$ip"
fi
conf_append "$SERVER" "$DNS_ADDRESS $ADDITIONAL_ARGS"
conf_append "$SERVER" "$DNS_ADDRESS $ADDITIONAL_ARGS $addition_arg"
}
load_service() {
@@ -217,6 +228,11 @@ load_service() {
conf_append "dualstack-ip-selection" "yes"
fi
config_get "prefetch_domain" "$section" "prefetch_domain" "0"
if [ "$prefetch_domain" = "1" ]; then
conf_append "prefetch-domain" "yes"
fi
SMARTDNS_PORT="$port"
config_get "cache_size" "$section" "cache_size" ""

View File

@@ -2,8 +2,20 @@
SMARTDNS_BIN=/opt/usr/sbin/smartdns
SMARTDNS_CONF=/opt/etc/smartdns/smartdns.conf
DNSMASQ_CONF=/etc/dnsmasq.conf
SMARTDNS_PID="/var/run/smartdns.pid"
SMARTDNS_PORT=535
SMARTDNS_OPT=/opt/etc/smartdns/smartdns-opt.conf
# workmode
# 0: run as port only
# 1: redirect port
# 2: replace
SMARTDNS_WORKMODE="1"
if [ -f "$SMARTDNS_OPT" ]; then
. $SMARTDNS_OPT
fi
set_iptable()
{
@@ -38,16 +50,165 @@ clear_iptable()
}
restart_dnsmasq()
{
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`"
fi
if [ -z "$CMD" ]; then
echo "cannot find dnsmasq"
return 1
fi
PID=`echo "$CMD" | awk '{print $1}'`
if [ ! -d "/proc/$PID" ]; then
echo "dnsmasq is not running"
return 1
fi
kill -9 $PID
DNSMASQ_CMD="`echo $CMD | awk '{for(i=5; i<=NF;i++)printf \$i " "}'`"
$DNSMASQ_CMD
}
get_server_ip()
{
IPS="`ifconfig | grep "inet addr" | grep -v ":127" | grep "Bcast" | awk '{print $2}' | awk -F: '{print $2}'`"
LOCAL_SERVER_IP=""
for IP in $IPS
do
N=3
while [ $N -gt 0 ]
do
ADDR=`echo $IP | awk -F. "{for(i=1;i<=$N;i++)printf \\$i\".\"}"`
grep "dhcp-range=" $DNSMASQ_CONF | 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}'`"
LOCAL_SERVER_IP="$IP"
return 0
fi
N="`expr $N - 1`"
done
done
return 1
}
set_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 [ $? -ne 0 ]; then
sed -i "/^dhcp-option *=$SERVER_TAG,6,/d" $DNSMASQ_CONF
echo "dhcp-option=$SERVER_TAG,6,$LOCAL_SERVER_IP" >> $DNSMASQ_CONF
RESTART_DNSMASQ=1
fi
fi
grep "^port *=0" $DNSMASQ_CONF > /dev/null 2>&1
if [ $? -ne 0 ]; then
sed -i "/^port *=/d" $DNSMASQ_CONF
echo "port=0" >> $DNSMASQ_CONF
RESTART_DNSMASQ=1
fi
if [ $RESTART_DNSMASQ -ne 0 ]; then
restart_dnsmasq
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
if [ $RESTART_DNSMASQ -ne 0 ]; then
restart_dnsmasq
fi
}
set_smartdns_port()
{
if [ "$SMARTDNS_WORKMODE" = "0" ]; then
return 0
elif [ "$SMARTDNS_WORKMODE" = "1" ]; then
sed -i "s/^\(bind .*\):53 *\(.*\)\$/\1:$SMARTDNS_PORT \2/g" $SMARTDNS_CONF
sed -i "s/^\(bind-tcp .*\):53 *\(.*\)\$/\1:$SMARTDNS_PORT \2/g" $SMARTDNS_CONF
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
else
return 1
fi
return 0
}
set_rule()
{
if [ "$SMARTDNS_WORKMODE" = "0" ]; then
return 0
elif [ "$SMARTDNS_WORKMODE" = "1" ]; then
set_iptable
return $?
elif [ "$SMARTDNS_WORKMODE" = "2" ]; then
set_dnsmasq
return $?
else
return 1
fi
}
clear_rule()
{
if [ "$SMARTDNS_WORKMODE" = "0" ]; then
return 0
elif [ "$SMARTDNS_WORKMODE" = "1" ]; then
clear_iptable
return $?
elif [ "$SMARTDNS_WORKMODE" = "2" ]; then
clear_dnsmasq
return $?
else
return 1
fi
}
case "$1" in
start)
set_iptable
set_rule
if [ $? -ne 0 ]; then
exit 1
fi
set_smartdns_port
$SMARTDNS_BIN -c $SMARTDNS_CONF -p $SMARTDNS_PID
if [ $? -ne 0 ]; then
clear_iptable
clear_rule
fi
;;
status)
@@ -65,7 +226,7 @@ case "$1" in
return 0;
;;
stop)
clear_iptable
clear_rule
pid="`cat $SMARTDNS_PID | head -n 1 2>/dev/null`"
if [ -z "$pid" ]; then
echo "smartdns not running."
@@ -78,7 +239,7 @@ case "$1" in
kill -9 $pid 2>/dev/null
;;
force-reload|restart)
restart)
$0 stop
$0 start
;;
@@ -89,7 +250,7 @@ case "$1" in
nvram set apps_state_action=install
nvram set apps_u2ec_ex=2
;;
firewall-start)
firewall-start|reload|force-reload|reconfigure)
$0 restart
;;
*)

View File

@@ -1 +1,2 @@
/opt/etc/smartdns/smartdns.conf
/opt/etc/smartdns/smartdns-opt.conf

View File

@@ -5,6 +5,7 @@ VER="`date +"1.%Y.%m.%d-%H%M"`"
SMARTDNS_DIR=$CURR_DIR/../../
SMARTDNS_BIN=$SMARTDNS_DIR/src/smartdns
SMARTDNS_CONF=$SMARTDNS_DIR/etc/smartdns/smartdns.conf
SMARTDNS_OPT=$CURR_DIR/smartdns-opt.conf
showhelp()
{
@@ -29,10 +30,10 @@ build()
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
sed -i "s/^\(bind .*\):53/\1:535/g" $ROOT/opt/etc/smartdns/smartdns.conf
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

View File

@@ -0,0 +1,8 @@
# workmode
# 0: run as port only
# 1: redirect port
# 2: replace
SMARTDNS_WORKMODE="1"
# smartdns port
SMARTDNS_PORT="535"

View File

@@ -0,0 +1,21 @@
@echo off
set "CURR_PATH=%~dp0"
set "STARTUP_PATH=%userprofile%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"
FOR /F %%i IN ('wsl pwd') DO @set DIR_IN_WSL=%%i
wsl sudo %DIR_IN_WSL%/../../install -i
IF NOT %ERRORLEVEL% == 0 (
echo Install smartdns failed.
pause
exit 1
)
copy %CURR_PATH%\wsl-run.vbs "%STARTUP_PATH%/"
IF NOT %ERRORLEVEL% == 0 (
echo Install startupt script failed.
pause
exit 1
)
echo Install smartdns success
pause

View File

@@ -0,0 +1,21 @@
@echo off
set "CURR_PATH=%~dp0"
set "STARTUP_PATH=%userprofile%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"
FOR /F %%i IN ('wsl pwd') DO @set DIR_IN_WSL=%%i
wsl sudo cp -avf %DIR_IN_WSL%/../../etc/smartdns/* /etc/smartdns/
IF NOT %ERRORLEVEL% == 0 (
echo copy smartdns configuration file failed.
pause
exit 1
)
wsl sudo /etc/init.d/smartdns restart
IF NOT %ERRORLEVEL% == 0 (
echo reload smartdns failed.
pause
exit 1
)
echo reload smartdns success
pause

View File

@@ -0,0 +1,22 @@
@echo off
set "CURR_PATH=%~dp0"
set "STARTUP_PATH=%userprofile%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"
FOR /F %%i IN ('wsl pwd') DO @set DIR_IN_WSL=%%i
wsl sudo %DIR_IN_WSL%/../../install -u
IF NOT %ERRORLEVEL% == 0 (
echo Uninstall smartdns failed.
pause
exit 1
)
del "%STARTUP_PATH%\wsl-run.vbs"
IF NOT %ERRORLEVEL% == 0 (
echo Uninstall startup script failed.
pause
exit 1
)
echo uninstall success
pause

View File

@@ -0,0 +1,2 @@
Set ws = WScript.CreateObject("WScript.Shell")
ws.run "wsl sudo /etc/init.d/smartdns restart", vbhide

View File

@@ -2,10 +2,10 @@
BIN=smartdns
OBJS_LIB=lib/rbtree.o lib/art.o lib/bitops.o lib/radix.o lib/conf.o
OBJS=smartdns.o fast_ping.o dns_client.o dns_server.o dns.o util.o tlog.o dns_conf.o dns_cache.o $(OBJS_LIB)
CFLAGS +=-O2 -Wall -Wstrict-prototypes -fno-omit-frame-pointer -Wstrict-aliasing
CFLAGS +=-O2 -g -Wall -Wstrict-prototypes -fno-omit-frame-pointer -Wstrict-aliasing
CFLAGS +=-Iinclude
CFLAGS += -DBASE_FILE_NAME=\"$(notdir $<)\"
CXXFLAGS=-O2 -Wall -std=c++11
CXXFLAGS=-O2 -g -Wall -std=c++11
CXXFLAGS +=-Iinclude
LDFLAGS += -lpthread -lssl -lcrypto

409
src/dns.c
View File

@@ -25,6 +25,7 @@
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <arpa/inet.h>
#define QR_MASK 0x8000
#define OPCODE_MASK 0x7800
@@ -35,10 +36,13 @@
#define RCODE_MASK 0x000F
#define DNS_RR_END (0XFFFF)
#define UNUSED(expr) do { (void)(expr); } while (0)
#define UNUSED(expr) \
do { \
(void)(expr); \
} while (0)
/* read short and move pointer */
short dns_read_short(unsigned char **buffer)
static short _dns_read_short(unsigned char **buffer)
{
unsigned short value;
@@ -48,14 +52,14 @@ short dns_read_short(unsigned char **buffer)
}
/* write char and move pointer */
void dns_write_char(unsigned char **buffer, unsigned char value)
static __attribute__((unused)) void _dns_write_char(unsigned char **buffer, unsigned char value)
{
**buffer = value;
*buffer += 1;
}
/* read char and move pointer */
unsigned char dns_read_char(unsigned char **buffer)
static unsigned char _dns_read_char(unsigned char **buffer)
{
unsigned char value = **buffer;
*buffer += 1;
@@ -63,7 +67,7 @@ unsigned char dns_read_char(unsigned char **buffer)
}
/* write short and move pointer */
void dns_write_short(unsigned char **buffer, unsigned short value)
static void _dns_write_short(unsigned char **buffer, unsigned short value)
{
value = htons(value);
*((unsigned short *)(*buffer)) = value;
@@ -71,7 +75,7 @@ void dns_write_short(unsigned char **buffer, unsigned short value)
}
/* write int and move pointer */
void dns_write_int(unsigned char **buffer, unsigned int value)
static void _dns_write_int(unsigned char **buffer, unsigned int value)
{
value = htonl(value);
*((unsigned int *)(*buffer)) = value;
@@ -79,7 +83,7 @@ void dns_write_int(unsigned char **buffer, unsigned int value)
}
/* read int and move pointer */
unsigned int dns_read_int(unsigned char **buffer)
static unsigned int _dns_read_int(unsigned char **buffer)
{
unsigned int value;
@@ -113,6 +117,10 @@ struct dns_rrs *dns_get_rrs_start(struct dns_packet *packet, dns_rr_type type, i
*count = head->nrcount;
start = packet->additional;
break;
case DNS_RRS_OPT:
*count = packet->optcount;
start = packet->optional;
break;
default:
return NULL;
break;
@@ -138,14 +146,14 @@ struct dns_rrs *dns_get_rrs_next(struct dns_packet *packet, struct dns_rrs *rrs)
}
/* iterator add rrs begin */
unsigned char *_dns_add_rrs_start(struct dns_packet *packet, int *maxlen)
static unsigned char *_dns_add_rrs_start(struct dns_packet *packet, int *maxlen)
{
struct dns_rrs *rrs;
unsigned char *end = packet->data + packet->len;
rrs = (struct dns_rrs *)end;
*maxlen = packet->size - packet->len - sizeof(*packet);
if (packet->len >= packet->size - sizeof(*packet)) {
*maxlen = packet->size - packet->len - sizeof(*packet) - sizeof(*rrs);
if (*maxlen <= 0) {
/* if size exceeds max packet size, return NULL */
return NULL;
}
@@ -153,7 +161,7 @@ unsigned char *_dns_add_rrs_start(struct dns_packet *packet, int *maxlen)
}
/* iterator add rrs end */
int dns_rr_add_end(struct dns_packet *packet, int type, dns_type_t rtype, int len)
static int _dns_rr_add_end(struct dns_packet *packet, int type, dns_type_t rtype, int len)
{
struct dns_rrs *rrs;
struct dns_rrs *rrs_next;
@@ -163,7 +171,7 @@ int dns_rr_add_end(struct dns_packet *packet, int type, dns_type_t rtype, int le
unsigned short *start;
rrs = (struct dns_rrs *)end;
if (packet->len + len > packet->size - sizeof(*packet)) {
if (packet->len + len > packet->size - sizeof(*packet) - sizeof(*rrs)) {
return -1;
}
@@ -187,6 +195,7 @@ int dns_rr_add_end(struct dns_packet *packet, int type, dns_type_t rtype, int le
case DNS_RRS_OPT:
count = &packet->optcount;
start = &packet->optional;
break;
default:
return -1;
break;
@@ -220,14 +229,14 @@ static inline int _dns_data_left_len(struct dns_data_context *data_context)
return data_context->maxsize - (data_context->ptr - data_context->data);
}
int _dns_add_qr_head(struct dns_data_context *data_context, char *domain, int qtype, int qclass)
static int _dns_add_qr_head(struct dns_data_context *data_context, char *domain, int qtype, int qclass)
{
/* question head */
/* |domain |
* |qtype | qclass |
*/
while (1) {
if (_dns_data_left_len(data_context) < 1) {
if (_dns_data_left_len(data_context) < 4) {
return -1;
}
*data_context->ptr = *domain;
@@ -252,15 +261,15 @@ int _dns_add_qr_head(struct dns_data_context *data_context, char *domain, int qt
return 0;
}
int _dns_get_qr_head(struct dns_data_context *data_context, char *domain, int maxsize, int *qtype, int *qclass)
static int _dns_get_qr_head(struct dns_data_context *data_context, char *domain, int maxsize, int *qtype, int *qclass)
{
int i;
/* question head */
/* |domain |
* |qtype | qclass |
*/
for (i = 0; i < maxsize; i++) {
if (_dns_data_left_len(data_context) < 1) {
for (i = 0; i < maxsize - 1; i++) {
if (_dns_data_left_len(data_context) < 4) {
return -1;
}
*domain = *data_context->ptr;
@@ -275,6 +284,8 @@ int _dns_get_qr_head(struct dns_data_context *data_context, char *domain, int ma
data_context->ptr++;
}
*domain = '\0';
if (_dns_data_left_len(data_context) < 4) {
return -1;
}
@@ -288,7 +299,7 @@ int _dns_get_qr_head(struct dns_data_context *data_context, char *domain, int ma
return 0;
}
int _dns_add_rr_head(struct dns_data_context *data_context, char *domain, int qtype, int qclass, int ttl, int rr_len)
static int _dns_add_rr_head(struct dns_data_context *data_context, char *domain, int qtype, int qclass, int ttl, int rr_len)
{
int len = 0;
@@ -316,7 +327,7 @@ int _dns_add_rr_head(struct dns_data_context *data_context, char *domain, int qt
return 0;
}
int _dns_get_rr_head(struct dns_data_context *data_context, char *domain, int maxsize, int *qtype, int *qclass, int *ttl, int *rr_len)
static int _dns_get_rr_head(struct dns_data_context *data_context, char *domain, int maxsize, int *qtype, int *qclass, int *ttl, int *rr_len)
{
int len = 0;
@@ -341,7 +352,7 @@ int _dns_get_rr_head(struct dns_data_context *data_context, char *domain, int ma
return len;
}
int dns_add_RAW(struct dns_packet *packet, dns_rr_type rrtype, dns_type_t rtype, char *domain, int ttl, void *raw, int raw_len)
static int _dns_add_RAW(struct dns_packet *packet, dns_rr_type rrtype, dns_type_t rtype, char *domain, int ttl, void *raw, int raw_len)
{
int maxlen = 0;
int len = 0;
@@ -377,10 +388,10 @@ int dns_add_RAW(struct dns_packet *packet, dns_rr_type rrtype, dns_type_t rtype,
data_context.ptr += raw_len;
len = data_context.ptr - data_context.data;
return dns_rr_add_end(packet, rrtype, rtype, len);
return _dns_rr_add_end(packet, rrtype, rtype, len);
}
int dns_get_RAW(struct dns_rrs *rrs, char *domain, int maxsize, int *ttl, void *raw, int *raw_len)
static int _dns_get_RAW(struct dns_rrs *rrs, char *domain, int maxsize, int *ttl, void *raw, int *raw_len)
{
int qtype = 0;
int qclass = 0;
@@ -418,10 +429,33 @@ int dns_get_RAW(struct dns_rrs *rrs, char *domain, int maxsize, int *ttl, void *
return 0;
}
int dns_add_OPT(struct dns_packet *packet, dns_rr_type type, unsigned short opt_code, unsigned short opt_len, struct dns_opt *opt)
static int _dns_add_opt_RAW(struct dns_packet *packet, dns_opt_code_t opt_rrtype, void *raw, int raw_len)
{
unsigned char opt_data[DNS_MAX_OPT_LEN];
struct dns_opt *opt = (struct dns_opt *)opt_data;
int len = 0;
opt->code = DNS_OPT_T_TCP_KEEPALIVE;
opt->length = sizeof(unsigned short);
memcpy(opt->data, raw, raw_len);
len += raw_len;
len += sizeof(*opt);
return _dns_add_RAW(packet, DNS_RRS_OPT, DNS_OPT_T_TCP_KEEPALIVE, "", 0, opt_data, len);
}
static int _dns_get_opt_RAW(struct dns_rrs *rrs, char *domain, int maxsize, int *ttl, struct dns_opt *dns_opt, int *dns_optlen)
{
*dns_optlen = DNS_MAX_OPT_LEN;
return _dns_get_RAW(rrs, domain, maxsize, ttl, dns_opt, dns_optlen);
}
static int __attribute__((unused)) _dns_add_OPT(struct dns_packet *packet, dns_rr_type type, unsigned short opt_code, unsigned short opt_len, struct dns_opt *opt)
{
// TODO
int maxlen = 0;
int len = 0;
struct dns_data_context data_context;
@@ -429,15 +463,15 @@ int dns_add_OPT(struct dns_packet *packet, dns_rr_type type, unsigned short opt_
int ttl = 0;
/*
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
0: | OPTION-CODE |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
2: | OPTION-LENGTH |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
4: | |
/ OPTION-DATA /
/ /
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
/ OPTION-DATA /
/ /
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
*/
unsigned char *data = _dns_add_rrs_start(packet, &maxlen);
if (data == NULL) {
@@ -465,10 +499,10 @@ int dns_add_OPT(struct dns_packet *packet, dns_rr_type type, unsigned short opt_
data_context.ptr += total_len;
len = data_context.ptr - data_context.data;
return dns_rr_add_end(packet, type, DNS_T_OPT, len);
return _dns_rr_add_end(packet, type, DNS_T_OPT, len);
}
int dns_get_OPT(struct dns_rrs *rrs, unsigned short *opt_code, unsigned short *opt_len, struct dns_opt *opt, int *opt_maxlen)
static int __attribute__((unused)) _dns_get_OPT(struct dns_rrs *rrs, unsigned short *opt_code, unsigned short *opt_len, struct dns_opt *opt, int *opt_maxlen)
{
// TODO
@@ -506,63 +540,62 @@ int dns_get_OPT(struct dns_rrs *rrs, unsigned short *opt_code, unsigned short *o
return 0;
}
int dns_add_CNAME(struct dns_packet *packet, dns_rr_type type, char *domain, int ttl, char *cname)
{
int rr_len = strnlen(cname, DNS_MAX_CNAME_LEN) + 1;
return dns_add_RAW(packet, type, DNS_T_CNAME, domain, ttl, cname, rr_len);
return _dns_add_RAW(packet, type, DNS_T_CNAME, domain, ttl, cname, rr_len);
}
int dns_get_CNAME(struct dns_rrs *rrs, char *domain, int maxsize, int *ttl, char *cname, int cname_size)
{
int len = cname_size;
return dns_get_RAW(rrs, domain, maxsize, ttl, cname, &len);
return _dns_get_RAW(rrs, domain, maxsize, ttl, cname, &len);
}
int dns_add_A(struct dns_packet *packet, dns_rr_type type, char *domain, int ttl, unsigned char addr[DNS_RR_A_LEN])
{
return dns_add_RAW(packet, type, DNS_T_A, domain, ttl, addr, DNS_RR_A_LEN);
return _dns_add_RAW(packet, type, DNS_T_A, domain, ttl, addr, DNS_RR_A_LEN);
}
int dns_get_A(struct dns_rrs *rrs, char *domain, int maxsize, int *ttl, unsigned char addr[DNS_RR_A_LEN])
{
int len = DNS_RR_A_LEN;
return dns_get_RAW(rrs, domain, maxsize, ttl, addr, &len);
return _dns_get_RAW(rrs, domain, maxsize, ttl, addr, &len);
}
int dns_add_PTR(struct dns_packet *packet, dns_rr_type type, char *domain, int ttl, char *cname)
{
int rr_len = strnlen(cname, DNS_MAX_CNAME_LEN) + 1;
return dns_add_RAW(packet, type, DNS_T_PTR, domain, ttl, cname, rr_len);
return _dns_add_RAW(packet, type, DNS_T_PTR, domain, ttl, cname, rr_len);
}
int dns_get_PTR(struct dns_rrs *rrs, char *domain, int maxsize, int *ttl, char *cname, int cname_size)
{
int len = cname_size;
return dns_get_RAW(rrs, domain, maxsize, ttl, cname, &len);
return _dns_get_RAW(rrs, domain, maxsize, ttl, cname, &len);
}
int dns_add_NS(struct dns_packet *packet, dns_rr_type type, char *domain, int ttl, char *cname)
{
int rr_len = strnlen(cname, DNS_MAX_CNAME_LEN) + 1;
return dns_add_RAW(packet, type, DNS_T_NS, domain, ttl, cname, rr_len);
return _dns_add_RAW(packet, type, DNS_T_NS, domain, ttl, cname, rr_len);
}
int dns_get_NS(struct dns_rrs *rrs, char *domain, int maxsize, int *ttl, char *cname, int cname_size)
{
int len = cname_size;
return dns_get_RAW(rrs, domain, maxsize, ttl, cname, &len);
return _dns_get_RAW(rrs, domain, maxsize, ttl, cname, &len);
}
int dns_add_AAAA(struct dns_packet *packet, dns_rr_type type, char *domain, int ttl, unsigned char addr[DNS_RR_AAAA_LEN])
{
return dns_add_RAW(packet, type, DNS_T_AAAA, domain, ttl, addr, DNS_RR_AAAA_LEN);
return _dns_add_RAW(packet, type, DNS_T_AAAA, domain, ttl, addr, DNS_RR_AAAA_LEN);
}
int dns_get_AAAA(struct dns_rrs *rrs, char *domain, int maxsize, int *ttl, unsigned char addr[DNS_RR_AAAA_LEN])
{
int len = DNS_RR_AAAA_LEN;
return dns_get_RAW(rrs, domain, maxsize, ttl, addr, &len);
return _dns_get_RAW(rrs, domain, maxsize, ttl, addr, &len);
}
int dns_add_SOA(struct dns_packet *packet, dns_rr_type type, char *domain, int ttl, struct dns_soa *soa)
@@ -595,7 +628,7 @@ int dns_add_SOA(struct dns_packet *packet, dns_rr_type type, char *domain, int t
ptr += 4;
len = ptr - data;
return dns_add_RAW(packet, type, DNS_T_SOA, domain, ttl, data, len);
return _dns_add_RAW(packet, type, DNS_T_SOA, domain, ttl, data, len);
}
int dns_get_SOA(struct dns_rrs *rrs, char *domain, int maxsize, int *ttl, struct dns_soa *soa)
@@ -613,7 +646,7 @@ int dns_get_SOA(struct dns_rrs *rrs, char *domain, int maxsize, int *ttl, struct
*| expire |
*| minimum |
*/
if (dns_get_RAW(rrs, domain, maxsize, ttl, data, &len) != 0) {
if (_dns_get_RAW(rrs, domain, maxsize, ttl, data, &len) != 0) {
return -1;
}
@@ -671,7 +704,7 @@ int dns_add_OPT_ECS(struct dns_packet *packet, struct dns_opt_ecs *ecs)
len += (ecs->source_prefix / 8);
len += (ecs->source_prefix % 8 > 0) ? 1 : 0;
return dns_add_RAW(packet, DNS_RRS_OPT, DNS_OPT_T_ECS, "", 0, opt_data, len);
return _dns_add_RAW(packet, DNS_RRS_OPT, DNS_OPT_T_ECS, "", 0, opt_data, len);
}
int dns_get_OPT_ECS(struct dns_rrs *rrs, unsigned short *opt_code, unsigned short *opt_len, struct dns_opt_ecs *ecs)
@@ -681,7 +714,7 @@ int dns_get_OPT_ECS(struct dns_rrs *rrs, unsigned short *opt_code, unsigned shor
int len = DNS_MAX_OPT_LEN;
int ttl = 0;
if (dns_get_RAW(rrs, 0, 0, &ttl, opt_data, &len) != 0) {
if (_dns_get_RAW(rrs, NULL, 0, &ttl, opt_data, &len) != 0) {
return -1;
}
@@ -698,6 +731,54 @@ int dns_get_OPT_ECS(struct dns_rrs *rrs, unsigned short *opt_code, unsigned shor
return 0;
}
int dns_add_OPT_TCP_KEEYALIVE(struct dns_packet *packet, unsigned short timeout)
{
unsigned short timeout_net = htons(timeout);
int data_len = 0;
if (timeout > 0) {
data_len = sizeof(timeout);
}
return _dns_add_opt_RAW(packet, DNS_OPT_T_TCP_KEEPALIVE, &timeout_net, data_len);
}
int dns_get_OPT_TCP_KEEYALIVE(struct dns_rrs *rrs, unsigned short *opt_code, unsigned short *opt_len, unsigned short *timeout)
{
unsigned char opt_data[DNS_MAX_OPT_LEN];
struct dns_opt *opt = (struct dns_opt *)opt_data;
int len = DNS_MAX_OPT_LEN;
int ttl = 0;
unsigned char *data = NULL;
if (_dns_get_opt_RAW(rrs, NULL, 0, &ttl, opt, &len) != 0) {
return -1;
}
if (len < sizeof(*opt)) {
return -1;
}
if (opt->code != DNS_OPT_T_TCP_KEEPALIVE) {
return -1;
}
if (opt->length == 0) {
*timeout = 0;
return 0;
}
if (opt->length != sizeof(unsigned short)) {
return -1;
}
data = opt->data;
*timeout = _dns_read_short(&data);
return 0;
}
/*
* Format:
* |DNS_NAME\0(string)|qtype(short)|qclass(short)|
@@ -724,7 +805,7 @@ int dns_add_domain(struct dns_packet *packet, char *domain, int qtype, int qclas
len = data_context.ptr - data_context.data;
return dns_rr_add_end(packet, DNS_RRS_QD, DNS_T_CNAME, len);
return _dns_rr_add_end(packet, DNS_RRS_QD, DNS_T_CNAME, len);
}
int dns_get_domain(struct dns_rrs *rrs, char *domain, int maxsize, int *qtype, int *qclass)
@@ -775,8 +856,8 @@ static int _dns_decode_head(struct dns_context *context)
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
*/
head->id = dns_read_short(&context->ptr);
fields = dns_read_short(&context->ptr);
head->id = _dns_read_short(&context->ptr);
fields = _dns_read_short(&context->ptr);
head->qr = (fields & QR_MASK) >> 15;
head->opcode = (fields & OPCODE_MASK) >> 11;
head->aa = (fields & AA_MASK) >> 10;
@@ -784,10 +865,10 @@ static int _dns_decode_head(struct dns_context *context)
head->rd = (fields & RD_MASK) >> 8;
head->ra = (fields & RA_MASK) >> 7;
head->rcode = (fields & RCODE_MASK) >> 0;
head->qdcount = dns_read_short(&context->ptr);
head->ancount = dns_read_short(&context->ptr);
head->nscount = dns_read_short(&context->ptr);
head->nrcount = dns_read_short(&context->ptr);
head->qdcount = _dns_read_short(&context->ptr);
head->ancount = _dns_read_short(&context->ptr);
head->nscount = _dns_read_short(&context->ptr);
head->nrcount = _dns_read_short(&context->ptr);
return 0;
}
@@ -801,7 +882,7 @@ static int _dns_encode_head(struct dns_context *context)
return -1;
}
dns_write_short(&context->ptr, head->id);
_dns_write_short(&context->ptr, head->id);
int fields = 0;
fields |= (head->qr << 15) & QR_MASK;
@@ -811,12 +892,12 @@ static int _dns_encode_head(struct dns_context *context)
fields |= (head->rd << 8) & RD_MASK;
fields |= (head->ra << 7) & RA_MASK;
fields |= (head->rcode << 0) & RCODE_MASK;
dns_write_short(&context->ptr, fields);
_dns_write_short(&context->ptr, fields);
dns_write_short(&context->ptr, head->qdcount);
dns_write_short(&context->ptr, head->ancount);
dns_write_short(&context->ptr, head->nscount);
dns_write_short(&context->ptr, head->nrcount);
_dns_write_short(&context->ptr, head->qdcount);
_dns_write_short(&context->ptr, head->ancount);
_dns_write_short(&context->ptr, head->nscount);
_dns_write_short(&context->ptr, head->nrcount);
return len;
}
@@ -827,10 +908,10 @@ static int _dns_encode_head_count(struct dns_context *context)
unsigned char *ptr = context->data;
ptr += 4;
dns_write_short(&ptr, head->qdcount);
dns_write_short(&ptr, head->ancount);
dns_write_short(&ptr, head->nscount);
dns_write_short(&ptr, head->nrcount);
_dns_write_short(&ptr, head->qdcount);
_dns_write_short(&ptr, head->ancount);
_dns_write_short(&ptr, head->nscount);
_dns_write_short(&ptr, head->nrcount);
return len;
}
@@ -838,16 +919,17 @@ static int _dns_decode_domain(struct dns_context *context, char *output, int siz
{
int output_len = 0;
int copy_len = 0;
int len = *(context->ptr);
int len = 0;
unsigned char *ptr = context->ptr;
int is_compressed = 0;
int ptr_jump = 0;
/*[len]string[len]string...[0]0 */
while (1) {
if (ptr > context->data + context->maxsize || ptr < context->data) {
if (ptr > context->data + context->maxsize || ptr < context->data || output_len >= size - 1 || ptr_jump > 4) {
return -1;
}
len = *ptr;
if (len == 0) {
*output = 0;
@@ -867,7 +949,7 @@ static int _dns_decode_domain(struct dns_context *context, char *output, int siz
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
*/
/* read offset */
len = dns_read_short(&ptr) & 0x3FFF;
len = _dns_read_short(&ptr) & 0x3FFF;
if (is_compressed == 0) {
context->ptr = ptr;
}
@@ -877,13 +959,17 @@ static int _dns_decode_domain(struct dns_context *context, char *output, int siz
return -1;
}
is_compressed = 1;
ptr_jump++;
continue;
}
ptr_jump = 0;
/* change [len] to '.' */
if (output_len > 0) {
*output = '.';
output++;
output_len += 1;
}
if (ptr > context->data + context->maxsize) {
@@ -950,7 +1036,7 @@ static int _dns_decode_qr_head(struct dns_context *context, char *domain, int do
{
int ret = 0;
/*
0 1 2 3 4 5 6 7 8 9 A B C D E F
0 1 2 3 4 5 6 7 8 9 A B C D E F
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| |
/ /
@@ -973,8 +1059,8 @@ static int _dns_decode_qr_head(struct dns_context *context, char *domain, int do
return -1;
}
*qtype = dns_read_short(&context->ptr);
*qclass = dns_read_short(&context->ptr);
*qtype = _dns_read_short(&context->ptr);
*qclass = _dns_read_short(&context->ptr);
return 0;
}
@@ -991,8 +1077,8 @@ static int _dns_encode_qr_head(struct dns_context *context, char *domain, int qt
return -1;
}
dns_write_short(&context->ptr, qtype);
dns_write_short(&context->ptr, qclass);
_dns_write_short(&context->ptr, qtype);
_dns_write_short(&context->ptr, qclass);
return 0;
}
@@ -1012,8 +1098,8 @@ static int _dns_decode_rr_head(struct dns_context *context, char *domain, int do
return -1;
}
*ttl = dns_read_int(&context->ptr);
*rr_len = dns_read_short(&context->ptr);
*ttl = _dns_read_int(&context->ptr);
*rr_len = _dns_read_short(&context->ptr);
return 0;
}
@@ -1030,8 +1116,8 @@ static int _dns_encode_rr_head(struct dns_context *context, char *domain, int qt
return -1;
}
dns_write_int(&context->ptr, ttl);
dns_write_short(&context->ptr, rr_len);
_dns_write_int(&context->ptr, ttl);
_dns_write_short(&context->ptr, rr_len);
return 0;
}
@@ -1046,7 +1132,7 @@ static int _dns_encode_raw(struct dns_context *context, struct dns_rrs *rrs)
int rr_len;
struct dns_data_context data_context;
/*
0 1 2 3 4 5 6 7 8 9 A B C D E F
0 1 2 3 4 5 6 7 8 9 A B C D E F
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| |
/ /
@@ -1103,7 +1189,7 @@ static int _dns_decode_raw(struct dns_context *context, unsigned char *raw, int
return 0;
}
int _dns_decode_CNAME(struct dns_context *context, char *cname, int cname_size)
static int _dns_decode_CNAME(struct dns_context *context, char *cname, int cname_size)
{
int ret = 0;
ret = _dns_decode_domain(context, cname, cname_size);
@@ -1114,7 +1200,7 @@ int _dns_decode_CNAME(struct dns_context *context, char *cname, int cname_size)
return 0;
}
int _dns_encode_CNAME(struct dns_context *context, struct dns_rrs *rrs)
static int _dns_encode_CNAME(struct dns_context *context, struct dns_rrs *rrs)
{
int ret;
int qtype = 0;
@@ -1154,7 +1240,7 @@ int _dns_encode_CNAME(struct dns_context *context, struct dns_rrs *rrs)
return 0;
}
int _dns_decode_SOA(struct dns_context *context, struct dns_soa *soa)
static int _dns_decode_SOA(struct dns_context *context, struct dns_soa *soa)
{
int ret = 0;
ret = _dns_decode_domain(context, soa->mname, DNS_MAX_CNAME_LEN - 1);
@@ -1171,16 +1257,16 @@ int _dns_decode_SOA(struct dns_context *context, struct dns_soa *soa)
return -1;
}
soa->serial = dns_read_int(&context->ptr);
soa->refresh = dns_read_int(&context->ptr);
soa->retry = dns_read_int(&context->ptr);
soa->expire = dns_read_int(&context->ptr);
soa->minimum = dns_read_int(&context->ptr);
soa->serial = _dns_read_int(&context->ptr);
soa->refresh = _dns_read_int(&context->ptr);
soa->retry = _dns_read_int(&context->ptr);
soa->expire = _dns_read_int(&context->ptr);
soa->minimum = _dns_read_int(&context->ptr);
return 0;
}
int _dns_encode_SOA(struct dns_context *context, struct dns_rrs *rrs)
static int _dns_encode_SOA(struct dns_context *context, struct dns_rrs *rrs)
{
int ret;
int qtype = 0;
@@ -1230,33 +1316,32 @@ int _dns_encode_SOA(struct dns_context *context, struct dns_rrs *rrs)
return -1;
}
dns_write_int(&context->ptr, *(unsigned int *)data_context.ptr);
_dns_write_int(&context->ptr, *(unsigned int *)data_context.ptr);
data_context.ptr += 4;
dns_write_int(&context->ptr, *(unsigned int *)data_context.ptr);
_dns_write_int(&context->ptr, *(unsigned int *)data_context.ptr);
data_context.ptr += 4;
dns_write_int(&context->ptr, *(unsigned int *)data_context.ptr);
_dns_write_int(&context->ptr, *(unsigned int *)data_context.ptr);
data_context.ptr += 4;
dns_write_int(&context->ptr, *(unsigned int *)data_context.ptr);
_dns_write_int(&context->ptr, *(unsigned int *)data_context.ptr);
data_context.ptr += 4;
dns_write_int(&context->ptr, *(unsigned int *)data_context.ptr);
_dns_write_int(&context->ptr, *(unsigned int *)data_context.ptr);
data_context.ptr += 4;
return 0;
}
static int _dns_decode_opt_ecs(struct dns_context *context, struct dns_opt_ecs *ecs)
{
// TODO
int len = 0;
if (_dns_left_len(context) < 4) {
return -1;
}
ecs->family = dns_read_short(&context->ptr);
ecs->source_prefix = dns_read_char(&context->ptr);
ecs->scope_prefix = dns_read_char(&context->ptr);
ecs->family = _dns_read_short(&context->ptr);
ecs->source_prefix = _dns_read_char(&context->ptr);
ecs->scope_prefix = _dns_read_char(&context->ptr);
len = (ecs->source_prefix / 8);
len += (ecs->source_prefix % 8 > 0) ? 1 : 0;
@@ -1273,7 +1358,7 @@ static int _dns_decode_opt_ecs(struct dns_context *context, struct dns_opt_ecs *
return 0;
}
int _dns_encode_OPT(struct dns_context *context, struct dns_rrs *rrs)
static int _dns_encode_OPT(struct dns_context *context, struct dns_rrs *rrs)
{
int ret;
int opt_code = 0;
@@ -1282,6 +1367,7 @@ int _dns_encode_OPT(struct dns_context *context, struct dns_rrs *rrs)
struct dns_data_context data_context;
int rr_len = 0;
int ttl;
struct dns_opt *dns_opt = NULL;
data_context.data = rrs->data;
data_context.ptr = rrs->data;
@@ -1292,19 +1378,29 @@ int _dns_encode_OPT(struct dns_context *context, struct dns_rrs *rrs)
return -1;
}
if (_dns_left_len(context) < (4 + rr_len)) {
if (rr_len < sizeof(*dns_opt)) {
return -1;
}
dns_write_short(&context->ptr, opt_code);
dns_write_short(&context->ptr, rr_len);
memcpy(context->ptr, data_context.ptr, rr_len);
context->ptr += rr_len;
if (_dns_left_len(context) < (rr_len)) {
return -1;
}
dns_opt = (struct dns_opt *)data_context.ptr;
_dns_write_short(&context->ptr, dns_opt->code);
_dns_write_short(&context->ptr, dns_opt->length);
if (_dns_left_len(context) < dns_opt->length) {
return -1;
}
memcpy(context->ptr, dns_opt->data, dns_opt->length);
context->ptr += dns_opt->length;
return 0;
}
int _dns_get_opts_data_len(struct dns_packet *packet, struct dns_rrs *rrs, int count)
static int _dns_get_opts_data_len(struct dns_packet *packet, struct dns_rrs *rrs, int count)
{
int i = 0;
int len = 0;
@@ -1332,7 +1428,7 @@ int _dns_get_opts_data_len(struct dns_packet *packet, struct dns_rrs *rrs, int c
return len;
}
int _dns_encode_opts(struct dns_packet *packet, struct dns_context *context, struct dns_rrs *rrs, int count)
static int _dns_encode_opts(struct dns_packet *packet, struct dns_context *context, struct dns_rrs *rrs, int count)
{
int i = 0;
int len = 0;
@@ -1374,7 +1470,7 @@ static int _dns_decode_opt(struct dns_context *context, dns_rr_type type, unsign
unsigned short opt_code;
unsigned short opt_len;
unsigned short ercode = (ttl >> 16) & 0xFFFF;
unsigned short ever = (ttl) & 0xFFFF;
unsigned short ever = (ttl)&0xFFFF;
unsigned char *start = context->ptr;
struct dns_packet *packet = context->packet;
int ret = 0;
@@ -1382,63 +1478,73 @@ static int _dns_decode_opt(struct dns_context *context, dns_rr_type type, unsign
UNUSED(ever);
/*
Field Name Field Type Description
------------------------------------------------------
NAME domain name empty (root domain)
TYPE u_int16_t OPT
CLASS u_int16_t sender's UDP payload size
TTL u_int32_t extended RCODE and flags
RDLEN u_int16_t describes RDATA
RDATA octet stream {attribute,value} pairs
Field Name Field Type Description
------------------------------------------------------
NAME domain name empty (root domain)
TYPE u_int16_t OPT
CLASS u_int16_t sender's UDP payload size
TTL u_int32_t extended RCODE and flags
RDLEN u_int16_t describes RDATA
RDATA octet stream {attribute,value} pairs
+0 (MSB) +1 (LSB)
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
+0 (MSB) +1 (LSB)
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
0: | OPTION-CODE |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
2: | OPTION-LENGTH |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
4: | |
/ OPTION-DATA /
/ /
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
/ OPTION-DATA /
/ /
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
TTL
+0 (MSB) +1 (LSB)
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
+0 (MSB) +1 (LSB)
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
0: | EXTENDED-RCODE | VERSION |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
2: | Z |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
*/
if (ercode != 0) {
tlog(TLOG_ERROR, "extend rcode invalid.");
return -1;
}
while (context->ptr - start < rr_len) {
if (_dns_left_len(context) < 4) {
return -1;
}
opt_code = dns_read_short(&context->ptr);
opt_len = dns_read_short(&context->ptr);
opt_code = _dns_read_short(&context->ptr);
opt_len = _dns_read_short(&context->ptr);
if (_dns_left_len(context) < opt_len) {
tlog(TLOG_ERROR, "read opt data failed, opt_code = %d, opt_le = %d", opt_code, opt_len);
return -1;
}
tlog(TLOG_DEBUG, "opt type %d", opt_code);
switch (opt_code) {
case DNS_OPT_T_ECS: {
struct dns_opt_ecs ecs;
ret = _dns_decode_opt_ecs(context, &ecs);
if (ret != 0 ) {
if (ret != 0) {
tlog(TLOG_ERROR, "decode ecs failed.");
return -1;
}
ret = dns_add_OPT_ECS(packet, &ecs);
if (ret != 0) {
tlog(TLOG_ERROR, "add ecs failed.");
return -1;
}
} break;
default:
context->ptr += opt_len;
tlog(TLOG_DEBUG, "DNS opt type = %d not supported", opt_code);
break;
}
}
}
return 0;
@@ -1571,7 +1677,7 @@ static int _dns_decode_an(struct dns_context *context, dns_rr_type type)
}
} break;
case DNS_T_OPT: {
unsigned char *opt_start = context->ptr;
unsigned char *opt_start = context->ptr;
ret = _dns_decode_opt(context, type, ttl, rr_len);
if (ret < 0) {
tlog(TLOG_ERROR, "decode opt failed, %s", domain);
@@ -1586,6 +1692,10 @@ static int _dns_decode_an(struct dns_context *context, dns_rr_type type)
dns_set_OPT_payload_size(packet, qclass);
} break;
default:
if (_dns_left_len(context) < rr_len) {
tlog(TLOG_DEBUG, "length mitchmatch\n");
return -1;
}
context->ptr += rr_len;
tlog(TLOG_DEBUG, "DNS type = %d not supported", qtype);
break;
@@ -1661,41 +1771,46 @@ static int _dns_decode_body(struct dns_context *context)
struct dns_head *head = &packet->head;
int i = 0;
int ret = 0;
int count = 0;
for (i = 0; i < head->qdcount; i++) {
count = head->qdcount;
head->qdcount = 0;
for (i = 0; i < count; i++) {
ret = _dns_decode_qd(context);
if (ret < 0) {
tlog(TLOG_DEBUG, "decode qd failed.");
return -1;
}
head->qdcount--;
}
for (i = 0; i < head->ancount; i++) {
count = head->ancount;
head->ancount = 0;
for (i = 0; i < count; i++) {
ret = _dns_decode_an(context, DNS_RRS_AN);
if (ret < 0) {
tlog(TLOG_DEBUG, "decode an failed.");
return -1;
}
head->ancount--;
}
for (i = 0; i < head->nscount; i++) {
count = head->nscount;
head->nscount = 0;
for (i = 0; i < count; i++) {
ret = _dns_decode_an(context, DNS_RRS_NS);
if (ret < 0) {
tlog(TLOG_DEBUG, "decode ns failed.");
return -1;
}
head->nscount--;
}
for (i = 0; i < head->nrcount; i++) {
count = head->nrcount;
head->nrcount = 0;
for (i = 0; i < count; i++) {
ret = _dns_decode_an(context, DNS_RRS_NR);
if (ret < 0) {
tlog(TLOG_DEBUG, "decode nr failed.");
return -1;
}
head->nrcount--;
}
return 0;
@@ -1761,6 +1876,10 @@ static int _dns_encode_body(struct dns_context *context)
int dns_packet_init(struct dns_packet *packet, int size, struct dns_head *head)
{
struct dns_head *init_head = &packet->head;
if (size < sizeof(*packet)) {
return -1;
}
memset(packet, 0, size);
packet->size = size;
init_head->id = head->id;
@@ -1796,7 +1915,11 @@ int dns_decode(struct dns_packet *packet, int maxsize, unsigned char *data, int
context.ptr = data;
context.maxsize = size;
dns_packet_init(packet, maxsize, head);
ret = dns_packet_init(packet, maxsize, head);
if (ret != 0) {
return -1;
}
ret = _dns_decode_head(&context);
if (ret < 0) {
return -1;
@@ -1840,7 +1963,8 @@ int dns_encode(unsigned char *data, int size, struct dns_packet *packet)
return context.ptr - context.data;
}
void dns_debug(void)
#if 0
static void dns_debug(void)
{
unsigned char data[1024];
int len;
@@ -1864,10 +1988,11 @@ void dns_debug(void)
memset(data, 0, sizeof(data));
len = dns_encode(data, 1024, packet);
if (len < 0) {
tlog(TLOG_ERROR, "encode failed.\n");
tlog(TLOG_ERROR, "encode failed.");
}
fd = open("dns-cmp.bin", O_CREAT | O_TRUNC | O_RDWR);
write(fd, data, len);
close(fd);
}
#endif

View File

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

View File

@@ -10,7 +10,7 @@ struct dns_cache_head {
pthread_mutex_t lock;
};
struct dns_cache_head dns_cache_head;
static struct dns_cache_head dns_cache_head;
int dns_cache_init(int size)
{
@@ -19,22 +19,22 @@ int dns_cache_init(int size)
dns_cache_head.num = 0;
dns_cache_head.size = size;
pthread_mutex_init(&dns_cache_head.lock, 0);
pthread_mutex_init(&dns_cache_head.lock, NULL);
return 0;
}
struct dns_cache *_dns_cache_last(void)
static __attribute__((unused)) struct dns_cache *_dns_cache_last(void)
{
return list_last_entry(&dns_cache_head.cache_list, struct dns_cache, list);
}
struct dns_cache *_dns_cache_first(void)
static struct dns_cache *_dns_cache_first(void)
{
return list_first_entry(&dns_cache_head.cache_list, struct dns_cache, list);
return list_first_entry_or_null(&dns_cache_head.cache_list, struct dns_cache, list);
}
void _dns_cache_delete(struct dns_cache *dns_cache)
static void _dns_cache_delete(struct dns_cache *dns_cache)
{
hash_del(&dns_cache->node);
list_del_init(&dns_cache->list);
@@ -59,6 +59,13 @@ void dns_cache_release(struct dns_cache *dns_cache)
_dns_cache_delete(dns_cache);
}
static void _dns_cache_remove(struct dns_cache *dns_cache)
{
hash_del(&dns_cache->node);
list_del_init(&dns_cache->list);
dns_cache_release(dns_cache);
}
int dns_cache_replace(char *domain, char *cname, int cname_ttl, int ttl, dns_type_t qtype, unsigned char *addr, int addr_len)
{
struct dns_cache *dns_cache = NULL;
@@ -67,15 +74,24 @@ int dns_cache_replace(char *domain, char *cname, int cname_ttl, int ttl, dns_typ
return 0;
}
/* lookup existing cache */
dns_cache = dns_cache_lookup(domain, qtype);
if (dns_cache == NULL) {
return 0;
}
if (ttl < DNS_CACHE_TTL_MIN) {
ttl = DNS_CACHE_TTL_MIN;
}
/* update cache data */
pthread_mutex_lock(&dns_cache_head.lock);
dns_cache->ttl = ttl;
dns_cache->qtype = qtype;
dns_cache->ttl = ttl;
dns_cache->del_pending = 0;
time(&dns_cache->insert_time);
pthread_mutex_unlock(&dns_cache_head.lock);
if (qtype == DNS_T_A) {
if (addr_len != DNS_RR_A_LEN) {
goto errout;
@@ -114,8 +130,10 @@ int dns_cache_insert(char *domain, char *cname, int cname_ttl, int ttl, dns_type
return 0;
}
/* if cache already exists, free */
dns_cache = dns_cache_lookup(domain, qtype);
if (dns_cache) {
dns_cache_delete(dns_cache);
dns_cache_release(dns_cache);
dns_cache = NULL;
}
@@ -125,12 +143,18 @@ int dns_cache_insert(char *domain, char *cname, int cname_ttl, int ttl, dns_type
goto errout;
}
if (ttl < DNS_CACHE_TTL_MIN) {
ttl = DNS_CACHE_TTL_MIN;
}
key = hash_string(domain);
key = jhash(&qtype, sizeof(qtype), key);
strncpy(dns_cache->domain, domain, DNS_MAX_CNAME_LEN);
dns_cache->cname[0] = 0;
dns_cache->qtype = qtype;
dns_cache->ttl = ttl;
dns_cache->hitnum = 2;
dns_cache->del_pending = 0;
atomic_set(&dns_cache->ref, 1);
time(&dns_cache->insert_time);
if (qtype == DNS_T_A) {
@@ -158,10 +182,13 @@ int dns_cache_insert(char *domain, char *cname, int cname_ttl, int ttl, dns_type
INIT_LIST_HEAD(&dns_cache->check_list);
dns_cache_head.num++;
/* Release extra cache, remove oldest cache record */
if (dns_cache_head.num > dns_cache_head.size) {
struct dns_cache *del_cache;
del_cache = _dns_cache_first();
dns_cache_release(del_cache);
if (del_cache) {
_dns_cache_remove(del_cache);
}
}
pthread_mutex_unlock(&dns_cache_head.lock);
@@ -189,6 +216,7 @@ struct dns_cache *dns_cache_lookup(char *domain, dns_type_t qtype)
key = jhash(&qtype, sizeof(qtype), key);
time(&now);
/* find cache */
pthread_mutex_lock(&dns_cache_head.lock);
hash_for_each_possible(dns_cache_head.cache_hash, dns_cache, node, key)
{
@@ -205,11 +233,12 @@ struct dns_cache *dns_cache_lookup(char *domain, dns_type_t qtype)
}
if (dns_cache_ret) {
/* Return NULL if the cache times out */
if (now - dns_cache_ret->insert_time > dns_cache_ret->ttl) {
_dns_cache_delete(dns_cache_ret);
_dns_cache_remove(dns_cache_ret);
dns_cache_ret = NULL;
} else {
atomic_inc(&dns_cache_ret->ref);
dns_cache_get(dns_cache_ret);
}
}
@@ -235,10 +264,8 @@ int dns_cache_get_ttl(struct dns_cache *dns_cache)
void dns_cache_delete(struct dns_cache *dns_cache)
{
pthread_mutex_lock(&dns_cache_head.lock);
hash_del(&dns_cache->node);
list_del_init(&dns_cache->list);
_dns_cache_remove(dns_cache);
pthread_mutex_unlock(&dns_cache_head.lock);
dns_cache_release(dns_cache);
}
void dns_cache_update(struct dns_cache *dns_cache)
@@ -247,6 +274,7 @@ void dns_cache_update(struct dns_cache *dns_cache)
if (!list_empty(&dns_cache->list)) {
list_del_init(&dns_cache->list);
list_add_tail(&dns_cache->list, &dns_cache_head.cache_list);
dns_cache->hitnum++;
}
pthread_mutex_unlock(&dns_cache_head.lock);
}
@@ -268,31 +296,28 @@ void dns_cache_invalidate(dns_cache_preinvalid_callback callback, int ttl_pre)
list_for_each_entry_safe(dns_cache, tmp, &dns_cache_head.cache_list, list)
{
ttl = dns_cache->insert_time + dns_cache->ttl - now;
if (ttl > 0) {
if (ttl < ttl_pre) {
if (callback) {
list_add_tail(&dns_cache->check_list, &checklist);
dns_cache_get(dns_cache);
continue;
}
}
if (callback) {
if (ttl > 0 && ttl < ttl_pre) {
/* If the TTL time is in the pre-timeout range, call callback function */
if (callback && dns_cache->del_pending == 0) {
list_add_tail(&dns_cache->check_list, &checklist);
dns_cache_get(dns_cache);
dns_cache->del_pending = 1;
continue;
}
break;
}
hash_del(&dns_cache->node);
list_del_init(&dns_cache->list);
dns_cache_release(dns_cache);
if (ttl < 0) {
_dns_cache_remove(dns_cache);
}
}
pthread_mutex_unlock(&dns_cache_head.lock);
list_for_each_entry_safe(dns_cache, tmp, &checklist, check_list)
{
callback(dns_cache);
list_del_init(&dns_cache->check_list);
/* run callback */
if (callback) {
callback(dns_cache);
}
dns_cache_release(dns_cache);
}
}
@@ -309,4 +334,4 @@ void dns_cache_destroy(void)
pthread_mutex_unlock(&dns_cache_head.lock);
pthread_mutex_destroy(&dns_cache_head.lock);
}
}

View File

@@ -6,8 +6,11 @@
#include "hash.h"
#include "hashtable.h"
#include "list.h"
#include <stdlib.h>
#include <time.h>
#define DNS_CACHE_TTL_MIN 30
struct dns_cache {
struct hlist_node node;
struct list_head list;
@@ -17,6 +20,8 @@ struct dns_cache {
char cname[DNS_MAX_CNAME_LEN];
unsigned int cname_ttl;
unsigned int ttl;
int hitnum;
int del_pending;
time_t insert_time;
dns_type_t qtype;
union {
@@ -50,4 +55,4 @@ int dns_cache_get_ttl(struct dns_cache *dns_cache);
void dns_cache_destroy(void);
#endif // !_SMARTDNS_CACHE_H
#endif // !_SMARTDNS_CACHE_H

File diff suppressed because it is too large Load Diff

View File

@@ -2,11 +2,13 @@
#define _SMART_DNS_CLIENT_H
#include "dns.h"
#define DNS_SERVER_GROUP_DEFAULT "default"
typedef enum {
DNS_SERVER_UDP,
DNS_SERVER_TCP,
DNS_SERVER_TLS,
DNS_SERVER_HTTPS,
DNS_SERVER_TYPE_END,
} dns_server_type_t;
@@ -29,15 +31,23 @@ typedef int (*dns_client_callback)(char *domain, dns_result_type rtype, unsigned
int inpacket_len, void *user_ptr);
/* query domain */
int dns_client_query(char *domain, int qtype, dns_client_callback callback, void *user_ptr);
int dns_client_query(char *domain, int qtype, dns_client_callback callback, void *user_ptr, const char *group_name);
void dns_client_exit(void);
/* add remote dns server */
int dns_add_server(char *server_ip, int port, dns_server_type_t server_type, int result_flag, int ttl);
int dns_client_add_server(char *server_ip, int port, dns_server_type_t server_type, unsigned int server_flag, unsigned int result_flag, int ttl, char *spki);
/* remove remote dns server */
int dns_remove_server(char *server_ip, int port, dns_server_type_t server_type);
int dns_client_remove_server(char *server_ip, int port, dns_server_type_t server_type);
int dns_client_add_group(char *group_name);
int dns_client_add_to_group(char *group_name, char *server_ip, int port, dns_server_type_t server_type);
int dns_client_remove_from_group(char *group_name, char *server_ip, int port, dns_server_type_t server_type);
int dns_client_remove_group(char *group_name);
int dns_server_num(void);

File diff suppressed because it is too large Load Diff

View File

@@ -12,7 +12,10 @@
#define DNS_MAX_SERVERS 64
#define DNS_MAX_IPSET_NAMELEN 32
#define DNS_GROUP_NAME_LEN 32
#define DNS_NAX_GROUP_NUMBER 16
#define DNS_MAX_IPLEN 64
#define DNS_MAX_SPKI_LEN 64
#define DNS_MAX_PATH 1024
#define DEFAULT_DNS_PORT 53
#define DEFAULT_DNS_TLS_PORT 853
@@ -22,12 +25,29 @@
#define SMARTDNS_AUDIT_FILE "/var/log/smartdns-audit.log"
enum domain_rule {
DOMAIN_RULE_ADDRESS_IPV4 = 1,
DOMAIN_RULE_ADDRESS_IPV6 = 2,
DOMAIN_RULE_IPSET = 3,
DOMAIN_RULE_FLAGS = 0,
DOMAIN_RULE_ADDRESS_IPV4,
DOMAIN_RULE_ADDRESS_IPV6,
DOMAIN_RULE_IPSET,
DOMAIN_RULE_NAMESERVER,
DOMAIN_RULE_MAX,
};
#define DOMAIN_FLAG_ADDR_SOA (1 << 0)
#define DOMAIN_FLAG_ADDR_IPV4_SOA (1 << 1)
#define DOMAIN_FLAG_ADDR_IPV6_SOA (1 << 2)
#define DOMAIN_FLAG_ADDR_IGN (1 << 3)
#define DOMAIN_FLAG_ADDR_IPV4_IGN (1 << 4)
#define DOMAIN_FLAG_ADDR_IPV6_IGN (1 << 5)
#define DOMAIN_FLAG_IPSET_IGNORE (1 << 6)
#define DOMAIN_FLAG_NAMESERVER_IGNORE (1 << 7)
#define SERVER_FLAG_EXCLUDE_DEFAULT (1 << 0)
struct dns_rule_flags {
unsigned int flags;
};
struct dns_address_IPV4 {
unsigned char ipv4_addr[DNS_RR_A_LEN];
};
@@ -49,12 +69,30 @@ struct dns_domain_rule {
void *rules[DOMAIN_RULE_MAX];
};
struct dns_nameserver_rule {
const char *group_name;
};
struct dns_server_groups {
struct hlist_node node;
char group_name[DNS_GROUP_NAME_LEN];
int server_num;
struct dns_servers *servers[DNS_MAX_SERVERS];
};
struct dns_group_table {
DECLARE_HASHTABLE(group, 8);
};
extern struct dns_group_table dns_group_table;
struct dns_servers {
char server[DNS_MAX_IPLEN];
unsigned short port;
unsigned int result_flag;
unsigned int server_flag;
int ttl;
dns_server_type_t type;
char spki[DNS_MAX_SPKI_LEN];
};
/* ip address lists of domain */
@@ -71,11 +109,13 @@ struct dns_bogus_ip_address {
enum address_rule {
ADDRESS_RULE_BLACKLIST = 1,
ADDRESS_RULE_BOGUS = 2,
ADDRESS_RULE_IP_IGNORE = 3,
};
struct dns_ip_address_rule {
unsigned int blacklist : 1;
unsigned int bogus : 1;
unsigned int ip_ignore : 1;
};
struct dns_edns_client_subnet {
@@ -84,6 +124,11 @@ struct dns_edns_client_subnet {
int subnet;
};
struct dns_conf_address_rule {
radix_tree_t *ipv4;
radix_tree_t *ipv6;
};
extern char dns_conf_server_ip[DNS_MAX_IPLEN];
extern char dns_conf_server_tcp_ip[DNS_MAX_IPLEN];
extern int dns_conf_tcp_idle_time;
@@ -97,6 +142,9 @@ 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_server_groups dns_conf_server_groups[DNS_NAX_GROUP_NUMBER];
extern int dns_conf_server_group_num;
extern int dns_conf_audit_enable;
extern char dns_conf_audit_file[DNS_MAX_PATH];
extern size_t dns_conf_audit_size;
@@ -104,7 +152,7 @@ extern int dns_conf_audit_num;
extern char dns_conf_server_name[DNS_MAX_CONF_CNAME_LEN];
extern art_tree dns_conf_domain_rule;
extern radix_tree_t *dns_conf_address_rule;
extern struct dns_conf_address_rule dns_conf_address_rule;
extern int dns_conf_dualstack_ip_selection;
extern int dns_conf_dualstack_ip_selection_threshold;
@@ -113,6 +161,7 @@ extern int dns_conf_rr_ttl;
extern int dns_conf_rr_ttl_min;
extern int dns_conf_rr_ttl_max;
extern int dns_conf_force_AAAA_SOA;
extern int dns_conf_ipset_timeout_enable;
extern struct dns_edns_client_subnet dns_conf_ipv4_ecs;
extern struct dns_edns_client_subnet dns_conf_ipv6_ecs;
@@ -123,4 +172,4 @@ int dns_server_load_conf(const char *file);
extern int config_addtional_file(void *data, int argc, char *argv[]);
#endif // !_DNS_CONF
#endif // !_DNS_CONF

File diff suppressed because it is too large Load Diff

View File

@@ -1,12 +1,21 @@
#ifndef _SMART_DNS_SERVER_H
#define _SMART_DNS_SERVER_H
#ifdef __cpluscplus
extern "C" {
#endif
int dns_server_init(void);
int dns_server_run(void);
int dns_server_start(void);
void dns_server_stop(void);
void dns_server_exit(void);
#ifdef __cpluscplus
}
#endif
#endif

View File

@@ -45,9 +45,9 @@
#define ICMP_INPACKET_SIZE 1024
#ifndef ICMP_FILTER
#define ICMP_FILTER 1
#define ICMP_FILTER 1
struct icmp_filter {
uint32_t data;
uint32_t data;
};
#endif
@@ -142,7 +142,7 @@ static struct fast_ping_struct ping;
static atomic_t ping_sid = ATOMIC_INIT(0);
static int bool_print_log = 1;
uint16_t _fast_ping_checksum(uint16_t *header, size_t len)
static uint16_t _fast_ping_checksum(uint16_t *header, size_t len)
{
uint32_t sum = 0;
int i;
@@ -154,7 +154,7 @@ uint16_t _fast_ping_checksum(uint16_t *header, size_t len)
return htons(~((sum >> 16) + (sum & 0xffff)));
}
void _fast_ping_install_filter_v6(int sock)
static void _fast_ping_install_filter_v6(int sock)
{
struct icmp6_filter icmp6_filter;
ICMP6_FILTER_SETBLOCKALL(&icmp6_filter);
@@ -186,7 +186,7 @@ void _fast_ping_install_filter_v6(int sock)
}
}
void _fast_ping_install_filter_v4(int sock)
static void _fast_ping_install_filter_v4(int sock)
{
static int once;
static struct sock_filter insns[] = {
@@ -350,7 +350,8 @@ static int _fast_ping_sendping_v6(struct ping_host_struct *ping_host)
icmp6->icmp6_id = ping.ident;
icmp6->icmp6_seq = htons(ping_host->seq);
gettimeofday(&packet->msg.tv, 0);
gettimeofday(&packet->msg.tv, NULL);
gettimeofday(&ping_host->last, NULL);
packet->msg.sid = ping_host->sid;
packet->msg.cookie = ping_host->cookie;
packet->msg.seq = ping_host->seq;
@@ -371,7 +372,7 @@ static int _fast_ping_sendping_v6(struct ping_host_struct *ping_host)
}
char ping_host_name[PING_MAX_HOSTLEN];
tlog(TLOG_ERROR, "sendto %s, id %d, %s", gethost_by_addr(ping_host_name, (struct sockaddr *)&ping_host->addr, ping_host->addr_len), ping_host->sid,
tlog(TLOG_ERROR, "sendto %s, id %d, %s", gethost_by_addr(ping_host_name, sizeof(ping_host_name), (struct sockaddr *)&ping_host->addr), ping_host->sid,
strerror(err));
goto errout;
}
@@ -396,7 +397,8 @@ static int _fast_ping_sendping_v4(struct ping_host_struct *ping_host)
icmp->icmp_id = ping.ident;
icmp->icmp_seq = htons(ping_host->seq);
gettimeofday(&packet->msg.tv, 0);
gettimeofday(&packet->msg.tv, NULL);
gettimeofday(&ping_host->last, NULL);
packet->msg.sid = ping_host->sid;
packet->msg.seq = ping_host->seq;
packet->msg.cookie = ping_host->cookie;
@@ -409,7 +411,7 @@ static int _fast_ping_sendping_v4(struct ping_host_struct *ping_host)
goto errout;
}
char ping_host_name[PING_MAX_HOSTLEN];
tlog(TLOG_ERROR, "sendto %s, id %d, %s", gethost_by_addr(ping_host_name, (struct sockaddr *)&ping_host->addr, ping_host->addr_len), ping_host->sid,
tlog(TLOG_ERROR, "sendto %s, id %d, %s", gethost_by_addr(ping_host_name, sizeof(ping_host_name), (struct sockaddr *)&ping_host->addr), ping_host->sid,
strerror(err));
goto errout;
}
@@ -425,6 +427,7 @@ static int _fast_ping_sendping_udp(struct ping_host_struct *ping_host)
struct ping_dns_head dns_head;
int len;
int flag = 0;
int fd = 0;
flag |= (0 << 15) & 0x8000;
flag |= (2 << 11) & 0x7800;
@@ -434,18 +437,27 @@ static int _fast_ping_sendping_udp(struct ping_host_struct *ping_host)
flag |= (0 << 7) & 0x0080;
flag |= (0 << 0) & 0x000F;
if (ping_host->type == FAST_PING_UDP) {
fd = ping.fd_udp;
} else if (ping_host->type == FAST_PING_UDP6) {
fd = ping.fd_udp6;
} else {
return -1;
}
ping_host->seq++;
memset(&dns_head, 0, sizeof(dns_head));
dns_head.id = htons(ping_host->sid);
dns_head.flag = flag;
len = sendto(ping.fd_udp, &dns_head, sizeof(dns_head), 0, (struct sockaddr *)&ping_host->addr, ping_host->addr_len);
gettimeofday(&ping_host->last, NULL);
len = sendto(fd, &dns_head, sizeof(dns_head), 0, (struct sockaddr *)&ping_host->addr, ping_host->addr_len);
if (len < 0 || len != sizeof(dns_head)) {
int err = errno;
if (errno == ENETUNREACH || errno == EINVAL) {
goto errout;
}
char ping_host_name[PING_MAX_HOSTLEN];
tlog(TLOG_ERROR, "sendto %s, id %d, %s", gethost_by_addr(ping_host_name, (struct sockaddr *)&ping_host->addr, ping_host->addr_len), ping_host->sid,
tlog(TLOG_ERROR, "sendto %s, id %d, %s", gethost_by_addr(ping_host_name, sizeof(ping_host_name), (struct sockaddr *)&ping_host->addr), ping_host->sid,
strerror(err));
goto errout;
}
@@ -487,15 +499,16 @@ static int _fast_ping_sendping_tcp(struct ping_host_struct *ping_host)
bool_print_log = 0;
}
tlog(TLOG_ERROR, "connect %s, id %d, %s", gethost_by_addr(ping_host_name, (struct sockaddr *)&ping_host->addr, ping_host->addr_len), ping_host->sid,
strerror(errno));
tlog(TLOG_ERROR, "connect %s, id %d, %s", gethost_by_addr(ping_host_name, sizeof(ping_host_name), (struct sockaddr *)&ping_host->addr),
ping_host->sid, strerror(errno));
goto errout;
}
}
gettimeofday(&ping_host->last, NULL);
ping_host->fd = fd;
memset(&event, 0, sizeof(event));
event.events = EPOLLIN | EPOLLOUT;
event.events = EPOLLIN | EPOLLOUT | EPOLLERR;
event.data.ptr = ping_host;
if (epoll_ctl(ping.epoll_fd, EPOLL_CTL_ADD, fd, &event) != 0) {
ping_host->fd = -1;
@@ -515,6 +528,7 @@ errout:
static int _fast_ping_sendping(struct ping_host_struct *ping_host)
{
int ret = -1;
gettimeofday(&ping_host->last, NULL);
if (ping_host->type == FAST_PING_ICMP) {
ret = _fast_ping_sendping_v4(ping_host);
@@ -522,12 +536,11 @@ static int _fast_ping_sendping(struct ping_host_struct *ping_host)
ret = _fast_ping_sendping_v6(ping_host);
} else if (ping_host->type == FAST_PING_TCP) {
ret = _fast_ping_sendping_tcp(ping_host);
} else if (ping_host->type == FAST_PING_UDP) {
} else if (ping_host->type == FAST_PING_UDP || ping_host->type == FAST_PING_UDP6) {
ret = _fast_ping_sendping_udp(ping_host);
}
ping_host->send = 1;
gettimeofday(&ping_host->last, 0);
if (ret != 0) {
return ret;
@@ -652,6 +665,7 @@ static int _fast_ping_create_udp_sock(FAST_PING_TYPE type)
}
udp_host = &ping.udp_host;
udp_host->type = FAST_PING_UDP;
break;
case FAST_PING_UDP6:
fd = socket(AF_INET6, SOCK_DGRAM, 0);
@@ -661,6 +675,10 @@ static int _fast_ping_create_udp_sock(FAST_PING_TYPE type)
}
udp_host = &ping.udp6_host;
udp_host->type = FAST_PING_UDP6;
setsockopt(fd, IPPROTO_IPV6, IPV6_RECVHOPLIMIT, &on, sizeof(on));
setsockopt(fd, IPPROTO_IPV6, IPV6_2292HOPLIMIT, &on, sizeof(on));
setsockopt(fd, IPPROTO_IPV6, IPV6_HOPLIMIT, &on, sizeof(on));
break;
default:
return -1;
@@ -677,7 +695,6 @@ static int _fast_ping_create_udp_sock(FAST_PING_TYPE type)
}
udp_host->fd = fd;
udp_host->type = FAST_PING_UDP;
return fd;
errout:
@@ -724,7 +741,7 @@ errout:
return -1;
}
void fast_ping_print_result(struct ping_host_struct *ping_host, const char *host, FAST_PING_RESULT result, struct sockaddr *addr, socklen_t addr_len, int seqno,
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) {
@@ -829,7 +846,6 @@ struct ping_host_struct *fast_ping_start(PING_TYPE type, const char *host, int c
socktype = SOCK_DGRAM;
snprintf(port_str, MAX_IP_LEN, "%d", port);
service = port_str;
ping_type = FAST_PING_UDP;
if (_fast_ping_create_udp(ping_type) < 0) {
goto errout;
@@ -866,7 +882,7 @@ struct ping_host_struct *fast_ping_start(PING_TYPE type, const char *host, int c
if (ping_callback) {
ping_host->ping_callback = ping_callback;
} else {
ping_host->ping_callback = fast_ping_print_result;
ping_host->ping_callback = _fast_ping_print_result;
}
ping_host->interval = (timeout > interval) ? timeout : interval;
ping_host->addr_len = gai->ai_addrlen;
@@ -1012,7 +1028,7 @@ static struct fast_ping_packet *_fast_ping_icmp_packet(struct ping_host_struct *
return packet;
}
struct fast_ping_packet *_fast_ping_recv_packet(struct ping_host_struct *ping_host, struct msghdr *msg, u_char *inpacket, int len, struct timeval *tvrecv)
static struct fast_ping_packet *_fast_ping_recv_packet(struct ping_host_struct *ping_host, struct msghdr *msg, u_char *inpacket, int len, struct timeval *tvrecv)
{
struct fast_ping_packet *packet = NULL;
@@ -1074,7 +1090,7 @@ static int _fast_ping_process_icmp(struct ping_host_struct *ping_host, struct ti
packet = _fast_ping_recv_packet(ping_host, &msg, inpacket, len, now);
if (packet == NULL) {
char name[PING_MAX_HOSTLEN];
tlog(TLOG_DEBUG, "recv ping packet from %s failed.", gethost_by_addr(name, (struct sockaddr *)&from, from_len));
tlog(TLOG_DEBUG, "recv ping packet from %s failed.", gethost_by_addr(name, sizeof(name), (struct sockaddr *)&from));
goto errout;
}
@@ -1136,6 +1152,7 @@ static int _fast_ping_process_tcp(struct ping_host_struct *ping_host, struct epo
if (getsockopt(ping_host->fd, SOL_SOCKET, SO_ERROR, (char *)&connect_error, &len) != 0) {
goto errout;
}
if (connect_error != 0 && connect_error != ECONNREFUSED) {
goto errout;
}
@@ -1148,6 +1165,8 @@ static int _fast_ping_process_tcp(struct ping_host_struct *ping_host, struct epo
ping_host->send = 0;
_fast_ping_close_host_sock(ping_host);
if (ping_host->count == 1) {
_fast_ping_host_remove(ping_host);
}
@@ -1194,9 +1213,15 @@ static int _fast_ping_process_udp(struct ping_host_struct *ping_host, struct tim
for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
if (cmsg->cmsg_level == SOL_IP && cmsg->cmsg_type == IP_TTL) {
uint8_t *ttlPtr = (uint8_t *)CMSG_DATA(cmsg);
ttl = *ttlPtr;
break;
if (cmsg->cmsg_len >= sizeof(int)) {
int *ttlPtr = (int *)CMSG_DATA(cmsg);
ttl = *ttlPtr;
}
} else if (cmsg->cmsg_level == IPPROTO_IPV6 && cmsg->cmsg_type == IPV6_HOPLIMIT) {
if (cmsg->cmsg_len >= sizeof(int)) {
int *ttlPtr = (int *)CMSG_DATA(cmsg);
ttl = *ttlPtr;
}
}
}
@@ -1256,6 +1281,7 @@ static int _fast_ping_process(struct ping_host_struct *ping_host, struct epoll_e
case FAST_PING_TCP:
ret = _fast_ping_process_tcp(ping_host, event, now);
break;
case FAST_PING_UDP6:
case FAST_PING_UDP:
ret = _fast_ping_process_udp(ping_host, now);
break;
@@ -1299,7 +1325,7 @@ static void _fast_ping_period_run(void)
struct timeval now;
struct timeval interval;
int64_t millisecond;
gettimeofday(&now, 0);
gettimeofday(&now, NULL);
LIST_HEAD(action);
pthread_mutex_lock(&ping.map_lock);
@@ -1396,7 +1422,7 @@ static void *_fast_ping_work(void *arg)
continue;
}
gettimeofday(&tvnow, 0);
gettimeofday(&tvnow, NULL);
for (i = 0; i < num; i++) {
struct epoll_event *event = &events[i];
struct ping_host_struct *ping_host = (struct ping_host_struct *)event->data.ptr;
@@ -1430,8 +1456,8 @@ int fast_ping_init(void)
goto errout;
}
pthread_mutex_init(&ping.map_lock, 0);
pthread_mutex_init(&ping.lock, 0);
pthread_mutex_init(&ping.map_lock, NULL);
pthread_mutex_init(&ping.lock, NULL);
hash_init(ping.addrmap);
ping.epoll_fd = epollfd;
ping.ident = (getpid() & 0XFFFF);

View File

@@ -237,4 +237,4 @@ int art_iter_prefix(art_tree *t, const unsigned char *prefix, int prefix_len, ar
}
#endif
#endif
#endif

View File

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

View File

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

View File

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

View File

@@ -8,6 +8,11 @@
#define CONF_INT_MAX (~(1 << 31))
#define CONF_INT_MIN (1 << 31)
#define CONF_RET_OK 0
#define CONF_RET_ERR -1
#define CONF_RET_WARN -2
#define CONF_RET_NOENT -3
struct config_item {
const char *item;
int (*item_func)(const char *item, void *data, int argc, char *argv[]);
@@ -81,7 +86,7 @@ struct config_item_size {
#define CONF_END() \
{ \
0, 0, 0 \
NULL, NULL, NULL \
}
extern int conf_custom(const char *item, void *data, int argc, char *argv[]);
@@ -107,10 +112,12 @@ extern int conf_size(const char *item, void *data, int argc, char *argv[]);
*
*/
int load_conf(const char *file, struct config_item items[]);
typedef int(conf_error_handler)(const char *file, int lineno, int ret);
int load_conf_get_line_count(void);
int load_conf(const char *file, struct config_item items[], conf_error_handler handler);
void load_exit(void);
#endif // !_GENERIC_CONF_H
const char *conf_get_conf_file(void);
#endif // !_GENERIC_CONF_H

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -159,3 +159,4 @@ const char *prefix_addr_ntop(prefix_t *prefix, char *buf, size_t len);
const char *prefix_ntop(prefix_t *prefix, char *buf, size_t len);
#endif /* _RADIX_H */

View File

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

View File

@@ -1027,7 +1027,6 @@ void *art_substring(const art_tree *t, const unsigned char *str, int str_len, un
// Check if the expanded path matches
if (!str_prefix_matches((art_leaf*)n, str, str_len)) {
found = (art_leaf*)n;
art_copy_key(found, key, key_len);
}
break;
}
@@ -1040,7 +1039,6 @@ void *art_substring(const art_tree *t, const unsigned char *str, int str_len, un
// Check if the expanded path matches
if (!str_prefix_matches((art_leaf*)m, str, str_len)) {
found = (art_leaf*)m;
art_copy_key(found, key, key_len);
}
}
@@ -1062,5 +1060,7 @@ void *art_substring(const art_tree *t, const unsigned char *str, int str_len, un
return NULL;
}
art_copy_key(found, key, key_len);
return found->value;
}

View File

@@ -5,7 +5,12 @@
#include <string.h>
#include <unistd.h>
__thread int line_no;
static const char *currrent_conf_file = NULL;
const char *conf_get_conf_file(void)
{
return currrent_conf_file;
}
int conf_custom(const char *item, void *data, int argc, char *argv[])
{
@@ -57,6 +62,10 @@ int conf_yesno(const char *item, void *data, int argc, char *argv[])
}
char *value = argv[1];
if (strncmp("auto", value, sizeof("auto")) == 0 || strncmp("AUTO", value, sizeof("AUTO")) == 0) {
return 0;
}
if (strncmp("yes", value, sizeof("yes")) == 0 || strncmp("YES", value, sizeof("YES")) == 0) {
yes = 1;
} else if (strncmp("no", value, sizeof("no")) == 0 || strncmp("NO", value, sizeof("NO")) == 0) {
@@ -182,12 +191,21 @@ void load_exit(void)
return;
}
int load_conf_get_line_count(void)
int load_conf_printf(const char *file, int lineno, int ret)
{
return line_no;
if (ret != CONF_RET_OK) {
printf("process config file '%s' failed at line %d.", file, lineno);
if (ret == CONF_RET_ERR || ret == CONF_RET_NOENT) {
return -1;
}
return 0;
}
return 0;
}
int load_conf_file(const char *file, struct config_item *items)
int load_conf_file(const char *file, struct config_item *items, conf_error_handler handler)
{
FILE *fp = NULL;
char line[MAX_LINE_LEN];
@@ -197,6 +215,13 @@ int load_conf_file(const char *file, struct config_item *items)
int i;
int argc;
char *argv[1024];
int ret = 0;
int call_ret = 0;
int line_no = 0;
if (handler == NULL) {
handler = load_conf_printf;
}
fp = fopen(file, "r");
if (fp == NULL) {
@@ -223,6 +248,7 @@ int load_conf_file(const char *file, struct config_item *items)
for (i = 0;; i++) {
if (items[i].item == NULL) {
handler(file, line_no, CONF_RET_NOENT);
break;
}
@@ -236,7 +262,10 @@ int load_conf_file(const char *file, struct config_item *items)
conf_getopt_reset();
/* call item function */
if (items[i].item_func(items[i].item, items[i].data, argc, argv) != 0) {
currrent_conf_file = file;
call_ret = items[i].item_func(items[i].item, items[i].data, argc, argv);
ret = handler(file, line_no, call_ret);
if (ret != 0) {
conf_getopt_reset();
goto errout;
}
@@ -257,7 +286,7 @@ errout:
return -1;
}
int load_conf(const char *file, struct config_item items[])
int load_conf(const char *file, struct config_item items[], conf_error_handler handler)
{
return load_conf_file(file, items);
return load_conf_file(file, items, handler);
}

View File

@@ -221,6 +221,9 @@ Clear_Radix(radix_tree_t *radix, rdx_cb_t func, void *cbctx)
void
Destroy_Radix(radix_tree_t *radix, rdx_cb_t func, void *cbctx)
{
if (radix == NULL) {
return;
}
Clear_Radix(radix, func, cbctx);
free(radix);
}

View File

@@ -49,7 +49,7 @@
static int verbose_screen;
void help(void)
static void _help(void)
{
/* clang-format off */
char *help = ""
@@ -69,7 +69,7 @@ void help(void)
printf("%s", help);
}
int smartdns_load_from_resolv(void)
static int _smartdns_load_from_resolv(void)
{
FILE *fp = NULL;
char line[MAX_LINE_LEN];
@@ -120,23 +120,48 @@ int smartdns_load_from_resolv(void)
return ret;
}
int smartdns_add_servers(void)
static int _smartdns_add_servers(void)
{
int i = 0;
int j = 0;
int ret = 0;
struct dns_server_groups *group = NULL;
struct dns_servers *server = NULL;
for (i = 0; i < dns_conf_server_num; i++) {
ret = dns_add_server(dns_conf_servers[i].server, dns_conf_servers[i].port, dns_conf_servers[i].type, dns_conf_servers[i].result_flag,
dns_conf_servers[i].ttl);
ret = dns_client_add_server(dns_conf_servers[i].server, dns_conf_servers[i].port, dns_conf_servers[i].type, dns_conf_servers[i].server_flag,
dns_conf_servers[i].result_flag, dns_conf_servers[i].ttl, dns_conf_servers[i].spki);
if (ret != 0) {
tlog(TLOG_ERROR, "add server failed, %s:%d", dns_conf_servers[i].server, dns_conf_servers[i].port);
return -1;
}
}
hash_for_each(dns_group_table.group, i, group, node)
{
ret = dns_client_add_group(group->group_name);
if (ret != 0) {
tlog(TLOG_ERROR, "add group failed, %s", group->group_name);
return -1;
}
for (j = 0; j < group->server_num; j++) {
server = group->servers[j];
if (server == NULL) {
continue;
}
ret = dns_client_add_to_group(group->group_name, server->server, server->port, server->type);
if (ret != 0) {
tlog(TLOG_ERROR, "add server %s to group %s failed", server->server, group->group_name);
return -1;
}
}
}
return 0;
}
int smartdns_set_ecs_ip(void)
static int _smartdns_set_ecs_ip(void)
{
int ret = 0;
if (dns_conf_ipv4_ecs.enable) {
@@ -150,69 +175,26 @@ int smartdns_set_ecs_ip(void)
return ret;
}
int create_pid_file(const char *pid_file)
{
int fd;
int flags;
char buff[TMP_BUFF_LEN_32];
/* create pid file, and lock this file */
fd = open(pid_file, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
if (fd == -1) {
fprintf(stderr, "create pid file failed, %s\n", strerror(errno));
return -1;
}
flags = fcntl(fd, F_GETFD);
if (flags < 0) {
fprintf(stderr, "Could not get flags for PID file %s\n", pid_file);
goto errout;
}
flags |= FD_CLOEXEC;
if (fcntl(fd, F_SETFD, flags) == -1) {
fprintf(stderr, "Could not set flags for PID file %s\n", pid_file);
goto errout;
}
if (lockf(fd, F_TLOCK, 0) < 0) {
fprintf(stderr, "Server is already running.\n");
goto errout;
}
snprintf(buff, TMP_BUFF_LEN_32, "%d\n", getpid());
if (write(fd, buff, strnlen(buff, TMP_BUFF_LEN_32)) < 0) {
fprintf(stderr, "write pid to file failed, %s.\n", strerror(errno));
goto errout;
}
return 0;
errout:
if (fd > 0) {
close(fd);
}
return -1;
}
int smartdns_init_ssl(void)
static int _smartdns_init_ssl(void)
{
SSL_load_error_strings();
SSL_library_init();
OpenSSL_add_all_algorithms();
SSL_CRYPTO_thread_setup();
return 0;
}
int smartdns_destroy_ssl(void)
static int _smartdns_destroy_ssl(void)
{
SSL_CRYPTO_thread_cleanup();
ERR_free_strings();
EVP_cleanup();
return 0;
}
int smartdns_init(void)
static int _smartdns_init(void)
{
int ret;
char *logfile = SMARTDNS_LOG_FILE;
@@ -232,13 +214,13 @@ int smartdns_init(void)
tlog(TLOG_NOTICE, "smartdns starting...(Copyright (C) Nick Peng <pymumu@gmail.com>, build:%s %s)", __DATE__, __TIME__);
if (smartdns_init_ssl() != 0) {
if (_smartdns_init_ssl() != 0) {
tlog(TLOG_ERROR, "init ssl failed.");
goto errout;
}
if (dns_conf_server_num <= 0) {
if (smartdns_load_from_resolv() != 0) {
if (_smartdns_load_from_resolv() != 0) {
tlog(TLOG_ERROR, "load dns from resolv failed.");
goto errout;
}
@@ -261,13 +243,13 @@ int smartdns_init(void)
tlog(TLOG_ERROR, "start dns client failed.\n");
goto errout;
}
ret = smartdns_add_servers();
ret = _smartdns_add_servers();
if (ret != 0) {
tlog(TLOG_ERROR, "add servers failed.");
goto errout;
}
ret = smartdns_set_ecs_ip();
ret = _smartdns_set_ecs_ip();
if (ret != 0) {
tlog(TLOG_WARN, "set ecs ip address failed.");
}
@@ -278,57 +260,59 @@ errout:
return -1;
}
int smartdns_run(void)
static int _smartdns_run(void)
{
return dns_server_run();
}
void smartdns_exit(void)
static void _smartdns_exit(void)
{
dns_server_exit();
dns_client_exit();
fast_ping_exit();
smartdns_destroy_ssl();
_smartdns_destroy_ssl();
tlog_exit();
dns_server_load_exit();
}
void sig_exit(int signo)
static void _sig_exit(int signo)
{
dns_server_stop();
}
void sig_error_exit(int signo, siginfo_t *siginfo, void *ct)
static void _sig_error_exit(int signo, siginfo_t *siginfo, void *ct)
{
unsigned long PC = 0;
ucontext_t *context = ct;
#if defined(__i386__)
int *pgregs = (int*)(&(context->uc_mcontext.gregs));
PC = pgregs[REG_EIP];
#elif defined(__x86_64__)
int *pgregs = (int*)(&(context->uc_mcontext.gregs));
PC = pgregs[REG_RIP];
#elif defined(__aarch64__) || defined(__arm__)
PC = context->uc_mcontext.arm_pc;
int *pgregs = (int *)(&(context->uc_mcontext.gregs));
PC = pgregs[REG_EIP];
#elif defined(__x86_64__)
int *pgregs = (int *)(&(context->uc_mcontext.gregs));
PC = pgregs[REG_RIP];
#elif defined(__arm__)
PC = context->uc_mcontext.arm_pc;
#elif defined(__aarch64__)
PC = context->uc_mcontext.pc;
#elif defined(__mips__)
PC = context->uc_mcontext.pc;
PC = context->uc_mcontext.pc;
#endif
tlog(TLOG_ERROR, "process exit with signal %d, code = %d, errno = %d, pid = %d, self = %d, pc = %#lx, addr = %#lx, build(%s %s)\n", signo, siginfo->si_code, siginfo->si_errno,
siginfo->si_pid, getpid(), PC, (unsigned long)siginfo->si_addr, __DATE__, __TIME__);
tlog(TLOG_ERROR, "process exit with signal %d, code = %d, errno = %d, pid = %d, self = %d, pc = %#lx, addr = %#lx, build(%s %s)\n", signo, siginfo->si_code,
siginfo->si_errno, siginfo->si_pid, getpid(), PC, (unsigned long)siginfo->si_addr, __DATE__, __TIME__);
sleep(1);
_exit(0);
}
int sig_list[] = {SIGSEGV, SIGABRT, SIGBUS, SIGILL, SIGFPE};
static int sig_list[] = {SIGSEGV, SIGABRT, SIGBUS, SIGILL, SIGFPE};
int sig_num = sizeof(sig_list) / sizeof(int);
static int sig_num = sizeof(sig_list) / sizeof(int);
void reg_signal(void)
static void _reg_signal(void)
{
struct sigaction act, old;
int i = 0;
act.sa_sigaction = sig_error_exit;
act.sa_sigaction = _sig_error_exit;
sigemptyset(&act.sa_mask);
act.sa_flags = SA_RESTART | SA_SIGINFO;
@@ -367,7 +351,7 @@ int main(int argc, char *argv[])
verbose_screen = 1;
break;
case 'h':
help();
_help();
return 1;
}
}
@@ -380,27 +364,29 @@ int main(int argc, char *argv[])
}
if (signal_ignore == 0) {
reg_signal();
_reg_signal();
}
if (dns_server_load_conf(config_file) != 0) {
fprintf(stderr, "load config failed.\n");
goto errout;
}
if (create_pid_file(pid_file) != 0) {
goto errout;
}
ret = smartdns_init();
ret = _smartdns_init();
if (ret != 0) {
usleep(100000);
goto errout;
}
signal(SIGINT, sig_exit);
signal(SIGINT, _sig_exit);
signal(SIGPIPE, SIG_IGN);
atexit(smartdns_exit);
atexit(_smartdns_exit);
return smartdns_run();
return _smartdns_run();
errout:

View File

@@ -97,10 +97,10 @@ struct tlog_info_inter {
typedef int (*list_callback)(const char *name, struct dirent *entry, void *user);
typedef int (*vprint_callback)(char *buff, int maxlen, void *userptr, const char *format, va_list ap);
struct tlog tlog;
static struct tlog tlog;
static int tlog_disable_early_print = 0;
static tlog_level tlog_set_level = TLOG_INFO;
tlog_format_func tlog_format;
static tlog_format_func tlog_format;
static unsigned int tlog_localtime_lock = 0;
static const char *tlog_level_str[] = {
@@ -332,7 +332,7 @@ static int _tlog_print_buffer(char *buff, int maxlen, void *userptr, const char
return total_len;
}
int _tlog_vprintf(struct tlog_log *log, vprint_callback print_callback, void *userptr, const char *format, va_list ap)
static int _tlog_vprintf(struct tlog_log *log, vprint_callback print_callback, void *userptr, const char *format, va_list ap)
{
int len;
int maxlen = 0;
@@ -406,7 +406,7 @@ int _tlog_vprintf(struct tlog_log *log, vprint_callback print_callback, void *us
int tlog_vprintf(struct tlog_log *log, const char *format, va_list ap)
{
return _tlog_vprintf(log, _tlog_print_buffer, 0, format, ap);
return _tlog_vprintf(log, _tlog_print_buffer, NULL, format, ap);
}
int tlog_printf(struct tlog_log *log, const char *format, ...)
@@ -421,7 +421,7 @@ int tlog_printf(struct tlog_log *log, const char *format, ...)
return len;
}
int _tlog_early_print(const char *format, va_list ap)
static int _tlog_early_print(const char *format, va_list ap)
{
char log_buf[TLOG_MAX_LINE_LEN];
int len = 0;
@@ -901,7 +901,7 @@ static int _tlog_write_log(struct tlog_log *log, char *buff, int bufflen)
return len;
}
int _tlog_has_data(void)
static int _tlog_has_data(void)
{
struct tlog_log *next = NULL;
@@ -919,7 +919,7 @@ int _tlog_has_data(void)
return 0;
}
int _tlog_wait_pids(void)
static int _tlog_wait_pids(void)
{
static time_t last = -1;
time_t now = 0;
@@ -931,7 +931,7 @@ int _tlog_wait_pids(void)
while (next) {
if (next->zip_pid > 0) {
if (now == 0) {
now = time(0);
now = time(NULL);
}
if (now != last) {
@@ -953,7 +953,7 @@ int _tlog_wait_pids(void)
return 0;
}
int _tlog_close(struct tlog_log *log, int wait_hang)
static int _tlog_close(struct tlog_log *log, int wait_hang)
{
struct tlog_log *next = tlog.log;
@@ -1042,7 +1042,7 @@ static void *_tlog_work(void *arg)
if ((log == loop_log || log == NULL) && tlog.run) {
/* if buffer is empty, wait */
if ((log == NULL) || (log && log->end == log->start && log->ext_end <= 0)) {
if ((log == NULL) || (log && (log->end == log->start) && (log->ext_end <= 0))) {
clock_gettime(CLOCK_REALTIME, &tm);
tm.tv_sec += 2;
tlog.is_wait = 1;
@@ -1064,7 +1064,7 @@ static void *_tlog_work(void *arg)
}
}
if (log && log->end == log->start && log->ext_end <= 0) {
if (log && (log->end == log->start) && (log->ext_end <= 0)) {
if (log->is_exit) {
if (_tlog_close(log, 0) == 0) {
log = NULL;
@@ -1126,7 +1126,7 @@ void tlog_set_early_printf(int enable)
tlog_disable_early_print = (enable == 0) ? 1 : 0;
}
void _tlog_log_setlogscreen(struct tlog_log *log, int enable)
static void _tlog_log_setlogscreen(struct tlog_log *log, int enable)
{
if (log == NULL) {
return;
@@ -1260,9 +1260,9 @@ int tlog_init(const char *logfile, int maxlogsize, int maxlogcount, int block, i
tlog.is_wait = 0;
pthread_attr_init(&attr);
pthread_mutex_init(&tlog.lock, 0);
pthread_cond_init(&tlog.cond, 0);
pthread_cond_init(&tlog.client_cond, 0);
pthread_mutex_init(&tlog.lock, NULL);
pthread_cond_init(&tlog.cond, NULL);
pthread_cond_init(&tlog.client_cond, NULL);
tlog.run = 1;
log = tlog_open(logfile, maxlogsize, maxlogcount, block, buffsize, multiwrite);

View File

@@ -48,7 +48,7 @@ format: Log formats
#ifndef BASE_FILE_NAME
#define BASE_FILE_NAME __FILE__
#endif
#define tlog(level, format, ...) tlog_ext(level, BASE_FILE_NAME, __LINE__, __func__, 0, format, ##__VA_ARGS__)
#define tlog(level, format, ...) tlog_ext(level, BASE_FILE_NAME, __LINE__, __func__, NULL, format, ##__VA_ARGS__)
extern int tlog_ext(tlog_level level, const char *file, int line, const char *func, void *userptr, const char *format, ...)
__attribute__((format(printf, 6, 7)));

View File

@@ -1,12 +1,23 @@
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include "util.h"
#include "dns_conf.h"
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/netlink.h>
#include <openssl/crypto.h>
#include <openssl/ssl.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#define TMP_BUFF_LEN_32 32
#define NFNL_SUBSYS_IPSET 6
@@ -16,6 +27,7 @@
#define IPSET_ATTR_IPADDR_IPV6 2
#define IPSET_ATTR_PROTOCOL 1
#define IPSET_ATTR_SETNAME 2
#define IPSET_ATTR_TIMEOUT 6
#define IPSET_ADD 9
#define IPSET_DEL 10
#define IPSET_MAXNAMELEN 32
@@ -62,7 +74,7 @@ unsigned long get_tick_count(void)
return (ts.tv_sec * 1000 + ts.tv_nsec / 1000000);
}
char *gethost_by_addr(char *host, struct sockaddr *addr, socklen_t addr_len)
char *gethost_by_addr(char *host, int maxsize, struct sockaddr *addr)
{
struct sockaddr_storage *addr_store = (struct sockaddr_storage *)addr;
host[0] = 0;
@@ -70,7 +82,7 @@ char *gethost_by_addr(char *host, struct sockaddr *addr, socklen_t addr_len)
case AF_INET: {
struct sockaddr_in *addr_in;
addr_in = (struct sockaddr_in *)addr;
inet_ntop(AF_INET, &addr_in->sin_addr, host, addr_len);
inet_ntop(AF_INET, &addr_in->sin_addr, host, maxsize);
} break;
case AF_INET6: {
struct sockaddr_in6 *addr_in6;
@@ -79,9 +91,9 @@ char *gethost_by_addr(char *host, struct sockaddr *addr, socklen_t addr_len)
struct sockaddr_in addr_in4;
memset(&addr_in4, 0, sizeof(addr_in4));
memcpy(&addr_in4.sin_addr.s_addr, addr_in6->sin6_addr.s6_addr + 12, sizeof(addr_in4.sin_addr.s_addr));
inet_ntop(AF_INET, &addr_in4.sin_addr, host, addr_len);
inet_ntop(AF_INET, &addr_in4.sin_addr, host, maxsize);
} else {
inet_ntop(AF_INET6, &addr_in6->sin6_addr, host, addr_len);
inet_ntop(AF_INET6, &addr_in6->sin6_addr, host, maxsize);
}
} break;
default:
@@ -243,11 +255,20 @@ static int _ipset_socket_init(void)
return 0;
}
static int _ipset_operate(const char *ipsetname, const unsigned char addr[], int addr_len, int operate)
static int _ipset_support_timeout(const char *ipsetname)
{
if (dns_conf_ipset_timeout_enable) {
return 0;
}
return -1;
}
static int _ipset_operate(const char *ipsetname, const unsigned char addr[], int addr_len, unsigned long timeout, int operate)
{
struct nlmsghdr *netlink_head;
struct ipset_netlink_msg *netlink_msg;
struct ipset_netlink_attr *nested[2];
struct ipset_netlink_attr *nested[3];
char buffer[BUFF_SZ];
uint8_t proto;
ssize_t rc;
@@ -282,7 +303,7 @@ static int _ipset_operate(const char *ipsetname, const unsigned char addr[], int
netlink_head = (struct nlmsghdr *)buffer;
netlink_head->nlmsg_len = NETLINK_ALIGN(sizeof(struct nlmsghdr));
netlink_head->nlmsg_type = operate | (NFNL_SUBSYS_IPSET << 8);
netlink_head->nlmsg_flags = NLM_F_REQUEST;
netlink_head->nlmsg_flags = NLM_F_REQUEST | NLM_F_REPLACE;
netlink_msg = (struct ipset_netlink_msg *)(buffer + netlink_head->nlmsg_len);
netlink_head->nlmsg_len += NETLINK_ALIGN(sizeof(struct ipset_netlink_msg));
@@ -300,9 +321,15 @@ static int _ipset_operate(const char *ipsetname, const unsigned char addr[], int
nested[1] = (struct ipset_netlink_attr *)(buffer + NETLINK_ALIGN(netlink_head->nlmsg_len));
netlink_head->nlmsg_len += NETLINK_ALIGN(sizeof(struct ipset_netlink_attr));
nested[1]->type = NLA_F_NESTED | IPSET_ATTR_IP;
_ipset_add_attr(netlink_head, (af == AF_INET ? IPSET_ATTR_IPADDR_IPV4 : IPSET_ATTR_IPADDR_IPV6) | NLA_F_NET_BYTEORDER, addr_len, addr);
_ipset_add_attr(netlink_head, (af == AF_INET ? IPSET_ATTR_IPADDR_IPV4 : IPSET_ATTR_IPADDR_IPV6) | NLA_F_NET_BYTEORDER, addr_len, addr);
nested[1]->len = (void *)buffer + NETLINK_ALIGN(netlink_head->nlmsg_len) - (void *)nested[1];
if (timeout > 0 && _ipset_support_timeout(ipsetname) == 0) {
timeout = htonl(timeout);
_ipset_add_attr(netlink_head, IPSET_ATTR_TIMEOUT | NLA_F_NET_BYTEORDER, sizeof(timeout), &timeout);
}
nested[0]->len = (void *)buffer + NETLINK_ALIGN(netlink_head->nlmsg_len) - (void *)nested[0];
for (;;) {
@@ -323,12 +350,152 @@ static int _ipset_operate(const char *ipsetname, const unsigned char addr[], int
return rc;
}
int ipset_add(const char *ipsetname, const unsigned char addr[], int addr_len)
int ipset_add(const char *ipsetname, const unsigned char addr[], int addr_len, unsigned long timeout)
{
return _ipset_operate(ipsetname, addr, addr_len, IPSET_ADD);
return _ipset_operate(ipsetname, addr, addr_len, timeout, IPSET_ADD);
}
int ipset_del(const char *ipsetname, const unsigned char addr[], int addr_len)
{
return _ipset_operate(ipsetname, addr, addr_len, IPSET_DEL);
}
return _ipset_operate(ipsetname, addr, addr_len, 0, IPSET_DEL);
}
unsigned char *SSL_SHA256(const unsigned char *d, size_t n, unsigned char *md)
{
SHA256_CTX c;
static unsigned char m[SHA256_DIGEST_LENGTH];
if (md == NULL)
md = m;
SHA256_Init(&c);
SHA256_Update(&c, d, n);
SHA256_Final(md, &c);
OPENSSL_cleanse(&c, sizeof(c));
return (md);
}
int SSL_base64_decode(const char *in, unsigned char *out)
{
size_t inlen = strlen(in);
int outlen;
if (inlen == 0) {
return 0;
}
outlen = EVP_DecodeBlock(out, (unsigned char *)in, inlen);
if (outlen < 0) {
goto errout;
}
/* Subtract padding bytes from |outlen| */
while (in[--inlen] == '=') {
--outlen;
}
return outlen;
errout:
return -1;
}
int create_pid_file(const char *pid_file)
{
int fd;
int flags;
char buff[TMP_BUFF_LEN_32];
/* create pid file, and lock this file */
fd = open(pid_file, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
if (fd == -1) {
fprintf(stderr, "create pid file failed, %s\n", strerror(errno));
return -1;
}
flags = fcntl(fd, F_GETFD);
if (flags < 0) {
fprintf(stderr, "Could not get flags for PID file %s\n", pid_file);
goto errout;
}
flags |= FD_CLOEXEC;
if (fcntl(fd, F_SETFD, flags) == -1) {
fprintf(stderr, "Could not set flags for PID file %s\n", pid_file);
goto errout;
}
if (lockf(fd, F_TLOCK, 0) < 0) {
fprintf(stderr, "Server is already running.\n");
goto errout;
}
snprintf(buff, TMP_BUFF_LEN_32, "%d\n", getpid());
if (write(fd, buff, strnlen(buff, TMP_BUFF_LEN_32)) < 0) {
fprintf(stderr, "write pid to file failed, %s.\n", strerror(errno));
goto errout;
}
return 0;
errout:
if (fd > 0) {
close(fd);
}
return -1;
}
#define THREAD_STACK_SIZE (16 * 1024)
static pthread_mutex_t *lock_cs;
static long *lock_count;
static __attribute__((unused)) void _pthreads_locking_callback(int mode, int type, const char *file, int line)
{
if (mode & CRYPTO_LOCK) {
pthread_mutex_lock(&(lock_cs[type]));
lock_count[type]++;
} else {
pthread_mutex_unlock(&(lock_cs[type]));
}
}
static __attribute__((unused)) unsigned long _pthreads_thread_id(void)
{
unsigned long ret;
ret = (unsigned long)pthread_self();
return (ret);
}
void SSL_CRYPTO_thread_setup(void)
{
int i;
lock_cs = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
if (!lock_cs || !lock_count) {
/* Nothing we can do about this...void function! */
if (lock_cs)
OPENSSL_free(lock_cs);
if (lock_count)
OPENSSL_free(lock_count);
return;
}
for (i = 0; i < CRYPTO_num_locks(); i++) {
lock_count[i] = 0;
pthread_mutex_init(&(lock_cs[i]), NULL);
}
CRYPTO_set_id_callback(_pthreads_thread_id);
CRYPTO_set_locking_callback(_pthreads_locking_callback);
}
void SSL_CRYPTO_thread_cleanup(void)
{
int i;
CRYPTO_set_locking_callback(NULL);
for (i = 0; i < CRYPTO_num_locks(); i++) {
pthread_mutex_destroy(&(lock_cs[i]));
}
OPENSSL_free(lock_cs);
OPENSSL_free(lock_count);
}

View File

@@ -10,7 +10,7 @@
unsigned long get_tick_count(void);
char *gethost_by_addr(char *host, struct sockaddr *addr, socklen_t addr_len);
char *gethost_by_addr(char *host, int maxsize, struct sockaddr *addr);
int getaddr_by_host(char *host, struct sockaddr *addr, socklen_t *addr_len);
@@ -22,8 +22,18 @@ char *reverse_string(char *output, char *input, int len);
void print_stack(void);
int ipset_add(const char *ipsetname, const unsigned char addr[], int addr_len);
int ipset_add(const char *ipsetname, const unsigned char addr[], int addr_len, unsigned long timeout);
int ipset_del(const char *ipsetname, const unsigned char addr[], int addr_len);
#endif
void SSL_CRYPTO_thread_setup(void);
void SSL_CRYPTO_thread_cleanup(void);
unsigned char *SSL_SHA256(const unsigned char *d, size_t n, unsigned char *md);
int SSL_base64_decode(const char *in, unsigned char *out);
int create_pid_file(const char *pid_file);
#endif