update 2023-09-21 20:09:10

This commit is contained in:
github-actions[bot] 2023-09-21 20:09:10 +08:00
parent 34a08ae0b7
commit 968f54aac2
15 changed files with 2439 additions and 73 deletions

View File

@ -16,7 +16,7 @@
include $(TOPDIR)/rules.mk
PKG_NAME:=luci-app-amlogic
PKG_VERSION:=3.1.198
PKG_VERSION:=3.1.199
PKG_RELEASE:=1
PKG_LICENSE:=GPL-2.0 License

View File

@ -62,25 +62,25 @@ elif [[ "$(echo ${MYDEVICE_NAME} | grep "FastRhino R68S")" != "" ]]; then
MYDTB_FDTFILE="rk3568-fastrhino-r68s.dtb"
fi
SOC="r68s"
elif [[ "$(echo ${MYDEVICE_NAME} | grep "HINLINK OPC-H66K Board")" != "" ]]; then
elif [[ "$(echo ${MYDEVICE_NAME} | grep "HINLINK OPC-H66K Board")" != "" || "$(echo ${MYDEVICE_NAME} | grep "Hlink H66K")" != "" ]]; then
if [ -n "${CURRENT_FDTFILE}" ]; then
MYDTB_FDTFILE="${CURRENT_FDTFILE}"
else
MYDTB_FDTFILE="rk3568-opc-h66k.dtb"
MYDTB_FDTFILE="rk3568-hlink-h66k.dtb"
fi
SOC="h66k"
elif [[ "$(echo ${MYDEVICE_NAME} | grep "HINLINK OPC-H68K Board")" != "" ]]; then
elif [[ "$(echo ${MYDEVICE_NAME} | grep "HINLINK OPC-H68K Board")" != "" || "$(echo ${MYDEVICE_NAME} | grep "Hlink H68K")" != "" ]]; then
if [ -n "${CURRENT_FDTFILE}" ]; then
MYDTB_FDTFILE="${CURRENT_FDTFILE}"
else
MYDTB_FDTFILE="rk3568-opc-h68k.dtb"
MYDTB_FDTFILE="rk3568-hlink-h68k.dtb"
fi
SOC="h68k"
elif [[ "$(echo ${MYDEVICE_NAME} | grep "HINLINK OPC-H69K Board")" != "" ]]; then
elif [[ "$(echo ${MYDEVICE_NAME} | grep "HINLINK OPC-H69K Board")" != "" || "$(echo ${MYDEVICE_NAME} | grep "Hlink H69K")" != "" ]]; then
if [ -n "${CURRENT_FDTFILE}" ]; then
MYDTB_FDTFILE="${CURRENT_FDTFILE}"
else
MYDTB_FDTFILE="rk3568-opc-h69k.dtb"
MYDTB_FDTFILE="rk3568-hlink-h69k.dtb"
fi
SOC="h69k"
elif [[ "$(echo ${MYDEVICE_NAME} | grep "Radxa E25")" != "" ]]; then
@ -111,20 +111,27 @@ elif [[ "$(echo ${MYDEVICE_NAME} | grep "Radxa ROCK 5B")" != "" ]]; then
MYDTB_FDTFILE="rk3588-rock-5b.dtb"
fi
SOC="rock5b"
elif [[ "$(echo ${MYDEVICE_NAME} | grep "HINLINK OWL H88K-V3")" != "" ]]; then
elif [[ "$(echo ${MYDEVICE_NAME} | grep "HINLINK OWL H88K-V3")" != "" || "$(echo ${MYDEVICE_NAME} | grep "Hlink H88K-V3")" != "" ]]; then
if [ -n "${CURRENT_FDTFILE}" ]; then
MYDTB_FDTFILE="${CURRENT_FDTFILE}"
else
MYDTB_FDTFILE="rk3588-hinlink-h88k-v3.dtb"
MYDTB_FDTFILE="rk3588-hlink-h88k-v3.dtb"
fi
SOC="h88k-v3"
elif [[ "$(echo ${MYDEVICE_NAME} | grep "HINLINK OWL H88K")" != "" ]]; then
elif [[ "$(echo ${MYDEVICE_NAME} | grep "HINLINK OWL H88K")" != "" || "$(echo ${MYDEVICE_NAME} | grep "Hlink H88K")" != "" ]]; then
if [ -n "${CURRENT_FDTFILE}" ]; then
MYDTB_FDTFILE="${CURRENT_FDTFILE}"
else
MYDTB_FDTFILE="rk3588-hinlink-h88k.dtb"
MYDTB_FDTFILE="rk3588-hlink-h88k.dtb"
fi
SOC="ak88/h88k"
elif [[ "$(echo ${MYDEVICE_NAME} | grep "Hlink H28K")" != "" ]]; then
if [ -n "${CURRENT_FDTFILE}" ]; then
MYDTB_FDTFILE="${CURRENT_FDTFILE}"
else
MYDTB_FDTFILE="rk3528-hlink-h28k.dtb"
fi
SOC="h28k"
elif [[ -f "/etc/flippy-openwrt-release" ]]; then
source /etc/flippy-openwrt-release 2>/dev/null
if [ -n "${CURRENT_FDTFILE}" ]; then
@ -595,7 +602,7 @@ cat >>./etc/crontabs/root <<EOF
EOF
sed -e 's/ttyAMA0/ttyS2/' -i ./etc/inittab
sed -e 's/ttyS0/tty1/' -i ./etc/inittab
[ "${SOC}" != "h28k" ] && $sed -e 's/ttyS0/tty1/' -i ./etc/inittab
sss=$(date +%s)
ddd=$((sss / 86400))
sed -e "s/:0:0:99999:7:::/:${ddd}:0:99999:7:::/" -i ./etc/shadow

View File

@ -1,7 +1,7 @@
include $(TOPDIR)/rules.mk
PKG_NAME:=luci-app-mosdns
PKG_VERSION:=1.5.9
PKG_VERSION:=1.5.10
PKG_RELEASE:=1
LUCI_TITLE:=LuCI Support for mosdns

View File

@ -60,6 +60,7 @@ o:value("114.114.115.115", "114.114.115.115 (114DNS Secondary)")
o:value("180.76.76.76", "180.76.76.76 (Baidu DNS)")
o:value("https://doh.pub/dns-query", "DNSPod DoH")
o:value("https://dns.alidns.com/dns-query", "AliDNS DoH")
o:value("quic://dns.alidns.com", "AliDNS DoQ")
o:value("https://doh.360.cn/dns-query", "360DNS DoH")
o:depends("custom_local_dns", "1")
@ -169,9 +170,8 @@ o = s:taboption("advanced", Flag, "adblock", translate("Enable DNS ADblock"))
o:depends("configfile", "/etc/mosdns/config.yaml")
o.default = false
o = s:taboption("advanced", Value, "ad_source", translate("ADblock Source"), translate("When using custom rule sources, use the rule types supported by MosDNS"))
o = s:taboption("advanced", DynamicList, "ad_source", translate("ADblock Source"), translate("When using custom rule sources, please use rule types supported by MosDNS (domain lists).") .. '<br />' .. translate("Support for local files, such as: file:///var/mosdns/example.txt"))
o:depends("adblock", "1")
o.default = "https://raw.githubusercontent.com/privacy-protection-tools/anti-AD/master/anti-ad-domains.txt"
o:value("geosite.dat", "v2ray-geosite")
o:value("https://raw.githubusercontent.com/privacy-protection-tools/anti-AD/master/anti-ad-domains.txt", "anti-AD")
o:value("https://raw.githubusercontent.com/ookangzheng/dbl-oisd-nl/master/dbl_light.txt", "oisd (small)")

View File

@ -73,8 +73,11 @@ msgstr "启用 DNS 广告过滤"
msgid "ADblock Source"
msgstr "广告过滤规则来源"
msgid "When using custom rule sources, use the rule types supported by MosDNS"
msgstr "使用自定义规则来源时,请使用 MosDNS 支持的规则类型"
msgid "When using custom rule sources, please use rule types supported by MosDNS (domain lists)."
msgstr "使用自定义规则来源时,请使用 MosDNS 支持的规则类型(域名列表)"
msgid "Support for local files, such as: file:///var/mosdns/example.txt"
msgstr "支持本地文件例如file:///var/mosdns/example.txt"
msgid "Restart-Service"
msgstr "重启服务"

View File

@ -67,9 +67,9 @@ get_config() {
init_yaml() {
TMPDIR=$(mktemp -d) || exit 1
adlist=$($MOSDNS_SCRIPT ad)
[ $enable_pipeline -eq 1 ] && enable_pipeline=true || enable_pipeline=false
[ $insecure_skip_verify -eq 1 ] && insecure_skip_verify=true || insecure_skip_verify=false
# HTTP/3
[ $enable_http3_local -eq 1 ] && enable_http3_local=true || enable_http3_local=false
[ $enable_http3_remote -eq 1 ] && enable_http3_remote=true || enable_http3_remote=false
if [ $enable_http3_local = true ]; then
@ -80,6 +80,7 @@ init_yaml() {
[ -n "$address" ] && echo ${domain#*://} $address >> $RULE_HOSTS
done
fi
# Write parameters
[ "$custom_local_dns" -eq 1 ] && \
local_dns=$($MOSDNS_SCRIPT dns | awk '{for(i=1;i<=NF;i++)printf "%s- addr: \"%s\"\n%s bootstrap: '${bootstrap_dns}'\n%s enable_pipeline: '${enable_pipeline}'\n%s max_conns: '${max_conns}'\n%s insecure_skip_verify: '${insecure_skip_verify}'\n%s idle_timeout: '${idle_timeout}'\n%s enable_http3: '${enable_http3_local}'\n",s,$i,s,s,s,s,s,s}' s=' ') || \
local_dns=$($MOSDNS_SCRIPT dns | awk '{for(i=1;i<=NF;i++)printf "%s- addr: \"%s\"\n",s,$i,s}' s=' ')
@ -90,20 +91,29 @@ init_yaml() {
s,minimal_ttl_custom,$minimal_ttl_custom,g; \
s,maximum_ttl_custom,$maximum_ttl_custom,g; \
s,concurrent_num,$concurrent,g;s,api_port,$listen_port_api,g; \
s,adblock,$adlist,g;s,remote_dns_pipeline,$enable_pipeline,g" $DEFAULT_CONF > $CONF
s,remote_dns_pipeline,$enable_pipeline,g" $DEFAULT_CONF > $CONF
# Adlist
adlist=$($MOSDNS_SCRIPT adlist)
echo "${adlist}" > $TMPDIR/adlist_files.txt
sed -i -e '/ADBLOCK_LIST/{r '$TMPDIR/adlist_files.txt -e';d}' $CONF
# DNS
echo "${local_dns}" > $TMPDIR/local_dns.txt
echo "${remote_dns}" > $TMPDIR/remote_dns.txt
sed -i -e '/- addr: local_dns/{r '$TMPDIR/local_dns.txt -e';d};/- addr: remote_dns/{r '$TMPDIR/remote_dns.txt -e';d}' $CONF
# Cache dump
[ "$dump_file" -eq 1 ] && sed -i "/lazy_cache_ttl/a\ dump_file: $DUMP_FILE\n dump_interval: $dump_interval" $CONF
[ "$dump_file" -eq 1 ] && [ ! -f $DUMP_FILE ] && cp -a $DUMP_FILE_DEFAULT $DUMP_FILE
[ "$dump_file" -eq 0 ] && \cp -a $DUMP_FILE_DEFAULT $DUMP_FILE
# ECS
if [ "$enable_ecs_remote" -eq 1 ]; then
ecs_remote=$(sh $MOSDNS_SCRIPT ecs_remote)
sed -i "s,ecs_remote,$ecs_remote,g" $CONF
else
sed -i "/ecs_remote/d;" $CONF
fi
# DNS Leak
[ $dns_leak -eq 1 ] && sed -i "s,primary: query_is_local_ip,primary: query_is_remote,g" $CONF
# Cloudflare IP
if [ $cloudflare -eq 1 ]; then
cloudflare_ip=$(sh $MOSDNS_SCRIPT cloudflare)
sed -i "s/CLOUDFLARE_IP/$cloudflare_ip/g" $CONF
@ -193,11 +203,22 @@ start_service() {
[ "$redirect" -ne 1 ] && [ -f "/etc/mosdns/redirect.lock" ] && restore_setting
[ "$redirect" -eq 1 ] && redirect_setting
reload_dnsmasq
# Update Adlist
update_list=0
[ "$adblock" -eq 1 ] && [ "$ad_source" != "geosite.dat" ] && {
[ -s "/etc/mosdns/rule/adlist.txt" ] && [ -f "/etc/mosdns/rule/.ad_source" ] && url_adlist=$(cat /etc/mosdns/rule/.ad_source) || update_list=1
[ "$ad_source" != "$url_adlist" ] && update_list=1
}
if [ "$adblock" -eq 1 ]; then
if [ -f "/etc/mosdns/rule/.ad_source" ]; then
for url in $ad_source;
do
[ "$url" = "geosite.dat" ] && continue
if [ $(grep -c "$url" "/etc/mosdns/rule/.ad_source") -eq 0 ]; then
update_list=1
break
fi
done
else
update_list=1
fi
fi
[ "$update_list" -eq 1 ] && $MOSDNS_SCRIPT adlist_update &> /dev/null &
}

View File

@ -66,7 +66,7 @@ plugins:
type: domain_set
args:
files:
- "adblock"
ADBLOCK_LIST
- tag: local_ptr
type: domain_set

View File

@ -29,37 +29,62 @@ interface_dns() (
fi
)
ad_block() (
get_adlist() (
adblock=$(uci -q get mosdns.config.adblock)
if [ "$adblock" = 1 ]; then
mkdir -p /etc/mosdns/rule/adlist
ad_source=$(uci -q get mosdns.config.ad_source)
if [ "$ad_source" = "geosite.dat" ]; then
echo "/var/mosdns/geosite_category-ads-all.txt"
else
echo "/etc/mosdns/rule/adlist.txt"
fi
for url in $ad_source;
do
if [ $(echo $url) = 'geosite.dat' ]; then
echo " - \"/var/mosdns/geosite_category-ads-all.txt\""
elif echo "$url" | grep -Eq "^file://" ; then
echo " - \"$(echo "$url" | sed 's/file:\/\///')\""
else
echo " - \"/etc/mosdns/rule/adlist/$(basename $url)\""
[ ! -f "/etc/mosdns/rule/adlist/$(basename $url)" ] && touch /etc/mosdns/rule/adlist/$(basename $url)
fi
done
else
touch /var/disable-ads.txt ; echo "/var/disable-ads.txt"
rm -rf /etc/mosdns/rule/adlist /etc/mosdns/rule/.ad_source /etc/mosdns/rule/adlist.txt
touch /var/disable-ads.txt
echo " - \"/var/disable-ads.txt\""
fi
)
adlist_update() (
[ $(uci -q get mosdns.config.adblock) -eq 0 ] && exit 0
ad_source=$(uci -q get mosdns.config.ad_source)
[ "$ad_source" = "geosite.dat" ] || [ -z "$ad_source" ] && exit 0
AD_TMPDIR=$(mktemp -d) || exit 1
if echo "$ad_source" | grep -Eq "^https://raw.githubusercontent.com" ; then
google_status=$(curl -I -4 -m 3 -o /dev/null -s -w %{http_code} http://www.google.com/generate_204)
[ "$google_status" -ne "204" ] && mirror="https://ghproxy.com/"
fi
echo -e "\e[1;32mDownloading $mirror$ad_source\e[0m"
curl --connect-timeout 60 -m 90 --ipv4 -kfSLo "$AD_TMPDIR/adlist.txt" "$mirror$ad_source"
google_status=$(curl -I -4 -m 3 -o /dev/null -s -w %{http_code} http://www.google.com/generate_204)
mirror=""
: > /etc/mosdns/rule/.ad_source
has_update=0
for url in $ad_source;
do
if [ "$url" != "geosite.dat" ] && [ $(echo "$url" | grep -c -E "^file://") -eq 0 ]; then
echo "$url" >> /etc/mosdns/rule/.ad_source
filename=$(basename $url)
if echo "$url" | grep -Eq "^https://raw.githubusercontent.com" ; then
[ "$google_status" -ne "204" ] && mirror="https://ghproxy.com/"
fi
echo -e "\e[1;32mDownloading $mirror$url\e[0m"
curl --connect-timeout 5 -m 90 --ipv4 -kfSLo "$AD_TMPDIR/$filename" "$mirror$url"
has_update=1
fi
done
if [ $? -ne 0 ]; then
echo -e "\e[1;31mRules download failed.\e[0m"
rm -rf "$AD_TMPDIR"
exit 1
else
\cp "$AD_TMPDIR/adlist.txt" /etc/mosdns/rule/adlist.txt
echo "$ad_source" > /etc/mosdns/rule/.ad_source
rm -rf "$AD_TMPDIR"
[ $has_update -eq 1 ] && {
mkdir -p /etc/mosdns/rule/adlist
rm -rf /etc/mosdns/rule/adlist/*
\cp $AD_TMPDIR/* /etc/mosdns/rule/adlist
rm -rf "$AD_TMPDIR"
restart_service
}
fi
)
@ -69,11 +94,11 @@ geodat_update() (
[ "$google_status" -ne "204" ] && mirror="https://ghproxy.com/"
# geoip.dat - cn-private
echo -e "\e[1;32mDownloading "$mirror"https://github.com/Loyalsoldier/geoip/releases/latest/download/geoip-only-cn-private.dat\e[0m"
curl --connect-timeout 60 -m 900 --ipv4 -kfSLo "$TMPDIR/geoip.dat" ""$mirror"https://github.com/Loyalsoldier/geoip/releases/latest/download/geoip-only-cn-private.dat"
curl --connect-timeout 5 -m 60 --ipv4 -kfSLo "$TMPDIR/geoip.dat" ""$mirror"https://github.com/Loyalsoldier/geoip/releases/latest/download/geoip-only-cn-private.dat"
[ $? -ne 0 ] && rm -rf "$TMPDIR" && exit 1
# checksum - geoip.dat
echo -e "\e[1;32mDownloading "$mirror"https://github.com/Loyalsoldier/geoip/releases/latest/download/geoip-only-cn-private.dat.sha256sum\e[0m"
curl --connect-timeout 60 -m 900 --ipv4 -kfSLo "$TMPDIR/geoip.dat.sha256sum" ""$mirror"https://github.com/Loyalsoldier/geoip/releases/latest/download/geoip-only-cn-private.dat.sha256sum"
curl --connect-timeout 5 -m 10 --ipv4 -kfSLo "$TMPDIR/geoip.dat.sha256sum" ""$mirror"https://github.com/Loyalsoldier/geoip/releases/latest/download/geoip-only-cn-private.dat.sha256sum"
[ $? -ne 0 ] && rm -rf "$TMPDIR" && exit 1
if [ "$(sha256sum "$TMPDIR/geoip.dat" | awk '{print $1}')" != "$(cat "$TMPDIR/geoip.dat.sha256sum" | awk '{print $1}')" ]; then
echo -e "\e[1;31mgeoip.dat checksum error\e[0m"
@ -83,11 +108,11 @@ geodat_update() (
# geosite.dat
echo -e "\e[1;32mDownloading "$mirror"https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat\e[0m"
curl --connect-timeout 60 -m 900 --ipv4 -kfSLo "$TMPDIR/geosite.dat" ""$mirror"https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat"
curl --connect-timeout 5 -m 120 --ipv4 -kfSLo "$TMPDIR/geosite.dat" ""$mirror"https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat"
[ $? -ne 0 ] && rm -rf "$TMPDIR" && exit 1
# checksum - geosite.dat
echo -e "\e[1;32mDownloading "$mirror"https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat.sha256sum\e[0m"
curl --connect-timeout 60 -m 900 --ipv4 -kfSLo "$TMPDIR/geosite.dat.sha256sum" ""$mirror"https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat.sha256sum"
curl --connect-timeout 5 -m 10 --ipv4 -kfSLo "$TMPDIR/geosite.dat.sha256sum" ""$mirror"https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat.sha256sum"
[ $? -ne 0 ] && rm -rf "$TMPDIR" && exit 1
if [ "$(sha256sum "$TMPDIR/geosite.dat" | awk '{print $1}')" != "$(cat "$TMPDIR/geosite.dat.sha256sum" | awk '{print $1}')" ]; then
echo -e "\e[1;31mgeosite.dat checksum error\e[0m"
@ -124,7 +149,7 @@ v2dat_dump() {
# default config
v2dat unpack geoip -o /var/mosdns -f cn $v2dat_dir/geoip.dat
v2dat unpack geosite -o /var/mosdns -f cn -f 'geolocation-!cn' $v2dat_dir/geosite.dat
[ "$adblock" -eq 1 ] && [ "$ad_source" = "geosite.dat" ] && v2dat unpack geosite -o /var/mosdns -f category-ads-all $v2dat_dir/geosite.dat
[ "$adblock" -eq 1 ] && [ $(echo $ad_source | grep -c geosite.dat) -ge '1' ] && v2dat unpack geosite -o /var/mosdns -f category-ads-all $v2dat_dir/geosite.dat
else
# custom config
v2dat unpack geoip -o /var/mosdns -f cn $v2dat_dir/geoip.dat
@ -144,8 +169,8 @@ case $script_action in
"dns")
interface_dns
;;
"ad")
ad_block
"adlist")
get_adlist
;;
"geodata")
geodat_update && adlist_update && restart_service
@ -154,7 +179,7 @@ case $script_action in
logfile_path
;;
"adlist_update")
adlist_update && restart_service
adlist_update
;;
"ecs_remote")
ecs_remote

View File

@ -0,0 +1,639 @@
From 24c1cd73acc4fb1c9e5fb8a54eff570889ec81a3 Mon Sep 17 00:00:00 2001
From: Irine Sistiana <49315432+IrineSistiana@users.noreply.github.com>
Date: Wed, 20 Sep 2023 09:25:41 +0800
Subject: [PATCH 1/6] pkg/server: decoupling from query_context
---
.../handler.go => http_handler.go} | 68 +++++++++--------
pkg/server/iface.go | 23 ++++++
pkg/server/tcp.go | 74 ++++++++-----------
pkg/server/udp.go | 49 ++++--------
pkg/server/utils.go | 7 ++
.../entry_handler.go | 31 ++++----
plugin/server/http_server/http_server.go | 16 ++--
plugin/server/server_utils/handler.go | 10 ++-
plugin/server/tcp_server/tcp_server.go | 11 ++-
plugin/server/udp_server/udp_server.go | 4 +-
10 files changed, 144 insertions(+), 149 deletions(-)
rename pkg/server/{http_handler/handler.go => http_handler.go} (75%)
create mode 100644 pkg/server/iface.go
create mode 100644 pkg/server/utils.go
rename pkg/{server/dns_handler => server_handler}/entry_handler.go (77%)
diff --git a/pkg/server/http_handler/handler.go b/pkg/server/http_handler.go
similarity index 75%
rename from pkg/server/http_handler/handler.go
rename to pkg/server/http_handler.go
index 25f52e1..5fa76b4 100644
--- a/pkg/server/http_handler/handler.go
+++ b/pkg/server/http_handler.go
@@ -17,69 +17,67 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
-package http_handler
+package server
import (
"encoding/base64"
"errors"
"fmt"
- "github.com/IrineSistiana/mosdns/v5/mlog"
- "github.com/IrineSistiana/mosdns/v5/pkg/dnsutils"
- "github.com/IrineSistiana/mosdns/v5/pkg/pool"
- "github.com/IrineSistiana/mosdns/v5/pkg/query_context"
- "github.com/IrineSistiana/mosdns/v5/pkg/server/dns_handler"
- "github.com/miekg/dns"
- "go.uber.org/zap"
"io"
"net/http"
"net/netip"
"strings"
-)
-type HandlerOpts struct {
- // DNSHandler is required.
- DNSHandler dns_handler.Handler
+ "github.com/IrineSistiana/mosdns/v5/pkg/dnsutils"
+ "github.com/IrineSistiana/mosdns/v5/pkg/pool"
+ "github.com/miekg/dns"
+ "go.uber.org/zap"
+)
- // SrcIPHeader specifies the header that contain client source address.
+type HttpHandlerOpts struct {
+ // GetSrcIPFromHeader specifies the header that contain client source address.
// e.g. "X-Forwarded-For".
- SrcIPHeader string
+ GetSrcIPFromHeader string
// Logger specifies the logger which Handler writes its log to.
// Default is a nop logger.
Logger *zap.Logger
}
-func (opts *HandlerOpts) init() {
- if opts.Logger == nil {
- opts.Logger = mlog.Nop()
- }
- return
+type HttpHandler struct {
+ dnsHandler Handler
+ logger *zap.Logger
+ srcIPHeader string
}
-type Handler struct {
- opts HandlerOpts
-}
+var _ http.Handler = (*HttpHandler)(nil)
-func NewHandler(opts HandlerOpts) *Handler {
- opts.init()
- return &Handler{opts: opts}
+func NewHttpHandler(h Handler, opts HttpHandlerOpts) *HttpHandler {
+ hh := new(HttpHandler)
+ hh.dnsHandler = h
+ hh.srcIPHeader = opts.GetSrcIPFromHeader
+ hh.logger = opts.Logger
+ if hh.logger == nil {
+ hh.logger = nopLogger
+ }
+ return hh
}
-func (h *Handler) warnErr(req *http.Request, msg string, err error) {
- h.opts.Logger.Warn(msg, zap.String("from", req.RemoteAddr), zap.String("method", req.Method), zap.String("url", req.RequestURI), zap.Error(err))
+func (h *HttpHandler) warnErr(req *http.Request, msg string, err error) {
+ h.logger.Warn(msg, zap.String("from", req.RemoteAddr), zap.String("method", req.Method), zap.String("url", req.RequestURI), zap.Error(err))
}
-func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
+func (h *HttpHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
addrPort, err := netip.ParseAddrPort(req.RemoteAddr)
if err != nil {
- h.opts.Logger.Error("failed to parse request remote addr", zap.String("addr", req.RemoteAddr), zap.Error(err))
+ h.logger.Error("failed to parse request remote addr", zap.String("addr", req.RemoteAddr), zap.Error(err))
w.WriteHeader(http.StatusInternalServerError)
return
}
clientAddr := addrPort.Addr()
// read remote addr from header
- if header := h.opts.SrcIPHeader; len(header) != 0 {
+ if header := h.srcIPHeader; len(header) != 0 {
if xff := req.Header.Get(header); len(xff) != 0 {
addr, err := readClientAddrFromXFF(xff)
if err != nil {
@@ -100,12 +98,12 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
return
}
- qCtx := query_context.NewContext(q)
- query_context.SetClientAddr(qCtx, &clientAddr)
- if err := h.opts.DNSHandler.ServeDNS(req.Context(), qCtx); err != nil {
- panic(err.Error()) // Force http server to close connection.
+ r, err := h.dnsHandler.Handle(req.Context(), q, QueryMeta{ClientAddr: clientAddr})
+ if err != nil {
+ h.warnErr(req, "handler err", err)
+ panic(err) // Force http server to close connection.
}
- r := qCtx.R()
+
b, buf, err := pool.PackBuffer(r)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
diff --git a/pkg/server/iface.go b/pkg/server/iface.go
new file mode 100644
index 0000000..2f15be1
--- /dev/null
+++ b/pkg/server/iface.go
@@ -0,0 +1,23 @@
+package server
+
+import (
+ "context"
+ "net/netip"
+
+ "github.com/miekg/dns"
+)
+
+// Handler handles incoming request q and MUST ALWAYS return a response.
+// Handler MUST handle dns errors by itself and return a proper error responses.
+// e.g. Return a SERVFAIL if something goes wrong.
+// If Handle() returns an error, caller considers that the error is associated
+// with the downstream connection and will close the downstream connection
+// immediately.
+type Handler interface {
+ Handle(ctx context.Context, q *dns.Msg, meta QueryMeta) (resp *dns.Msg, err error)
+}
+
+type QueryMeta struct {
+ ClientAddr netip.Addr // Maybe invalid
+ FromUDP bool
+}
diff --git a/pkg/server/tcp.go b/pkg/server/tcp.go
index 5dc80de..5f479b1 100644
--- a/pkg/server/tcp.go
+++ b/pkg/server/tcp.go
@@ -22,15 +22,13 @@ package server
import (
"context"
"fmt"
- "github.com/IrineSistiana/mosdns/v5/mlog"
+ "net"
+ "net/netip"
+ "time"
+
"github.com/IrineSistiana/mosdns/v5/pkg/dnsutils"
"github.com/IrineSistiana/mosdns/v5/pkg/pool"
- "github.com/IrineSistiana/mosdns/v5/pkg/query_context"
- "github.com/IrineSistiana/mosdns/v5/pkg/server/dns_handler"
- "github.com/IrineSistiana/mosdns/v5/pkg/utils"
"go.uber.org/zap"
- "net"
- "time"
)
const (
@@ -38,33 +36,30 @@ const (
tcpFirstReadTimeout = time.Millisecond * 500
)
-type TCPServer struct {
- opts TCPServerOpts
-}
-
-func NewTCPServer(opts TCPServerOpts) *TCPServer {
- opts.init()
- return &TCPServer{opts: opts}
-}
-
type TCPServerOpts struct {
- DNSHandler dns_handler.Handler // Required.
- Logger *zap.Logger
- IdleTimeout time.Duration
-}
+ // Nil logger == nop
+ Logger *zap.Logger
-func (opts *TCPServerOpts) init() {
- if opts.Logger == nil {
- opts.Logger = mlog.Nop()
- }
- utils.SetDefaultNum(&opts.IdleTimeout, defaultTCPIdleTimeout)
- return
+ // Default is defaultTCPIdleTimeout.
+ IdleTimeout time.Duration
}
// ServeTCP starts a server at l. It returns if l had an Accept() error.
// It always returns a non-nil error.
-func (s *TCPServer) ServeTCP(l net.Listener) error {
- // handle listener
+func ServeTCP(l net.Listener, h Handler, opts TCPServerOpts) error {
+ logger := opts.Logger
+ if logger == nil {
+ logger = nopLogger
+ }
+ idleTimeout := opts.IdleTimeout
+ if idleTimeout <= 0 {
+ idleTimeout = defaultTCPIdleTimeout
+ }
+ firstReadTimeout := tcpFirstReadTimeout
+ if idleTimeout < firstReadTimeout {
+ firstReadTimeout = idleTimeout
+ }
+
listenerCtx, cancel := context.WithCancel(context.Background())
defer cancel()
for {
@@ -79,14 +74,12 @@ func (s *TCPServer) ServeTCP(l net.Listener) error {
defer c.Close()
defer cancelConn()
- firstReadTimeout := tcpFirstReadTimeout
- idleTimeout := s.opts.IdleTimeout
- if idleTimeout < firstReadTimeout {
- firstReadTimeout = idleTimeout
+ var clientAddr netip.Addr
+ ta, ok := c.RemoteAddr().(*net.TCPAddr)
+ if ok {
+ clientAddr = ta.AddrPort().Addr()
}
- clientAddr := utils.GetAddrFromAddr(c.RemoteAddr())
-
firstRead := true
for {
if firstRead {
@@ -102,24 +95,21 @@ func (s *TCPServer) ServeTCP(l net.Listener) error {
// handle query
go func() {
- qCtx := query_context.NewContext(req)
- query_context.SetClientAddr(qCtx, &clientAddr)
- if err := s.opts.DNSHandler.ServeDNS(tcpConnCtx, qCtx); err != nil {
- s.opts.Logger.Warn("handler err", zap.Error(err))
- c.Close()
+ r, err := h.Handle(tcpConnCtx, req, QueryMeta{ClientAddr: clientAddr})
+ if err != nil {
+ logger.Warn("handler err", zap.Error(err))
+ c.Close() // abort the connection
return
}
- r := qCtx.R()
-
b, buf, err := pool.PackBuffer(r)
if err != nil {
- s.opts.Logger.Error("failed to unpack handler's response", zap.Error(err), zap.Stringer("msg", r))
+ logger.Error("failed to unpack handler's response", zap.Error(err), zap.Stringer("msg", r))
return
}
defer pool.ReleaseBuf(buf)
if _, err := dnsutils.WriteRawMsgToTCP(c, b); err != nil {
- s.opts.Logger.Warn("failed to write response", zap.Stringer("client", c.RemoteAddr()), zap.Error(err))
+ logger.Warn("failed to write response", zap.Stringer("client", c.RemoteAddr()), zap.Error(err))
return
}
}()
diff --git a/pkg/server/udp.go b/pkg/server/udp.go
index 8bb1b85..247455b 100644
--- a/pkg/server/udp.go
+++ b/pkg/server/udp.go
@@ -24,38 +24,24 @@ import (
"fmt"
"net"
- "github.com/IrineSistiana/mosdns/v5/mlog"
"github.com/IrineSistiana/mosdns/v5/pkg/pool"
- "github.com/IrineSistiana/mosdns/v5/pkg/query_context"
- "github.com/IrineSistiana/mosdns/v5/pkg/server/dns_handler"
"github.com/miekg/dns"
"go.uber.org/zap"
)
-type UDPServer struct {
- opts UDPServerOpts
-}
-
-func NewUDPServer(opts UDPServerOpts) *UDPServer {
- opts.init()
- return &UDPServer{opts: opts}
-}
-
type UDPServerOpts struct {
- DNSHandler dns_handler.Handler // Required.
- Logger *zap.Logger
-}
-
-func (opts *UDPServerOpts) init() {
- if opts.Logger == nil {
- opts.Logger = mlog.Nop()
- }
- return
+ Logger *zap.Logger
}
// ServeUDP starts a server at c. It returns if c had a read error.
// It always returns a non-nil error.
-func (s *UDPServer) ServeUDP(c *net.UDPConn) error {
+// h is required. logger is optional.
+func ServeUDP(c *net.UDPConn, h Handler, opts UDPServerOpts) error {
+ logger := opts.Logger
+ if logger == nil {
+ logger = nopLogger
+ }
+
listenerCtx, cancel := context.WithCancel(context.Background())
defer cancel()
@@ -78,11 +64,10 @@ func (s *UDPServer) ServeUDP(c *net.UDPConn) error {
if err != nil {
return fmt.Errorf("unexpected read err: %w", err)
}
- clientAddr := remoteAddr.Addr()
q := new(dns.Msg)
if err := q.Unpack((*rb)[:n]); err != nil {
- s.opts.Logger.Warn("invalid msg", zap.Error(err), zap.Binary("msg", (*rb)[:n]), zap.Stringer("from", remoteAddr))
+ logger.Warn("invalid msg", zap.Error(err), zap.Binary("msg", (*rb)[:n]), zap.Stringer("from", remoteAddr))
continue
}
@@ -91,34 +76,32 @@ func (s *UDPServer) ServeUDP(c *net.UDPConn) error {
var err error
dstIpFromCm, err = oobReader(ob[:oobn])
if err != nil {
- s.opts.Logger.Error("failed to get dst address from oob", zap.Error(err))
+ logger.Error("failed to get dst address from oob", zap.Error(err))
}
}
// handle query
go func() {
- qCtx := query_context.NewContext(q)
- query_context.SetClientAddr(qCtx, &clientAddr)
- if err := s.opts.DNSHandler.ServeDNS(listenerCtx, qCtx); err != nil {
- s.opts.Logger.Warn("handler err", zap.Error(err))
+ r, err := h.Handle(listenerCtx, q, QueryMeta{ClientAddr: remoteAddr.Addr(), FromUDP: true})
+ if err != nil {
+ logger.Warn("handler err", zap.Error(err))
return
}
- r := qCtx.R()
if r != nil {
r.Truncate(getUDPSize(q))
b, buf, err := pool.PackBuffer(r)
if err != nil {
- s.opts.Logger.Error("failed to unpack handler's response", zap.Error(err), zap.Stringer("msg", r))
+ logger.Error("failed to unpack handler's response", zap.Error(err), zap.Stringer("msg", r))
return
}
defer pool.ReleaseBuf(buf)
- var oob []byte
+ var oob []byte
if oobWriter != nil && dstIpFromCm != nil {
oob = oobWriter(dstIpFromCm)
}
if _, _, err := c.WriteMsgUDPAddrPort(b, oob, remoteAddr); err != nil {
- s.opts.Logger.Warn("failed to write response", zap.Stringer("client", remoteAddr), zap.Error(err))
+ logger.Warn("failed to write response", zap.Stringer("client", remoteAddr), zap.Error(err))
}
}
}()
diff --git a/pkg/server/utils.go b/pkg/server/utils.go
new file mode 100644
index 0000000..5e1b5c1
--- /dev/null
+++ b/pkg/server/utils.go
@@ -0,0 +1,7 @@
+package server
+
+import "go.uber.org/zap"
+
+var (
+ nopLogger = zap.NewNop()
+)
diff --git a/pkg/server/dns_handler/entry_handler.go b/pkg/server_handler/entry_handler.go
similarity index 77%
rename from pkg/server/dns_handler/entry_handler.go
rename to pkg/server_handler/entry_handler.go
index cec4123..121d943 100644
--- a/pkg/server/dns_handler/entry_handler.go
+++ b/pkg/server_handler/entry_handler.go
@@ -17,17 +17,19 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
-package dns_handler
+package server_handler
import (
"context"
+ "time"
+
"github.com/IrineSistiana/mosdns/v5/mlog"
"github.com/IrineSistiana/mosdns/v5/pkg/query_context"
+ "github.com/IrineSistiana/mosdns/v5/pkg/server"
"github.com/IrineSistiana/mosdns/v5/pkg/utils"
"github.com/IrineSistiana/mosdns/v5/plugin/executable/sequence"
"github.com/miekg/dns"
"go.uber.org/zap"
- "time"
)
const (
@@ -38,18 +40,6 @@ var (
nopLogger = mlog.Nop()
)
-// Handler handles dns query.
-type Handler interface {
- // ServeDNS handles incoming request qCtx and MUST ALWAYS set a response.
- // Implements must not keep and use qCtx after the ServeDNS returned.
- // ServeDNS should handle dns errors by itself and return a proper error responses
- // for clients.
- // If ServeDNS returns an error, caller considers that the error is associated
- // with the downstream connection and will close the downstream connection
- // immediately.
- ServeDNS(ctx context.Context, qCtx *query_context.Context) error
-}
-
type EntryHandlerOpts struct {
// Logger is used for logging. Default is a noop logger.
Logger *zap.Logger
@@ -73,20 +63,26 @@ type EntryHandler struct {
opts EntryHandlerOpts
}
+var _ server.Handler = (*EntryHandler)(nil)
+
func NewEntryHandler(opts EntryHandlerOpts) *EntryHandler {
opts.init()
return &EntryHandler{opts: opts}
}
-// ServeDNS implements Handler.
+// ServeDNS implements server.Handler.
// If entry returns an error, a SERVFAIL response will be set.
// If entry returns without a response, a REFUSED response will be set.
-func (h *EntryHandler) ServeDNS(ctx context.Context, qCtx *query_context.Context) error {
+func (h *EntryHandler) Handle(ctx context.Context, q *dns.Msg, qInfo server.QueryMeta) (*dns.Msg, error) {
ddl := time.Now().Add(h.opts.QueryTimeout)
ctx, cancel := context.WithDeadline(ctx, ddl)
defer cancel()
// exec entry
+ qCtx := query_context.NewContext(q)
+ if qInfo.ClientAddr.IsValid() {
+ query_context.SetClientAddr(qCtx, &qInfo.ClientAddr)
+ }
err := h.opts.Entry.Exec(ctx, qCtx)
respMsg := qCtx.R()
if err != nil {
@@ -106,6 +102,5 @@ func (h *EntryHandler) ServeDNS(ctx context.Context, qCtx *query_context.Context
respMsg.Rcode = dns.RcodeServerFailure
}
respMsg.RecursionAvailable = true
- qCtx.SetResponse(respMsg)
- return nil
+ return respMsg, nil
}
diff --git a/plugin/server/http_server/http_server.go b/plugin/server/http_server/http_server.go
index 8e66b37..daca6db 100644
--- a/plugin/server/http_server/http_server.go
+++ b/plugin/server/http_server/http_server.go
@@ -21,13 +21,14 @@ package tcp_server
import (
"fmt"
+ "net/http"
+ "time"
+
"github.com/IrineSistiana/mosdns/v5/coremain"
- "github.com/IrineSistiana/mosdns/v5/pkg/server/http_handler"
+ "github.com/IrineSistiana/mosdns/v5/pkg/server"
"github.com/IrineSistiana/mosdns/v5/pkg/utils"
"github.com/IrineSistiana/mosdns/v5/plugin/server/server_utils"
"golang.org/x/net/http2"
- "net/http"
- "time"
)
const PluginType = "http_server"
@@ -73,12 +74,11 @@ func StartServer(bp *coremain.BP, args *Args) (*HttpServer, error) {
if err != nil {
return nil, fmt.Errorf("failed to init dns handler, %w", err)
}
- hhOpts := http_handler.HandlerOpts{
- DNSHandler: dh,
- SrcIPHeader: args.SrcIPHeader,
- Logger: bp.L(),
+ hhOpts := server.HttpHandlerOpts{
+ GetSrcIPFromHeader: args.SrcIPHeader,
+ Logger: bp.L(),
}
- hh := http_handler.NewHandler(hhOpts)
+ hh := server.NewHttpHandler(dh, hhOpts)
mux.Handle(entry.Path, hh)
}
diff --git a/plugin/server/server_utils/handler.go b/plugin/server/server_utils/handler.go
index 2a20e1a..bbc6eab 100644
--- a/plugin/server/server_utils/handler.go
+++ b/plugin/server/server_utils/handler.go
@@ -21,21 +21,23 @@ package server_utils
import (
"fmt"
+
"github.com/IrineSistiana/mosdns/v5/coremain"
- "github.com/IrineSistiana/mosdns/v5/pkg/server/dns_handler"
+ "github.com/IrineSistiana/mosdns/v5/pkg/server"
+ "github.com/IrineSistiana/mosdns/v5/pkg/server_handler"
"github.com/IrineSistiana/mosdns/v5/plugin/executable/sequence"
)
-func NewHandler(bp *coremain.BP, entry string) (dns_handler.Handler, error) {
+func NewHandler(bp *coremain.BP, entry string) (server.Handler, error) {
p := bp.M().GetPlugin(entry)
exec := sequence.ToExecutable(p)
if exec == nil {
return nil, fmt.Errorf("cannot find executable entry by tag %s", entry)
}
- handlerOpts := dns_handler.EntryHandlerOpts{
+ handlerOpts := server_handler.EntryHandlerOpts{
Logger: bp.L(),
Entry: exec,
}
- return dns_handler.NewEntryHandler(handlerOpts), nil
+ return server_handler.NewEntryHandler(handlerOpts), nil
}
diff --git a/plugin/server/tcp_server/tcp_server.go b/plugin/server/tcp_server/tcp_server.go
index 5aca0f5..f69c667 100644
--- a/plugin/server/tcp_server/tcp_server.go
+++ b/plugin/server/tcp_server/tcp_server.go
@@ -22,12 +22,13 @@ package tcp_server
import (
"crypto/tls"
"fmt"
+ "net"
+ "time"
+
"github.com/IrineSistiana/mosdns/v5/coremain"
"github.com/IrineSistiana/mosdns/v5/pkg/server"
"github.com/IrineSistiana/mosdns/v5/pkg/utils"
"github.com/IrineSistiana/mosdns/v5/plugin/server/server_utils"
- "net"
- "time"
)
const PluginType = "tcp_server"
@@ -69,9 +70,6 @@ func StartServer(bp *coremain.BP, args *Args) (*TcpServer, error) {
return nil, fmt.Errorf("failed to init dns handler, %w", err)
}
- serverOpts := server.TCPServerOpts{Logger: bp.L(), DNSHandler: dh, IdleTimeout: time.Duration(args.IdleTimeout) * time.Second}
- s := server.NewTCPServer(serverOpts)
-
// Init tls
var tc *tls.Config
if len(args.Key)+len(args.Cert) > 0 {
@@ -91,7 +89,8 @@ func StartServer(bp *coremain.BP, args *Args) (*TcpServer, error) {
go func() {
defer l.Close()
- err := s.ServeTCP(l)
+ serverOpts := server.TCPServerOpts{Logger: bp.L(), IdleTimeout: time.Duration(args.IdleTimeout) * time.Second}
+ err := server.ServeTCP(l, dh, serverOpts)
bp.M().GetSafeClose().SendCloseSignal(err)
}()
return &TcpServer{
diff --git a/plugin/server/udp_server/udp_server.go b/plugin/server/udp_server/udp_server.go
index 293f720..988f312 100644
--- a/plugin/server/udp_server/udp_server.go
+++ b/plugin/server/udp_server/udp_server.go
@@ -64,15 +64,13 @@ func StartServer(bp *coremain.BP, args *Args) (*UdpServer, error) {
return nil, fmt.Errorf("failed to init dns handler, %w", err)
}
- serverOpts := server.UDPServerOpts{Logger: bp.L(), DNSHandler: dh}
- s := server.NewUDPServer(serverOpts)
c, err := net.ListenPacket("udp", args.Listen)
if err != nil {
return nil, fmt.Errorf("failed to create socket, %w", err)
}
go func() {
defer c.Close()
- err := s.ServeUDP(c.(*net.UDPConn))
+ err := server.ServeUDP(c.(*net.UDPConn), dh, server.UDPServerOpts{Logger: bp.L()})
bp.M().GetSafeClose().SendCloseSignal(err)
}()
return &UdpServer{
--
2.34.8

View File

@ -0,0 +1,31 @@
From 61c1586082d21ad793447c3c4510230b492ffbc0 Mon Sep 17 00:00:00 2001
From: Irine Sistiana <49315432+IrineSistiana@users.noreply.github.com>
Date: Wed, 20 Sep 2023 09:31:39 +0800
Subject: [PATCH 2/6] server: don't exit udp server on tempory read err
---
pkg/server/udp.go | 8 +++++++-
1 file changed, 7 insertions(+), 1 deletion(-)
diff --git a/pkg/server/udp.go b/pkg/server/udp.go
index 247455b..4dc1087 100644
--- a/pkg/server/udp.go
+++ b/pkg/server/udp.go
@@ -62,7 +62,13 @@ func ServeUDP(c *net.UDPConn, h Handler, opts UDPServerOpts) error {
for {
n, oobn, _, remoteAddr, err := c.ReadMsgUDPAddrPort(*rb, ob)
if err != nil {
- return fmt.Errorf("unexpected read err: %w", err)
+ if n == 0 {
+ // err with zero read. Most likely becasue c was closed.
+ return fmt.Errorf("unexpected read err: %w", err)
+ }
+ // err with some read. Tempory err.
+ logger.Warn("read err", zap.Error(err))
+ continue
}
q := new(dns.Msg)
--
2.34.8

View File

@ -0,0 +1,25 @@
From c19d24ab47674c2a82591c9e16fb450df7882465 Mon Sep 17 00:00:00 2001
From: Irine Sistiana <49315432+IrineSistiana@users.noreply.github.com>
Date: Thu, 21 Sep 2023 08:57:07 +0800
Subject: [PATCH 3/6] pool: fixed bytes pool size was 1k
---
pkg/pool/allocator.go | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/pkg/pool/allocator.go b/pkg/pool/allocator.go
index eb011ea..84b1110 100644
--- a/pkg/pool/allocator.go
+++ b/pkg/pool/allocator.go
@@ -24,7 +24,7 @@ import (
)
var (
- _pool = bytesPool.NewPool(10) // 1Mbyte pool, should be enough.
+ _pool = bytesPool.NewPool(20) // 1Mbyte pool, should be enough.
GetBuf = _pool.Get
ReleaseBuf = _pool.Release
)
--
2.34.8

View File

@ -0,0 +1,32 @@
From bedebc75e1f88d02e737203b09041c39094d5777 Mon Sep 17 00:00:00 2001
From: Irine Sistiana <49315432+IrineSistiana@users.noreply.github.com>
Date: Thu, 21 Sep 2023 11:04:03 +0800
Subject: [PATCH 4/6] pool: fixed PackTCPBuffer always re-allocate
---
pkg/pool/msg_buf.go | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/pkg/pool/msg_buf.go b/pkg/pool/msg_buf.go
index f132cc2..11faf7d 100644
--- a/pkg/pool/msg_buf.go
+++ b/pkg/pool/msg_buf.go
@@ -60,13 +60,14 @@ func PackTCPBuffer(m *dns.Msg) (buf *[]byte, err error) {
return nil, fmt.Errorf("dns payload size %d is too large", l)
}
- if &((*b)[0]) != &wire[0] { // reallocated
+ if &((*b)[2]) != &wire[0] { // reallocated
ReleaseBuf(b)
b = GetBuf(l + 2)
binary.BigEndian.PutUint16((*b)[:2], uint16(l))
copy((*b)[2:], wire)
return b, nil
}
+ binary.BigEndian.PutUint16((*b)[:2], uint16(l))
*b = (*b)[:2+l]
return b, nil
}
--
2.34.8

View File

@ -0,0 +1,31 @@
From f0005ccc3a27dcbcc2266c550ffb7acf688523f0 Mon Sep 17 00:00:00 2001
From: Irine Sistiana <49315432+IrineSistiana@users.noreply.github.com>
Date: Thu, 21 Sep 2023 11:04:35 +0800
Subject: [PATCH 5/6] dnsutils: let WriteMsgToTCP use PackTCPBuffer
---
pkg/dnsutils/net_io.go | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/pkg/dnsutils/net_io.go b/pkg/dnsutils/net_io.go
index 8fc769b..f165446 100644
--- a/pkg/dnsutils/net_io.go
+++ b/pkg/dnsutils/net_io.go
@@ -78,12 +78,12 @@ func ReadMsgFromTCP(c io.Reader) (*dns.Msg, int, error) {
// WriteMsgToTCP packs and writes m to c in RFC 1035 format.
// n represents how many bytes are written to c.
func WriteMsgToTCP(c io.Writer, m *dns.Msg) (n int, err error) {
- mRaw, buf, err := pool.PackBuffer(m)
+ buf, err := pool.PackTCPBuffer(m)
if err != nil {
return 0, err
}
defer pool.ReleaseBuf(buf)
- return WriteRawMsgToTCP(c, mRaw)
+ return c.Write(*buf)
}
// WriteRawMsgToTCP See WriteMsgToTCP
--
2.34.8

File diff suppressed because it is too large Load Diff

View File

@ -4,31 +4,17 @@ Date: Sun, 25 Jun 2023 06:50:27 +0800
Subject: [PATCH 10/10] add debug log again
---
pkg/server/dns_handler/entry_handler.go | 4 +++-
pkg/server/http_handler/handler.go | 1 +
plugin/executable/cache/cache.go | 3 +++
3 files changed, 7 insertions(+), 1 deletion(-)
pkg/server/http_handler.go | 1 +
pkg/server_handler/entry_handler.go | 2 ++
pkg/upstream/bootstrap/bootstrap.go | 2 +-
plugin/executable/cache/cache.go | 3 +++
4 files changed, 7 insertions(+), 1 deletion(-)
diff --git a/pkg/server/dns_handler/entry_handler.go b/pkg/server/dns_handler/entry_handler.go
index 4737811..cec4123 100644
--- a/pkg/server/dns_handler/entry_handler.go
+++ b/pkg/server/dns_handler/entry_handler.go
@@ -90,7 +90,9 @@ func (h *EntryHandler) ServeDNS(ctx context.Context, qCtx *query_context.Context
err := h.opts.Entry.Exec(ctx, qCtx)
respMsg := qCtx.R()
if err != nil {
- h.opts.Logger.Warn("entry err", qCtx.InfoField(), zap.Error(err))
+ h.opts.Logger.Warn("entry returned an err", qCtx.InfoField(), zap.Error(err))
+ } else {
+ h.opts.Logger.Debug("entry returned", qCtx.InfoField())
}
if err == nil && respMsg == nil {
diff --git a/pkg/server/http_handler/handler.go b/pkg/server/http_handler/handler.go
index 3e800f9..25f52e1 100644
--- a/pkg/server/http_handler/handler.go
+++ b/pkg/server/http_handler/handler.go
@@ -96,6 +96,7 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
diff --git a/pkg/server/http_handler.go b/pkg/server/http_handler.go
index 58f5811..5fa76b4 100644
--- a/pkg/server/http_handler.go
+++ b/pkg/server/http_handler.go
@@ -94,6 +94,7 @@ func (h *HttpHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if err != nil {
h.warnErr(req, "invalid request", err)
w.WriteHeader(http.StatusBadRequest)
@ -36,6 +22,32 @@ index 3e800f9..25f52e1 100644
return
}
diff --git a/pkg/server_handler/entry_handler.go b/pkg/server_handler/entry_handler.go
index 520e3d2..38df952 100644
--- a/pkg/server_handler/entry_handler.go
+++ b/pkg/server_handler/entry_handler.go
@@ -87,6 +87,8 @@ func (h *EntryHandler) Handle(ctx context.Context, q *dns.Msg, qInfo server.Quer
respMsg := qCtx.R()
if err != nil {
h.opts.Logger.Warn("entry err", qCtx.InfoField(), zap.Error(err))
+ } else {
+ h.opts.Logger.Debug("entry returned", qCtx.InfoField())
}
if err == nil && respMsg == nil {
diff --git a/pkg/upstream/bootstrap/bootstrap.go b/pkg/upstream/bootstrap/bootstrap.go
index 2cd8ef9..5192053 100644
--- a/pkg/upstream/bootstrap/bootstrap.go
+++ b/pkg/upstream/bootstrap/bootstrap.go
@@ -117,7 +117,7 @@ func (sp *Bootstrap) tryUpdate() {
if updateInterval < minimumUpdateInterval {
updateInterval = minimumUpdateInterval
}
- sp.logger.Info(
+ sp.logger.Debug(
"bootstrap addr updated",
zap.String("fqdn", sp.fqdn),
zap.Stringer("addr", addr),
diff --git a/plugin/executable/cache/cache.go b/plugin/executable/cache/cache.go
index 58162ee..dd833dc 100644
--- a/plugin/executable/cache/cache.go