From 47f1462baffca9d43040cc2fc348b844e5e2ce3f Mon Sep 17 00:00:00 2001 From: Markson Joe Hon Date: Thu, 2 Jul 2026 13:10:12 +0800 Subject: [PATCH] feat: init a new for v2raya core and fix a firewall mistake --- .gitmodules | 3 - core/dns/cache.go | 424 ++++ core/dns/cache_test.go | 957 ++++++++ core/dns/config.go | 96 + core/dns/diagnostics.go | 240 ++ core/dns/dispatcher.go | 25 + {service/core => core}/dns/dns.go | 0 {service/core => core}/dns/dns_unix.go | 0 {service/core => core}/dns/dns_windows.go | 0 core/dns/go_dns.go | 13 + core/dns/handler.go | 495 ++++ core/dns/listener.go | 219 ++ core/dns/metrics.go | 392 +++ core/dns/metrics_test.go | 487 ++++ core/dns/module.go | 507 ++++ core/dns/qtype.go | 135 ++ core/dns/response.go | 379 +++ core/dns/response_test.go | 1040 ++++++++ core/dns/router.go | 217 ++ core/dns/rule.go | 274 +++ {service/core => core}/dns/system_darwin.go | 0 {service/core => core}/dns/system_other.go | 0 {service/core => core}/dns/system_windows.go | 0 core/dns/types.go | 161 ++ core/dns/upstream.go | 258 ++ core/dns/upstream_stub.go | 741 ++++++ core/dns/upstream_test.go | 746 ++++++ core/dns/validator.go | 158 ++ core/examples/dns-with-socks.json | 146 ++ core/main/dns_module.go | 184 ++ core/main/geosite.go | 69 + core/main/run.go | 64 +- core/main/xray_dispatcher.go | 89 + core/v2ray | 1 - service/common/httpClient/httpClient.go | 2 +- service/common/parseGeoIP/parser.go | 2 +- service/conf/report/connection.go | 4 +- service/conf/report/coreStatus.go | 4 +- service/conf/report/curl.go | 2 +- service/core/v2ray/dnsParser.go | 20 - service/core/v2ray/transparent.go | 126 - service/core/v2ray/v2rayTmpl.go | 2160 ----------------- service/db/configure/configure.go | 26 + service/db/configure/dnsrules.go | 22 + service/db/configure/migrate_dns.go | 92 + service/db/configure/raw.go | 2 +- service/db/configure/setting.go | 20 +- service/go.mod | 14 +- service/go.sum | 16 + service/{core => kernel}/coreObj/coreObj.go | 20 +- .../ipforward/ipforward_linux.go | 0 .../ipforward/ipforward_other.go | 0 .../ipforward/ipforward_unix.go | 0 .../{core => kernel}/iptables/dropSpoofing.go | 0 service/{core => kernel}/iptables/iptables.go | 0 service/{core => kernel}/iptables/redirect.go | 47 +- .../iptables/systemProxy_macos.go | 0 .../iptables/systemProxy_other.go | 0 .../iptables/systemProxy_windows.go | 0 service/{core => kernel}/iptables/tproxy.go | 60 +- service/{core => kernel}/iptables/utils.go | 0 service/{core => kernel}/iptables/watcher.go | 0 service/{core => kernel}/serverObj/anytls.go | 2 +- service/{core => kernel}/serverObj/http.go | 0 .../{core => kernel}/serverObj/hysteria2.go | 0 service/{core => kernel}/serverObj/juicity.go | 2 +- service/{core => kernel}/serverObj/plugin.go | 2 +- .../{core => kernel}/serverObj/serverObj.go | 4 +- .../{core => kernel}/serverObj/shadowsocks.go | 2 +- .../serverObj/shadowsocksr.go | 0 service/{core => kernel}/serverObj/socks.go | 2 +- service/{core => kernel}/serverObj/trojan.go | 2 +- service/{core => kernel}/serverObj/tuic.go | 2 +- service/{core => kernel}/serverObj/v2ray.go | 2 +- .../{core => kernel}/serverObj/wireguard.go | 2 +- service/{core => kernel}/touch/touch.go | 0 service/{core => kernel}/v2ray/api.go | 0 service/{core => kernel}/v2ray/asset/asset.go | 0 .../{core => kernel}/v2ray/asset/dat/geoip.go | 2 +- .../v2ray/asset/dat/geosite.go | 2 +- .../v2ray/asset/dat/gfwlist.go | 6 +- .../{core => kernel}/v2ray/connectivity.go | 0 service/{core => kernel}/v2ray/dnsHijack.go | 14 + service/{core => kernel}/v2ray/dnslisten.go | 17 +- service/{core => kernel}/v2ray/feed.go | 0 service/{core => kernel}/v2ray/process.go | 37 +- .../{core => kernel}/v2ray/processManager.go | 2 +- .../{core => kernel}/v2ray/service/service.go | 6 +- .../{core => kernel}/v2ray/templateJson.go | 0 service/kernel/v2ray/template_api.go | 128 + service/kernel/v2ray/template_core.go | 201 ++ service/kernel/v2ray/template_dns.go | 370 +++ service/kernel/v2ray/template_inbound.go | 303 +++ service/kernel/v2ray/template_outbound.go | 411 ++++ service/kernel/v2ray/template_routing.go | 591 +++++ service/kernel/v2ray/template_serverdata.go | 100 + service/kernel/v2ray/template_validate.go | 120 + .../{core => kernel}/v2ray/tinytun_enabled.go | 4 +- .../{core => kernel}/v2ray/tinytun_stub.go | 0 service/kernel/v2ray/transparent.go | 212 ++ service/{core => kernel}/v2ray/where/where.go | 0 .../{core => kernel}/vmessInfo/vmessInfo.go | 0 service/pre.go | 421 +--- service/pre_database.go | 203 ++ service/pre_environment.go | 77 + service/pre_run.go | 60 + service/pre_update.go | 119 + service/server/controller/dnslist.go | 62 +- service/server/controller/gfwlist.go | 2 +- service/server/controller/outbound.go | 2 +- service/server/controller/ports.go | 4 +- service/server/controller/setting.go | 4 +- service/server/controller/subscription.go | 2 +- service/server/controller/touch.go | 4 +- service/server/controller/version.go | 8 +- service/server/service/connect.go | 6 +- service/server/service/import.go | 6 +- service/server/service/latency.go | 6 +- service/server/service/message.go | 2 +- service/server/service/ports.go | 2 +- service/server/service/resolve.go | 2 +- service/server/service/setting.go | 6 +- service/server/service/subscription.go | 4 +- service/service_windows.go | 2 +- 124 files changed, 11862 insertions(+), 2849 deletions(-) create mode 100644 core/dns/cache.go create mode 100644 core/dns/cache_test.go create mode 100644 core/dns/config.go create mode 100644 core/dns/diagnostics.go create mode 100644 core/dns/dispatcher.go rename {service/core => core}/dns/dns.go (100%) rename {service/core => core}/dns/dns_unix.go (100%) rename {service/core => core}/dns/dns_windows.go (100%) create mode 100644 core/dns/go_dns.go create mode 100644 core/dns/handler.go create mode 100644 core/dns/listener.go create mode 100644 core/dns/metrics.go create mode 100644 core/dns/metrics_test.go create mode 100644 core/dns/module.go create mode 100644 core/dns/qtype.go create mode 100644 core/dns/response.go create mode 100644 core/dns/response_test.go create mode 100644 core/dns/router.go create mode 100644 core/dns/rule.go rename {service/core => core}/dns/system_darwin.go (100%) rename {service/core => core}/dns/system_other.go (100%) rename {service/core => core}/dns/system_windows.go (100%) create mode 100644 core/dns/types.go create mode 100644 core/dns/upstream.go create mode 100644 core/dns/upstream_stub.go create mode 100644 core/dns/upstream_test.go create mode 100644 core/dns/validator.go create mode 100644 core/examples/dns-with-socks.json create mode 100644 core/main/dns_module.go create mode 100644 core/main/geosite.go create mode 100644 core/main/xray_dispatcher.go delete mode 160000 core/v2ray delete mode 100644 service/core/v2ray/dnsParser.go delete mode 100644 service/core/v2ray/transparent.go delete mode 100644 service/core/v2ray/v2rayTmpl.go create mode 100644 service/db/configure/migrate_dns.go rename service/{core => kernel}/coreObj/coreObj.go (95%) rename service/{core => kernel}/ipforward/ipforward_linux.go (100%) rename service/{core => kernel}/ipforward/ipforward_other.go (100%) rename service/{core => kernel}/ipforward/ipforward_unix.go (100%) rename service/{core => kernel}/iptables/dropSpoofing.go (100%) rename service/{core => kernel}/iptables/iptables.go (100%) rename service/{core => kernel}/iptables/redirect.go (77%) rename service/{core => kernel}/iptables/systemProxy_macos.go (100%) rename service/{core => kernel}/iptables/systemProxy_other.go (100%) rename service/{core => kernel}/iptables/systemProxy_windows.go (100%) rename service/{core => kernel}/iptables/tproxy.go (75%) rename service/{core => kernel}/iptables/utils.go (100%) rename service/{core => kernel}/iptables/watcher.go (100%) rename service/{core => kernel}/serverObj/anytls.go (98%) rename service/{core => kernel}/serverObj/http.go (100%) rename service/{core => kernel}/serverObj/hysteria2.go (100%) rename service/{core => kernel}/serverObj/juicity.go (98%) rename service/{core => kernel}/serverObj/plugin.go (98%) rename service/{core => kernel}/serverObj/serverObj.go (96%) rename service/{core => kernel}/serverObj/shadowsocks.go (99%) rename service/{core => kernel}/serverObj/shadowsocksr.go (100%) rename service/{core => kernel}/serverObj/socks.go (98%) rename service/{core => kernel}/serverObj/trojan.go (99%) rename service/{core => kernel}/serverObj/tuic.go (99%) rename service/{core => kernel}/serverObj/v2ray.go (99%) rename service/{core => kernel}/serverObj/wireguard.go (99%) rename service/{core => kernel}/touch/touch.go (100%) rename service/{core => kernel}/v2ray/api.go (100%) rename service/{core => kernel}/v2ray/asset/asset.go (100%) rename service/{core => kernel}/v2ray/asset/dat/geoip.go (96%) rename service/{core => kernel}/v2ray/asset/dat/geosite.go (96%) rename service/{core => kernel}/v2ray/asset/dat/gfwlist.go (97%) rename service/{core => kernel}/v2ray/connectivity.go (100%) rename service/{core => kernel}/v2ray/dnsHijack.go (62%) rename service/{core => kernel}/v2ray/dnslisten.go (80%) rename service/{core => kernel}/v2ray/feed.go (100%) rename service/{core => kernel}/v2ray/process.go (89%) rename service/{core => kernel}/v2ray/processManager.go (99%) rename service/{core => kernel}/v2ray/service/service.go (93%) rename service/{core => kernel}/v2ray/templateJson.go (100%) create mode 100644 service/kernel/v2ray/template_api.go create mode 100644 service/kernel/v2ray/template_core.go create mode 100644 service/kernel/v2ray/template_dns.go create mode 100644 service/kernel/v2ray/template_inbound.go create mode 100644 service/kernel/v2ray/template_outbound.go create mode 100644 service/kernel/v2ray/template_routing.go create mode 100644 service/kernel/v2ray/template_serverdata.go create mode 100644 service/kernel/v2ray/template_validate.go rename service/{core => kernel}/v2ray/tinytun_enabled.go (99%) rename service/{core => kernel}/v2ray/tinytun_stub.go (100%) create mode 100644 service/kernel/v2ray/transparent.go rename service/{core => kernel}/v2ray/where/where.go (100%) rename service/{core => kernel}/vmessInfo/vmessInfo.go (100%) create mode 100644 service/pre_database.go create mode 100644 service/pre_environment.go create mode 100644 service/pre_run.go create mode 100644 service/pre_update.go diff --git a/.gitmodules b/.gitmodules index d81f139d..1f77f91f 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,6 +1,3 @@ [submodule "core/xray"] path = core/xray url = https://github.com/XTLS/Xray-core.git -[submodule "core/v2ray"] - path = core/v2ray - url = https://github.com/v2fly/v2ray-core.git diff --git a/core/dns/cache.go b/core/dns/cache.go new file mode 100644 index 00000000..98538879 --- /dev/null +++ b/core/dns/cache.go @@ -0,0 +1,424 @@ +package dns + +import ( + "container/list" + "sync" + "time" + + "github.com/miekg/dns" +) + +// CacheKey 缓存键 - 四元组确保隔离 +type CacheKey struct { + UpstreamAddr string // 上游地址 + ProxyTag string // 代理渠道标签 + Name string // 查询域名(小写) + QType QueryType // 查询类型 +} + +// CacheEntry 缓存条目 +type CacheEntry struct { + Key CacheKey + Response *DnsResponse + OriginalTTL uint32 // 上游返回的原始 TTL + EffectiveTTL uint32 // 钳制后的生效 TTL + StoredAt time.Time // 存储时间 + ExpiresAt time.Time // 过期时间 + HitCount int64 // 命中次数 + Prefetching bool // 是否正在预取 + Negative bool // 是否为负缓存 + PrefetchFailCount int // 预取失败次数 + PrefetchBackoff time.Duration // 当前预取退避时长 + LastPrefetchFail time.Time // 上次预取失败时间 +} + +// DnsCache DNS 缓存(LRU + TTL 双淘汰) +type DnsCache struct { + config *CacheConfig + entries map[CacheKey]*list.Element + lruList *list.List // LRU 顺序链表 + mu sync.RWMutex + maxSize int + stats CacheStats +} + +// CacheStats 缓存统计 +type CacheStats struct { + Size int + Hits int64 + Misses int64 + Evictions int64 + PrefetchCnt int64 + HitRate float64 +} + +// NewDnsCache 创建新的 DNS 缓存实例 +func NewDnsCache(config *CacheConfig) *DnsCache { + maxSize := config.Size + if maxSize <= 0 { + maxSize = 4096 + } + return &DnsCache{ + config: config, + entries: make(map[CacheKey]*list.Element), + lruList: list.New(), + maxSize: maxSize, + } +} + +// calculateEffectiveTTL 计算生效 TTL(参照 mihomo 策略) +// 公式: effectiveTTL = min(max(minTTL, originalTTL), maxTTL) +func calculateEffectiveTTL(originalTTL uint32, minTTL, maxTTL int) uint32 { + if minTTL <= 0 { + minTTL = 60 // 默认最小 60 秒 + } + if maxTTL <= 0 { + maxTTL = 86400 // 默认最大 86400 秒(24小时) + } + + effective := originalTTL + if effective < uint32(minTTL) { + effective = uint32(minTTL) + } + if effective > uint32(maxTTL) { + effective = uint32(maxTTL) + } + return effective +} + +// negativeTTL 负缓存 TTL(秒) +// NXDOMAIN (3) → 60s, SERVFAIL (2) → 30s, REFUSED (5) → 10s, 其他 → 5s +func negativeTTL(rcode int) uint32 { + switch rcode { + case dns.RcodeNameError: // NXDOMAIN + return 60 + case dns.RcodeServerFailure: // SERVFAIL + return 30 + case dns.RcodeRefused: // REFUSED + return 10 + default: + return 5 + } +} + +// prefetchBackoff 计算预取退避时间 +// 3 次失败后,退避时间逐步增加 5s→30s→120s +func prefetchBackoff(failCount int) time.Duration { + switch failCount { + case 0: + return 0 + case 1: + return 5 * time.Second + case 2: + return 30 * time.Second + default: + return 120 * time.Second + } +} + +// Get 获取缓存条目 +// 返回缓存的响应和是否命中。如果条目不存在或已过期,返回 nil, false。 +func (c *DnsCache) Get(key CacheKey) (*DnsResponse, bool) { + c.mu.Lock() + defer c.mu.Unlock() + + elem, ok := c.entries[key] + if !ok { + c.stats.Misses++ + c.updateHitRate() + return nil, false + } + + entry, ok := elem.Value.(*CacheEntry) + if !ok { + c.stats.Misses++ + c.updateHitRate() + return nil, false + } + + // 检查是否过期 + if time.Now().After(entry.ExpiresAt) { + c.removeElement(elem) + c.stats.Misses++ + c.updateHitRate() + return nil, false + } + + // 移动到链表头部(最近使用) + c.lruList.MoveToFront(elem) + + entry.HitCount++ + c.stats.Hits++ + c.updateHitRate() + + // 标记响应来自缓存 + resp := *entry.Response + resp.Cached = true + return &resp, true +} + +// Set 设置缓存条目 +// 如果键已存在则更新;否则添加新条目。超过最大容量时淘汰最久未使用的条目。 +func (c *DnsCache) Set(key CacheKey, resp *DnsResponse, originalTTL uint32) { + c.mu.Lock() + defer c.mu.Unlock() + + now := time.Now() + + // 如果键已存在,更新旧条目 + if elem, ok := c.entries[key]; ok { + c.lruList.MoveToFront(elem) + entry := elem.Value.(*CacheEntry) + + // 重置预取状态 + entry.Prefetching = false + + // 如果是成功响应,重置预取失败计数 + if resp != nil && resp.Rcode == dns.RcodeSuccess { + entry.PrefetchFailCount = 0 + entry.PrefetchBackoff = 0 + } + + // 计算生效 TTL + entry.Response = resp + entry.OriginalTTL = originalTTL + entry.StoredAt = now + entry.EffectiveTTL = computeEffectiveTTL(resp, originalTTL, c.config) + entry.ExpiresAt = now.Add(time.Duration(entry.EffectiveTTL) * time.Second) + entry.Negative = resp != nil && resp.Rcode != dns.RcodeSuccess + + c.stats.Size = c.lruList.Len() + c.updateHitRate() + return + } + + // 计算生效 TTL + effectiveTTL := computeEffectiveTTL(resp, originalTTL, c.config) + negative := resp != nil && resp.Rcode != dns.RcodeSuccess + + entry := &CacheEntry{ + Key: key, + Response: resp, + OriginalTTL: originalTTL, + EffectiveTTL: effectiveTTL, + StoredAt: now, + ExpiresAt: now.Add(time.Duration(effectiveTTL) * time.Second), + Negative: negative, + } + + elem := c.lruList.PushFront(entry) + c.entries[key] = elem + + // LRU 淘汰:超过最大条目数时淘汰最久未使用的条目 + if c.lruList.Len() > c.maxSize { + back := c.lruList.Back() + if back != nil { + c.removeElement(back) + c.stats.Evictions++ + } + } + + c.stats.Size = c.lruList.Len() + c.updateHitRate() +} + +// computeEffectiveTTL 根据响应类型计算生效 TTL +// 成功响应使用 min/max 钳制;负响应使用独立的负缓存 TTL +func computeEffectiveTTL(resp *DnsResponse, originalTTL uint32, config *CacheConfig) uint32 { + if resp != nil && resp.Rcode != dns.RcodeSuccess { + return negativeTTL(resp.Rcode) + } + return calculateEffectiveTTL(originalTTL, config.MinTTL, config.MaxTTL) +} + +// Remove 从缓存中移除指定键的条目 +func (c *DnsCache) Remove(key CacheKey) { + c.mu.Lock() + defer c.mu.Unlock() + + if elem, ok := c.entries[key]; ok { + c.removeElement(elem) + c.stats.Size = c.lruList.Len() + c.updateHitRate() + } +} + +// Clear 清空所有缓存条目 +func (c *DnsCache) Clear() { + c.mu.Lock() + defer c.mu.Unlock() + + c.entries = make(map[CacheKey]*list.Element) + c.lruList.Init() + c.stats.Size = 0 + c.updateHitRate() +} + +// Stats 返回缓存统计信息的快照 +func (c *DnsCache) Stats() CacheStats { + c.mu.RLock() + defer c.mu.RUnlock() + + return c.stats +} + +// removeElement 从 LRU 链表和索引中移除元素 +func (c *DnsCache) removeElement(elem *list.Element) { + entry, ok := elem.Value.(*CacheEntry) + if ok { + delete(c.entries, entry.Key) + } + c.lruList.Remove(elem) +} + +// updateHitRate 更新缓存命中率 +func (c *DnsCache) updateHitRate() { + total := c.stats.Hits + c.stats.Misses + if total > 0 { + c.stats.HitRate = float64(c.stats.Hits) / float64(total) + } else { + c.stats.HitRate = 0 + } +} + +// ShouldPrefetch 判断是否需要预取 +// 策略:TTL 剩余低于 10% 或低于 PrefetchThreshold 秒时触发 +func (c *DnsCache) ShouldPrefetch(key CacheKey) bool { + c.mu.RLock() + defer c.mu.RUnlock() + + elem, ok := c.entries[key] + if !ok { + return false + } + + entry, ok := elem.Value.(*CacheEntry) + if !ok { + return false + } + + return shouldPrefetch(entry, c.config) +} + +// shouldPrefetch 判断条目是否需要预取(内部方法,不持有锁) +func shouldPrefetch(entry *CacheEntry, config *CacheConfig) bool { + if !config.Prefetch { + return false + } + + if entry.Prefetching { + return false // 已在预取中,避免重复 + } + + // 预取失败退避检查 + if entry.PrefetchFailCount >= 3 { + // 超过 3 次失败,不再自动触发预取 + return false + } + + // 检查退避期是否已过 + backoff := prefetchBackoff(entry.PrefetchFailCount) + if backoff > 0 && time.Since(entry.LastPrefetchFail) < backoff { + return false + } + + remaining := time.Until(entry.ExpiresAt) + totalTTL := entry.ExpiresAt.Sub(entry.StoredAt) + + // TTL 剩余低于 10% + if totalTTL > 0 && remaining < totalTTL/10 { + return true + } + + // TTL 剩余低于阈值(默认 30 秒) + threshold := config.PrefetchThreshold + if threshold <= 0 { + threshold = 30 + } + if remaining < time.Duration(threshold)*time.Second { + return true + } + + return false +} + +// SetPrefetching 设置条目的预取状态 +func (c *DnsCache) SetPrefetching(key CacheKey, status bool) { + c.mu.Lock() + defer c.mu.Unlock() + + elem, ok := c.entries[key] + if !ok { + return + } + + entry, ok := elem.Value.(*CacheEntry) + if !ok { + return + } + + entry.Prefetching = status + if status { + c.stats.PrefetchCnt++ + } +} + +// RecordPrefetchFailure 记录预取失败并更新退避状态 +func (c *DnsCache) RecordPrefetchFailure(key CacheKey) { + c.mu.Lock() + defer c.mu.Unlock() + + elem, ok := c.entries[key] + if !ok { + return + } + + entry, ok := elem.Value.(*CacheEntry) + if !ok { + return + } + + entry.PrefetchFailCount++ + entry.LastPrefetchFail = time.Now() + entry.Prefetching = false + entry.PrefetchBackoff = prefetchBackoff(entry.PrefetchFailCount) +} + +// RecordPrefetchSuccess 记录预取成功并重置退避状态 +func (c *DnsCache) RecordPrefetchSuccess(key CacheKey) { + c.mu.Lock() + defer c.mu.Unlock() + + elem, ok := c.entries[key] + if !ok { + return + } + + entry, ok := elem.Value.(*CacheEntry) + if !ok { + return + } + + entry.PrefetchFailCount = 0 + entry.PrefetchBackoff = 0 + entry.Prefetching = false +} + +// Len 返回当前缓存条目数 +func (c *DnsCache) Len() int { + c.mu.RLock() + defer c.mu.RUnlock() + return c.lruList.Len() +} + +// Keys 返回所有缓存键的列表(用于调试和监控) +func (c *DnsCache) Keys() []CacheKey { + c.mu.RLock() + defer c.mu.RUnlock() + + keys := make([]CacheKey, 0, len(c.entries)) + for k := range c.entries { + keys = append(keys, k) + } + return keys +} diff --git a/core/dns/cache_test.go b/core/dns/cache_test.go new file mode 100644 index 00000000..f902e9b0 --- /dev/null +++ b/core/dns/cache_test.go @@ -0,0 +1,957 @@ +package dns + +import ( + "fmt" + "sync" + "testing" + "time" + + "github.com/miekg/dns" +) + +// --- Helper functions --- + +func newTestCacheConfig() *CacheConfig { + return &CacheConfig{ + Enabled: true, + Size: 100, + MinTTL: 60, + MaxTTL: 86400, + Prefetch: true, + PrefetchThreshold: 30, + NegativeCache: true, + } +} + +func newTestCacheKey(name string, qtype QueryType) CacheKey { + return CacheKey{ + UpstreamAddr: "8.8.8.8:53", + ProxyTag: "direct", + Name: name, + QType: qtype, + } +} + +func newTestDNSResponse(name string, qtype QueryType, rcode int, ttl uint32) *DnsResponse { + m := new(dns.Msg) + m.SetQuestion(dns.Fqdn(name), uint16(qtype)) + m.Response = true + m.Rcode = rcode + m.RecursionAvailable = true + + // Add answer records if success + if rcode == dns.RcodeSuccess { + switch qtype { + case TypeA: + rr, _ := dns.NewRR(dns.Fqdn(name) + " 300 IN A 1.2.3.4") + m.Answer = []dns.RR{rr} + case TypeAAAA: + rr, _ := dns.NewRR(dns.Fqdn(name) + " 300 IN AAAA ::1") + m.Answer = []dns.RR{rr} + } + // Override TTL + if ttl > 0 { + m.Answer[0].Header().Ttl = ttl + } + } + + return &DnsResponse{ + RawMsg: m, + Rcode: m.Rcode, + Answer: m.Answer, + TTL: ttl, + Upstream: "8.8.8.8:53", + ProxyTag: "direct", + } +} + +// --- Test: NewDnsCache --- + +func TestNewDnsCache(t *testing.T) { + cache := NewDnsCache(newTestCacheConfig()) + + if cache == nil { + t.Fatal("NewDnsCache returned nil") + } + if cache.maxSize != 100 { + t.Errorf("expected maxSize=100, got %d", cache.maxSize) + } + if cache.lruList.Len() != 0 { + t.Errorf("expected empty cache, got %d items", cache.lruList.Len()) + } +} + +func TestNewDnsCacheDefaultSize(t *testing.T) { + // Zero size should default to 4096 + config := CacheConfig{Enabled: true, Size: 0} + cache := NewDnsCache(&config) + if cache.maxSize != 4096 { + t.Errorf("expected default maxSize=4096, got %d", cache.maxSize) + } + + // Negative size should default to 4096 + config = CacheConfig{Enabled: true, Size: -1} + cache = NewDnsCache(&config) + if cache.maxSize != 4096 { + t.Errorf("expected default maxSize=4096 for negative, got %d", cache.maxSize) + } +} + +// --- Test: Set and Get basic --- + +func TestSetAndGet(t *testing.T) { + cache := NewDnsCache(newTestCacheConfig()) + key := newTestCacheKey("example.com", TypeA) + resp := newTestDNSResponse("example.com", TypeA, dns.RcodeSuccess, 300) + + // Set cache + cache.Set(key, resp, 300) + + // Get cache + got, ok := cache.Get(key) + if !ok { + t.Fatal("expected cache hit, got miss") + } + if got == nil { + t.Fatal("expected non-nil response") + } + if got.Rcode != dns.RcodeSuccess { + t.Errorf("expected RcodeSuccess, got %d", got.Rcode) + } + if !got.Cached { + t.Error("expected Cached=true for cache response") + } +} + +func TestGetMiss(t *testing.T) { + cache := NewDnsCache(newTestCacheConfig()) + key := newTestCacheKey("nonexistent.com", TypeA) + + got, ok := cache.Get(key) + if ok { + t.Error("expected cache miss for non-existent key") + } + if got != nil { + t.Error("expected nil response for cache miss") + } +} + +// --- Test: TTL expiration --- + +func TestTTLExpiration(t *testing.T) { + config := newTestCacheConfig() + config.MinTTL = 1 // 1 second min TTL for fast test + config.MaxTTL = 2 + cache := NewDnsCache(config) + + key := newTestCacheKey("example.com", TypeA) + resp := newTestDNSResponse("example.com", TypeA, dns.RcodeSuccess, 1) + + cache.Set(key, resp, 1) + + // Should be immediately available + if _, ok := cache.Get(key); !ok { + t.Fatal("expected cache hit immediately after set") + } + + // Wait for TTL to expire + time.Sleep(3 * time.Second) + + // Should be expired now + if _, ok := cache.Get(key); ok { + t.Error("expected cache miss after TTL expiration") + } +} + +// --- Test: TTL clamping (min/max) --- + +func TestTTLClampingMin(t *testing.T) { + config := newTestCacheConfig() + config.MinTTL = 60 + config.MaxTTL = 86400 + cache := NewDnsCache(config) + + key := newTestCacheKey("example.com", TypeA) + resp := newTestDNSResponse("example.com", TypeA, dns.RcodeSuccess, 5) // original TTL=5 + + cache.Set(key, resp, 5) + + // The effective TTL should be clamped to minTTL=60 + if elem, ok := cache.entries[key]; ok { + entry := elem.Value.(*CacheEntry) + if entry.EffectiveTTL != 60 { + t.Errorf("expected effective TTL=60 (clamped from 5), got %d", entry.EffectiveTTL) + } + } +} + +func TestTTLClampingMax(t *testing.T) { + config := newTestCacheConfig() + config.MinTTL = 60 + config.MaxTTL = 600 + cache := NewDnsCache(config) + + key := newTestCacheKey("example.com", TypeA) + resp := newTestDNSResponse("example.com", TypeA, dns.RcodeSuccess, 86400) // original TTL=86400 + + cache.Set(key, resp, 86400) + + // The effective TTL should be clamped to maxTTL=600 + if elem, ok := cache.entries[key]; ok { + entry := elem.Value.(*CacheEntry) + if entry.EffectiveTTL != 600 { + t.Errorf("expected effective TTL=600 (clamped from 86400), got %d", entry.EffectiveTTL) + } + } +} + +func TestTTLClampingMiddle(t *testing.T) { + config := newTestCacheConfig() + config.MinTTL = 60 + config.MaxTTL = 86400 + cache := NewDnsCache(config) + + key := newTestCacheKey("example.com", TypeA) + resp := newTestDNSResponse("example.com", TypeA, dns.RcodeSuccess, 300) // original TTL=300 + + cache.Set(key, resp, 300) + + // The effective TTL should be 300 (within [60, 86400]) + if elem, ok := cache.entries[key]; ok { + entry := elem.Value.(*CacheEntry) + if entry.EffectiveTTL != 300 { + t.Errorf("expected effective TTL=300, got %d", entry.EffectiveTTL) + } + } +} + +// --- Test: calculateEffectiveTTL --- + +func TestCalculateEffectiveTTL(t *testing.T) { + tests := []struct { + name string + original uint32 + minTTL int + maxTTL int + expected uint32 + }{ + {"within range", 300, 60, 86400, 300}, + {"below min", 5, 60, 86400, 60}, + {"above max", 100000, 60, 86400, 86400}, + {"zero min", 300, 0, 86400, 300}, // min defaults to 60, but 300 > 60 + {"zero max", 300, 60, 0, 300}, // max defaults to 86400, but 300 < 86400 + {"zero both", 300, 0, 0, 300}, + {"exact min", 60, 60, 86400, 60}, + {"exact max", 86400, 60, 86400, 86400}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := calculateEffectiveTTL(tt.original, tt.minTTL, tt.maxTTL) + if got != tt.expected { + t.Errorf("calculateEffectiveTTL(%d, %d, %d) = %d, want %d", + tt.original, tt.minTTL, tt.maxTTL, got, tt.expected) + } + }) + } +} + +// --- Test: negativeTTL --- + +func TestNegativeTTL(t *testing.T) { + tests := []struct { + name string + rcode int + expected uint32 + }{ + {"NXDOMAIN", dns.RcodeNameError, 60}, + {"SERVFAIL", dns.RcodeServerFailure, 30}, + {"REFUSED", dns.RcodeRefused, 10}, + {"other error", dns.RcodeNotImplemented, 5}, + {"success", dns.RcodeSuccess, 5}, // Not negative, but function returns default + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := negativeTTL(tt.rcode) + if got != tt.expected { + t.Errorf("negativeTTL(%d) = %d, want %d", tt.rcode, got, tt.expected) + } + }) + } +} + +// --- Test: Negative cache --- + +func TestNegativeCache(t *testing.T) { + config := newTestCacheConfig() + config.MinTTL = 1 + config.MaxTTL = 86400 + cache := NewDnsCache(config) + + key := newTestCacheKey("nxdomain.example.com", TypeA) + resp := newTestDNSResponse("nxdomain.example.com", TypeA, dns.RcodeNameError, 0) + + cache.Set(key, resp, 0) + + // Verify it's marked as negative + if elem, ok := cache.entries[key]; ok { + entry := elem.Value.(*CacheEntry) + if !entry.Negative { + t.Error("expected Negative=true for NXDOMAIN response") + } + if entry.EffectiveTTL != 60 { + t.Errorf("expected negative TTL=60 for NXDOMAIN, got %d", entry.EffectiveTTL) + } + } + + // Should be retrievable + got, ok := cache.Get(key) + if !ok { + t.Fatal("expected cache hit for negative entry") + } + if got.Rcode != dns.RcodeNameError { + t.Errorf("expected RcodeNameError, got %d", got.Rcode) + } +} + +func TestNegativeCacheSERVFAIL(t *testing.T) { + config := newTestCacheConfig() + cache := NewDnsCache(config) + + key := newTestCacheKey("servfail.example.com", TypeA) + resp := newTestDNSResponse("servfail.example.com", TypeA, dns.RcodeServerFailure, 0) + + cache.Set(key, resp, 0) + + if elem, ok := cache.entries[key]; ok { + entry := elem.Value.(*CacheEntry) + if entry.EffectiveTTL != 30 { + t.Errorf("expected negative TTL=30 for SERVFAIL, got %d", entry.EffectiveTTL) + } + } +} + +func TestNegativeCacheREFUSED(t *testing.T) { + config := newTestCacheConfig() + cache := NewDnsCache(config) + + key := newTestCacheKey("refused.example.com", TypeA) + resp := newTestDNSResponse("refused.example.com", TypeA, dns.RcodeRefused, 0) + + cache.Set(key, resp, 0) + + if elem, ok := cache.entries[key]; ok { + entry := elem.Value.(*CacheEntry) + if entry.EffectiveTTL != 10 { + t.Errorf("expected negative TTL=10 for REFUSED, got %d", entry.EffectiveTTL) + } + } +} + +// --- Test: LRU eviction --- + +func TestLRUEviction(t *testing.T) { + config := newTestCacheConfig() + config.Size = 3 // Very small cache for easy eviction + cache := NewDnsCache(config) + + // Add 3 items (cache full) + resp1 := newTestDNSResponse("alpha.com", TypeA, dns.RcodeSuccess, 300) + resp2 := newTestDNSResponse("beta.com", TypeA, dns.RcodeSuccess, 300) + resp3 := newTestDNSResponse("gamma.com", TypeA, dns.RcodeSuccess, 300) + + cache.Set(newTestCacheKey("alpha.com", TypeA), resp1, 300) + cache.Set(newTestCacheKey("beta.com", TypeA), resp2, 300) + cache.Set(newTestCacheKey("gamma.com", TypeA), resp3, 300) + + if cache.Len() != 3 { + t.Errorf("expected 3 items, got %d", cache.Len()) + } + + // Access alpha to make it recently used + cache.Get(newTestCacheKey("alpha.com", TypeA)) + + // Add 4th item - should evict the least recently used (beta, since gamma was last added) + resp4 := newTestDNSResponse("delta.com", TypeA, dns.RcodeSuccess, 300) + cache.Set(newTestCacheKey("delta.com", TypeA), resp4, 300) + + if cache.Len() != 3 { + t.Errorf("expected 3 items after eviction, got %d", cache.Len()) + } + + // beta should have been evicted (least recently used) + if _, ok := cache.Get(newTestCacheKey("beta.com", TypeA)); ok { + t.Error("expected beta to be evicted (LRU)") + } + + // alpha and delta should still be present + if _, ok := cache.Get(newTestCacheKey("alpha.com", TypeA)); !ok { + t.Error("expected alpha to still be in cache") + } + if _, ok := cache.Get(newTestCacheKey("delta.com", TypeA)); !ok { + t.Error("expected delta to still be in cache") + } + + // Check eviction stats + stats := cache.Stats() + if stats.Evictions != 1 { + t.Errorf("expected 1 eviction, got %d", stats.Evictions) + } +} + +// --- Test: Remove --- + +func TestRemove(t *testing.T) { + cache := NewDnsCache(newTestCacheConfig()) + key := newTestCacheKey("example.com", TypeA) + resp := newTestDNSResponse("example.com", TypeA, dns.RcodeSuccess, 300) + + cache.Set(key, resp, 300) + + // Verify it's there + if _, ok := cache.Get(key); !ok { + t.Fatal("expected cache hit before removal") + } + + // Remove it + cache.Remove(key) + + // Verify it's gone + if _, ok := cache.Get(key); ok { + t.Error("expected cache miss after removal") + } +} + +// --- Test: Clear --- + +func TestClear(t *testing.T) { + cache := NewDnsCache(newTestCacheConfig()) + + // Add multiple items + for i := 0; i < 10; i++ { + name := fmt.Sprintf("host%d.example.com", i) + key := newTestCacheKey(name, TypeA) + resp := newTestDNSResponse(name, TypeA, dns.RcodeSuccess, 300) + cache.Set(key, resp, 300) + } + + if cache.Len() != 10 { + t.Errorf("expected 10 items, got %d", cache.Len()) + } + + cache.Clear() + + if cache.Len() != 0 { + t.Errorf("expected 0 items after clear, got %d", cache.Len()) + } + + stats := cache.Stats() + if stats.Size != 0 { + t.Errorf("expected stats.Size=0 after clear, got %d", stats.Size) + } +} + +// --- Test: Stats --- + +func TestStats(t *testing.T) { + config := newTestCacheConfig() + config.Size = 3 + cache := NewDnsCache(config) + + stats := cache.Stats() + if stats.Size != 0 { + t.Errorf("expected initial Size=0, got %d", stats.Size) + } + if stats.Hits != 0 { + t.Errorf("expected initial Hits=0, got %d", stats.Hits) + } + if stats.Misses != 0 { + t.Errorf("expected initial Misses=0, got %d", stats.Misses) + } + + // Add and hit + key := newTestCacheKey("example.com", TypeA) + resp := newTestDNSResponse("example.com", TypeA, dns.RcodeSuccess, 300) + cache.Set(key, resp, 300) + cache.Get(key) + + stats = cache.Stats() + if stats.Hits != 1 { + t.Errorf("expected 1 hit, got %d", stats.Hits) + } + + // Miss + cache.Get(newTestCacheKey("nonexistent.com", TypeA)) + stats = cache.Stats() + if stats.Misses != 1 { + t.Errorf("expected 1 miss, got %d", stats.Misses) + } + + // Hit rate should be 0.5 (1 hit / 2 total) + if stats.HitRate != 0.5 { + t.Errorf("expected HitRate=0.5, got %f", stats.HitRate) + } +} + +// --- Test: Concurrent safety --- + +func TestConcurrentAccess(t *testing.T) { + config := newTestCacheConfig() + config.Size = 2000 // Large enough for concurrent writes + cache := NewDnsCache(config) + var wg sync.WaitGroup + numGoroutines := 20 + numOps := 50 + + // Concurrent writes + for i := 0; i < numGoroutines; i++ { + wg.Add(1) + go func(id int) { + defer wg.Done() + for j := 0; j < numOps; j++ { + name := fmt.Sprintf("host%d-%d.example.com", id, j) + key := newTestCacheKey(name, TypeA) + resp := newTestDNSResponse(name, TypeA, dns.RcodeSuccess, 300) + cache.Set(key, resp, 300) + } + }(i) + } + + wg.Wait() + + expectedTotal := numGoroutines * numOps + if cache.Len() != expectedTotal { + t.Errorf("expected %d items after concurrent writes, got %d", expectedTotal, cache.Len()) + } + + // Concurrent reads + var readWg sync.WaitGroup + for i := 0; i < numGoroutines; i++ { + readWg.Add(1) + go func(id int) { + defer readWg.Done() + for j := 0; j < numOps; j++ { + name := fmt.Sprintf("host%d-%d.example.com", id, j) + key := newTestCacheKey(name, TypeA) + cache.Get(key) + } + }(i) + } + + readWg.Wait() + + stats := cache.Stats() + if stats.Hits == 0 { + t.Error("expected some cache hits from concurrent reads") + } + + // Concurrent mixed read/write/remove + var mixedWg sync.WaitGroup + for i := 0; i < 10; i++ { + mixedWg.Add(1) + go func(id int) { + defer mixedWg.Done() + for j := 0; j < 20; j++ { + name := fmt.Sprintf("host%d-%d.example.com", id, j) + key := newTestCacheKey(name, TypeA) + switch j % 3 { + case 0: + resp := newTestDNSResponse(name, TypeA, dns.RcodeSuccess, 300) + cache.Set(key, resp, 300) + case 1: + cache.Get(key) + case 2: + cache.Remove(key) + } + } + }(i) + } + mixedWg.Wait() + + // Should not panic + _ = cache.Stats() + _ = cache.Len() + _ = cache.Keys() +} + +// --- Test: Update existing entry --- + +func TestUpdateExistingEntry(t *testing.T) { + cache := NewDnsCache(newTestCacheConfig()) + key := newTestCacheKey("example.com", TypeA) + + // Initial set + resp1 := newTestDNSResponse("example.com", TypeA, dns.RcodeSuccess, 300) + cache.Set(key, resp1, 300) + + // Update with different data + resp2 := newTestDNSResponse("example.com", TypeA, dns.RcodeSuccess, 600) + cache.Set(key, resp2, 600) + + // Verify updated + if elem, ok := cache.entries[key]; ok { + entry := elem.Value.(*CacheEntry) + if entry.OriginalTTL != 600 { + t.Errorf("expected updated OriginalTTL=600, got %d", entry.OriginalTTL) + } + if entry.Prefetching { + t.Error("expected Prefetching=false after update") + } + } + + // Verify hit count is from the new entry + got, ok := cache.Get(key) + if !ok { + t.Fatal("expected cache hit after update") + } + if got.TTL != 600 { + t.Errorf("expected TTL=600 from updated entry, got %d", got.TTL) + } +} + +// --- Test: Prefetch logic --- + +func TestShouldPrefetchBasic(t *testing.T) { + config := newTestCacheConfig() + config.Prefetch = true + config.PrefetchThreshold = 30 + cache := NewDnsCache(config) + + key := newTestCacheKey("example.com", TypeA) + resp := newTestDNSResponse("example.com", TypeA, dns.RcodeSuccess, 86400) // very long TTL + cache.Set(key, resp, 86400) + + // Just after set, should not prefetch (TTL just started) + shouldPrefetch := cache.ShouldPrefetch(key) + if shouldPrefetch { + t.Log("Note: ShouldPrefetch returned true immediately after set (may vary based on timing)") + } +} + +func TestShouldPrefetchAlreadyPrefetching(t *testing.T) { + config := newTestCacheConfig() + config.Prefetch = true + cache := NewDnsCache(config) + + key := newTestCacheKey("example.com", TypeA) + resp := newTestDNSResponse("example.com", TypeA, dns.RcodeSuccess, 300) + cache.Set(key, resp, 300) + + // Mark as already prefetching + cache.SetPrefetching(key, true) + + // Should not trigger prefetch again + if cache.ShouldPrefetch(key) { + t.Error("expected ShouldPrefetch=false when already prefetching") + } +} + +func TestShouldPrefetchDisabled(t *testing.T) { + config := newTestCacheConfig() + config.Prefetch = false + cache := NewDnsCache(config) + + key := newTestCacheKey("example.com", TypeA) + resp := newTestDNSResponse("example.com", TypeA, dns.RcodeSuccess, 5) // very short TTL + cache.Set(key, resp, 5) + + // With prefetch disabled, should never prefetch + if cache.ShouldPrefetch(key) { + t.Error("expected ShouldPrefetch=false when prefetch is disabled") + } +} + +func TestSetPrefetching(t *testing.T) { + cache := NewDnsCache(newTestCacheConfig()) + + key := newTestCacheKey("example.com", TypeA) + resp := newTestDNSResponse("example.com", TypeA, dns.RcodeSuccess, 300) + cache.Set(key, resp, 300) + + // Set prefetching + cache.SetPrefetching(key, true) + if elem, ok := cache.entries[key]; ok { + entry := elem.Value.(*CacheEntry) + if !entry.Prefetching { + t.Error("expected Prefetching=true after SetPrefetching(true)") + } + } + + // Unset prefetching + cache.SetPrefetching(key, false) + if elem, ok := cache.entries[key]; ok { + entry := elem.Value.(*CacheEntry) + if entry.Prefetching { + t.Error("expected Prefetching=false after SetPrefetching(false)") + } + } +} + +// --- Test: Prefetch failure backoff --- + +func TestPrefetchBackoff(t *testing.T) { + tests := []struct { + failCount int + expected time.Duration + }{ + {0, 0}, + {1, 5 * time.Second}, + {2, 30 * time.Second}, + {3, 120 * time.Second}, + {4, 120 * time.Second}, // capped at 120s + {10, 120 * time.Second}, + } + + for _, tt := range tests { + got := prefetchBackoff(tt.failCount) + if got != tt.expected { + t.Errorf("prefetchBackoff(%d) = %v, want %v", tt.failCount, got, tt.expected) + } + } +} + +func TestRecordPrefetchFailure(t *testing.T) { + cache := NewDnsCache(newTestCacheConfig()) + + key := newTestCacheKey("example.com", TypeA) + resp := newTestDNSResponse("example.com", TypeA, dns.RcodeSuccess, 300) + cache.Set(key, resp, 300) + + // Record failures + cache.RecordPrefetchFailure(key) + cache.RecordPrefetchFailure(key) + + if elem, ok := cache.entries[key]; ok { + entry := elem.Value.(*CacheEntry) + if entry.PrefetchFailCount != 2 { + t.Errorf("expected PrefetchFailCount=2, got %d", entry.PrefetchFailCount) + } + if entry.PrefetchBackoff != 30*time.Second { + t.Errorf("expected PrefetchBackoff=30s, got %v", entry.PrefetchBackoff) + } + if entry.Prefetching { + t.Error("expected Prefetching=false after failure") + } + } + + // After 3 failures, ShouldPrefetch should return false + cache.RecordPrefetchFailure(key) + if cache.ShouldPrefetch(key) { + t.Error("expected ShouldPrefetch=false after 3 failures") + } +} + +func TestRecordPrefetchSuccess(t *testing.T) { + cache := NewDnsCache(newTestCacheConfig()) + + key := newTestCacheKey("example.com", TypeA) + resp := newTestDNSResponse("example.com", TypeA, dns.RcodeSuccess, 300) + cache.Set(key, resp, 300) + + // Fail twice, then succeed + cache.RecordPrefetchFailure(key) + cache.RecordPrefetchFailure(key) + cache.RecordPrefetchSuccess(key) + + if elem, ok := cache.entries[key]; ok { + entry := elem.Value.(*CacheEntry) + if entry.PrefetchFailCount != 0 { + t.Errorf("expected PrefetchFailCount=0 after success, got %d", entry.PrefetchFailCount) + } + if entry.PrefetchBackoff != 0 { + t.Errorf("expected PrefetchBackoff=0 after success, got %v", entry.PrefetchBackoff) + } + if entry.Prefetching { + t.Error("expected Prefetching=false after success") + } + } +} + +// --- Test: Different query types --- + +func TestCacheKeyIsolationByType(t *testing.T) { + cache := NewDnsCache(newTestCacheConfig()) + + keyA := newTestCacheKey("example.com", TypeA) + keyAAAA := newTestCacheKey("example.com", TypeAAAA) + + respA := newTestDNSResponse("example.com", TypeA, dns.RcodeSuccess, 300) + respAAAA := newTestDNSResponse("example.com", TypeAAAA, dns.RcodeSuccess, 300) + + cache.Set(keyA, respA, 300) + cache.Set(keyAAAA, respAAAA, 300) + + // Both should be independently accessible + if _, ok := cache.Get(keyA); !ok { + t.Error("expected cache hit for A record") + } + if _, ok := cache.Get(keyAAAA); !ok { + t.Error("expected cache hit for AAAA record") + } +} + +func TestCacheKeyIsolationByUpstream(t *testing.T) { + cache := NewDnsCache(newTestCacheConfig()) + + key1 := CacheKey{UpstreamAddr: "8.8.8.8:53", ProxyTag: "direct", Name: "example.com.", QType: TypeA} + key2 := CacheKey{UpstreamAddr: "1.1.1.1:53", ProxyTag: "direct", Name: "example.com.", QType: TypeA} + + resp := newTestDNSResponse("example.com", TypeA, dns.RcodeSuccess, 300) + + cache.Set(key1, resp, 300) + + // Different upstream should not share cache + if _, ok := cache.Get(key2); ok { + t.Error("expected cache miss for different upstream") + } +} + +func TestCacheKeyIsolationByProxyTag(t *testing.T) { + cache := NewDnsCache(newTestCacheConfig()) + + keyDirect := CacheKey{UpstreamAddr: "8.8.8.8:53", ProxyTag: "direct", Name: "example.com.", QType: TypeA} + keyProxy := CacheKey{UpstreamAddr: "8.8.8.8:53", ProxyTag: "proxy", Name: "example.com.", QType: TypeA} + + resp := newTestDNSResponse("example.com", TypeA, dns.RcodeSuccess, 300) + + cache.Set(keyDirect, resp, 300) + + // Different proxy tag should not share cache + if _, ok := cache.Get(keyProxy); ok { + t.Error("expected cache miss for different proxy tag") + } +} + +// --- Test: Empty cache behavior --- + +func TestEmptyCache(t *testing.T) { + cache := NewDnsCache(&CacheConfig{}) + + if cache.Len() != 0 { + t.Errorf("expected empty cache, got %d items", cache.Len()) + } + + stats := cache.Stats() + if stats.Size != 0 { + t.Errorf("expected Size=0, got %d", stats.Size) + } + + keys := cache.Keys() + if len(keys) != 0 { + t.Errorf("expected 0 keys, got %d", len(keys)) + } +} + +// --- Test: Keys method --- + +func TestKeys(t *testing.T) { + cache := NewDnsCache(&CacheConfig{}) + + // Add some entries + names := []string{"alpha.com", "beta.com", "gamma.com"} + for _, name := range names { + key := newTestCacheKey(name, TypeA) + resp := newTestDNSResponse(name, TypeA, dns.RcodeSuccess, 300) + cache.Set(key, resp, 300) + } + + keys := cache.Keys() + if len(keys) != 3 { + t.Errorf("expected 3 keys, got %d", len(keys)) + } +} + +// --- Test: Concurrent Set/Get/Remove on same key --- + +func TestConcurrentSameKey(t *testing.T) { + cache := NewDnsCache(&CacheConfig{}) + key := newTestCacheKey("contested.com", TypeA) + var wg sync.WaitGroup + + for i := 0; i < 10; i++ { + wg.Add(1) + go func(id int) { + defer wg.Done() + for j := 0; j < 10; j++ { + resp := newTestDNSResponse("contested.com", TypeA, dns.RcodeSuccess, uint32(100+j)) + cache.Set(key, resp, uint32(100+j)) + cache.Get(key) + cache.Remove(key) + } + }(i) + } + wg.Wait() + + // Should not panic or deadlock + t.Log("concurrent same-key operations completed without deadlock") +} + +// --- Test: buildCacheKey (from handler.go) --- + +func TestBuildCacheKey(t *testing.T) { + query := newTestQuery("example.com", TypeA) + upstream := &UpstreamInstance{ + Addr: "8.8.8.8:53", + ProxyTag: "proxy", + } + + key := buildCacheKey(query, upstream) + if key.UpstreamAddr != "8.8.8.8:53" { + t.Errorf("expected UpstreamAddr=8.8.8.8:53, got %s", key.UpstreamAddr) + } + if key.ProxyTag != "proxy" { + t.Errorf("expected ProxyTag=proxy, got %s", key.ProxyTag) + } + if key.Name != "example.com" { + t.Errorf("expected Name=example.com, got %s", key.Name) + } + if key.QType != TypeA { + t.Errorf("expected QType=A, got %d", key.QType) + } +} + +func TestBuildCacheKeyNilUpstream(t *testing.T) { + query := newTestQuery("example.com", TypeA) + key := buildCacheKey(query, nil) + if key.ProxyTag != "direct" { + t.Errorf("expected ProxyTag=direct for nil upstream, got %s", key.ProxyTag) + } + if key.UpstreamAddr != "" { + t.Errorf("expected empty UpstreamAddr for nil upstream, got %s", key.UpstreamAddr) + } +} + +// --- Test: Large number of entries --- + +func TestLargeCache(t *testing.T) { + config := newTestCacheConfig() + config.Size = 1000 + cache := NewDnsCache(config) + + // Add 1000 entries + for i := 0; i < 1000; i++ { + name := fmt.Sprintf("host%d.example.com", i) + key := newTestCacheKey(name, TypeA) + resp := newTestDNSResponse(name, TypeA, dns.RcodeSuccess, 300) + cache.Set(key, resp, 300) + } + + if cache.Len() != 1000 { + t.Errorf("expected 1000 entries, got %d", cache.Len()) + } + + // Add one more - should evict one + extraKey := newTestCacheKey("extra.example.com", TypeA) + extraResp := newTestDNSResponse("extra.example.com", TypeA, dns.RcodeSuccess, 300) + cache.Set(extraKey, extraResp, 300) + + if cache.Len() != 1000 { + t.Errorf("expected 1000 entries after eviction, got %d", cache.Len()) + } + + stats := cache.Stats() + if stats.Evictions != 1 { + t.Errorf("expected 1 eviction, got %d", stats.Evictions) + } +} diff --git a/core/dns/config.go b/core/dns/config.go new file mode 100644 index 00000000..efeef5d2 --- /dev/null +++ b/core/dns/config.go @@ -0,0 +1,96 @@ +package dns + +import ( + "fmt" + "strings" +) + +// Default configuration constants. +const ( + // DefaultListenAddr is the default DNS listener address. + DefaultListenAddr = "0.0.0.0:52353" + // DefaultTimeout is the default query timeout in seconds. + DefaultTimeout = 5 + // DefaultCacheSize is the default maximum number of cache entries. + DefaultCacheSize = 4096 + // DefaultMinTTL is the default minimum TTL in seconds. + DefaultMinTTL = 60 + // DefaultMaxTTL is the default maximum TTL in seconds. + DefaultMaxTTL = 86400 +) + +// DefaultDnsListenerConfig returns a DnsListenerConfig with default values. +func DefaultDnsListenerConfig() *DnsListenerConfig { + return &DnsListenerConfig{ + ListenAddr: DefaultListenAddr, + Timeout: DefaultTimeout, + } +} + +// DefaultDnsModuleConfig returns a DnsModuleConfig with default values. +func DefaultDnsModuleConfig() *DnsModuleConfig { + return &DnsModuleConfig{ + Listener: *DefaultDnsListenerConfig(), + Cache: CacheConfig{ + Enabled: true, + Size: DefaultCacheSize, + MinTTL: DefaultMinTTL, + MaxTTL: DefaultMaxTTL, + }, + } +} + +// Validate checks the DnsListenerConfig and returns an error if any field is invalid. +func (c *DnsListenerConfig) Validate() error { + if c.ListenAddr == "" { + return fmt.Errorf("dns listener: listen address must not be empty") + } + // Basic address format check: must contain ':' + if !strings.Contains(c.ListenAddr, ":") { + return fmt.Errorf("dns listener: listen address %q must include port (e.g. \"0.0.0.0:52353\")", c.ListenAddr) + } + for i, addr := range c.ExtraListenAddrs { + if !strings.Contains(addr, ":") { + return fmt.Errorf("dns listener: extra address[%d] %q must include port", i, addr) + } + } + if c.Timeout <= 0 { + return fmt.Errorf("dns listener: timeout must be positive, got %d", c.Timeout) + } + return nil +} + +// Validate checks the DnsModuleConfig and returns an error if any field is invalid. +func (c *DnsModuleConfig) Validate() error { + if err := c.Listener.Validate(); err != nil { + return err + } + if c.Cache.Size < 0 { + return fmt.Errorf("dns module: cache size must be non-negative, got %d", c.Cache.Size) + } + if c.Cache.MinTTL < 0 { + return fmt.Errorf("dns module: min TTL must be non-negative, got %d", c.Cache.MinTTL) + } + if c.Cache.MaxTTL < 0 { + return fmt.Errorf("dns module: max TTL must be non-negative, got %d", c.Cache.MaxTTL) + } + if c.Cache.MinTTL > c.Cache.MaxTTL && c.Cache.MaxTTL > 0 { + return fmt.Errorf("dns module: min TTL (%d) must not exceed max TTL (%d)", c.Cache.MinTTL, c.Cache.MaxTTL) + } + return nil +} + +// String returns a human-readable summary of the DnsListenerConfig. +func (c *DnsListenerConfig) String() string { + return fmt.Sprintf("listen=%s timeout=%ds", c.ListenAddr, c.Timeout) +} + +// String returns a human-readable summary of the DnsModuleConfig. +func (c *DnsModuleConfig) String() string { + cacheStatus := "disabled" + if c.Cache.Enabled { + cacheStatus = fmt.Sprintf("enabled(size=%d,minTTL=%d,maxTTL=%d)", c.Cache.Size, c.Cache.MinTTL, c.Cache.MaxTTL) + } + return fmt.Sprintf("listener[%s] cache[%s] upstreams=%d rules=%d", + c.Listener.String(), cacheStatus, len(c.Upstreams), len(c.Rules)) +} diff --git a/core/dns/diagnostics.go b/core/dns/diagnostics.go new file mode 100644 index 00000000..8dafbb95 --- /dev/null +++ b/core/dns/diagnostics.go @@ -0,0 +1,240 @@ +package dns + +import ( + "fmt" + "strings" + "time" +) + +// Diagnostics DNS 诊断信息收集器 +type Diagnostics struct { + module *DnsModule +} + +// DebugInfo 调试信息快照 +type DebugInfo struct { + Uptime string + ListenerStatus string + CacheStats CacheStats + MetricsSnapshot *MetricsSnapshot + UpstreamStatus []UpstreamStatus + RuleStatus []RuleStatus +} + +// UpstreamStatus 上游服务器状态 +type UpstreamStatus struct { + ID string + Addr string + ProxyTag string + Healthy bool + Queries int64 + Errors int64 + AvgRTT string + LastSeen string +} + +// RuleStatus 规则状态 +type RuleStatus struct { + ID string + Matches int64 + Action string + Active bool +} + +// NewDiagnostics 创建新的诊断信息收集器 +func NewDiagnostics(module *DnsModule) *Diagnostics { + return &Diagnostics{ + module: module, + } +} + +// GetDebugInfo 收集完整的调试信息 +func (d *Diagnostics) GetDebugInfo() *DebugInfo { + info := &DebugInfo{} + + // 运行时间 + info.Uptime = time.Since(d.module.stats.StartedAt).Round(time.Second).String() + + // 监听状态 + listenerStatus := "stopped" + if d.module.listener != nil && d.module.listener.Healthy() { + listenerStatus = fmt.Sprintf("running on %s", d.module.config.Listener.ListenAddr) + } + info.ListenerStatus = listenerStatus + + // 缓存统计 + if d.module.cache != nil { + info.CacheStats = d.module.cache.Stats() + } + + // 指标快照 + if d.module.metrics != nil { + info.MetricsSnapshot = d.module.metrics.Snapshot() + } + + // 上游状态 + upstreamMgr := d.module.GetUpstreamManager() + if upstreamMgr != nil { + upstreams := upstreamMgr.ListUpstreams() + info.UpstreamStatus = make([]UpstreamStatus, 0, len(upstreams)) + + // 获取指标快照用于填充上游统计 + var snap *MetricsSnapshot + if d.module.metrics != nil { + snap = d.module.metrics.Snapshot() + } + + for _, u := range upstreams { + status := UpstreamStatus{ + ID: u.ID, + Addr: u.Addr, + ProxyTag: u.ProxyTag, + Healthy: u.Healthy, + } + + // 从指标快照中获取上游统计 + if snap != nil { + // 尝试用 ID 查找 + if um, ok := snap.QueriesByUpstream[u.ID]; ok { + status.Queries = um.Queries + status.Errors = um.Errors + status.AvgRTT = um.AvgRTT.Round(time.Millisecond).String() + if !um.LastQuery.IsZero() { + status.LastSeen = um.LastQuery.Format("15:04:05") + } + } else if um, ok := snap.QueriesByUpstream[u.Addr]; ok { + status.Queries = um.Queries + status.Errors = um.Errors + status.AvgRTT = um.AvgRTT.Round(time.Millisecond).String() + if !um.LastQuery.IsZero() { + status.LastSeen = um.LastQuery.Format("15:04:05") + } + } + } + + if status.LastSeen == "" { + status.LastSeen = "never" + } + if status.AvgRTT == "" { + status.AvgRTT = "N/A" + } + + info.UpstreamStatus = append(info.UpstreamStatus, status) + } + } + + // 规则状态 + router := d.module.GetRouter() + if router != nil { + rules := router.ListRules() + info.RuleStatus = make([]RuleStatus, 0, len(rules)) + + // 获取规则命中次数 + ruleHits := make(map[string]int64) + if d.module.metrics != nil { + snap := d.module.metrics.Snapshot() + for k, v := range snap.HitsByRule { + ruleHits[k] = v + } + } + + for _, rule := range rules { + status := RuleStatus{ + ID: rule.ID, + Action: rule.Action, + Active: true, + Matches: ruleHits[rule.ID], + } + info.RuleStatus = append(info.RuleStatus, status) + } + } + + return info +} + +// Summary 返回人类可读的诊断概要 +func (d *Diagnostics) Summary() string { + info := d.GetDebugInfo() + + var b strings.Builder + b.WriteString("=== DNS Module Diagnostics ===\n") + b.WriteString(fmt.Sprintf("Uptime: %s\n", info.Uptime)) + b.WriteString(fmt.Sprintf("Listener: %s\n", info.ListenerStatus)) + + // 指标概要 + if info.MetricsSnapshot != nil { + s := info.MetricsSnapshot + b.WriteString(fmt.Sprintf("Queries: %d total, %d responses, %d errors, %d timeouts\n", + s.TotalQueries, s.TotalResponses, s.TotalErrors, s.TotalTimeouts)) + b.WriteString(fmt.Sprintf("Cache: %d hits, %d misses, %d evictions (rate: %.1f%%)\n", + s.CacheHits, s.CacheMisses, s.CacheEvictions, calcHitRate(s.CacheHits, s.CacheMisses))) + b.WriteString(fmt.Sprintf("Actions: %d routed, %d rejected, %d bypassed\n", + s.RoutedQueries, s.RejectedQueries, s.BypassedQueries)) + } + + // 上游状态 + b.WriteString("\n--- Upstreams ---\n") + if len(info.UpstreamStatus) > 0 { + for _, us := range info.UpstreamStatus { + health := "✅" + if !us.Healthy { + health = "❌" + } + b.WriteString(fmt.Sprintf(" %s %s (%s) tag=%s queries=%d errors=%d avgRTT=%s last=%s\n", + health, us.ID, us.Addr, us.ProxyTag, us.Queries, us.Errors, us.AvgRTT, us.LastSeen)) + } + } else { + b.WriteString(" (none configured)\n") + } + + // 规则状态 + b.WriteString("\n--- Rules ---\n") + if len(info.RuleStatus) > 0 { + for _, rs := range info.RuleStatus { + b.WriteString(fmt.Sprintf(" %s -> %s (matches: %d)\n", rs.ID, rs.Action, rs.Matches)) + } + } else { + b.WriteString(" (no rules configured)\n") + } + + // 缓存详情 + b.WriteString("\n--- Cache ---\n") + cs := info.CacheStats + b.WriteString(fmt.Sprintf(" Size: %d entries, Hits: %d, Misses: %d, HitRate: %.1f%%\n", + cs.Size, cs.Hits, cs.Misses, cs.HitRate*100)) + b.WriteString(fmt.Sprintf(" Evictions: %d, Prefetches: %d\n", cs.Evictions, cs.PrefetchCnt)) + + // 延迟分布 + if info.MetricsSnapshot != nil && len(info.MetricsSnapshot.LatencyBuckets) > 0 { + b.WriteString("\n--- Latency Distribution ---\n") + for _, lb := range info.MetricsSnapshot.LatencyBuckets { + if lb.Count > 0 { + bar := strings.Repeat("█", int(lb.Count/10)) + if bar == "" && lb.Count > 0 { + bar = "▏" + } + b.WriteString(fmt.Sprintf(" %-10s: %5d %s\n", lb.Label, lb.Count, bar)) + } + } + } + + return b.String() +} + +// CacheDump 导出缓存内容(调试用) +// 返回当前缓存中所有的键列表 +func (d *Diagnostics) CacheDump() []CacheKey { + if d.module.cache == nil { + return nil + } + return d.module.cache.Keys() +} + +// calcHitRate 计算缓存命中率(百分比) +func calcHitRate(hits, misses int64) float64 { + total := hits + misses + if total == 0 { + return 0 + } + return float64(hits) / float64(total) * 100 +} diff --git a/core/dns/dispatcher.go b/core/dns/dispatcher.go new file mode 100644 index 00000000..c498b478 --- /dev/null +++ b/core/dns/dispatcher.go @@ -0,0 +1,25 @@ +package dns + +import ( + "context" + "net" +) + +// RouteDispatcher is the interface for dispatching DNS queries through +// v2raya-core's internal routing. It mirrors the subset of xray-core's +// routing.Dispatcher that the DNS module needs, avoiding a direct import +// of xray-core packages in the DNS module. +// +// xray-core's default.Dispatcher implements this interface. +// The DNS module uses this to route queries through the appropriate outbound +// (e.g., "proxy" outbound) based on the proxy tag, just like xray-core's +// built-in DNS module does via session.ContextWithInbound. +type RouteDispatcher interface { + // Dispatch creates a connection to the given destination through + // xray-core's routing engine. The proxyTag controls the routing + // decision (e.g., "proxy" routes through proxy outbound, + // "direct" routes directly). The implementation sets + // session.ContextWithInbound internally, like xray-core's DNS module. + // Returns a net.Conn for DNS-over-TCP exchange. + Dispatch(ctx context.Context, network, addr, proxyTag string) (net.Conn, error) +} diff --git a/service/core/dns/dns.go b/core/dns/dns.go similarity index 100% rename from service/core/dns/dns.go rename to core/dns/dns.go diff --git a/service/core/dns/dns_unix.go b/core/dns/dns_unix.go similarity index 100% rename from service/core/dns/dns_unix.go rename to core/dns/dns_unix.go diff --git a/service/core/dns/dns_windows.go b/core/dns/dns_windows.go similarity index 100% rename from service/core/dns/dns_windows.go rename to core/dns/dns_windows.go diff --git a/core/dns/go_dns.go b/core/dns/go_dns.go new file mode 100644 index 00000000..e1d6c0d3 --- /dev/null +++ b/core/dns/go_dns.go @@ -0,0 +1,13 @@ +// Package dns provides a standalone DNS module for v2rayA. +// +// This file exists solely to ensure go.sum tracks the github.com/miekg/dns +// dependency, which is required by the DNS module. The actual imports are +// in types.go and listener.go. +// +// This file will be removed once the project's go.mod properly tracks +// all dependencies through normal build workflows. +package dns + +import ( + _ "github.com/miekg/dns" +) diff --git a/core/dns/handler.go b/core/dns/handler.go new file mode 100644 index 00000000..d05119bf --- /dev/null +++ b/core/dns/handler.go @@ -0,0 +1,495 @@ +package dns + +import ( + "context" + "fmt" + "log" + "strings" + "time" + + "github.com/miekg/dns" +) + +// DnsHandler processes incoming DNS queries and returns responses. +// It uses the Router to determine which upstream to query, and the +// UpstreamManager to send queries to upstream DNS servers. +type DnsHandler struct { + timeout time.Duration + module *DnsModule +} + +// prefetchAsync 异步执行预取,后台刷新缓存条目 +func (h *DnsHandler) prefetchAsync(ctx context.Context, upstream *UpstreamInstance, + upstreamMgr *UpstreamManager, query *DnsQuery, key CacheKey) { + + if upstream == nil || upstreamMgr == nil { + h.module.cache.SetPrefetching(key, false) + return + } + + // 记录预取指标 + if h.module.metrics != nil { + h.module.metrics.RecordPrefetch() + } + + log.Printf("[dns] prefetch: %s %s via %s (tag=%s)", + dns.Type(uint16(query.QType)).String(), query.Name, upstream.Addr, upstream.ProxyTag) + + resp, err := upstreamMgr.Exchange(upstream, query) + if err != nil { + log.Printf("[dns] prefetch error for %s %s: %v", + dns.Type(uint16(query.QType)).String(), query.Name, err) + h.module.cache.RecordPrefetchFailure(key) + return + } + + if resp == nil { + h.module.cache.RecordPrefetchFailure(key) + return + } + + // 预取成功,更新缓存 + h.module.cache.Set(key, resp, resp.TTL) + h.module.cache.RecordPrefetchSuccess(key) + + log.Printf("[dns] prefetch completed: %s %s via %s", + dns.Type(uint16(query.QType)).String(), query.Name, upstream.Addr) +} + +// buildCacheKey 构建完整的缓存键(路由后已知上游和代理渠道) +func buildCacheKey(query *DnsQuery, upstream *UpstreamInstance) CacheKey { + proxyTag := "direct" + if upstream != nil && upstream.ProxyTag != "" { + proxyTag = upstream.ProxyTag + } + upstreamAddr := "" + if upstream != nil { + upstreamAddr = upstream.Addr + } + return CacheKey{ + UpstreamAddr: upstreamAddr, + ProxyTag: proxyTag, + Name: query.Name, + QType: query.QType, + } +} + +// NewDnsHandler creates a new DnsHandler with the given timeout and module reference. +func NewDnsHandler(timeout time.Duration, module *DnsModule) *DnsHandler { + return &DnsHandler{ + timeout: timeout, + module: module, + } +} + +// HandleQuery processes a DNS query by routing it through the router +// and sending it to the appropriate upstream server. +// +// Processing flow: +// 1. Route the query using the Router. +// 2. Based on the action (route/reject/bypass), take appropriate action. +// 3. For "route": send the query to the matched upstream via UpstreamManager. +// 4. For "reject": return a REFUSED response. +// 5. For "bypass": send the query directly (bypass routing). +// 6. Track statistics. +func (h *DnsHandler) HandleQuery(ctx context.Context, query *DnsQuery) (*DnsResponse, error) { + select { + case <-ctx.Done(): + return nil, fmt.Errorf("dns handler: context cancelled: %w", ctx.Err()) + default: + } + + // Log the incoming query (structured, concise). + clientIP := "unknown" + if query.ClientIP != nil { + clientIP = query.ClientIP.String() + } + log.Printf("[dns] query: %s %s from %s", QTypeToString(query.QType), query.Name, clientIP) + + // Get module references. + module := h.module + if module == nil { + // Fallback: return stub response if no module configured. + log.Printf("[dns] no module configured, returning stub response for %s", query.Name) + return h.buildStubResponse(query), nil + } + + router := module.GetRouter() + upstreamMgr := module.GetUpstreamManager() + + // Track total queries (backward compatible stats). + module.stats.mu.Lock() + module.stats.TotalQueries++ + module.stats.mu.Unlock() + + // Step 1: Route the query. + var result *RouteResult + if router != nil { + result = router.Route(query) + } else { + // No router — use default behavior. + result = &RouteResult{ + Action: "route", + Policy: "single", + } + } + + // Step 2: Handle based on action. + switch result.Action { + case "reject": + return h.handleReject(query, module, result) + + case "bypass": + return h.handleBypass(query, module, result, upstreamMgr) + + default: // "route" + return h.handleRoute(ctx, query, module, result, upstreamMgr) + } +} + +// handleRoute sends the query to the matched upstream server. +// 查询流程(方案2:先路由再查缓存): +// +// 1. Route the query to determine upstream + proxy channel. +// 2. Build full CacheKey (with upstream + proxy tag). +// 3. Check cache. If hit: return cached response, optionally trigger prefetch. +// 4. If miss: send query to upstream, store result in cache, return response. +func (h *DnsHandler) handleRoute(ctx context.Context, query *DnsQuery, module *DnsModule, + result *RouteResult, upstreamMgr *UpstreamManager) (*DnsResponse, error) { + + upstreamID := result.UpstreamID + var upstream *UpstreamInstance + + if upstreamMgr != nil && upstreamID != "" { + var ok bool + upstream, ok = upstreamMgr.GetUpstream(upstreamID) + if !ok { + log.Printf("[dns] upstream %q not found, using default", upstreamID) + } + } + + // If no upstream found, or no router matched, use first available upstream. + if upstream == nil && upstreamMgr != nil { + // Try to find a non-bootstrap upstream. + for _, u := range module.config.Upstreams { + if !u.Bootstrap { + upstream, _ = upstreamMgr.GetUpstream(u.ID) + if upstream == nil { + upstream, _ = upstreamMgr.GetUpstream(u.Addr) + } + break + } + } + // Fallback: use any upstream. + if upstream == nil && len(module.config.Upstreams) > 0 { + u := module.config.Upstreams[0] + upstream, _ = upstreamMgr.GetUpstream(u.ID) + if upstream == nil { + upstream, _ = upstreamMgr.GetUpstream(u.Addr) + } + } + } + + if upstream == nil || upstreamMgr == nil { + log.Printf("[dns] no upstream available for %s %s, returning stub", QTypeToString(query.QType), query.Name) + return h.buildStubResponse(query), nil + } + + // Build full CacheKey after routing (upstream + proxy tag known). + cacheKey := buildCacheKey(query, upstream) + + // Record route metrics. + if module.metrics != nil { + module.metrics.RecordQuery(query, upstreamID) + module.metrics.RecordAction("route") + if result.RuleID != "" { + module.metrics.RecordRuleHit(result.RuleID) + } + } + + // Log route decision (structured, concise). + proxyInfo := upstream.ProxyTag + if proxyInfo == "" { + proxyInfo = "direct" + } + ruleInfo := "" + if result.RuleID != "" { + ruleInfo = fmt.Sprintf(" rule(%s)", result.RuleID) + } + log.Printf("[dns] route: %s %s → %s(%s)%s action(route)", + QTypeToString(query.QType), query.Name, upstreamID, proxyInfo, ruleInfo) + + // Check cache (if enabled). + cache := module.cache + if cache != nil { + if cached, ok := cache.Get(cacheKey); ok { + // Log cache hit. + _ = cached // DnsResponse, used below + log.Printf("[dns] cache-hit: %s %s", + QTypeToString(query.QType), query.Name) + + // Track cache hit (backward compatible stats). + module.stats.mu.Lock() + module.stats.CacheHits++ + module.stats.mu.Unlock() + + // Track cache hit (metrics). + if module.metrics != nil { + module.metrics.RecordCacheHit() + } + + // Check if prefetch is needed (async refresh). + if cache.ShouldPrefetch(cacheKey) { + cache.SetPrefetching(cacheKey, true) + go h.prefetchAsync(ctx, upstream, upstreamMgr, query, cacheKey) + } + + return cached, nil + } + + // Log cache miss. + log.Printf("[dns] cache-miss: %s %s", QTypeToString(query.QType), query.Name) + + // Track cache miss (backward compatible stats). + module.stats.mu.Lock() + module.stats.CacheMisses++ + module.stats.mu.Unlock() + + // Track cache miss (metrics). + if module.metrics != nil { + module.metrics.RecordCacheMiss() + } + } + + // Send query to upstream (cache miss or cache disabled). + start := time.Now() + resp, err := upstreamMgr.Exchange(upstream, query) + rtt := time.Since(start) + + if err != nil { + log.Printf("[dns] error: %s %s: %v", upstream.Addr, query.Name, err) + + // Track error in stats. + module.stats.mu.Lock() + module.stats.RoutedQueries[upstreamID]++ + module.stats.mu.Unlock() + + // Track error in metrics. + if module.metrics != nil { + module.metrics.RecordError(upstreamID, err) + } + + return nil, fmt.Errorf("dns handler: upstream error: %w", err) + } + + if resp == nil { + log.Printf("[dns] empty response for %s %s", QTypeToString(query.QType), query.Name) + return h.buildStubResponse(query), nil + } + + // Log successful upstream response. + log.Printf("[dns] upstream: %s:53 via %s (rtt=%dms)", + upstream.Addr, proxyInfo, rtt.Milliseconds()) + + // Store response in cache (if enabled and not a bootstrap query). + if cache != nil && !query.IsBootstrap { + cache.Set(cacheKey, resp, resp.TTL) + } + + // Track statistics. + module.stats.mu.Lock() + module.stats.RoutedQueries[upstreamID]++ + module.stats.AvgRTT = updateAvgRTT(module.stats.AvgRTT, rtt, module.stats.TotalQueries) + module.stats.mu.Unlock() + + // Record response metrics. + if module.metrics != nil { + module.metrics.RecordResponse(resp, rtt) + } + + return resp, nil +} + +// handleReject returns a REFUSED response for rejected queries. +func (h *DnsHandler) handleReject(query *DnsQuery, module *DnsModule, result *RouteResult) (*DnsResponse, error) { + log.Printf("[dns] reject: %s %s (rule=%s)", QTypeToString(query.QType), query.Name, result.RuleID) + + // Track statistics. + module.stats.mu.Lock() + module.stats.RejectedQueries++ + module.stats.mu.Unlock() + + // Record metrics. + if module.metrics != nil { + module.metrics.RecordQuery(query, "") + module.metrics.RecordAction("reject") + if result.RuleID != "" { + module.metrics.RecordRuleHit(result.RuleID) + } + } + + return h.buildRefused(query), nil +} + +// handleBypass handles bypass queries — sends directly without proxy routing. +func (h *DnsHandler) handleBypass(query *DnsQuery, module *DnsModule, result *RouteResult, + upstreamMgr *UpstreamManager) (*DnsResponse, error) { + + log.Printf("[dns] bypass: %s %s (rule=%s)", QTypeToString(query.QType), query.Name, result.RuleID) + + // Track statistics. + module.stats.mu.Lock() + module.stats.BypassedQueries++ + module.stats.mu.Unlock() + + // For bypass, we still need an upstream. Find a direct upstream. + var upstream *UpstreamInstance + if upstreamMgr != nil { + upstreamID := result.UpstreamID + if upstreamID != "" { + upstream, _ = upstreamMgr.GetUpstream(upstreamID) + } + // If no specific upstream for bypass, use first non-bootstrap upstream. + if upstream == nil { + for _, u := range module.config.Upstreams { + if !u.Bootstrap { + upstream, _ = upstreamMgr.GetUpstream(u.ID) + if upstream == nil { + upstream, _ = upstreamMgr.GetUpstream(u.Addr) + } + break + } + } + } + } + + if upstream == nil || upstreamMgr == nil { + return h.buildStubResponse(query), nil + } + + // Record bypass metrics. + if module.metrics != nil { + module.metrics.RecordQuery(query, result.UpstreamID) + module.metrics.RecordAction("bypass") + if result.RuleID != "" { + module.metrics.RecordRuleHit(result.RuleID) + } + } + + start := time.Now() + resp, err := upstreamMgr.Exchange(upstream, query) + rtt := time.Since(start) + + if err != nil { + log.Printf("[dns] error: %s %s: %v", upstream.Addr, query.Name, err) + if module.metrics != nil { + module.metrics.RecordError(result.UpstreamID, err) + } + return nil, fmt.Errorf("dns handler: bypass upstream error: %w", err) + } + + if resp == nil { + return h.buildStubResponse(query), nil + } + + // Log successful bypass response. + log.Printf("[dns] upstream: %s:53 direct (rtt=%dms)", + upstream.Addr, rtt.Milliseconds()) + + module.stats.mu.Lock() + module.stats.RoutedQueries[upstream.ID]++ + module.stats.AvgRTT = updateAvgRTT(module.stats.AvgRTT, rtt, module.stats.TotalQueries) + module.stats.mu.Unlock() + + // Record response metrics. + if module.metrics != nil { + module.metrics.RecordResponse(resp, rtt) + } + + return resp, nil +} + +// HandleQueryWithTimeout wraps HandleQuery with a timeout derived from the config. +func (h *DnsHandler) HandleQueryWithTimeout(query *DnsQuery, timeout time.Duration) (*DnsResponse, error) { + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + + return h.HandleQuery(ctx, query) +} + +// buildStubResponse creates a minimal stub response echoing the query. +func (h *DnsHandler) buildStubResponse(query *DnsQuery) *DnsResponse { + resp := &DnsResponse{ + Query: *query, + Rcode: dns.RcodeSuccess, + Upstream: "stub", + ProxyTag: "direct", + RTT: 0, + Cached: false, + } + + m := new(dns.Msg) + m.SetQuestion(query.Name, uint16(query.QType)) + m.Response = true + m.RecursionAvailable = true + m.Rcode = dns.RcodeSuccess + + resp.RawMsg = m + return resp +} + +// buildRefused creates a REFUSED DNS response. +func (h *DnsHandler) buildRefused(query *DnsQuery) *DnsResponse { + m := new(dns.Msg) + m.SetQuestion(query.Name, uint16(query.QType)) + m.Response = true + m.Rcode = dns.RcodeRefused + + return &DnsResponse{ + Query: *query, + RawMsg: m, + Rcode: dns.RcodeRefused, + Upstream: "", + ProxyTag: "", + RTT: 0, + Cached: false, + } +} + +// updateAvgRTT updates the average RTT using exponential moving average. +func updateAvgRTT(current time.Duration, sample time.Duration, count int64) time.Duration { + if count <= 1 { + return sample + } + // Use weighted average: new = old * (n-1)/n + sample/n + avg := int64(current)*(count-1)/count + int64(sample)/count + return time.Duration(avg) +} + +// QueryTypeFromString parses a DNS query type string (e.g., "A", "AAAA") to QueryType. +func QueryTypeFromString(s string) (QueryType, error) { + s = strings.TrimSpace(s) + switch strings.ToUpper(s) { + case "A": + return TypeA, nil + case "AAAA": + return TypeAAAA, nil + case "CNAME": + return TypeCNAME, nil + case "TXT": + return TypeTXT, nil + case "MX": + return TypeMX, nil + case "SRV": + return TypeSRV, nil + case "NS": + return TypeNS, nil + case "PTR": + return TypePTR, nil + case "SOA": + return TypeSOA, nil + default: + // Try to parse as numeric value. + return 0, fmt.Errorf("unknown query type: %s", s) + } +} diff --git a/core/dns/listener.go b/core/dns/listener.go new file mode 100644 index 00000000..4e782882 --- /dev/null +++ b/core/dns/listener.go @@ -0,0 +1,219 @@ +package dns + +import ( + "context" + "fmt" + "log" + "net" + "sync" + "time" + + "github.com/miekg/dns" +) + +// Handler is the interface for processing DNS queries. +// Implementations must be safe for concurrent use. +type Handler interface { + // HandleQuery processes a DNS query and returns a response. + // The context may carry a deadline for timeout control. + HandleQuery(ctx context.Context, query *DnsQuery) (*DnsResponse, error) +} + +// serverPair holds UDP and TCP server instances for a single listen address. +type serverPair struct { + udp *dns.Server + tcp *dns.Server +} + +// DnsListener listens for DNS queries on one or more addresses (UDP + TCP per address). +type DnsListener struct { + config *DnsListenerConfig + handler Handler + servers []serverPair + wg sync.WaitGroup + ctx context.Context + cancel context.CancelFunc +} + +// NewDnsListener creates a new DnsListener with the given config and handler. +func NewDnsListener(config *DnsListenerConfig, handler Handler) *DnsListener { + return &DnsListener{ + config: config, + handler: handler, + } +} + +// Start starts UDP and TCP listeners for the primary address and all extra addresses. +func (l *DnsListener) Start() error { + if l.config == nil { + return fmt.Errorf("dns listener: config is nil") + } + if l.handler == nil { + return fmt.Errorf("dns listener: handler is nil") + } + if err := l.config.Validate(); err != nil { + return fmt.Errorf("dns listener: invalid config: %w", err) + } + + l.ctx, l.cancel = context.WithCancel(context.Background()) + + // Collect all listen addresses (primary + extras). + allAddrs := []string{l.config.ListenAddr} + allAddrs = append(allAddrs, l.config.ExtraListenAddrs...) + + for _, addr := range allAddrs { + pair, err := l.startPair(addr) + if err != nil { + // Clean up already started listeners. + l.Stop() + return fmt.Errorf("dns listener: %s: %w", addr, err) + } + l.servers = append(l.servers, *pair) + } + + return nil +} + +// startPair starts UDP and TCP listeners for a single address. +func (l *DnsListener) startPair(addr string) (*serverPair, error) { + timeout := time.Duration(l.config.Timeout) * time.Second + + udpSrv := &dns.Server{ + Addr: addr, + Net: "udp", + Handler: dns.HandlerFunc(l.handlePacket), + UDPSize: 1452, + ReadTimeout: timeout, + WriteTimeout: timeout, + } + + l.wg.Add(1) + go func() { + defer l.wg.Done() + log.Printf("[dns] UDP listener starting on %s", addr) + if err := udpSrv.ListenAndServe(); err != nil { + log.Printf("[dns] UDP listener stopped: %v", err) + } + }() + + tcpSrv := &dns.Server{ + Addr: addr, + Net: "tcp", + Handler: dns.HandlerFunc(l.handlePacket), + ReadTimeout: timeout, + WriteTimeout: timeout, + } + + l.wg.Add(1) + go func() { + defer l.wg.Done() + log.Printf("[dns] TCP listener starting on %s", addr) + if err := tcpSrv.ListenAndServe(); err != nil { + log.Printf("[dns] TCP listener stopped: %v", err) + } + }() + + return &serverPair{udp: udpSrv, tcp: tcpSrv}, nil +} + +// Stop gracefully shuts down all listeners. +func (l *DnsListener) Stop() error { + if l.cancel != nil { + l.cancel() + } + + var lastErr error + for _, pair := range l.servers { + if pair.udp != nil { + if err := pair.udp.Shutdown(); err != nil { + log.Printf("[dns] UDP shutdown error: %v", err) + lastErr = err + } + } + if pair.tcp != nil { + if err := pair.tcp.Shutdown(); err != nil { + log.Printf("[dns] TCP shutdown error: %v", err) + lastErr = err + } + } + } + + l.wg.Wait() + l.servers = nil + + if lastErr != nil { + return fmt.Errorf("dns listener: shutdown error: %w", lastErr) + } + return nil +} + +// handlePacket is the callback invoked by miekg/dns for each incoming query. +func (l *DnsListener) handlePacket(w dns.ResponseWriter, msg *dns.Msg) { + if msg == nil { + return + } + if len(msg.Question) == 0 { + log.Printf("[dns] received message with no questions from %s", w.RemoteAddr()) + return + } + + q := msg.Question[0] + clientAddr := w.RemoteAddr() + + query := &DnsQuery{ + Name: q.Name, + QType: QueryType(q.Qtype), + } + + switch addr := clientAddr.(type) { + case *net.UDPAddr: + query.ClientIP = addr.IP + case *net.TCPAddr: + query.ClientIP = addr.IP + } + + log.Printf("[dns] query: %s %s from %s", dns.Type(q.Qtype).String(), q.Name, clientAddr.String()) + + ctx, cancel := context.WithTimeout(l.ctx, time.Duration(l.config.Timeout)*time.Second) + defer cancel() + + resp, err := l.handler.HandleQuery(ctx, query) + if err != nil { + log.Printf("[dns] error handling query %s %s: %v", dns.Type(q.Qtype).String(), q.Name, err) + m := new(dns.Msg) + m.SetReply(msg) + m.Rcode = dns.RcodeServerFailure + _ = w.WriteMsg(m) + return + } + + m := new(dns.Msg) + m.SetReply(msg) + + if resp != nil && resp.RawMsg != nil { + m = resp.RawMsg + m.SetReply(msg) + } else if resp != nil { + m.Rcode = resp.Rcode + m.Answer = resp.Answer + m.Ns = resp.Authority + m.Extra = resp.Additional + } + + if err := w.WriteMsg(m); err != nil { + log.Printf("[dns] error writing response to %s: %v", clientAddr, err) + } +} + +// Healthy returns true if all listeners are active. +func (l *DnsListener) Healthy() bool { + if len(l.servers) == 0 { + return false + } + select { + case <-l.ctx.Done(): + return false + default: + return true + } +} diff --git a/core/dns/metrics.go b/core/dns/metrics.go new file mode 100644 index 00000000..6dce7ed9 --- /dev/null +++ b/core/dns/metrics.go @@ -0,0 +1,392 @@ +package dns + +import ( + "fmt" + "strings" + "sync" + "sync/atomic" + "time" +) + +// DnsMetrics DNS 模块指标收集器 +// 使用 atomic 操作和 sync.Map 确保并发安全 +type DnsMetrics struct { + // 查询总量 + TotalQueries atomic.Int64 + TotalResponses atomic.Int64 + TotalErrors atomic.Int64 + TotalTimeouts atomic.Int64 + + // 按记录类型统计 + QueriesByType sync.Map // map[QueryType]int64 + + // 按上游统计 + QueriesByUpstream sync.Map // map[string]*UpstreamMetrics + ErrorsByUpstream sync.Map // map[string]int64 + + // 按规则统计 + HitsByRule sync.Map // map[string]int64 — ruleID → 命中次数 + + // 缓存统计 + CacheHits atomic.Int64 + CacheMisses atomic.Int64 + CacheEvictions atomic.Int64 + PrefetchCount atomic.Int64 + + // 延迟分布 + LatencyBuckets []LatencyBucket + + // Action 统计 + RoutedQueries atomic.Int64 + RejectedQueries atomic.Int64 + BypassedQueries atomic.Int64 + + mu sync.Mutex + startedAt time.Time +} + +// UpstreamMetrics 上游服务器的详细指标 +type UpstreamMetrics struct { + Queries int64 + Successes int64 + Errors int64 + AvgRTT time.Duration + MinRTT time.Duration + MaxRTT time.Duration + LastQuery time.Time + mu sync.Mutex +} + +// LatencyBucket 延迟分布区间 +type LatencyBucket struct { + Label string // "<1ms", "1-5ms", "5-10ms", "10-50ms", "50-200ms", "200ms+" + Count int64 +} + +// MetricsSnapshot 指标快照,用于一次性读取所有指标 +type MetricsSnapshot struct { + TotalQueries int64 + TotalResponses int64 + TotalErrors int64 + TotalTimeouts int64 + QueriesByType map[string]int64 + QueriesByUpstream map[string]*UpstreamMetrics + ErrorsByUpstream map[string]int64 + HitsByRule map[string]int64 + CacheHits int64 + CacheMisses int64 + CacheEvictions int64 + PrefetchCount int64 + LatencyBuckets []LatencyBucket + RoutedQueries int64 + RejectedQueries int64 + BypassedQueries int64 + Uptime string +} + +// NewDnsMetrics 创建新的指标收集器 +func NewDnsMetrics() *DnsMetrics { + return &DnsMetrics{ + startedAt: time.Now(), + LatencyBuckets: []LatencyBucket{ + {Label: "<1ms", Count: 0}, + {Label: "1-5ms", Count: 0}, + {Label: "5-10ms", Count: 0}, + {Label: "10-50ms", Count: 0}, + {Label: "50-200ms", Count: 0}, + {Label: "200ms+", Count: 0}, + }, + } +} + +// getOrCreateUpstreamMetrics 获取或创建上游指标 +func (m *DnsMetrics) getOrCreateUpstreamMetrics(upstream string) *UpstreamMetrics { + actual, _ := m.QueriesByUpstream.LoadOrStore(upstream, &UpstreamMetrics{ + MinRTT: time.Duration(1<<63 - 1), // MaxInt64 作为初始值 + }) + return actual.(*UpstreamMetrics) +} + +// getOrInitCounter 获取或初始化一个 atomic.Int64 计数器 +func getOrInitCounter(m *sync.Map, key interface{}) *atomic.Int64 { + v, _ := m.LoadOrStore(key, &atomic.Int64{}) + return v.(*atomic.Int64) +} + +// RecordQuery 记录一次查询 +func (m *DnsMetrics) RecordQuery(query *DnsQuery, upstream string) { + m.TotalQueries.Add(1) + + // 按类型统计(使用 atomic.Int64 指针避免竞态) + counter := getOrInitCounter(&m.QueriesByType, query.QType) + counter.Add(1) + + // 按上游统计 + if upstream != "" { + um := m.getOrCreateUpstreamMetrics(upstream) + um.mu.Lock() + um.Queries++ + um.LastQuery = time.Now() + um.mu.Unlock() + } +} + +// RecordResponse 记录一次响应 +func (m *DnsMetrics) RecordResponse(resp *DnsResponse, rtt time.Duration) { + m.TotalResponses.Add(1) + + // 记录延迟分布 + m.recordLatency(rtt) + + // 按上游记录 RTT + upstream := resp.Upstream + if upstream != "" { + um := m.getOrCreateUpstreamMetrics(upstream) + um.mu.Lock() + um.Successes++ + if rtt > 0 { + // 更新平均 RTT(指数移动平均) + if um.AvgRTT == 0 { + um.AvgRTT = rtt + } else { + um.AvgRTT = (um.AvgRTT*2 + rtt) / 3 + } + // 更新最小 RTT + if rtt < um.MinRTT { + um.MinRTT = rtt + } + // 更新最大 RTT + if rtt > um.MaxRTT { + um.MaxRTT = rtt + } + } + um.mu.Unlock() + } +} + +// RecordError 记录一次错误 +func (m *DnsMetrics) RecordError(upstream string, err error) { + m.TotalErrors.Add(1) + + if upstream != "" { + // 按上游统计错误(使用 atomic.Int64 指针) + counter := getOrInitCounter(&m.ErrorsByUpstream, upstream) + counter.Add(1) + + um := m.getOrCreateUpstreamMetrics(upstream) + um.mu.Lock() + um.Errors++ + um.mu.Unlock() + } +} + +// RecordTimeout 记录一次超时 +func (m *DnsMetrics) RecordTimeout(upstream string) { + m.TotalTimeouts.Add(1) + m.RecordError(upstream, fmt.Errorf("timeout")) +} + +// RecordCacheHit 记录缓存命中 +func (m *DnsMetrics) RecordCacheHit() { + m.CacheHits.Add(1) +} + +// RecordCacheMiss 记录缓存未命中 +func (m *DnsMetrics) RecordCacheMiss() { + m.CacheMisses.Add(1) +} + +// RecordCacheEviction 记录缓存淘汰 +func (m *DnsMetrics) RecordCacheEviction() { + m.CacheEvictions.Add(1) +} + +// RecordPrefetch 记录预取 +func (m *DnsMetrics) RecordPrefetch() { + m.PrefetchCount.Add(1) +} + +// RecordRuleHit 记录规则命中 +func (m *DnsMetrics) RecordRuleHit(ruleID string) { + if ruleID == "" { + return + } + counter := getOrInitCounter(&m.HitsByRule, ruleID) + counter.Add(1) +} + +// RecordAction 记录分流动作 +func (m *DnsMetrics) RecordAction(action string) { + switch action { + case "route": + m.RoutedQueries.Add(1) + case "reject": + m.RejectedQueries.Add(1) + case "bypass": + m.BypassedQueries.Add(1) + } +} + +// recordLatency 记录延迟到对应区间 +func (m *DnsMetrics) recordLatency(rtt time.Duration) { + m.mu.Lock() + defer m.mu.Unlock() + + ms := rtt.Milliseconds() + switch { + case ms < 1: + m.LatencyBuckets[0].Count++ + case ms <= 5: + m.LatencyBuckets[1].Count++ + case ms <= 10: + m.LatencyBuckets[2].Count++ + case ms <= 50: + m.LatencyBuckets[3].Count++ + case ms <= 200: + m.LatencyBuckets[4].Count++ + default: + m.LatencyBuckets[5].Count++ + } +} + +// Snapshot 返回当前指标的原子快照 +func (m *DnsMetrics) Snapshot() *MetricsSnapshot { + s := &MetricsSnapshot{ + TotalQueries: m.TotalQueries.Load(), + TotalResponses: m.TotalResponses.Load(), + TotalErrors: m.TotalErrors.Load(), + TotalTimeouts: m.TotalTimeouts.Load(), + CacheHits: m.CacheHits.Load(), + CacheMisses: m.CacheMisses.Load(), + CacheEvictions: m.CacheEvictions.Load(), + PrefetchCount: m.PrefetchCount.Load(), + RoutedQueries: m.RoutedQueries.Load(), + RejectedQueries: m.RejectedQueries.Load(), + BypassedQueries: m.BypassedQueries.Load(), + Uptime: time.Since(m.startedAt).Round(time.Second).String(), + QueriesByType: make(map[string]int64), + QueriesByUpstream: make(map[string]*UpstreamMetrics), + ErrorsByUpstream: make(map[string]int64), + HitsByRule: make(map[string]int64), + } + + // 拷贝按类型统计(atomic.Int64 指针) + m.QueriesByType.Range(func(key, val interface{}) bool { + qt := key.(QueryType) + counter := val.(*atomic.Int64) + s.QueriesByType[QTypeToString(qt)] = counter.Load() + return true + }) + + // 拷贝按上游统计(使用指针避免复制 sync.Mutex) + m.QueriesByUpstream.Range(func(key, val interface{}) bool { + upstream := key.(string) + um := val.(*UpstreamMetrics) + s.QueriesByUpstream[upstream] = um + return true + }) + + // 拷贝按上游错误统计(atomic.Int64 指针) + m.ErrorsByUpstream.Range(func(key, val interface{}) bool { + counter := val.(*atomic.Int64) + s.ErrorsByUpstream[key.(string)] = counter.Load() + return true + }) + + // 拷贝按规则命中统计(atomic.Int64 指针) + m.HitsByRule.Range(func(key, val interface{}) bool { + counter := val.(*atomic.Int64) + s.HitsByRule[key.(string)] = counter.Load() + return true + }) + + // 拷贝延迟分布 + m.mu.Lock() + s.LatencyBuckets = make([]LatencyBucket, len(m.LatencyBuckets)) + copy(s.LatencyBuckets, m.LatencyBuckets) + m.mu.Unlock() + + return s +} + +// Reset 重置所有指标 +func (m *DnsMetrics) Reset() { + m.TotalQueries.Store(0) + m.TotalResponses.Store(0) + m.TotalErrors.Store(0) + m.TotalTimeouts.Store(0) + m.CacheHits.Store(0) + m.CacheMisses.Store(0) + m.CacheEvictions.Store(0) + m.PrefetchCount.Store(0) + m.RoutedQueries.Store(0) + m.RejectedQueries.Store(0) + m.BypassedQueries.Store(0) + + m.QueriesByType.Range(func(key, _ interface{}) bool { + m.QueriesByType.Delete(key) + return true + }) + m.QueriesByUpstream.Range(func(key, _ interface{}) bool { + m.QueriesByUpstream.Delete(key) + return true + }) + m.ErrorsByUpstream.Range(func(key, _ interface{}) bool { + m.ErrorsByUpstream.Delete(key) + return true + }) + m.HitsByRule.Range(func(key, _ interface{}) bool { + m.HitsByRule.Delete(key) + return true + }) + + m.mu.Lock() + for i := range m.LatencyBuckets { + m.LatencyBuckets[i].Count = 0 + } + m.mu.Unlock() + + m.startedAt = time.Now() +} + +// String 返回人类可读的指标概要 +func (m *DnsMetrics) String() string { + s := m.Snapshot() + var b strings.Builder + b.WriteString(fmt.Sprintf("📊 DNS Metrics (uptime: %s)\n", s.Uptime)) + b.WriteString(fmt.Sprintf(" Queries: %d total, %d responses, %d errors, %d timeouts\n", + s.TotalQueries, s.TotalResponses, s.TotalErrors, s.TotalTimeouts)) + b.WriteString(fmt.Sprintf(" Cache: %d hits, %d misses, %d evictions, %d prefetches\n", + s.CacheHits, s.CacheMisses, s.CacheEvictions, s.PrefetchCount)) + b.WriteString(fmt.Sprintf(" Actions: %d routed, %d rejected, %d bypassed\n", + s.RoutedQueries, s.RejectedQueries, s.BypassedQueries)) + + if len(s.QueriesByType) > 0 { + b.WriteString(" By Type:\n") + for qt, count := range s.QueriesByType { + b.WriteString(fmt.Sprintf(" %s: %d\n", qt, count)) + } + } + if len(s.QueriesByUpstream) > 0 { + b.WriteString(" By Upstream:\n") + for upstream, um := range s.QueriesByUpstream { + b.WriteString(fmt.Sprintf(" %s: queries=%d successes=%d errors=%d avgRTT=%s\n", + upstream, um.Queries, um.Successes, um.Errors, um.AvgRTT)) + } + } + if len(s.HitsByRule) > 0 { + b.WriteString(" Rule Hits:\n") + for ruleID, count := range s.HitsByRule { + b.WriteString(fmt.Sprintf(" %s: %d\n", ruleID, count)) + } + } + if len(s.LatencyBuckets) > 0 { + b.WriteString(" Latency Distribution:\n") + for _, lb := range s.LatencyBuckets { + if lb.Count > 0 { + b.WriteString(fmt.Sprintf(" %s: %d\n", lb.Label, lb.Count)) + } + } + } + return b.String() +} diff --git a/core/dns/metrics_test.go b/core/dns/metrics_test.go new file mode 100644 index 00000000..a3a329ff --- /dev/null +++ b/core/dns/metrics_test.go @@ -0,0 +1,487 @@ +package dns + +import ( + "sync" + "testing" + "time" + + "github.com/miekg/dns" +) + +// Helper: create a basic DnsQuery for testing. +func testQuery(name string, qtype QueryType) *DnsQuery { + return &DnsQuery{ + Name: name, + QType: qtype, + QClass: dns.ClassINET, + } +} + +// Helper: create a basic DnsResponse for testing. +func testResponse(query *DnsQuery, rtt time.Duration, upstream string) *DnsResponse { + return &DnsResponse{ + Query: *query, + Rcode: dns.RcodeSuccess, + Upstream: upstream, + ProxyTag: "direct", + RTT: rtt, + Cached: false, + TTL: 300, + } +} + +// TestNewDnsMetrics verifies that NewDnsMetrics initializes correctly. +func TestNewDnsMetrics(t *testing.T) { + m := NewDnsMetrics() + if m == nil { + t.Fatal("NewDnsMetrics() returned nil") + } + + // Verify latency buckets are initialized. + if len(m.LatencyBuckets) != 6 { + t.Fatalf("expected 6 latency buckets, got %d", len(m.LatencyBuckets)) + } + + // Verify all counters start at zero. + snap := m.Snapshot() + if snap.TotalQueries != 0 || snap.TotalResponses != 0 || snap.TotalErrors != 0 { + t.Fatal("expected all counters to be zero") + } +} + +// TestRecordQueryAndResponse tests basic query and response recording. +func TestRecordQueryAndResponse(t *testing.T) { + m := NewDnsMetrics() + + // Record a query. + q := testQuery("example.com", TypeA) + m.RecordQuery(q, "upstream-1") + + // Record a response. + resp := testResponse(q, 10*time.Millisecond, "upstream-1") + m.RecordResponse(resp, 10*time.Millisecond) + + // Snapshot and verify. + snap := m.Snapshot() + if snap.TotalQueries != 1 { + t.Errorf("expected 1 query, got %d", snap.TotalQueries) + } + if snap.TotalResponses != 1 { + t.Errorf("expected 1 response, got %d", snap.TotalResponses) + } + + // Verify query type breakdown. + if snap.QueriesByType["A"] != 1 { + t.Errorf("expected 1 A query, got %d", snap.QueriesByType["A"]) + } + + // Verify upstream stats. + um, ok := snap.QueriesByUpstream["upstream-1"] + if !ok { + t.Fatal("expected upstream-1 stats") + } + if um.Queries != 1 { + t.Errorf("expected 1 query for upstream-1, got %d", um.Queries) + } + if um.Successes != 1 { + t.Errorf("expected 1 success for upstream-1, got %d", um.Successes) + } + if um.AvgRTT != 10*time.Millisecond { + t.Errorf("expected AvgRTT=10ms, got %v", um.AvgRTT) + } +} + +// TestCacheHitMiss tests cache hit/miss counting. +func TestCacheHitMiss(t *testing.T) { + m := NewDnsMetrics() + + m.RecordCacheHit() + m.RecordCacheHit() + m.RecordCacheHit() + m.RecordCacheMiss() + + snap := m.Snapshot() + if snap.CacheHits != 3 { + t.Errorf("expected 3 cache hits, got %d", snap.CacheHits) + } + if snap.CacheMisses != 1 { + t.Errorf("expected 1 cache miss, got %d", snap.CacheMisses) + } +} + +// TestCacheEvictionAndPrefetch tests eviction and prefetch counting. +func TestCacheEvictionAndPrefetch(t *testing.T) { + m := NewDnsMetrics() + + m.RecordCacheEviction() + m.RecordCacheEviction() + m.RecordCacheEviction() + m.RecordPrefetch() + + snap := m.Snapshot() + if snap.CacheEvictions != 3 { + t.Errorf("expected 3 evictions, got %d", snap.CacheEvictions) + } + if snap.PrefetchCount != 1 { + t.Errorf("expected 1 prefetch, got %d", snap.PrefetchCount) + } +} + +// TestUpstreamStats tests per-upstream statistics including RTT tracking. +func TestUpstreamStats(t *testing.T) { + m := NewDnsMetrics() + + upstream := "8.8.8.8:53" + + // Record queries. + for i := 0; i < 5; i++ { + q := testQuery("test.com", TypeA) + m.RecordQuery(q, upstream) + } + + // Record responses with different RTTs. + rtts := []time.Duration{5, 10, 15, 20, 25} + for _, rtt := range rtts { + q := testQuery("test.com", TypeA) + resp := testResponse(q, rtt*time.Millisecond, upstream) + m.RecordResponse(resp, rtt*time.Millisecond) + } + + // Also record some errors. + m.RecordError(upstream, dns.ErrRcode) + m.RecordError(upstream, dns.ErrRcode) + + snap := m.Snapshot() + + // Verify upstream stats. + um, ok := snap.QueriesByUpstream[upstream] + if !ok { + t.Fatal("expected upstream stats") + } + if um.Queries != 5 { + t.Errorf("expected 5 queries, got %d", um.Queries) + } + if um.Successes != 5 { + t.Errorf("expected 5 successes, got %d", um.Successes) + } + if um.Errors != 2 { + t.Errorf("expected 2 errors, got %d", um.Errors) + } + if um.AvgRTT == 0 { + t.Error("expected non-zero AvgRTT") + } + if um.MinRTT != 5*time.Millisecond { + t.Errorf("expected MinRTT=5ms, got %v", um.MinRTT) + } + if um.MaxRTT != 25*time.Millisecond { + t.Errorf("expected MaxRTT=25ms, got %v", um.MaxRTT) + } + + // Verify errors by upstream. + if snap.ErrorsByUpstream[upstream] != 2 { + t.Errorf("expected 2 errors for upstream, got %d", snap.ErrorsByUpstream[upstream]) + } +} + +// TestLatencyDistribution tests latency bucket recording. +func TestLatencyDistribution(t *testing.T) { + m := NewDnsMetrics() + + // Record responses with various latencies. + rtts := []time.Duration{ + 500 * time.Microsecond, // <1ms + 3 * time.Millisecond, // 1-5ms + 7 * time.Millisecond, // 5-10ms + 30 * time.Millisecond, // 10-50ms + 100 * time.Millisecond, // 50-200ms + 500 * time.Millisecond, // 200ms+ + } + + upstream := "latency-upstream" + for _, rtt := range rtts { + q := testQuery("test.com", TypeA) + resp := testResponse(q, rtt, upstream) + m.RecordResponse(resp, rtt) + } + + snap := m.Snapshot() + if len(snap.LatencyBuckets) != 6 { + t.Fatalf("expected 6 latency buckets, got %d", len(snap.LatencyBuckets)) + } + + // Verify each bucket has exactly 1 entry. + expected := map[string]int64{ + "<1ms": 1, + "1-5ms": 1, + "5-10ms": 1, + "10-50ms": 1, + "50-200ms": 1, + "200ms+": 1, + } + for _, lb := range snap.LatencyBuckets { + expect, ok := expected[lb.Label] + if !ok { + t.Errorf("unexpected bucket label: %s", lb.Label) + continue + } + if lb.Count != expect { + t.Errorf("bucket %s: expected %d, got %d", lb.Label, expect, lb.Count) + } + } +} + +// TestRuleHit tests rule hit counting. +func TestRuleHit(t *testing.T) { + m := NewDnsMetrics() + + m.RecordRuleHit("rule-1") + m.RecordRuleHit("rule-1") + m.RecordRuleHit("rule-2") + m.RecordRuleHit("") // Should be ignored. + + snap := m.Snapshot() + if snap.HitsByRule["rule-1"] != 2 { + t.Errorf("expected 2 hits for rule-1, got %d", snap.HitsByRule["rule-1"]) + } + if snap.HitsByRule["rule-2"] != 1 { + t.Errorf("expected 1 hit for rule-2, got %d", snap.HitsByRule["rule-2"]) + } + if len(snap.HitsByRule) != 2 { + t.Errorf("expected 2 rules in map, got %d", len(snap.HitsByRule)) + } +} + +// TestActionRouting tests action routing counting. +func TestActionRouting(t *testing.T) { + m := NewDnsMetrics() + + m.RecordAction("route") + m.RecordAction("route") + m.RecordAction("reject") + m.RecordAction("bypass") + m.RecordAction("bypass") + m.RecordAction("bypass") + + snap := m.Snapshot() + if snap.RoutedQueries != 2 { + t.Errorf("expected 2 routed, got %d", snap.RoutedQueries) + } + if snap.RejectedQueries != 1 { + t.Errorf("expected 1 rejected, got %d", snap.RejectedQueries) + } + if snap.BypassedQueries != 3 { + t.Errorf("expected 3 bypassed, got %d", snap.BypassedQueries) + } +} + +// TestConcurrentSafety tests that metrics are safe for concurrent access. +func TestConcurrentSafety(t *testing.T) { + m := NewDnsMetrics() + + var wg sync.WaitGroup + n := 100 + + // Concurrently record queries from multiple goroutines. + for i := 0; i < n; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + q := testQuery("concurrent.test", TypeA) + m.RecordQuery(q, "upstream-concurrent") + m.RecordCacheHit() + m.RecordAction("route") + m.RecordRuleHit("rule-concurrent") + }(i) + } + + wg.Wait() + + snap := m.Snapshot() + if snap.TotalQueries != int64(n) { + t.Errorf("expected %d queries, got %d", n, snap.TotalQueries) + } + if snap.CacheHits != int64(n) { + t.Errorf("expected %d cache hits, got %d", n, snap.CacheHits) + } + if snap.RoutedQueries != int64(n) { + t.Errorf("expected %d routed, got %d", n, snap.RoutedQueries) + } + if snap.HitsByRule["rule-concurrent"] != int64(n) { + t.Errorf("expected %d rule hits, got %d", n, snap.HitsByRule["rule-concurrent"]) + } +} + +// TestSnapshotConsistency tests that Snapshot returns consistent data. +func TestSnapshotConsistency(t *testing.T) { + m := NewDnsMetrics() + + // Record some data. + q := testQuery("snapshot.test", TypeAAAA) + m.RecordQuery(q, "upstream-snap") + resp := testResponse(q, 50*time.Millisecond, "upstream-snap") + m.RecordResponse(resp, 50*time.Millisecond) + m.RecordError("upstream-snap", dns.ErrRcode) + m.RecordCacheHit() + m.RecordCacheMiss() + m.RecordRuleHit("rule-snap") + m.RecordAction("route") + + // Take snapshot. + snap := m.Snapshot() + + // Verify total consistency. + if snap.TotalQueries != snap.QueriesByUpstream["upstream-snap"].Queries { + t.Errorf("total queries (%d) != upstream queries (%d)", + snap.TotalQueries, snap.QueriesByUpstream["upstream-snap"].Queries) + } + if snap.TotalErrors != snap.ErrorsByUpstream["upstream-snap"] { + t.Errorf("total errors (%d) != upstream errors (%d)", + snap.TotalErrors, snap.ErrorsByUpstream["upstream-snap"]) + } + + // Verify query type exists. + if snap.QueriesByType["AAAA"] != 1 { + t.Errorf("expected 1 AAAA query, got %d", snap.QueriesByType["AAAA"]) + } +} + +// TestReset tests that Reset clears all metrics. +func TestReset(t *testing.T) { + m := NewDnsMetrics() + + // Record some data. + q := testQuery("reset.test", TypeA) + m.RecordQuery(q, "upstream-reset") + resp := testResponse(q, 10*time.Millisecond, "upstream-reset") + m.RecordResponse(resp, 10*time.Millisecond) + m.RecordCacheHit() + m.RecordCacheMiss() + m.RecordError("upstream-reset", dns.ErrRcode) + m.RecordRuleHit("rule-reset") + m.RecordAction("route") + + // Reset. + m.Reset() + + // Verify all counters are zero. + snap := m.Snapshot() + if snap.TotalQueries != 0 { + t.Errorf("expected 0 queries after reset, got %d", snap.TotalQueries) + } + if snap.TotalResponses != 0 { + t.Errorf("expected 0 responses after reset, got %d", snap.TotalResponses) + } + if snap.TotalErrors != 0 { + t.Errorf("expected 0 errors after reset, got %d", snap.TotalErrors) + } + if snap.CacheHits != 0 { + t.Errorf("expected 0 cache hits after reset, got %d", snap.CacheHits) + } + if snap.CacheMisses != 0 { + t.Errorf("expected 0 cache misses after reset, got %d", snap.CacheMisses) + } + if snap.RoutedQueries != 0 { + t.Errorf("expected 0 routed after reset, got %d", snap.RoutedQueries) + } + if len(snap.QueriesByUpstream) != 0 { + t.Errorf("expected empty upstream map after reset, got %d entries", len(snap.QueriesByUpstream)) + } + if len(snap.HitsByRule) != 0 { + t.Errorf("expected empty rule hits after reset, got %d entries", len(snap.HitsByRule)) + } +} + +// TestTimeoutRecording tests timeout recording. +func TestTimeoutRecording(t *testing.T) { + m := NewDnsMetrics() + + m.RecordTimeout("upstream-timeout") + m.RecordTimeout("upstream-timeout") + + snap := m.Snapshot() + if snap.TotalTimeouts != 2 { + t.Errorf("expected 2 timeouts, got %d", snap.TotalTimeouts) + } + if snap.TotalErrors != 2 { + t.Errorf("expected 2 errors (timeout counted as error), got %d", snap.TotalErrors) + } +} + +// TestMultipleQTypes tests recording of multiple query types. +func TestMultipleQTypes(t *testing.T) { + m := NewDnsMetrics() + + upstream := "upstream-multi" + types := []QueryType{TypeA, TypeAAAA, TypeCNAME, TypeTXT, TypeMX} + for i, qt := range types { + q := testQuery("multi.test", qt) + m.RecordQuery(q, upstream) + + resp := testResponse(q, time.Duration(i+1)*time.Millisecond, upstream) + m.RecordResponse(resp, time.Duration(i+1)*time.Millisecond) + } + + snap := m.Snapshot() + if len(snap.QueriesByType) != 5 { + t.Errorf("expected 5 query types, got %d", len(snap.QueriesByType)) + } + for _, qt := range types { + name := QTypeToString(qt) + if snap.QueriesByType[name] != 1 { + t.Errorf("expected 1 query of type %s, got %d", name, snap.QueriesByType[name]) + } + } +} + +// TestUpstreamMetricsConcurrent tests concurrent access to upstream metrics. +func TestUpstreamMetricsConcurrent(t *testing.T) { + m := NewDnsMetrics() + + var wg sync.WaitGroup + n := 50 + + for i := 0; i < n; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + upstream := "concurrent-upstream" + q := testQuery("concurrent.test", TypeA) + m.RecordQuery(q, upstream) + resp := testResponse(q, time.Duration(i)*time.Millisecond, upstream) + m.RecordResponse(resp, time.Duration(i)*time.Millisecond) + }(i) + } + + wg.Wait() + + snap := m.Snapshot() + um, ok := snap.QueriesByUpstream["concurrent-upstream"] + if !ok { + t.Fatal("expected upstream metrics") + } + if um.Queries != int64(n) { + t.Errorf("expected %d queries, got %d", n, um.Queries) + } + if um.Successes != int64(n) { + t.Errorf("expected %d successes, got %d", n, um.Successes) + } +} + +// TestUptimeAfterReset tests that uptime is reset after Reset. +func TestUptimeAfterReset(t *testing.T) { + m := NewDnsMetrics() + + // Sleep enough for Round(time.Second) to show a difference. + time.Sleep(1100 * time.Millisecond) + + snap1 := m.Snapshot() + t.Logf("Uptime before reset: %s", snap1.Uptime) + + m.Reset() + + snap2 := m.Snapshot() + if snap2.Uptime == snap1.Uptime { + t.Error("expected uptime to change after reset") + } + t.Logf("Uptime after reset: %s", snap2.Uptime) +} diff --git a/core/dns/module.go b/core/dns/module.go new file mode 100644 index 00000000..1021eaa7 --- /dev/null +++ b/core/dns/module.go @@ -0,0 +1,507 @@ +package dns + +import ( + "context" + "fmt" + "log" + "net" + "net/netip" + "sync" + "time" + + "github.com/miekg/dns" +) + +// DnsModule is the top-level lifecycle manager for the DNS module. +// It coordinates the listener, router, upstream manager, cache, and statistics. +type DnsModule struct { + config *DnsModuleConfig + listener *DnsListener + handler *DnsHandler + router *Router + upstreamMgr *UpstreamManager + cache *DnsCache // DNS 缓存模块(LRU + TTL 双淘汰) + stats DnsStats + metrics *DnsMetrics // 指标收集器(新增) + diagnostics *Diagnostics // 诊断模块(新增) + dispatcher RouteDispatcher // xray-core 内部路由调度器(Start 前设置) + mu sync.RWMutex + ctx context.Context + cancel context.CancelFunc + wg sync.WaitGroup + healthy bool +} + +// NewDnsModule creates a new DnsModule with the given configuration. +func NewDnsModule(config *DnsModuleConfig) *DnsModule { + if config == nil { + config = DefaultDnsModuleConfig() + } + return &DnsModule{ + config: config, + stats: DnsStats{ + RoutedQueries: make(map[string]int64), + StartedAt: time.Now(), + }, + metrics: NewDnsMetrics(), + diagnostics: nil, // 在 Start 中创建,因为需要引用 module 自身 + } +} + +// Start initializes and starts all DNS module components. +// It validates the configuration, creates the handler, router, upstream manager, +// and listener, and begins serving DNS queries on the configured address. +func (m *DnsModule) Start() error { + m.mu.Lock() + defer m.mu.Unlock() + + if m.healthy { + return fmt.Errorf("dns module: already started") + } + + if err := m.config.Validate(); err != nil { + return fmt.Errorf("dns module: invalid config: %w", err) + } + + m.ctx, m.cancel = context.WithCancel(context.Background()) + + // Initialize diagnostics (requires module reference). + m.diagnostics = NewDiagnostics(m) + + // Initialize statistics. + m.stats = DnsStats{ + RoutedQueries: make(map[string]int64), + StartedAt: time.Now(), + } + + // Reset metrics (fresh start). + m.metrics.Reset() + + // 解析 bootstrap domain — 当 DNS 上游地址是域名时,用系统 DNS 解析出 IP。 + // 避免 DNS 模块自身依赖 DNS 的循环依赖。 + if len(m.config.Bootstrap) > 0 { + log.Printf("[dns module] bootstrap: %d domains to resolve: %v", len(m.config.Bootstrap), m.config.Bootstrap) + resolved := m.resolveBootstrap(m.config.Bootstrap) + log.Printf("[dns module] bootstrap: resolved %d/%d domains", len(resolved), len(m.config.Bootstrap)) + for domain, ip := range resolved { + log.Printf("[dns module] bootstrap: %s → %s", domain, ip) + } + for i, upstream := range m.config.Upstreams { + if upstream.Bootstrap { + continue + } + before := upstream.Addr + // 从上游地址中提取主机名 + host, port, err := net.SplitHostPort(upstream.Addr) + if err != nil { + // 格式不符合 host:port,尝试直接匹配 + if ip, ok := resolved[upstream.Addr]; ok { + m.config.Upstreams[i].Addr = ip + ":53" + log.Printf("[dns module] bootstrap: upstream %s → %s (was %s)", upstream.ID, m.config.Upstreams[i].Addr, before) + } else { + log.Printf("[dns module] bootstrap: upstream %s addr=%s not resolved, keeping as-is", upstream.ID, upstream.Addr) + } + continue + } + if net.ParseIP(host) == nil { + if ip, ok := resolved[host]; ok { + m.config.Upstreams[i].Addr = net.JoinHostPort(ip, port) + log.Printf("[dns module] bootstrap: upstream %s → %s (was %s)", upstream.ID, m.config.Upstreams[i].Addr, before) + } else { + log.Printf("[dns module] bootstrap: upstream %s host=%s not resolved, keeping as-is", upstream.ID, host) + } + } + } + } else { + log.Printf("[dns module] bootstrap: no domains to resolve (list is empty)") + } + + // 为所有缺失端口的上游地址补充默认端口 + for i, upstream := range m.config.Upstreams { + if _, _, err := net.SplitHostPort(upstream.Addr); err != nil { + // 没有端口号,根据协议补充 + port := "53" + switch upstream.Protocol { + case "tcp-tls", "tls": + port = "853" + } + m.config.Upstreams[i].Addr = net.JoinHostPort(upstream.Addr, port) + log.Printf("[dns module] added default port %s to upstream %s (protocol=%s)", port, upstream.Addr, upstream.Protocol) + } + } + + // 打印最终上游列表 + log.Printf("[dns module] upstream list after bootstrap:") + for _, u := range m.config.Upstreams { + log.Printf("[dns module] id=%s addr=%s protocol=%s proxy_tag=%s", u.ID, u.Addr, u.Protocol, u.ProxyTag) + } + + // Create the UpstreamManager. + m.upstreamMgr = NewUpstreamManager(m.config.Upstreams) + + // Set xray-core internal dispatcher (if configured before Start). + if m.dispatcher != nil { + m.upstreamMgr.SetDispatcher(m.dispatcher) + } + + // Set proxy address resolver from ProxyMap (if configured). + if len(m.config.ProxyMap) > 0 { + proxyMap := m.config.ProxyMap + m.upstreamMgr.SetProxyAddrResolver(func(proxyTag string) string { + if addr, ok := proxyMap[proxyTag]; ok { + return addr + } + return "" + }) + } + + // Initialize cache if enabled. + if m.config.Cache.Enabled { + m.cache = NewDnsCache(&m.config.Cache) + log.Printf("[dns module] cache initialized: size=%d, minTTL=%d, maxTTL=%d, prefetch=%v", + m.config.Cache.Size, m.config.Cache.MinTTL, m.config.Cache.MaxTTL, m.config.Cache.Prefetch) + } else { + m.cache = nil + log.Printf("[dns module] cache disabled") + } + + // Build rules from config. + rules := make([]*DnsRule, len(m.config.Rules)) + for i, rc := range m.config.Rules { + rules[i] = &DnsRule{ + ID: rc.ID, + Domain: rc.Domain, + DomainSuffix: rc.DomainSuffix, + DomainRegex: rc.DomainRegex, + IP: rc.IP, + QueryType: rc.QueryType, + ClientIP: rc.ClientIP, + Upstream: rc.Upstream, + Action: rc.Action, + Policy: rc.Policy, + } + } + + // Determine default upstream: the LAST non-bootstrap upstream. + // Convention: the first upstreams have domain-specific rules, + // and the LAST upstream (with empty domain) is the fallback. + defaultUpstream := "" + for _, u := range m.config.Upstreams { + if !u.Bootstrap { + defaultUpstream = u.ID + if defaultUpstream == "" { + defaultUpstream = u.Addr + } + // Continue iterating — the LAST non-bootstrap upstream wins. + } + } + if defaultUpstream == "" && len(m.config.Upstreams) > 0 { + u := m.config.Upstreams[len(m.config.Upstreams)-1] + defaultUpstream = u.ID + if defaultUpstream == "" { + defaultUpstream = u.Addr + } + } + + // Create the Router. + router, err := NewRouter(rules, m.config.Upstreams, defaultUpstream) + if err != nil { + m.cancel() + return fmt.Errorf("dns module: failed to create router: %w", err) + } + m.router = router + + // Create the DNS handler with the configured timeout. + timeout := time.Duration(m.config.Listener.Timeout) * time.Second + m.handler = NewDnsHandler(timeout, m) + + // Create the DNS listener. + m.listener = NewDnsListener(&m.config.Listener, m.handler) + + // Start the listener. + log.Printf("[dns module] starting DNS listener on %s", m.config.Listener.ListenAddr) + if err := m.listener.Start(); err != nil { + m.cancel() + return fmt.Errorf("dns module: failed to start listener: %w", err) + } + + m.healthy = true + log.Printf("[dns module] started successfully: %s", m.config.String()) + return nil +} + +// resolveBootstrap resolves a list of domain names using the system DNS. +// Returns a map of domain → first resolved IP address. +// This breaks the circular dependency: DNS upstream addresses that are domain names +// need DNS resolution themselves, so we use the system resolver (/etc/resolv.conf). +func (m *DnsModule) resolveBootstrap(domains []string) map[string]string { + resolved := make(map[string]string, len(domains)) + if len(domains) == 0 { + return resolved + } + + // 优先使用配置中保存的系统 DNS(在劫持发生前由 v2rayA 读取并写入配置)。 + // 回退到直接从 /etc/resolv.conf 读取(劫持可能已生效)。 + var sysServers []netip.AddrPort + if len(m.config.BootstrapDns) > 0 { + for _, s := range m.config.BootstrapDns { + if ap, err := netip.ParseAddrPort(s); err == nil { + sysServers = append(sysServers, ap) + } + } + } + if len(sysServers) == 0 { + sysServers = GetSystemDNS() + } + if len(sysServers) == 0 { + log.Printf("[dns module] warning: no system DNS available for bootstrap resolution") + return resolved + } + + log.Printf("[dns module] resolving %d bootstrap domains using system DNS", len(domains)) + for _, s := range sysServers { + log.Printf("[dns module] system DNS: %s", s.String()) + } + + for _, domain := range domains { + if domain == "" { + continue + } + if net.ParseIP(domain) != nil { + resolved[domain] = domain + continue + } + // 对每个系统 DNS 服务器尝试解析 + for _, srv := range sysServers { + addr := srv.String() + m := new(dns.Msg) + m.SetQuestion(dns.Fqdn(domain), dns.TypeA) + m.RecursionDesired = true + + client := &dns.Client{Net: "udp", Timeout: 3 * time.Second} + resp, _, err := client.Exchange(m, addr) + if err != nil { + log.Printf("[dns module] bootstrap: %s via %s failed: %v", domain, addr, err) + continue + } + if resp == nil || len(resp.Answer) == 0 { + continue + } + for _, ans := range resp.Answer { + if a, ok := ans.(*dns.A); ok { + resolved[domain] = a.A.String() + log.Printf("[dns module] bootstrap resolved %s → %s via %s", domain, a.A.String(), addr) + break + } + } + if _, ok := resolved[domain]; ok { + break // 已解析成功 + } + } + if _, ok := resolved[domain]; !ok { + log.Printf("[dns module] warning: bootstrap resolution failed for %s (all system DNS exhausted)", domain) + } + } + + return resolved +} + +// Stop gracefully shuts down the DNS module and all its components. +// It stops the listener and waits for all goroutines to complete. +func (m *DnsModule) Stop() error { + m.mu.Lock() + defer m.mu.Unlock() + + if !m.healthy { + return nil // Already stopped. + } + + log.Printf("[dns module] stopping...") + + // Stop the listener. + if m.listener != nil { + if err := m.listener.Stop(); err != nil { + log.Printf("[dns module] listener stop error: %v", err) + } + } + + if m.cancel != nil { + m.cancel() + } + + m.wg.Wait() + m.healthy = false + log.Printf("[dns module] stopped") + return nil +} + +// Healthy returns true if the DNS module is running and healthy. +func (m *DnsModule) Healthy() bool { + m.mu.RLock() + defer m.mu.RUnlock() + + if !m.healthy { + return false + } + if m.listener == nil { + return false + } + return m.listener.Healthy() +} + +// Stats returns a map of current module statistics. +// This now includes rich metrics from the DnsMetrics collector. +func (m *DnsModule) Stats() map[string]interface{} { + m.mu.RLock() + defer m.mu.RUnlock() + + // Collect DnsStats (backward compatibility). + m.stats.mu.Lock() + totalQueries := m.stats.TotalQueries + rejected := m.stats.RejectedQueries + bypassed := m.stats.BypassedQueries + cacheHits := m.stats.CacheHits + cacheMisses := m.stats.CacheMisses + avgRTT := m.stats.AvgRTT + + // Copy routed queries map. + routedQueries := make(map[string]int64, len(m.stats.RoutedQueries)) + for k, v := range m.stats.RoutedQueries { + routedQueries[k] = v + } + m.stats.mu.Unlock() + + // Collect cache stats if available. + var cacheSize int + var cacheHitRate float64 + var cacheEvictions int64 + var cachePrefetchCnt int64 + if m.cache != nil { + cs := m.cache.Stats() + cacheSize = cs.Size + cacheHitRate = cs.HitRate + cacheEvictions = cs.Evictions + cachePrefetchCnt = cs.PrefetchCnt + } + + // Build stats map (basic stats for backward compatibility). + stats := map[string]interface{}{ + "healthy": m.healthy, + "listener": m.config.Listener.String(), + "total_queries": totalQueries, + "rejected_queries": rejected, + "bypassed_queries": bypassed, + "cache_hits": cacheHits, + "cache_misses": cacheMisses, + "cache_size": cacheSize, + "cache_hit_rate": cacheHitRate, + "cache_evictions": cacheEvictions, + "cache_prefetchs": cachePrefetchCnt, + "avg_rtt": avgRTT.String(), + "routed_queries": routedQueries, + "num_rules": len(m.config.Rules), + "num_upstreams": len(m.config.Upstreams), + } + + // Add rich metrics from DnsMetrics if available. + if m.metrics != nil { + snap := m.metrics.Snapshot() + stats["metrics_total_queries"] = snap.TotalQueries + stats["metrics_total_responses"] = snap.TotalResponses + stats["metrics_total_errors"] = snap.TotalErrors + stats["metrics_total_timeouts"] = snap.TotalTimeouts + stats["metrics_cache_hits"] = snap.CacheHits + stats["metrics_cache_misses"] = snap.CacheMisses + stats["metrics_cache_evictions"] = snap.CacheEvictions + stats["metrics_prefetch_count"] = snap.PrefetchCount + stats["metrics_routed"] = snap.RoutedQueries + stats["metrics_rejected"] = snap.RejectedQueries + stats["metrics_bypassed"] = snap.BypassedQueries + stats["metrics_uptime"] = snap.Uptime + + // Query type breakdown. + if len(snap.QueriesByType) > 0 { + stats["queries_by_type"] = snap.QueriesByType + } + + // Rule hits. + if len(snap.HitsByRule) > 0 { + stats["rule_hits"] = snap.HitsByRule + } + + // Latency buckets. + if len(snap.LatencyBuckets) > 0 { + latencyMap := make(map[string]int64) + for _, lb := range snap.LatencyBuckets { + latencyMap[lb.Label] = lb.Count + } + stats["latency_distribution"] = latencyMap + } + + // Upstream stats. + if len(snap.QueriesByUpstream) > 0 { + upstreamStats := make(map[string]map[string]interface{}) + for upstream, um := range snap.QueriesByUpstream { + upstreamStats[upstream] = map[string]interface{}{ + "queries": um.Queries, + "successes": um.Successes, + "errors": um.Errors, + "avg_rtt": um.AvgRTT.String(), + "min_rtt": um.MinRTT.String(), + "max_rtt": um.MaxRTT.String(), + } + } + stats["upstream_stats"] = upstreamStats + } + } + + return stats +} + +// SetDispatcher sets the xray-core routing dispatcher for internal routing. +// Must be called before Start(). +func (m *DnsModule) SetDispatcher(d RouteDispatcher) { + m.mu.Lock() + defer m.mu.Unlock() + m.dispatcher = d +} + +// Config returns the module configuration. +func (m *DnsModule) Config() *DnsModuleConfig { + return m.config +} + +// GetRouter returns the router instance. +func (m *DnsModule) GetRouter() *Router { + m.mu.RLock() + defer m.mu.RUnlock() + return m.router +} + +// GetUpstreamManager returns the upstream manager instance. +func (m *DnsModule) GetUpstreamManager() *UpstreamManager { + m.mu.RLock() + defer m.mu.RUnlock() + return m.upstreamMgr +} + +// GetCache returns the DNS cache instance. +func (m *DnsModule) GetCache() *DnsCache { + m.mu.RLock() + defer m.mu.RUnlock() + return m.cache +} + +// GetMetrics returns the metrics collector. +func (m *DnsModule) GetMetrics() *DnsMetrics { + m.mu.RLock() + defer m.mu.RUnlock() + return m.metrics +} + +// GetDiagnostics returns the diagnostics collector. +func (m *DnsModule) GetDiagnostics() *Diagnostics { + m.mu.RLock() + defer m.mu.RUnlock() + return m.diagnostics +} diff --git a/core/dns/qtype.go b/core/dns/qtype.go new file mode 100644 index 00000000..61d7377f --- /dev/null +++ b/core/dns/qtype.go @@ -0,0 +1,135 @@ +package dns + +import ( + "fmt" + "strings" + + "github.com/miekg/dns" +) + +// QTypeToString converts a QueryType to its string representation. +// For example, TypeA → "A", TypeAAAA → "AAAA". +// If the query type is not in the supported list, it returns the +// numeric string representation (e.g., "TYPE99"). +func QTypeToString(qt QueryType) string { + switch qt { + case TypeA: + return "A" + case TypeAAAA: + return "AAAA" + case TypeCNAME: + return "CNAME" + case TypeTXT: + return "TXT" + case TypeMX: + return "MX" + case TypeSRV: + return "SRV" + case TypeNS: + return "NS" + case TypePTR: + return "PTR" + case TypeSOA: + return "SOA" + default: + // Try miekg/dns string representation first. + s := dns.TypeToString[uint16(qt)] + if s != "" { + return s + } + return fmt.Sprintf("TYPE%d", uint16(qt)) + } +} + +// StringToQType converts a string to a QueryType. +// It supports standard type names ("A", "AAAA", etc.) and +// numeric format ("1", "28", "TYPE1", "TYPE28"). +// Returns an error if the string does not represent a valid query type. +func StringToQType(s string) (QueryType, error) { + s = strings.TrimSpace(s) + if s == "" { + return 0, fmt.Errorf("dns qtype: empty string") + } + + // Try uppercase name lookup first. + upper := strings.ToUpper(s) + switch upper { + case "A": + return TypeA, nil + case "AAAA": + return TypeAAAA, nil + case "CNAME": + return TypeCNAME, nil + case "TXT": + return TypeTXT, nil + case "MX": + return TypeMX, nil + case "SRV": + return TypeSRV, nil + case "NS": + return TypeNS, nil + case "PTR": + return TypePTR, nil + case "SOA": + return TypeSOA, nil + } + + // Try miekg/dns reverse lookup via StringToType. + if qt, ok := dns.StringToType[upper]; ok { + return QueryType(qt), nil + } + + // Try "TYPE" format. + if strings.HasPrefix(upper, "TYPE") { + var num uint16 + if _, err := fmt.Sscanf(upper, "TYPE%d", &num); err == nil { + return QueryType(num), nil + } + } + + // Try plain numeric format. + var num uint16 + if _, err := fmt.Sscanf(upper, "%d", &num); err == nil { + return QueryType(num), nil + } + + return 0, fmt.Errorf("dns qtype: unknown query type: %q", s) +} + +// SupportsQType returns true if the given QueryType is one of the +// supported types (A, AAAA, CNAME, TXT, MX, SRV, NS, PTR, SOA). +func SupportsQType(qt QueryType) bool { + switch qt { + case TypeA, TypeAAAA, TypeCNAME, TypeTXT, + TypeMX, TypeSRV, TypeNS, TypePTR, TypeSOA: + return true + default: + return false + } +} + +// SupportedQTypes returns a list of all supported query types. +func SupportedQTypes() []QueryType { + return []QueryType{ + TypeA, + TypeAAAA, + TypeCNAME, + TypeTXT, + TypeMX, + TypeSRV, + TypeNS, + TypePTR, + TypeSOA, + } +} + +// IsAddressQuery returns true if the query type is A or AAAA. +func IsAddressQuery(qt QueryType) bool { + return qt == TypeA || qt == TypeAAAA +} + +// NeedsDNS64 returns true if DNS64 synthesis should be considered +// for this query type (i.e., AAAA query). +func NeedsDNS64(qt QueryType) bool { + return qt == TypeAAAA +} diff --git a/core/dns/response.go b/core/dns/response.go new file mode 100644 index 00000000..251d5af0 --- /dev/null +++ b/core/dns/response.go @@ -0,0 +1,379 @@ +package dns + +import ( + "fmt" + "net" + "time" + + "github.com/miekg/dns" +) + +// ResponseBuilder builds DNS response messages. +// It handles all supported record types, response compression, +// EDNS0 options, TC bit handling, and DNS64 synthesis. +type ResponseBuilder struct { + // EnableDNS64, when true, enables DNS64 synthetic AAAA record + // synthesis from A records (stub for future implementation). + EnableDNS64 bool + // DNS64Prefix is the NAT64 prefix used for DNS64 synthesis. + DNS64Prefix net.IP +} + +// NewResponseBuilder creates a new ResponseBuilder. +func NewResponseBuilder() *ResponseBuilder { + return &ResponseBuilder{} +} + +// BuildResponse constructs a final *dns.Msg from an upstream DNS response. +// It copies the question section, sets response flags, applies compression, +// and preserves EDNS0 (OPT) records from the upstream response. +func (b *ResponseBuilder) BuildResponse(query *DnsQuery, upstreamResp *DnsResponse) *dns.Msg { + m := new(dns.Msg) + m.SetReply(upstreamResp.RawMsg) + + // Ensure the question matches the original query. + m.Question = []dns.Question{ + { + Name: dns.Fqdn(query.Name), + Qtype: uint16(query.QType), + Qclass: query.QClass, + }, + } + + // Copy response flags from upstream. + m.Response = true + m.Rcode = upstreamResp.Rcode + m.RecursionAvailable = upstreamResp.RawMsg.RecursionAvailable + m.Authoritative = upstreamResp.RawMsg.Authoritative + m.AuthenticatedData = upstreamResp.RawMsg.AuthenticatedData + m.CheckingDisabled = upstreamResp.RawMsg.CheckingDisabled + + // Copy resource records. + if len(upstreamResp.Answer) > 0 { + m.Answer = make([]dns.RR, len(upstreamResp.Answer)) + copy(m.Answer, upstreamResp.Answer) + } + if len(upstreamResp.Authority) > 0 { + m.Ns = make([]dns.RR, len(upstreamResp.Authority)) + copy(m.Ns, upstreamResp.Authority) + } + if len(upstreamResp.Additional) > 0 { + m.Extra = make([]dns.RR, len(upstreamResp.Additional)) + copy(m.Extra, upstreamResp.Additional) + } + + // Enable compression. + m.Compress = true + + // Handle DNS64 synthesis if enabled. + if b.EnableDNS64 && m.Rcode == dns.RcodeSuccess { + b.synthesizeDNS64(m) + } + + return m +} + +// BuildRefused creates a REFUSED DNS response message. +func (b *ResponseBuilder) BuildRefused(query *DnsQuery) *dns.Msg { + m := new(dns.Msg) + m.SetQuestion(dns.Fqdn(query.Name), uint16(query.QType)) + m.Response = true + m.Rcode = dns.RcodeRefused + m.RecursionAvailable = true + m.Compress = true + return m +} + +// BuildNXDOMAIN creates an NXDOMAIN DNS response message. +func (b *ResponseBuilder) BuildNXDOMAIN(query *DnsQuery) *dns.Msg { + m := new(dns.Msg) + m.SetQuestion(dns.Fqdn(query.Name), uint16(query.QType)) + m.Response = true + m.Rcode = dns.RcodeNameError + m.RecursionAvailable = true + m.Compress = true + return m +} + +// BuildServerFailure creates a SERVFAIL DNS response message. +func (b *ResponseBuilder) BuildServerFailure(query *DnsQuery) *dns.Msg { + m := new(dns.Msg) + m.SetQuestion(dns.Fqdn(query.Name), uint16(query.QType)) + m.Response = true + m.Rcode = dns.RcodeServerFailure + m.RecursionAvailable = true + m.Compress = true + return m +} + +// SetTruncated sets the TC (Truncation) bit on the message. +// This is used to indicate UDP truncation to the client. +func (b *ResponseBuilder) SetTruncated(m *dns.Msg) { + m.Truncated = true +} + +// IsTruncated returns true if the message has the TC bit set. +func (b *ResponseBuilder) IsTruncated(m *dns.Msg) bool { + return m.Truncated +} + +// AddEDNS0 adds or updates an EDNS0 (OPT) pseudo-record to the message. +// If the message already has an OPT record, it updates its UDP payload size; +// otherwise it appends a new OPT record. +func (b *ResponseBuilder) AddEDNS0(m *dns.Msg, udpPayloadSize uint16, options ...dns.EDNS0) { + opt := m.IsEdns0() + if opt != nil { + opt.SetUDPSize(udpPayloadSize) + // Preserve existing options and append new ones. + for _, o := range options { + opt.Option = append(opt.Option, o) + } + return + } + + // Create a new OPT record. + extra := []dns.RR{ + &dns.OPT{ + Hdr: dns.RR_Header{ + Name: ".", + Rrtype: dns.TypeOPT, + Class: udpPayloadSize, + }, + Option: options, + }, + } + m.Extra = append(m.Extra, extra...) +} + +// AddECSSubnet adds an EDNS0 Client Subnet (ECS) option to the message. +// ECS allows the upstream to return location-specific responses. +func (b *ResponseBuilder) AddECSSubnet(m *dns.Msg, clientIP net.IP) { + if clientIP == nil { + return + } + + var family uint16 + var mask uint8 + var ip net.IP + + if ipv4 := clientIP.To4(); ipv4 != nil { + family = 1 // IPv4 + mask = 24 + ip = ipv4 + } else { + family = 2 // IPv6 + mask = 48 + ip = clientIP.To16() + } + + subnet := &dns.EDNS0_SUBNET{ + Code: dns.EDNS0SUBNET, + Family: family, + SourceNetmask: mask, + SourceScope: 0, + Address: ip, + } + + b.AddEDNS0(m, dns.DefaultMsgSize, subnet) +} + +// SetDNSSEC sets the DNSSEC OK (DO) bit on the message. +func (b *ResponseBuilder) SetDNSSEC(m *dns.Msg) { + opt := m.IsEdns0() + if opt != nil { + opt.SetDo() + return + } + // Create new OPT with DO bit set. + extra := []dns.RR{ + &dns.OPT{ + Hdr: dns.RR_Header{ + Name: ".", + Rrtype: dns.TypeOPT, + Class: dns.DefaultMsgSize, + }, + }, + } + m.Extra = append(m.Extra, extra...) + m.Extra[len(m.Extra)-1].(*dns.OPT).SetDo() +} + +// ExtractRecords extracts resource records from a *dns.Msg into a DnsResponse. +// It populates Answer, Authority, Additional, Rcode, and computes the +// minimum TTL across answer records. +func ExtractRecords(msg *dns.Msg) *DnsResponse { + if msg == nil { + return nil + } + + resp := &DnsResponse{ + RawMsg: msg, + Rcode: msg.Rcode, + Answer: msg.Answer, + Authority: msg.Ns, + Additional: msg.Extra, + } + + // Compute minimum TTL across answer records. + if len(msg.Answer) > 0 { + resp.TTL = msg.Answer[0].Header().Ttl + for _, rr := range msg.Answer[1:] { + if rr.Header().Ttl < resp.TTL { + resp.TTL = rr.Header().Ttl + } + } + } + + return resp +} + +// ExtractQuestion extracts a DnsQuery from a *dns.Msg. +func ExtractQuestion(msg *dns.Msg) (*DnsQuery, error) { + if msg == nil { + return nil, fmt.Errorf("dns response: nil message") + } + if len(msg.Question) == 0 { + return nil, fmt.Errorf("dns response: no question section") + } + + q := msg.Question[0] + return &DnsQuery{ + Name: dns.Fqdn(q.Name), + QType: QueryType(q.Qtype), + QClass: q.Qclass, + }, nil +} + +// BuildResponseMsg constructs a *dns.Msg from DnsQuery and answer resource records. +// This is a convenience helper that creates a response directly from records, +// without needing an upstream response. +func BuildResponseMsg(query *DnsQuery, answer []dns.RR, rcode int) *dns.Msg { + m := new(dns.Msg) + m.SetReply(&dns.Msg{ + MsgHdr: dns.MsgHdr{ + Id: dns.Id(), + }, + Question: []dns.Question{ + { + Name: dns.Fqdn(query.Name), + Qtype: uint16(query.QType), + Qclass: query.QClass, + }, + }, + }) + m.Response = true + m.Rcode = rcode + m.RecursionAvailable = true + m.Compress = true + + if len(answer) > 0 { + m.Answer = answer + } + + return m +} + +// PackMsg serializes a *dns.Msg into wire format bytes. +// It handles compression and returns the packed bytes. +func PackMsg(m *dns.Msg) ([]byte, error) { + wire, err := m.Pack() + if err != nil { + return nil, fmt.Errorf("dns response: pack error: %w", err) + } + return wire, nil +} + +// UnpackMsg deserializes wire format bytes into a *dns.Msg. +func UnpackMsg(wire []byte) (*dns.Msg, error) { + m := new(dns.Msg) + if err := m.Unpack(wire); err != nil { + return nil, fmt.Errorf("dns response: unpack error: %w", err) + } + return m, nil +} + +// handleTruncation checks if the response is truncated and, if so, +// sets the TC bit and clears all resource records except the question. +// This follows the standard DNS truncation behavior for UDP. +func (b *ResponseBuilder) handleTruncation(m *dns.Msg, maxSize int) { + if m.Len() > maxSize { + m.Truncated = true + m.Answer = nil + m.Ns = nil + m.Extra = nil + } +} + +// synthesizeDNS64 performs DNS64 synthetic AAAA record synthesis (stub). +// When enabled, if the response has A records but no AAAA records, +// this synthesizes AAAA records using the configured NAT64 prefix. +func (b *ResponseBuilder) synthesizeDNS64(m *dns.Msg) { + if !b.EnableDNS64 || b.DNS64Prefix == nil { + return + } + + // Check if response already has AAAA records. + hasAAAA := false + for _, rr := range m.Answer { + if rr.Header().Rrtype == dns.TypeAAAA { + hasAAAA = true + break + } + } + if hasAAAA { + return + } + + // Check if response has A records to synthesize from. + var aRecords []*dns.A + for _, rr := range m.Answer { + if a, ok := rr.(*dns.A); ok { + aRecords = append(aRecords, a) + } + } + if len(aRecords) == 0 { + return + } + + // Synthesize AAAA records using NAT64 prefix. + prefix := b.DNS64Prefix.To16() + if prefix == nil { + return + } + + for _, a := range aRecords { + ipv4 := a.A.To4() + if ipv4 == nil { + continue + } + + // Construct IPv4-embedded IPv6 address. + syntheticIP := make(net.IP, 16) + copy(syntheticIP, prefix) + syntheticIP[12] = ipv4[0] + syntheticIP[13] = ipv4[1] + syntheticIP[14] = ipv4[2] + syntheticIP[15] = ipv4[3] + + aaaa := &dns.AAAA{ + Hdr: dns.RR_Header{ + Name: a.Hdr.Name, + Rrtype: dns.TypeAAAA, + Class: a.Hdr.Class, + Ttl: a.Hdr.Ttl, + }, + AAAA: syntheticIP, + } + m.Answer = append(m.Answer, aaaa) + } +} + +// ResponseTime returns the appropriate duration for the DNS response time. +// It calculates the response time based on when the query was received +// and the upstream response RTT. +func ResponseTime(queryTime time.Time, rtt time.Duration) time.Duration { + if rtt > 0 { + return rtt + } + return time.Since(queryTime) +} diff --git a/core/dns/response_test.go b/core/dns/response_test.go new file mode 100644 index 00000000..537650d2 --- /dev/null +++ b/core/dns/response_test.go @@ -0,0 +1,1040 @@ +package dns + +import ( + "net" + "testing" + "time" + + "github.com/miekg/dns" +) + +// ============================================================================ +// Helper functions +// ============================================================================ + +func newTestQuery(name string, qtype QueryType) *DnsQuery { + return &DnsQuery{ + Name: name, + QType: qtype, + QClass: dns.ClassINET, + ClientIP: net.ParseIP("192.168.1.100"), + } +} + +func newTestResponse(query *DnsQuery, rcode int, answers []dns.RR) *DnsResponse { + m := new(dns.Msg) + m.SetReply(&dns.Msg{ + MsgHdr: dns.MsgHdr{Id: dns.Id()}, + Question: []dns.Question{ + {Name: dns.Fqdn(query.Name), Qtype: uint16(query.QType), Qclass: query.QClass}, + }, + }) + m.Rcode = rcode + m.RecursionAvailable = true + m.Answer = answers + + return &DnsResponse{ + Query: *query, + RawMsg: m, + Rcode: rcode, + Answer: answers, + Upstream: "8.8.8.8:53", + ProxyTag: "proxy", + RTT: 10 * time.Millisecond, + } +} + +// ============================================================================ +// Test: Record Type Build and Parse +// ============================================================================ + +func TestBuildResponse_A(t *testing.T) { + query := newTestQuery("example.com", TypeA) + builder := NewResponseBuilder() + + answer := []dns.RR{ + &dns.A{ + Hdr: dns.RR_Header{ + Name: dns.Fqdn("example.com"), + Rrtype: dns.TypeA, + Class: dns.ClassINET, + Ttl: 300, + }, + A: net.ParseIP("1.2.3.4").To4(), + }, + } + resp := newTestResponse(query, dns.RcodeSuccess, answer) + msg := builder.BuildResponse(query, resp) + + if msg.Rcode != dns.RcodeSuccess { + t.Fatalf("expected RcodeSuccess, got %d", msg.Rcode) + } + if len(msg.Answer) != 1 { + t.Fatalf("expected 1 answer, got %d", len(msg.Answer)) + } + a, ok := msg.Answer[0].(*dns.A) + if !ok { + t.Fatalf("expected *dns.A, got %T", msg.Answer[0]) + } + if a.A.String() != "1.2.3.4" { + t.Fatalf("expected IP 1.2.3.4, got %s", a.A.String()) + } + if !msg.Compress { + t.Fatal("expected Compress to be true") + } +} + +func TestBuildResponse_AAAA(t *testing.T) { + query := newTestQuery("ipv6.example.com", TypeAAAA) + builder := NewResponseBuilder() + + answer := []dns.RR{ + &dns.AAAA{ + Hdr: dns.RR_Header{ + Name: dns.Fqdn("ipv6.example.com"), + Rrtype: dns.TypeAAAA, + Class: dns.ClassINET, + Ttl: 300, + }, + AAAA: net.ParseIP("2001:db8::1"), + }, + } + resp := newTestResponse(query, dns.RcodeSuccess, answer) + msg := builder.BuildResponse(query, resp) + + if msg.Rcode != dns.RcodeSuccess { + t.Fatalf("expected RcodeSuccess, got %d", msg.Rcode) + } + if len(msg.Answer) != 1 { + t.Fatalf("expected 1 answer, got %d", len(msg.Answer)) + } + aaaa, ok := msg.Answer[0].(*dns.AAAA) + if !ok { + t.Fatalf("expected *dns.AAAA, got %T", msg.Answer[0]) + } + if aaaa.AAAA.String() != "2001:db8::1" { + t.Fatalf("expected IP 2001:db8::1, got %s", aaaa.AAAA.String()) + } +} + +func TestBuildResponse_CNAME(t *testing.T) { + query := newTestQuery("www.example.com", TypeCNAME) + builder := NewResponseBuilder() + + answer := []dns.RR{ + &dns.CNAME{ + Hdr: dns.RR_Header{ + Name: dns.Fqdn("www.example.com"), + Rrtype: dns.TypeCNAME, + Class: dns.ClassINET, + Ttl: 300, + }, + Target: dns.Fqdn("example.com"), + }, + } + resp := newTestResponse(query, dns.RcodeSuccess, answer) + msg := builder.BuildResponse(query, resp) + + if len(msg.Answer) != 1 { + t.Fatalf("expected 1 answer, got %d", len(msg.Answer)) + } + cname, ok := msg.Answer[0].(*dns.CNAME) + if !ok { + t.Fatalf("expected *dns.CNAME, got %T", msg.Answer[0]) + } + if cname.Target != dns.Fqdn("example.com") { + t.Fatalf("expected target example.com., got %s", cname.Target) + } +} + +func TestBuildResponse_TXT(t *testing.T) { + query := newTestQuery("example.com", TypeTXT) + builder := NewResponseBuilder() + + answer := []dns.RR{ + &dns.TXT{ + Hdr: dns.RR_Header{ + Name: dns.Fqdn("example.com"), + Rrtype: dns.TypeTXT, + Class: dns.ClassINET, + Ttl: 300, + }, + Txt: []string{"v=spf1 include:_spf.example.com ~all"}, + }, + } + resp := newTestResponse(query, dns.RcodeSuccess, answer) + msg := builder.BuildResponse(query, resp) + + if len(msg.Answer) != 1 { + t.Fatalf("expected 1 answer, got %d", len(msg.Answer)) + } + txt, ok := msg.Answer[0].(*dns.TXT) + if !ok { + t.Fatalf("expected *dns.TXT, got %T", msg.Answer[0]) + } + if len(txt.Txt) != 1 || txt.Txt[0] != "v=spf1 include:_spf.example.com ~all" { + t.Fatalf("unexpected TXT record content: %v", txt.Txt) + } +} + +func TestBuildResponse_MX(t *testing.T) { + query := newTestQuery("example.com", TypeMX) + builder := NewResponseBuilder() + + answer := []dns.RR{ + &dns.MX{ + Hdr: dns.RR_Header{ + Name: dns.Fqdn("example.com"), + Rrtype: dns.TypeMX, + Class: dns.ClassINET, + Ttl: 300, + }, + Preference: 10, + Mx: dns.Fqdn("mail.example.com"), + }, + } + resp := newTestResponse(query, dns.RcodeSuccess, answer) + msg := builder.BuildResponse(query, resp) + + if len(msg.Answer) != 1 { + t.Fatalf("expected 1 answer, got %d", len(msg.Answer)) + } + mx, ok := msg.Answer[0].(*dns.MX) + if !ok { + t.Fatalf("expected *dns.MX, got %T", msg.Answer[0]) + } + if mx.Mx != dns.Fqdn("mail.example.com") || mx.Preference != 10 { + t.Fatalf("unexpected MX record: pref=%d, target=%s", mx.Preference, mx.Mx) + } +} + +func TestBuildResponse_SRV(t *testing.T) { + query := newTestQuery("_sip._tcp.example.com", TypeSRV) + builder := NewResponseBuilder() + + answer := []dns.RR{ + &dns.SRV{ + Hdr: dns.RR_Header{ + Name: dns.Fqdn("_sip._tcp.example.com"), + Rrtype: dns.TypeSRV, + Class: dns.ClassINET, + Ttl: 300, + }, + Priority: 10, + Weight: 5, + Port: 5060, + Target: dns.Fqdn("sip.example.com"), + }, + } + resp := newTestResponse(query, dns.RcodeSuccess, answer) + msg := builder.BuildResponse(query, resp) + + if len(msg.Answer) != 1 { + t.Fatalf("expected 1 answer, got %d", len(msg.Answer)) + } + srv, ok := msg.Answer[0].(*dns.SRV) + if !ok { + t.Fatalf("expected *dns.SRV, got %T", msg.Answer[0]) + } + if srv.Priority != 10 || srv.Weight != 5 || srv.Port != 5060 || srv.Target != dns.Fqdn("sip.example.com") { + t.Fatalf("unexpected SRV record: prio=%d weight=%d port=%d target=%s", + srv.Priority, srv.Weight, srv.Port, srv.Target) + } +} + +func TestBuildResponse_NS(t *testing.T) { + query := newTestQuery("example.com", TypeNS) + builder := NewResponseBuilder() + + answer := []dns.RR{ + &dns.NS{ + Hdr: dns.RR_Header{ + Name: dns.Fqdn("example.com"), + Rrtype: dns.TypeNS, + Class: dns.ClassINET, + Ttl: 300, + }, + Ns: dns.Fqdn("ns1.example.com"), + }, + } + resp := newTestResponse(query, dns.RcodeSuccess, answer) + msg := builder.BuildResponse(query, resp) + + if len(msg.Answer) != 1 { + t.Fatalf("expected 1 answer, got %d", len(msg.Answer)) + } + ns, ok := msg.Answer[0].(*dns.NS) + if !ok { + t.Fatalf("expected *dns.NS, got %T", msg.Answer[0]) + } + if ns.Ns != dns.Fqdn("ns1.example.com") { + t.Fatalf("expected ns1.example.com., got %s", ns.Ns) + } +} + +func TestBuildResponse_PTR(t *testing.T) { + query := newTestQuery("4.3.2.1.in-addr.arpa", TypePTR) + builder := NewResponseBuilder() + + answer := []dns.RR{ + &dns.PTR{ + Hdr: dns.RR_Header{ + Name: dns.Fqdn("4.3.2.1.in-addr.arpa"), + Rrtype: dns.TypePTR, + Class: dns.ClassINET, + Ttl: 300, + }, + Ptr: dns.Fqdn("host.example.com"), + }, + } + resp := newTestResponse(query, dns.RcodeSuccess, answer) + msg := builder.BuildResponse(query, resp) + + if len(msg.Answer) != 1 { + t.Fatalf("expected 1 answer, got %d", len(msg.Answer)) + } + ptr, ok := msg.Answer[0].(*dns.PTR) + if !ok { + t.Fatalf("expected *dns.PTR, got %T", msg.Answer[0]) + } + if ptr.Ptr != dns.Fqdn("host.example.com") { + t.Fatalf("expected host.example.com., got %s", ptr.Ptr) + } +} + +func TestBuildResponse_SOA(t *testing.T) { + query := newTestQuery("example.com", TypeSOA) + builder := NewResponseBuilder() + + answer := []dns.RR{ + &dns.SOA{ + Hdr: dns.RR_Header{ + Name: dns.Fqdn("example.com"), + Rrtype: dns.TypeSOA, + Class: dns.ClassINET, + Ttl: 300, + }, + Ns: dns.Fqdn("ns1.example.com"), + Mbox: dns.Fqdn("admin.example.com"), + Serial: 2024010100, + Refresh: 3600, + Retry: 1800, + Expire: 86400, + Minttl: 300, + }, + } + resp := newTestResponse(query, dns.RcodeSuccess, answer) + msg := builder.BuildResponse(query, resp) + + if len(msg.Answer) != 1 { + t.Fatalf("expected 1 answer, got %d", len(msg.Answer)) + } + soa, ok := msg.Answer[0].(*dns.SOA) + if !ok { + t.Fatalf("expected *dns.SOA, got %T", msg.Answer[0]) + } + if soa.Ns != dns.Fqdn("ns1.example.com") || soa.Serial != 2024010100 { + t.Fatalf("unexpected SOA record: ns=%s serial=%d", soa.Ns, soa.Serial) + } +} + +// ============================================================================ +// Test: Error Response Building +// ============================================================================ + +func TestBuildRefused(t *testing.T) { + query := newTestQuery("example.com", TypeA) + builder := NewResponseBuilder() + + msg := builder.BuildRefused(query) + + if msg.Rcode != dns.RcodeRefused { + t.Fatalf("expected RcodeRefused (%d), got %d", dns.RcodeRefused, msg.Rcode) + } + if !msg.Response { + t.Fatal("expected Response bit to be set") + } + if len(msg.Question) != 1 { + t.Fatalf("expected 1 question, got %d", len(msg.Question)) + } + if msg.Question[0].Name != dns.Fqdn("example.com") { + t.Fatalf("expected question name %q, got %q", dns.Fqdn("example.com"), msg.Question[0].Name) + } +} + +func TestBuildNXDOMAIN(t *testing.T) { + query := newTestQuery("nonexistent.example.com", TypeA) + builder := NewResponseBuilder() + + msg := builder.BuildNXDOMAIN(query) + + if msg.Rcode != dns.RcodeNameError { + t.Fatalf("expected RcodeNameError (%d), got %d", dns.RcodeNameError, msg.Rcode) + } + if !msg.Response { + t.Fatal("expected Response bit to be set") + } +} + +func TestBuildServerFailure(t *testing.T) { + query := newTestQuery("example.com", TypeA) + builder := NewResponseBuilder() + + msg := builder.BuildServerFailure(query) + + if msg.Rcode != dns.RcodeServerFailure { + t.Fatalf("expected RcodeServerFailure (%d), got %d", dns.RcodeServerFailure, msg.Rcode) + } + if !msg.Response { + t.Fatal("expected Response bit to be set") + } +} + +// ============================================================================ +// Test: Response Validation +// ============================================================================ + +func TestValidateResponse_Valid(t *testing.T) { + m := new(dns.Msg) + m.Response = true + m.Rcode = dns.RcodeSuccess + m.Question = []dns.Question{ + {Name: "example.com.", Qtype: dns.TypeA, Qclass: dns.ClassINET}, + } + m.Answer = []dns.RR{ + &dns.A{ + Hdr: dns.RR_Header{Name: "example.com.", Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 300}, + A: net.ParseIP("1.2.3.4").To4(), + }, + } + + err := ValidateResponse(m) + if err != nil { + t.Fatalf("expected no error, got: %v", err) + } +} + +func TestValidateResponse_NilMessage(t *testing.T) { + err := ValidateResponse(nil) + if err == nil { + t.Fatal("expected error for nil message") + } +} + +func TestValidateResponse_NotResponse(t *testing.T) { + m := new(dns.Msg) + m.Response = false + m.Question = []dns.Question{ + {Name: "example.com.", Qtype: dns.TypeA, Qclass: dns.ClassINET}, + } + + err := ValidateResponse(m) + if err == nil { + t.Fatal("expected error for non-response message") + } +} + +func TestValidateResponse_NoQuestion(t *testing.T) { + m := new(dns.Msg) + m.Response = true + m.Rcode = dns.RcodeSuccess + + err := ValidateResponse(m) + if err == nil { + t.Fatal("expected error for missing question section") + } +} + +func TestValidateResponse_NilAnswer(t *testing.T) { + m := new(dns.Msg) + m.Response = true + m.Rcode = dns.RcodeSuccess + m.Question = []dns.Question{ + {Name: "example.com.", Qtype: dns.TypeA, Qclass: dns.ClassINET}, + } + m.Answer = []dns.RR{nil} + + err := ValidateResponse(m) + if err == nil { + t.Fatal("expected error for nil answer record") + } +} + +func TestValidateQuestionMatch(t *testing.T) { + m := new(dns.Msg) + m.Question = []dns.Question{ + {Name: "example.com.", Qtype: dns.TypeA, Qclass: dns.ClassINET}, + } + + // Matching query. + err := ValidateQuestionMatch(m, "example.com", TypeA) + if err != nil { + t.Fatalf("expected no error for matching query, got: %v", err) + } + + // Mismatched name. + err = ValidateQuestionMatch(m, "other.com", TypeA) + if err == nil { + t.Fatal("expected error for mismatched name") + } + + // Mismatched type. + err = ValidateQuestionMatch(m, "example.com", TypeAAAA) + if err == nil { + t.Fatal("expected error for mismatched type") + } +} + +func TestValidateAnswerCount(t *testing.T) { + m := new(dns.Msg) + m.Rcode = dns.RcodeSuccess + m.Answer = nil + + err := ValidateAnswerCount(m) + if err == nil { + t.Fatal("expected error for success with zero answers") + } + + m.Answer = []dns.RR{ + &dns.A{ + Hdr: dns.RR_Header{Name: "example.com.", Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 300}, + A: net.ParseIP("1.2.3.4").To4(), + }, + } + err = ValidateAnswerCount(m) + if err != nil { + t.Fatalf("expected no error for success with answers, got: %v", err) + } +} + +// ============================================================================ +// Test: Truncation +// ============================================================================ + +func TestTruncation(t *testing.T) { + builder := NewResponseBuilder() + + m := new(dns.Msg) + m.Truncated = false + m.Answer = []dns.RR{ + &dns.A{ + Hdr: dns.RR_Header{Name: "example.com.", Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 300}, + A: net.ParseIP("1.2.3.4").To4(), + }, + } + + // Initially not truncated. + if builder.IsTruncated(m) { + t.Fatal("expected not truncated initially") + } + + // Set truncated. + builder.SetTruncated(m) + if !builder.IsTruncated(m) { + t.Fatal("expected truncated after SetTruncated") + } + + // Test handleTruncation with small max size. + builder.handleTruncation(m, 0) + if !builder.IsTruncated(m) { + t.Fatal("expected truncated after handleTruncation") + } + if m.Answer != nil { + t.Fatal("expected answer to be cleared after truncation") + } +} + +// ============================================================================ +// Test: EDNS0 +// ============================================================================ + +func TestEDNS0(t *testing.T) { + builder := NewResponseBuilder() + m := new(dns.Msg) + m.SetQuestion("example.com.", dns.TypeA) + + // Add EDNS0. + builder.AddEDNS0(m, 4096) + opt := m.IsEdns0() + if opt == nil { + t.Fatal("expected EDNS0 OPT record after AddEDNS0") + } + if opt.UDPSize() != 4096 { + t.Fatalf("expected UDP size 4096, got %d", opt.UDPSize()) + } + + // Update EDNS0 UDP size. + builder.AddEDNS0(m, 1232) + if opt.UDPSize() != 1232 { + t.Fatalf("expected UDP size 1232 after update, got %d", opt.UDPSize()) + } +} + +func TestECSSubnet(t *testing.T) { + builder := NewResponseBuilder() + m := new(dns.Msg) + m.SetQuestion("example.com.", dns.TypeA) + + // Add ECS for IPv4 client. + builder.AddECSSubnet(m, net.ParseIP("192.168.1.100")) + opt := m.IsEdns0() + if opt == nil { + t.Fatal("expected EDNS0 OPT record") + } + + foundECS := false + for _, o := range opt.Option { + if subnet, ok := o.(*dns.EDNS0_SUBNET); ok { + foundECS = true + if subnet.Family != 1 { + t.Fatalf("expected IPv4 family (1), got %d", subnet.Family) + } + if subnet.SourceNetmask != 24 { + t.Fatalf("expected /24 mask, got %d", subnet.SourceNetmask) + } + break + } + } + if !foundECS { + t.Fatal("expected EDNS0_SUBNET option") + } +} + +func TestECSSubnet_IPv6(t *testing.T) { + builder := NewResponseBuilder() + m := new(dns.Msg) + m.SetQuestion("example.com.", dns.TypeAAAA) + + builder.AddECSSubnet(m, net.ParseIP("2001:db8::1")) + opt := m.IsEdns0() + if opt == nil { + t.Fatal("expected EDNS0 OPT record") + } + + foundECS := false + for _, o := range opt.Option { + if subnet, ok := o.(*dns.EDNS0_SUBNET); ok { + foundECS = true + if subnet.Family != 2 { + t.Fatalf("expected IPv6 family (2), got %d", subnet.Family) + } + if subnet.SourceNetmask != 48 { + t.Fatalf("expected /48 mask, got %d", subnet.SourceNetmask) + } + break + } + } + if !foundECS { + t.Fatal("expected EDNS0_SUBNET option") + } +} + +func TestDNSSEC(t *testing.T) { + builder := NewResponseBuilder() + m := new(dns.Msg) + m.SetQuestion("example.com.", dns.TypeA) + + builder.SetDNSSEC(m) + opt := m.IsEdns0() + if opt == nil { + t.Fatal("expected EDNS0 OPT record") + } + if !opt.Do() { + t.Fatal("expected DNSSEC OK (DO) bit to be set") + } +} + +// ============================================================================ +// Test: ExtractRecords +// ============================================================================ + +func TestExtractRecords(t *testing.T) { + m := new(dns.Msg) + m.Response = true + m.Rcode = dns.RcodeSuccess + m.Question = []dns.Question{ + {Name: "example.com.", Qtype: dns.TypeA, Qclass: dns.ClassINET}, + } + m.Answer = []dns.RR{ + &dns.A{ + Hdr: dns.RR_Header{Name: "example.com.", Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 300}, + A: net.ParseIP("1.2.3.4").To4(), + }, + &dns.A{ + Hdr: dns.RR_Header{Name: "example.com.", Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 600}, + A: net.ParseIP("5.6.7.8").To4(), + }, + } + + resp := ExtractRecords(m) + if resp == nil { + t.Fatal("expected non-nil response") + } + if resp.Rcode != dns.RcodeSuccess { + t.Fatalf("expected RcodeSuccess, got %d", resp.Rcode) + } + if len(resp.Answer) != 2 { + t.Fatalf("expected 2 answers, got %d", len(resp.Answer)) + } + if resp.TTL != 300 { + t.Fatalf("expected min TTL 300, got %d", resp.TTL) + } +} + +func TestExtractRecords_Nil(t *testing.T) { + resp := ExtractRecords(nil) + if resp != nil { + t.Fatal("expected nil for nil input") + } +} + +// ============================================================================ +// Test: ExtractQuestion +// ============================================================================ + +func TestExtractQuestion(t *testing.T) { + m := new(dns.Msg) + m.Question = []dns.Question{ + {Name: "example.com.", Qtype: dns.TypeA, Qclass: dns.ClassINET}, + } + + q, err := ExtractQuestion(m) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if q == nil { + t.Fatal("expected non-nil query") + } + if q.Name != "example.com." { + t.Fatalf("expected name example.com., got %s", q.Name) + } + if q.QType != TypeA { + t.Fatalf("expected TypeA, got %d", q.QType) + } +} + +func TestExtractQuestion_NilMessage(t *testing.T) { + _, err := ExtractQuestion(nil) + if err == nil { + t.Fatal("expected error for nil message") + } +} + +func TestExtractQuestion_NoQuestion(t *testing.T) { + m := new(dns.Msg) + _, err := ExtractQuestion(m) + if err == nil { + t.Fatal("expected error for no question section") + } +} + +// ============================================================================ +// Test: BuildResponseMsg +// ============================================================================ + +func TestBuildResponseMsg(t *testing.T) { + query := newTestQuery("example.com", TypeA) + + answers := []dns.RR{ + &dns.A{ + Hdr: dns.RR_Header{Name: "example.com.", Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 300}, + A: net.ParseIP("1.2.3.4").To4(), + }, + } + + msg := BuildResponseMsg(query, answers, dns.RcodeSuccess) + if msg.Rcode != dns.RcodeSuccess { + t.Fatalf("expected RcodeSuccess, got %d", msg.Rcode) + } + if len(msg.Answer) != 1 { + t.Fatalf("expected 1 answer, got %d", len(msg.Answer)) + } +} + +// ============================================================================ +// Test: QType Conversion +// ============================================================================ + +func TestQTypeToString(t *testing.T) { + tests := []struct { + qt QueryType + expected string + }{ + {TypeA, "A"}, + {TypeAAAA, "AAAA"}, + {TypeCNAME, "CNAME"}, + {TypeTXT, "TXT"}, + {TypeMX, "MX"}, + {TypeSRV, "SRV"}, + {TypeNS, "NS"}, + {TypePTR, "PTR"}, + {TypeSOA, "SOA"}, + {QueryType(10000), "TYPE10000"}, + } + + for _, tt := range tests { + got := QTypeToString(tt.qt) + if got != tt.expected { + t.Errorf("QTypeToString(%d): expected %q, got %q", uint16(tt.qt), tt.expected, got) + } + } +} + +func TestStringToQType(t *testing.T) { + tests := []struct { + input string + expected QueryType + wantErr bool + }{ + {"A", TypeA, false}, + {"AAAA", TypeAAAA, false}, + {"CNAME", TypeCNAME, false}, + {"TXT", TypeTXT, false}, + {"MX", TypeMX, false}, + {"SRV", TypeSRV, false}, + {"NS", TypeNS, false}, + {"PTR", TypePTR, false}, + {"SOA", TypeSOA, false}, + {"a", TypeA, false}, + {"txt", TypeTXT, false}, + {"1", TypeA, false}, // numeric + {"28", TypeAAAA, false}, // numeric + {"TYPE1", TypeA, false}, // TYPE format + {"TYPE28", TypeAAAA, false}, // TYPE format + {"", 0, true}, + {"INVALID", 0, true}, + {"ZZ_TYPE", 0, true}, + } + + for _, tt := range tests { + got, err := StringToQType(tt.input) + if tt.wantErr { + if err == nil { + t.Errorf("StringToQType(%q): expected error, got %d", tt.input, got) + } + continue + } + if err != nil { + t.Errorf("StringToQType(%q): unexpected error: %v", tt.input, err) + continue + } + if got != tt.expected { + t.Errorf("StringToQType(%q): expected %d, got %d", tt.input, uint16(tt.expected), uint16(got)) + } + } +} + +func TestSupportsQType(t *testing.T) { + if !SupportsQType(TypeA) { + t.Error("expected TypeA to be supported") + } + if !SupportsQType(TypeAAAA) { + t.Error("expected TypeAAAA to be supported") + } + if !SupportsQType(TypeSOA) { + t.Error("expected TypeSOA to be supported") + } + if SupportsQType(QueryType(99)) { + t.Error("expected Type99 to NOT be supported") + } +} + +func TestSupportedQTypes(t *testing.T) { + types := SupportedQTypes() + if len(types) != 9 { + t.Fatalf("expected 9 supported types, got %d", len(types)) + } + + // Verify all expected types are present. + expected := map[QueryType]bool{ + TypeA: true, TypeAAAA: true, TypeCNAME: true, + TypeTXT: true, TypeMX: true, TypeSRV: true, + TypeNS: true, TypePTR: true, TypeSOA: true, + } + for _, qt := range types { + if !expected[qt] { + t.Errorf("unexpected type in SupportedQTypes: %d", uint16(qt)) + } + delete(expected, qt) + } + if len(expected) > 0 { + t.Errorf("missing types in SupportedQTypes: %v", expected) + } +} + +func TestIsAddressQuery(t *testing.T) { + if !IsAddressQuery(TypeA) { + t.Error("expected TypeA to be an address query") + } + if !IsAddressQuery(TypeAAAA) { + t.Error("expected TypeAAAA to be an address query") + } + if IsAddressQuery(TypeCNAME) { + t.Error("expected TypeCNAME to NOT be an address query") + } +} + +// ============================================================================ +// Test: Pack / Unpack +// ============================================================================ + +func TestPackUnpack(t *testing.T) { + m := new(dns.Msg) + m.SetQuestion("example.com.", dns.TypeA) + m.Response = true + m.Answer = []dns.RR{ + &dns.A{ + Hdr: dns.RR_Header{Name: "example.com.", Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 300}, + A: net.ParseIP("1.2.3.4").To4(), + }, + } + + wire, err := PackMsg(m) + if err != nil { + t.Fatalf("PackMsg error: %v", err) + } + + unpacked, err := UnpackMsg(wire) + if err != nil { + t.Fatalf("UnpackMsg error: %v", err) + } + + if unpacked.Rcode != m.Rcode { + t.Fatalf("Rcode mismatch after unpack: got %d, expected %d", unpacked.Rcode, m.Rcode) + } + if len(unpacked.Answer) != 1 { + t.Fatalf("expected 1 answer after unpack, got %d", len(unpacked.Answer)) + } +} + +// ============================================================================ +// Test: DNS64 Synthesis +// ============================================================================ + +func TestDNS64Synthesis(t *testing.T) { + prefix := net.ParseIP("64:ff9b::") + builder := &ResponseBuilder{ + EnableDNS64: true, + DNS64Prefix: prefix, + } + + query := newTestQuery("example.com", TypeAAAA) + + // Build a response that has A records but no AAAA records. + m := new(dns.Msg) + m.SetReply(&dns.Msg{ + MsgHdr: dns.MsgHdr{Id: dns.Id()}, + Question: []dns.Question{ + {Name: "example.com.", Qtype: dns.TypeAAAA, Qclass: dns.ClassINET}, + }, + }) + m.Rcode = dns.RcodeSuccess + m.Answer = []dns.RR{ + &dns.A{ + Hdr: dns.RR_Header{Name: "example.com.", Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 300}, + A: net.ParseIP("1.2.3.4").To4(), + }, + } + + resp := &DnsResponse{ + Query: *query, + RawMsg: m, + Rcode: dns.RcodeSuccess, + Answer: m.Answer, + } + + msg := builder.BuildResponse(query, resp) + + // Should have the original A record plus a synthesized AAAA. + foundAAAA := false + foundA := false + for _, rr := range msg.Answer { + switch v := rr.(type) { + case *dns.AAAA: + foundAAAA = true + expectedIP := net.ParseIP("64:ff9b::1.2.3.4") + if !v.AAAA.Equal(expectedIP) { + t.Fatalf("expected synthetic IP %s, got %s", expectedIP, v.AAAA.String()) + } + case *dns.A: + foundA = true + } + } + if !foundA { + t.Fatal("expected original A record to be preserved") + } + if !foundAAAA { + t.Fatal("expected synthesized AAAA record") + } +} + +func TestDNS64Synthesis_Disabled(t *testing.T) { + builder := NewResponseBuilder() // DNS64 disabled by default + + query := newTestQuery("example.com", TypeAAAA) + m := new(dns.Msg) + m.SetReply(&dns.Msg{ + MsgHdr: dns.MsgHdr{Id: dns.Id()}, + Question: []dns.Question{ + {Name: "example.com.", Qtype: dns.TypeAAAA, Qclass: dns.ClassINET}, + }, + }) + m.Rcode = dns.RcodeSuccess + m.Answer = []dns.RR{ + &dns.A{ + Hdr: dns.RR_Header{Name: "example.com.", Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 300}, + A: net.ParseIP("1.2.3.4").To4(), + }, + } + + resp := &DnsResponse{ + Query: *query, + RawMsg: m, + Rcode: dns.RcodeSuccess, + Answer: m.Answer, + } + + msg := builder.BuildResponse(query, resp) + + // DNS64 disabled, should only have A record, no AAAA synthesized. + for _, rr := range msg.Answer { + if _, ok := rr.(*dns.AAAA); ok { + t.Fatal("expected no AAAA synthesis when DNS64 is disabled") + } + } +} + +// ============================================================================ +// Test: ResponseTime +// ============================================================================ + +func TestResponseTime(t *testing.T) { + // With RTT > 0, should return the RTT. + rtt := ResponseTime(time.Now(), 50*time.Millisecond) + if rtt != 50*time.Millisecond { + t.Fatalf("expected 50ms, got %v", rtt) + } + + // With zero RTT, should return time since queryTime. + start := time.Now().Add(-100 * time.Millisecond) + rtt = ResponseTime(start, 0) + if rtt < 50*time.Millisecond || rtt > 200*time.Millisecond { + t.Fatalf("expected ~100ms, got %v", rtt) + } +} + +// ============================================================================ +// Test: NeedsDNS64 / IsAddressQuery +// ============================================================================ + +func TestNeedsDNS64(t *testing.T) { + if !NeedsDNS64(TypeAAAA) { + t.Error("expected TypeAAAA to need DNS64") + } + if NeedsDNS64(TypeA) { + t.Error("expected TypeA to NOT need DNS64") + } + if NeedsDNS64(TypeCNAME) { + t.Error("expected TypeCNAME to NOT need DNS64") + } +} diff --git a/core/dns/router.go b/core/dns/router.go new file mode 100644 index 00000000..ae76fe0f --- /dev/null +++ b/core/dns/router.go @@ -0,0 +1,217 @@ +package dns + +import ( + "fmt" + "log" + "sync" +) + +// RouteResult represents the result of routing a DNS query. +type RouteResult struct { + // UpstreamID is the ID of the matched upstream server. + UpstreamID string + // UpstreamAddr is the address of the matched upstream server. + UpstreamAddr string + // Action is the routing action: route / reject / bypass. + Action string + // RuleID is the ID of the matched rule. + RuleID string + // Policy is the query policy: single / parallel / fallback. + Policy string + // ProxyTag is the proxy channel tag associated with the upstream. + // Empty or "direct" means direct connection; other values indicate + // a specific proxy outbound tag. + ProxyTag string +} + +// Router is the DNS query routing engine. +// It maintains an ordered list of rules and matches incoming queries +// against them to determine the upstream server. +type Router struct { + rules []*DnsRule // Ordered list of routing rules. + matchers [][]RuleMatcher // Pre-built matchers for each rule. + upstreamMap map[string]string // Upstream ID → upstream address mapping. + upstreamProxyTag map[string]string // Upstream ID → proxy tag mapping. + defaultUpstream string // Default upstream ID used when no rule matches. + geositeResolver GeositeResolver // Resolves geosite tags (set externally). + mu sync.RWMutex +} + +// NewRouter creates a new Router with the given rules and default upstream. +func NewRouter(rules []*DnsRule, upstreams []UpstreamConfig, defaultUpstream string) (*Router, error) { + r := &Router{ + rules: make([]*DnsRule, 0), + matchers: make([][]RuleMatcher, 0), + upstreamMap: make(map[string]string), + upstreamProxyTag: make(map[string]string), + defaultUpstream: defaultUpstream, + } + + // Build upstream address and proxy tag mapping. + for _, u := range upstreams { + if u.ID != "" { + r.upstreamMap[u.ID] = u.Addr + if u.ProxyTag != "" { + r.upstreamProxyTag[u.ID] = u.ProxyTag + } + } + } + + // Load and compile rules. + if err := r.UpdateRules(rules); err != nil { + return nil, fmt.Errorf("new router: %w", err) + } + + return r, nil +} + +// Route matches a DNS query against the rule list and returns the routing result. +// Rules are evaluated in order; the first matching rule determines the result. +// If no rule matches, the default upstream is used. +func (r *Router) Route(query *DnsQuery) *RouteResult { + r.mu.RLock() + defer r.mu.RUnlock() + + // Iterate rules in order. + for i, rule := range r.rules { + if i >= len(r.matchers) { + continue + } + matchers := r.matchers[i] + + // Check if all matchers match (AND logic). + if MatchAny(matchers, query) { + // Rule matched — determine upstream address. + upstreamAddr := r.upstreamMap[rule.Upstream] + + log.Printf("[dns router] rule %q matched query %s %s → upstream=%s action=%s", + rule.ID, query.Name, rule.Upstream, upstreamAddr, rule.Action) + + action := rule.Action + if action == "" { + action = "route" + } + policy := rule.Policy + if policy == "" { + policy = "single" + } + + // Get proxy tag for the matched upstream. + proxyTag := r.upstreamProxyTag[rule.Upstream] + + return &RouteResult{ + UpstreamID: rule.Upstream, + UpstreamAddr: upstreamAddr, + Action: action, + RuleID: rule.ID, + Policy: policy, + ProxyTag: proxyTag, + } + } + } + + // No rule matched — use default upstream. + log.Printf("[dns router] no rule matched for %s %d → using default upstream %s", + query.Name, query.QType, r.defaultUpstream) + + defaultAddr := r.upstreamMap[r.defaultUpstream] + defaultProxyTag := r.upstreamProxyTag[r.defaultUpstream] + return &RouteResult{ + UpstreamID: r.defaultUpstream, + UpstreamAddr: defaultAddr, + Action: "route", + RuleID: "", + Policy: "single", + ProxyTag: defaultProxyTag, + } +} + +// UpdateRules replaces the current rule set with new rules. +// It rebuilds all matchers for the new rules, expanding geosite tags using +// the configured resolver. +func (r *Router) UpdateRules(rules []*DnsRule) error { + r.mu.Lock() + defer r.mu.Unlock() + + newRules := make([]*DnsRule, len(rules)) + newMatchers := make([][]RuleMatcher, len(rules)) + + for i, rule := range rules { + // Validate and build matchers, passing the geosite resolver. + matchers, err := BuildMatchers(rule, r.geositeResolver) + if err != nil { + return fmt.Errorf("rule %d (id=%q): %w", i, rule.ID, err) + } + + // Copy the rule. + r := *rule + newRules[i] = &r + newMatchers[i] = matchers + } + + r.rules = newRules + r.matchers = newMatchers + + log.Printf("[dns router] updated rules: %d rules loaded", len(rules)) + return nil +} + +// ListRules returns a copy of all registered rules. +func (r *Router) ListRules() []*DnsRule { + r.mu.RLock() + defer r.mu.RUnlock() + + rules := make([]*DnsRule, len(r.rules)) + for i, rule := range r.rules { + cp := *rule + rules[i] = &cp + } + return rules +} + +// SetGeositeResolver sets the geosite tag resolver function. +func (r *Router) SetGeositeResolver(resolver GeositeResolver) { + r.mu.Lock() + defer r.mu.Unlock() + r.geositeResolver = resolver +} + +// Reload reloads the router configuration from a DnsModuleConfig. +func (r *Router) Reload(cfg *DnsModuleConfig) error { + if cfg == nil { + return fmt.Errorf("router reload: config is nil") + } + + // Convert RuleConfigs to DnsRules. + rules := make([]*DnsRule, len(cfg.Rules)) + for i, rc := range cfg.Rules { + rules[i] = &DnsRule{ + ID: rc.ID, + Domain: rc.Domain, + DomainSuffix: rc.DomainSuffix, + DomainRegex: rc.DomainRegex, + IP: rc.IP, + QueryType: rc.QueryType, + ClientIP: rc.ClientIP, + Upstream: rc.Upstream, + Action: rc.Action, + Policy: rc.Policy, + } + } + + // Rebuild upstream mapping. + r.mu.Lock() + r.upstreamMap = make(map[string]string) + r.upstreamProxyTag = make(map[string]string) + for _, u := range cfg.Upstreams { + if u.ID != "" { + r.upstreamMap[u.ID] = u.Addr + if u.ProxyTag != "" { + r.upstreamProxyTag[u.ID] = u.ProxyTag + } + } + } + r.mu.Unlock() + + return r.UpdateRules(rules) +} diff --git a/core/dns/rule.go b/core/dns/rule.go new file mode 100644 index 00000000..47600ec5 --- /dev/null +++ b/core/dns/rule.go @@ -0,0 +1,274 @@ +package dns + +import ( + "fmt" + "net" + "regexp" + "strings" +) + +// GeositeResolver resolves a geosite tag (e.g. "cn", "geolocation-!cn") +// into domain and suffix patterns. Returns (domains, suffixes) where +// domains are for exact/full matching and suffixes for suffix matching. +// Nil means the tag is not recognized/loaded. +type GeositeResolver func(tag string) (domains, suffixes []string) + +// RuleMatcher is the interface for DNS query rule matchers. +type RuleMatcher interface { + // Match checks whether the given query matches this rule. + Match(query *DnsQuery) bool + // Type returns the matcher type description (e.g., "domain", "ip", "querytype", "clientip"). + Type() string + // Value returns the matcher value description. + Value() string +} + +// DomainRule matches DNS queries by domain name. +// It supports exact match, suffix match (wildcard), and regex match. +type DomainRule struct { + Domain string + IsSuffix bool // true: match suffix like .example.com; false: exact match + IsRegex bool // true: regex match + Re *regexp.Regexp +} + +// Match checks if the query domain matches this domain rule. +func (r *DomainRule) Match(query *DnsQuery) bool { + name := strings.TrimSuffix(query.Name, ".") + + if r.IsRegex { + return r.Re.MatchString(name) + } + + if r.IsSuffix { + // Suffix match: domain ".example.com" matches "sub.example.com" or "example.com" + // If the rule domain starts with ".", treat it as a suffix match for subdomains. + domain := strings.TrimSuffix(r.Domain, ".") + if strings.HasPrefix(domain, ".") { + // ".example.com" matches anything ending with ".example.com" + return strings.HasSuffix(name, domain) + } + // "example.com" matches "example.com" itself and "sub.example.com" + if name == domain { + return true + } + return strings.HasSuffix(name, "."+domain) + } + + // Exact match + domain := strings.TrimSuffix(r.Domain, ".") + return name == domain +} + +// Type returns the matcher type. +func (r *DomainRule) Type() string { + if r.IsRegex { + return "domain_regex" + } + if r.IsSuffix { + return "domain_suffix" + } + return "domain" +} + +// Value returns the matcher value. +func (r *DomainRule) Value() string { + return r.Domain +} + +// IPRule matches DNS queries by response IP CIDR range. +// Note: This matcher is used for response IP-based filtering. +// For query-time matching, it checks against the query name's resolved IPs +// (pre-match mode) or is used in post-processing. +type IPRule struct { + CIDR *net.IPNet +} + +// Match checks if the client IP or any embedded IP matches this rule. +// For request-time use, this typically matches the query's ClientIP against +// the CIDR range. Response-time matching would check answer records. +func (r *IPRule) Match(query *DnsQuery) bool { + if r.CIDR == nil { + return false + } + return r.CIDR.Contains(query.ClientIP) +} + +// Type returns the matcher type. +func (r *IPRule) Type() string { + return "ip" +} + +// Value returns the matcher value. +func (r *IPRule) Value() string { + if r.CIDR == nil { + return "" + } + return r.CIDR.String() +} + +// QueryTypeRule matches DNS queries by query type (A, AAAA, etc.). +type QueryTypeRule struct { + QType QueryType +} + +// Match checks if the query type matches this rule. +func (r *QueryTypeRule) Match(query *DnsQuery) bool { + return r.QType == query.QType +} + +// Type returns the matcher type. +func (r *QueryTypeRule) Type() string { + return "query_type" +} + +// Value returns the matcher value. +func (r *QueryTypeRule) Value() string { + return fmt.Sprintf("%d", uint16(r.QType)) +} + +// ClientIPRule matches DNS queries by client IP CIDR range. +type ClientIPRule struct { + CIDR *net.IPNet +} + +// Match checks if the query's client IP matches this rule. +func (r *ClientIPRule) Match(query *DnsQuery) bool { + if r.CIDR == nil || query.ClientIP == nil { + return false + } + return r.CIDR.Contains(query.ClientIP) +} + +// Type returns the matcher type. +func (r *ClientIPRule) Type() string { + return "client_ip" +} + +// Value returns the matcher value. +func (r *ClientIPRule) Value() string { + if r.CIDR == nil { + return "" + } + return r.CIDR.String() +} + +// parseCIDR parses a CIDR string and returns the IPNet. +// Supports both regular CIDR (e.g., "10.0.0.0/8") and single IP (e.g., "10.0.0.1"). +func parseCIDR(s string) (*net.IPNet, error) { + if strings.Contains(s, "/") { + _, cidr, err := net.ParseCIDR(s) + if err != nil { + return nil, fmt.Errorf("invalid CIDR %q: %w", s, err) + } + return cidr, nil + } + // Single IP: treat as /32 for IPv4 or /128 for IPv6 + ip := net.ParseIP(s) + if ip == nil { + return nil, fmt.Errorf("invalid IP address %q", s) + } + if ip.To4() != nil { + _, cidr, err := net.ParseCIDR(s + "/32") + if err != nil { + return nil, err + } + return cidr, nil + } + _, cidr, err := net.ParseCIDR(s + "/128") + if err != nil { + return nil, err + } + return cidr, nil +} + +// BuildMatchers constructs a list of RuleMatcher from a DnsRule configuration. +// Each rule field generates one or more matchers. All matchers must match (AND logic). +// If a resolver is provided, geosite tags (e.g. "geosite:cn") are expanded. +func BuildMatchers(rule *DnsRule, resolver GeositeResolver) ([]RuleMatcher, error) { + var matchers []RuleMatcher + + // Build domain exact matchers, expanding geosite tags if resolver is available. + for _, d := range rule.Domain { + if strings.HasPrefix(d, "geosite:") { + if resolver != nil { + doms, suffs := resolver(strings.TrimPrefix(d, "geosite:")) + for _, dom := range doms { + matchers = append(matchers, &DomainRule{Domain: dom, IsSuffix: false, IsRegex: false}) + } + for _, suf := range suffs { + matchers = append(matchers, &DomainRule{Domain: suf, IsSuffix: true, IsRegex: false}) + } + } + // Without resolver, geosite tags are silently skipped (no matcher created). + continue + } + matchers = append(matchers, &DomainRule{Domain: d, IsSuffix: false, IsRegex: false}) + } + + // Build domain suffix matchers (also check for geosite patterns). + for _, d := range rule.DomainSuffix { + if strings.HasPrefix(d, "geosite:") { + if resolver != nil { + doms, suffs := resolver(strings.TrimPrefix(d, "geosite:")) + for _, dom := range doms { + matchers = append(matchers, &DomainRule{Domain: dom, IsSuffix: false, IsRegex: false}) + } + for _, suf := range suffs { + matchers = append(matchers, &DomainRule{Domain: suf, IsSuffix: true, IsRegex: false}) + } + } + continue + } + matchers = append(matchers, &DomainRule{Domain: d, IsSuffix: true, IsRegex: false}) + } + + // Build domain regex matchers + for _, d := range rule.DomainRegex { + re, err := regexp.Compile(d) + if err != nil { + return nil, fmt.Errorf("invalid domain regex %q: %w", d, err) + } + matchers = append(matchers, &DomainRule{Domain: d, IsRegex: true, Re: re}) + } + + // Build IP CIDR matchers + for _, ipStr := range rule.IP { + cidr, err := parseCIDR(ipStr) + if err != nil { + return nil, fmt.Errorf("invalid IP CIDR %q: %w", ipStr, err) + } + matchers = append(matchers, &IPRule{CIDR: cidr}) + } + + // Build query type matchers + for _, qt := range rule.QueryType { + matchers = append(matchers, &QueryTypeRule{QType: qt}) + } + + // Build client IP CIDR matchers + for _, cipStr := range rule.ClientIP { + cidr, err := parseCIDR(cipStr) + if err != nil { + return nil, fmt.Errorf("invalid client IP CIDR %q: %w", cipStr, err) + } + matchers = append(matchers, &ClientIPRule{CIDR: cidr}) + } + + return matchers, nil +} + +// MatchAny checks if all matchers in the list match the query (AND logic). +// Returns true only if every matcher matches. +func MatchAny(matchers []RuleMatcher, query *DnsQuery) bool { + if len(matchers) == 0 { + // Empty matchers means no constraints — matches everything. + return true + } + for _, m := range matchers { + if !m.Match(query) { + return false + } + } + return true +} diff --git a/service/core/dns/system_darwin.go b/core/dns/system_darwin.go similarity index 100% rename from service/core/dns/system_darwin.go rename to core/dns/system_darwin.go diff --git a/service/core/dns/system_other.go b/core/dns/system_other.go similarity index 100% rename from service/core/dns/system_other.go rename to core/dns/system_other.go diff --git a/service/core/dns/system_windows.go b/core/dns/system_windows.go similarity index 100% rename from service/core/dns/system_windows.go rename to core/dns/system_windows.go diff --git a/core/dns/types.go b/core/dns/types.go new file mode 100644 index 00000000..304cc7ff --- /dev/null +++ b/core/dns/types.go @@ -0,0 +1,161 @@ +// Package dns provides a standalone DNS module for v2rayA. +// It directly listens on UDP/TCP ports to handle DNS queries, +// replacing the previous approach of routing DNS traffic through +// xray's dokodemo-door and dns-out. +package dns + +import ( + "net" + "sync" + "time" + + "github.com/miekg/dns" +) + +// QueryType represents a DNS query type. +type QueryType uint16 + +// Supported DNS query type constants. +const ( + TypeA QueryType = QueryType(dns.TypeA) + TypeAAAA QueryType = QueryType(dns.TypeAAAA) + TypeCNAME QueryType = QueryType(dns.TypeCNAME) + TypeTXT QueryType = QueryType(dns.TypeTXT) + TypeMX QueryType = QueryType(dns.TypeMX) + TypeSRV QueryType = QueryType(dns.TypeSRV) + TypeNS QueryType = QueryType(dns.TypeNS) + TypePTR QueryType = QueryType(dns.TypePTR) + TypeSOA QueryType = QueryType(dns.TypeSOA) +) + +// DnsQuery represents a normalized DNS query request. +type DnsQuery struct { + // Name is the queried domain name (e.g. "www.example.com"). + Name string + // QType is the DNS query type (A, AAAA, etc.). + QType QueryType + // QClass is the DNS query class (usually IN=1). + QClass uint16 + // ClientIP is the IP address of the DNS client. + ClientIP net.IP + // IsBootstrap indicates whether this is a bootstrap query. + IsBootstrap bool +} + +// DnsResponse represents a normalized DNS query response. +type DnsResponse struct { + // Query is the original query corresponding to this response. + Query DnsQuery + // RawMsg is the raw DNS response message. + RawMsg *dns.Msg + // Rcode is the DNS response code (e.g. dns.RcodeSuccess). + Rcode int + // Answer contains the answer resource records. + Answer []dns.RR + // Authority contains the authority resource records. + Authority []dns.RR + // Additional contains the additional resource records. + Additional []dns.RR + // TTL is the minimum TTL among all answer records. + TTL uint32 + // Upstream is the upstream DNS server address that provided the response. + Upstream string + // ProxyTag is the proxy channel tag used for the query. + ProxyTag string + // RTT is the round-trip time of the query. + RTT time.Duration + // Cached indicates whether the response was served from cache. + Cached bool +} + +// DnsListenerConfig holds configuration for the DNS listener. +type DnsListenerConfig struct { + // ListenAddr is the primary listening address, default "0.0.0.0:52353". + ListenAddr string `json:"listen_addr"` + // ExtraListenAddrs is a list of additional addresses to listen on. + // For example, ["127.2.0.17:53"] to handle hijacked system DNS queries + // directly, avoiding the need for iptables REDIRECT rules. + ExtraListenAddrs []string `json:"extra_listen_addrs,omitempty"` + // Timeout is the query timeout in seconds, default 5. + Timeout int `json:"timeout"` +} + +// DnsModuleConfig holds the complete DNS module configuration. +type DnsModuleConfig struct { + Listener DnsListenerConfig `json:"listener"` + Cache CacheConfig `json:"cache"` + Upstreams []UpstreamConfig `json:"upstreams"` + Rules []RuleConfig `json:"rules"` + // ProxyMap maps proxy tags (e.g. "proxy") to SOCKS5 proxy addresses (e.g. "127.0.0.1:20170"). + // The DNS module connects to these SOCKS5 proxies when sending queries through tagged upstreams. + // If a tag is not found in this map, the module falls back to common defaults ("proxy" → "127.0.0.1:1080"). + ProxyMap map[string]string `json:"proxy_map,omitempty"` + // Bootstrap lists domain names of DNS upstream servers that need to be resolved + // via system DNS before the module can use them. These are resolved at startup. + Bootstrap []string `json:"bootstrap,omitempty"` + // BootstrapDns lists saved system DNS servers (read from /etc/resolv.conf before hijack). + // Used by resolveBootstrap to avoid chicken-and-egg: the hijacked resolv.conf + // points to 127.2.0.17:53 (our own DNS module), but it hasn't started yet. + BootstrapDns []string `json:"bootstrap_dns,omitempty"` +} + +// CacheConfig holds DNS cache configuration. +type CacheConfig struct { + Enabled bool `json:"enabled"` + Size int `json:"size"` + MinTTL int `json:"min_ttl"` + MaxTTL int `json:"max_ttl"` + Prefetch bool `json:"prefetch"` + PrefetchThreshold int `json:"prefetch_threshold"` + NegativeCache bool `json:"neg_cache"` +} + +// UpstreamConfig holds DNS upstream server configuration. +type UpstreamConfig struct { + ID string `json:"id"` + Addr string `json:"addr"` + Protocol string `json:"protocol,omitempty"` + ProxyTag string `json:"proxy_tag,omitempty"` + Bootstrap bool `json:"bootstrap,omitempty"` +} + +// RuleConfig holds DNS routing rule configuration. +type RuleConfig struct { + ID string `json:"id,omitempty"` + Domain []string `json:"domain,omitempty"` + DomainSuffix []string `json:"domain_suffix,omitempty"` + DomainRegex []string `json:"domain_regex,omitempty"` + IP []string `json:"ip,omitempty"` + QueryType []QueryType `json:"query_type,omitempty"` + ClientIP []string `json:"client_ip,omitempty"` + Upstream string `json:"upstream"` + Action string `json:"action,omitempty"` + Policy string `json:"policy,omitempty"` +} + +// DnsRule represents a fully parsed DNS routing rule with metadata. +type DnsRule struct { + ID string + Domain []string + DomainSuffix []string + DomainRegex []string + IP []string + QueryType []QueryType + ClientIP []string + Upstream string + Action string + Policy string +} + +// DnsStats accumulates DNS query statistics. +type DnsStats struct { + TotalQueries int64 + RoutedQueries map[string]int64 // Per-upstream query count. + RejectedQueries int64 + BypassedQueries int64 + CacheHits int64 + CacheMisses int64 + AvgRTT time.Duration + mu sync.Mutex + StartedAt time.Time // 模块启动时间 +} diff --git a/core/dns/upstream.go b/core/dns/upstream.go new file mode 100644 index 00000000..31da830d --- /dev/null +++ b/core/dns/upstream.go @@ -0,0 +1,258 @@ +package dns + +import ( + "fmt" + "log" + "sync" + "time" + + "github.com/miekg/dns" +) + +// BuildUpstreamKey builds a composite key for an upstream instance, +// combining the address and proxy channel tag. +// This ensures that the same DNS server queried through different +// proxy channels is treated as separate instances. +// +// Examples: +// +// BuildUpstreamKey("8.8.8.8:53", "") → "8.8.8.8:53|" +// BuildUpstreamKey("8.8.8.8:53", "direct") → "8.8.8.8:53|direct" +// BuildUpstreamKey("8.8.8.8:53", "proxy") → "8.8.8.8:53|proxy" +func BuildUpstreamKey(addr, proxyTag string) string { + return fmt.Sprintf("%s|%s", addr, proxyTag) +} + +// UpstreamInstance represents a single DNS upstream server instance. +type UpstreamInstance struct { + // ID is the unique identifier for this upstream. + ID string + // Addr is the upstream server address (e.g., "8.8.8.8:53"). + Addr string + // Protocol is the transport protocol: udp, tcp, dot, doh. + Protocol string + // ProxyTag is the proxy channel tag for routing. + ProxyTag string + // Client is the DNS client used to send queries. + Client *dns.Client + // Healthy indicates whether the upstream is currently healthy. + Healthy bool + // Bootstrap indicates whether this upstream is used for bootstrap resolution. + Bootstrap bool +} + +// CompositeKey returns the composite key for this instance. +func (u *UpstreamInstance) CompositeKey() string { + return BuildUpstreamKey(u.Addr, u.ProxyTag) +} + +// UpstreamManager manages a collection of DNS upstream servers. +// It provides methods for retrieving upstream instances and sending queries. +// Each upstream instance is identified by a composite key of (addr, proxyTag), +// allowing the same DNS server to be used through different proxy channels +// as independent instances with separate connection pools and health states. +type UpstreamManager struct { + upstreams map[string]*UpstreamInstance // Composite key → instance + upstreamsByID map[string]*UpstreamInstance // ID → instance (backward compatibility) + proxyAddrResolver ProxyAddrResolver // Resolver for proxy tag → SOCKS5 address (legacy) + dispatcher RouteDispatcher // xray-core internal routing dispatcher + mu sync.RWMutex +} + +// NewUpstreamManager creates a new UpstreamManager from a list of upstream configurations. +// Each upstream configuration produces an instance keyed by (addr, proxyTag). +// If two configs share the same addr but have different proxy tags, they are +// stored as separate instances. +func NewUpstreamManager(configs []UpstreamConfig) *UpstreamManager { + m := &UpstreamManager{ + upstreams: make(map[string]*UpstreamInstance), + upstreamsByID: make(map[string]*UpstreamInstance), + } + + for _, cfg := range configs { + id := cfg.ID + if id == "" { + id = cfg.Addr + } + + net := cfg.Protocol + if net == "" { + net = "udp" + } + + proxyTag := cfg.ProxyTag + if proxyTag == "" { + proxyTag = "direct" + } + + instance := &UpstreamInstance{ + ID: id, + Addr: cfg.Addr, + Protocol: net, + ProxyTag: proxyTag, + Healthy: true, + Bootstrap: cfg.Bootstrap, + Client: &dns.Client{ + Net: net, + Timeout: 5 * time.Second, + ReadTimeout: 5 * time.Second, + WriteTimeout: 5 * time.Second, + }, + } + + compositeKey := instance.CompositeKey() + m.upstreams[compositeKey] = instance + + // Also index by ID for backward compatibility. + // If multiple instances share the same ID, the last one wins. + m.upstreamsByID[id] = instance + } + + log.Printf("[dns upstream] created manager with %d upstreams", len(configs)) + return m +} + +// GetUpstream returns the upstream instance with the given ID. +// Returns false if the upstream is not found. +// This uses the ID-based index for backward compatibility. +func (m *UpstreamManager) GetUpstream(id string) (*UpstreamInstance, bool) { + m.mu.RLock() + defer m.mu.RUnlock() + + u, ok := m.upstreamsByID[id] + if !ok { + // Fallback: try direct lookup in upstreams map + u, ok = m.upstreams[id] + } + return u, ok +} + +// GetUpstreamByKey returns the upstream instance with the given composite key +// (addr|proxyTag). This provides direct access to a specific channel's instance. +func (m *UpstreamManager) GetUpstreamByKey(compositeKey string) (*UpstreamInstance, bool) { + m.mu.RLock() + defer m.mu.RUnlock() + + u, ok := m.upstreams[compositeKey] + return u, ok +} + +// GetOrCreateUpstream retrieves an existing upstream instance for the given +// configuration, or creates a new one if it doesn't exist. +// The instance is identified by the composite key of (Addr, ProxyTag). +// This allows the same DNS server address to have separate instances +// for different proxy channels. +func (m *UpstreamManager) GetOrCreateUpstream(config UpstreamConfig) *UpstreamInstance { + proxyTag := config.ProxyTag + if proxyTag == "" { + proxyTag = "direct" + } + + compositeKey := BuildUpstreamKey(config.Addr, proxyTag) + + m.mu.Lock() + defer m.mu.Unlock() + + // Check if an instance already exists for this composite key. + if existing, ok := m.upstreams[compositeKey]; ok { + return existing + } + + // Create a new instance. + id := config.ID + if id == "" { + id = config.Addr + } + + net := config.Protocol + if net == "" { + net = "udp" + } + + instance := &UpstreamInstance{ + ID: id, + Addr: config.Addr, + Protocol: net, + ProxyTag: proxyTag, + Healthy: true, + Bootstrap: config.Bootstrap, + Client: &dns.Client{ + Net: net, + Timeout: 5 * time.Second, + ReadTimeout: 5 * time.Second, + WriteTimeout: 5 * time.Second, + }, + } + + m.upstreams[compositeKey] = instance + m.upstreamsByID[id] = instance + + log.Printf("[dns upstream] created instance: key=%s addr=%s proxyTag=%s", + compositeKey, config.Addr, proxyTag) + + return instance +} + +// HealthCheck performs a health check on all upstream servers. +// Returns a map of composite key → health status. +func (m *UpstreamManager) HealthCheck() map[string]bool { + m.mu.RLock() + defer m.mu.RUnlock() + + results := make(map[string]bool, len(m.upstreams)) + + for key, upstream := range m.upstreams { + healthy := m.pingUpstream(upstream) + upstream.Healthy = healthy + results[key] = healthy + log.Printf("[dns upstream] health check: %s (%s, proxy=%s) → healthy=%v", + key, upstream.Addr, upstream.ProxyTag, healthy) + } + + return results +} + +// HealthCheckByProxyTag performs a health check on upstream instances +// matching the given proxy tag. This allows per-channel health checks. +func (m *UpstreamManager) HealthCheckByProxyTag(proxyTag string) map[string]bool { + m.mu.RLock() + defer m.mu.RUnlock() + + results := make(map[string]bool) + for key, upstream := range m.upstreams { + if upstream.ProxyTag == proxyTag { + healthy := m.pingUpstream(upstream) + upstream.Healthy = healthy + results[key] = healthy + } + } + + return results +} + +// pingUpstream performs a simple reachability check by sending an SOA query. +func (m *UpstreamManager) pingUpstream(upstream *UpstreamInstance) bool { + client := upstream.Client + if client == nil { + return false + } + + msg := new(dns.Msg) + msg.SetQuestion(".", dns.TypeSOA) + msg.RecursionDesired = true + + _, _, err := client.Exchange(msg, upstream.Addr) + return err == nil +} + +// ListUpstreams returns a snapshot of all upstream instances. +func (m *UpstreamManager) ListUpstreams() []*UpstreamInstance { + m.mu.RLock() + defer m.mu.RUnlock() + + instances := make([]*UpstreamInstance, 0, len(m.upstreams)) + for _, u := range m.upstreams { + instances = append(instances, u) + } + return instances +} diff --git a/core/dns/upstream_stub.go b/core/dns/upstream_stub.go new file mode 100644 index 00000000..efaecb32 --- /dev/null +++ b/core/dns/upstream_stub.go @@ -0,0 +1,741 @@ +package dns + +import ( + "context" + "fmt" + "log" + "net" + "syscall" + "time" + + "github.com/miekg/dns" +) + +// ProxyAddrResolver is a function type that resolves a proxy tag to a +// SOCKS5/HTTP proxy address. This allows external code (e.g., v2rayA's +// process manager) to provide the proxy address lookup logic. +// Returns the proxy address (e.g., "127.0.0.1:1080") or empty string +// if the tag is unknown. +type ProxyAddrResolver func(proxyTag string) string + +// SetProxyAddrResolver sets the proxy address resolver function. +// This is used by exchangeViaProxy to determine how to route DNS +// queries through a specific proxy channel. +func (m *UpstreamManager) SetProxyAddrResolver(resolver ProxyAddrResolver) { + m.mu.Lock() + defer m.mu.Unlock() + m.proxyAddrResolver = resolver +} + +// SetDispatcher sets the xray-core routing dispatcher for internal routing. +// When set, proxy-tagged upstreams use xray-core's internal routing +// instead of external SOCKS5 proxy (like xray-core's traditional DNS module). +func (m *UpstreamManager) SetDispatcher(d RouteDispatcher) { + m.mu.Lock() + defer m.mu.Unlock() + m.dispatcher = d +} + +// Exchange sends a DNS query to the specified upstream server via UDP or TCP +// and returns the parsed response. This is a concrete implementation of the +// upstream query mechanism. +// +// The method: +// 1. Constructs a dns.Msg from the DnsQuery. +// 2. Adds EDNS0 Client Subnet (ECS) option if client IP is available. +// 3. Sets the DNSSEC OK (DO) bit for DNSSEC-aware upstreams. +// 4. Selects the transport protocol (udp/tcp) from the upstream config. +// 5. If xray-core dispatcher is available, ALWAYS uses it to prevent DNS loop: +// - Without dispatcher: direct UDP/TCP query hits iptables --dport 53 redirect +// → gets sent back to DNS module → infinite loop +// - With dispatcher: xray outbound has sockopt.mark=0x80, iptables sees the +// 0x80 mark and skips redirect (TP_OUT/DNS_MARK chains RETURN on 0x80/0x80) +// 6. If the upstream has a non-empty, non-"direct" ProxyTag without dispatcher, +// routes through external SOCKS5 proxy. +// 7. Otherwise, sends directly via UDP/TCP. +// 8. Sends the query and measures round-trip time. +// 9. If UDP response is truncated, automatically falls back to TCP. +// 10. On failure, retries once after a short delay. +// 11. Wraps the response into DnsResponse. +func (m *UpstreamManager) Exchange(upstream *UpstreamInstance, query *DnsQuery) (*DnsResponse, error) { + if upstream == nil { + return nil, nil + } + + // Route through proxy if a proxy channel is specified — use dispatcher or SOCKS5. + if upstream.ProxyTag != "" && upstream.ProxyTag != "direct" { + if m.dispatcher != nil { + return m.exchangeViaDispatcher(upstream, query) + } + return m.exchangeViaProxy(upstream, query) + } + + // Direct upstream: use direct UDP/TCP with SO_MARK=0x80 on the socket. + // This prevents the iptables DNS redirect loop: + // - DNS_MARK chain checks 0x80/0x80 → RETURN (skip) + // - No 0x40 mark set, so ip rule fwmark 0x40/0xc0 doesn't match + // - Packet goes out normally, no redirect to :52353 + return m.exchangeDirect(upstream, query) +} + +// exchangeDirect sends a DNS query directly via UDP/TCP with SO_MARK=0x80 set +// on the socket. The 0x80 mark tells iptables to skip redirect (loop protection). +func (m *UpstreamManager) exchangeDirect(upstream *UpstreamInstance, query *DnsQuery) (*DnsResponse, error) { + if upstream == nil { + return nil, nil + } + + // Build the DNS query message. + msg := new(dns.Msg) + msg.SetQuestion(dns.Fqdn(query.Name), uint16(query.QType)) + msg.RecursionDesired = true + + if query.ClientIP != nil { + builder := NewResponseBuilder() + builder.AddECSSubnet(msg, query.ClientIP) + } + msg.SetEdns0(4096, true) + + protocol := upstream.Protocol + if protocol == "" { + protocol = "udp" + } + + log.Printf("[dns upstream] exchange direct: %s %s → %s (%s)", + dns.Type(uint16(query.QType)).String(), query.Name, upstream.Addr, protocol) + + // Create DNS client with SO_MARK=0x80 on all sockets. + // The Control function sets the socket mark to 0x80, which iptables + // DNS_MARK/TP_OUT chains check and RETURN (skip), preventing the loop. + markFd := func(network, address string, c syscall.RawConn) error { + return c.Control(func(fd uintptr) { + syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, 36, 0x80) // SO_MARK=36 + }) + } + + client := &dns.Client{ + Net: protocol, + Timeout: 5 * time.Second, + ReadTimeout: 5 * time.Second, + WriteTimeout: 5 * time.Second, + Dialer: &net.Dialer{ + Timeout: 5 * time.Second, + Control: markFd, + }, + } + + // Attempt the exchange with retry logic. + var resp *dns.Msg + var rtt time.Duration + var err error + + for attempt := 0; attempt < 2; attempt++ { + if attempt > 0 { + log.Printf("[dns upstream] retry %d: %s %s → %s", attempt+1, + dns.Type(uint16(query.QType)).String(), query.Name, upstream.Addr) + time.Sleep(100 * time.Millisecond) + } + + if protocol == "udp" { + resp, rtt, err = m.exchangeUDPWithMark(client, msg, upstream.Addr) + } else { + resp, rtt, err = client.Exchange(msg, upstream.Addr) + } + + if err != nil { + log.Printf("[dns upstream] attempt %d error: %s %s → %s: %v", attempt+1, + dns.Type(uint16(query.QType)).String(), query.Name, upstream.Addr, err) + continue + } + + // Handle UDP truncation → TCP fallback. + if resp != nil && resp.Truncated && protocol == "udp" { + log.Printf("[dns upstream] truncated response, falling back to TCP: %s %s → %s", + dns.Type(uint16(query.QType)).String(), query.Name, upstream.Addr) + + tcpClient := &dns.Client{ + Net: "tcp", + Timeout: 5 * time.Second, + Dialer: &net.Dialer{ + Timeout: 5 * time.Second, + Control: markFd, + }, + } + resp, rtt, err = tcpClient.Exchange(msg, upstream.Addr) + if err != nil { + log.Printf("[dns upstream] TCP fallback error (attempt %d): %s %s → %s: %v", attempt+1, + dns.Type(uint16(query.QType)).String(), query.Name, upstream.Addr, err) + continue + } + } + + break + } + + if err != nil { + return nil, fmt.Errorf("dns upstream: exchange failed: %w", err) + } + + if resp == nil { + return nil, nil + } + + if err := ValidateResponse(resp); err != nil { + return nil, fmt.Errorf("dns upstream: invalid response: %w", err) + } + if err := ValidateQuestionMatch(resp, query.Name, query.QType); err != nil { + return nil, fmt.Errorf("dns upstream: question mismatch: %w", err) + } + + var ttl uint32 + if len(resp.Answer) > 0 { + ttl = resp.Answer[0].Header().Ttl + for _, rr := range resp.Answer[1:] { + if rr.Header().Ttl < ttl { + ttl = rr.Header().Ttl + } + } + } + + dnsResp := &DnsResponse{ + Query: *query, + RawMsg: resp, + Rcode: resp.Rcode, + Answer: resp.Answer, + Authority: resp.Ns, + Additional: resp.Extra, + TTL: ttl, + Upstream: upstream.Addr, + ProxyTag: upstream.ProxyTag, + RTT: rtt, + Cached: false, + } + + log.Printf("[dns upstream] direct response: %s %s → %s (rcode=%d, rtt=%v, answers=%d)", + dns.Type(uint16(query.QType)).String(), query.Name, upstream.Addr, + resp.Rcode, rtt, len(resp.Answer)) + + return dnsResp, nil +} + +// exchangeUDPWithMark sends a DNS query over UDP with SO_MARK=0x80 set on the socket. +// miekg/dns.Client.Exchange for UDP doesn't use the Dialer.Control function, +// so we create the UDP socket manually to set the socket mark. +func (m *UpstreamManager) exchangeUDPWithMark(client *dns.Client, msg *dns.Msg, addr string) (*dns.Msg, time.Duration, error) { + // Resolve UDP address + udpAddr, err := net.ResolveUDPAddr("udp", addr) + if err != nil { + return nil, 0, fmt.Errorf("resolve udp: %w", err) + } + + // Create UDP connection with SO_MARK=0x80 + conn, err := net.DialUDP("udp", nil, udpAddr) + if err != nil { + return nil, 0, fmt.Errorf("dial udp: %w", err) + } + defer conn.Close() + + // Set SO_MARK on the UDP socket + rawConn, err := conn.SyscallConn() + if err != nil { + return nil, 0, fmt.Errorf("get raw conn: %w", err) + } + rawConn.Control(func(fd uintptr) { + syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, 36, 0x80) + }) + + // Pack and send the DNS query + packed, err := msg.Pack() + if err != nil { + return nil, 0, fmt.Errorf("dns pack: %w", err) + } + + start := time.Now() + + if _, err := conn.Write(packed); err != nil { + return nil, 0, fmt.Errorf("dns write: %w", err) + } + + // Read response + respBuf := make([]byte, dns.DefaultMsgSize) + conn.SetReadDeadline(time.Now().Add(client.ReadTimeout)) + n, err := conn.Read(respBuf) + rtt := time.Since(start) + if err != nil { + return nil, rtt, fmt.Errorf("dns read: %w", err) + } + + // Unpack response + resp := new(dns.Msg) + if err := resp.Unpack(respBuf[:n]); err != nil { + return nil, rtt, fmt.Errorf("dns unpack: %w", err) + } + + return resp, rtt, nil +} + +// exchangeViaProxy sends a DNS query through a proxy channel. +// It uses the configured ProxyAddrResolver to find the SOCKS5/HTTP proxy +// address for the given proxy tag, then sends the DNS query over TCP +// through that proxy. +// +// This is a simplified implementation that: +// 1. Resolves the proxy tag to a SOCKS5 proxy address. +// 2. Establishes a TCP connection through the SOCKS5 proxy. +// 3. Sends the DNS query over TCP (DNS over TCP is required for proxy). +// 4. Reads and parses the response. +// 5. Falls back to direct connection if no proxy address is available. +func (m *UpstreamManager) exchangeViaProxy(upstream *UpstreamInstance, query *DnsQuery) (*DnsResponse, error) { + if upstream == nil { + return nil, nil + } + + log.Printf("[dns upstream] exchange via proxy: %s %s → %s (proxyTag=%s)", + dns.Type(uint16(query.QType)).String(), query.Name, upstream.Addr, upstream.ProxyTag) + + // Get the proxy address for the configured tag. + proxyAddr := m.resolveProxyAddr(upstream.ProxyTag) + if proxyAddr == "" { + log.Printf("[dns upstream] no proxy address for tag %q, falling back to direct", upstream.ProxyTag) + // Fallback: create a temporary upstream with ProxyTag="direct" and retry + directUpstream := &UpstreamInstance{ + Addr: upstream.Addr, + Protocol: "tcp", + ProxyTag: "direct", + Client: m.getClientForProtocol(upstream, "tcp"), + } + return m.Exchange(directUpstream, query) + } + + // Build DNS query message. + msg := new(dns.Msg) + msg.SetQuestion(dns.Fqdn(query.Name), uint16(query.QType)) + msg.RecursionDesired = true + + if query.ClientIP != nil { + builder := NewResponseBuilder() + builder.AddECSSubnet(msg, query.ClientIP) + } + msg.SetEdns0(4096, true) + + // Exchange via SOCKS5 proxy (DNS over TCP). + start := time.Now() + resp, err := m.exchangeViaSocks5(proxyAddr, upstream.Addr, msg) + rtt := time.Since(start) + + if err != nil { + log.Printf("[dns upstream] proxy exchange error: %s %s → %s via %s: %v", + dns.Type(uint16(query.QType)).String(), query.Name, upstream.Addr, proxyAddr, err) + + // Retry once + time.Sleep(100 * time.Millisecond) + start = time.Now() + resp, err = m.exchangeViaSocks5(proxyAddr, upstream.Addr, msg) + rtt = time.Since(start) + + if err != nil { + log.Printf("[dns upstream] proxy exchange retry failed: %s %s → %s via %s: %v", + dns.Type(uint16(query.QType)).String(), query.Name, upstream.Addr, proxyAddr, err) + return nil, fmt.Errorf("dns upstream: proxy exchange failed: %w", err) + } + } + + if resp == nil { + log.Printf("[dns upstream] empty proxy response: %s %s → %s", + dns.Type(uint16(query.QType)).String(), query.Name, upstream.Addr) + return nil, nil + } + + // Validate response. + if err := ValidateResponse(resp); err != nil { + return nil, fmt.Errorf("dns upstream: invalid proxy response: %w", err) + } + if err := ValidateQuestionMatch(resp, query.Name, query.QType); err != nil { + return nil, fmt.Errorf("dns upstream: proxy question mismatch: %w", err) + } + + // Calculate TTL. + var ttl uint32 + if len(resp.Answer) > 0 { + ttl = resp.Answer[0].Header().Ttl + for _, rr := range resp.Answer[1:] { + if rr.Header().Ttl < ttl { + ttl = rr.Header().Ttl + } + } + } + + dnsResp := &DnsResponse{ + Query: *query, + RawMsg: resp, + Rcode: resp.Rcode, + Answer: resp.Answer, + Authority: resp.Ns, + Additional: resp.Extra, + TTL: ttl, + Upstream: upstream.Addr, + ProxyTag: upstream.ProxyTag, + RTT: rtt, + Cached: false, + } + + log.Printf("[dns upstream] proxy response: %s %s → %s via %s (rcode=%d, rtt=%v, answers=%d)", + dns.Type(uint16(query.QType)).String(), query.Name, upstream.Addr, proxyAddr, + resp.Rcode, rtt, len(resp.Answer)) + + return dnsResp, nil +} + +// exchangeViaSocks5 sends a DNS query through a SOCKS5 proxy using TCP. +// It implements the SOCKS5 protocol to establish a connection through +// the proxy, then sends the DNS query over TCP. +func (m *UpstreamManager) exchangeViaSocks5(proxyAddr, targetAddr string, msg *dns.Msg) (*dns.Msg, error) { + // Establish TCP connection to the SOCKS5 proxy. + conn, err := net.DialTimeout("tcp", proxyAddr, 5*time.Second) + if err != nil { + return nil, fmt.Errorf("socks5 dial: %w", err) + } + defer conn.Close() + + // SOCKS5 handshake: send greeting (no auth) + _, err = conn.Write([]byte{0x05, 0x01, 0x00}) + if err != nil { + return nil, fmt.Errorf("socks5 greeting: %w", err) + } + + // Read server response + buf := make([]byte, 2) + if _, err := conn.Read(buf); err != nil { + return nil, fmt.Errorf("socks5 greeting response: %w", err) + } + if buf[0] != 0x05 { + return nil, fmt.Errorf("socks5: invalid version: %d", buf[0]) + } + + // Parse target host and port for SOCKS5 request. + host, portStr, err := net.SplitHostPort(targetAddr) + if err != nil { + host = targetAddr + portStr = "53" + } + port := 53 + if p, err := net.LookupPort("tcp", portStr); err == nil { + port = p + } + + // Build SOCKS5 connect request (ATYP: 0x01 for IPv4, 0x03 for domain) + var req []byte + ip := net.ParseIP(host) + if ip != nil { + if ip4 := ip.To4(); ip4 != nil { + // IPv4 + req = []byte{0x05, 0x01, 0x00, 0x01} + req = append(req, ip4...) + } else { + // IPv6 + req = []byte{0x05, 0x01, 0x00, 0x04} + req = append(req, ip.To16()...) + } + } else { + // Domain name + req = []byte{0x05, 0x01, 0x00, 0x03} + req = append(req, byte(len(host))) + req = append(req, []byte(host)...) + } + req = append(req, byte(port>>8), byte(port)) + + if _, err := conn.Write(req); err != nil { + return nil, fmt.Errorf("socks5 connect request: %w", err) + } + + // Read SOCKS5 response + respBuf := make([]byte, 256) + n, err := conn.Read(respBuf) + if err != nil { + return nil, fmt.Errorf("socks5 connect response: %w", err) + } + if n < 2 || respBuf[0] != 0x05 || respBuf[1] != 0x00 { + return nil, fmt.Errorf("socks5 connect failed: version=%d status=%d", respBuf[0], respBuf[1]) + } + + // DNS over TCP: prepend length prefix. + packed, err := msg.Pack() + if err != nil { + return nil, fmt.Errorf("dns pack: %w", err) + } + + tcpMsg := make([]byte, 2+len(packed)) + tcpMsg[0] = byte(len(packed) >> 8) + tcpMsg[1] = byte(len(packed)) + copy(tcpMsg[2:], packed) + + // Send DNS query. + conn.SetWriteDeadline(time.Now().Add(5 * time.Second)) + if _, err := conn.Write(tcpMsg); err != nil { + return nil, fmt.Errorf("dns write via socks5: %w", err) + } + + // Read DNS response (TCP length-prefixed). + conn.SetReadDeadline(time.Now().Add(5 * time.Second)) + + // Read the 2-byte length prefix. + if _, err := conn.Read(tcpMsg[:2]); err != nil { + return nil, fmt.Errorf("dns read length via socks5: %w", err) + } + respLen := int(tcpMsg[0])<<8 | int(tcpMsg[1]) + if respLen < 0 || respLen > 65535 { + return nil, fmt.Errorf("dns invalid response length: %d", respLen) + } + + // Read the full DNS response. + respData := make([]byte, respLen) + totalRead := 0 + for totalRead < respLen { + n, err := conn.Read(respData[totalRead:]) + if err != nil { + return nil, fmt.Errorf("dns read data via socks5: %w", err) + } + totalRead += n + } + + // Unpack the DNS response. + dnsResp := new(dns.Msg) + if err := dnsResp.Unpack(respData); err != nil { + return nil, fmt.Errorf("dns unpack: %w", err) + } + + return dnsResp, nil +} + +// resolveProxyAddr resolves a proxy tag to a SOCKS5 proxy address. +// It first checks the configured ProxyAddrResolver, then falls back +// to known defaults for well-known tags. +func (m *UpstreamManager) resolveProxyAddr(proxyTag string) string { + m.mu.RLock() + resolver := m.proxyAddrResolver + m.mu.RUnlock() + + if resolver != nil { + if addr := resolver(proxyTag); addr != "" { + return addr + } + } + + // Fallback: check well-known default proxy addresses. + // These can be overridden by the resolver. + switch proxyTag { + case "proxy": + return "127.0.0.1:1080" // Common SOCKS5 proxy port + } + + return "" +} + +// exchangeWithProtocol sends a DNS query using the specified protocol and +// returns the response, round-trip time, and any error. +func (m *UpstreamManager) exchangeWithProtocol(upstream *UpstreamInstance, msg *dns.Msg, protocol string) (*dns.Msg, time.Duration, error) { + // Create or reuse the DNS client for the specified protocol. + client := m.getClientForProtocol(upstream, protocol) + if client == nil { + return nil, 0, fmt.Errorf("failed to create DNS client for %s", protocol) + } + + // Use a context with timeout for the exchange. + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + resp, rtt, err := client.ExchangeContext(ctx, msg, upstream.Addr) + if err != nil { + return resp, rtt, err + } + + return resp, rtt, nil +} + +// getClientForProtocol returns a DNS client configured for the given protocol. +// It reuses the upstream's client if the protocol matches; otherwise, it creates +// a new client for the requested protocol. +func (m *UpstreamManager) getClientForProtocol(upstream *UpstreamInstance, protocol string) *dns.Client { + // If the upstream already has a client with the matching protocol, reuse it. + if upstream.Client != nil && upstream.Client.Net == protocol { + return upstream.Client + } + + // Create a new client for the requested protocol. + return &dns.Client{ + Net: protocol, + Timeout: 5 * time.Second, + ReadTimeout: 5 * time.Second, + WriteTimeout: 5 * time.Second, + } +} + +// ExchangeRaw sends a raw *dns.Msg to the upstream and returns the raw response. +// This is used for cases where the caller needs low-level access to the DNS +// message without DnsQuery/DnsResponse wrapping. +func (m *UpstreamManager) ExchangeRaw(upstream *UpstreamInstance, msg *dns.Msg) (*dns.Msg, time.Duration, error) { + if upstream == nil { + return nil, 0, fmt.Errorf("dns upstream: nil upstream") + } + if msg == nil { + return nil, 0, fmt.Errorf("dns upstream: nil message") + } + + protocol := upstream.Protocol + if protocol == "" { + protocol = "udp" + } + + client := m.getClientForProtocol(upstream, protocol) + + resp, rtt, err := client.Exchange(msg, upstream.Addr) + if err != nil { + return nil, rtt, fmt.Errorf("dns upstream: exchange raw: %w", err) + } + + // Handle UDP truncation → TCP fallback. + if resp != nil && resp.Truncated && protocol == "udp" { + log.Printf("[dns upstream] truncated raw response, falling back to TCP: %s", + upstream.Addr) + + tcpClient := m.getClientForProtocol(upstream, "tcp") + resp, rtt, err = tcpClient.Exchange(msg, upstream.Addr) + if err != nil { + return nil, rtt, fmt.Errorf("dns upstream: exchange raw tcp fallback: %w", err) + } + } + + return resp, rtt, nil +} + +// exchangeViaDispatcher sends a DNS query through xray-core's internal routing +// dispatcher. It uses the RouteDispatcher to create a connection through +// xray-core's routing engine (like xray-core's traditional DNS module does), +// then performs DNS-over-TCP on that connection. +// +// This replaces the external SOCKS5 proxy approach with v2raya-core's built-in +// routing logic, supporting any outbound type (VMESS, VLESS, Trojan, etc.). +func (m *UpstreamManager) exchangeViaDispatcher(upstream *UpstreamInstance, query *DnsQuery) (*DnsResponse, error) { + if upstream == nil || m.dispatcher == nil { + return nil, nil + } + + log.Printf("[dns upstream] exchange via xray routing: %s %s → %s (proxyTag=%s)", + dns.Type(uint16(query.QType)).String(), query.Name, upstream.Addr, upstream.ProxyTag) + + // Build DNS query message. + msg := new(dns.Msg) + msg.SetQuestion(dns.Fqdn(query.Name), uint16(query.QType)) + msg.RecursionDesired = true + + if query.ClientIP != nil { + builder := NewResponseBuilder() + builder.AddECSSubnet(msg, query.ClientIP) + } + msg.SetEdns0(4096, true) + + // Pack DNS query for TCP transport. + packed, err := msg.Pack() + if err != nil { + return nil, fmt.Errorf("dns pack: %w", err) + } + + // Dispatch through xray-core's routing via TCP. + // The proxyTag is passed to the dispatcher, which sets session.ContextWithInbound + // internally (like xray-core's DNS module), so xray's routing engine + // determines the outbound based on routing rules. + start := time.Now() + conn, err := m.dispatcher.Dispatch(context.Background(), "tcp", upstream.Addr, upstream.ProxyTag) + if err != nil { + log.Printf("[dns upstream] dispatcher error: %s %s → %s: %v", + dns.Type(uint16(query.QType)).String(), query.Name, upstream.Addr, err) + + // Retry once + time.Sleep(100 * time.Millisecond) + conn, err = m.dispatcher.Dispatch(context.Background(), "tcp", upstream.Addr, upstream.ProxyTag) + if err != nil { + return nil, fmt.Errorf("dns upstream: dispatcher retry failed: %w", err) + } + } + defer conn.Close() + + // DNS over TCP: prepend 2-byte length prefix. + tcpMsg := make([]byte, 2+len(packed)) + tcpMsg[0] = byte(len(packed) >> 8) + tcpMsg[1] = byte(len(packed)) + copy(tcpMsg[2:], packed) + + // Send DNS query. + conn.SetWriteDeadline(time.Now().Add(5 * time.Second)) + if _, err := conn.Write(tcpMsg); err != nil { + return nil, fmt.Errorf("dns write via dispatcher: %w", err) + } + + // Read 2-byte length prefix. + conn.SetReadDeadline(time.Now().Add(5 * time.Second)) + if _, err := conn.Read(tcpMsg[:2]); err != nil { + return nil, fmt.Errorf("dns read length via dispatcher: %w", err) + } + respLen := int(tcpMsg[0])<<8 | int(tcpMsg[1]) + if respLen < 0 || respLen > 65535 { + return nil, fmt.Errorf("dns invalid response length: %d", respLen) + } + + // Read full DNS response. + respData := make([]byte, respLen) + totalRead := 0 + for totalRead < respLen { + n, err := conn.Read(respData[totalRead:]) + if err != nil { + return nil, fmt.Errorf("dns read data via dispatcher: %w", err) + } + totalRead += n + } + + rtt := time.Since(start) + + // Unpack DNS response. + dnsResp := new(dns.Msg) + if err := dnsResp.Unpack(respData); err != nil { + return nil, fmt.Errorf("dns unpack: %w", err) + } + + // Validate response. + if err := ValidateResponse(dnsResp); err != nil { + return nil, fmt.Errorf("dns upstream: invalid dispatcher response: %w", err) + } + if err := ValidateQuestionMatch(dnsResp, query.Name, query.QType); err != nil { + return nil, fmt.Errorf("dns upstream: dispatcher question mismatch: %w", err) + } + + // Calculate TTL. + var ttl uint32 + if len(dnsResp.Answer) > 0 { + ttl = dnsResp.Answer[0].Header().Ttl + for _, rr := range dnsResp.Answer[1:] { + if rr.Header().Ttl < ttl { + ttl = rr.Header().Ttl + } + } + } + + resp := &DnsResponse{ + Query: *query, + RawMsg: dnsResp, + Rcode: dnsResp.Rcode, + Answer: dnsResp.Answer, + Authority: dnsResp.Ns, + Additional: dnsResp.Extra, + TTL: ttl, + Upstream: upstream.Addr, + ProxyTag: upstream.ProxyTag, + RTT: rtt, + Cached: false, + } + + log.Printf("[dns upstream] dispatcher response: %s %s → %s (rcode=%d, rtt=%v, answers=%d)", + dns.Type(uint16(query.QType)).String(), query.Name, upstream.Addr, + dnsResp.Rcode, rtt, len(dnsResp.Answer)) + + return resp, nil +} diff --git a/core/dns/upstream_test.go b/core/dns/upstream_test.go new file mode 100644 index 00000000..20133bad --- /dev/null +++ b/core/dns/upstream_test.go @@ -0,0 +1,746 @@ +package dns + +import ( + "fmt" + "testing" + "time" + + "github.com/miekg/dns" +) + +// --- Helper functions --- + +func newTestUpstreamConfig(id, addr, proxyTag string) UpstreamConfig { + return UpstreamConfig{ + ID: id, + Addr: addr, + Protocol: "udp", + ProxyTag: proxyTag, + } +} + +func newTestUpstreamInstance(id, addr, proxyTag string) *UpstreamInstance { + proxy := proxyTag + if proxy == "" { + proxy = "direct" + } + return &UpstreamInstance{ + ID: id, + Addr: addr, + Protocol: "udp", + ProxyTag: proxy, + Healthy: true, + Client: &dns.Client{ + Net: "udp", + Timeout: 5 * time.Second, + ReadTimeout: 5 * time.Second, + WriteTimeout: 5 * time.Second, + }, + } +} + +// --- Test: BuildUpstreamKey --- + +func TestBuildUpstreamKey(t *testing.T) { + tests := []struct { + addr string + proxyTag string + expected string + }{ + {"8.8.8.8:53", "", "8.8.8.8:53|"}, + {"8.8.8.8:53", "direct", "8.8.8.8:53|direct"}, + {"8.8.8.8:53", "proxy", "8.8.8.8:53|proxy"}, + {"1.1.1.1:53", "proxy", "1.1.1.1:53|proxy"}, + {"8.8.8.8:53", "my-custom-tag", "8.8.8.8:53|my-custom-tag"}, + } + + for _, tt := range tests { + t.Run(fmt.Sprintf("%s|%s", tt.addr, tt.proxyTag), func(t *testing.T) { + got := BuildUpstreamKey(tt.addr, tt.proxyTag) + if got != tt.expected { + t.Errorf("BuildUpstreamKey(%q, %q) = %q, want %q", + tt.addr, tt.proxyTag, got, tt.expected) + } + }) + } +} + +// --- Test: UpstreamInstance.CompositeKey --- + +func TestUpstreamInstanceCompositeKey(t *testing.T) { + instance := newTestUpstreamInstance("google", "8.8.8.8:53", "proxy") + expected := "8.8.8.8:53|proxy" + if got := instance.CompositeKey(); got != expected { + t.Errorf("CompositeKey() = %q, want %q", got, expected) + } +} + +// --- Test: NewUpstreamManager with multi-channel --- + +func TestNewUpstreamManagerMultiChannel(t *testing.T) { + // Same address, different proxy tags should create separate instances. + configs := []UpstreamConfig{ + newTestUpstreamConfig("google-direct", "8.8.8.8:53", "direct"), + newTestUpstreamConfig("google-proxy", "8.8.8.8:53", "proxy"), + } + + mgr := NewUpstreamManager(configs) + + // Verify both instances exist and are separate. + directKey := BuildUpstreamKey("8.8.8.8:53", "direct") + proxyKey := BuildUpstreamKey("8.8.8.8:53", "proxy") + + directInstance, ok := mgr.GetUpstreamByKey(directKey) + if !ok { + t.Fatal("expected direct upstream instance") + } + if directInstance.ProxyTag != "direct" { + t.Errorf("expected ProxyTag=direct, got %s", directInstance.ProxyTag) + } + + proxyInstance, ok := mgr.GetUpstreamByKey(proxyKey) + if !ok { + t.Fatal("expected proxy upstream instance") + } + if proxyInstance.ProxyTag != "proxy" { + t.Errorf("expected ProxyTag=proxy, got %s", proxyInstance.ProxyTag) + } + + // They should be different instances (different pointers). + if directInstance == proxyInstance { + t.Error("direct and proxy instances should be different objects") + } + + // They should have the same address. + if directInstance.Addr != proxyInstance.Addr { + t.Errorf("expected same addr, got %q vs %q", directInstance.Addr, proxyInstance.Addr) + } +} + +func TestNewUpstreamManagerSingleChannel(t *testing.T) { + // Single upstream without proxy tag should work as before. + configs := []UpstreamConfig{ + newTestUpstreamConfig("google", "8.8.8.8:53", ""), + } + + mgr := NewUpstreamManager(configs) + + key := BuildUpstreamKey("8.8.8.8:53", "direct") + instance, ok := mgr.GetUpstreamByKey(key) + if !ok { + t.Fatal("expected upstream instance") + } + if instance.ProxyTag != "direct" { + t.Errorf("expected default ProxyTag=direct, got %s", instance.ProxyTag) + } + if instance.ID != "google" { + t.Errorf("expected ID=google, got %s", instance.ID) + } +} + +// --- Test: GetUpstream backward compatibility --- + +func TestGetUpstreamByID(t *testing.T) { + configs := []UpstreamConfig{ + newTestUpstreamConfig("google", "8.8.8.8:53", "direct"), + newTestUpstreamConfig("cloudflare", "1.1.1.1:53", ""), + } + + mgr := NewUpstreamManager(configs) + + // Get by ID should work. + instance, ok := mgr.GetUpstream("google") + if !ok { + t.Fatal("expected to find upstream by ID 'google'") + } + if instance.Addr != "8.8.8.8:53" { + t.Errorf("expected addr 8.8.8.8:53, got %s", instance.Addr) + } + + instance, ok = mgr.GetUpstream("cloudflare") + if !ok { + t.Fatal("expected to find upstream by ID 'cloudflare'") + } + if instance.Addr != "1.1.1.1:53" { + t.Errorf("expected addr 1.1.1.1:53, got %s", instance.Addr) + } + + // Non-existent ID should return false. + _, ok = mgr.GetUpstream("nonexistent") + if ok { + t.Error("expected false for nonexistent ID") + } +} + +// --- Test: GetOrCreateUpstream --- + +func TestGetOrCreateUpstreamNew(t *testing.T) { + mgr := NewUpstreamManager(nil) // Empty manager + + // Create a new upstream instance. + config := newTestUpstreamConfig("google", "8.8.8.8:53", "proxy") + instance := mgr.GetOrCreateUpstream(config) + + if instance == nil { + t.Fatal("expected non-nil instance") + } + if instance.ID != "google" { + t.Errorf("expected ID=google, got %s", instance.ID) + } + if instance.ProxyTag != "proxy" { + t.Errorf("expected ProxyTag=proxy, got %s", instance.ProxyTag) + } + if !instance.Healthy { + t.Error("expected new instance to be healthy") + } +} + +func TestGetOrCreateUpstreamExisting(t *testing.T) { + configs := []UpstreamConfig{ + newTestUpstreamConfig("google", "8.8.8.8:53", "proxy"), + } + mgr := NewUpstreamManager(configs) + + // Get existing instance. + config := newTestUpstreamConfig("google", "8.8.8.8:53", "proxy") + instance := mgr.GetOrCreateUpstream(config) + + if instance == nil { + t.Fatal("expected non-nil instance") + } + if instance.ID != "google" { + t.Errorf("expected ID=google, got %s", instance.ID) + } + + // Getting again should return the same instance (same pointer). + instance2 := mgr.GetOrCreateUpstream(config) + if instance != instance2 { + t.Error("GetOrCreateUpstream should return the same instance for the same config") + } +} + +func TestGetOrCreateUpstreamDifferentChannels(t *testing.T) { + mgr := NewUpstreamManager(nil) + + // Create instances for same address but different proxy tags. + directConfig := newTestUpstreamConfig("google-direct", "8.8.8.8:53", "direct") + proxyConfig := newTestUpstreamConfig("google-proxy", "8.8.8.8:53", "proxy") + + directInstance := mgr.GetOrCreateUpstream(directConfig) + proxyInstance := mgr.GetOrCreateUpstream(proxyConfig) + + if directInstance == proxyInstance { + t.Error("direct and proxy instances should be different") + } + + if directInstance.ProxyTag != "direct" { + t.Errorf("expected direct ProxyTag, got %s", directInstance.ProxyTag) + } + if proxyInstance.ProxyTag != "proxy" { + t.Errorf("expected proxy ProxyTag, got %s", proxyInstance.ProxyTag) + } +} + +// --- Test: Multi-channel cache isolation --- +// CacheKey already contains ProxyTag (verified in cache_test.go). +// These tests verify the end-to-end isolation through UpstreamManager. + +func TestMultiChannelUpstreamIsolation(t *testing.T) { + // Create an upstream manager with multi-channel instances. + configs := []UpstreamConfig{ + newTestUpstreamConfig("google-direct", "8.8.8.8:53", "direct"), + newTestUpstreamConfig("google-proxy", "8.8.8.8:53", "proxy"), + } + mgr := NewUpstreamManager(configs) + + // Get instances for different channels. + directKey := BuildUpstreamKey("8.8.8.8:53", "direct") + proxyKey := BuildUpstreamKey("8.8.8.8:53", "proxy") + + directInstance, ok := mgr.GetUpstreamByKey(directKey) + if !ok { + t.Fatal("expected direct instance") + } + proxyInstance, ok := mgr.GetUpstreamByKey(proxyKey) + if !ok { + t.Fatal("expected proxy instance") + } + + // Verify they have different composite keys. + if directInstance.CompositeKey() == proxyInstance.CompositeKey() { + t.Error("instances should have different composite keys") + } + + // Verify they are independently accessible. + _, ok = mgr.GetUpstream("google-direct") + if !ok { + t.Error("expected to find google-direct by ID") + } + _, ok = mgr.GetUpstream("google-proxy") + if !ok { + t.Error("expected to find google-proxy by ID") + } +} + +// --- Test: DnsResponse ProxyTag propagation --- + +func TestDnsResponseProxyTag(t *testing.T) { + // When building a DnsResponse, ProxyTag should be set correctly. + resp := &DnsResponse{ + Query: DnsQuery{ + Name: "example.com", + QType: TypeA, + }, + Rcode: dns.RcodeSuccess, + Upstream: "8.8.8.8:53", + ProxyTag: "proxy", + } + + if resp.ProxyTag != "proxy" { + t.Errorf("expected ProxyTag=proxy, got %s", resp.ProxyTag) + } + + // Direct query. + resp2 := &DnsResponse{ + Query: DnsQuery{ + Name: "example.com", + QType: TypeA, + }, + Rcode: dns.RcodeSuccess, + Upstream: "8.8.8.8:53", + ProxyTag: "direct", + } + + if resp2.ProxyTag != "direct" { + t.Errorf("expected ProxyTag=direct, got %s", resp2.ProxyTag) + } + + // Same upstream, different proxy tags → different responses. + if resp.ProxyTag == resp2.ProxyTag { + t.Error("proxy and direct responses should have different ProxyTags") + } +} + +// --- Test: CacheKey isolation with different ProxyTags --- +// This complements cache_test.go's TestCacheKeyIsolationByProxyTag. + +func TestCacheKeyIsolationMultiChannel(t *testing.T) { + cache := NewDnsCache(newTestCacheConfig()) + + // Create cache keys for same upstream but different proxy channels. + keys := []CacheKey{ + {UpstreamAddr: "8.8.8.8:53", ProxyTag: "direct", Name: "google.com.", QType: TypeA}, + {UpstreamAddr: "8.8.8.8:53", ProxyTag: "proxy", Name: "google.com.", QType: TypeA}, + {UpstreamAddr: "8.8.8.8:53", ProxyTag: "my-proxy", Name: "google.com.", QType: TypeA}, + } + + // Set different responses for each channel. + for i, key := range keys { + resp := newTestDNSResponse("google.com", TypeA, dns.RcodeSuccess, uint32(300+i*100)) + cache.Set(key, resp, uint32(300+i*100)) + } + + // Verify each channel has its own cached entry. + for i, key := range keys { + got, ok := cache.Get(key) + if !ok { + t.Errorf("expected cache hit for key[%d] (proxy=%s)", i, key.ProxyTag) + } else { + if got == nil { + t.Errorf("got nil response for key[%d]", i) + } + } + } + + // Verify cache entries are independent (different TTLs from the Set above). + for i, key := range keys { + if elem, ok := cache.entries[key]; ok { + entry := elem.Value.(*CacheEntry) + expectedTTL := uint32(300 + i*100) + // The effective TTL may be clamped to minTTL, but OriginalTTL should match. + if entry.OriginalTTL != expectedTTL { + t.Errorf("key[%d] (proxy=%s): expected OriginalTTL=%d, got %d", + i, key.ProxyTag, expectedTTL, entry.OriginalTTL) + } + } + } + + // Ensure removing one channel's entry doesn't affect others. + cache.Remove(keys[1]) // Remove proxy channel + if _, ok := cache.Get(keys[1]); ok { + t.Error("expected cache miss for removed key") + } + if _, ok := cache.Get(keys[0]); !ok { + t.Error("expected cache hit for direct channel (should be unaffected)") + } + if _, ok := cache.Get(keys[2]); !ok { + t.Error("expected cache hit for my-proxy channel (should be unaffected)") + } +} + +// --- Test: Multi-channel RouteResult --- + +func TestRouteResultWithProxyTag(t *testing.T) { + // RouteResult should carry the proxy tag. + result := &RouteResult{ + UpstreamID: "google-proxy", + UpstreamAddr: "8.8.8.8:53", + Action: "route", + RuleID: "rule-1", + Policy: "single", + ProxyTag: "proxy", + } + + if result.ProxyTag != "proxy" { + t.Errorf("expected ProxyTag=proxy, got %s", result.ProxyTag) + } + + // Direct route result. + result2 := &RouteResult{ + UpstreamID: "google-direct", + UpstreamAddr: "8.8.8.8:53", + Action: "route", + RuleID: "rule-2", + Policy: "single", + ProxyTag: "direct", + } + + if result2.ProxyTag != "direct" { + t.Errorf("expected ProxyTag=direct, got %s", result2.ProxyTag) + } + + // Same upstream address, different proxy tags. + if result.UpstreamAddr == result2.UpstreamAddr && result.ProxyTag == result2.ProxyTag { + t.Error("different channels should have different RouteResults") + } +} + +// --- Test: HealthCheck isolation --- + +func TestHealthCheckIsolation(t *testing.T) { + configs := []UpstreamConfig{ + newTestUpstreamConfig("google-direct", "8.8.8.8:53", "direct"), + newTestUpstreamConfig("google-proxy", "8.8.8.8:53", "proxy"), + newTestUpstreamConfig("cloudflare-direct", "1.1.1.1:53", "direct"), + } + mgr := NewUpstreamManager(configs) + + // HealthCheck should return results for all instances. + results := mgr.HealthCheck() + if len(results) != 3 { + t.Errorf("expected 3 health check results, got %d", len(results)) + } + + // Each composite key should have its own health result. + directKey := BuildUpstreamKey("8.8.8.8:53", "direct") + proxyKey := BuildUpstreamKey("8.8.8.8:53", "proxy") + cfKey := BuildUpstreamKey("1.1.1.1:53", "direct") + + if _, ok := results[directKey]; !ok { + t.Errorf("expected health result for %s", directKey) + } + if _, ok := results[proxyKey]; !ok { + t.Errorf("expected health result for %s", proxyKey) + } + if _, ok := results[cfKey]; !ok { + t.Errorf("expected health result for %s", cfKey) + } + + // Per-channel health check. + directResults := mgr.HealthCheckByProxyTag("direct") + if len(directResults) != 2 { + t.Errorf("expected 2 direct health results, got %d", len(directResults)) + } + + proxyResults := mgr.HealthCheckByProxyTag("proxy") + if len(proxyResults) != 1 { + t.Errorf("expected 1 proxy health result, got %d", len(proxyResults)) + } +} + +// --- Test: ListUpstreams --- + +func TestListUpstreams(t *testing.T) { + configs := []UpstreamConfig{ + newTestUpstreamConfig("google-direct", "8.8.8.8:53", "direct"), + newTestUpstreamConfig("google-proxy", "8.8.8.8:53", "proxy"), + newTestUpstreamConfig("cloudflare", "1.1.1.1:53", ""), + } + mgr := NewUpstreamManager(configs) + + instances := mgr.ListUpstreams() + if len(instances) != 3 { + t.Errorf("expected 3 instances, got %d", len(instances)) + } + + // Verify we have the expected instances. + foundDirect := false + foundProxy := false + foundCF := false + for _, inst := range instances { + switch inst.ID { + case "google-direct": + foundDirect = true + case "google-proxy": + foundProxy = true + case "cloudflare": + foundCF = true + } + } + if !foundDirect { + t.Error("expected to find google-direct") + } + if !foundProxy { + t.Error("expected to find google-proxy") + } + if !foundCF { + t.Error("expected to find cloudflare") + } +} + +// --- Test: ProxyAddrResolver --- + +func TestProxyAddrResolver(t *testing.T) { + mgr := NewUpstreamManager(nil) + + // No resolver set → should use fallback defaults. + addr := mgr.resolveProxyAddr("unknown-tag") + if addr != "" { + t.Errorf("expected empty for unknown tag, got %s", addr) + } + + // "proxy" tag should use default SOCKS5 address. + addr = mgr.resolveProxyAddr("proxy") + if addr != "127.0.0.1:1080" { + t.Errorf("expected 127.0.0.1:1080 for proxy tag, got %s", addr) + } + + // Set custom resolver. + mgr.SetProxyAddrResolver(func(tag string) string { + switch tag { + case "my-proxy": + return "10.0.0.1:2080" + case "proxy": + return "192.168.1.1:1080" + default: + return "" + } + }) + + // Custom resolver should take precedence. + addr = mgr.resolveProxyAddr("my-proxy") + if addr != "10.0.0.1:2080" { + t.Errorf("expected 10.0.0.1:2080, got %s", addr) + } + + addr = mgr.resolveProxyAddr("proxy") + if addr != "192.168.1.1:1080" { + t.Errorf("expected 192.168.1.1:1080 (resolver override), got %s", addr) + } + + addr = mgr.resolveProxyAddr("unknown") + if addr != "" { + t.Errorf("expected empty for unknown tag with custom resolver, got %s", addr) + } +} + +// --- Test: Exchange routing via proxy --- + +func TestExchangeProxyRouting(t *testing.T) { + // Test the logic that determines whether to route through proxy. + // This tests the routing decision, not the actual network exchange. + + tests := []struct { + name string + proxyTag string + expectViaProxy bool + }{ + {"empty tag = direct", "", false}, + {"direct tag = direct", "direct", false}, + {"proxy tag = via proxy", "proxy", true}, + {"custom tag = via proxy", "my-proxy", true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + upstream := &UpstreamInstance{ + Addr: "8.8.8.8:53", + ProxyTag: tt.proxyTag, + } + + isViaProxy := upstream.ProxyTag != "" && upstream.ProxyTag != "direct" + if isViaProxy != tt.expectViaProxy { + t.Errorf("expected viaProxy=%v for ProxyTag=%q, got %v", + tt.expectViaProxy, tt.proxyTag, isViaProxy) + } + }) + } +} + +// --- Test: concurrent multi-channel operations --- + +func TestConcurrentMultiChannelOperations(t *testing.T) { + mgr := NewUpstreamManager(nil) + + // Concurrently create upstream instances for different channels. + done := make(chan bool, 10) + for i := 0; i < 10; i++ { + go func(idx int) { + proxyTag := fmt.Sprintf("channel-%d", idx) + config := UpstreamConfig{ + ID: fmt.Sprintf("upstream-%d", idx), + Addr: "8.8.8.8:53", + Protocol: "udp", + ProxyTag: proxyTag, + } + instance := mgr.GetOrCreateUpstream(config) + if instance == nil { + t.Errorf("goroutine %d: got nil instance", idx) + } + done <- true + }(i) + } + + // Wait for all goroutines. + for i := 0; i < 10; i++ { + <-done + } + + // Verify all 10 instances were created. + instances := mgr.ListUpstreams() + if len(instances) != 10 { + t.Errorf("expected 10 instances, got %d", len(instances)) + } + + // Verify they're all accessible by composite key. + for i := 0; i < 10; i++ { + proxyTag := fmt.Sprintf("channel-%d", i) + key := BuildUpstreamKey("8.8.8.8:53", proxyTag) + _, ok := mgr.GetUpstreamByKey(key) + if !ok { + t.Errorf("expected to find instance for key %s", key) + } + } +} + +// --- Test: Empty manager --- + +func TestEmptyUpstreamManager(t *testing.T) { + mgr := NewUpstreamManager(nil) + + if mgr == nil { + t.Fatal("NewUpstreamManager(nil) returned nil") + } + + instances := mgr.ListUpstreams() + if len(instances) != 0 { + t.Errorf("expected 0 instances, got %d", len(instances)) + } + + _, ok := mgr.GetUpstream("anything") + if ok { + t.Error("expected false for GetUpstream on empty manager") + } +} + +// --- Test: Multiple channels, same address --- + +func TestSameAddressDifferentChannels(t *testing.T) { + // Multiple proxy channels for the same upstream address. + channels := []string{"direct", "proxy", "proxy-us", "proxy-eu", "proxy-asia"} + configs := make([]UpstreamConfig, len(channels)) + for i, ch := range channels { + configs[i] = UpstreamConfig{ + ID: fmt.Sprintf("google-%s", ch), + Addr: "8.8.8.8:53", + Protocol: "udp", + ProxyTag: ch, + } + } + + mgr := NewUpstreamManager(configs) + + // Verify all channels are separate instances. + for _, ch := range channels { + key := BuildUpstreamKey("8.8.8.8:53", ch) + instance, ok := mgr.GetUpstreamByKey(key) + if !ok { + t.Errorf("expected instance for channel %q", ch) + } else if instance.ProxyTag != ch { + t.Errorf("expected ProxyTag=%q, got %q", ch, instance.ProxyTag) + } + } + + // Verify count. + instances := mgr.ListUpstreams() + if len(instances) != len(channels) { + t.Errorf("expected %d instances, got %d", len(channels), len(instances)) + } +} + +// --- Test: buildCacheKey with different proxy tags --- + +func TestBuildCacheKeyWithProxyTags(t *testing.T) { + query := newTestQuery("example.com", TypeA) + + tests := []struct { + proxyTag string + expectedTag string + }{ + {"direct", "direct"}, + {"proxy", "proxy"}, + {"", "direct"}, // Empty defaults to "direct" + } + + for _, tt := range tests { + t.Run(tt.expectedTag, func(t *testing.T) { + upstream := &UpstreamInstance{ + Addr: "8.8.8.8:53", + ProxyTag: tt.proxyTag, + } + key := buildCacheKey(query, upstream) + if key.ProxyTag != tt.expectedTag { + t.Errorf("expected ProxyTag=%q, got %q", tt.expectedTag, key.ProxyTag) + } + }) + } +} + +// --- Test: Exchange via proxy tag routing (decision only) --- + +func TestExchangeProxyTagRoutingDecision(t *testing.T) { + tests := []struct { + name string + proxyTag string + wantProxy bool + }{ + {"direct connection", "direct", false}, + {"empty proxy tag", "", false}, + {"proxy channel", "proxy", true}, + {"custom channel", "my-proxy", true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + upstream := &UpstreamInstance{ + Addr: "8.8.8.8:53", + Protocol: "udp", + ProxyTag: tt.proxyTag, + Client: &dns.Client{ + Net: "udp", + Timeout: 5 * time.Second, + ReadTimeout: 5 * time.Second, + WriteTimeout: 5 * time.Second, + }, + } + + // The Exchange method checks ProxyTag to decide routing. + shouldProxy := upstream.ProxyTag != "" && upstream.ProxyTag != "direct" + + if shouldProxy != tt.wantProxy { + t.Errorf("Exchange(%q): expected proxy=%v, got proxy=%v", + upstream.ProxyTag, tt.wantProxy, shouldProxy) + } + }) + } +} diff --git a/core/dns/validator.go b/core/dns/validator.go new file mode 100644 index 00000000..aa3bc69e --- /dev/null +++ b/core/dns/validator.go @@ -0,0 +1,158 @@ +package dns + +import ( + "fmt" + + "github.com/miekg/dns" +) + +// ValidateResponse validates a DNS response message for integrity and consistency. +// It checks: +// - Message is not nil +// - Question section is present and valid +// - Response code (RCODE) is a valid value +// - Message is marked as a response (QR bit) +// - Question matches the query (checked externally via ID matching by miekg/dns) +// +// Returns nil if the response is valid, or an error describing the issue. +func ValidateResponse(msg *dns.Msg) error { + if msg == nil { + return fmt.Errorf("dns validator: nil response message") + } + + // Verify the message is a response (QR bit = 1). + if !msg.Response { + return fmt.Errorf("dns validator: message is not a response (QR bit not set)") + } + + // Verify question section is present. + if len(msg.Question) == 0 { + return fmt.Errorf("dns validator: response has no question section") + } + + // Verify question is well-formed. + q := msg.Question[0] + if q.Name == "" { + return fmt.Errorf("dns validator: empty question name") + } + if q.Qtype == 0 { + return fmt.Errorf("dns validator: zero query type in question") + } + if q.Qclass == 0 { + return fmt.Errorf("dns validator: zero query class in question") + } + + // Validate response code (RCODE). + if err := validateRcode(msg.Rcode); err != nil { + return fmt.Errorf("dns validator: %w", err) + } + + // Validate answer section consistency. + for i, rr := range msg.Answer { + if rr == nil { + return fmt.Errorf("dns validator: nil answer record at index %d", i) + } + if rr.Header().Rrtype == 0 { + return fmt.Errorf("dns validator: answer record %d has zero type", i) + } + // Validate record name is non-empty and fully qualified. + if rr.Header().Name == "" { + return fmt.Errorf("dns validator: answer record %d has empty name", i) + } + } + + // Validate authority section. + for i, rr := range msg.Ns { + if rr == nil { + return fmt.Errorf("dns validator: nil authority record at index %d", i) + } + if rr.Header().Rrtype == 0 { + return fmt.Errorf("dns validator: authority record %d has zero type", i) + } + } + + // Validate additional section (excluding OPT pseudo-records which are metadata). + for i, rr := range msg.Extra { + if rr == nil { + return fmt.Errorf("dns validator: nil additional record at index %d", i) + } + if rr.Header().Rrtype == dns.TypeOPT { + // OPT records are valid; skip detailed validation. + continue + } + if rr.Header().Rrtype == 0 { + return fmt.Errorf("dns validator: additional record %d has zero type", i) + } + } + + return nil +} + +// validateRcode checks if the DNS response code (RCODE) is valid. +// Standard RCODEs are 0-15; extended RCODEs may be higher but should be +// checked for known values. +func validateRcode(rcode int) error { + switch rcode { + case dns.RcodeSuccess: // 0 + case dns.RcodeFormatError: // 1 + case dns.RcodeServerFailure: // 2 + case dns.RcodeNameError: // 3 + case dns.RcodeNotImplemented: // 4 + case dns.RcodeRefused: // 5 + case dns.RcodeYXDomain: // 6 + case dns.RcodeYXRrset: // 7 + case dns.RcodeNXRrset: // 8 + case dns.RcodeNotAuth: // 9 + case dns.RcodeNotZone: // 10 + case dns.RcodeBadSig: // 16 (also RcodeBadVers) + case dns.RcodeBadKey: // 17 + case dns.RcodeBadTime: // 18 + case dns.RcodeBadMode: // 19 + case dns.RcodeBadName: // 20 + case dns.RcodeBadAlg: // 21 + case dns.RcodeBadTrunc: // 22 + case dns.RcodeBadCookie: // 23 + default: + // Allow extended RCODEs (higher than 23) as they may be valid + // in specific contexts, but warn about unexpected values. + if rcode < 0 || rcode > 0xFFF { + return fmt.Errorf("invalid rcode %d: out of valid range (0-4095)", rcode) + } + } + return nil +} + +// ValidateAnswerCount checks that the response contains at least one +// answer record when the RCODE is success. +func ValidateAnswerCount(msg *dns.Msg) error { + if msg == nil { + return fmt.Errorf("dns validator: nil message") + } + if msg.Rcode == dns.RcodeSuccess && len(msg.Answer) == 0 { + return fmt.Errorf("dns validator: success response with zero answers") + } + return nil +} + +// ValidateQuestionMatch verifies that the response question matches the +// expected query name and type. This is an additional safety check beyond +// the ID matching that miekg/dns performs internally. +func ValidateQuestionMatch(msg *dns.Msg, expectedName string, expectedQType QueryType) error { + if msg == nil { + return fmt.Errorf("dns validator: nil message") + } + if len(msg.Question) == 0 { + return fmt.Errorf("dns validator: no question in response") + } + + q := msg.Question[0] + if q.Name != dns.Fqdn(expectedName) { + return fmt.Errorf("dns validator: question name mismatch: got %q, expected %q", + q.Name, dns.Fqdn(expectedName)) + } + if q.Qtype != uint16(expectedQType) { + return fmt.Errorf("dns validator: question type mismatch: got %d, expected %d", + q.Qtype, uint16(expectedQType)) + } + return nil +} diff --git a/core/examples/dns-with-socks.json b/core/examples/dns-with-socks.json new file mode 100644 index 00000000..4c7b9e47 --- /dev/null +++ b/core/examples/dns-with-socks.json @@ -0,0 +1,146 @@ +{ + "_comment": "Example config for v2raya-core with standalone DNS module and SOCKS outbound.", + "_note": "DNS 模块是 v2raya-core 的一部分,在 xray-core 启动前独立运行。\n配置中的 'dns_module' 段由 v2raya-core 启动时解析,不经过 xray-core。\niptables/nftables 规则将 53 端口流量重定向到 DNS 模块监听端口 52353。", + + "log": { + "loglevel": "info" + }, + + "inbounds": [ + { + "tag": "socks-in", + "protocol": "socks", + "listen": "127.0.0.1", + "port": 20170, + "settings": { + "udp": true + } + }, + { + "tag": "http-in", + "protocol": "http", + "listen": "127.0.0.1", + "port": 20171 + } + ], + + "outbounds": [ + { + "tag": "proxy", + "protocol": "socks", + "settings": { + "servers": [ + { + "address": "your-socks-server.com", + "port": 1080, + "users": [] + } + ] + }, + "streamSettings": { + "sockopt": { + "mark": 128 + } + } + }, + { + "tag": "direct", + "protocol": "freedom", + "streamSettings": { + "sockopt": { + "mark": 128 + } + } + }, + { + "tag": "block", + "protocol": "blackhole" + } + ], + + "routing": { + "domainStrategy": "IPIfNonMatch", + "rules": [ + { + "type": "field", + "ip": ["geoip:private"], + "outboundTag": "direct" + }, + { + "type": "field", + "domain": ["geosite:cn"], + "outboundTag": "direct" + }, + { + "type": "field", + "port": "0-65535", + "outboundTag": "proxy" + } + ] + }, + + "dns_module": { + "_comment": "DNS 模块配置。v2raya-core 启动时解析此段,启动独立 DNS 监听器。", + "listener": { + "listen_addr": "127.2.0.17:52353", + "timeout": 5 + }, + "cache": { + "enabled": true, + "size": 4096, + "min_ttl": 60, + "max_ttl": 86400, + "prefetch": true, + "prefetch_threshold": 30, + "neg_cache": true + }, + "proxy_map": { + "proxy": "127.0.0.1:20170" + }, + "upstreams": [ + { + "id": "dns-direct", + "addr": "223.5.5.5:53", + "protocol": "udp", + "proxy_tag": "direct" + }, + { + "id": "dns-proxy", + "addr": "8.8.8.8:53", + "protocol": "udp", + "proxy_tag": "proxy" + }, + { + "id": "dns-doh", + "addr": "https://dns.google/dns-query", + "protocol": "https", + "proxy_tag": "proxy" + } + ], + "rules": [ + { + "id": "rule-private", + "domain": ["geosite:private"], + "upstream": "dns-direct", + "action": "route", + "policy": "single" + }, + { + "id": "rule-cn", + "domain": ["geosite:cn"], + "upstream": "dns-direct", + "action": "route", + "policy": "single" + }, + { + "id": "rule-fallback", + "domain_suffix": [], + "domain": [], + "ip": [], + "upstream": "dns-proxy", + "action": "route", + "policy": "single" + } + ] + } +} diff --git a/core/main/dns_module.go b/core/main/dns_module.go new file mode 100644 index 00000000..511296ad --- /dev/null +++ b/core/main/dns_module.go @@ -0,0 +1,184 @@ +// Package main provides DNS module integration for v2raya-core. +// The DNS module starts before xray-core and listens on the configured port (default 52353). +// v2rayA (the service layer) writes DNS module configuration into the xray JSON config file +// under the "dns_module" key; v2raya-core reads it here at startup. +package main + +import ( + "encoding/json" + "fmt" + "log" + "os" + "sync" + "time" + + "github.com/v2rayA/v2raya-core/dns" + "github.com/xtls/xray-core/common/cmdarg" + xcore "github.com/xtls/xray-core/core" +) + +// dnsModuleManager manages the lifecycle of the DNS module within v2raya-core. +// It reads the "dns_module" configuration from xray's JSON config files and +// starts/stops the DNS listener independently of xray-core. +type dnsModuleManager struct { + module *dns.DnsModule + mu sync.Mutex +} + +var dnsMgr dnsModuleManager + +// startDnsModuleWithXray reads the dns_module config, creates the DNS module, +// connects it to xray-core's internal routing dispatcher, and starts it. +// DNS starts AFTER xray so it can use xray's routing for internal dispatching +// (like xray-core's traditional DNS module). +func startDnsModuleWithXray(configFiles cmdarg.Arg, srv *xcore.Instance) error { + cfg, err := extractDnsModuleConfig(configFiles) + if err != nil { + return fmt.Errorf("dns module: extract config: %w", err) + } + if cfg == nil { + log.Println("[dns module] no dns_module config found, skipping") + return nil + } + + // Create the xray dispatcher adapter for internal routing. + adapter, err := newXrayDispatcherAdapter(srv) + if err != nil { + return fmt.Errorf("dns module: create dispatcher: %w", err) + } + + module := dns.NewDnsModule(cfg) + + // 在 Start 之前设置 xray-core 路由调度器。 + module.SetDispatcher(adapter) + + if err := module.Start(); err != nil { + return fmt.Errorf("dns module: start failed: %w", err) + } + + // Start 后设置 geosite 解析器(Router 在 Start 中创建)。 + // geositeResolver 使用 geosite.dat 展开分流规则中的 geosite: 标签, + // 使 geosite:cn → 具体域名列表,实现真正的分流。 + if router := module.GetRouter(); router != nil { + router.SetGeositeResolver(geositeResolver) + // 重新加载规则以应用 geosite 解析器 + router.Reload(module.Config()) + log.Println("[dns module] geosite resolver set, rules reloaded with geosite expansion") + } + + dnsMgr.mu.Lock() + dnsMgr.module = module + dnsMgr.mu.Unlock() + + log.Printf("[dns module] started successfully, listening on %s", cfg.Listener.ListenAddr) + return nil +} + +// stopDnsModule gracefully stops the DNS module. +func stopDnsModule() { + dnsMgr.mu.Lock() + module := dnsMgr.module + dnsMgr.module = nil + dnsMgr.mu.Unlock() + + if module != nil { + log.Println("[dns module] stopping...") + if err := module.Stop(); err != nil { + log.Printf("[dns module] stop error: %v", err) + } + log.Println("[dns module] stopped") + } +} + +// extractDnsModuleConfig reads all config files, merges them, and extracts the +// "dns_module" configuration. Returns nil if the key is not present. +func extractDnsModuleConfig(configFiles cmdarg.Arg) (*dns.DnsModuleConfig, error) { + if len(configFiles) == 0 { + return nil, nil + } + + // Merge all config files into a single JSON object. + merged := make(map[string]interface{}) + for _, configFile := range configFiles { + if configFile == "stdin:" { + continue // skip stdin, unlikely to contain dns_module + } + data, err := os.ReadFile(configFile) + if err != nil { + return nil, fmt.Errorf("read config %q: %w", configFile, err) + } + + var cfg map[string]interface{} + if err := json.Unmarshal(data, &cfg); err != nil { + log.Printf("[dns module] warning: cannot parse config %q as JSON: %v", configFile, err) + continue + } + + // Merge into the combined config. + for k, v := range cfg { + merged[k] = v + } + } + + // Check for dns_module key. + raw, ok := merged["dns_module"] + if !ok { + return nil, nil + } + + // Marshal the dns_module value back to JSON for unmarshaling into DnsModuleConfig. + jsonBytes, err := json.Marshal(raw) + if err != nil { + return nil, fmt.Errorf("marshal dns_module config: %w", err) + } + + var cfg dns.DnsModuleConfig + if err := json.Unmarshal(jsonBytes, &cfg); err != nil { + return nil, fmt.Errorf("unmarshal dns_module config: %w", err) + } + + // Apply defaults where needed. + if cfg.Listener.ListenAddr == "" { + cfg.Listener.ListenAddr = "0.0.0.0:52353" + } + if cfg.Listener.Timeout <= 0 { + cfg.Listener.Timeout = 5 + } + if cfg.Cache.Size <= 0 { + cfg.Cache.Size = 4096 + } + if cfg.Cache.MinTTL <= 0 { + cfg.Cache.MinTTL = 60 + } + if cfg.Cache.MaxTTL <= 0 { + cfg.Cache.MaxTTL = 86400 + } + + return &cfg, nil +} + +// waitForDnsModuleReady blocks until the DNS module is healthy or a timeout expires. +// This allows the transparent proxy setup (iptables rules) to wait for DNS readiness. +func waitForDnsModuleReady(timeout time.Duration) error { + deadline := time.Now().Add(timeout) + for time.Now().Before(deadline) { + dnsMgr.mu.Lock() + module := dnsMgr.module + dnsMgr.mu.Unlock() + + if module != nil && module.Healthy() { + return nil + } + time.Sleep(50 * time.Millisecond) + } + return fmt.Errorf("dns module: not ready within %v", timeout) +} + +// DnsModuleReady returns true if the DNS module is running and healthy. +// This is used by external health checks (e.g., from v2rayA service via API). +func DnsModuleReady() bool { + dnsMgr.mu.Lock() + module := dnsMgr.module + dnsMgr.mu.Unlock() + return module != nil && module.Healthy() +} diff --git a/core/main/geosite.go b/core/main/geosite.go new file mode 100644 index 00000000..e8c169c1 --- /dev/null +++ b/core/main/geosite.go @@ -0,0 +1,69 @@ +package main + +import ( + "log" + "os" + "path/filepath" + + "github.com/xtls/xray-core/common/geodata" + "google.golang.org/protobuf/proto" +) + +// geositeResolver implements dns.GeositeResolver using xray-core's geodata. +// It loads geosite.dat from the standard asset directory and expands tags +// (e.g. "cn") into domain/suffix patterns. +func geositeResolver(tag string) (domains, suffixes []string) { + // Determine geosite.dat location from environment. + assetDir := os.Getenv("XRAY_LOCATION_ASSET") + if assetDir == "" { + assetDir = os.Getenv("V2RAY_LOCATION_ASSET") + } + if assetDir == "" { + log.Printf("[dns] geosite: XRAY_LOCATION_ASSET not set, skipping geosite expansion") + return nil, nil + } + + geositePath := filepath.Join(assetDir, "geosite.dat") + data, err := os.ReadFile(geositePath) + if err != nil { + log.Printf("[dns] geosite: cannot read %s: %v", geositePath, err) + return nil, nil + } + + var list geodata.GeoSiteList + if err := proto.Unmarshal(data, &list); err != nil { + log.Printf("[dns] geosite: cannot parse %s: %v", geositePath, err) + return nil, nil + } + + for _, entry := range list.Entry { + if entry.Code != tag { + continue + } + for _, domain := range entry.Domain { + switch domain.Type { + case geodata.Domain_Domain: + // Domain match: exact domain (but also matches subdomains in xray routing). + // In our DNS module, we add as suffix match for broader matching. + suffixes = append(suffixes, domain.Value) + case geodata.Domain_Full: + // Full match: exact domain only. + domains = append(domains, domain.Value) + case geodata.Domain_Regex: + // Regex: include as-is; the router will create Regex matchers. + // For DNS rules, we treat these as domains (the matcher will fail gracefully). + domains = append(domains, domain.Value) + case geodata.Domain_Substr: + // Substring: cannot be directly used as domain matcher; skip. + // Note: keyword: tag would be better for substring matching. + } + } + if len(domains) > 0 || len(suffixes) > 0 { + log.Printf("[dns] geosite: expanded %s → %d domains, %d suffixes", tag, len(domains), len(suffixes)) + } + return domains, suffixes + } + + log.Printf("[dns] geosite: tag %q not found in geosite.dat", tag) + return nil, nil +} diff --git a/core/main/run.go b/core/main/run.go index bdb9406f..4284c0e7 100644 --- a/core/main/run.go +++ b/core/main/run.go @@ -28,15 +28,15 @@ var cmdRun = &base.Command{ Long: ` Run Xray with config, the default command. -The -config=file, -c=file flags set the config files for +The -config=file, -c=file flags set the config files for Xray. Multiple assign is accepted. The -confdir=dir flag sets a dir with multiple json config -The -format=json flag sets the format of config files. +The -format=json flag sets the format of config files. Default "auto". -The -test flag tells Xray to test config files only, +The -test flag tells Xray to test config files only, without launching the server. The -dump flag tells Xray to print the merged config. @@ -75,10 +75,15 @@ func executeRun(cmd *base.Command, args []string) { } printVersion() - server, err := startXray() + + // 获取配置文件路径(需要在 xray 加载配置之前读取,因为 xray 会处理掉自定义字段) + configFiles := getConfigFilePath(true) + + // 先启动 xray-core,使其路由引擎(dispatcher)可用。 + // DNS 模块在 xray 之后启动,以便使用 xray 的路由分流走内部逻辑(类似原始 xray DNS 模块)。 + server, err := startXrayFromFiles(configFiles) if err != nil { fmt.Println("Failed to start:", err) - // Configuration error. Exit with a special value to prevent systemd from restarting. os.Exit(23) } @@ -91,13 +96,18 @@ func executeRun(cmd *base.Command, args []string) { fmt.Println("Failed to start:", err) os.Exit(-1) } - defer server.Close() - /* - conf.FileCache = nil - conf.IPCache = nil - conf.SiteCache = nil - */ + // xray 启动后,获取路由 dispatcher 并启动 DNS 模块(如配置了 dns_module) + if err := startDnsModuleWithXray(configFiles, server); err != nil { + fmt.Println("Failed to start DNS module:", err) + os.Exit(23) + } + + defer func() { + // DNS 模块在 xray 之前关闭,确保所有进行中的 DNS 查询能完成 + stopDnsModule() + server.Close() + }() // Explicitly triggering GC to remove garbage from config loading. runtime.GC() @@ -110,6 +120,22 @@ func executeRun(cmd *base.Command, args []string) { } } +// startXrayFromFiles loads xray config from the given files and creates a server. +// This is split from startXray to allow DNS module to read config files first. +func startXrayFromFiles(configFiles cmdarg.Arg) (*core.Instance, error) { + c, err := core.LoadConfig(getConfigFormat(), configFiles) + if err != nil { + return nil, errors.New("failed to load config files: [", configFiles.String(), "]").Base(err) + } + + server, err := core.New(c) + if err != nil { + return nil, errors.New("failed to create server").Base(err) + } + + return server, nil +} + func dumpConfig() int { files := getConfigFilePath(false) if config, err := core.GetMergedConfig(files); err != nil { @@ -214,19 +240,3 @@ func getConfigFormat() string { } return f } - -func startXray() (core.Server, error) { - configFiles := getConfigFilePath(true) - - c, err := core.LoadConfig(getConfigFormat(), configFiles) - if err != nil { - return nil, errors.New("failed to load config files: [", configFiles.String(), "]").Base(err) - } - - server, err := core.New(c) - if err != nil { - return nil, errors.New("failed to create server").Base(err) - } - - return server, nil -} diff --git a/core/main/xray_dispatcher.go b/core/main/xray_dispatcher.go new file mode 100644 index 00000000..dfb8d48c --- /dev/null +++ b/core/main/xray_dispatcher.go @@ -0,0 +1,89 @@ +package main + +import ( + "context" + "fmt" + "net" + "strconv" + "strings" + + xnet "github.com/xtls/xray-core/common/net" + "github.com/xtls/xray-core/common/net/cnc" + "github.com/xtls/xray-core/common/session" + xcore "github.com/xtls/xray-core/core" + "github.com/xtls/xray-core/features/routing" +) + +// xrayDispatcherAdapter implements dns.RouteDispatcher using xray-core's +// internal routing dispatcher. This allows the DNS module to route queries +// through xray-core's proxy outbounds (VMESS, VLESS, Trojan, etc.) just like +// xray-core's built-in DNS module does. +// +// It sets session.ContextWithInbound on the dispatch context so that xray's +// routing engine selects the appropriate outbound based on routing rules. +type xrayDispatcherAdapter struct { + dispatcher routing.Dispatcher +} + +// newXrayDispatcherAdapter creates a new adapter from an xray core instance. +func newXrayDispatcherAdapter(srv *xcore.Instance) (*xrayDispatcherAdapter, error) { + var dispatcher routing.Dispatcher + if err := srv.RequireFeatures(func(d routing.Dispatcher) { + dispatcher = d + }, false); err != nil { + return nil, fmt.Errorf("xray dispatcher not available: %w", err) + } + return &xrayDispatcherAdapter{dispatcher: dispatcher}, nil +} + +// Dispatch implements dns.RouteDispatcher. +// It creates a TCP connection to addr through xray-core's routing engine. +// The proxyTag is used to set the inbound tag on the context, which xray's +// routing rules use to determine the outbound (like xray-core's DNS module). +func (a *xrayDispatcherAdapter) Dispatch(ctx context.Context, network, addr, proxyTag string) (net.Conn, error) { + // Parse the destination address. + host, portStr, err := net.SplitHostPort(addr) + if err != nil { + host = addr + portStr = "53" + } + port, err := strconv.Atoi(portStr) + if err != nil { + port = 53 + } + + var dest xnet.Destination + switch strings.ToLower(network) { + case "tcp", "tcp4", "tcp6": + dest = xnet.TCPDestination(xnet.ParseAddress(host), xnet.Port(port)) + case "udp", "udp4", "udp6": + dest = xnet.UDPDestination(xnet.ParseAddress(host), xnet.Port(port)) + default: + dest = xnet.TCPDestination(xnet.ParseAddress(host), xnet.Port(port)) + } + + // Set the inbound tag on the context so xray's routing engine + // selects the appropriate outbound (like xray-core's DNS module). + // For "direct", no special tag is needed (uses default routing). + dnsCtx := ctx + if proxyTag != "" && proxyTag != "direct" { + dnsCtx = session.ContextWithInbound(dnsCtx, &session.Inbound{Tag: proxyTag}) + } + // Mark as DNS traffic to prevent recursive DNS resolution. + dnsCtx = session.ContextWithContent(dnsCtx, &session.Content{ + Protocol: "dns", + SkipDNSResolve: true, + }) + + // Dispatch through xray-core's routing engine. + link, err := a.dispatcher.Dispatch(dnsCtx, dest) + if err != nil { + return nil, fmt.Errorf("xray dispatch: %w", err) + } + + // Wrap the transport link into a standard net.Conn. + return cnc.NewConnection( + cnc.ConnectionInputMulti(link.Writer), + cnc.ConnectionOutputMulti(link.Reader), + ), nil +} diff --git a/core/v2ray b/core/v2ray deleted file mode 160000 index cf7577f6..00000000 --- a/core/v2ray +++ /dev/null @@ -1 +0,0 @@ -Subproject commit cf7577f650f97226d34a4e7ab6e30b765a15677a diff --git a/service/common/httpClient/httpClient.go b/service/common/httpClient/httpClient.go index f0657bbe..ac19677e 100644 --- a/service/common/httpClient/httpClient.go +++ b/service/common/httpClient/httpClient.go @@ -3,7 +3,7 @@ package httpClient import ( "fmt" "github.com/v2rayA/v2rayA/common" - "github.com/v2rayA/v2rayA/core/v2ray" + "github.com/v2rayA/v2rayA/kernel/v2ray" "github.com/v2rayA/v2rayA/db/configure" proxyWithHttp2 "github.com/v2rayA/v2rayA/pkg/util/proxyWithHttp" "net" diff --git a/service/common/parseGeoIP/parser.go b/service/common/parseGeoIP/parser.go index bd58ecc6..40236604 100644 --- a/service/common/parseGeoIP/parser.go +++ b/service/common/parseGeoIP/parser.go @@ -6,7 +6,7 @@ import ( "os" "strings" - "github.com/v2rayA/v2rayA/core/v2ray/asset" + "github.com/v2rayA/v2rayA/kernel/v2ray/asset" "google.golang.org/protobuf/proto" ) diff --git a/service/conf/report/connection.go b/service/conf/report/connection.go index ded92acc..b6067a20 100644 --- a/service/conf/report/connection.go +++ b/service/conf/report/connection.go @@ -3,8 +3,8 @@ package report import ( "fmt" "github.com/v2rayA/v2rayA/conf" - "github.com/v2rayA/v2rayA/core/ipforward" - "github.com/v2rayA/v2rayA/core/v2ray/where" + "github.com/v2rayA/v2rayA/kernel/ipforward" + "github.com/v2rayA/v2rayA/kernel/v2ray/where" "github.com/v2rayA/v2rayA/db/configure" "strings" ) diff --git a/service/conf/report/coreStatus.go b/service/conf/report/coreStatus.go index d1c33ce6..2b68cad7 100644 --- a/service/conf/report/coreStatus.go +++ b/service/conf/report/coreStatus.go @@ -3,8 +3,8 @@ package report import ( "fmt" jsoniter "github.com/json-iterator/go" - "github.com/v2rayA/v2rayA/core/v2ray" - "github.com/v2rayA/v2rayA/core/v2ray/asset" + "github.com/v2rayA/v2rayA/kernel/v2ray" + "github.com/v2rayA/v2rayA/kernel/v2ray/asset" "github.com/v2rayA/v2rayA/db/configure" "net" "strconv" diff --git a/service/conf/report/curl.go b/service/conf/report/curl.go index ae09409a..40d3c1cb 100644 --- a/service/conf/report/curl.go +++ b/service/conf/report/curl.go @@ -3,7 +3,7 @@ package report import ( "fmt" "github.com/v2rayA/v2rayA/common/httpClient" - "github.com/v2rayA/v2rayA/core/v2ray" + "github.com/v2rayA/v2rayA/kernel/v2ray" "github.com/v2rayA/v2rayA/db/configure" "io" "net" diff --git a/service/core/v2ray/dnsParser.go b/service/core/v2ray/dnsParser.go deleted file mode 100644 index 74e5237f..00000000 --- a/service/core/v2ray/dnsParser.go +++ /dev/null @@ -1,20 +0,0 @@ -package v2ray - -import "strings" - -type Dns struct { - Val string - Out string -} - -func ParseAdvancedDnsLine(dnsLine string) *Dns { - dnsLine = strings.TrimSpace(dnsLine) - index := strings.LastIndex(dnsLine, "->") - if index >= 0 { - return &Dns{ - Val: strings.TrimSpace(dnsLine[:index]), - Out: strings.TrimSpace(dnsLine[index+2:]), - } - } - return nil -} diff --git a/service/core/v2ray/transparent.go b/service/core/v2ray/transparent.go deleted file mode 100644 index 00c104ea..00000000 --- a/service/core/v2ray/transparent.go +++ /dev/null @@ -1,126 +0,0 @@ -package v2ray - -import ( - "fmt" - "strings" - "time" - - "github.com/v2rayA/v2rayA/common/cmds" - "github.com/v2rayA/v2rayA/conf" - "github.com/v2rayA/v2rayA/core/iptables" - "github.com/v2rayA/v2rayA/db/configure" - "github.com/v2rayA/v2rayA/pkg/util/log" -) - -// cleanupResidualTransparentProxyRules cleans up any residual iptables/nftables rules -// that may have been left behind after an abnormal termination (e.g., kill -9, system crash, panic). -// It uses "2>/dev/null || true" to ensure no errors are raised if rules/chains don't exist. -func cleanupResidualTransparentProxyRules() { - commands := ` -iptables -w 2 -t mangle -F TP_OUT 2>/dev/null || true -iptables -w 2 -t mangle -D OUTPUT -j TP_OUT 2>/dev/null || true -iptables -w 2 -t mangle -X TP_OUT 2>/dev/null || true -iptables -w 2 -t mangle -F TP_PRE 2>/dev/null || true -iptables -w 2 -t mangle -D PREROUTING -j TP_PRE 2>/dev/null || true -iptables -w 2 -t mangle -X TP_PRE 2>/dev/null || true -iptables -w 2 -t mangle -F TP_RULE 2>/dev/null || true -iptables -w 2 -t mangle -X TP_RULE 2>/dev/null || true -iptables -w 2 -t mangle -F TP_MARK 2>/dev/null || true -iptables -w 2 -t mangle -X TP_MARK 2>/dev/null || true -iptables -w 2 -t nat -F TP_OUT 2>/dev/null || true -iptables -w 2 -t nat -D OUTPUT -j TP_OUT 2>/dev/null || true -iptables -w 2 -t nat -X TP_OUT 2>/dev/null || true -iptables -w 2 -t nat -F TP_PRE 2>/dev/null || true -iptables -w 2 -t nat -D PREROUTING -j TP_PRE 2>/dev/null || true -iptables -w 2 -t nat -X TP_PRE 2>/dev/null || true -iptables -w 2 -t nat -F TP_RULE 2>/dev/null || true -iptables -w 2 -t nat -X TP_RULE 2>/dev/null || true -iptables -w 2 -F DROP_SPOOFING 2>/dev/null || true -iptables -w 2 -D INPUT -j DROP_SPOOFING 2>/dev/null || true -iptables -w 2 -D FORWARD -j DROP_SPOOFING 2>/dev/null || true -iptables -w 2 -X DROP_SPOOFING 2>/dev/null || true -ip rule del fwmark 0x40/0xc0 table 100 2>/dev/null || true -ip route del local 0.0.0.0/0 dev lo table 100 2>/dev/null || true -nft delete table inet v2raya 2>/dev/null || true -` - cmds.ExecCommands(commands, false) -} - -func deleteTransparentProxyRulesKeepSystemProxy() { - stopTinyTun() - iptables.CloseWatcher() - if !conf.GetEnvironmentConfig().Lite { - removeResolvHijacker() - iptables.Tproxy.GetCleanCommands().Run(false) - iptables.Redirect.GetCleanCommands().Run(false) - iptables.DropSpoofing.GetCleanCommands().Run(false) - } - time.Sleep(30 * time.Millisecond) -} - -func deleteTransparentProxyRules() { - deleteTransparentProxyRulesKeepSystemProxy() - iptables.SystemProxy.GetCleanCommands().Run(false) -} - -func writeTransparentProxyRules(tmpl *Template) (err error) { - defer func() { - if err != nil { - log.Warn("writeTransparentProxyRules: %v", err) - deleteTransparentProxyRules() - } - }() - cleanupResidualTransparentProxyRules() - setting := configure.GetSettingNotNil() - switch setting.TransparentType { - case configure.TransparentTun: - return startTinyTun(tmpl) - case configure.TransparentTproxy: - if err = iptables.Tproxy.GetSetupCommands().Run(true); err != nil { - if strings.Contains(err.Error(), "TPROXY") && strings.Contains(err.Error(), "No chain") { - err = fmt.Errorf("you does not compile xt_TPROXY in kernel") - } - return fmt.Errorf("not support \"tproxy\" mode of transparent proxy: %w", err) - } - iptables.SetWatcher(iptables.Tproxy) - case configure.TransparentRedirect: - if err = iptables.Redirect.GetSetupCommands().Run(true); err != nil { - return fmt.Errorf("not support \"redirect\" mode of transparent proxy: %w", err) - } - iptables.SetWatcher(iptables.Redirect) - case configure.TransparentSystemProxy: - if err = iptables.SystemProxy.GetSetupCommands().Run(true); err != nil { - return fmt.Errorf("not support \"system proxy\" mode of transparent proxy: %w", err) - } - default: - return fmt.Errorf("undefined \"%v\" mode of transparent proxy", setting.TransparentType) - } - - if ShouldLocalDnsListen() { - if couldListenLocalhost, e := CouldLocalDnsListen(); couldListenLocalhost { - if e != nil { - log.Warn("only listen at 127.2.0.17: %v", e) - } - resetResolvHijacker() - } else { - log.Warn("writeTransparentProxyRules: %v", e) - } - } - return nil -} - -func IsTransparentOn(setting *configure.Setting) bool { - if setting == nil { - setting = configure.GetSettingNotNil() - } - if setting.Transparent == configure.TransparentClose { - return false - } - if conf.GetEnvironmentConfig().Lite && - (setting.TransparentType == configure.TransparentTproxy || - setting.TransparentType == configure.TransparentRedirect) { - return false - } - return true -} - diff --git a/service/core/v2ray/v2rayTmpl.go b/service/core/v2ray/v2rayTmpl.go deleted file mode 100644 index 6538c2e4..00000000 --- a/service/core/v2ray/v2rayTmpl.go +++ /dev/null @@ -1,2160 +0,0 @@ -package v2ray - -import ( - "crypto/sha256" - "encoding/hex" - "errors" - "fmt" - "net" - "net/url" - "os" - "regexp" - "sort" - "strconv" - "strings" - "time" - - "github.com/go-leo/slicex" - - jsoniter "github.com/json-iterator/go" - "github.com/mohae/deepcopy" - "github.com/v2rayA/RoutingA" - "github.com/v2rayA/v2rayA/common" - "github.com/v2rayA/v2rayA/common/netTools/netstat" - "github.com/v2rayA/v2rayA/common/netTools/ports" - "github.com/v2rayA/v2rayA/conf" - "github.com/v2rayA/v2rayA/core/coreObj" - "github.com/v2rayA/v2rayA/core/iptables" - "github.com/v2rayA/v2rayA/core/serverObj" - "github.com/v2rayA/v2rayA/core/v2ray/asset" - "github.com/v2rayA/v2rayA/core/v2ray/where" - "github.com/v2rayA/v2rayA/db/configure" - "github.com/v2rayA/v2rayA/pkg/util/log" -) - -type Template struct { - Log *coreObj.Log `json:"log,omitempty"` - Inbounds []coreObj.Inbound `json:"inbounds"` - Outbounds []coreObj.OutboundObject `json:"outbounds"` - Routing struct { - DomainStrategy string `json:"domainStrategy"` - DomainMatcher string `json:"domainMatcher,omitempty"` - Rules []coreObj.RoutingRule `json:"rules"` - Balancers []coreObj.Balancer `json:"balancers,omitempty"` - } `json:"routing"` - DNS *coreObj.DNS `json:"dns,omitempty"` - MultiObservatory *coreObj.MultiObservatory `json:"multiObservatory,omitempty"` - Observatory *coreObj.ObservatoryItem `json:"observatory,omitempty"` - API *coreObj.APIObject `json:"api,omitempty"` - - Variant where.Variant `json:"-"` - CoreVersion string `json:"-"` - OutboundTags []string `json:"-"` - ApiCloses []func() `json:"-"` - ApiPort int `json:"-"` - Setting *configure.Setting `json:"-"` - serverInfoMap map[string]*serverInfo `json:"-"` // outbound tag -> server info -} - -func (t *Template) Close() error { - for _, f := range t.ApiCloses { - f() - } - return nil -} - -type Addr struct { - host string - port string - udp bool -} - -func parseDnsAddr(addr string) Addr { - // 223.5.5.5 - if net.ParseIP(addr) != nil { - return Addr{ - host: addr, - port: "53", - udp: true, - } - } - // dns.google:53 - if host, port, err := net.SplitHostPort(addr); err == nil { - if _, err = strconv.Atoi(port); err == nil { - return Addr{ - host: host, - port: port, - udp: true, - } - } - } - // tcp://8.8.8.8:53, https://dns.google/dns-query, quic://dns.nextdns.io - if strings.Contains(addr, "://") { - if u, err := url.Parse(addr); err == nil { - udp := false - if u.Scheme == "quic" { - udp = true - } - return Addr{ - host: u.Hostname(), - port: u.Port(), - udp: udp, - } - } - } - // dns.google, dns.pub, etc. - return Addr{ - host: addr, - port: "53", - udp: true, - } -} - -type DnsRouting struct { - DirectDomains []Addr - ProxyDomains []Addr - DirectIPs []Addr - ProxyIPs []Addr -} - -func parseAdvancedDnsServers(lines []string, domains []string) (domainNameServers []interface{}, routing []coreObj.RoutingRule) { - for _, line := range lines { - if len(line) == 0 { - continue - } - dns := ParseAdvancedDnsLine(line) - if u, err := url.Parse(dns.Val); err == nil && - strings.Contains(dns.Val, "://") && - !strings.Contains(u.Scheme, "://") { - // FIXME: after quic:// supported - if u.Scheme == "quic" { - u.Scheme = "quic+local" - dns.Val = u.String() - } - if domains != nil { - domainNameServers = append(domainNameServers, coreObj.DnsServer{ - Address: dns.Val, - Domains: domains, - }) - } else { - domainNameServers = append(domainNameServers, dns.Val) - } - } else { - addr := parseDnsAddr(dns.Val) - p, _ := strconv.Atoi(addr.port) - if domains == nil { - // Fallback DNS (no domain scope): use plain string format as per v2fly documentation, no braces. - // Object format is still required for non-standard ports, but without the Domains field. - if p == 0 || p == 53 { - domainNameServers = append(domainNameServers, addr.host) - } else { - domainNameServers = append(domainNameServers, coreObj.DnsServer{ - Address: addr.host, - Port: p, - }) - } - } else { - // DNS with domain matching scope: object format, port 53 is the default and not written. - portToSet := 0 - if p != 53 { - portToSet = p - } - domainNameServers = append(domainNameServers, coreObj.DnsServer{ - Address: addr.host, - Port: portToSet, - Domains: domains, - }) - } - } - - if dns.Val == "localhost" { - // no need to routing - continue - } - // we believe all lines are legal - var addr = parseDnsAddr(dns.Val) - - if net.ParseIP(addr.host) != nil { - routing = append(routing, coreObj.RoutingRule{ - Type: "field", OutboundTag: dns.Out, IP: []string{addr.host}, Port: addr.port, - }) - } else { - routing = append(routing, coreObj.RoutingRule{ - Type: "field", OutboundTag: dns.Out, Domain: []string{addr.host}, Port: addr.port, - }) - } - } - return domainNameServers, routing -} - -// outName -> isGroup -func (t *Template) outNames() map[string]bool { - tags := make(map[string]bool) - for _, o := range t.Outbounds { - if len(o.Balancers) > 0 { - for _, groupName := range o.Balancers { - tags[groupName] = true - } - } else { - tags[o.Tag] = false - } - } - return tags -} - -func (t *Template) FirstProxyOutboundName(filter func(outboundName string, isGroup bool) bool) (outboundName string, isGroup bool) { - if filter == nil { - filter = func(outboundName string, isGroup bool) bool { - return true - } - } - // deduplicate - m := make(map[string]struct{}) - - for _, o := range t.Outbounds { - switch o.Tag { - case "direct", "block", "dns-out": - continue - } - if len(o.Balancers) > 0 { - for _, v := range o.Balancers { - if _, ok := m[v]; !ok { - if filter(v, true) { - return v, true - } - m[v] = struct{}{} - } - } - } else { - if filter(o.Tag, false) { - return o.Tag, false - } - } - } - return -} - -// dnsRuleToLines converts a configure.DnsRule to the "server -> outbound" line format -// and the domain list used for the DNS server object. -// Returns (serverLine, []domains). serverLine is empty if server is empty. -func dnsRuleToLines(rule configure.DnsRule) (serverLine string, domains []string) { - if rule.Server == "" { - return "", nil - } - serverLine = rule.Server + " -> " + rule.Outbound - if rule.Domains != "" { - for _, d := range strings.Split(strings.TrimSpace(rule.Domains), "\n") { - d = strings.TrimSpace(d) - if d != "" { - domains = append(domains, d) - } - } - } - return serverLine, domains -} - -func (t *Template) setDNS(outbounds []serverInfo, supportUDP map[string]bool) (routing []coreObj.RoutingRule, err error) { - firstOutboundTag, _ := t.FirstProxyOutboundName(nil) - outboundTags := t.outNames() - - rules := configure.GetDnsRulesNotNil() - - // Validate outbound tags existence and UDP constraints - for _, rule := range rules { - if rule.Server == "" || rule.Outbound == "" { - continue - } - if rule.Outbound == "direct" || rule.Outbound == "block" { - continue - } - if _, ok := outboundTags[rule.Outbound]; !ok { - return nil, fmt.Errorf(`your DNS rule "%v -> %v" depends on the outbound "%v", thus you should select at least one server in this outbound`, rule.Server, rule.Outbound, rule.Outbound) - } - if parseDnsAddr(rule.Server).udp && !supportUDP[rule.Outbound] { - return nil, fmt.Errorf(`due to the protocol of outbound "%v" with no UDP supported, please use tcp:// or https:// DNS instead, or change the connected server`, rule.Outbound) - } - } - - t.DNS = &coreObj.DNS{ - Tag: "dns", - } - - // Separate fallback (no domain) from domain-specific rules. - // Per v2fly docs: fallback servers (no domains) should come FIRST in the list - // and are represented as plain strings, not wrapped in objects. - var fallbackLines []string - type domainGroup struct { - line string - domains []string - } - var domainGroups []domainGroup - - for _, rule := range rules { - line, domains := dnsRuleToLines(rule) - if line == "" { - continue - } - if len(domains) == 0 { - fallbackLines = append(fallbackLines, line) - } else { - domainGroups = append(domainGroups, domainGroup{line: line, domains: domains}) - } - } - - // Add fallback servers first (plain string form) - if len(fallbackLines) > 0 { - d, r := parseAdvancedDnsServers(fallbackLines, nil) - t.DNS.Servers = append(t.DNS.Servers, d...) - routing = append(routing, r...) - } - - // Add domain-specific servers (ServerObject form) - for _, g := range domainGroups { - d, r := parseAdvancedDnsServers([]string{g.line}, g.domains) - t.DNS.Servers = append(t.DNS.Servers, d...) - routing = append(routing, r...) - } - - if t.DNS.Servers == nil { - t.DNS.Servers = []interface{}{"localhost"} - } - var domainsToLookup []string - // Collect domains from outbound servers - for _, v := range outbounds { - if net.ParseIP(v.Info.GetHostname()) == nil { - domainsToLookup = append(domainsToLookup, v.Info.GetHostname()) - } - } - // Collect domains from routing rules - for _, r := range routing { - if len(r.Domain) > 0 { - domainsToLookup = append(domainsToLookup, r.Domain...) - } - } - // Collect domains from DNS servers themselves (for DoT/DoH) - for _, srv := range t.DNS.Servers { - var dnsAddr string - switch s := srv.(type) { - case string: - dnsAddr = s - case coreObj.DnsServer: - dnsAddr = s.Address - } - if dnsAddr == "" || dnsAddr == "localhost" || dnsAddr == "fakedns" { - continue - } - // Parse DNS address to extract hostname - addr := parseDnsAddr(dnsAddr) - if net.ParseIP(addr.host) == nil { - // DNS server address is a domain, need to resolve it - domainsToLookup = append(domainsToLookup, addr.host) - } - } - domainsToLookup = common.Deduplicate(domainsToLookup) - if len(domainsToLookup) > 0 { - // Use Google 8.8.8.8 and Tencent 119.29.29.29 to resolve these critical domains - var dnsList []string - dnsList = []string{ - "8.8.8.8 -> " + firstOutboundTag, - "119.29.29.29 -> direct", - } - d, r := parseAdvancedDnsServers(dnsList, domainsToLookup) - t.DNS.Servers = append(t.DNS.Servers, d...) - routing = append(routing, r...) - } - // hard code for SNI problem like apple pushing - t.DNS.Hosts = make(coreObj.Hosts) - t.DNS.Hosts["courier.push.apple.com"] = []string{"1-courier.push.apple.com"} - - // deduplicate - strRouting := make([]string, 0, len(routing)) - for _, r := range routing { - b, err := jsoniter.Marshal(r) - if err != nil { - return nil, fmt.Errorf("jsoniter.Marshal: %v", err) - } - strRouting = append(strRouting, string(b)) - } - strRouting = common.Deduplicate(strRouting) - routing = routing[:0] - for _, sr := range strRouting { - var r coreObj.RoutingRule - if err := jsoniter.Unmarshal([]byte(sr), &r); err != nil { - return nil, fmt.Errorf("jsoniter.Unmarshal: RoutingRule: %v", err) - } - routing = append(routing, r) - } - return routing, nil -} - -// FilterIPs returns filtered IP list. -// The order are from v4 IPs to v6 IPs. -// If the system does not support IPv6, v6 IPs will not be returned. -func FilterIPs(ips []string) []string { - var ret []string - for _, ip := range ips { - if net.ParseIP(ip).To4() != nil { - ret = append(ret, ip) - } - } - if !iptables.IsIPv6Supported() { - return ret - } - for _, ip := range ips { - if net.ParseIP(ip).To4() == nil { - ret = append(ret, ip) - } - } - return ret -} -func (t *Template) setDNSRouting(routing []coreObj.RoutingRule, supportUDP map[string]bool) { - firstOutboundTag, _ := t.FirstProxyOutboundName(nil) - // In TinyTun mode DNS is handled by TinyTun itself; skip all v2ray DNS routing rules. - isTinyTunMode := t.Setting != nil && t.Setting.TransparentType == configure.TransparentTun && IsTransparentOn(t.Setting) - if !isTinyTunMode { - t.Routing.Rules = append(t.Routing.Rules, routing...) - } - setting := t.Setting - // DNS is always active: hijack port-53 traffic into dns-out - if ShouldLocalDnsListen() { - if couldListenLocalhost, _ := CouldLocalDnsListen(); couldListenLocalhost { - // 先添加特定规则:DNS 端口 53 优先匹配 dns-out - t.Routing.Rules = append(t.Routing.Rules, coreObj.RoutingRule{ - Type: "field", - InboundTag: []string{"dns-in"}, - Port: "53", - OutboundTag: "dns-out", - }) - } - } - // 后添加通用规则,排除 DNS 端口(避免通用规则抢在特定规则之前匹配) - if !isTinyTunMode { - t.Routing.Rules = append(t.Routing.Rules, - coreObj.RoutingRule{Type: "field", InboundTag: []string{"dns-in"}, OutboundTag: "direct"}, - ) - } - if !supportUDP[firstOutboundTag] { - // find an outbound that supports UDP and redirect all leaky UDP traffic to it - var found bool - for outbound, support := range supportUDP { - if support { - t.Routing.Rules = append(t.Routing.Rules, - coreObj.RoutingRule{ - Type: "field", - OutboundTag: outbound, - Network: "udp", - }, - ) - found = true - break - } - } - if !found { - // no outbound with UDP supported, so redirect all leaky UDP traffic to outbound direct - t.Routing.Rules = append(t.Routing.Rules, - coreObj.RoutingRule{ - Type: "field", - OutboundTag: "direct", - Network: "udp", - }, - ) - } - } else { - if IsTransparentOn(setting) { - // TProxy 模式下,将透明代理入站的 DNS 流量无条件路由到 dns-out - // 此规则在 setDNSRouting 中添加,早于 setTransparentRouting 的其他规则,因此优先匹配 - t.Routing.Rules = append(t.Routing.Rules, - coreObj.RoutingRule{ - Type: "field", - OutboundTag: "dns-out", - InboundTag: []string{ - "transparent", - }, - Port: "53", - }) - } - } -} - -func (t *Template) AppendRoutingRuleByMode(mode configure.RulePortMode, inbounds []string) (err error) { - firstOutboundTag, _ := t.FirstProxyOutboundName(nil) - // apple pushing. #495 #479 - t.Routing.Rules = append(t.Routing.Rules, coreObj.RoutingRule{ - Type: "field", - OutboundTag: "direct", - InboundTag: deepcopy.Copy(inbounds).([]string), - Domain: []string{"domain:push-apple.com.akadns.net", "domain:push.apple.com"}, - }) - switch mode { - case configure.WhitelistMode: - // foreign domains with intranet IP should be proxied first rather than directly connected - if asset.DoesV2rayAssetExist("LoyalsoldierSite.dat") { - t.Routing.Rules = append(t.Routing.Rules, - coreObj.RoutingRule{ - Type: "field", - OutboundTag: firstOutboundTag, - InboundTag: deepcopy.Copy(inbounds).([]string), - Domain: []string{"ext:LoyalsoldierSite.dat:geolocation-!cn"}, - }) - } else { - t.Routing.Rules = append(t.Routing.Rules, - coreObj.RoutingRule{ - Type: "field", - OutboundTag: firstOutboundTag, - InboundTag: deepcopy.Copy(inbounds).([]string), - Domain: []string{"geosite:geolocation-!cn"}, - }) - } - t.Routing.Rules = append(t.Routing.Rules, - coreObj.RoutingRule{ - Type: "field", - OutboundTag: "proxy", - InboundTag: deepcopy.Copy(inbounds).([]string), - // https://github.com/v2rayA/v2rayA/issues/285 - Domain: []string{"geosite:google"}, - }, - coreObj.RoutingRule{ - Type: "field", - OutboundTag: "direct", - InboundTag: deepcopy.Copy(inbounds).([]string), - Domain: []string{"geosite:cn"}, - }, - coreObj.RoutingRule{ - Type: "field", - OutboundTag: "proxy", - InboundTag: deepcopy.Copy(inbounds).([]string), - IP: []string{"geoip:hk", "geoip:mo"}, - }, - coreObj.RoutingRule{ - Type: "field", - OutboundTag: "direct", - InboundTag: deepcopy.Copy(inbounds).([]string), - IP: []string{"geoip:private", "geoip:cn"}, - }, - ) - case configure.GfwlistMode: - if asset.DoesV2rayAssetExist("LoyalsoldierSite.dat") { - t.Routing.Rules = append(t.Routing.Rules, - coreObj.RoutingRule{ - Type: "field", - OutboundTag: firstOutboundTag, - InboundTag: deepcopy.Copy(inbounds).([]string), - Domain: []string{"ext:LoyalsoldierSite.dat:gfw"}, - }, - coreObj.RoutingRule{ - Type: "field", - OutboundTag: firstOutboundTag, - InboundTag: deepcopy.Copy(inbounds).([]string), - Domain: []string{"ext:LoyalsoldierSite.dat:greatfire"}, - }) - } else { - t.Routing.Rules = append(t.Routing.Rules, - coreObj.RoutingRule{ - Type: "field", - OutboundTag: firstOutboundTag, - InboundTag: deepcopy.Copy(inbounds).([]string), - Domain: []string{"geosite:geolocation-!cn"}, - }) - } - - t.Routing.Rules = append(t.Routing.Rules, - coreObj.RoutingRule{ - Type: "field", - OutboundTag: firstOutboundTag, - InboundTag: deepcopy.Copy(inbounds).([]string), - // From: https://github.com/Loyalsoldier/geoip/blob/release/text/telegram.txt - IP: []string{"91.105.192.0/23", "91.108.4.0/22", "91.108.8.0/21", "91.108.16.0/21", "91.108.56.0/22", - "95.161.64.0/20", "149.154.160.0/20", "185.76.151.0/24", "2001:67c:4e8::/48", "2001:b28:f23c::/47", - "2001:b28:f23f::/48", "2a0a:f280:203::/48"}, - }, - coreObj.RoutingRule{ - Type: "field", - OutboundTag: "direct", - InboundTag: deepcopy.Copy(inbounds).([]string), - }, - ) - case configure.RoutingAMode: - if err := parseRoutingA(t, deepcopy.Copy(inbounds).([]string)); err != nil { - return err - } - } - return nil -} - -func (t *Template) setRulePortRouting() error { - // append rule-http and rule-socks no mather if they are enabled - // because "The Same as the Rule Port" may need them - return t.AppendRoutingRuleByMode(t.Setting.RulePortMode, []string{"rule-http", "rule-socks"}) -} -func parseRoutingA(t *Template, routingInboundTags []string) error { - lines := strings.Split(configure.GetRoutingA(), "\n") - hardcodeReplacement := regexp.MustCompile(`\$\$.+?\$\$`) - for i := range lines { - hardcodes := hardcodeReplacement.FindAllString(lines[i], -1) - for _, hardcode := range hardcodes { - env := strings.TrimSuffix(strings.TrimPrefix(hardcode, "$$"), "$$") - val, ok := os.LookupEnv(env) - if !ok { - log.Error("RoutingA: Environment variable \"%v\" is not found", env) - } else { - log.Info("RoutingA: Environment variable %v=%v", env, strconv.Quote(val)) - } - lines[i] = strings.Replace(lines[i], hardcode, val, 1) - } - } - rules, err := RoutingA.Parse(strings.Join(lines, "\n")) - if err != nil { - log.Warn("parseRoutingA: %v", err) - return err - } - defaultOutbound, _ := t.FirstProxyOutboundName(nil) - for _, rule := range rules { - switch rule := rule.(type) { - case RoutingA.Define: - switch rule.Name { - case "inbound", "outbound": - switch o := rule.Value.(type) { - case RoutingA.Bound: - proto := o.Value - switch proto.Name { - case "http", "socks": - if len(proto.NamedParams["address"]) < 1 || - len(proto.NamedParams["port"]) < 1 { - continue - } - port, err := strconv.Atoi(proto.NamedParams["port"][0]) - if err != nil { - continue - } - server := coreObj.Server{ - Port: port, - Address: proto.NamedParams["address"][0], - } - if unames := proto.NamedParams["user"]; len(unames) > 0 { - passwords := proto.NamedParams["pass"] - levels := proto.NamedParams["level"] - for i, uname := range unames { - u := coreObj.OutboundUser{ - User: uname, - } - if i < len(passwords) { - u.Pass = passwords[i] - } - if i < len(levels) { - level, err := strconv.Atoi(levels[i]) - if err == nil { - u.Level = level - } - } - server.Users = append(server.Users, u) - } - } - switch rule.Name { - case "outbound": - t.Outbounds = append(t.Outbounds, coreObj.OutboundObject{ - Tag: o.Name, - Protocol: o.Value.Name, - Settings: coreObj.Settings{ - Servers: []coreObj.Server{ - server, - }, - }, - }) - case "inbound": - // DEPRECATED: inbound definition in RoutingA is no longer supported. - // Log a warning and skip creating the inbound. - log.Warn("parseRoutingA: inbound definition '%s' is deprecated and will be ignored. "+ - "Use custom inbound settings with RoutingA rules instead.", o.Name) - } - case "freedom": - settings := coreObj.Settings{} - if len(proto.NamedParams["domainStrategy"]) > 0 { - settings.DomainStrategy = proto.NamedParams["domainStrategy"][0] - } - if len(proto.NamedParams["redirect"]) > 0 { - settings.Redirect = proto.NamedParams["redirect"][0] - } - if len(proto.NamedParams["userLevel"]) > 0 { - level, err := strconv.Atoi(proto.NamedParams["userLevel"][0]) - if err == nil { - settings.UserLevel = &level - } - } - t.Outbounds = append(t.Outbounds, coreObj.OutboundObject{ - Tag: o.Name, - Protocol: o.Value.Name, - Settings: settings, - }) - } - } - } - } - } - outboundTags := t.outNames() - for _, rule := range rules { - switch rule := rule.(type) { - case RoutingA.Define: - switch rule.Name { - case "default": - switch v := rule.Value.(type) { - case string: - defaultOutbound = v - if _, ok := outboundTags[v]; !ok { - return fmt.Errorf(`your RoutingA rules depend on the outbound "%v", thus you should select at least one server in this outbound`, v) - } - } - } - case RoutingA.Routing: - rr := deepcopy.Copy(coreObj.RoutingRule{ - Type: "field", - OutboundTag: rule.Out, - InboundTag: routingInboundTags, - }).(coreObj.RoutingRule) - for _, f := range rule.And { - switch f.Name { - case "domain", "domains": - for k, vv := range f.NamedParams { - for _, v := range vv { - if k == "contains" { - rr.Domain = append(rr.Domain, v) - continue - } - if k == "ext" { - datFilenameAndTag := strings.SplitN(v, ":", 2) - if len(datFilenameAndTag) < 2 { - return fmt.Errorf("%v: tag is not given", v) - } - if !asset.DoesV2rayAssetExist(datFilenameAndTag[0]) { - return fmt.Errorf("%v: file is not found", datFilenameAndTag[0]) - } - } - rr.Domain = append(rr.Domain, fmt.Sprintf("%v:%v", k, v)) - } - } - // unnamed param is not recommended - rr.Domain = append(rr.Domain, f.Params...) - case "ip": - for k, vv := range f.NamedParams { - for _, v := range vv { - if k == "ext" { - datFilenameAndTag := strings.SplitN(v, ":", 2) - if len(datFilenameAndTag) < 2 { - return fmt.Errorf("%v: tag is not given", v) - } - if !asset.DoesV2rayAssetExist(datFilenameAndTag[0]) { - return fmt.Errorf("%v: file is not found", datFilenameAndTag[0]) - } - } - rr.IP = append(rr.IP, fmt.Sprintf("%v:%v", k, v)) - } - } - rr.IP = append(rr.IP, f.Params...) - case "network": - rr.Network = strings.Join(f.Params, ",") - case "port": - rr.Port = strings.Join(f.Params, ",") - case "sourcePort": - rr.SourcePort = strings.Join(f.Params, ",") - case "protocol": - rr.Protocol = f.Params - case "source": - rr.Source = f.Params - case "user": - rr.User = f.Params - case "inboundTag": - rr.InboundTag = f.Params - } - } - if rr.OutboundTag != "" { - if _, ok := outboundTags[rr.OutboundTag]; !ok { - return fmt.Errorf(`your RoutingA rules depend on the outbound "%v", thus you should select at least one server in this outbound`, rr.OutboundTag) - } - } - t.Routing.Rules = append(t.Routing.Rules, rr) - } - } - t.Routing.Rules = append(t.Routing.Rules, coreObj.RoutingRule{ - Type: "field", - OutboundTag: defaultOutbound, - InboundTag: []string{"rule-http", "rule-socks"}, - }) - return nil -} - -// parseRoutingARules parses RoutingA rule text and returns routing rules -// filtered by the given inboundTag. This is used for custom inbound RoutingA rules. -// It does NOT create any inbounds or outbounds - only routing rules. -func parseRoutingARules(rulesText string, inboundTag string) (rules []coreObj.RoutingRule, err error) { - lines := strings.Split(rulesText, "\n") - hardcodeReplacement := regexp.MustCompile(`\$\$.+?\$\$`) - for i := range lines { - hardcodes := hardcodeReplacement.FindAllString(lines[i], -1) - for _, hardcode := range hardcodes { - env := strings.TrimSuffix(strings.TrimPrefix(hardcode, "$$"), "$$") - val, ok := os.LookupEnv(env) - if !ok { - log.Error("parseRoutingARules: Environment variable \"%v\" is not found", env) - } else { - log.Info("parseRoutingARules: Environment variable %v=%v", env, strconv.Quote(val)) - } - lines[i] = strings.Replace(lines[i], hardcode, val, 1) - } - } - parsedRules, err := RoutingA.Parse(strings.Join(lines, "\n")) - if err != nil { - return nil, err - } - for _, rule := range parsedRules { - switch rule := rule.(type) { - case RoutingA.Routing: - rr := deepcopy.Copy(coreObj.RoutingRule{ - Type: "field", - OutboundTag: rule.Out, - InboundTag: []string{inboundTag}, - }).(coreObj.RoutingRule) - for _, f := range rule.And { - switch f.Name { - case "domain", "domains": - for k, vv := range f.NamedParams { - for _, v := range vv { - if k == "contains" { - rr.Domain = append(rr.Domain, v) - continue - } - if k == "ext" { - datFilenameAndTag := strings.SplitN(v, ":", 2) - if len(datFilenameAndTag) < 2 { - return nil, fmt.Errorf("%v: tag is not given", v) - } - if !asset.DoesV2rayAssetExist(datFilenameAndTag[0]) { - return nil, fmt.Errorf("%v: file is not found", datFilenameAndTag[0]) - } - } - rr.Domain = append(rr.Domain, fmt.Sprintf("%v:%v", k, v)) - } - } - rr.Domain = append(rr.Domain, f.Params...) - case "ip": - for k, vv := range f.NamedParams { - for _, v := range vv { - if k == "ext" { - datFilenameAndTag := strings.SplitN(v, ":", 2) - if len(datFilenameAndTag) < 2 { - return nil, fmt.Errorf("%v: tag is not given", v) - } - if !asset.DoesV2rayAssetExist(datFilenameAndTag[0]) { - return nil, fmt.Errorf("%v: file is not found", datFilenameAndTag[0]) - } - } - rr.IP = append(rr.IP, fmt.Sprintf("%v:%v", k, v)) - } - } - rr.IP = append(rr.IP, f.Params...) - case "network": - rr.Network = strings.Join(f.Params, ",") - case "port": - rr.Port = strings.Join(f.Params, ",") - case "sourcePort": - rr.SourcePort = strings.Join(f.Params, ",") - case "protocol": - rr.Protocol = f.Params - case "source": - rr.Source = f.Params - case "user": - rr.User = f.Params - case "inboundTag": - rr.InboundTag = f.Params - } - } - if rr.OutboundTag != "" { - rules = append(rules, rr) - } - } - } - return rules, nil -} - -func (t *Template) setTransparentRouting() (err error) { - defaultOutbound, _ := t.FirstProxyOutboundName(nil) - switch t.Setting.Transparent { - case configure.TransparentProxy: - // Global transparent: route all transparent inbound to default outbound - t.Routing.Rules = append(t.Routing.Rules, coreObj.RoutingRule{ - Type: "field", - InboundTag: []string{"transparent"}, - OutboundTag: defaultOutbound, - }) - case configure.TransparentWhitelist: - return t.AppendRoutingRuleByMode(configure.WhitelistMode, []string{"transparent"}) - case configure.TransparentGfwlist: - return t.AppendRoutingRuleByMode(configure.GfwlistMode, []string{"transparent"}) - case configure.TransparentFollowRule: - // transparent mode is the same as rule - for i := range t.Routing.Rules { - ok := false - for _, in := range t.Routing.Rules[i].InboundTag { - if in == "rule-http" { - ok = true - break - } - } - if ok { - t.Routing.Rules[i].InboundTag = append(t.Routing.Rules[i].InboundTag, "transparent") - } - } - } - return nil -} -func (t *Template) AppendDokodemoTProxy(tproxy string, port int, tag string) { - dokodemo := coreObj.Inbound{ - Listen: "127.0.0.1", - Port: port, - Protocol: "dokodemo-door", - Sniffing: coreObj.Sniffing{ - Enabled: true, - DestOverride: []string{"http", "tls"}, - }, - Settings: &coreObj.InboundSettings{Network: "tcp,udp"}, - Tag: tag, - } - dokodemo.StreamSettings = &coreObj.StreamSettings{Sockopt: &coreObj.Sockopt{Tproxy: &tproxy}} - dokodemo.Settings.FollowRedirect = true - t.Inbounds = append(t.Inbounds, dokodemo) -} - -func (t *Template) SetOutboundSockopt() { - mark := 0x80 - //tos := 184 - for i := range t.Outbounds { - if t.Outbounds[i].Protocol == "blackhole" || t.Outbounds[i].Protocol == "dns" { - continue - } - if t.Outbounds[i].StreamSettings == nil { - t.Outbounds[i].StreamSettings = new(coreObj.StreamSettings) - } - if t.Outbounds[i].StreamSettings.Sockopt == nil { - t.Outbounds[i].StreamSettings.Sockopt = new(coreObj.Sockopt) - } - if t.Outbounds[i].Protocol == "freedom" && t.Outbounds[i].Tag == "direct" { - t.Outbounds[i].Settings.DomainStrategy = "UseIP" - } - if t.Setting.TcpFastOpen != configure.Default { - tmp := t.Setting.TcpFastOpen == configure.Yes - t.Outbounds[i].StreamSettings.Sockopt.TCPFastOpen = &tmp - } - t.checkAndSetMark(&t.Outbounds[i], mark) - } -} -func (t *Template) setDualStack() { - const ( - tag4Suffix = "_ipv4" - tag6Suffix = "_ipv6" - ) - tagMap := make(map[string]struct{}) - inbounds6 := deepcopy.Copy(t.Inbounds).([]coreObj.Inbound) - - // Add ::1 twins for every inbound that listens on a 127.x loopback address. - // Inbounds on 0.0.0.0 (LAN-shared) are not duplicated. - // Special exclusions: - // transparent+Redirect – kernel REDIRECT requires 0.0.0.0 - // dns-in – receives the 127.2.0.17 treatment below - for i := range t.Inbounds { - tag := t.Inbounds[i].Tag - if tag == "transparent" && t.Setting.TransparentType == configure.TransparentRedirect { - // https://ipset.netfilter.org/iptables-extensions.man.html#lbDK - // REDIRECT rewrites the destination to the primary address of the incoming interface, - // so the inbound must stay at 0.0.0.0. - inbounds6[i].Tag = "THIS_IS_A_DROPPED_TAG" - continue - } - if tag == "dns-in" { - // Handled separately — skip generic duplication. - inbounds6[i].Tag = "THIS_IS_A_DROPPED_TAG" - continue - } - if !strings.HasPrefix(t.Inbounds[i].Listen, "127.") { - // 0.0.0.0 or other non-loopback address — no ::1 twin needed. - inbounds6[i].Tag = "THIS_IS_A_DROPPED_TAG" - continue - } - inbounds6[i].Listen = "::1" - if tag != "" { - tagMap[tag] = struct{}{} - t.Inbounds[i].Tag += tag4Suffix - inbounds6[i].Tag += tag6Suffix - } - } - - for i := len(inbounds6) - 1; i >= 0; i-- { - if inbounds6[i].Tag == "THIS_IS_A_DROPPED_TAG" { - inbounds6 = append(inbounds6[:i], inbounds6[i+1:]...) - } - } - - if iptables.IsIPv6Supported() { - t.Inbounds = append(t.Inbounds, inbounds6...) - } - - // Update routing rules with _ipv4/_ipv6 suffixes for duplicated inbounds. - for i := range t.Routing.Rules { - tag6 := make([]string, 0) - for j, tag := range t.Routing.Rules[i].InboundTag { - if _, ok := tagMap[tag]; ok { - t.Routing.Rules[i].InboundTag[j] += tag4Suffix - tag6 = append(tag6, tag+tag6Suffix) - } - } - if v6supported := iptables.IsIPv6Supported(); len(tag6) > 0 && v6supported { - t.Routing.Rules[i].InboundTag = append(t.Routing.Rules[i].InboundTag, tag6...) - } - } - - // dns-in special handling: always bind to 127.2.0.17 for split-routing local queries. - // When PortSharing is on the inbound also stays on 0.0.0.0 for LAN DNS, so we add a - // second copy at 127.2.0.17 with tag dns-in-local. - for i := range t.Inbounds { - if t.Inbounds[i].Tag != "dns-in" { - continue - } - if !t.Setting.PortSharing { - // PortSharing off: move the single dns-in inbound to loopback-only. - t.Inbounds[i].Listen = "127.2.0.17" - } else { - // PortSharing on: keep 0.0.0.0 for LAN; also add a local copy. - if couldListenLocalhost, e := CouldLocalDnsListen(); couldListenLocalhost && e != nil { - // Port 53 is already in use on localhost; only listen on the special address. - t.Inbounds[i].Listen = "127.2.0.17" - } else { - localDnsInbound := t.Inbounds[i] - localDnsInbound.Listen = "127.2.0.17" - localDnsInbound.Tag = "dns-in-local" - t.Inbounds = append(t.Inbounds, localDnsInbound) - // Add dns-in-local to any routing rule that references dns-in. - for ri := range t.Routing.Rules { - for _, rtag := range t.Routing.Rules[ri].InboundTag { - if rtag == "dns-in" { - t.Routing.Rules[ri].InboundTag = append(t.Routing.Rules[ri].InboundTag, "dns-in-local") - break - } - } - } - } - } - break - } -} -func (t *Template) appendDNSOutbound() { - t.Outbounds = append(t.Outbounds, coreObj.OutboundObject{ - Tag: "dns-out", - Protocol: "dns", - // DNS outbound without address setting will use the internal DNS module, - // which respects the DNS servers configured in the dns block (e.g., 8.8.4.4, 180.184.1.1) - // and applies DNS routing rules properly. - // See: https://www.v2fly.org/config/protocols/dns.html - }) -} - -func (t *Template) setSendThrough() { - for i := 0; i < len(t.Outbounds); i++ { - outbound := &t.Outbounds[i] - - // Get server info for this outbound - sInfo, exists := t.serverInfoMap[outbound.Tag] - if !exists { - continue - } - - // Determine the appropriate local address - sendThrough := t.getSendThroughForServer(sInfo) - if sendThrough != "" { - outbound.SendThrough = sendThrough - log.Trace("[v2ray] Set sendThrough for %s: %s", outbound.Tag, sendThrough) - } - } -} - -func (t *Template) getSendThroughForServer(sInfo *serverInfo) string { - serverHost := sInfo.Info.GetHostname() - - // If connecting to plugin (localhost), use 127.0.0.1 - if sInfo.PluginPort > 0 { - return "127.0.0.1" - } - - // Check if server is IPv4 or IPv6 - if serverIP := net.ParseIP(serverHost); serverIP != nil { - if serverIP.To4() != nil { - // IPv4 server - use IPv4 local address - if ip, err := GetBestLocalIP(false); err == nil { - return ip.String() - } - } else { - // IPv6 server - use IPv6 local address - if ip, err := GetBestLocalIP(true); err == nil { - return ip.String() - } - // Fallback to link-local IPv6 if no global address available - if ip, err := GetLinkLocalIPv6(); err == nil { - return ip.String() - } - } - } else { - // Domain name - prefer IPv4 - if ip, err := GetBestLocalIP(false); err == nil { - return ip.String() - } - } - - return "" -} - -// GetBestLocalIP returns the best local IP address, skipping TUN, loopback, and APIPA addresses -func GetBestLocalIP(preferIPv6 bool) (net.IP, error) { - interfaces, err := net.Interfaces() - if err != nil { - return nil, err - } - - var bestIP net.IP - - for _, iface := range interfaces { - // Skip interfaces that are down - if iface.Flags&net.FlagUp == 0 { - continue - } - - // Skip TUN interfaces (typically named tun0, utun0, etc.) - ifName := strings.ToLower(iface.Name) - if strings.Contains(ifName, "tun") || strings.Contains(ifName, "tap") { - continue - } - - addrs, err := iface.Addrs() - if err != nil { - continue - } - - for _, addr := range addrs { - ipnet, ok := addr.(*net.IPNet) - if !ok { - continue - } - - ip := ipnet.IP - - // Skip loopback - if ip.IsLoopback() { - continue - } - - // Skip APIPA (169.254.x.x) - if ip.To4() != nil && ip.To4()[0] == 169 && ip.To4()[1] == 254 { - continue - } - - if preferIPv6 { - if ip.To4() == nil && ip.To16() != nil { - // IPv6 address - // Skip link-local for now (fe80::), prefer global - if !ip.IsLinkLocalUnicast() { - return ip, nil - } - if bestIP == nil { - bestIP = ip - } - } - } else { - if ip.To4() != nil { - // IPv4 address - return ip, nil - } - } - } - } - - if bestIP != nil { - return bestIP, nil - } - - if preferIPv6 { - return nil, errors.New("no suitable IPv6 address found") - } - return nil, errors.New("no suitable IPv4 address found") -} - -// GetLinkLocalIPv6 returns a link-local IPv6 address as fallback -func GetLinkLocalIPv6() (net.IP, error) { - interfaces, err := net.Interfaces() - if err != nil { - return nil, err - } - - for _, iface := range interfaces { - if iface.Flags&net.FlagUp == 0 { - continue - } - - // Skip TUN interfaces - ifName := strings.ToLower(iface.Name) - if strings.Contains(ifName, "tun") || strings.Contains(ifName, "tap") { - continue - } - - addrs, err := iface.Addrs() - if err != nil { - continue - } - - for _, addr := range addrs { - ipnet, ok := addr.(*net.IPNet) - if !ok { - continue - } - - ip := ipnet.IP - if ip.To4() == nil && ip.To16() != nil && ip.IsLinkLocalUnicast() { - return ip, nil - } - } - } - - return nil, errors.New("no link-local IPv6 address found") -} - -func GenerateIdFromAccounts() (id string, err error) { - accounts, err := configure.GetAccounts() - if err != nil { - return "", err - } - sort.Slice(accounts, func(i, j int) bool { - if accounts[i][0] == accounts[j][0] { - return accounts[i][1] < accounts[j][1] - } - return accounts[i][0] < accounts[j][0] - }) - h := sha256.New() - for _, account := range accounts { - h.Write([]byte(account[0])) - h.Write([]byte(account[1])) - } - id = common.StringToUUID5(hex.EncodeToString(h.Sum(nil))) - return id, nil -} - -func SetVmessInbound(vmess *coreObj.Inbound) (err error) { - id, err := GenerateIdFromAccounts() - if err != nil { - return err - } - vmess.Settings.Clients = []coreObj.VlessClient{{Id: id}} - return nil -} - -func (t *Template) setInbound(setting *configure.Setting) error { - p := configure.GetPortsNotNil() - if p != nil { - t.Inbounds[0].Port = p.Socks5 - t.Inbounds[1].Port = p.Http - t.Inbounds[2].Port = p.Socks5WithPac - t.Inbounds[3].Port = p.HttpWithPac - listenAddr := "127.0.0.1" - if t.Setting.PortSharing { - listenAddr = "0.0.0.0" - } - for i := 0; i < 5 && i < len(t.Inbounds); i++ { - t.Inbounds[i].Listen = listenAddr - } - vmess := &t.Inbounds[4] - vmess.Port = p.Vmess - if p.Vmess > 0 { - if err := SetVmessInbound(vmess); err != nil { - return err - } - } - } - // remove those inbounds with zero port number - for i := len(t.Inbounds) - 1; i >= 0; i-- { - if t.Inbounds[i].Port == 0 { - t.Inbounds = append(t.Inbounds[:i], t.Inbounds[i+1:]...) - } - } - // Append user-defined custom inbounds (SOCKS / HTTP only) - listenAddrForCustom := "127.0.0.1" - if t.Setting != nil && t.Setting.PortSharing { - listenAddrForCustom = "0.0.0.0" - } - for _, ci := range configure.GetCustomInbounds() { - if ci.Port <= 0 || (ci.Protocol != "socks" && ci.Protocol != "http") { - continue - } - ib := coreObj.Inbound{ - Port: ci.Port, - Protocol: ci.Protocol, - Listen: listenAddrForCustom, - Tag: ci.Tag, - } - if ci.Protocol == "socks" { - ib.Settings = &coreObj.InboundSettings{UDP: true} - } - t.Inbounds = append(t.Inbounds, ib) - - // Generate per-inbound routing rules based on the bound outbound group - if ci.Outbound != "" && ci.OutboundType != "" { - switch ci.OutboundType { - case "direct": - // Direct single outbound: route all traffic from this inbound to the bound outbound group - t.Routing.Rules = append(t.Routing.Rules, coreObj.RoutingRule{ - Type: "field", - OutboundTag: ci.Outbound, - InboundTag: []string{ci.Tag}, - }) - case "routingA": - // RoutingA rules: parse and apply with InboundTag filter - if ci.RoutingARules != "" { - rules, err := parseRoutingARules(ci.RoutingARules, ci.Tag) - if err != nil { - log.Warn("setInbound: failed to parse RoutingA rules for inbound %s: %v", ci.Tag, err) - } else { - t.Routing.Rules = append(t.Routing.Rules, rules...) - } - } - } - } - } - if IsTransparentOn(t.Setting) { - switch t.Setting.TransparentType { - case configure.TransparentTproxy, configure.TransparentRedirect: - t.AppendDokodemoTProxy(string(t.Setting.TransparentType), 52345, "transparent") - case configure.TransparentSystemProxy: - t.Inbounds = append(t.Inbounds, coreObj.Inbound{ - Port: 52345, - Protocol: "http", - Listen: "127.0.0.1", - Tag: "transparent", - }, coreObj.Inbound{ - Port: 52306, - Protocol: "socks", - Listen: "127.0.0.1", - Settings: &coreObj.InboundSettings{ - UDP: true, - }, - Tag: "transparent-socks", - }) - case configure.TransparentTun: - t.Inbounds = append(t.Inbounds, coreObj.Inbound{ - Port: tinytunSocksPort, - Protocol: "socks", - Listen: "127.0.0.1", - Settings: &coreObj.InboundSettings{ - UDP: true, - }, - Tag: "transparent", - }) - // TinyTun v0.0.2+ handles DNS routing natively via its own DNS groups. - // The former dns-in-tun dokodemo-door (127.0.0.1:6053) is no longer needed; - // v2ray acts as a pure SOCKS5 forwarder for non-DNS traffic. - } - - } - if ShouldLocalDnsListen() { - if couldListenLocalhost, err := CouldLocalDnsListen(); couldListenLocalhost { - // set up a solo dokodemo-door for dns - t.Inbounds = append(t.Inbounds, coreObj.Inbound{ - Port: 53, - Protocol: "dokodemo-door", - Listen: "0.0.0.0", - Settings: &coreObj.InboundSettings{ - Network: "udp", - // the non-A/AAAA/CNAME problem has been fixed by the setting in DNS outbound. - // so the Address here is innocuous. - // related commit: https://github.com/v2rayA/v2rayA/commit/ecbf915d4be8b9066955a21059519266bcca6b92 - Address: "2.0.1.7", - Port: 53, - }, - Tag: "dns-in", - }) - } else { - log.Warn("DNS hijack may be unavailable: cannot listen on port 53: %v", err) - } - } - - // Set up domain sniffing - if setting.InboundSniffing != configure.InboundSniffingDisable && setting.InboundSniffing != "" { - enableSniffingRouteOnly := configure.GetSettingNotNil().RouteOnly - domainsExcludedText := configure.GetDomainsExcluded() - for i := len(t.Inbounds) - 1; i >= 0; i-- { - if setting.InboundSniffing == configure.InboundSniffingHttpTLS { - t.Inbounds[i].Sniffing.DestOverride = []string{"http", "tls"} - } else { - t.Inbounds[i].Sniffing.DestOverride = []string{"http", "tls", "quic"} - } - t.Inbounds[i].Sniffing.DomainsExcluded = strings.Split(domainsExcludedText, "\n") - t.Inbounds[i].Sniffing.Enabled = true - t.Inbounds[i].Sniffing.RouteOnly = enableSniffingRouteOnly - } - - } - return nil -} - -type serverInfo struct { - Info serverObj.ServerObj - OutboundName string - PluginPort int -} - -func GroupWrapper(ps string) string { - return fmt.Sprintf("『%v』", ps) -} - -func (t *Template) updatePrivateRouting() { - privateAddrs, _ := iptables.GetLocalCIDR() - if len(privateAddrs) == 0 { - return - } - for i := range t.Routing.Rules { - for j := range t.Routing.Rules[i].IP { - if t.Routing.Rules[i].IP[j] == "geoip:private" { - t.Routing.Rules[i].IP = append(t.Routing.Rules[i].IP, privateAddrs...) - break - } - } - } -} - -func (t *Template) optimizeGeoipMemoryOccupation() { - if asset.DoesV2rayAssetExist("geoip-only-cn-private.dat") { - for i := range t.Routing.Rules { - for j := range t.Routing.Rules[i].IP { - switch t.Routing.Rules[i].IP[j] { - case "geoip:private", "geoip:cn": - t.Routing.Rules[i].IP[j] = "ext:geoip-only-cn-private.dat:" + strings.TrimPrefix(t.Routing.Rules[i].IP[j], "geoip:") - } - } - } - } -} - -func (t *Template) setWhitelistRouting(whitelist []Addr) { - var rules []coreObj.RoutingRule - for _, addr := range whitelist { - if net.ParseIP(addr.host) != nil { - rules = append(rules, coreObj.RoutingRule{ - Type: "field", - OutboundTag: "direct", - IP: []string{addr.host}, - Port: addr.port, - }) - } else { - rules = append(rules, coreObj.RoutingRule{ - Type: "field", - OutboundTag: "direct", - Domain: []string{addr.host}, - Port: addr.port, - }) - } - } - if len(rules) > 0 { - t.Routing.Rules = append(rules, t.Routing.Rules...) - } -} - -func (t *Template) setGroupRouting() { - outbounds := t.outNames() - for i := range t.Routing.Rules { - if t.Routing.Rules[i].OutboundTag != "" && outbounds[t.Routing.Rules[i].OutboundTag] == true { - t.Routing.Rules[i].BalancerTag, t.Routing.Rules[i].OutboundTag = t.Routing.Rules[i].OutboundTag, "" - } - } -} - -type ServerData struct { - RawServerInfos []serverInfo - ServerInfos []serverInfo - OutboundName2Setting map[string]configure.OutboundSetting - Link2ServerInfos map[string][]*serverInfo - Link2ServerObj map[string]serverObj.ServerObj - OutboundName2ServerObjs map[string][]serverObj.ServerObj -} - -func NewServerData(serverInfos []serverInfo) (serverData *ServerData) { - // guarantee that an v2ray outbound is reusable for balancers - var rawServerInfos = make([]serverInfo, len(serverInfos)) - copy(rawServerInfos, serverInfos) - link2ServerInfos := make(map[string][]*serverInfo) - link2ServerObj := make(map[string]serverObj.ServerObj) - for i, info := range serverInfos { - link := info.Info.ExportToURL() - link2ServerObj[link] = info.Info - link2ServerInfos[link] = append(link2ServerInfos[link], &serverInfos[i]) - } - // make ps unique - link2ServerInfosAfter := make(map[string][]*serverInfo) - mPsRenaming := make(map[string]struct{}) - for link, ois := range link2ServerInfos { - ps := link2ServerObj[link].GetName() - cnt := 2 - for { - if _, ok := mPsRenaming[ps]; !ok { - mPsRenaming[ps] = struct{}{} - link2ServerObj[link].SetName(ps) - link2ServerInfosAfter[link] = ois - break - } - ps = fmt.Sprintf("%v(%v)", link2ServerObj[link].GetName(), strconv.Itoa(cnt)) - cnt++ - } - } - - outboundName2ServerObjs := make(map[string][]serverObj.ServerObj) - for link, ois := range link2ServerInfosAfter { - for _, oi := range ois { - outboundName2ServerObjs[oi.OutboundName] = append(outboundName2ServerObjs[oi.OutboundName], link2ServerObj[link]) - } - } - - OutboundName2Setting := make(map[string]configure.OutboundSetting) - for outbound := range outboundName2ServerObjs { - OutboundName2Setting[outbound] = configure.GetOutboundSetting(outbound) - } - - return &ServerData{ - RawServerInfos: rawServerInfos, - ServerInfos: serverInfos, - Link2ServerInfos: link2ServerInfosAfter, - Link2ServerObj: link2ServerObj, - OutboundName2ServerObjs: outboundName2ServerObjs, - OutboundName2Setting: OutboundName2Setting, - } -} - -func (sd *ServerData) ServerObj2ServerInfos() map[serverObj.ServerObj][]*serverInfo { - m := make(map[serverObj.ServerObj][]*serverInfo) - for link, sObj := range sd.Link2ServerObj { - m[sObj] = sd.Link2ServerInfos[link] - } - return m -} - -func (sd *ServerData) Ps2OutboundNames() map[string][]string { - ps2OutboundNames := make(map[string][]string) - for outboundName, objs := range sd.OutboundName2ServerObjs { - for _, vi := range objs { - ps2OutboundNames[vi.GetName()] = append(ps2OutboundNames[vi.GetName()], outboundName) - } - } - return ps2OutboundNames -} - -// resolveEffectiveBackend returns the effective backend ("v2ray" or "") for a ServerObj. -// It checks the node's own backend setting first, then falls back to the system setting. -func resolveEffectiveBackend(obj serverObj.ServerObj, setting *configure.Setting) string { - bg, ok := obj.(serverObj.BackendGetter) - if !ok { - return "" - } - nodeBackend := bg.GetBackend() - if nodeBackend != "" { - return nodeBackend - } - // Fall back to system setting - switch obj.GetProtocol() { - case "shadowsocks", "ss": - return setting.SsBackend - case "trojan", "trojan-go": - return setting.TrojanBackend - } - return "" -} - -func (t *Template) resolveOutbounds( - serverData *ServerData, -) (supportUDP map[string]bool, outboundTags []string, err error) { - - supportUDP = make(map[string]bool) - t.serverInfoMap = make(map[string]*serverInfo) - type _outbound struct { - weight int - outbound coreObj.OutboundObject - balancer bool - } - serverInfo2Index := make(map[*serverInfo]int) - for i := range serverData.ServerInfos { - serverInfo2Index[&serverData.ServerInfos[i]] = i - } - // keep order with serverInfos - outboundTags = make([]string, len(serverData.ServerInfos)) - var extraOutbounds []coreObj.OutboundObject - var outbounds []_outbound - setting := configure.GetSettingNotNil() - for obj, sInfos := range serverData.ServerObj2ServerInfos() { - var ( - usedByBalancer bool - ) - // an vmessInfo(server template) may be used by multiple serverInfos(a connected server) - - // outbound name is not just v2ray outbound tag, it may be a balancer - type balancer struct { - name string - serverInfo *serverInfo - } - var balancers []balancer - for _, sInfo := range sInfos { - if len(serverData.OutboundName2ServerObjs[sInfo.OutboundName]) > 1 { - // balancer - if !usedByBalancer { - usedByBalancer = true - } - balancers = append(balancers, balancer{ - name: sInfo.OutboundName, - serverInfo: sInfo, - }) - } else { - // pure outbound - outboundTag := sInfo.OutboundName - c, err := obj.Configuration(serverObj.PriorInfo{ - Variant: t.Variant, - CoreVersion: t.CoreVersion, - Tag: outboundTag, - PluginPort: sInfo.PluginPort, - Backend: resolveEffectiveBackend(obj, setting), - }) - if err != nil { - return nil, nil, err - } - // Store server info for this outbound - t.serverInfoMap[outboundTag] = sInfo - extraOutbounds = append(extraOutbounds, c.ExtraOutbounds...) - outbounds = append(outbounds, _outbound{ - weight: serverInfo2Index[sInfo], - outbound: c.CoreOutbound, - balancer: false, - }) - outboundTags[serverInfo2Index[sInfo]] = outboundTag - supportUDP[sInfo.OutboundName] = c.UDPSupport - } - } - if usedByBalancer { - // the v2ray outbound is shared by balancers - outboundTag := GroupWrapper(obj.GetName()) - c, err := obj.Configuration(serverObj.PriorInfo{ - Variant: t.Variant, - CoreVersion: t.CoreVersion, - Tag: outboundTag, - PluginPort: 0, - Backend: resolveEffectiveBackend(obj, setting), - }) - if err != nil { - // Store server info for balancer outbound (use first balancer's info) - if len(balancers) > 0 { - t.serverInfoMap[outboundTag] = balancers[0].serverInfo - } - return nil, nil, err - } - extraOutbounds = append(extraOutbounds, c.ExtraOutbounds...) - for _, v := range balancers { - c.CoreOutbound.Balancers = append(c.CoreOutbound.Balancers, v.name) - } - // we use the lowest serverInfo index as the order weight of the balancer outbound - weight := -1 - for _, v := range balancers { - index := serverInfo2Index[v.serverInfo] - if weight == -1 || weight > index { - weight = index - } - // tag - outboundTags[index] = outboundTag - } - outbounds = append(outbounds, _outbound{ - weight: weight, - outbound: c.CoreOutbound, - balancer: true, - }) - - // if any node does not support UDP, the outbound should be tagged as UDP unsupported - for _, outboundName := range c.CoreOutbound.Balancers { - _supportUDP := c.UDPSupport - if _, ok := supportUDP[outboundName]; !ok { - supportUDP[outboundName] = _supportUDP - } - if supportUDP[outboundName] && !_supportUDP { - supportUDP[outboundName] = false - } - } - } - } - sort.Slice(outbounds, func(i, j int) bool { - return outbounds[i].weight < outbounds[j].weight - }) - for _, v := range outbounds { - t.Outbounds = append(t.Outbounds, v.outbound) - } - t.Outbounds = append(t.Outbounds, coreObj.OutboundObject{ - Tag: "direct", - Protocol: "freedom", - }, coreObj.OutboundObject{ - Tag: "block", - Protocol: "blackhole", - }) - t.Outbounds = append(t.Outbounds, extraOutbounds...) - return supportUDP, outboundTags, nil -} - -func (t *Template) SetAPI(serverData *ServerData) (port int, err error) { - // find a valid port - config := configure.GetPortsNotNil() - if config.Api.Port != 0 { - port = config.Api.Port - } else { - for { - if l, err := net.Listen("tcp4", "127.0.0.1:0"); err == nil { - port = l.Addr().(*net.TCPAddr).Port - _ = l.Close() - break - } - time.Sleep(30 * time.Millisecond) - } - } - services := []string{ - "LoggerService", - } - services = slicex.Uniq(append(services, config.Api.Services...)) - // observatory - if serverData != nil { - outbounds := t.outNames() - for outbound, isGroup := range outbounds { - if !isGroup { - continue - } - - //TODO: random, leastload - strategy := serverData.OutboundName2Setting[outbound].Type - interval, err := time.ParseDuration(serverData.OutboundName2Setting[outbound].ProbeInterval) - if err != nil { - log.Warn("observatory: %v", err) - interval = 10 * time.Second - } - var selector []string - - for _, vi := range serverData.OutboundName2ServerObjs[outbound] { - selector = append(selector, GroupWrapper(vi.GetName())) - } - - t.Routing.Balancers = append(t.Routing.Balancers, coreObj.Balancer{ - Tag: outbound, - Selector: selector, - Strategy: coreObj.BalancerStrategy{ - Type: strategy.String(), - Settings: &coreObj.StrategySettings{ - ObserverTag: outbound, - }, - }, - }) - - if strings.ToLower(strategy.String()) == "leastping" { - probeUrl := serverData.OutboundName2Setting[outbound].ProbeURL - if _, err := url.Parse(probeUrl); err != nil { - log.Warn("observatory: %v", err) - probeUrl = "https://gstatic.com/generate_204" - } - - // v2raya_core always uses MultiObservatory: one observer per balancer group. - if t.MultiObservatory == nil { - t.MultiObservatory = &coreObj.MultiObservatory{} - } - t.MultiObservatory.Observers = append(t.MultiObservatory.Observers, coreObj.ObservatoryItem{ - Tag: outbound, - Settings: coreObj.Observatory{ - SubjectSelector: selector, - PingConfig: &coreObj.PingConfig{ - Destination: probeUrl, - Interval: interval.String(), - }, - // Keep legacy fields for backward compatibility with older custom cores. - ProbeURL: probeUrl, - ProbeInterval: interval.String(), - }, - }) - } - } - if t.MultiObservatory != nil || t.Observatory != nil { - // v2raya_core supports ObservatoryService via the v2ray-compat gRPC path. - if t.Variant == where.V2rayaCore { - - var observatoryTags []string - for name, isGroup := range t.outNames() { - if isGroup { - observatoryTags = append(observatoryTags, name) - } - } - t.ApiCloses = append(t.ApiCloses, ObservatoryProducer(port, observatoryTags)) - } - } - } - t.API = &coreObj.APIObject{ - Tag: "api-out", - Services: services, - } - - t.Inbounds = append(t.Inbounds, coreObj.Inbound{ - Port: port, - Protocol: "dokodemo-door", - Listen: "127.0.0.1", - Settings: &coreObj.InboundSettings{ - Address: "127.0.0.1", - }, - Tag: "api-in", - }) - t.Routing.Rules = append(t.Routing.Rules, coreObj.RoutingRule{ - Type: "field", - InboundTag: []string{"api-in"}, - OutboundTag: "api-out", - }) - t.ApiPort = port - return port, nil -} - -func (t *Template) setVmessInboundRouting() { - if configure.GetPortsNotNil().Vmess <= 0 { - return - } - for i := range t.Routing.Rules { - var bHasRule bool - for _, tag := range t.Routing.Rules[i].InboundTag { - if tag == "rule-http" { - bHasRule = true - } - } - if bHasRule { - t.Routing.Rules[i].InboundTag = append(t.Routing.Rules[i].InboundTag, "vmess") - } - } -} - -func NewTemplate(serverInfos []serverInfo, setting *configure.Setting) (t *Template, err error) { - serverData := NewServerData(serverInfos) - if setting != nil { - setting.FillEmpty() - } else { - setting = configure.GetSettingNotNil() - } - - var tmplJson Template - // read template json - raw := []byte(TemplateJson) - err = jsoniter.Unmarshal(raw, &tmplJson) - if err != nil { - return nil, fmt.Errorf("error occurs while reading template json, please check whether templateJson variable is correct json format") - } - tmplJson.Variant, tmplJson.CoreVersion, _ = where.GetV2rayServiceVersion() - t = &tmplJson - t.Setting = setting - // log - logLevel := setting.LogLevel - if logLevel == "" { - logLevel = conf.GetEnvironmentConfig().LogLevel - } - logLevel = strings.ToLower(logLevel) - t.Log = new(coreObj.Log) - switch logLevel { - case "trace", "debug": - t.Log.Loglevel = "debug" - t.Log.Access = "" - t.Log.Error = "" - case "info": - t.Log.Loglevel = "info" - t.Log.Access = "" - t.Log.Error = "none" - case "warn", "warning": - t.Log.Loglevel = "warning" - t.Log.Access = "none" - t.Log.Error = "" - case "error": - t.Log.Loglevel = "error" - t.Log.Access = "none" - t.Log.Error = "" - default: - t.Log = nil - } - // resolve Outbounds - supportUDP, outboundTags, err := t.resolveOutbounds(serverData) - if err != nil { - return nil, err - } - t.OutboundTags = outboundTags - - //set inbound ports according to the setting - if err = t.setInbound(setting); err != nil { - return nil, err - } - // When TinyTun is active it handles DNS routing natively; v2ray only forwards traffic. - // Skip the DNS module, DNS inbound, and DNS outbound for that mode. - isTinyTunMode := setting.TransparentType == configure.TransparentTun && IsTransparentOn(setting) - var dnsRouting []coreObj.RoutingRule - if !isTinyTunMode { - //set DNS - dnsRouting, err = t.setDNS(serverInfos, supportUDP) - if err != nil { - return nil, err - } - //append a DNS outbound - t.appendDNSOutbound() - } - //DNS routing - t.Routing.DomainMatcher = "mph" - t.setDNSRouting(dnsRouting, supportUDP) - //rule port routing - if err = t.setRulePortRouting(); err != nil { - return nil, err - } - //transparent routing - if IsTransparentOn(setting) { - if err = t.setTransparentRouting(); err != nil { - return nil, err - } - } - //set vmess inbound routing - t.setVmessInboundRouting() - // set api - if t.API == nil { - if _, err = t.SetAPI(serverData); err != nil { - return nil, err - } - } - // set routing whitelist - var whitelist []Addr - for _, info := range serverInfos { - port := "" - if info.Info.GetPort() != 0 { - port = strconv.Itoa(info.Info.GetPort()) - } - whitelist = append(whitelist, Addr{ - host: info.Info.GetHostname(), - port: port, - }) - } - t.setWhitelistRouting(whitelist) - - t.updatePrivateRouting() - - // add spare tire outbound routing. Fix: https://github.com/v2rayA/v2rayA/issues/447 - t.Routing.Rules = append(t.Routing.Rules, coreObj.RoutingRule{Type: "field", Port: "0-65535", OutboundTag: "proxy"}) - - // Set group routing. This should be put in the end of routing setters. - t.setGroupRouting() - - t.optimizeGeoipMemoryOccupation() - - //set outboundSockopt - t.SetOutboundSockopt() - - //set inbound listening address and routing - t.setDualStack() - - //check if there are any duplicated tags - if err = t.checkDuplicatedTags(); err != nil { - return nil, err - } - //check if there are any duplicated inbound ports - if err = t.checkDuplicatedInboundSockets(); err != nil { - return nil, err - } - - return t, nil -} - -func (t *Template) checkDuplicatedTags() error { - inboundTagsSet := make(map[string]interface{}) - for _, in := range t.Inbounds { - tag := in.Tag - if _, exists := inboundTagsSet[tag]; exists { - return fmt.Errorf("duplicated inbound tag: %v", tag) - } else { - inboundTagsSet[tag] = nil - } - } - outboundTagsSet := make(map[string]interface{}) - for _, out := range t.Outbounds { - tag := out.Tag - if _, exists := outboundTagsSet[tag]; exists { - return fmt.Errorf("duplicated outbound tag: %v", tag) - } else { - outboundTagsSet[tag] = nil - } - } - return nil -} - -func (t *Template) checkDuplicatedInboundSockets() error { - inboundSocketSet := make(map[string]interface{}) - for _, in := range t.Inbounds { - if in.Listen == "" { - // https://www.v2fly.org/config/inbounds.html#inboundobject - in.Listen = "0.0.0.0" - } - socket := net.JoinHostPort(in.Listen, strconv.Itoa(in.Port)) - if _, exists := inboundSocketSet[socket]; exists { - return fmt.Errorf("duplicated inbound listening address: %v", socket) - } else { - inboundSocketSet[socket] = nil - } - } - return nil -} - -var OccupiedErr = fmt.Errorf("port is occupied") - -func PortOccupied(syntax []string) (err error) { - occupied, sockets, err := ports.IsPortOccupied(syntax) - if err != nil { - if errors.Is(err, netstat.ErrorNotSupportOSErr) { - log.Trace("PortOccupied: %v", err) - return nil - } - return - } - if occupied { - if err = netstat.FillProcesses(sockets); err != nil { - if errors.Is(err, netstat.ErrorNotSupportOSErr) { - log.Warn("cannot judge port occupation: %v", err) - return nil - } - return fmt.Errorf("failed to check if port is occupied: %w", err) - } - for _, s := range sockets { - p := s.Proc - if p == nil { - continue - } - if ownPID := strconv.Itoa(os.Getpid()); p.PPID == ownPID || - p.PID == ownPID { - continue - } - occupiedErr := fmt.Errorf("%w by %v(%v): %v", OccupiedErr, p.Name, p.PID, s.LocalAddress.Port) - if configure.GetSettingNotNil().PortSharing { - // want to listen 0.0.0.0, which conflicts with all IPs - return occupiedErr - } - if s.LocalAddress.IP.IsUnspecified() { - return occupiedErr - } - if s.LocalAddress.IP.IsLoopback() { - return occupiedErr - } - } - } - return nil -} - -func (t *Template) CheckInboundPortsOccupied() (err error) { - var st []string - for _, in := range t.Inbounds { - switch strings.ToLower(in.Protocol) { - case "http", "vmess", "vless", "trojan": - st = append(st, strconv.Itoa(in.Port)+":tcp") - case "dokodemo-door": - if strings.HasPrefix(in.Tag, "dns-in") { - // checked before - continue - } else if in.Settings != nil && in.Settings.Network != "" { - st = append(st, strconv.Itoa(in.Port)+":"+in.Settings.Network) - } else { - st = append(st, strconv.Itoa(in.Port)+":tcp,udp") - } - default: - st = append(st, strconv.Itoa(in.Port)+":tcp,udp") - } - } - return PortOccupied(st) -} - -func (t *Template) ToConfigBytes() []byte { - b, _ := jsoniter.Marshal(t) - return b -} - -func WriteV2rayConfig(content []byte) (err error) { - err = os.WriteFile(asset.GetV2rayConfigPath(), content, os.FileMode(0600)) - if err != nil { - return fmt.Errorf("WriteV2rayConfig: %w", err) - } - return -} - -func NewEmptyTemplate(setting *configure.Setting) (t *Template) { - t = new(Template) - t.Variant, t.CoreVersion, _ = where.GetV2rayServiceVersion() - if setting != nil { - setting.FillEmpty() - } else { - setting = configure.GetSettingNotNil() - } - t.Setting = setting - return t -} - -func (t *Template) checkAndSetMark(o *coreObj.OutboundObject, mark int) { - if !IsTransparentOn(t.Setting) { - return - } - if o.StreamSettings == nil { - o.StreamSettings = new(coreObj.StreamSettings) - } - if o.StreamSettings.Sockopt == nil { - o.StreamSettings.Sockopt = new(coreObj.Sockopt) - } - o.StreamSettings.Sockopt.Mark = &mark -} - -func (t *Template) InsertMappingOutbound(o serverObj.ServerObj, inboundPort string, udpSupport bool, pluginPort int, protocol string) (err error) { - if t.CoreVersion == "" { - t.Variant, t.CoreVersion, _ = where.GetV2rayServiceVersion() - } - c, err := o.Configuration(serverObj.PriorInfo{ - Variant: t.Variant, - CoreVersion: t.CoreVersion, - Tag: "outbound" + inboundPort, - PluginPort: pluginPort, - Backend: resolveEffectiveBackend(o, configure.GetSettingNotNil()), - }) - if err != nil { - return err - } - var mark = 0x80 - t.checkAndSetMark(&c.CoreOutbound, mark) - t.Outbounds = append(t.Outbounds, c.CoreOutbound) - t.Outbounds = append(t.Outbounds, c.ExtraOutbounds...) - iPort, err := strconv.Atoi(inboundPort) - if err != nil || iPort <= 0 { - return fmt.Errorf("port of inbound must be a positive number with string type") - } - if protocol == "" { - protocol = "socks" - } - t.Inbounds = append(t.Inbounds, coreObj.Inbound{ - Port: iPort, - Protocol: protocol, - Listen: "0.0.0.0", - Sniffing: coreObj.Sniffing{ - Enabled: false, - DestOverride: []string{"http", "tls"}, - }, - Settings: &coreObj.InboundSettings{ - Auth: "noauth", - UDP: udpSupport, - }, - Tag: "inbound" + inboundPort, - }) - if t.Routing.DomainStrategy == "" { - t.Routing.DomainStrategy = "IPOnDemand" - } - // Insert at the beginning - tmp := make([]coreObj.RoutingRule, 1, len(t.Routing.Rules)+1) - tmp[0] = coreObj.RoutingRule{ - Type: "field", - OutboundTag: "outbound" + inboundPort, - InboundTag: []string{"inbound" + inboundPort}, - } - t.Routing.Rules = append(tmp, t.Routing.Rules...) - return -} diff --git a/service/db/configure/configure.go b/service/db/configure/configure.go index 7c6de498..bb422646 100644 --- a/service/db/configure/configure.go +++ b/service/db/configure/configure.go @@ -15,6 +15,12 @@ import ( "github.com/v2rayA/v2rayA/pkg/util/log" ) +// isJSONFieldExists 检查原始 JSON 中是否存在指定字段。 +// 用于在迁移场景中判断字段是否由旧配置显式设置。 +func isJSONFieldExists(raw []byte, field string) bool { + return gjson.GetBytes(raw, field).Exists() +} + type Configure struct { Servers []*ServerRaw `json:"servers"` Subscriptions []*SubscriptionRaw `json:"subscriptions"` @@ -207,6 +213,26 @@ func GetSettingNotNil() *Setting { if r.TransparentType == "" { r.TransparentType = TransparentRedirect } + // 执行新 DNS 模块配置迁移(处理旧配置升级场景) + MigrateSetting(r) + // 处理 DNS 缓存布尔字段默认值:common.FillEmpty 跳过布尔字段, + // 因此如果旧配置中缺少这些字段,它们会保持 false。 + if e == nil && b != nil { + hasDNSListenAddr := isJSONFieldExists(b, "dnsListenAddr") + hasDNSCacheEnabled := isJSONFieldExists(b, "dnsCacheEnabled") + hasDNSPrefetch := isJSONFieldExists(b, "dnsPrefetch") + hasDNSNegativeCache := isJSONFieldExists(b, "dnsNegativeCache") + + if !hasDNSListenAddr && !hasDNSCacheEnabled && !hasDNSPrefetch && !hasDNSNegativeCache { + r.DnsCacheEnabled = true + r.DnsPrefetch = true + r.DnsNegativeCache = true + } + } else if e != nil || b == nil { + r.DnsCacheEnabled = true + r.DnsPrefetch = true + r.DnsNegativeCache = true + } return r } func GetPortsNotNil() *Ports { diff --git a/service/db/configure/dnsrules.go b/service/db/configure/dnsrules.go index e711b4eb..7f9cd082 100644 --- a/service/db/configure/dnsrules.go +++ b/service/db/configure/dnsrules.go @@ -9,10 +9,32 @@ import ( // Server 是 DNS 服务器地址,例如 "8.8.8.8"、"https://dns.google/dns-query"、"localhost"。 // Domains 是换行分隔的域名模式列表;空字符串表示该服务器作为"兜底"DNS。 // Outbound 是路由出口标签,例如 "direct" 或 "proxy"。 +// +// 新字段(向后兼容扩展): +// - Upstream: 上游 DNS 地址(与 Server 语义一致,新配置使用) +// - Domain: 域名匹配模式(与 Domains 语义一致,新配置使用) +// - IP: IP 匹配(CIDR 格式) +// - QueryType: DNS 查询类型 A/AAAA/CNAME/TXT/MX/SRV/NS/PTR/SOA/* +// - ClientIP: 客户端 IP 匹配 +// - Action: route/reject/bypass +// - Policy: single/parallel/fallback +// - RuleID: 规则唯一标识 type DnsRule struct { + // 原始字段(向后兼容) Server string `json:"server"` Domains string `json:"domains"` Outbound string `json:"outbound"` + + // 新扩展字段 + ID int `json:"id" gorm:"primaryKey"` + Domain string `json:"domain"` + IP string `json:"ip"` + QueryType string `json:"queryType"` + ClientIP string `json:"clientIP"` + Upstream string `json:"upstream"` + Action string `json:"action"` + Policy string `json:"policy"` + RuleID string `json:"ruleId"` } // DefaultDnsRules 是内置的默认 DNS 规则。 diff --git a/service/db/configure/migrate_dns.go b/service/db/configure/migrate_dns.go new file mode 100644 index 00000000..a0161c2b --- /dev/null +++ b/service/db/configure/migrate_dns.go @@ -0,0 +1,92 @@ +package configure + +import "fmt" + +// MigrateDnsRules 将旧 DNS 规则迁移到新格式,为缺失的新字段填充合理的默认值。 +// 该函数保持向后兼容:旧规则的 Server/Domains 映射到新规则的 Upstream/Domain 语义。 +// 如果规则同时设置了新旧字段,优先使用新字段值。 +func MigrateDnsRules(oldRules []DnsRule) []DnsRule { + migrated := make([]DnsRule, len(oldRules)) + for i, rule := range oldRules { + migrated[i] = rule + + // 如果旧字段 Server 有值而新字段 Upstream 为空,则填充 + if migrated[i].Upstream == "" && migrated[i].Server != "" { + migrated[i].Upstream = migrated[i].Server + } + // 如果新字段 Upstream 有值而旧字段 Server 为空,则同步 + if migrated[i].Server == "" && migrated[i].Upstream != "" { + migrated[i].Server = migrated[i].Upstream + } + + // 如果旧字段 Domains 有值而新字段 Domain 为空,则填充 + if migrated[i].Domain == "" && migrated[i].Domains != "" { + migrated[i].Domain = migrated[i].Domains + } + // 如果新字段 Domain 有值而旧字段 Domains 为空,则同步 + if migrated[i].Domains == "" && migrated[i].Domain != "" { + migrated[i].Domains = migrated[i].Domain + } + + // 设置 Action 默认值 + if migrated[i].Action == "" { + migrated[i].Action = "route" + } + + // 设置 Policy 默认值 + if migrated[i].Policy == "" { + migrated[i].Policy = "single" + } + + // 设置 Outbound 默认值(仅当完全为空时) + if migrated[i].Outbound == "" { + migrated[i].Outbound = "direct" + } + + // 设置 QueryType 默认值(* 表示所有类型) + if migrated[i].QueryType == "" { + migrated[i].QueryType = "*" + } + + // 设置 RuleID 默认值 + if migrated[i].RuleID == "" { + migrated[i].RuleID = fmt.Sprintf("rule-%d", rule.ID) + } + } + return migrated +} + +// MigrateSetting 将旧设置配置迁移到新格式,为缺失的新 DNS 配置字段填充默认值。 +// 该函数只填充零值字段,不会覆盖用户已显式设置的字段。 +// +// 布尔字段的特殊处理: +// - FillEmpty() 跳过布尔字段,因此旧配置中缺失的布尔字段会保持 false +// - 本函数使用 gjson 检测原始 JSON 中是否存在该字段 +// - 仅当字段不存在于原始 JSON 时才设置默认值 true +func MigrateSetting(setting *Setting) { + // 监听地址默认值 + if setting.DnsListenAddr == "" { + setting.DnsListenAddr = "0.0.0.0:52353" + } + + // 缓存大小默认值 + if setting.DnsCacheSize == 0 { + setting.DnsCacheSize = 4096 + } + + // 最小 TTL 默认值 + if setting.DnsCacheMinTTL == 0 { + setting.DnsCacheMinTTL = 60 + } + + // 最大 TTL 默认值 + if setting.DnsCacheMaxTTL == 0 { + setting.DnsCacheMaxTTL = 86400 + } + + // 布尔字段默认值处理 —— 注意: + // common.FillEmpty 跳过布尔字段,所以旧配置中缺失的布尔字段会保持 false。 + // 这里不强制设置为 true,而是由调用方(如 GetSettingNotNil)根据 + // 原始 JSON 中的字段存在性来决定。 + // 对于全新的配置,NewSetting() 已设置正确的默认值。 +} diff --git a/service/db/configure/raw.go b/service/db/configure/raw.go index e52a9675..c74c244e 100644 --- a/service/db/configure/raw.go +++ b/service/db/configure/raw.go @@ -3,7 +3,7 @@ package configure import ( jsoniter "github.com/json-iterator/go" "github.com/tidwall/gjson" - "github.com/v2rayA/v2rayA/core/serverObj" + "github.com/v2rayA/v2rayA/kernel/serverObj" "github.com/v2rayA/v2rayA/pkg/util/log" ) diff --git a/service/db/configure/setting.go b/service/db/configure/setting.go index 2928aa1e..e870869b 100644 --- a/service/db/configure/setting.go +++ b/service/db/configure/setting.go @@ -2,7 +2,7 @@ package configure import ( "github.com/v2rayA/v2rayA/common" - "github.com/v2rayA/v2rayA/core/ipforward" + "github.com/v2rayA/v2rayA/kernel/ipforward" "github.com/v2rayA/v2rayA/pkg/util/log" ) @@ -34,6 +34,16 @@ type Setting struct { TunExcludeProcesses string `json:"tunExcludeProcesses"` SsBackend string `json:"ssBackend"` TrojanBackend string `json:"trojanBackend"` + // 新 DNS 模块监听配置 + DnsListenAddr string `json:"dnsListenAddr"` // 监听地址,默认 "0.0.0.0:52353" + + // DNS 缓存配置 + DnsCacheEnabled bool `json:"dnsCacheEnabled"` // 启用缓存,默认 true + DnsCacheSize int `json:"dnsCacheSize"` // 缓存大小,默认 4096 + DnsCacheMinTTL int `json:"dnsCacheMinTTL"` // 最小 TTL,默认 60 + DnsCacheMaxTTL int `json:"dnsCacheMaxTTL"` // 最大 TTL,默认 86400 + DnsPrefetch bool `json:"dnsPrefetch"` // 启用预取,默认 true + DnsNegativeCache bool `json:"dnsNegativeCache"` // 启用负缓存,默认 true } func NewSetting() (setting *Setting) { @@ -55,6 +65,14 @@ func NewSetting() (setting *Setting) { TransparentType: TransparentRedirect, TproxyExcludedInterfaces: "docker*,veth*,wg*,ppp*,br-*", TunAutoRoute: true, + // 新 DNS 模块默认值 + DnsListenAddr: "0.0.0.0:52353", + DnsCacheEnabled: true, + DnsCacheSize: 4096, + DnsCacheMinTTL: 60, + DnsCacheMaxTTL: 86400, + DnsPrefetch: true, + DnsNegativeCache: true, } } diff --git a/service/go.mod b/service/go.mod index 7147afeb..e74570eb 100644 --- a/service/go.mod +++ b/service/go.mod @@ -1,6 +1,6 @@ module github.com/v2rayA/v2rayA -go 1.24.7 +go 1.26 require ( github.com/adrg/xdg v0.4.0 @@ -26,9 +26,9 @@ require ( github.com/v2rayA/v2rayA-lib4 v0.0.0-20230812094818-595f87cb2a49 github.com/vearutop/statigz v1.1.7 go.etcd.io/bbolt v1.4.3 - golang.org/x/crypto v0.41.0 - golang.org/x/net v0.43.0 - golang.org/x/sys v0.35.0 + golang.org/x/crypto v0.46.0 + golang.org/x/net v0.48.0 + golang.org/x/sys v0.39.0 google.golang.org/grpc v1.57.1 google.golang.org/protobuf v1.36.1 gopkg.in/yaml.v3 v3.0.1 @@ -58,6 +58,7 @@ require ( github.com/leodido/go-urn v1.4.0 // indirect github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect github.com/mattn/go-isatty v0.0.20 // indirect + github.com/miekg/dns v1.1.72 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/ncruces/go-strftime v0.1.9 // indirect @@ -80,7 +81,10 @@ require ( go4.org/netipx v0.0.0-20231129151722-fdeea329fbba // indirect golang.org/x/arch v0.7.0 // indirect golang.org/x/exp v0.0.0-20250207012021-f9890c6ad9f3 // indirect - golang.org/x/text v0.28.0 // indirect + golang.org/x/mod v0.31.0 // indirect + golang.org/x/sync v0.19.0 // indirect + golang.org/x/text v0.32.0 // indirect + golang.org/x/tools v0.40.0 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20230807174057-1744710a1577 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 // indirect diff --git a/service/go.sum b/service/go.sum index 071ca8ad..0233889e 100644 --- a/service/go.sum +++ b/service/go.sum @@ -121,6 +121,8 @@ github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWE github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU= github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= +github.com/miekg/dns v1.1.72 h1:vhmr+TF2A3tuoGNkLDFK9zi36F2LS+hKTRW0Uf8kbzI= +github.com/miekg/dns v1.1.72/go.mod h1:+EuEPhdHOsfk6Wk5TT2CzssZdqkmFhf8r+aVyDEToIs= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -244,14 +246,22 @@ golang.org/x/arch v0.7.0 h1:pskyeJh/3AmoQ8CPE95vxHLqp1G1GfGNXTmcl9NEKTc= golang.org/x/arch v0.7.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= golang.org/x/crypto v0.41.0 h1:WKYxWedPGCTVVl5+WHSSrOBT0O8lx32+zxmHxijgXp4= golang.org/x/crypto v0.41.0/go.mod h1:pO5AFd7FA68rFak7rOAGVuygIISepHftHnr8dr6+sUc= +golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU= +golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0= golang.org/x/exp v0.0.0-20250207012021-f9890c6ad9f3 h1:qNgPs5exUA+G0C96DrPwNrvLSj7GT/9D+3WMWUcUg34= golang.org/x/exp v0.0.0-20250207012021-f9890c6ad9f3/go.mod h1:tujkw807nyEEAamNbDrEGzRav+ilXA7PCRAd6xsmwiU= golang.org/x/mod v0.26.0 h1:EGMPT//Ezu+ylkCijjPc+f4Aih7sZvaAr+O3EHBxvZg= golang.org/x/mod v0.26.0/go.mod h1:/j6NAhSk8iQ723BGAUyoAcn7SlD7s15Dp9Nd/SfeaFQ= +golang.org/x/mod v0.31.0 h1:HaW9xtz0+kOcWKwli0ZXy79Ix+UW/vOfmWI5QVd2tgI= +golang.org/x/mod v0.31.0/go.mod h1:43JraMp9cGx1Rx3AqioxrbrhNsLl2l/iNAvuBkrezpg= golang.org/x/net v0.43.0 h1:lat02VYK2j4aLzMzecihNvTlJNQUq316m2Mr9rnM6YE= golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg= +golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU= +golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY= golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw= golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= +golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4= +golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= golang.org/x/sys v0.0.0-20190116161447-11f53e031339/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -263,10 +273,16 @@ golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI= golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk= +golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng= golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU= +golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU= +golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY= golang.org/x/tools v0.35.0 h1:mBffYraMEf7aa0sB+NuKnuCy8qI/9Bughn8dC2Gu5r0= golang.org/x/tools v0.35.0/go.mod h1:NKdj5HkL/73byiZSJjqJgKn3ep7KjFkBOkR/Hps3VPw= +golang.org/x/tools v0.40.0 h1:yLkxfA+Qnul4cs9QA3KnlFu0lVmd8JJfoq+E41uSutA= +golang.org/x/tools v0.40.0/go.mod h1:Ik/tzLRlbscWpqqMRjyWYDisX8bG13FrdXp3o4Sr9lc= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/genproto/googleapis/rpc v0.0.0-20230807174057-1744710a1577 h1:wukfNtZmZUurLN/atp2hiIeTKn7QJWIQdHzqmsOnAOk= google.golang.org/genproto/googleapis/rpc v0.0.0-20230807174057-1744710a1577/go.mod h1:+Bk1OCOj40wS2hwAMA+aCW9ypzm63QTBBHp6lQ3p+9M= diff --git a/service/core/coreObj/coreObj.go b/service/kernel/coreObj/coreObj.go similarity index 95% rename from service/core/coreObj/coreObj.go rename to service/kernel/coreObj/coreObj.go index a5843bd5..e23cdd27 100644 --- a/service/core/coreObj/coreObj.go +++ b/service/kernel/coreObj/coreObj.go @@ -1,6 +1,9 @@ package coreObj -import "encoding/json" +import ( + "encoding/json" + "time" +) type APIObject struct { Tag string `json:"tag"` @@ -370,3 +373,18 @@ type Policy struct { StatsInboundDownlink bool `json:"statsInboundDownlink,omitempty"` } `json:"system"` } + +// DnsModuleStatus 表示新 DNS 模块的运行状态,用于 API 报告。 +type DnsModuleStatus struct { + Healthy bool `json:"healthy"` + ListenAddr string `json:"listenAddr"` + TotalQueries int64 `json:"totalQueries"` + RejectedQuery int64 `json:"rejectedQueries"` + BypassedQuery int64 `json:"bypassedQueries"` + CacheHits int64 `json:"cacheHits"` + CacheMisses int64 `json:"cacheMisses"` + AvgRTT time.Duration `json:"avgRtt"` + RoutedQueries map[string]int64 `json:"routedQueries"` + NumRules int `json:"numRules"` + NumUpstreams int `json:"numUpstreams"` +} diff --git a/service/core/ipforward/ipforward_linux.go b/service/kernel/ipforward/ipforward_linux.go similarity index 100% rename from service/core/ipforward/ipforward_linux.go rename to service/kernel/ipforward/ipforward_linux.go diff --git a/service/core/ipforward/ipforward_other.go b/service/kernel/ipforward/ipforward_other.go similarity index 100% rename from service/core/ipforward/ipforward_other.go rename to service/kernel/ipforward/ipforward_other.go diff --git a/service/core/ipforward/ipforward_unix.go b/service/kernel/ipforward/ipforward_unix.go similarity index 100% rename from service/core/ipforward/ipforward_unix.go rename to service/kernel/ipforward/ipforward_unix.go diff --git a/service/core/iptables/dropSpoofing.go b/service/kernel/iptables/dropSpoofing.go similarity index 100% rename from service/core/iptables/dropSpoofing.go rename to service/kernel/iptables/dropSpoofing.go diff --git a/service/core/iptables/iptables.go b/service/kernel/iptables/iptables.go similarity index 100% rename from service/core/iptables/iptables.go rename to service/kernel/iptables/iptables.go diff --git a/service/core/iptables/redirect.go b/service/kernel/iptables/redirect.go similarity index 77% rename from service/core/iptables/redirect.go rename to service/kernel/iptables/redirect.go index 5295f8b3..e766b2fa 100644 --- a/service/core/iptables/redirect.go +++ b/service/kernel/iptables/redirect.go @@ -6,7 +6,7 @@ import ( "strings" "github.com/v2rayA/v2rayA/common/cmds" - "github.com/v2rayA/v2rayA/core/v2ray/asset" + "github.com/v2rayA/v2rayA/kernel/v2ray/asset" ) type redirect interface { @@ -52,6 +52,7 @@ func (r *legacyRedirect) GetSetupCommands() Setter { iptables -w 2 -t nat -N TP_OUT iptables -w 2 -t nat -N TP_PRE iptables -w 2 -t nat -N TP_RULE +iptables -w 2 -t nat -N DNS_REDIRECT iptables -w 2 -t nat -A TP_RULE -d 0.0.0.0/32 -j RETURN iptables -w 2 -t nat -A TP_RULE -d 10.0.0.0/8 -j RETURN iptables -w 2 -t nat -A TP_RULE -d 100.64.0.0/10 -j RETURN @@ -69,6 +70,14 @@ iptables -w 2 -t nat -A TP_RULE -d 203.0.113.0/24 -j RETURN iptables -w 2 -t nat -A TP_RULE -d 224.0.0.0/4 -j RETURN iptables -w 2 -t nat -A TP_RULE -d 240.0.0.0/4 -j RETURN iptables -w 2 -t nat -A TP_RULE -m mark --mark 0x80/0x80 -j RETURN +# DNS 重定向到新 DNS 模块端口 52353(必须在通用 REDIRECT 规则之前) +iptables -w 2 -t nat -A DNS_REDIRECT -m mark --mark 0x80/0x80 -j RETURN +iptables -w 2 -t nat -A DNS_REDIRECT -j REDIRECT --to-port 52353 +# 在 PREROUTING 和 OUTPUT 中插入 DNS 规则(优先于 TP_PRE/TP_OUT) +iptables -w 2 -t nat -I PREROUTING -p udp --dport 53 -j DNS_REDIRECT +iptables -w 2 -t nat -I PREROUTING -p tcp --dport 53 -j DNS_REDIRECT +iptables -w 2 -t nat -I OUTPUT -p udp --dport 53 -j DNS_REDIRECT +iptables -w 2 -t nat -I OUTPUT -p tcp --dport 53 -j DNS_REDIRECT ` for _, v := range GetExcludedInterfaces() { commands += fmt.Sprintf("iptables -w 2 -t nat -A TP_RULE -i %s -j RETURN\n", strings.ReplaceAll(v, "*", "+")) @@ -92,6 +101,13 @@ iptables -w 2 -t nat -A TP_OUT -j TP_RULE ip6tables -w 2 -t nat -N TP_OUT ip6tables -w 2 -t nat -N TP_PRE ip6tables -w 2 -t nat -N TP_RULE +ip6tables -w 2 -t nat -N DNS_REDIRECT +ip6tables -w 2 -t nat -A DNS_REDIRECT -m mark --mark 0x80/0x80 -j RETURN +ip6tables -w 2 -t nat -A DNS_REDIRECT -j REDIRECT --to-port 52353 +ip6tables -w 2 -t nat -I PREROUTING -p udp --dport 53 -j DNS_REDIRECT +ip6tables -w 2 -t nat -I PREROUTING -p tcp --dport 53 -j DNS_REDIRECT +ip6tables -w 2 -t nat -I OUTPUT -p udp --dport 53 -j DNS_REDIRECT +ip6tables -w 2 -t nat -I OUTPUT -p tcp --dport 53 -j DNS_REDIRECT ip6tables -w 2 -t nat -A TP_RULE -d ::/128 -j RETURN ip6tables -w 2 -t nat -A TP_RULE -d ::1/128 -j RETURN ip6tables -w 2 -t nat -A TP_RULE -d 64:ff9b::/96 -j RETURN @@ -131,6 +147,12 @@ ip6tables -w 2 -t nat -A TP_OUT -j TP_RULE func (r *legacyRedirect) GetCleanCommands() Setter { commands := ` +iptables -w 2 -t nat -F DNS_REDIRECT +iptables -w 2 -t nat -D PREROUTING -p udp --dport 53 -j DNS_REDIRECT +iptables -w 2 -t nat -D PREROUTING -p tcp --dport 53 -j DNS_REDIRECT +iptables -w 2 -t nat -D OUTPUT -p udp --dport 53 -j DNS_REDIRECT +iptables -w 2 -t nat -D OUTPUT -p tcp --dport 53 -j DNS_REDIRECT +iptables -w 2 -t nat -X DNS_REDIRECT iptables -w 2 -t nat -F TP_OUT iptables -w 2 -t nat -D OUTPUT -p tcp -j TP_OUT iptables -w 2 -t nat -X TP_OUT @@ -142,6 +164,12 @@ iptables -w 2 -t nat -X TP_RULE ` if IsIPv6Supported() { commands += ` +ip6tables -w 2 -t nat -F DNS_REDIRECT +ip6tables -w 2 -t nat -D PREROUTING -p udp --dport 53 -j DNS_REDIRECT +ip6tables -w 2 -t nat -D PREROUTING -p tcp --dport 53 -j DNS_REDIRECT +ip6tables -w 2 -t nat -D OUTPUT -p udp --dport 53 -j DNS_REDIRECT +ip6tables -w 2 -t nat -D OUTPUT -p tcp --dport 53 -j DNS_REDIRECT +ip6tables -w 2 -t nat -X DNS_REDIRECT ip6tables -w 2 -t nat -F TP_OUT ip6tables -w 2 -t nat -D OUTPUT -p tcp -j TP_OUT ip6tables -w 2 -t nat -X TP_OUT @@ -241,6 +269,11 @@ table inet v2raya { auto-merge } + chain dns_redirect { + meta mark & 0x80 == 0x80 return + meta l4proto { tcp, udp } th dport 53 redirect to :52353 + } + chain tp_rule { ip daddr @whitelist return ip daddr @interface return @@ -248,20 +281,24 @@ table inet v2raya { ip6 daddr @interface6 return meta mark & 0x80 == 0x80 return ` - for _, v := range GetExcludedInterfaces() { - table += fmt.Sprintf(" iifname \"%s\" return\n", v) - } - table += ` + for _, v := range GetExcludedInterfaces() { + table += fmt.Sprintf(" iifname \"%s\" return\n", v) + } + table += ` meta l4proto tcp redirect to :52345 } chain tp_pre { type nat hook prerouting priority dstnat - 5 + # DNS 重定向到 52353(优先于通用透明代理) + meta nfproto { ipv4, ipv6 } meta l4proto { tcp, udp } th dport 53 jump dns_redirect meta nfproto { ipv4, ipv6 } meta l4proto tcp jump tp_rule } chain tp_out { type nat hook output priority -105 + # DNS 重定向到 52353(优先于通用透明代理) + meta nfproto { ipv4, ipv6 } meta l4proto { tcp, udp } th dport 53 jump dns_redirect meta nfproto { ipv4, ipv6 } meta l4proto tcp jump tp_rule } } diff --git a/service/core/iptables/systemProxy_macos.go b/service/kernel/iptables/systemProxy_macos.go similarity index 100% rename from service/core/iptables/systemProxy_macos.go rename to service/kernel/iptables/systemProxy_macos.go diff --git a/service/core/iptables/systemProxy_other.go b/service/kernel/iptables/systemProxy_other.go similarity index 100% rename from service/core/iptables/systemProxy_other.go rename to service/kernel/iptables/systemProxy_other.go diff --git a/service/core/iptables/systemProxy_windows.go b/service/kernel/iptables/systemProxy_windows.go similarity index 100% rename from service/core/iptables/systemProxy_windows.go rename to service/kernel/iptables/systemProxy_windows.go diff --git a/service/core/iptables/tproxy.go b/service/kernel/iptables/tproxy.go similarity index 75% rename from service/core/iptables/tproxy.go rename to service/kernel/iptables/tproxy.go index da95a7fd..0f286ece 100644 --- a/service/core/iptables/tproxy.go +++ b/service/kernel/iptables/tproxy.go @@ -7,7 +7,7 @@ import ( "strings" "github.com/v2rayA/v2rayA/common/cmds" - "github.com/v2rayA/v2rayA/core/v2ray/asset" + "github.com/v2rayA/v2rayA/kernel/v2ray/asset" ) var ( @@ -71,8 +71,15 @@ iptables -w 2 -t mangle -N TP_OUT iptables -w 2 -t mangle -N TP_PRE iptables -w 2 -t mangle -N TP_RULE iptables -w 2 -t mangle -N TP_MARK +iptables -w 2 -t mangle -N DNS_MARK +# DNS 规则必须在透明代理规则之前插入(环路保护) +iptables -w 2 -t mangle -I OUTPUT -p udp --dport 53 -j DNS_MARK +iptables -w 2 -t mangle -I OUTPUT -p tcp --dport 53 -j DNS_MARK iptables -w 2 -t mangle -I OUTPUT -j TP_OUT +# DNS 规则必须在透明代理规则之前插入 +iptables -w 2 -t mangle -I PREROUTING -p udp --dport 53 -j DNS_MARK +iptables -w 2 -t mangle -I PREROUTING -p tcp --dport 53 -j DNS_MARK iptables -w 2 -t mangle -I PREROUTING -j TP_PRE iptables -w 2 -t mangle -A TP_OUT -m mark --mark 0x80/0x80 -j RETURN @@ -82,9 +89,12 @@ iptables -w 2 -t mangle -A TP_OUT -p udp -m addrtype --src-type LOCAL ! --dst-ty iptables -w 2 -t mangle -A TP_PRE -i lo -m mark ! --mark 0x40/0xc0 -j RETURN iptables -w 2 -t mangle -A TP_PRE -p tcp -m addrtype ! --src-type LOCAL ! --dst-type LOCAL -j TP_RULE iptables -w 2 -t mangle -A TP_PRE -p udp -m addrtype ! --src-type LOCAL ! --dst-type LOCAL -j TP_RULE +# DNS 流量重定向到新 DNS 模块端口 52353(必须在通用 TPROXY 规则之前) +iptables -w 2 -t mangle -A TP_PRE -p tcp -m mark --mark 0x40/0xc0 --dport 53 -j TPROXY --on-port 52353 --on-ip 127.2.0.17 +iptables -w 2 -t mangle -A TP_PRE -p udp -m mark --mark 0x40/0xc0 --dport 53 -j TPROXY --on-port 52353 --on-ip 127.2.0.17 +# 通用 TPROXY 规则 iptables -w 2 -t mangle -A TP_PRE -p tcp -m mark --mark 0x40/0xc0 -j TPROXY --on-port 52345 --on-ip 127.0.0.1 iptables -w 2 -t mangle -A TP_PRE -p udp -m mark --mark 0x40/0xc0 -j TPROXY --on-port 52345 --on-ip 127.0.0.1 - iptables -w 2 -t mangle -A TP_RULE -j CONNMARK --restore-mark iptables -w 2 -t mangle -A TP_RULE -m mark --mark 0x40/0xc0 -j RETURN ` @@ -109,6 +119,10 @@ iptables -w 2 -t mangle -A TP_RULE -j TP_MARK iptables -w 2 -t mangle -A TP_MARK -p tcp -m tcp --syn -j MARK --set-xmark 0x40/0x40 iptables -w 2 -t mangle -A TP_MARK -p udp -m conntrack --ctstate NEW -j MARK --set-xmark 0x40/0x40 iptables -w 2 -t mangle -A TP_MARK -j CONNMARK --save-mark +# DNS_MARK 链:环路保护 + 标记 DNS 流量 +iptables -w 2 -t mangle -A DNS_MARK -m mark --mark 0x80/0x80 -j RETURN +iptables -w 2 -t mangle -A DNS_MARK -j MARK --set-xmark 0x40/0x40 +iptables -w 2 -t mangle -A DNS_MARK -j ACCEPT ` if IsIPv6Supported() { commands += ` @@ -119,8 +133,15 @@ ip6tables -w 2 -t mangle -N TP_OUT ip6tables -w 2 -t mangle -N TP_PRE ip6tables -w 2 -t mangle -N TP_RULE ip6tables -w 2 -t mangle -N TP_MARK +ip6tables -w 2 -t mangle -N DNS_MARK +# IPv6 DNS 规则必须在透明代理规则之前插入 +ip6tables -w 2 -t mangle -I OUTPUT -p udp --dport 53 -j DNS_MARK +ip6tables -w 2 -t mangle -I OUTPUT -p tcp --dport 53 -j DNS_MARK ip6tables -w 2 -t mangle -I OUTPUT -j TP_OUT +# IPv6 DNS 规则必须在透明代理规则之前插入 +ip6tables -w 2 -t mangle -I PREROUTING -p udp --dport 53 -j DNS_MARK +ip6tables -w 2 -t mangle -I PREROUTING -p tcp --dport 53 -j DNS_MARK ip6tables -w 2 -t mangle -I PREROUTING -j TP_PRE ip6tables -w 2 -t mangle -A TP_OUT -m mark --mark 0x80/0x80 -j RETURN @@ -130,9 +151,12 @@ ip6tables -w 2 -t mangle -A TP_OUT -p udp -m addrtype --src-type LOCAL ! --dst-t ip6tables -w 2 -t mangle -A TP_PRE -i lo -m mark ! --mark 0x40/0xc0 -j RETURN ip6tables -w 2 -t mangle -A TP_PRE -p tcp -m addrtype ! --src-type LOCAL ! --dst-type LOCAL -j TP_RULE ip6tables -w 2 -t mangle -A TP_PRE -p udp -m addrtype ! --src-type LOCAL ! --dst-type LOCAL -j TP_RULE +# DNS 流量重定向到新 DNS 模块端口 52353(必须在通用 TPROXY 规则之前) +ip6tables -w 2 -t mangle -A TP_PRE -p tcp -m mark --mark 0x40/0xc0 --dport 53 -j TPROXY --on-port 52353 --on-ip ::1 +ip6tables -w 2 -t mangle -A TP_PRE -p udp -m mark --mark 0x40/0xc0 --dport 53 -j TPROXY --on-port 52353 --on-ip ::1 +# 通用 TPROXY 规则 ip6tables -w 2 -t mangle -A TP_PRE -p tcp -m mark --mark 0x40/0xc0 -j TPROXY --on-port 52345 --on-ip ::1 ip6tables -w 2 -t mangle -A TP_PRE -p udp -m mark --mark 0x40/0xc0 -j TPROXY --on-port 52345 --on-ip ::1 - ip6tables -w 2 -t mangle -A TP_RULE -j CONNMARK --restore-mark ip6tables -w 2 -t mangle -A TP_RULE -m mark --mark 0x40/0xc0 -j RETURN ` @@ -156,6 +180,10 @@ ip6tables -w 2 -t mangle -A TP_RULE -j TP_MARK ip6tables -w 2 -t mangle -A TP_MARK -p tcp -m tcp --syn -j MARK --set-xmark 0x40/0x40 ip6tables -w 2 -t mangle -A TP_MARK -p udp -m conntrack --ctstate NEW -j MARK --set-xmark 0x40/0x40 ip6tables -w 2 -t mangle -A TP_MARK -j CONNMARK --save-mark +# IPv6 DNS_MARK 链:环路保护 + 标记 DNS 流量 +ip6tables -w 2 -t mangle -A DNS_MARK -m mark --mark 0x80/0x80 -j RETURN +ip6tables -w 2 -t mangle -A DNS_MARK -j MARK --set-xmark 0x40/0x40 +ip6tables -w 2 -t mangle -A DNS_MARK -j ACCEPT ` } return Setter{ @@ -178,6 +206,12 @@ iptables -w 2 -t mangle -F TP_RULE iptables -w 2 -t mangle -X TP_RULE iptables -w 2 -t mangle -F TP_MARK iptables -w 2 -t mangle -X TP_MARK +iptables -w 2 -t mangle -F DNS_MARK +iptables -w 2 -t mangle -D PREROUTING -p udp --dport 53 -j DNS_MARK +iptables -w 2 -t mangle -D PREROUTING -p tcp --dport 53 -j DNS_MARK +iptables -w 2 -t mangle -D OUTPUT -p udp --dport 53 -j DNS_MARK +iptables -w 2 -t mangle -D OUTPUT -p tcp --dport 53 -j DNS_MARK +iptables -w 2 -t mangle -X DNS_MARK ` if IsIPv6Supported() { commands += ` @@ -194,6 +228,12 @@ ip6tables -w 2 -t mangle -F TP_RULE ip6tables -w 2 -t mangle -X TP_RULE ip6tables -w 2 -t mangle -F TP_MARK ip6tables -w 2 -t mangle -X TP_MARK +ip6tables -w 2 -t mangle -F DNS_MARK +ip6tables -w 2 -t mangle -D PREROUTING -p udp --dport 53 -j DNS_MARK +ip6tables -w 2 -t mangle -D PREROUTING -p tcp --dport 53 -j DNS_MARK +ip6tables -w 2 -t mangle -D OUTPUT -p udp --dport 53 -j DNS_MARK +ip6tables -w 2 -t mangle -D OUTPUT -p tcp --dport 53 -j DNS_MARK +ip6tables -w 2 -t mangle -X DNS_MARK ` } commands += "conntrack -D --mark 0x40 2>/dev/null || true\n" @@ -272,17 +312,31 @@ func (t *nftTproxy) GetSetupCommands() Setter { chain tp_pre { iifname "lo" mark & 0xc0 != 0x40 return meta l4proto { tcp, udp } fib saddr type != local fib daddr type != local jump tp_rule + # DNS 流量重定向到新 DNS 模块端口 52353(必须在通用 TPROXY 规则之前) + meta l4proto { tcp, udp } mark & 0xc0 == 0x40 th dport 53 tproxy ip to 127.2.0.17:52353 + meta l4proto { tcp, udp } mark & 0xc0 == 0x40 th dport 53 tproxy ip6 to [::1]:52353 + # 通用 TPROXY 规则 meta l4proto { tcp, udp } mark & 0xc0 == 0x40 tproxy ip to 127.0.0.1:52345 meta l4proto { tcp, udp } mark & 0xc0 == 0x40 tproxy ip6 to [::1]:52345 } + chain dns_mark { + meta mark & 0x80 == 0x80 return + meta mark set mark | 0x40 + accept + } + chain output { type route hook output priority mangle - 5; policy accept; + # DNS 规则必须在透明代理规则之前匹配 + meta nfproto { ipv4, ipv6 } meta l4proto { tcp, udp } th dport 53 jump dns_mark meta nfproto { ipv4, ipv6 } jump tp_out } chain prerouting { type filter hook prerouting priority mangle - 5; policy accept; + # DNS 规则必须在透明代理规则之前匹配 + meta nfproto { ipv4, ipv6 } meta l4proto { tcp, udp } th dport 53 jump dns_mark meta nfproto { ipv4, ipv6 } jump tp_pre } diff --git a/service/core/iptables/utils.go b/service/kernel/iptables/utils.go similarity index 100% rename from service/core/iptables/utils.go rename to service/kernel/iptables/utils.go diff --git a/service/core/iptables/watcher.go b/service/kernel/iptables/watcher.go similarity index 100% rename from service/core/iptables/watcher.go rename to service/kernel/iptables/watcher.go diff --git a/service/core/serverObj/anytls.go b/service/kernel/serverObj/anytls.go similarity index 98% rename from service/core/serverObj/anytls.go rename to service/kernel/serverObj/anytls.go index 6c7d6eaa..88f5c1d3 100644 --- a/service/core/serverObj/anytls.go +++ b/service/kernel/serverObj/anytls.go @@ -6,7 +6,7 @@ import ( "net/url" "strconv" - "github.com/v2rayA/v2rayA/core/coreObj" + "github.com/v2rayA/v2rayA/kernel/coreObj" ) func init() { diff --git a/service/core/serverObj/http.go b/service/kernel/serverObj/http.go similarity index 100% rename from service/core/serverObj/http.go rename to service/kernel/serverObj/http.go diff --git a/service/core/serverObj/hysteria2.go b/service/kernel/serverObj/hysteria2.go similarity index 100% rename from service/core/serverObj/hysteria2.go rename to service/kernel/serverObj/hysteria2.go diff --git a/service/core/serverObj/juicity.go b/service/kernel/serverObj/juicity.go similarity index 98% rename from service/core/serverObj/juicity.go rename to service/kernel/serverObj/juicity.go index 771cab0a..d877fb33 100644 --- a/service/core/serverObj/juicity.go +++ b/service/kernel/serverObj/juicity.go @@ -7,7 +7,7 @@ import ( "net/url" "strconv" - "github.com/v2rayA/v2rayA/core/coreObj" + "github.com/v2rayA/v2rayA/kernel/coreObj" ) func init() { diff --git a/service/core/serverObj/plugin.go b/service/kernel/serverObj/plugin.go similarity index 98% rename from service/core/serverObj/plugin.go rename to service/kernel/serverObj/plugin.go index 93c78e49..926985e9 100644 --- a/service/core/serverObj/plugin.go +++ b/service/kernel/serverObj/plugin.go @@ -4,7 +4,7 @@ import ( "fmt" jsoniter "github.com/json-iterator/go" "github.com/v2rayA/v2rayA/conf" - "github.com/v2rayA/v2rayA/core/coreObj" + "github.com/v2rayA/v2rayA/kernel/coreObj" "github.com/v2rayA/v2rayA/pkg/util/log" "os/exec" "strconv" diff --git a/service/core/serverObj/serverObj.go b/service/kernel/serverObj/serverObj.go similarity index 96% rename from service/core/serverObj/serverObj.go rename to service/kernel/serverObj/serverObj.go index 7870614f..895d9bf3 100644 --- a/service/core/serverObj/serverObj.go +++ b/service/kernel/serverObj/serverObj.go @@ -5,8 +5,8 @@ import ( "net/url" "github.com/v2rayA/v2rayA/conf" - "github.com/v2rayA/v2rayA/core/coreObj" - "github.com/v2rayA/v2rayA/core/v2ray/where" + "github.com/v2rayA/v2rayA/kernel/coreObj" + "github.com/v2rayA/v2rayA/kernel/v2ray/where" ) var ErrInvalidParameter = fmt.Errorf("invalid parameters") diff --git a/service/core/serverObj/shadowsocks.go b/service/kernel/serverObj/shadowsocks.go similarity index 99% rename from service/core/serverObj/shadowsocks.go rename to service/kernel/serverObj/shadowsocks.go index 9e436520..f9d3c1ae 100644 --- a/service/core/serverObj/shadowsocks.go +++ b/service/kernel/serverObj/shadowsocks.go @@ -9,7 +9,7 @@ import ( "strings" "github.com/v2rayA/v2rayA/common" - "github.com/v2rayA/v2rayA/core/coreObj" + "github.com/v2rayA/v2rayA/kernel/coreObj" ) func init() { diff --git a/service/core/serverObj/shadowsocksr.go b/service/kernel/serverObj/shadowsocksr.go similarity index 100% rename from service/core/serverObj/shadowsocksr.go rename to service/kernel/serverObj/shadowsocksr.go diff --git a/service/core/serverObj/socks.go b/service/kernel/serverObj/socks.go similarity index 98% rename from service/core/serverObj/socks.go rename to service/kernel/serverObj/socks.go index d6a7cafa..c4dc8151 100644 --- a/service/core/serverObj/socks.go +++ b/service/kernel/serverObj/socks.go @@ -5,7 +5,7 @@ import ( "net/url" "strconv" - "github.com/v2rayA/v2rayA/core/coreObj" + "github.com/v2rayA/v2rayA/kernel/coreObj" ) func init() { diff --git a/service/core/serverObj/trojan.go b/service/kernel/serverObj/trojan.go similarity index 99% rename from service/core/serverObj/trojan.go rename to service/kernel/serverObj/trojan.go index ab0e71fc..9a208042 100644 --- a/service/core/serverObj/trojan.go +++ b/service/kernel/serverObj/trojan.go @@ -7,7 +7,7 @@ import ( "strconv" "strings" - "github.com/v2rayA/v2rayA/core/coreObj" + "github.com/v2rayA/v2rayA/kernel/coreObj" ) func init() { diff --git a/service/core/serverObj/tuic.go b/service/kernel/serverObj/tuic.go similarity index 99% rename from service/core/serverObj/tuic.go rename to service/kernel/serverObj/tuic.go index d768beaf..f7d97028 100644 --- a/service/core/serverObj/tuic.go +++ b/service/kernel/serverObj/tuic.go @@ -8,7 +8,7 @@ import ( "strconv" "strings" - "github.com/v2rayA/v2rayA/core/coreObj" + "github.com/v2rayA/v2rayA/kernel/coreObj" ) func init() { diff --git a/service/core/serverObj/v2ray.go b/service/kernel/serverObj/v2ray.go similarity index 99% rename from service/core/serverObj/v2ray.go rename to service/kernel/serverObj/v2ray.go index 1ca37812..d8272f82 100644 --- a/service/core/serverObj/v2ray.go +++ b/service/kernel/serverObj/v2ray.go @@ -14,7 +14,7 @@ import ( "github.com/tidwall/gjson" "github.com/v2rayA/v2rayA/common" "github.com/v2rayA/v2rayA/common/ntp" - "github.com/v2rayA/v2rayA/core/coreObj" + "github.com/v2rayA/v2rayA/kernel/coreObj" "github.com/v2rayA/v2rayA/pkg/util/log" ) diff --git a/service/core/serverObj/wireguard.go b/service/kernel/serverObj/wireguard.go similarity index 99% rename from service/core/serverObj/wireguard.go rename to service/kernel/serverObj/wireguard.go index 41efce73..96f2e433 100644 --- a/service/core/serverObj/wireguard.go +++ b/service/kernel/serverObj/wireguard.go @@ -7,7 +7,7 @@ import ( "strconv" "strings" - "github.com/v2rayA/v2rayA/core/coreObj" + "github.com/v2rayA/v2rayA/kernel/coreObj" ) func init() { diff --git a/service/core/touch/touch.go b/service/kernel/touch/touch.go similarity index 100% rename from service/core/touch/touch.go rename to service/kernel/touch/touch.go diff --git a/service/core/v2ray/api.go b/service/kernel/v2ray/api.go similarity index 100% rename from service/core/v2ray/api.go rename to service/kernel/v2ray/api.go diff --git a/service/core/v2ray/asset/asset.go b/service/kernel/v2ray/asset/asset.go similarity index 100% rename from service/core/v2ray/asset/asset.go rename to service/kernel/v2ray/asset/asset.go diff --git a/service/core/v2ray/asset/dat/geoip.go b/service/kernel/v2ray/asset/dat/geoip.go similarity index 96% rename from service/core/v2ray/asset/dat/geoip.go rename to service/kernel/v2ray/asset/dat/geoip.go index ec5f87ea..570ae248 100644 --- a/service/core/v2ray/asset/dat/geoip.go +++ b/service/kernel/v2ray/asset/dat/geoip.go @@ -5,7 +5,7 @@ import ( "os" "strings" - "github.com/v2rayA/v2rayA/core/v2ray/asset" + "github.com/v2rayA/v2rayA/kernel/v2ray/asset" "github.com/v2rayA/v2rayA/pkg/util/log" ) diff --git a/service/core/v2ray/asset/dat/geosite.go b/service/kernel/v2ray/asset/dat/geosite.go similarity index 96% rename from service/core/v2ray/asset/dat/geosite.go rename to service/kernel/v2ray/asset/dat/geosite.go index fdaa7c69..b9e6b49d 100644 --- a/service/core/v2ray/asset/dat/geosite.go +++ b/service/kernel/v2ray/asset/dat/geosite.go @@ -5,7 +5,7 @@ import ( "os" "strings" - "github.com/v2rayA/v2rayA/core/v2ray/asset" + "github.com/v2rayA/v2rayA/kernel/v2ray/asset" "github.com/v2rayA/v2rayA/pkg/util/log" ) diff --git a/service/core/v2ray/asset/dat/gfwlist.go b/service/kernel/v2ray/asset/dat/gfwlist.go similarity index 97% rename from service/core/v2ray/asset/dat/gfwlist.go rename to service/kernel/v2ray/asset/dat/gfwlist.go index 58ae0fe8..d23ae4be 100644 --- a/service/core/v2ray/asset/dat/gfwlist.go +++ b/service/kernel/v2ray/asset/dat/gfwlist.go @@ -14,8 +14,8 @@ import ( "github.com/tidwall/gjson" "github.com/v2rayA/v2rayA/common/files" "github.com/v2rayA/v2rayA/common/httpClient" - "github.com/v2rayA/v2rayA/core/v2ray" - "github.com/v2rayA/v2rayA/core/v2ray/asset" + "github.com/v2rayA/v2rayA/kernel/v2ray" + "github.com/v2rayA/v2rayA/kernel/v2ray/asset" "github.com/v2rayA/v2rayA/db/configure" "github.com/v2rayA/v2rayA/pkg/util/log" ) @@ -176,7 +176,7 @@ func CheckAndUpdateGFWList(downloadLink string) (localGFWListVersionAfterUpdate } if update { return "", fmt.Errorf( - "latest version is " + tRemote.Local().Format("2006-01-02") + ". GFWList is up to date", + "latest version is %v. GFWList is up to date", tRemote.Local().Format("2006-01-02"), ) } diff --git a/service/core/v2ray/connectivity.go b/service/kernel/v2ray/connectivity.go similarity index 100% rename from service/core/v2ray/connectivity.go rename to service/kernel/v2ray/connectivity.go diff --git a/service/core/v2ray/dnsHijack.go b/service/kernel/v2ray/dnsHijack.go similarity index 62% rename from service/core/v2ray/dnsHijack.go rename to service/kernel/v2ray/dnsHijack.go index b65b027f..a9f78a20 100644 --- a/service/core/v2ray/dnsHijack.go +++ b/service/kernel/v2ray/dnsHijack.go @@ -12,6 +12,17 @@ const ( checkInterval = 3 * time.Second ) +// ResolvHijacker 劫持系统 DNS 配置,将命名服务器指向 127.2.0.17:53。 +// 其流量路径为: +// +// /etc/resolv.conf → 127.2.0.17:53 → iptables/nftables DNS 规则 → 重定向到 52353 (新 DNS 模块) +// +// 旧路径(xray DNS 模式): +// +// /etc/resolv.conf → 127.2.0.17:53 → dns-in (dokodemo-door, port 53) → xray DNS 路由 → dns-out +// +// 新 DNS 模块启用时,劫持后的 53 端口流量被 iptables REDIRECT/TPROXY 规则捕获, +// 导向 DNS 模块的监听端口 52353,由 UpstreamManager 进行解析。 type ResolvHijacker struct { ticker *time.Ticker localDNS bool @@ -42,6 +53,9 @@ const HijackFlag = "# v2rayA DNS hijack" var hijacker *ResolvHijacker +// HijackResolv 将 /etc/resolv.conf 的 nameserver 设置为 127.2.0.17。 +// 当新 DNS 模块启用时,127.2.0.17:53 的流量被 iptables 规则重定向到 :52353(新 DNS 模块端口)。 +// 当使用旧 xray DNS 时,127.2.0.17:53 的流量被 dns-in (dokodemo-door) 捕获。 func (h *ResolvHijacker) HijackResolv() error { if runtime.GOOS != "linux" { return nil diff --git a/service/core/v2ray/dnslisten.go b/service/kernel/v2ray/dnslisten.go similarity index 80% rename from service/core/v2ray/dnslisten.go rename to service/kernel/v2ray/dnslisten.go index 95be8356..8cbf52db 100644 --- a/service/core/v2ray/dnslisten.go +++ b/service/kernel/v2ray/dnslisten.go @@ -22,17 +22,22 @@ var ( DnsPortOccupied = fmt.Errorf("dns port 53 is occupied") ) -// ShouldLocalDnsListen 在 redirect 透明代理启用时返回 true, -// 表示需要在本机监听 53 端口,将 DNS 流量导入 v2ray 处理。 -// 新版 DNS 模块始终启用,只要 redirect 透明代理开启即需要本机监听。 +// ShouldLocalDnsListen 在透明代理启用时返回 true, +// 表示需要劫持 /etc/resolv.conf 将系统 DNS 指向 127.2.0.17:53, +// 使 DNS 流量可以被 iptables/nftables 规则捕获后重定向到 52353。 +// +// 新 DNS 模块架构下,无论 Redirect 还是 TProxy 模式,都需要劫持 DNS: +// +// /etc/resolv.conf → 127.2.0.17:53 +// → iptables REDIRECT/TPROXY --dport 53 → 52353 +// → v2raya-core DNS 模块处理 +// +// 不依赖 xray 的 dns-in/dns-out,DNS 模块直接查询上游并返回结果。 func ShouldLocalDnsListen() bool { setting := configure.GetSettingNotNil() if setting.Transparent == configure.TransparentClose { return false } - if setting.TransparentType != configure.TransparentRedirect { - return false - } if conf.GetEnvironmentConfig().Lite { return false } diff --git a/service/core/v2ray/feed.go b/service/kernel/v2ray/feed.go similarity index 100% rename from service/core/v2ray/feed.go rename to service/kernel/v2ray/feed.go diff --git a/service/core/v2ray/process.go b/service/kernel/v2ray/process.go similarity index 89% rename from service/core/v2ray/process.go rename to service/kernel/v2ray/process.go index 45d39b78..a7195cb3 100644 --- a/service/core/v2ray/process.go +++ b/service/kernel/v2ray/process.go @@ -17,9 +17,9 @@ import ( "github.com/shirou/gopsutil/v3/mem" "github.com/v2rayA/v2rayA/common" "github.com/v2rayA/v2rayA/conf" - "github.com/v2rayA/v2rayA/core/serverObj" - "github.com/v2rayA/v2rayA/core/v2ray/asset" - "github.com/v2rayA/v2rayA/core/v2ray/where" + "github.com/v2rayA/v2rayA/kernel/serverObj" + "github.com/v2rayA/v2rayA/kernel/v2ray/asset" + "github.com/v2rayA/v2rayA/kernel/v2ray/where" "github.com/v2rayA/v2rayA/db/configure" "github.com/v2rayA/v2rayA/pkg/util/log" ) @@ -45,6 +45,19 @@ func NewProcess(tmpl *Template, template: tmpl, done: make(chan struct{}), } + var err error + var rollbackStage int + defer func() { + if err != nil { + process.rollback(rollbackStage) + } + }() + + // DNS 模块由 v2raya-core 进程内启动(基于 dns_module 配置段), + // v2rayA 仅负责生成配置和在透明代理时应用防火墙规则。 + if tmpl.Setting != nil && tmpl.DnsModuleConfig != nil { + log.Info("DNS module config written to v2raya-core config") + } if tmpl.MultiObservatory != nil { // NOTICE: tag2WhichIndex is reliable because once connected servers are changed when v2ray is running, // the func UpdateV2RayConfig should be invoked and tag2WhichIndex will be regenerated. @@ -54,7 +67,7 @@ func NewProcess(tmpl *Template, } process.tag2WhichIndex = tag2WhichIndex } - err := WriteV2rayConfig(tmpl.ToConfigBytes()) + err = WriteV2rayConfig(tmpl.ToConfigBytes()) if err != nil { return nil, err } @@ -83,6 +96,7 @@ func NewProcess(tmpl *Template, if err != nil { return nil, err } + rollbackStage = 1 // xray 已启动 if err = poststart(); err != nil { return nil, err } @@ -172,6 +186,7 @@ var logWriter logInfoWriter func (p *Process) Close() error { p.mutex.Lock() defer p.mutex.Unlock() + // 停止 xray 进程(v2raya-core 内部会同时关闭 DNS 模块) if p.procCancel != nil { p.procCancel() p.procCancel = nil @@ -179,11 +194,11 @@ func (p *Process) Close() error { if err != nil { return err } - return nil } else { _, err := p.proc.Wait() return err } + return nil } func (p *Process) WaitUntilExit(ctx context.Context) error { @@ -356,3 +371,15 @@ func UpdateV2RayConfig() (err error) { } return } + +// rollback 回滚已启动的组件。 +// 注意:透明代理规则回滚由 processManager.afterStart 的 defer 处理。 +func (p *Process) rollback(stage int) { + if stage == 1 { + // xray 已启动 → 回滚 + if p.procCancel != nil { + p.procCancel() + p.procCancel = nil + } + } +} diff --git a/service/core/v2ray/processManager.go b/service/kernel/v2ray/processManager.go similarity index 99% rename from service/core/v2ray/processManager.go rename to service/kernel/v2ray/processManager.go index 8e3d2c81..8e54987c 100644 --- a/service/core/v2ray/processManager.go +++ b/service/kernel/v2ray/processManager.go @@ -8,7 +8,7 @@ import ( "github.com/v2rayA/v2rayA/common/resolv" "github.com/v2rayA/v2rayA/conf" - "github.com/v2rayA/v2rayA/core/v2ray/asset" + "github.com/v2rayA/v2rayA/kernel/v2ray/asset" "github.com/v2rayA/v2rayA/db/configure" "github.com/v2rayA/v2rayA/pkg/util/log" ) diff --git a/service/core/v2ray/service/service.go b/service/kernel/v2ray/service/service.go similarity index 93% rename from service/core/v2ray/service/service.go rename to service/kernel/v2ray/service/service.go index 0c9c4a46..09fdaeaf 100644 --- a/service/core/v2ray/service/service.go +++ b/service/kernel/v2ray/service/service.go @@ -8,9 +8,9 @@ import ( "github.com/v2rayA/v2rayA/common" "github.com/v2rayA/v2rayA/conf" - "github.com/v2rayA/v2rayA/core/iptables" - "github.com/v2rayA/v2rayA/core/v2ray/asset" - "github.com/v2rayA/v2rayA/core/v2ray/where" + "github.com/v2rayA/v2rayA/kernel/iptables" + "github.com/v2rayA/v2rayA/kernel/v2ray/asset" + "github.com/v2rayA/v2rayA/kernel/v2ray/where" ) var CoreVersionMismatchError = fmt.Errorf("core version mismatch") diff --git a/service/core/v2ray/templateJson.go b/service/kernel/v2ray/templateJson.go similarity index 100% rename from service/core/v2ray/templateJson.go rename to service/kernel/v2ray/templateJson.go diff --git a/service/kernel/v2ray/template_api.go b/service/kernel/v2ray/template_api.go new file mode 100644 index 00000000..2f1e381f --- /dev/null +++ b/service/kernel/v2ray/template_api.go @@ -0,0 +1,128 @@ +package v2ray + +import ( + "net" + "net/url" + "strings" + "time" + + "github.com/go-leo/slicex" + "github.com/v2rayA/v2rayA/db/configure" + "github.com/v2rayA/v2rayA/kernel/coreObj" + "github.com/v2rayA/v2rayA/kernel/v2ray/where" + "github.com/v2rayA/v2rayA/pkg/util/log" +) + +func (t *Template) SetAPI(serverData *ServerData) (port int, err error) { + // find a valid port + config := configure.GetPortsNotNil() + if config.Api.Port != 0 { + port = config.Api.Port + } else { + for { + if l, err := net.Listen("tcp4", "127.0.0.1:0"); err == nil { + port = l.Addr().(*net.TCPAddr).Port + _ = l.Close() + break + } + time.Sleep(30 * time.Millisecond) + } + } + services := []string{ + "LoggerService", + } + services = slicex.Uniq(append(services, config.Api.Services...)) + // observatory + if serverData != nil { + outbounds := t.outNames() + for outbound, isGroup := range outbounds { + if !isGroup { + continue + } + + //TODO: random, leastload + strategy := serverData.OutboundName2Setting[outbound].Type + interval, err := time.ParseDuration(serverData.OutboundName2Setting[outbound].ProbeInterval) + if err != nil { + log.Warn("observatory: %v", err) + interval = 10 * time.Second + } + var selector []string + + for _, vi := range serverData.OutboundName2ServerObjs[outbound] { + selector = append(selector, GroupWrapper(vi.GetName())) + } + + t.Routing.Balancers = append(t.Routing.Balancers, coreObj.Balancer{ + Tag: outbound, + Selector: selector, + Strategy: coreObj.BalancerStrategy{ + Type: strategy.String(), + Settings: &coreObj.StrategySettings{ + ObserverTag: outbound, + }, + }, + }) + + if strings.ToLower(strategy.String()) == "leastping" { + probeUrl := serverData.OutboundName2Setting[outbound].ProbeURL + if _, err := url.Parse(probeUrl); err != nil { + log.Warn("observatory: %v", err) + probeUrl = "https://gstatic.com/generate_204" + } + + // v2raya_core always uses MultiObservatory: one observer per balancer group. + if t.MultiObservatory == nil { + t.MultiObservatory = &coreObj.MultiObservatory{} + } + t.MultiObservatory.Observers = append(t.MultiObservatory.Observers, coreObj.ObservatoryItem{ + Tag: outbound, + Settings: coreObj.Observatory{ + SubjectSelector: selector, + PingConfig: &coreObj.PingConfig{ + Destination: probeUrl, + Interval: interval.String(), + }, + // Keep legacy fields for backward compatibility with older custom cores. + ProbeURL: probeUrl, + ProbeInterval: interval.String(), + }, + }) + } + } + if t.MultiObservatory != nil || t.Observatory != nil { + // v2raya_core supports ObservatoryService via the v2ray-compat gRPC path. + if t.Variant == where.V2rayaCore { + + var observatoryTags []string + for name, isGroup := range t.outNames() { + if isGroup { + observatoryTags = append(observatoryTags, name) + } + } + t.ApiCloses = append(t.ApiCloses, ObservatoryProducer(port, observatoryTags)) + } + } + } + t.API = &coreObj.APIObject{ + Tag: "api-out", + Services: services, + } + + t.Inbounds = append(t.Inbounds, coreObj.Inbound{ + Port: port, + Protocol: "dokodemo-door", + Listen: "127.0.0.1", + Settings: &coreObj.InboundSettings{ + Address: "127.0.0.1", + }, + Tag: "api-in", + }) + t.Routing.Rules = append(t.Routing.Rules, coreObj.RoutingRule{ + Type: "field", + InboundTag: []string{"api-in"}, + OutboundTag: "api-out", + }) + t.ApiPort = port + return port, nil +} diff --git a/service/kernel/v2ray/template_core.go b/service/kernel/v2ray/template_core.go new file mode 100644 index 00000000..fbc9735b --- /dev/null +++ b/service/kernel/v2ray/template_core.go @@ -0,0 +1,201 @@ +package v2ray + +import ( + "encoding/json" + "fmt" + "os" + "strconv" + "strings" + + jsoniter "github.com/json-iterator/go" + "github.com/v2rayA/v2rayA/conf" + "github.com/v2rayA/v2rayA/db/configure" + "github.com/v2rayA/v2rayA/kernel/coreObj" + "github.com/v2rayA/v2rayA/kernel/v2ray/asset" + "github.com/v2rayA/v2rayA/kernel/v2ray/where" +) + +type Template struct { + Log *coreObj.Log `json:"log,omitempty"` + Inbounds []coreObj.Inbound `json:"inbounds"` + Outbounds []coreObj.OutboundObject `json:"outbounds"` + Routing struct { + DomainStrategy string `json:"domainStrategy"` + DomainMatcher string `json:"domainMatcher,omitempty"` + Rules []coreObj.RoutingRule `json:"rules"` + Balancers []coreObj.Balancer `json:"balancers,omitempty"` + } `json:"routing"` + DNS *coreObj.DNS `json:"dns,omitempty"` + MultiObservatory *coreObj.MultiObservatory `json:"multiObservatory,omitempty"` + Observatory *coreObj.ObservatoryItem `json:"observatory,omitempty"` + API *coreObj.APIObject `json:"api,omitempty"` + // DnsModuleConfig 是新 DNS 模块的配置,由 v2raya-core 启动时解析并启动 DNS 监听器。 + DnsModuleConfig json.RawMessage `json:"dns_module,omitempty"` + + Variant where.Variant `json:"-"` + CoreVersion string `json:"-"` + OutboundTags []string `json:"-"` + ApiCloses []func() `json:"-"` + ApiPort int `json:"-"` + Setting *configure.Setting `json:"-"` + serverInfoMap map[string]*serverInfo `json:"-"` // outbound tag -> server info +} + +func (t *Template) Close() error { + for _, f := range t.ApiCloses { + f() + } + return nil +} + +func NewTemplate(serverInfos []serverInfo, setting *configure.Setting) (t *Template, err error) { + serverData := NewServerData(serverInfos) + if setting != nil { + setting.FillEmpty() + } else { + setting = configure.GetSettingNotNil() + } + + var tmplJson Template + // read template json + raw := []byte(TemplateJson) + err = jsoniter.Unmarshal(raw, &tmplJson) + if err != nil { + return nil, fmt.Errorf("error occurs while reading template json, please check whether templateJson variable is correct json format") + } + tmplJson.Variant, tmplJson.CoreVersion, _ = where.GetV2rayServiceVersion() + t = &tmplJson + t.Setting = setting + // log + logLevel := setting.LogLevel + if logLevel == "" { + logLevel = conf.GetEnvironmentConfig().LogLevel + } + logLevel = strings.ToLower(logLevel) + t.Log = new(coreObj.Log) + switch logLevel { + case "trace", "debug": + t.Log.Loglevel = "debug" + t.Log.Access = "" + t.Log.Error = "" + case "info": + t.Log.Loglevel = "info" + t.Log.Access = "" + t.Log.Error = "none" + case "warn", "warning": + t.Log.Loglevel = "warning" + t.Log.Access = "none" + t.Log.Error = "" + case "error": + t.Log.Loglevel = "error" + t.Log.Access = "none" + t.Log.Error = "" + default: + t.Log = nil + } + // resolve Outbounds + _, outboundTags, err := t.resolveOutbounds(serverData) + if err != nil { + return nil, err + } + t.OutboundTags = outboundTags + + //set inbound ports according to the setting + if err = t.setInbound(setting); err != nil { + return nil, err + } + // When TinyTun is active it handles DNS routing natively; v2ray only forwards traffic. + // Skip the DNS module for that mode. + isTinyTunMode := setting.TransparentType == configure.TransparentTun && IsTransparentOn(setting) + if !isTinyTunMode { + //生成新 DNS 模块配置 + if err = t.setDNS(); err != nil { + return nil, err + } + } + // 路由域名匹配器 + t.Routing.DomainMatcher = "mph" + //rule port routing + if err = t.setRulePortRouting(); err != nil { + return nil, err + } + //transparent routing + if IsTransparentOn(setting) { + if err = t.setTransparentRouting(); err != nil { + return nil, err + } + } + //set vmess inbound routing + t.setVmessInboundRouting() + // set api + if t.API == nil { + if _, err = t.SetAPI(serverData); err != nil { + return nil, err + } + } + // set routing whitelist + var whitelist []Addr + for _, info := range serverInfos { + port := "" + if info.Info.GetPort() != 0 { + port = strconv.Itoa(info.Info.GetPort()) + } + whitelist = append(whitelist, Addr{ + host: info.Info.GetHostname(), + port: port, + }) + } + t.setWhitelistRouting(whitelist) + + t.updatePrivateRouting() + + // add spare tire outbound routing. Fix: https://github.com/v2rayA/v2rayA/issues/447 + t.Routing.Rules = append(t.Routing.Rules, coreObj.RoutingRule{Type: "field", Port: "0-65535", OutboundTag: "proxy"}) + + // Set group routing. This should be put in the end of routing setters. + t.setGroupRouting() + + t.optimizeGeoipMemoryOccupation() + + //set outboundSockopt + t.SetOutboundSockopt() + + //set inbound listening address and routing + t.setDualStack() + + //check if there are any duplicated tags + if err = t.checkDuplicatedTags(); err != nil { + return nil, err + } + //check if there are any duplicated inbound ports + if err = t.checkDuplicatedInboundSockets(); err != nil { + return nil, err + } + + return t, nil +} + +func (t *Template) ToConfigBytes() []byte { + b, _ := jsoniter.Marshal(t) + return b +} + +func WriteV2rayConfig(content []byte) (err error) { + err = os.WriteFile(asset.GetV2rayConfigPath(), content, os.FileMode(0600)) + if err != nil { + return fmt.Errorf("WriteV2rayConfig: %w", err) + } + return +} + +func NewEmptyTemplate(setting *configure.Setting) (t *Template) { + t = new(Template) + t.Variant, t.CoreVersion, _ = where.GetV2rayServiceVersion() + if setting != nil { + setting.FillEmpty() + } else { + setting = configure.GetSettingNotNil() + } + t.Setting = setting + return t +} diff --git a/service/kernel/v2ray/template_dns.go b/service/kernel/v2ray/template_dns.go new file mode 100644 index 00000000..9013b5e8 --- /dev/null +++ b/service/kernel/v2ray/template_dns.go @@ -0,0 +1,370 @@ +package v2ray + +import ( + "encoding/json" + "fmt" + "net" + "net/url" + "os" + "strconv" + "strings" + + jsoniter "github.com/json-iterator/go" + "github.com/v2rayA/v2rayA/common" + "github.com/v2rayA/v2rayA/db/configure" +) + +type Addr struct { + host string + port string + udp bool +} + +func parseDnsAddr(addr string) Addr { + // 223.5.5.5 + if net.ParseIP(addr) != nil { + return Addr{ + host: addr, + port: "53", + udp: true, + } + } + // dns.google:53 + if host, port, err := net.SplitHostPort(addr); err == nil { + if _, err = strconv.Atoi(port); err == nil { + return Addr{ + host: host, + port: port, + udp: true, + } + } + } + // tcp://8.8.8.8:53, https://dns.google/dns-query, quic://dns.nextdns.io + if strings.Contains(addr, "://") { + if u, err := url.Parse(addr); err == nil { + udp := false + if u.Scheme == "quic" { + udp = true + } + return Addr{ + host: u.Hostname(), + port: u.Port(), + udp: udp, + } + } + } + // dns.google, dns.pub, etc. + return Addr{ + host: addr, + port: "53", + udp: true, + } +} + +type DnsRouting struct { + DirectDomains []Addr + ProxyDomains []Addr + DirectIPs []Addr + ProxyIPs []Addr +} + +// setDNS 生成新 DNS 模块的配置,嵌入 xray JSON 供 v2raya-core 读取。 +// v2raya-core 启动时解析此配置并启动独立 DNS 监听器,v2rayA 不参与 DNS 查询处理。 +func (t *Template) setDNS() error { + return t.generateDnsModuleConfig() +} + +// generateDnsModuleConfig 生成新 DNS 模块的 JSON 配置,嵌入 xray JSON 配置文件。 +// v2raya-core 启动时解析此配置并启动独立 DNS 监听器,v2rayA 不参与 DNS 查询处理。 +// +// 生成的配置结构对应 core/dns/config.go 中的 DnsModuleConfig。 +func (t *Template) generateDnsModuleConfig() error { + setting := t.Setting + if setting == nil { + setting = configure.GetSettingNotNil() + } + + listenAddr := setting.DnsListenAddr + if listenAddr == "" { + listenAddr = "0.0.0.0:52353" + } + + // 获取 SOCKS 入站端口(用于 proxy_map) + socksPort := 20170 + if p := configure.GetPortsNotNil(); p != nil && p.Socks5 > 0 { + socksPort = p.Socks5 + } + + // 读取当前系统 DNS(保存原始配置,用于 v2raya-core 的 bootstrap 解析)。 + // 此时 /etc/resolv.conf 尚未被劫持,读取的是真实的系统 DNS。 + bootstrapDns := getSystemDnsServers() + + cfg := map[string]interface{}{ + "listener": map[string]interface{}{ + "listen_addr": listenAddr, + "extra_listen_addrs": []string{"127.2.0.17:53"}, + "timeout": 5, + }, + "cache": map[string]interface{}{ + "enabled": setting.DnsCacheEnabled, + "size": setting.DnsCacheSize, + "min_ttl": setting.DnsCacheMinTTL, + "max_ttl": setting.DnsCacheMaxTTL, + "prefetch": setting.DnsPrefetch, + "neg_cache": setting.DnsNegativeCache, + }, + "proxy_map": make(map[string]interface{}), + "bootstrap": make([]string, 0), + "bootstrap_dns": bootstrapDns, + "upstreams": make([]map[string]interface{}, 0), + "rules": make([]map[string]interface{}, 0), + } + + // 应用默认值 + cache := cfg["cache"].(map[string]interface{}) + if cache["size"].(int) <= 0 { + cache["size"] = 4096 + } + if cache["min_ttl"].(int) <= 0 { + cache["min_ttl"] = 60 + } + if cache["max_ttl"].(int) <= 0 { + cache["max_ttl"] = 86400 + } + + // 获取并迁移 DNS 规则 + rules := configure.GetDnsRulesNotNil() + migrated := configure.MigrateDnsRules(rules) + + // 扫描所有 DNS 规则中引用的出站标签,构建 proxy_map + // (仅当标签非 direct/block 时创建映射,指向本地 SOCKS 入站端口) + proxyMap := cfg["proxy_map"].(map[string]interface{}) + bootstrapList := cfg["bootstrap"].([]string) + + // 用于上游去重的 key + type upstreamKey struct { + addr string + tag string + } + seenUpstream := make(map[upstreamKey]int) // key → index in upstreams list + upstreams := cfg["upstreams"].([]map[string]interface{}) + rulesList := cfg["rules"].([]map[string]interface{}) + + for _, rule := range migrated { + upstreamAddr := rule.Upstream + if upstreamAddr == "" { + upstreamAddr = rule.Server + } + if upstreamAddr == "" || upstreamAddr == "localhost" { + continue + } + + // 解析协议和地址,确保端口默认值正确 + proto := "udp" + addr := upstreamAddr + needDefaultPort := false + + if strings.Contains(upstreamAddr, "://") { + if strings.HasPrefix(upstreamAddr, "https://") { + proto = "https" + // DoH 地址保留完整 URL,端口由 URL 隐含 + } else if strings.HasPrefix(upstreamAddr, "tcp://") { + proto = "tcp" + addr = strings.TrimPrefix(upstreamAddr, "tcp://") + needDefaultPort = true + } else if strings.HasPrefix(upstreamAddr, "tls://") { + proto = "tcp-tls" + addr = strings.TrimPrefix(upstreamAddr, "tls://") + needDefaultPort = true + } else if strings.HasPrefix(upstreamAddr, "quic://") { + proto = "quic" + addr = strings.TrimPrefix(upstreamAddr, "quic://") + needDefaultPort = true + } else { + addr = upstreamAddr + needDefaultPort = true + } + } else { + needDefaultPort = true + } + + // 如果地址中没有端口号,根据协议类型补充默认端口 + if needDefaultPort { + if _, _, err := net.SplitHostPort(addr); err != nil { + switch proto { + case "https": + // DoH URL 包含完整地址,不需追加端口 + case "tcp-tls", "tls": + addr = net.JoinHostPort(addr, "853") + default: + addr = net.JoinHostPort(addr, "53") + } + } + } + + // 如果是域名地址,加入 bootstrap 列表,由 v2raya-core 用系统 DNS 解析 + if !strings.Contains(upstreamAddr, "://") { + host, _, err := net.SplitHostPort(addr) + if err != nil { + host = addr + } + if net.ParseIP(host) == nil { + bootstrapList = append(bootstrapList, host) + } + } + + outboundTag := rule.Outbound + if outboundTag == "" { + outboundTag = "direct" + } + + // 构建 proxy_map:为每个非直连的出站标签创建 SOCKS5 映射 + if outboundTag != "direct" && outboundTag != "block" { + if _, exists := proxyMap[outboundTag]; !exists { + proxyMap[outboundTag] = fmt.Sprintf("127.0.0.1:%d", socksPort) + } + } + + // 上游去重(相同地址+代理标签的上游只创建一个实例) + key := upstreamKey{addr: addr, tag: outboundTag} + upstreamID := fmt.Sprintf("upstream-%d", len(upstreams)) + if idx, ok := seenUpstream[key]; ok { + upstreamID = fmt.Sprintf("upstream-%d", idx) + } else { + seenUpstream[key] = len(upstreams) + upstreams = append(upstreams, map[string]interface{}{ + "id": upstreamID, + "addr": addr, + "protocol": proto, + "proxy_tag": outboundTag, + "bootstrap": false, + }) + } + + // 解析域名匹配规则 + var domains, suffixes []string + domainStr := rule.Domain + if domainStr == "" { + domainStr = rule.Domains + } + if domainStr != "" { + for _, d := range strings.Split(strings.TrimSpace(domainStr), "\n") { + d = strings.TrimSpace(d) + if d == "" { + continue + } + if strings.HasPrefix(d, "domain:") { + suffixes = append(suffixes, strings.TrimPrefix(d, "domain:")) + } else if strings.HasPrefix(d, "geosite:") || strings.HasPrefix(d, "keyword:") { + domains = append(domains, d) + } else { + domains = append(domains, d) + } + } + } + + // 解析 IP 匹配 + var ips []string + if rule.IP != "" { + for _, ip := range strings.Split(rule.IP, ",") { + ip = strings.TrimSpace(ip) + if ip != "" { + ips = append(ips, ip) + } + } + } + + // 解析客户端 IP + var clientIPs []string + if rule.ClientIP != "" { + for _, cidr := range strings.Split(rule.ClientIP, ",") { + cidr = strings.TrimSpace(cidr) + if cidr != "" { + clientIPs = append(clientIPs, cidr) + } + } + } + + // 构建规则配置(仅在有匹配条件时) + if len(domains) > 0 || len(suffixes) > 0 || len(clientIPs) > 0 || len(ips) > 0 { + ruleID := rule.RuleID + if ruleID == "" { + ruleID = fmt.Sprintf("rule-%d", len(rulesList)) + } + + action := rule.Action + if action == "" { + action = "route" + } + + policy := rule.Policy + if policy == "" { + policy = "single" + } + + rc := map[string]interface{}{ + "id": ruleID, + "upstream": upstreamID, + "action": action, + "policy": policy, + "domain": domains, + "domain_suffix": suffixes, + "ip": ips, + "client_ip": clientIPs, + } + + // 解析查询类型 + if rule.QueryType != "" && rule.QueryType != "*" { + var qtypes []string + for _, qt := range strings.Split(rule.QueryType, ",") { + qt = strings.TrimSpace(qt) + if qt != "" { + qtypes = append(qtypes, strings.ToUpper(qt)) + } + } + rc["query_type"] = qtypes + } + + rulesList = append(rulesList, rc) + } + } + + cfg["upstreams"] = upstreams + cfg["rules"] = rulesList + + // bootstrap 列表去重 + bootstrapList = common.Deduplicate(bootstrapList) + cfg["bootstrap"] = bootstrapList + + // 序列化为 JSON + raw, err := jsoniter.Marshal(cfg) + if err != nil { + return fmt.Errorf("marshal dns module config: %w", err) + } + t.DnsModuleConfig = json.RawMessage(raw) + + return nil +} + +// getSystemDnsServers 读取当前系统的 DNS 服务器列表(从 /etc/resolv.conf)。 +// 在劫持发生前调用,保存原始 DNS 供 v2raya-core bootstrap 使用。 +func getSystemDnsServers() []string { + data, err := os.ReadFile("/etc/resolv.conf") + if err != nil { + return nil + } + var servers []string + for _, line := range strings.Split(string(data), "\n") { + line = strings.TrimSpace(line) + if strings.HasPrefix(line, "nameserver") { + parts := strings.Fields(line) + if len(parts) >= 2 { + ip := parts[1] + if net.ParseIP(ip) != nil { + servers = append(servers, net.JoinHostPort(ip, "53")) + } + } + } + } + return servers +} diff --git a/service/kernel/v2ray/template_inbound.go b/service/kernel/v2ray/template_inbound.go new file mode 100644 index 00000000..985b5707 --- /dev/null +++ b/service/kernel/v2ray/template_inbound.go @@ -0,0 +1,303 @@ +package v2ray + +import ( + "crypto/sha256" + "encoding/hex" + "errors" + "net" + "sort" + "strings" + + "github.com/v2rayA/v2rayA/common" + "github.com/v2rayA/v2rayA/db/configure" + "github.com/v2rayA/v2rayA/kernel/coreObj" + "github.com/v2rayA/v2rayA/kernel/iptables" + "github.com/v2rayA/v2rayA/pkg/util/log" +) + +func FilterIPs(ips []string) []string { + var ret []string + for _, ip := range ips { + if net.ParseIP(ip).To4() != nil { + ret = append(ret, ip) + } + } + if !iptables.IsIPv6Supported() { + return ret + } + for _, ip := range ips { + if net.ParseIP(ip).To4() == nil { + ret = append(ret, ip) + } + } + return ret +} +func GetBestLocalIP(preferIPv6 bool) (net.IP, error) { + interfaces, err := net.Interfaces() + if err != nil { + return nil, err + } + + var bestIP net.IP + + for _, iface := range interfaces { + // Skip interfaces that are down + if iface.Flags&net.FlagUp == 0 { + continue + } + + // Skip TUN interfaces (typically named tun0, utun0, etc.) + ifName := strings.ToLower(iface.Name) + if strings.Contains(ifName, "tun") || strings.Contains(ifName, "tap") { + continue + } + + addrs, err := iface.Addrs() + if err != nil { + continue + } + + for _, addr := range addrs { + ipnet, ok := addr.(*net.IPNet) + if !ok { + continue + } + + ip := ipnet.IP + + // Skip loopback + if ip.IsLoopback() { + continue + } + + // Skip APIPA (169.254.x.x) + if ip.To4() != nil && ip.To4()[0] == 169 && ip.To4()[1] == 254 { + continue + } + + if preferIPv6 { + if ip.To4() == nil && ip.To16() != nil { + // IPv6 address + // Skip link-local for now (fe80::), prefer global + if !ip.IsLinkLocalUnicast() { + return ip, nil + } + if bestIP == nil { + bestIP = ip + } + } + } else { + if ip.To4() != nil { + // IPv4 address + return ip, nil + } + } + } + } + + if bestIP != nil { + return bestIP, nil + } + + if preferIPv6 { + return nil, errors.New("no suitable IPv6 address found") + } + return nil, errors.New("no suitable IPv4 address found") +} + +// GetLinkLocalIPv6 returns a link-local IPv6 address as fallback +func GetLinkLocalIPv6() (net.IP, error) { + interfaces, err := net.Interfaces() + if err != nil { + return nil, err + } + + for _, iface := range interfaces { + if iface.Flags&net.FlagUp == 0 { + continue + } + + // Skip TUN interfaces + ifName := strings.ToLower(iface.Name) + if strings.Contains(ifName, "tun") || strings.Contains(ifName, "tap") { + continue + } + + addrs, err := iface.Addrs() + if err != nil { + continue + } + + for _, addr := range addrs { + ipnet, ok := addr.(*net.IPNet) + if !ok { + continue + } + + ip := ipnet.IP + if ip.To4() == nil && ip.To16() != nil && ip.IsLinkLocalUnicast() { + return ip, nil + } + } + } + + return nil, errors.New("no link-local IPv6 address found") +} + +func GenerateIdFromAccounts() (id string, err error) { + accounts, err := configure.GetAccounts() + if err != nil { + return "", err + } + sort.Slice(accounts, func(i, j int) bool { + if accounts[i][0] == accounts[j][0] { + return accounts[i][1] < accounts[j][1] + } + return accounts[i][0] < accounts[j][0] + }) + h := sha256.New() + for _, account := range accounts { + h.Write([]byte(account[0])) + h.Write([]byte(account[1])) + } + id = common.StringToUUID5(hex.EncodeToString(h.Sum(nil))) + return id, nil +} + +func SetVmessInbound(vmess *coreObj.Inbound) (err error) { + id, err := GenerateIdFromAccounts() + if err != nil { + return err + } + vmess.Settings.Clients = []coreObj.VlessClient{{Id: id}} + return nil +} + +func (t *Template) setInbound(setting *configure.Setting) error { + p := configure.GetPortsNotNil() + if p != nil { + t.Inbounds[0].Port = p.Socks5 + t.Inbounds[1].Port = p.Http + t.Inbounds[2].Port = p.Socks5WithPac + t.Inbounds[3].Port = p.HttpWithPac + listenAddr := "127.0.0.1" + if t.Setting.PortSharing { + listenAddr = "0.0.0.0" + } + for i := 0; i < 5 && i < len(t.Inbounds); i++ { + t.Inbounds[i].Listen = listenAddr + } + vmess := &t.Inbounds[4] + vmess.Port = p.Vmess + if p.Vmess > 0 { + if err := SetVmessInbound(vmess); err != nil { + return err + } + } + } + // remove those inbounds with zero port number + for i := len(t.Inbounds) - 1; i >= 0; i-- { + if t.Inbounds[i].Port == 0 { + t.Inbounds = append(t.Inbounds[:i], t.Inbounds[i+1:]...) + } + } + // Append user-defined custom inbounds (SOCKS / HTTP only) + listenAddrForCustom := "127.0.0.1" + if t.Setting != nil && t.Setting.PortSharing { + listenAddrForCustom = "0.0.0.0" + } + for _, ci := range configure.GetCustomInbounds() { + if ci.Port <= 0 || (ci.Protocol != "socks" && ci.Protocol != "http") { + continue + } + ib := coreObj.Inbound{ + Port: ci.Port, + Protocol: ci.Protocol, + Listen: listenAddrForCustom, + Tag: ci.Tag, + } + if ci.Protocol == "socks" { + ib.Settings = &coreObj.InboundSettings{UDP: true} + } + t.Inbounds = append(t.Inbounds, ib) + + // Generate per-inbound routing rules based on the bound outbound group + if ci.Outbound != "" && ci.OutboundType != "" { + switch ci.OutboundType { + case "direct": + // Direct single outbound: route all traffic from this inbound to the bound outbound group + t.Routing.Rules = append(t.Routing.Rules, coreObj.RoutingRule{ + Type: "field", + OutboundTag: ci.Outbound, + InboundTag: []string{ci.Tag}, + }) + case "routingA": + // RoutingA rules: parse and apply with InboundTag filter + if ci.RoutingARules != "" { + rules, err := parseRoutingARules(ci.RoutingARules, ci.Tag) + if err != nil { + log.Warn("setInbound: failed to parse RoutingA rules for inbound %s: %v", ci.Tag, err) + } else { + t.Routing.Rules = append(t.Routing.Rules, rules...) + } + } + } + } + } + if IsTransparentOn(t.Setting) { + switch t.Setting.TransparentType { + case configure.TransparentTproxy, configure.TransparentRedirect: + t.AppendDokodemoTProxy(string(t.Setting.TransparentType), 52345, "transparent") + case configure.TransparentSystemProxy: + t.Inbounds = append(t.Inbounds, coreObj.Inbound{ + Port: 52345, + Protocol: "http", + Listen: "127.0.0.1", + Tag: "transparent", + }, coreObj.Inbound{ + Port: 52306, + Protocol: "socks", + Listen: "127.0.0.1", + Settings: &coreObj.InboundSettings{ + UDP: true, + }, + Tag: "transparent-socks", + }) + case configure.TransparentTun: + t.Inbounds = append(t.Inbounds, coreObj.Inbound{ + Port: tinytunSocksPort, + Protocol: "socks", + Listen: "127.0.0.1", + Settings: &coreObj.InboundSettings{ + UDP: true, + }, + Tag: "transparent", + }) + // TinyTun v0.0.2+ handles DNS routing natively via its own DNS groups. + // The former dns-in-tun dokodemo-door (127.0.0.1:6053) is no longer needed; + // v2ray acts as a pure SOCKS5 forwarder for non-DNS traffic. + } + + } + if ShouldLocalDnsListen() { + log.Trace("DNS module handles DNS on port 52353, no dns-in needed") + } + + // Set up domain sniffing + if setting.InboundSniffing != configure.InboundSniffingDisable && setting.InboundSniffing != "" { + enableSniffingRouteOnly := configure.GetSettingNotNil().RouteOnly + domainsExcludedText := configure.GetDomainsExcluded() + for i := len(t.Inbounds) - 1; i >= 0; i-- { + if setting.InboundSniffing == configure.InboundSniffingHttpTLS { + t.Inbounds[i].Sniffing.DestOverride = []string{"http", "tls"} + } else { + t.Inbounds[i].Sniffing.DestOverride = []string{"http", "tls", "quic"} + } + t.Inbounds[i].Sniffing.DomainsExcluded = strings.Split(domainsExcludedText, "\n") + t.Inbounds[i].Sniffing.Enabled = true + t.Inbounds[i].Sniffing.RouteOnly = enableSniffingRouteOnly + } + + } + return nil +} diff --git a/service/kernel/v2ray/template_outbound.go b/service/kernel/v2ray/template_outbound.go new file mode 100644 index 00000000..0b0c080f --- /dev/null +++ b/service/kernel/v2ray/template_outbound.go @@ -0,0 +1,411 @@ +package v2ray + +import ( + "fmt" + "net" + "sort" + "strconv" + "strings" + + "github.com/mohae/deepcopy" + "github.com/v2rayA/v2rayA/db/configure" + "github.com/v2rayA/v2rayA/kernel/coreObj" + "github.com/v2rayA/v2rayA/kernel/iptables" + "github.com/v2rayA/v2rayA/kernel/serverObj" + "github.com/v2rayA/v2rayA/kernel/v2ray/where" + "github.com/v2rayA/v2rayA/pkg/util/log" +) + +func (t *Template) SetOutboundSockopt() { + mark := 0x80 + //tos := 184 + for i := range t.Outbounds { + if t.Outbounds[i].Protocol == "blackhole" || t.Outbounds[i].Protocol == "dns" { + continue + } + if t.Outbounds[i].StreamSettings == nil { + t.Outbounds[i].StreamSettings = new(coreObj.StreamSettings) + } + if t.Outbounds[i].StreamSettings.Sockopt == nil { + t.Outbounds[i].StreamSettings.Sockopt = new(coreObj.Sockopt) + } + if t.Outbounds[i].Protocol == "freedom" && t.Outbounds[i].Tag == "direct" { + t.Outbounds[i].Settings.DomainStrategy = "UseIP" + } + if t.Setting.TcpFastOpen != configure.Default { + tmp := t.Setting.TcpFastOpen == configure.Yes + t.Outbounds[i].StreamSettings.Sockopt.TCPFastOpen = &tmp + } + t.checkAndSetMark(&t.Outbounds[i], mark) + } +} +func (t *Template) setDualStack() { + const ( + tag4Suffix = "_ipv4" + tag6Suffix = "_ipv6" + ) + tagMap := make(map[string]struct{}) + inbounds6 := deepcopy.Copy(t.Inbounds).([]coreObj.Inbound) + + // Add ::1 twins for every inbound that listens on a 127.x loopback address. + // Inbounds on 0.0.0.0 (LAN-shared) are not duplicated. + // Special exclusions: + // transparent+Redirect – kernel REDIRECT requires 0.0.0.0 + // dns-in – receives the 127.2.0.17 treatment below + for i := range t.Inbounds { + tag := t.Inbounds[i].Tag + if tag == "transparent" && t.Setting.TransparentType == configure.TransparentRedirect { + // https://ipset.netfilter.org/iptables-extensions.man.html#lbDK + // REDIRECT rewrites the destination to the primary address of the incoming interface, + // so the inbound must stay at 0.0.0.0. + inbounds6[i].Tag = "THIS_IS_A_DROPPED_TAG" + continue + } + if tag == "dns-in" { + // Handled separately — skip generic duplication. + inbounds6[i].Tag = "THIS_IS_A_DROPPED_TAG" + continue + } + if !strings.HasPrefix(t.Inbounds[i].Listen, "127.") { + // 0.0.0.0 or other non-loopback address — no ::1 twin needed. + inbounds6[i].Tag = "THIS_IS_A_DROPPED_TAG" + continue + } + inbounds6[i].Listen = "::1" + if tag != "" { + tagMap[tag] = struct{}{} + t.Inbounds[i].Tag += tag4Suffix + inbounds6[i].Tag += tag6Suffix + } + } + + for i := len(inbounds6) - 1; i >= 0; i-- { + if inbounds6[i].Tag == "THIS_IS_A_DROPPED_TAG" { + inbounds6 = append(inbounds6[:i], inbounds6[i+1:]...) + } + } + + if iptables.IsIPv6Supported() { + t.Inbounds = append(t.Inbounds, inbounds6...) + } + + // Update routing rules with _ipv4/_ipv6 suffixes for duplicated inbounds. + for i := range t.Routing.Rules { + tag6 := make([]string, 0) + for j, tag := range t.Routing.Rules[i].InboundTag { + if _, ok := tagMap[tag]; ok { + t.Routing.Rules[i].InboundTag[j] += tag4Suffix + tag6 = append(tag6, tag+tag6Suffix) + } + } + if v6supported := iptables.IsIPv6Supported(); len(tag6) > 0 && v6supported { + t.Routing.Rules[i].InboundTag = append(t.Routing.Rules[i].InboundTag, tag6...) + } + } + + // dns-in special handling: always bind to 127.2.0.17 for split-routing local queries. + // When PortSharing is on the inbound also stays on 0.0.0.0 for LAN DNS, so we add a + // second copy at 127.2.0.17 with tag dns-in-local. + for i := range t.Inbounds { + if t.Inbounds[i].Tag != "dns-in" { + continue + } + if !t.Setting.PortSharing { + // PortSharing off: move the single dns-in inbound to loopback-only. + t.Inbounds[i].Listen = "127.2.0.17" + } else { + // PortSharing on: keep 0.0.0.0 for LAN; also add a local copy. + if couldListenLocalhost, e := CouldLocalDnsListen(); couldListenLocalhost && e != nil { + // Port 53 is already in use on localhost; only listen on the special address. + t.Inbounds[i].Listen = "127.2.0.17" + } else { + localDnsInbound := t.Inbounds[i] + localDnsInbound.Listen = "127.2.0.17" + localDnsInbound.Tag = "dns-in-local" + t.Inbounds = append(t.Inbounds, localDnsInbound) + // Add dns-in-local to any routing rule that references dns-in. + for ri := range t.Routing.Rules { + for _, rtag := range t.Routing.Rules[ri].InboundTag { + if rtag == "dns-in" { + t.Routing.Rules[ri].InboundTag = append(t.Routing.Rules[ri].InboundTag, "dns-in-local") + break + } + } + } + } + } + break + } +} +func (t *Template) setSendThrough() { + for i := 0; i < len(t.Outbounds); i++ { + outbound := &t.Outbounds[i] + + // Get server info for this outbound + sInfo, exists := t.serverInfoMap[outbound.Tag] + if !exists { + continue + } + + // Determine the appropriate local address + sendThrough := t.getSendThroughForServer(sInfo) + if sendThrough != "" { + outbound.SendThrough = sendThrough + log.Trace("[v2ray] Set sendThrough for %s: %s", outbound.Tag, sendThrough) + } + } +} + +func (t *Template) getSendThroughForServer(sInfo *serverInfo) string { + serverHost := sInfo.Info.GetHostname() + + // If connecting to plugin (localhost), use 127.0.0.1 + if sInfo.PluginPort > 0 { + return "127.0.0.1" + } + + // Check if server is IPv4 or IPv6 + if serverIP := net.ParseIP(serverHost); serverIP != nil { + if serverIP.To4() != nil { + // IPv4 server - use IPv4 local address + if ip, err := GetBestLocalIP(false); err == nil { + return ip.String() + } + } else { + // IPv6 server - use IPv6 local address + if ip, err := GetBestLocalIP(true); err == nil { + return ip.String() + } + // Fallback to link-local IPv6 if no global address available + if ip, err := GetLinkLocalIPv6(); err == nil { + return ip.String() + } + } + } else { + // Domain name - prefer IPv4 + if ip, err := GetBestLocalIP(false); err == nil { + return ip.String() + } + } + + return "" +} + +// GetBestLocalIP returns the best local IP address, skipping TUN, loopback, and APIPA addresses +func resolveEffectiveBackend(obj serverObj.ServerObj, setting *configure.Setting) string { + bg, ok := obj.(serverObj.BackendGetter) + if !ok { + return "" + } + nodeBackend := bg.GetBackend() + if nodeBackend != "" { + return nodeBackend + } + // Fall back to system setting + switch obj.GetProtocol() { + case "shadowsocks", "ss": + return setting.SsBackend + case "trojan", "trojan-go": + return setting.TrojanBackend + } + return "" +} + +func (t *Template) resolveOutbounds( + serverData *ServerData, +) (supportUDP map[string]bool, outboundTags []string, err error) { + + supportUDP = make(map[string]bool) + t.serverInfoMap = make(map[string]*serverInfo) + type _outbound struct { + weight int + outbound coreObj.OutboundObject + balancer bool + } + serverInfo2Index := make(map[*serverInfo]int) + for i := range serverData.ServerInfos { + serverInfo2Index[&serverData.ServerInfos[i]] = i + } + // keep order with serverInfos + outboundTags = make([]string, len(serverData.ServerInfos)) + var extraOutbounds []coreObj.OutboundObject + var outbounds []_outbound + setting := configure.GetSettingNotNil() + for obj, sInfos := range serverData.ServerObj2ServerInfos() { + var ( + usedByBalancer bool + ) + // an vmessInfo(server template) may be used by multiple serverInfos(a connected server) + + // outbound name is not just v2ray outbound tag, it may be a balancer + type balancer struct { + name string + serverInfo *serverInfo + } + var balancers []balancer + for _, sInfo := range sInfos { + if len(serverData.OutboundName2ServerObjs[sInfo.OutboundName]) > 1 { + // balancer + if !usedByBalancer { + usedByBalancer = true + } + balancers = append(balancers, balancer{ + name: sInfo.OutboundName, + serverInfo: sInfo, + }) + } else { + // pure outbound + outboundTag := sInfo.OutboundName + c, err := obj.Configuration(serverObj.PriorInfo{ + Variant: t.Variant, + CoreVersion: t.CoreVersion, + Tag: outboundTag, + PluginPort: sInfo.PluginPort, + Backend: resolveEffectiveBackend(obj, setting), + }) + if err != nil { + return nil, nil, err + } + // Store server info for this outbound + t.serverInfoMap[outboundTag] = sInfo + extraOutbounds = append(extraOutbounds, c.ExtraOutbounds...) + outbounds = append(outbounds, _outbound{ + weight: serverInfo2Index[sInfo], + outbound: c.CoreOutbound, + balancer: false, + }) + outboundTags[serverInfo2Index[sInfo]] = outboundTag + supportUDP[sInfo.OutboundName] = c.UDPSupport + } + } + if usedByBalancer { + // the v2ray outbound is shared by balancers + outboundTag := GroupWrapper(obj.GetName()) + c, err := obj.Configuration(serverObj.PriorInfo{ + Variant: t.Variant, + CoreVersion: t.CoreVersion, + Tag: outboundTag, + PluginPort: 0, + Backend: resolveEffectiveBackend(obj, setting), + }) + if err != nil { + // Store server info for balancer outbound (use first balancer's info) + if len(balancers) > 0 { + t.serverInfoMap[outboundTag] = balancers[0].serverInfo + } + return nil, nil, err + } + extraOutbounds = append(extraOutbounds, c.ExtraOutbounds...) + for _, v := range balancers { + c.CoreOutbound.Balancers = append(c.CoreOutbound.Balancers, v.name) + } + // we use the lowest serverInfo index as the order weight of the balancer outbound + weight := -1 + for _, v := range balancers { + index := serverInfo2Index[v.serverInfo] + if weight == -1 || weight > index { + weight = index + } + // tag + outboundTags[index] = outboundTag + } + outbounds = append(outbounds, _outbound{ + weight: weight, + outbound: c.CoreOutbound, + balancer: true, + }) + + // if any node does not support UDP, the outbound should be tagged as UDP unsupported + for _, outboundName := range c.CoreOutbound.Balancers { + _supportUDP := c.UDPSupport + if _, ok := supportUDP[outboundName]; !ok { + supportUDP[outboundName] = _supportUDP + } + if supportUDP[outboundName] && !_supportUDP { + supportUDP[outboundName] = false + } + } + } + } + sort.Slice(outbounds, func(i, j int) bool { + return outbounds[i].weight < outbounds[j].weight + }) + for _, v := range outbounds { + t.Outbounds = append(t.Outbounds, v.outbound) + } + t.Outbounds = append(t.Outbounds, coreObj.OutboundObject{ + Tag: "direct", + Protocol: "freedom", + }, coreObj.OutboundObject{ + Tag: "block", + Protocol: "blackhole", + }) + t.Outbounds = append(t.Outbounds, extraOutbounds...) + return supportUDP, outboundTags, nil +} + +func (t *Template) checkAndSetMark(o *coreObj.OutboundObject, mark int) { + if !IsTransparentOn(t.Setting) { + return + } + if o.StreamSettings == nil { + o.StreamSettings = new(coreObj.StreamSettings) + } + if o.StreamSettings.Sockopt == nil { + o.StreamSettings.Sockopt = new(coreObj.Sockopt) + } + o.StreamSettings.Sockopt.Mark = &mark +} + +func (t *Template) InsertMappingOutbound(o serverObj.ServerObj, inboundPort string, udpSupport bool, pluginPort int, protocol string) (err error) { + if t.CoreVersion == "" { + t.Variant, t.CoreVersion, _ = where.GetV2rayServiceVersion() + } + c, err := o.Configuration(serverObj.PriorInfo{ + Variant: t.Variant, + CoreVersion: t.CoreVersion, + Tag: "outbound" + inboundPort, + PluginPort: pluginPort, + Backend: resolveEffectiveBackend(o, configure.GetSettingNotNil()), + }) + if err != nil { + return err + } + var mark = 0x80 + t.checkAndSetMark(&c.CoreOutbound, mark) + t.Outbounds = append(t.Outbounds, c.CoreOutbound) + t.Outbounds = append(t.Outbounds, c.ExtraOutbounds...) + iPort, err := strconv.Atoi(inboundPort) + if err != nil || iPort <= 0 { + return fmt.Errorf("port of inbound must be a positive number with string type") + } + if protocol == "" { + protocol = "socks" + } + t.Inbounds = append(t.Inbounds, coreObj.Inbound{ + Port: iPort, + Protocol: protocol, + Listen: "0.0.0.0", + Sniffing: coreObj.Sniffing{ + Enabled: false, + DestOverride: []string{"http", "tls"}, + }, + Settings: &coreObj.InboundSettings{ + Auth: "noauth", + UDP: udpSupport, + }, + Tag: "inbound" + inboundPort, + }) + if t.Routing.DomainStrategy == "" { + t.Routing.DomainStrategy = "IPOnDemand" + } + // Insert at the beginning + tmp := make([]coreObj.RoutingRule, 1, len(t.Routing.Rules)+1) + tmp[0] = coreObj.RoutingRule{ + Type: "field", + OutboundTag: "outbound" + inboundPort, + InboundTag: []string{"inbound" + inboundPort}, + } + t.Routing.Rules = append(tmp, t.Routing.Rules...) + return +} diff --git a/service/kernel/v2ray/template_routing.go b/service/kernel/v2ray/template_routing.go new file mode 100644 index 00000000..8bb2f62d --- /dev/null +++ b/service/kernel/v2ray/template_routing.go @@ -0,0 +1,591 @@ +package v2ray + +import ( + "fmt" + "net" + "os" + "regexp" + "strconv" + "strings" + + "github.com/mohae/deepcopy" + "github.com/v2rayA/RoutingA" + "github.com/v2rayA/v2rayA/db/configure" + "github.com/v2rayA/v2rayA/kernel/coreObj" + "github.com/v2rayA/v2rayA/kernel/iptables" + "github.com/v2rayA/v2rayA/kernel/v2ray/asset" + "github.com/v2rayA/v2rayA/pkg/util/log" +) + +func (t *Template) outNames() map[string]bool { + tags := make(map[string]bool) + for _, o := range t.Outbounds { + if len(o.Balancers) > 0 { + for _, groupName := range o.Balancers { + tags[groupName] = true + } + } else { + tags[o.Tag] = false + } + } + return tags +} + +func (t *Template) FirstProxyOutboundName(filter func(outboundName string, isGroup bool) bool) (outboundName string, isGroup bool) { + if filter == nil { + filter = func(outboundName string, isGroup bool) bool { + return true + } + } + // deduplicate + m := make(map[string]struct{}) + + for _, o := range t.Outbounds { + switch o.Tag { + case "direct", "block", "dns-out": + continue + } + if len(o.Balancers) > 0 { + for _, v := range o.Balancers { + if _, ok := m[v]; !ok { + if filter(v, true) { + return v, true + } + m[v] = struct{}{} + } + } + } else { + if filter(o.Tag, false) { + return o.Tag, false + } + } + } + return +} + +// dnsRuleToLines converts a configure.DnsRule to the "server -> outbound" line format +// and the domain list used for the DNS server object. +// Returns (serverLine, []domains). serverLine is empty if server is empty. +func (t *Template) AppendRoutingRuleByMode(mode configure.RulePortMode, inbounds []string) (err error) { + firstOutboundTag, _ := t.FirstProxyOutboundName(nil) + // apple pushing. #495 #479 + t.Routing.Rules = append(t.Routing.Rules, coreObj.RoutingRule{ + Type: "field", + OutboundTag: "direct", + InboundTag: deepcopy.Copy(inbounds).([]string), + Domain: []string{"domain:push-apple.com.akadns.net", "domain:push.apple.com"}, + }) + switch mode { + case configure.WhitelistMode: + // foreign domains with intranet IP should be proxied first rather than directly connected + if asset.DoesV2rayAssetExist("LoyalsoldierSite.dat") { + t.Routing.Rules = append(t.Routing.Rules, + coreObj.RoutingRule{ + Type: "field", + OutboundTag: firstOutboundTag, + InboundTag: deepcopy.Copy(inbounds).([]string), + Domain: []string{"ext:LoyalsoldierSite.dat:geolocation-!cn"}, + }) + } else { + t.Routing.Rules = append(t.Routing.Rules, + coreObj.RoutingRule{ + Type: "field", + OutboundTag: firstOutboundTag, + InboundTag: deepcopy.Copy(inbounds).([]string), + Domain: []string{"geosite:geolocation-!cn"}, + }) + } + t.Routing.Rules = append(t.Routing.Rules, + coreObj.RoutingRule{ + Type: "field", + OutboundTag: "proxy", + InboundTag: deepcopy.Copy(inbounds).([]string), + // https://github.com/v2rayA/v2rayA/issues/285 + Domain: []string{"geosite:google"}, + }, + coreObj.RoutingRule{ + Type: "field", + OutboundTag: "direct", + InboundTag: deepcopy.Copy(inbounds).([]string), + Domain: []string{"geosite:cn"}, + }, + coreObj.RoutingRule{ + Type: "field", + OutboundTag: "proxy", + InboundTag: deepcopy.Copy(inbounds).([]string), + IP: []string{"geoip:hk", "geoip:mo"}, + }, + coreObj.RoutingRule{ + Type: "field", + OutboundTag: "direct", + InboundTag: deepcopy.Copy(inbounds).([]string), + IP: []string{"geoip:private", "geoip:cn"}, + }, + ) + case configure.GfwlistMode: + if asset.DoesV2rayAssetExist("LoyalsoldierSite.dat") { + t.Routing.Rules = append(t.Routing.Rules, + coreObj.RoutingRule{ + Type: "field", + OutboundTag: firstOutboundTag, + InboundTag: deepcopy.Copy(inbounds).([]string), + Domain: []string{"ext:LoyalsoldierSite.dat:gfw"}, + }, + coreObj.RoutingRule{ + Type: "field", + OutboundTag: firstOutboundTag, + InboundTag: deepcopy.Copy(inbounds).([]string), + Domain: []string{"ext:LoyalsoldierSite.dat:greatfire"}, + }) + } else { + t.Routing.Rules = append(t.Routing.Rules, + coreObj.RoutingRule{ + Type: "field", + OutboundTag: firstOutboundTag, + InboundTag: deepcopy.Copy(inbounds).([]string), + Domain: []string{"geosite:geolocation-!cn"}, + }) + } + + t.Routing.Rules = append(t.Routing.Rules, + coreObj.RoutingRule{ + Type: "field", + OutboundTag: firstOutboundTag, + InboundTag: deepcopy.Copy(inbounds).([]string), + // From: https://github.com/Loyalsoldier/geoip/blob/release/text/telegram.txt + IP: []string{"91.105.192.0/23", "91.108.4.0/22", "91.108.8.0/21", "91.108.16.0/21", "91.108.56.0/22", + "95.161.64.0/20", "149.154.160.0/20", "185.76.151.0/24", "2001:67c:4e8::/48", "2001:b28:f23c::/47", + "2001:b28:f23f::/48", "2a0a:f280:203::/48"}, + }, + coreObj.RoutingRule{ + Type: "field", + OutboundTag: "direct", + InboundTag: deepcopy.Copy(inbounds).([]string), + }, + ) + case configure.RoutingAMode: + if err := parseRoutingA(t, deepcopy.Copy(inbounds).([]string)); err != nil { + return err + } + } + return nil +} + +func (t *Template) setRulePortRouting() error { + // append rule-http and rule-socks no mather if they are enabled + // because "The Same as the Rule Port" may need them + return t.AppendRoutingRuleByMode(t.Setting.RulePortMode, []string{"rule-http", "rule-socks"}) +} +func parseRoutingA(t *Template, routingInboundTags []string) error { + lines := strings.Split(configure.GetRoutingA(), "\n") + hardcodeReplacement := regexp.MustCompile(`\$\$.+?\$\$`) + for i := range lines { + hardcodes := hardcodeReplacement.FindAllString(lines[i], -1) + for _, hardcode := range hardcodes { + env := strings.TrimSuffix(strings.TrimPrefix(hardcode, "$$"), "$$") + val, ok := os.LookupEnv(env) + if !ok { + log.Error("RoutingA: Environment variable \"%v\" is not found", env) + } else { + log.Info("RoutingA: Environment variable %v=%v", env, strconv.Quote(val)) + } + lines[i] = strings.Replace(lines[i], hardcode, val, 1) + } + } + rules, err := RoutingA.Parse(strings.Join(lines, "\n")) + if err != nil { + log.Warn("parseRoutingA: %v", err) + return err + } + defaultOutbound, _ := t.FirstProxyOutboundName(nil) + for _, rule := range rules { + switch rule := rule.(type) { + case RoutingA.Define: + switch rule.Name { + case "inbound", "outbound": + switch o := rule.Value.(type) { + case RoutingA.Bound: + proto := o.Value + switch proto.Name { + case "http", "socks": + if len(proto.NamedParams["address"]) < 1 || + len(proto.NamedParams["port"]) < 1 { + continue + } + port, err := strconv.Atoi(proto.NamedParams["port"][0]) + if err != nil { + continue + } + server := coreObj.Server{ + Port: port, + Address: proto.NamedParams["address"][0], + } + if unames := proto.NamedParams["user"]; len(unames) > 0 { + passwords := proto.NamedParams["pass"] + levels := proto.NamedParams["level"] + for i, uname := range unames { + u := coreObj.OutboundUser{ + User: uname, + } + if i < len(passwords) { + u.Pass = passwords[i] + } + if i < len(levels) { + level, err := strconv.Atoi(levels[i]) + if err == nil { + u.Level = level + } + } + server.Users = append(server.Users, u) + } + } + switch rule.Name { + case "outbound": + t.Outbounds = append(t.Outbounds, coreObj.OutboundObject{ + Tag: o.Name, + Protocol: o.Value.Name, + Settings: coreObj.Settings{ + Servers: []coreObj.Server{ + server, + }, + }, + }) + case "inbound": + // DEPRECATED: inbound definition in RoutingA is no longer supported. + // Log a warning and skip creating the inbound. + log.Warn("parseRoutingA: inbound definition '%s' is deprecated and will be ignored. "+ + "Use custom inbound settings with RoutingA rules instead.", o.Name) + } + case "freedom": + settings := coreObj.Settings{} + if len(proto.NamedParams["domainStrategy"]) > 0 { + settings.DomainStrategy = proto.NamedParams["domainStrategy"][0] + } + if len(proto.NamedParams["redirect"]) > 0 { + settings.Redirect = proto.NamedParams["redirect"][0] + } + if len(proto.NamedParams["userLevel"]) > 0 { + level, err := strconv.Atoi(proto.NamedParams["userLevel"][0]) + if err == nil { + settings.UserLevel = &level + } + } + t.Outbounds = append(t.Outbounds, coreObj.OutboundObject{ + Tag: o.Name, + Protocol: o.Value.Name, + Settings: settings, + }) + } + } + } + } + } + outboundTags := t.outNames() + for _, rule := range rules { + switch rule := rule.(type) { + case RoutingA.Define: + switch rule.Name { + case "default": + switch v := rule.Value.(type) { + case string: + defaultOutbound = v + if _, ok := outboundTags[v]; !ok { + return fmt.Errorf(`your RoutingA rules depend on the outbound "%v", thus you should select at least one server in this outbound`, v) + } + } + } + case RoutingA.Routing: + rr := deepcopy.Copy(coreObj.RoutingRule{ + Type: "field", + OutboundTag: rule.Out, + InboundTag: routingInboundTags, + }).(coreObj.RoutingRule) + for _, f := range rule.And { + switch f.Name { + case "domain", "domains": + for k, vv := range f.NamedParams { + for _, v := range vv { + if k == "contains" { + rr.Domain = append(rr.Domain, v) + continue + } + if k == "ext" { + datFilenameAndTag := strings.SplitN(v, ":", 2) + if len(datFilenameAndTag) < 2 { + return fmt.Errorf("%v: tag is not given", v) + } + if !asset.DoesV2rayAssetExist(datFilenameAndTag[0]) { + return fmt.Errorf("%v: file is not found", datFilenameAndTag[0]) + } + } + rr.Domain = append(rr.Domain, fmt.Sprintf("%v:%v", k, v)) + } + } + // unnamed param is not recommended + rr.Domain = append(rr.Domain, f.Params...) + case "ip": + for k, vv := range f.NamedParams { + for _, v := range vv { + if k == "ext" { + datFilenameAndTag := strings.SplitN(v, ":", 2) + if len(datFilenameAndTag) < 2 { + return fmt.Errorf("%v: tag is not given", v) + } + if !asset.DoesV2rayAssetExist(datFilenameAndTag[0]) { + return fmt.Errorf("%v: file is not found", datFilenameAndTag[0]) + } + } + rr.IP = append(rr.IP, fmt.Sprintf("%v:%v", k, v)) + } + } + rr.IP = append(rr.IP, f.Params...) + case "network": + rr.Network = strings.Join(f.Params, ",") + case "port": + rr.Port = strings.Join(f.Params, ",") + case "sourcePort": + rr.SourcePort = strings.Join(f.Params, ",") + case "protocol": + rr.Protocol = f.Params + case "source": + rr.Source = f.Params + case "user": + rr.User = f.Params + case "inboundTag": + rr.InboundTag = f.Params + } + } + if rr.OutboundTag != "" { + if _, ok := outboundTags[rr.OutboundTag]; !ok { + return fmt.Errorf(`your RoutingA rules depend on the outbound "%v", thus you should select at least one server in this outbound`, rr.OutboundTag) + } + } + t.Routing.Rules = append(t.Routing.Rules, rr) + } + } + t.Routing.Rules = append(t.Routing.Rules, coreObj.RoutingRule{ + Type: "field", + OutboundTag: defaultOutbound, + InboundTag: []string{"rule-http", "rule-socks"}, + }) + return nil +} + +// parseRoutingARules parses RoutingA rule text and returns routing rules +// filtered by the given inboundTag. This is used for custom inbound RoutingA rules. +// It does NOT create any inbounds or outbounds - only routing rules. +func parseRoutingARules(rulesText string, inboundTag string) (rules []coreObj.RoutingRule, err error) { + lines := strings.Split(rulesText, "\n") + hardcodeReplacement := regexp.MustCompile(`\$\$.+?\$\$`) + for i := range lines { + hardcodes := hardcodeReplacement.FindAllString(lines[i], -1) + for _, hardcode := range hardcodes { + env := strings.TrimSuffix(strings.TrimPrefix(hardcode, "$$"), "$$") + val, ok := os.LookupEnv(env) + if !ok { + log.Error("parseRoutingARules: Environment variable \"%v\" is not found", env) + } else { + log.Info("parseRoutingARules: Environment variable %v=%v", env, strconv.Quote(val)) + } + lines[i] = strings.Replace(lines[i], hardcode, val, 1) + } + } + parsedRules, err := RoutingA.Parse(strings.Join(lines, "\n")) + if err != nil { + return nil, err + } + for _, rule := range parsedRules { + switch rule := rule.(type) { + case RoutingA.Routing: + rr := deepcopy.Copy(coreObj.RoutingRule{ + Type: "field", + OutboundTag: rule.Out, + InboundTag: []string{inboundTag}, + }).(coreObj.RoutingRule) + for _, f := range rule.And { + switch f.Name { + case "domain", "domains": + for k, vv := range f.NamedParams { + for _, v := range vv { + if k == "contains" { + rr.Domain = append(rr.Domain, v) + continue + } + if k == "ext" { + datFilenameAndTag := strings.SplitN(v, ":", 2) + if len(datFilenameAndTag) < 2 { + return nil, fmt.Errorf("%v: tag is not given", v) + } + if !asset.DoesV2rayAssetExist(datFilenameAndTag[0]) { + return nil, fmt.Errorf("%v: file is not found", datFilenameAndTag[0]) + } + } + rr.Domain = append(rr.Domain, fmt.Sprintf("%v:%v", k, v)) + } + } + rr.Domain = append(rr.Domain, f.Params...) + case "ip": + for k, vv := range f.NamedParams { + for _, v := range vv { + if k == "ext" { + datFilenameAndTag := strings.SplitN(v, ":", 2) + if len(datFilenameAndTag) < 2 { + return nil, fmt.Errorf("%v: tag is not given", v) + } + if !asset.DoesV2rayAssetExist(datFilenameAndTag[0]) { + return nil, fmt.Errorf("%v: file is not found", datFilenameAndTag[0]) + } + } + rr.IP = append(rr.IP, fmt.Sprintf("%v:%v", k, v)) + } + } + rr.IP = append(rr.IP, f.Params...) + case "network": + rr.Network = strings.Join(f.Params, ",") + case "port": + rr.Port = strings.Join(f.Params, ",") + case "sourcePort": + rr.SourcePort = strings.Join(f.Params, ",") + case "protocol": + rr.Protocol = f.Params + case "source": + rr.Source = f.Params + case "user": + rr.User = f.Params + case "inboundTag": + rr.InboundTag = f.Params + } + } + if rr.OutboundTag != "" { + rules = append(rules, rr) + } + } + } + return rules, nil +} + +func (t *Template) setTransparentRouting() (err error) { + defaultOutbound, _ := t.FirstProxyOutboundName(nil) + switch t.Setting.Transparent { + case configure.TransparentProxy: + // Global transparent: route all transparent inbound to default outbound + t.Routing.Rules = append(t.Routing.Rules, coreObj.RoutingRule{ + Type: "field", + InboundTag: []string{"transparent"}, + OutboundTag: defaultOutbound, + }) + case configure.TransparentWhitelist: + return t.AppendRoutingRuleByMode(configure.WhitelistMode, []string{"transparent"}) + case configure.TransparentGfwlist: + return t.AppendRoutingRuleByMode(configure.GfwlistMode, []string{"transparent"}) + case configure.TransparentFollowRule: + // transparent mode is the same as rule + for i := range t.Routing.Rules { + ok := false + for _, in := range t.Routing.Rules[i].InboundTag { + if in == "rule-http" { + ok = true + break + } + } + if ok { + t.Routing.Rules[i].InboundTag = append(t.Routing.Rules[i].InboundTag, "transparent") + } + } + } + return nil +} +func (t *Template) AppendDokodemoTProxy(tproxy string, port int, tag string) { + dokodemo := coreObj.Inbound{ + Listen: "127.0.0.1", + Port: port, + Protocol: "dokodemo-door", + Sniffing: coreObj.Sniffing{ + Enabled: true, + DestOverride: []string{"http", "tls"}, + }, + Settings: &coreObj.InboundSettings{Network: "tcp,udp"}, + Tag: tag, + } + dokodemo.StreamSettings = &coreObj.StreamSettings{Sockopt: &coreObj.Sockopt{Tproxy: &tproxy}} + dokodemo.Settings.FollowRedirect = true + t.Inbounds = append(t.Inbounds, dokodemo) +} + +func (t *Template) updatePrivateRouting() { + privateAddrs, _ := iptables.GetLocalCIDR() + if len(privateAddrs) == 0 { + return + } + for i := range t.Routing.Rules { + for j := range t.Routing.Rules[i].IP { + if t.Routing.Rules[i].IP[j] == "geoip:private" { + t.Routing.Rules[i].IP = append(t.Routing.Rules[i].IP, privateAddrs...) + break + } + } + } +} + +func (t *Template) optimizeGeoipMemoryOccupation() { + if asset.DoesV2rayAssetExist("geoip-only-cn-private.dat") { + for i := range t.Routing.Rules { + for j := range t.Routing.Rules[i].IP { + switch t.Routing.Rules[i].IP[j] { + case "geoip:private", "geoip:cn": + t.Routing.Rules[i].IP[j] = "ext:geoip-only-cn-private.dat:" + strings.TrimPrefix(t.Routing.Rules[i].IP[j], "geoip:") + } + } + } + } +} + +func (t *Template) setWhitelistRouting(whitelist []Addr) { + var rules []coreObj.RoutingRule + for _, addr := range whitelist { + if net.ParseIP(addr.host) != nil { + rules = append(rules, coreObj.RoutingRule{ + Type: "field", + OutboundTag: "direct", + IP: []string{addr.host}, + Port: addr.port, + }) + } else { + rules = append(rules, coreObj.RoutingRule{ + Type: "field", + OutboundTag: "direct", + Domain: []string{addr.host}, + Port: addr.port, + }) + } + } + if len(rules) > 0 { + t.Routing.Rules = append(rules, t.Routing.Rules...) + } +} + +func (t *Template) setGroupRouting() { + outbounds := t.outNames() + for i := range t.Routing.Rules { + if t.Routing.Rules[i].OutboundTag != "" && outbounds[t.Routing.Rules[i].OutboundTag] == true { + t.Routing.Rules[i].BalancerTag, t.Routing.Rules[i].OutboundTag = t.Routing.Rules[i].OutboundTag, "" + } + } +} + +func (t *Template) setVmessInboundRouting() { + if configure.GetPortsNotNil().Vmess <= 0 { + return + } + for i := range t.Routing.Rules { + var bHasRule bool + for _, tag := range t.Routing.Rules[i].InboundTag { + if tag == "rule-http" { + bHasRule = true + } + } + if bHasRule { + t.Routing.Rules[i].InboundTag = append(t.Routing.Rules[i].InboundTag, "vmess") + } + } +} diff --git a/service/kernel/v2ray/template_serverdata.go b/service/kernel/v2ray/template_serverdata.go new file mode 100644 index 00000000..9ee84d8d --- /dev/null +++ b/service/kernel/v2ray/template_serverdata.go @@ -0,0 +1,100 @@ +package v2ray + +import ( + "fmt" + "strconv" + + "github.com/v2rayA/v2rayA/db/configure" + "github.com/v2rayA/v2rayA/kernel/serverObj" +) + +type serverInfo struct { + Info serverObj.ServerObj + OutboundName string + PluginPort int +} + +func GroupWrapper(ps string) string { + return fmt.Sprintf("『%v』", ps) +} + +type ServerData struct { + RawServerInfos []serverInfo + ServerInfos []serverInfo + OutboundName2Setting map[string]configure.OutboundSetting + Link2ServerInfos map[string][]*serverInfo + Link2ServerObj map[string]serverObj.ServerObj + OutboundName2ServerObjs map[string][]serverObj.ServerObj +} + +func NewServerData(serverInfos []serverInfo) (serverData *ServerData) { + // guarantee that an v2ray outbound is reusable for balancers + var rawServerInfos = make([]serverInfo, len(serverInfos)) + copy(rawServerInfos, serverInfos) + link2ServerInfos := make(map[string][]*serverInfo) + link2ServerObj := make(map[string]serverObj.ServerObj) + for i, info := range serverInfos { + link := info.Info.ExportToURL() + link2ServerObj[link] = info.Info + link2ServerInfos[link] = append(link2ServerInfos[link], &serverInfos[i]) + } + // make ps unique + link2ServerInfosAfter := make(map[string][]*serverInfo) + mPsRenaming := make(map[string]struct{}) + for link, ois := range link2ServerInfos { + ps := link2ServerObj[link].GetName() + cnt := 2 + for { + if _, ok := mPsRenaming[ps]; !ok { + mPsRenaming[ps] = struct{}{} + link2ServerObj[link].SetName(ps) + link2ServerInfosAfter[link] = ois + break + } + ps = fmt.Sprintf("%v(%v)", link2ServerObj[link].GetName(), strconv.Itoa(cnt)) + cnt++ + } + } + + outboundName2ServerObjs := make(map[string][]serverObj.ServerObj) + for link, ois := range link2ServerInfosAfter { + for _, oi := range ois { + outboundName2ServerObjs[oi.OutboundName] = append(outboundName2ServerObjs[oi.OutboundName], link2ServerObj[link]) + } + } + + OutboundName2Setting := make(map[string]configure.OutboundSetting) + for outbound := range outboundName2ServerObjs { + OutboundName2Setting[outbound] = configure.GetOutboundSetting(outbound) + } + + return &ServerData{ + RawServerInfos: rawServerInfos, + ServerInfos: serverInfos, + Link2ServerInfos: link2ServerInfosAfter, + Link2ServerObj: link2ServerObj, + OutboundName2ServerObjs: outboundName2ServerObjs, + OutboundName2Setting: OutboundName2Setting, + } +} + +func (sd *ServerData) ServerObj2ServerInfos() map[serverObj.ServerObj][]*serverInfo { + m := make(map[serverObj.ServerObj][]*serverInfo) + for link, sObj := range sd.Link2ServerObj { + m[sObj] = sd.Link2ServerInfos[link] + } + return m +} + +func (sd *ServerData) Ps2OutboundNames() map[string][]string { + ps2OutboundNames := make(map[string][]string) + for outboundName, objs := range sd.OutboundName2ServerObjs { + for _, vi := range objs { + ps2OutboundNames[vi.GetName()] = append(ps2OutboundNames[vi.GetName()], outboundName) + } + } + return ps2OutboundNames +} + +// resolveEffectiveBackend returns the effective backend ("v2ray" or "") for a ServerObj. +// It checks the node's own backend setting first, then falls back to the system setting. diff --git a/service/kernel/v2ray/template_validate.go b/service/kernel/v2ray/template_validate.go new file mode 100644 index 00000000..511e7b9b --- /dev/null +++ b/service/kernel/v2ray/template_validate.go @@ -0,0 +1,120 @@ +package v2ray + +import ( + "errors" + "fmt" + "net" + "os" + "strconv" + "strings" + + "github.com/v2rayA/v2rayA/common/netTools/netstat" + "github.com/v2rayA/v2rayA/common/netTools/ports" + "github.com/v2rayA/v2rayA/db/configure" + "github.com/v2rayA/v2rayA/pkg/util/log" +) + +func (t *Template) checkDuplicatedTags() error { + inboundTagsSet := make(map[string]interface{}) + for _, in := range t.Inbounds { + tag := in.Tag + if _, exists := inboundTagsSet[tag]; exists { + return fmt.Errorf("duplicated inbound tag: %v", tag) + } else { + inboundTagsSet[tag] = nil + } + } + outboundTagsSet := make(map[string]interface{}) + for _, out := range t.Outbounds { + tag := out.Tag + if _, exists := outboundTagsSet[tag]; exists { + return fmt.Errorf("duplicated outbound tag: %v", tag) + } else { + outboundTagsSet[tag] = nil + } + } + return nil +} + +func (t *Template) checkDuplicatedInboundSockets() error { + inboundSocketSet := make(map[string]interface{}) + for _, in := range t.Inbounds { + if in.Listen == "" { + // https://www.v2fly.org/config/inbounds.html#inboundobject + in.Listen = "0.0.0.0" + } + socket := net.JoinHostPort(in.Listen, strconv.Itoa(in.Port)) + if _, exists := inboundSocketSet[socket]; exists { + return fmt.Errorf("duplicated inbound listening address: %v", socket) + } else { + inboundSocketSet[socket] = nil + } + } + return nil +} + +var OccupiedErr = fmt.Errorf("port is occupied") + +func PortOccupied(syntax []string) (err error) { + occupied, sockets, err := ports.IsPortOccupied(syntax) + if err != nil { + if errors.Is(err, netstat.ErrorNotSupportOSErr) { + log.Trace("PortOccupied: %v", err) + return nil + } + return + } + if occupied { + if err = netstat.FillProcesses(sockets); err != nil { + if errors.Is(err, netstat.ErrorNotSupportOSErr) { + log.Warn("cannot judge port occupation: %v", err) + return nil + } + return fmt.Errorf("failed to check if port is occupied: %w", err) + } + for _, s := range sockets { + p := s.Proc + if p == nil { + continue + } + if ownPID := strconv.Itoa(os.Getpid()); p.PPID == ownPID || + p.PID == ownPID { + continue + } + occupiedErr := fmt.Errorf("%w by %v(%v): %v", OccupiedErr, p.Name, p.PID, s.LocalAddress.Port) + if configure.GetSettingNotNil().PortSharing { + // want to listen 0.0.0.0, which conflicts with all IPs + return occupiedErr + } + if s.LocalAddress.IP.IsUnspecified() { + return occupiedErr + } + if s.LocalAddress.IP.IsLoopback() { + return occupiedErr + } + } + } + return nil +} + +func (t *Template) CheckInboundPortsOccupied() (err error) { + var st []string + for _, in := range t.Inbounds { + switch strings.ToLower(in.Protocol) { + case "http", "vmess", "vless", "trojan": + st = append(st, strconv.Itoa(in.Port)+":tcp") + case "dokodemo-door": + if strings.HasPrefix(in.Tag, "dns-in") { + // checked before + continue + } else if in.Settings != nil && in.Settings.Network != "" { + st = append(st, strconv.Itoa(in.Port)+":"+in.Settings.Network) + } else { + st = append(st, strconv.Itoa(in.Port)+":tcp,udp") + } + default: + st = append(st, strconv.Itoa(in.Port)+":tcp,udp") + } + } + return PortOccupied(st) +} diff --git a/service/core/v2ray/tinytun_enabled.go b/service/kernel/v2ray/tinytun_enabled.go similarity index 99% rename from service/core/v2ray/tinytun_enabled.go rename to service/kernel/v2ray/tinytun_enabled.go index 4b08f9a3..eaae8b46 100644 --- a/service/core/v2ray/tinytun_enabled.go +++ b/service/kernel/v2ray/tinytun_enabled.go @@ -18,8 +18,8 @@ import ( "gopkg.in/yaml.v3" "github.com/v2rayA/v2rayA/conf" - "github.com/v2rayA/v2rayA/core/v2ray/asset" - "github.com/v2rayA/v2rayA/core/v2ray/where" + "github.com/v2rayA/v2rayA/kernel/v2ray/asset" + "github.com/v2rayA/v2rayA/kernel/v2ray/where" "github.com/v2rayA/v2rayA/db/configure" "github.com/v2rayA/v2rayA/pkg/util/log" ) diff --git a/service/core/v2ray/tinytun_stub.go b/service/kernel/v2ray/tinytun_stub.go similarity index 100% rename from service/core/v2ray/tinytun_stub.go rename to service/kernel/v2ray/tinytun_stub.go diff --git a/service/kernel/v2ray/transparent.go b/service/kernel/v2ray/transparent.go new file mode 100644 index 00000000..13609203 --- /dev/null +++ b/service/kernel/v2ray/transparent.go @@ -0,0 +1,212 @@ +package v2ray + +import ( + "fmt" + "net" + "strings" + "time" + + "github.com/v2rayA/v2rayA/common/cmds" + "github.com/v2rayA/v2rayA/conf" + "github.com/v2rayA/v2rayA/db/configure" + "github.com/v2rayA/v2rayA/kernel/iptables" + "github.com/v2rayA/v2rayA/pkg/util/log" +) + +// cleanupResidualTransparentProxyRules cleans up any residual iptables/nftables rules +// that may have been left behind after an abnormal termination (e.g., kill -9, system crash, panic). +// It uses "2>/dev/null || true" to ensure no errors are raised if rules/chains don't exist. +func cleanupResidualTransparentProxyRules() { + commands := ` +# 清理 DNS_MARK 链(TProxy 模式) +iptables -w 2 -t mangle -F DNS_MARK 2>/dev/null || true +iptables -w 2 -t mangle -D PREROUTING -p udp --dport 53 -j DNS_MARK 2>/dev/null || true +iptables -w 2 -t mangle -D PREROUTING -p tcp --dport 53 -j DNS_MARK 2>/dev/null || true +iptables -w 2 -t mangle -D OUTPUT -p udp --dport 53 -j DNS_MARK 2>/dev/null || true +iptables -w 2 -t mangle -D OUTPUT -p tcp --dport 53 -j DNS_MARK 2>/dev/null || true +iptables -w 2 -t mangle -X DNS_MARK 2>/dev/null || true + # 清理 DNS_REDIRECT 链(Redirect 模式) + iptables -w 2 -t nat -F DNS_REDIRECT 2>/dev/null || true + iptables -w 2 -t nat -D PREROUTING -p udp --dport 53 -j DNS_REDIRECT 2>/dev/null || true + iptables -w 2 -t nat -D PREROUTING -p tcp --dport 53 -j DNS_REDIRECT 2>/dev/null || true + iptables -w 2 -t nat -D OUTPUT -p udp --dport 53 -j DNS_REDIRECT 2>/dev/null || true + iptables -w 2 -t nat -D OUTPUT -p tcp --dport 53 -j DNS_REDIRECT 2>/dev/null || true + iptables -w 2 -t nat -X DNS_REDIRECT 2>/dev/null || true + # 清理直接 REDIRECT 规则(所有透明代理模式通用的 DNS 重定向) + iptables -w 2 -t nat -D PREROUTING -p udp --dport 53 -j REDIRECT --to-port 52353 2>/dev/null || true + iptables -w 2 -t nat -D PREROUTING -p tcp --dport 53 -j REDIRECT --to-port 52353 2>/dev/null || true + iptables -w 2 -t nat -D OUTPUT -p udp --dport 53 -j REDIRECT --to-port 52353 2>/dev/null || true + iptables -w 2 -t nat -D OUTPUT -p tcp --dport 53 -j REDIRECT --to-port 52353 2>/dev/null || true +# IPv6 清理 +ip6tables -w 2 -t mangle -F DNS_MARK 2>/dev/null || true +ip6tables -w 2 -t mangle -D PREROUTING -p udp --dport 53 -j DNS_MARK 2>/dev/null || true +ip6tables -w 2 -t mangle -D PREROUTING -p tcp --dport 53 -j DNS_MARK 2>/dev/null || true +ip6tables -w 2 -t mangle -D OUTPUT -p udp --dport 53 -j DNS_MARK 2>/dev/null || true +ip6tables -w 2 -t mangle -D OUTPUT -p tcp --dport 53 -j DNS_MARK 2>/dev/null || true +ip6tables -w 2 -t mangle -X DNS_MARK 2>/dev/null || true + ip6tables -w 2 -t nat -F DNS_REDIRECT 2>/dev/null || true + ip6tables -w 2 -t nat -D PREROUTING -p udp --dport 53 -j DNS_REDIRECT 2>/dev/null || true + ip6tables -w 2 -t nat -D PREROUTING -p tcp --dport 53 -j DNS_REDIRECT 2>/dev/null || true + ip6tables -w 2 -t nat -D OUTPUT -p udp --dport 53 -j DNS_REDIRECT 2>/dev/null || true + ip6tables -w 2 -t nat -D OUTPUT -p tcp --dport 53 -j DNS_REDIRECT 2>/dev/null || true + ip6tables -w 2 -t nat -X DNS_REDIRECT 2>/dev/null || true + # 清理 IPv6 直接 REDIRECT 规则 + ip6tables -w 2 -t nat -D PREROUTING -p udp --dport 53 -j REDIRECT --to-port 52353 2>/dev/null || true + ip6tables -w 2 -t nat -D PREROUTING -p tcp --dport 53 -j REDIRECT --to-port 52353 2>/dev/null || true + ip6tables -w 2 -t nat -D OUTPUT -p udp --dport 53 -j REDIRECT --to-port 52353 2>/dev/null || true + ip6tables -w 2 -t nat -D OUTPUT -p tcp --dport 53 -j REDIRECT --to-port 52353 2>/dev/null || true +# 清理 TProxy 链 +iptables -w 2 -t mangle -F TP_OUT 2>/dev/null || true +iptables -w 2 -t mangle -D OUTPUT -j TP_OUT 2>/dev/null || true +iptables -w 2 -t mangle -X TP_OUT 2>/dev/null || true +iptables -w 2 -t mangle -F TP_PRE 2>/dev/null || true +iptables -w 2 -t mangle -D PREROUTING -j TP_PRE 2>/dev/null || true +iptables -w 2 -t mangle -X TP_PRE 2>/dev/null || true +iptables -w 2 -t mangle -F TP_RULE 2>/dev/null || true +iptables -w 2 -t mangle -X TP_RULE 2>/dev/null || true +iptables -w 2 -t mangle -F TP_MARK 2>/dev/null || true +iptables -w 2 -t mangle -X TP_MARK 2>/dev/null || true +# 清理 Redirect 链 +iptables -w 2 -t nat -F TP_OUT 2>/dev/null || true +iptables -w 2 -t nat -D OUTPUT -j TP_OUT 2>/dev/null || true +iptables -w 2 -t nat -X TP_OUT 2>/dev/null || true +iptables -w 2 -t nat -F TP_PRE 2>/dev/null || true +iptables -w 2 -t nat -D PREROUTING -j TP_PRE 2>/dev/null || true +iptables -w 2 -t nat -X TP_PRE 2>/dev/null || true +iptables -w 2 -t nat -F TP_RULE 2>/dev/null || true +iptables -w 2 -t nat -X TP_RULE 2>/dev/null || true +iptables -w 2 -F DROP_SPOOFING 2>/dev/null || true +iptables -w 2 -D INPUT -j DROP_SPOOFING 2>/dev/null || true +iptables -w 2 -D FORWARD -j DROP_SPOOFING 2>/dev/null || true +iptables -w 2 -X DROP_SPOOFING 2>/dev/null || true +ip rule del fwmark 0x40/0xc0 table 100 2>/dev/null || true +ip route del local 0.0.0.0/0 dev lo table 100 2>/dev/null || true +nft delete table inet v2raya 2>/dev/null || true +` + cmds.ExecCommands(commands, false) +} + +func deleteTransparentProxyRulesKeepSystemProxy() { + stopTinyTun() + iptables.CloseWatcher() + if !conf.GetEnvironmentConfig().Lite { + removeResolvHijacker() + iptables.Tproxy.GetCleanCommands().Run(false) + iptables.Redirect.GetCleanCommands().Run(false) + iptables.DropSpoofing.GetCleanCommands().Run(false) + } + time.Sleep(30 * time.Millisecond) +} + +func deleteTransparentProxyRules() { + deleteTransparentProxyRulesKeepSystemProxy() + iptables.SystemProxy.GetCleanCommands().Run(false) +} + +func writeTransparentProxyRules(tmpl *Template) (err error) { + defer func() { + if err != nil { + log.Warn("writeTransparentProxyRules: %v", err) + deleteTransparentProxyRules() + } + }() + // v2raya-core 进程内启动 DNS 模块(监听 :52353), + // v2rayA 负责在透明代理时应用 iptables/nftables 规则将 53 端口流量重定向到 52353。 + // 等待 DNS 模块就绪后应用防火墙规则。 + if tmpl != nil && tmpl.DnsModuleConfig != nil { + dnsAddr := "127.2.0.17:52353" + if tmpl.Setting != nil && tmpl.Setting.DnsListenAddr != "" { + dnsAddr = tmpl.Setting.DnsListenAddr + } + if err := waitForDnsPort(dnsAddr, 5*time.Second); err != nil { + return fmt.Errorf("dns module not ready: %w", err) + } + log.Trace("DNS module is ready on %s, setting up transparent proxy rules", dnsAddr) + } + cleanupResidualTransparentProxyRules() + setting := configure.GetSettingNotNil() + switch setting.TransparentType { + case configure.TransparentTun: + return startTinyTun(tmpl) + case configure.TransparentTproxy: + if err = iptables.Tproxy.GetSetupCommands().Run(true); err != nil { + if strings.Contains(err.Error(), "TPROXY") && strings.Contains(err.Error(), "No chain") { + err = fmt.Errorf("you does not compile xt_TPROXY in kernel") + } + return fmt.Errorf("not support \"tproxy\" mode of transparent proxy: %w", err) + } + iptables.SetWatcher(iptables.Tproxy) + case configure.TransparentRedirect: + if err = iptables.Redirect.GetSetupCommands().Run(true); err != nil { + return fmt.Errorf("not support \"redirect\" mode of transparent proxy: %w", err) + } + iptables.SetWatcher(iptables.Redirect) + case configure.TransparentSystemProxy: + if err = iptables.SystemProxy.GetSetupCommands().Run(true); err != nil { + return fmt.Errorf("not support \"system proxy\" mode of transparent proxy: %w", err) + } + default: + return fmt.Errorf("undefined \"%v\" mode of transparent proxy", setting.TransparentType) + } + + // 无论哪种透明代理模式,都用 nat 表的 REDIRECT 将 DNS 流量(:53)转到 DNS 模块(:52353)。 + // 同时拦截 OUTPUT(本地进程)和 PREROUTING(LAN 设备)的 DNS 查询。 + // TPROXY 模式对回环(loopback)流量的 TPROXY 拦截不可靠,而 REDIRECT 在 OUTPUT 链上稳定。 + if ShouldLocalDnsListen() { + dnsRedirect := ` +iptables -w 2 -t nat -I PREROUTING -p udp --dport 53 -j REDIRECT --to-port 52353 +iptables -w 2 -t nat -I PREROUTING -p tcp --dport 53 -j REDIRECT --to-port 52353 +iptables -w 2 -t nat -I OUTPUT -p udp --dport 53 -j REDIRECT --to-port 52353 +iptables -w 2 -t nat -I OUTPUT -p tcp --dport 53 -j REDIRECT --to-port 52353 +` + if iptables.IsIPv6Supported() { + dnsRedirect += ` +ip6tables -w 2 -t nat -I PREROUTING -p udp --dport 53 -j REDIRECT --to-port 52353 +ip6tables -w 2 -t nat -I PREROUTING -p tcp --dport 53 -j REDIRECT --to-port 52353 +ip6tables -w 2 -t nat -I OUTPUT -p udp --dport 53 -j REDIRECT --to-port 52353 +ip6tables -w 2 -t nat -I OUTPUT -p tcp --dport 53 -j REDIRECT --to-port 52353 +` + } + cmds.ExecCommands(dnsRedirect, false) + + if couldListenLocalhost, e := CouldLocalDnsListen(); couldListenLocalhost { + if e != nil { + log.Warn("only listen at 127.2.0.17: %v", e) + } + resetResolvHijacker() + } else { + log.Warn("writeTransparentProxyRules: %v", e) + } + } + return nil +} + +func IsTransparentOn(setting *configure.Setting) bool { + if setting == nil { + setting = configure.GetSettingNotNil() + } + if setting.Transparent == configure.TransparentClose { + return false + } + if conf.GetEnvironmentConfig().Lite && + (setting.TransparentType == configure.TransparentTproxy || + setting.TransparentType == configure.TransparentRedirect) { + return false + } + return true +} + +// waitForDnsPort polls the DNS module's listening port until it's ready or a timeout expires. +// This ensures the v2raya-core DNS module is accepting queries before we apply firewall rules. +func waitForDnsPort(addr string, timeout time.Duration) error { + deadline := time.Now().Add(timeout) + for time.Now().Before(deadline) { + conn, err := net.DialTimeout("udp", addr, 500*time.Millisecond) + if err == nil { + conn.Close() + return nil + } + time.Sleep(100 * time.Millisecond) + } + return fmt.Errorf("dns port %s not reachable within %v", addr, timeout) +} diff --git a/service/core/v2ray/where/where.go b/service/kernel/v2ray/where/where.go similarity index 100% rename from service/core/v2ray/where/where.go rename to service/kernel/v2ray/where/where.go diff --git a/service/core/vmessInfo/vmessInfo.go b/service/kernel/vmessInfo/vmessInfo.go similarity index 100% rename from service/core/vmessInfo/vmessInfo.go rename to service/kernel/vmessInfo/vmessInfo.go diff --git a/service/pre.go b/service/pre.go index db3e07b5..cf43b571 100644 --- a/service/pre.go +++ b/service/pre.go @@ -1,281 +1,15 @@ package main import ( - "errors" - "fmt" - "net" "os" - "os/signal" - "path/filepath" "runtime" - "sync" - "syscall" - "time" - "github.com/gin-gonic/gin" - jsonIteratorExtra "github.com/json-iterator/go/extra" - "github.com/v2rayA/v2rayA/common/netTools/ports" "github.com/v2rayA/v2rayA/conf" - "github.com/v2rayA/v2rayA/core/ipforward" - "github.com/v2rayA/v2rayA/core/v2ray" - "github.com/v2rayA/v2rayA/core/v2ray/asset" - "github.com/v2rayA/v2rayA/core/v2ray/asset/dat" - service2 "github.com/v2rayA/v2rayA/core/v2ray/service" - "github.com/v2rayA/v2rayA/core/v2ray/where" - "github.com/v2rayA/v2rayA/db" - "github.com/v2rayA/v2rayA/db/configure" - "github.com/v2rayA/v2rayA/pkg/util/copyfile" + "github.com/v2rayA/v2rayA/kernel/v2ray/asset" + "github.com/v2rayA/v2rayA/kernel/v2ray/where" "github.com/v2rayA/v2rayA/pkg/util/log" - "github.com/v2rayA/v2rayA/pkg/util/privilege" - "github.com/v2rayA/v2rayA/server/router" - "github.com/v2rayA/v2rayA/server/service" - - confv4 "github.com/v2rayA/v2rayA-lib4/conf" - - touchv4 "github.com/v2rayA/v2rayA-lib4/core/touch" - - configurev4 "github.com/v2rayA/v2rayA-lib4/db/configure" - - servicev4 "github.com/v2rayA/v2rayA-lib4/server/service" ) -func checkEnvironment() { - config := conf.GetEnvironmentConfig() - if len(config.PrintReport) > 0 { - db.SetReadOnly() - config.Report() - os.Exit(0) - } - if !config.PassCheckRoot { - switch runtime.GOOS { - case "linux": - if !privilege.IsRootOrAdmin() && !config.Lite { - log.Fatal("Please execute this program with sudo or as a root user for the best experience.\n" + - "If you are sure you are root user, use the --passcheckroot parameter to skip the check.\n" + - "If you don't want to run as root or you are a non-linux user, use --lite please.\n" + - "For example:\n" + - "$ v2raya --lite", - ) - } - case "windows": - if !privilege.IsRootOrAdmin() && !config.Lite { - log.Fatal("Please run v2rayA as Administrator (or SYSTEM) with elevation, or start with --lite to skip privilege checks.") - } - } - } - if config.ResetPassword { - fmt.Println("Config directory:", config.Config) - fmt.Println("Resetting password...\nIf no response for a long time, please stop other v2rayA instances and try again.") - err := configure.ResetAccounts() - if err != nil { - log.Fatal("checkEnvironment: %v", err) - } - fmt.Println("Succeed. It will work after you restart v2rayA.") - os.Exit(0) - } - _, v2rayAListeningPort, err := net.SplitHostPort(config.Address) - if err != nil { - log.Fatal("checkEnvironment: %v", err) - } - if occupied, sockets, err := ports.IsPortOccupied([]string{v2rayAListeningPort + ":tcp"}); occupied { - if err != nil { - log.Fatal("netstat: %v", err) - } - for _, socket := range sockets { - process, err := socket.Process() - if err == nil { - log.Fatal("Port %v is occupied by %v/%v", v2rayAListeningPort, process.Name, process.PID) - } - } - } -} - -func checkTProxySupportability() { - if conf.GetEnvironmentConfig().Lite { - return - } - // check if tproxy can be enabled - if err := service2.CheckAndProbeTProxy(); err != nil { - log.Info("Cannot load TPROXY module: %v", err) - } -} - -func initDBValue() { - log.Info("init DB") - err := configure.SetConfigure(configure.New()) - if err != nil { - log.Fatal("initDBValue: %v", err) - } -} - -func initConfigure() { - // initialize configuration - jsonIteratorExtra.RegisterFuzzyDecoders() - - // Track whether we performed a BoltDB→SQLite migration in this session. - // If so, we must skip the v4 migration and initDBValue() below, because - // the data has already been migrated into SQLite by MigrateFromBoltDB(). - migratedFromBoltDB := false - - // Try to initialize SQLite database. - // If an old BoltDB database (bolt.db) exists, Open() returns ErrNeedMigration, - // and we must run the migration first. - err := db.Open() - if errors.Is(err, db.ErrNeedMigration) { - log.Warn("Detected legacy BoltDB database, migrating to SQLite...") - if err := db.MigrateFromBoltDB(); err != nil { - log.Fatal("Database migration failed: %v", err) - } - migratedFromBoltDB = true - // Migration succeeded (MigrateFromBoltDB already logged the completion); - // now initialize SQLite normally. - if err := db.Open(); err != nil { - // If SQLite initialization fails after migration, restore the backup - // so the migration can be retried on next startup. - confPath := conf.GetEnvironmentConfig().Config - backupPath := filepath.Join(confPath, "bolt.db.bak") - if _, e := os.Stat(backupPath); e == nil { - if renameErr := os.Rename(backupPath, filepath.Join(confPath, "bolt.db")); renameErr == nil { - log.Warn("Restored bolt.db from bolt.db.bak due to SQLite initialization failure") - } - } - log.Fatal("Failed to initialize SQLite after migration: %v", err) - } - } else if err != nil { - log.Fatal("Failed to initialize database: %v", err) - } - - //db - dbPath := filepath.Join(conf.GetEnvironmentConfig().Config, "bolt.db") - if _, e := os.Lstat(dbPath); os.IsNotExist(e) { - // If we just migrated from BoltDB to SQLite, the data is already in - // SQLite. Do NOT run initDBValue() or v4 migration, as that would - // overwrite or clear the freshly migrated data. - if !migratedFromBoltDB { - // db.IsNewDB is true only when v2raya.db was just created by Open() - // (i.e., it did not exist before). In that case, we need to initialize - // the default configuration values. - // If db.IsNewDB is false, v2raya.db already existed (from a previous - // migration or a previous startup), so we skip initialization. - if db.IsNewDB { - // On Windows, v2rayA v4 was never available, so there is no v4 - // data to migrate. Calling any v4 library function here would - // trigger the v4 library to initialize with its Linux-default - // config path (/etc/v2raya), which on Windows resolves to - // \etc\v2raya on the current drive root and causes the library - // to create that directory and a boltv4.db file there. - // Skip the v4 migration check entirely on Windows. - if runtime.GOOS != "windows" && !configurev4.IsConfigureNotExists() { - // There is different format in server and subscription. - // So we keep other content and reimport servers and subscriptions. - log.Warn("Migrating from v4 to main") - if err := copyfile.CopyFileContent(filepath.Join( - confv4.GetEnvironmentConfig().Config, - "boltv4.db", - ), filepath.Join( - conf.GetEnvironmentConfig().Config, - "bolt.db", - )); err != nil { - log.Fatal("Failed to copy boltv4.db to bolt.db: %v", err) - } - - // clear connects of outbounds - for _, out := range configure.GetOutbounds() { - _ = configure.ClearConnects(out) - } - var indexes []int - for i := 0; i < configurev4.GetLenServers(); i++ { - indexes = append(indexes, i) - } - _ = configure.RemoveServers(indexes) - - indexes = nil - for i := 0; i < configurev4.GetLenSubscriptions(); i++ { - indexes = append(indexes, i) - } - _ = configure.RemoveSubscriptions(indexes) - - // migrate servers and subscriptions - t := touchv4.GenerateTouch() - subs := configurev4.GetSubscriptionsV2() - for _, sub := range subs { - log.Info("Importing subscription: %v", sub.Address) - if e := service.Import(sub.Address, nil); e != nil { - log.Warn("Failed to migrate subscription: %v", sub.Address) - } - } - for iSvr := range t.Servers { - if addr, e := servicev4.GetSharingAddress(&configurev4.Which{ - TYPE: configurev4.ServerType, - ID: iSvr + 1, - }); e == nil { - if e := service.Import(addr, nil); e != nil { - log.Warn("Failed to migrate server: %v", addr) - } - } - } - - log.Warn("Migration is done") - } else { - initDBValue() - } - } - } - - // ensure the default "proxy" outbound group exists - if err := configure.InitDefaultOutbound(); err != nil { - log.Warn("initDefaultOutbound: %v", err) - } - } - - if len(configure.GetTproxyWhiteIpGroups().CountryCodes) == 0 { - configure.SetTproxyWhiteIpGroups([]string{"PRIVATE"}, []string{}) - } - - // check if config.json exists - if _, err := os.Stat(asset.GetV2rayConfigPath()); err != nil { - // if not exists, create one. This mostly happens when mounting a volume in docker mode and it covers /etc/v2ray. - t := v2ray.Template{} - _ = v2ray.WriteV2rayConfig(t.ToConfigBytes()) - } - - // first determine if v2ray exists - if _, err := where.GetV2rayBinPath(); err == nil { - // check if geoip, geosite exist - if !asset.DoesV2rayAssetExist("geoip.dat") || !asset.DoesV2rayAssetExist("geosite.dat") { - log.Alert("downloading missing geoip.dat and geosite.dat") - var l net.Listener - if l, err = net.Listen("tcp", conf.GetEnvironmentConfig().Address); err != nil { - log.Fatal("net.Listen: %v", err) - } - e := gin.New() - e.GET("/", func(c *gin.Context) { - c.Header("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate") - c.Header("Pragma", "no-cache") - c.Header("Expires", "0") - c.String(200, "Downloading missing geoip.dat and geosite.dat; refresh the page later.") - }) - go e.RunListener(l) - if !asset.DoesV2rayAssetExist("geoip.dat") { - err := dat.UpdateLocalGeoIP() - if err != nil { - log.Fatal("UpdateLocalGeoIP: %v", err) - } - } - if !asset.DoesV2rayAssetExist("geosite.dat") { - err = dat.UpdateLocalGeoSite() - if err != nil { - log.Fatal("UpdateLocalGeoSite: %v", err) - } - } - if l != nil { - l.Close() - } - log.Alert("geoip.dat and geosite.dat are ready") - } - } -} - func hello() { v2rayPath, _ := where.GetV2rayBinPath() log.Alert("V2Ray binary is %v", v2rayPath) @@ -290,154 +24,3 @@ func hello() { log.Alert("Version: %v", conf.Version) log.Alert("Starting...") } - -func updateSubscriptions() { - subs := configure.GetSubscriptions() - lenSubs := len(subs) - control := make(chan struct{}, 2) // concurrency limit: update 2 subscriptions at a time - // Disconnect from subscriptions before auto-selecting servers from them - // to limit the number of connected servers and avoid hitting the limit - shouldDisconnect := true - err := service.AutoSelectServersFromSubscriptions(shouldDisconnect) - if err != nil { - log.Error("[AutoSelect] Failed to disconnect servers from subscriptions -- err: %v", err) - } - wg := new(sync.WaitGroup) - for i := 0; i < lenSubs; i++ { - wg.Add(1) - go func(i int) { - control <- struct{}{} - err := service.UpdateSubscription(i, false) - if err != nil { - log.Info("[AutoUpdate] Subscriptions: Failed to update subscription -- ID: %d, err: %v", i, err) - } else { - log.Info("[AutoUpdate] Subscriptions: Complete updating subscription -- ID: %d, Address: %s", i, subs[i].Address) - } - wg.Done() - <-control - }(i) - } - wg.Wait() - shouldDisconnect = false - err2 := service.AutoSelectServersFromSubscriptions(shouldDisconnect) - if err2 != nil { - log.Error("[AutoSelect] Failed to auto-select servers from subscriptions -- err: %v", err2) - } - -} - -func initUpdatingTicker() { - conf.TickerUpdateGFWList = time.NewTicker(24 * time.Hour * 365 * 100) - conf.TickerUpdateSubscription = time.NewTicker(24 * time.Hour * 365 * 100) - go func() { - for range conf.TickerUpdateGFWList.C { - _, err := dat.CheckAndUpdateGFWList("") - if err != nil { - log.Info("[AutoUpdate] GFWList: %v", err) - } - } - }() - go func() { - for range conf.TickerUpdateSubscription.C { - updateSubscriptions() - } - }() -} - -func checkUpdate() { - setting := service.GetSetting() - - // initialize ticker - initUpdatingTicker() - - // check for PAC file updates - if setting.GFWListAutoUpdateMode == configure.AutoUpdate || - setting.GFWListAutoUpdateMode == configure.AutoUpdateAtIntervals || - setting.Transparent == configure.TransparentGfwlist { - if setting.GFWListAutoUpdateMode == configure.AutoUpdateAtIntervals { - conf.TickerUpdateGFWList.Reset(time.Duration(setting.GFWListAutoUpdateIntervalHour) * time.Hour) - } - switch setting.RulePortMode { - case configure.GfwlistMode: - go func() { - /* Update LoyalsoldierSite.dat */ - localGFWListVersion, err := dat.CheckAndUpdateGFWList("") - if err != nil { - log.Warn("Failed to update PAC file: %v", err.Error()) - return - } - log.Info("Complete updating PAC file. Localtime: %v", localGFWListVersion) - }() - case configure.CustomMode: - // obsolete - } - } - - // check for subscription updates - if setting.SubscriptionAutoUpdateMode == configure.AutoUpdate || - setting.SubscriptionAutoUpdateMode == configure.AutoUpdateAtIntervals { - - if setting.SubscriptionAutoUpdateMode == configure.AutoUpdateAtIntervals { - conf.TickerUpdateSubscription.Reset(time.Duration(setting.SubscriptionAutoUpdateIntervalHour) * time.Hour) - } - go updateSubscriptions() - } - // check for server updates - go func() { - f := func() { - if foundNew, remote, err := service.CheckUpdate(); err == nil { - conf.FoundNew = foundNew - conf.RemoteVersion = remote - } - } - f() - c := time.Tick(7 * 24 * time.Hour) - for range c { - f() - } - }() -} - -func run() (err error) { - // check if v2ray should be started - if configure.GetRunning() { - //configure the ip forward - setting := service.GetSetting() - if setting.IpForward != ipforward.IsIpForwardOn() { - e := ipforward.WriteIpForward(setting.IpForward) - if e != nil { - log.Warn("Connect: %v", e) - } - } - // Start. - err := v2ray.UpdateV2RayConfig() - if err != nil { - log.Error("failed to start v2ray-core: %v", err) - } - } else { - log.Info("the core was not running the last time v2rayA exited") - } - //w := configure.GetConnectedServers() - //log.Println(err, ", which:", w) - //_ = configure.ClearConnected() - errch := make(chan error) - // start server - go func() { - errch <- router.Run() - }() - // listen for signals to handle transparent proxy shutdown - go func() { - sigs := make(chan os.Signal, 1) - signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGKILL, syscall.SIGILL) - <-sigs - errch <- nil - }() - if err = <-errch; err != nil { - log.Fatal("run: %v", err) - } - fmt.Println("Quitting...") - v2ray.ProcessManager.CheckAndStopTransparentProxy(nil) - v2ray.ProcessManager.Stop(false) - _ = db.Close() - return nil -} diff --git a/service/pre_database.go b/service/pre_database.go new file mode 100644 index 00000000..074159f9 --- /dev/null +++ b/service/pre_database.go @@ -0,0 +1,203 @@ +package main + +import ( + "errors" + "net" + "os" + "path/filepath" + "runtime" + + "github.com/gin-gonic/gin" + jsonIteratorExtra "github.com/json-iterator/go/extra" + "github.com/v2rayA/v2rayA/conf" + "github.com/v2rayA/v2rayA/db" + "github.com/v2rayA/v2rayA/db/configure" + "github.com/v2rayA/v2rayA/kernel/v2ray" + "github.com/v2rayA/v2rayA/kernel/v2ray/asset" + "github.com/v2rayA/v2rayA/kernel/v2ray/asset/dat" + "github.com/v2rayA/v2rayA/kernel/v2ray/where" + "github.com/v2rayA/v2rayA/pkg/util/copyfile" + "github.com/v2rayA/v2rayA/pkg/util/log" + "github.com/v2rayA/v2rayA/server/service" + + confv4 "github.com/v2rayA/v2rayA-lib4/conf" + touchv4 "github.com/v2rayA/v2rayA-lib4/core/touch" + configurev4 "github.com/v2rayA/v2rayA-lib4/db/configure" + servicev4 "github.com/v2rayA/v2rayA-lib4/server/service" +) + +func initDBValue() { + log.Info("init DB") + err := configure.SetConfigure(configure.New()) + if err != nil { + log.Fatal("initDBValue: %v", err) + } +} + +func initConfigure() { + // initialize configuration + jsonIteratorExtra.RegisterFuzzyDecoders() + + // Track whether we performed a BoltDB→SQLite migration in this session. + // If so, we must skip the v4 migration and initDBValue() below, because + // the data has already been migrated into SQLite by MigrateFromBoltDB(). + migratedFromBoltDB := false + + // Try to initialize SQLite database. + // If an old BoltDB database (bolt.db) exists, Open() returns ErrNeedMigration, + // and we must run the migration first. + err := db.Open() + if errors.Is(err, db.ErrNeedMigration) { + log.Warn("Detected legacy BoltDB database, migrating to SQLite...") + if err := db.MigrateFromBoltDB(); err != nil { + log.Fatal("Database migration failed: %v", err) + } + migratedFromBoltDB = true + // Migration succeeded (MigrateFromBoltDB already logged the completion); + // now initialize SQLite normally. + if err := db.Open(); err != nil { + // If SQLite initialization fails after migration, restore the backup + // so the migration can be retried on next startup. + confPath := conf.GetEnvironmentConfig().Config + backupPath := filepath.Join(confPath, "bolt.db.bak") + if _, e := os.Stat(backupPath); e == nil { + if renameErr := os.Rename(backupPath, filepath.Join(confPath, "bolt.db")); renameErr == nil { + log.Warn("Restored bolt.db from bolt.db.bak due to SQLite initialization failure") + } + } + log.Fatal("Failed to initialize SQLite after migration: %v", err) + } + } else if err != nil { + log.Fatal("Failed to initialize database: %v", err) + } + + //db + dbPath := filepath.Join(conf.GetEnvironmentConfig().Config, "bolt.db") + if _, e := os.Lstat(dbPath); os.IsNotExist(e) { + // If we just migrated from BoltDB to SQLite, the data is already in + // SQLite. Do NOT run initDBValue() or v4 migration, as that would + // overwrite or clear the freshly migrated data. + if !migratedFromBoltDB { + // db.IsNewDB is true only when v2raya.db was just created by Open() + // (i.e., it did not exist before). In that case, we need to initialize + // the default configuration values. + // If db.IsNewDB is false, v2raya.db already existed (from a previous + // migration or a previous startup), so we skip initialization. + if db.IsNewDB { + // On Windows, v2rayA v4 was never available, so there is no v4 + // data to migrate. Calling any v4 library function here would + // trigger the v4 library to initialize with its Linux-default + // config path (/etc/v2raya), which on Windows resolves to + // \etc\v2raya on the current drive root and causes the library + // to create that directory and a boltv4.db file there. + // Skip the v4 migration check entirely on Windows. + if runtime.GOOS != "windows" && !configurev4.IsConfigureNotExists() { + // There is different format in server and subscription. + // So we keep other content and reimport servers and subscriptions. + log.Warn("Migrating from v4 to main") + if err := copyfile.CopyFileContent(filepath.Join( + confv4.GetEnvironmentConfig().Config, + "boltv4.db", + ), filepath.Join( + conf.GetEnvironmentConfig().Config, + "bolt.db", + )); err != nil { + log.Fatal("Failed to copy boltv4.db to bolt.db: %v", err) + } + + // clear connects of outbounds + for _, out := range configure.GetOutbounds() { + _ = configure.ClearConnects(out) + } + var indexes []int + for i := 0; i < configurev4.GetLenServers(); i++ { + indexes = append(indexes, i) + } + _ = configure.RemoveServers(indexes) + + indexes = nil + for i := 0; i < configurev4.GetLenSubscriptions(); i++ { + indexes = append(indexes, i) + } + _ = configure.RemoveSubscriptions(indexes) + + // migrate servers and subscriptions + t := touchv4.GenerateTouch() + subs := configurev4.GetSubscriptionsV2() + for _, sub := range subs { + log.Info("Importing subscription: %v", sub.Address) + if e := service.Import(sub.Address, nil); e != nil { + log.Warn("Failed to migrate subscription: %v", sub.Address) + } + } + for iSvr := range t.Servers { + if addr, e := servicev4.GetSharingAddress(&configurev4.Which{ + TYPE: configurev4.ServerType, + ID: iSvr + 1, + }); e == nil { + if e := service.Import(addr, nil); e != nil { + log.Warn("Failed to migrate server: %v", addr) + } + } + } + + log.Warn("Migration is done") + } else { + initDBValue() + } + } + } + + // ensure the default "proxy" outbound group exists + if err := configure.InitDefaultOutbound(); err != nil { + log.Warn("initDefaultOutbound: %v", err) + } + } + + if len(configure.GetTproxyWhiteIpGroups().CountryCodes) == 0 { + configure.SetTproxyWhiteIpGroups([]string{"PRIVATE"}, []string{}) + } + + // check if config.json exists + if _, err := os.Stat(asset.GetV2rayConfigPath()); err != nil { + // if not exists, create one. This mostly happens when mounting a volume in docker mode and it covers /etc/v2ray. + t := v2ray.Template{} + _ = v2ray.WriteV2rayConfig(t.ToConfigBytes()) + } + + // first determine if v2ray exists + if _, err := where.GetV2rayBinPath(); err == nil { + // check if geoip, geosite exist + if !asset.DoesV2rayAssetExist("geoip.dat") || !asset.DoesV2rayAssetExist("geosite.dat") { + log.Alert("downloading missing geoip.dat and geosite.dat") + var l net.Listener + if l, err = net.Listen("tcp", conf.GetEnvironmentConfig().Address); err != nil { + log.Fatal("net.Listen: %v", err) + } + e := gin.New() + e.GET("/", func(c *gin.Context) { + c.Header("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate") + c.Header("Pragma", "no-cache") + c.Header("Expires", "0") + c.String(200, "Downloading missing geoip.dat and geosite.dat; refresh the page later.") + }) + go e.RunListener(l) + if !asset.DoesV2rayAssetExist("geoip.dat") { + err := dat.UpdateLocalGeoIP() + if err != nil { + log.Fatal("UpdateLocalGeoIP: %v", err) + } + } + if !asset.DoesV2rayAssetExist("geosite.dat") { + err = dat.UpdateLocalGeoSite() + if err != nil { + log.Fatal("UpdateLocalGeoSite: %v", err) + } + } + if l != nil { + l.Close() + } + log.Alert("geoip.dat and geosite.dat are ready") + } + } +} diff --git a/service/pre_environment.go b/service/pre_environment.go new file mode 100644 index 00000000..574835e5 --- /dev/null +++ b/service/pre_environment.go @@ -0,0 +1,77 @@ +package main + +import ( + "fmt" + "net" + "os" + "runtime" + + "github.com/v2rayA/v2rayA/common/netTools/ports" + "github.com/v2rayA/v2rayA/conf" + "github.com/v2rayA/v2rayA/db" + "github.com/v2rayA/v2rayA/db/configure" + service2 "github.com/v2rayA/v2rayA/kernel/v2ray/service" + "github.com/v2rayA/v2rayA/pkg/util/log" + "github.com/v2rayA/v2rayA/pkg/util/privilege" +) + +func checkEnvironment() { + config := conf.GetEnvironmentConfig() + if len(config.PrintReport) > 0 { + db.SetReadOnly() + config.Report() + os.Exit(0) + } + if !config.PassCheckRoot { + switch runtime.GOOS { + case "linux": + if !privilege.IsRootOrAdmin() && !config.Lite { + log.Fatal("Please execute this program with sudo or as a root user for the best experience.\n" + + "If you are sure you are root user, use the --passcheckroot parameter to skip the check.\n" + + "If you don't want to run as root or you are a non-linux user, use --lite please.\n" + + "For example:\n" + + "$ v2raya --lite", + ) + } + case "windows": + if !privilege.IsRootOrAdmin() && !config.Lite { + log.Fatal("Please run v2rayA as Administrator (or SYSTEM) with elevation, or start with --lite to skip privilege checks.") + } + } + } + if config.ResetPassword { + fmt.Println("Config directory:", config.Config) + fmt.Println("Resetting password...\nIf no response for a long time, please stop other v2rayA instances and try again.") + err := configure.ResetAccounts() + if err != nil { + log.Fatal("checkEnvironment: %v", err) + } + fmt.Println("Succeed. It will work after you restart v2rayA.") + os.Exit(0) + } + _, v2rayAListeningPort, err := net.SplitHostPort(config.Address) + if err != nil { + log.Fatal("checkEnvironment: %v", err) + } + if occupied, sockets, err := ports.IsPortOccupied([]string{v2rayAListeningPort + ":tcp"}); occupied { + if err != nil { + log.Fatal("netstat: %v", err) + } + for _, socket := range sockets { + process, err := socket.Process() + if err == nil { + log.Fatal("Port %v is occupied by %v/%v", v2rayAListeningPort, process.Name, process.PID) + } + } + } +} + +func checkTProxySupportability() { + if conf.GetEnvironmentConfig().Lite { + return + } + // check if tproxy can be enabled + if err := service2.CheckAndProbeTProxy(); err != nil { + log.Info("Cannot load TPROXY module: %v", err) + } +} diff --git a/service/pre_run.go b/service/pre_run.go new file mode 100644 index 00000000..984e62dd --- /dev/null +++ b/service/pre_run.go @@ -0,0 +1,60 @@ +package main + +import ( + "fmt" + "os" + "os/signal" + "syscall" + + "github.com/v2rayA/v2rayA/db" + "github.com/v2rayA/v2rayA/db/configure" + "github.com/v2rayA/v2rayA/kernel/ipforward" + "github.com/v2rayA/v2rayA/kernel/v2ray" + "github.com/v2rayA/v2rayA/pkg/util/log" + "github.com/v2rayA/v2rayA/server/router" + "github.com/v2rayA/v2rayA/server/service" +) + +func run() (err error) { + // check if v2ray should be started + if configure.GetRunning() { + //configure the ip forward + setting := service.GetSetting() + if setting.IpForward != ipforward.IsIpForwardOn() { + e := ipforward.WriteIpForward(setting.IpForward) + if e != nil { + log.Warn("Connect: %v", e) + } + } + // Start. + err := v2ray.UpdateV2RayConfig() + if err != nil { + log.Error("failed to start v2ray-core: %v", err) + } + } else { + log.Info("the core was not running the last time v2rayA exited") + } + //w := configure.GetConnectedServers() + //log.Println(err, ", which:", w) + //_ = configure.ClearConnected() + errch := make(chan error) + // start server + go func() { + errch <- router.Run() + }() + // listen for signals to handle transparent proxy shutdown + go func() { + sigs := make(chan os.Signal, 1) + signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGKILL, syscall.SIGILL) + <-sigs + errch <- nil + }() + if err = <-errch; err != nil { + log.Fatal("run: %v", err) + } + fmt.Println("Quitting...") + v2ray.ProcessManager.CheckAndStopTransparentProxy(nil) + v2ray.ProcessManager.Stop(false) + _ = db.Close() + return nil +} diff --git a/service/pre_update.go b/service/pre_update.go new file mode 100644 index 00000000..48a34c88 --- /dev/null +++ b/service/pre_update.go @@ -0,0 +1,119 @@ +package main + +import ( + "sync" + "time" + + "github.com/v2rayA/v2rayA/conf" + "github.com/v2rayA/v2rayA/db/configure" + "github.com/v2rayA/v2rayA/kernel/v2ray/asset/dat" + "github.com/v2rayA/v2rayA/pkg/util/log" + "github.com/v2rayA/v2rayA/server/service" +) + +func updateSubscriptions() { + subs := configure.GetSubscriptions() + lenSubs := len(subs) + control := make(chan struct{}, 2) // concurrency limit: update 2 subscriptions at a time + // Disconnect from subscriptions before auto-selecting servers from them + // to limit the number of connected servers and avoid hitting the limit + shouldDisconnect := true + err := service.AutoSelectServersFromSubscriptions(shouldDisconnect) + if err != nil { + log.Error("[AutoSelect] Failed to disconnect servers from subscriptions -- err: %v", err) + } + wg := new(sync.WaitGroup) + for i := 0; i < lenSubs; i++ { + wg.Add(1) + go func(i int) { + control <- struct{}{} + err := service.UpdateSubscription(i, false) + if err != nil { + log.Info("[AutoUpdate] Subscriptions: Failed to update subscription -- ID: %d, err: %v", i, err) + } else { + log.Info("[AutoUpdate] Subscriptions: Complete updating subscription -- ID: %d, Address: %s", i, subs[i].Address) + } + wg.Done() + <-control + }(i) + } + wg.Wait() + shouldDisconnect = false + err2 := service.AutoSelectServersFromSubscriptions(shouldDisconnect) + if err2 != nil { + log.Error("[AutoSelect] Failed to auto-select servers from subscriptions -- err: %v", err2) + } + +} + +func initUpdatingTicker() { + conf.TickerUpdateGFWList = time.NewTicker(24 * time.Hour * 365 * 100) + conf.TickerUpdateSubscription = time.NewTicker(24 * time.Hour * 365 * 100) + go func() { + for range conf.TickerUpdateGFWList.C { + _, err := dat.CheckAndUpdateGFWList("") + if err != nil { + log.Info("[AutoUpdate] GFWList: %v", err) + } + } + }() + go func() { + for range conf.TickerUpdateSubscription.C { + updateSubscriptions() + } + }() +} + +func checkUpdate() { + setting := service.GetSetting() + + // initialize ticker + initUpdatingTicker() + + // check for PAC file updates + if setting.GFWListAutoUpdateMode == configure.AutoUpdate || + setting.GFWListAutoUpdateMode == configure.AutoUpdateAtIntervals || + setting.Transparent == configure.TransparentGfwlist { + if setting.GFWListAutoUpdateMode == configure.AutoUpdateAtIntervals { + conf.TickerUpdateGFWList.Reset(time.Duration(setting.GFWListAutoUpdateIntervalHour) * time.Hour) + } + switch setting.RulePortMode { + case configure.GfwlistMode: + go func() { + /* Update LoyalsoldierSite.dat */ + localGFWListVersion, err := dat.CheckAndUpdateGFWList("") + if err != nil { + log.Warn("Failed to update PAC file: %v", err.Error()) + return + } + log.Info("Complete updating PAC file. Localtime: %v", localGFWListVersion) + }() + case configure.CustomMode: + // obsolete + } + } + + // check for subscription updates + if setting.SubscriptionAutoUpdateMode == configure.AutoUpdate || + setting.SubscriptionAutoUpdateMode == configure.AutoUpdateAtIntervals { + + if setting.SubscriptionAutoUpdateMode == configure.AutoUpdateAtIntervals { + conf.TickerUpdateSubscription.Reset(time.Duration(setting.SubscriptionAutoUpdateIntervalHour) * time.Hour) + } + go updateSubscriptions() + } + // check for server updates + go func() { + f := func() { + if foundNew, remote, err := service.CheckUpdate(); err == nil { + conf.FoundNew = foundNew + conf.RemoteVersion = remote + } + } + f() + c := time.Tick(7 * 24 * time.Hour) + for range c { + f() + } + }() +} diff --git a/service/server/controller/dnslist.go b/service/server/controller/dnslist.go index 9b61794b..9b0cb164 100644 --- a/service/server/controller/dnslist.go +++ b/service/server/controller/dnslist.go @@ -6,8 +6,18 @@ import ( "github.com/gin-gonic/gin" "github.com/v2rayA/v2rayA/common" "github.com/v2rayA/v2rayA/db/configure" + "github.com/v2rayA/v2rayA/server/service" ) +// DnsConfigResponse 是新 DNS 配置的 API 响应结构。 +type DnsConfigResponse struct { + UseNewModule bool `json:"useNewModule"` + Listener string `json:"listener"` + Rules []configure.DnsRule `json:"rules"` +} + +// PutDnsRules 处理 PUT /api/dns 请求,保存 DNS 规则配置。 +// 支持新格式和旧格式请求,向后兼容。 func PutDnsRules(ctx *gin.Context) { var rules []configure.DnsRule if err := ctx.ShouldBindJSON(&rules); err != nil { @@ -15,24 +25,62 @@ func PutDnsRules(ctx *gin.Context) { return } for i, rule := range rules { - if rule.Server == "" { - common.ResponseError(ctx, logError(fmt.Errorf("rule[%d]: server cannot be empty", i))) + // 检查上游地址:优先使用 Upstream 字段,回退到 Server + upstream := rule.Upstream + if upstream == "" { + upstream = rule.Server + } + if upstream == "" { + common.ResponseError(ctx, logError(fmt.Errorf("rule[%d]: server/upstream cannot be empty", i))) return } + // 同步新旧字段:确保 Server 和 Upstream 至少有一个有值 + if rule.Server == "" && rule.Upstream != "" { + rule.Server = rule.Upstream + } + if rule.Upstream == "" && rule.Server != "" { + rule.Upstream = rule.Server + } + // 同步 Domain 和 Domains + if rule.Domains == "" && rule.Domain != "" { + rule.Domains = rule.Domain + } + if rule.Domain == "" && rule.Domains != "" { + rule.Domain = rule.Domains + } if rule.Outbound == "" { - common.ResponseError(ctx, logError(fmt.Errorf("rule[%d]: outbound cannot be empty", i))) - return + rule.Outbound = "direct" } + rules[i] = rule } - if err := configure.SetDnsRules(rules); err != nil { + + // 执行迁移以确保新字段有默认值 + migrated := configure.MigrateDnsRules(rules) + + if err := configure.SetDnsRules(migrated); err != nil { common.ResponseError(ctx, logError(err)) return } common.ResponseSuccess(ctx, nil) } +// GetDnsRules 处理 GET /api/dns 请求,返回 DNS 规则配置和状态。 +// 返回新格式配置,同时保持向后兼容。 func GetDnsRules(ctx *gin.Context) { - common.ResponseSuccess(ctx, gin.H{ - "rules": configure.GetDnsRulesNotNil(), + rules := configure.GetDnsRulesNotNil() + migrated := configure.MigrateDnsRules(rules) + + // 获取当前设置以返回监听地址等信息 + setting := service.GetSetting() + + listener := "" + if setting != nil { + listener = setting.DnsListenAddr + } + + common.ResponseSuccess(ctx, DnsConfigResponse{ + UseNewModule: true, + Listener: listener, + Rules: migrated, }) } diff --git a/service/server/controller/gfwlist.go b/service/server/controller/gfwlist.go index b3b38992..5d7a7781 100644 --- a/service/server/controller/gfwlist.go +++ b/service/server/controller/gfwlist.go @@ -3,7 +3,7 @@ package controller import ( "github.com/gin-gonic/gin" "github.com/v2rayA/v2rayA/common" - "github.com/v2rayA/v2rayA/core/v2ray/asset/dat" + "github.com/v2rayA/v2rayA/kernel/v2ray/asset/dat" ) func PutGFWList(ctx *gin.Context) { diff --git a/service/server/controller/outbound.go b/service/server/controller/outbound.go index 37440cb4..20ecb359 100644 --- a/service/server/controller/outbound.go +++ b/service/server/controller/outbound.go @@ -6,7 +6,7 @@ import ( "github.com/gin-gonic/gin" "github.com/v2rayA/v2rayA/common" - "github.com/v2rayA/v2rayA/core/v2ray" + "github.com/v2rayA/v2rayA/kernel/v2ray" "github.com/v2rayA/v2rayA/db/configure" "github.com/v2rayA/v2rayA/server/service" ) diff --git a/service/server/controller/ports.go b/service/server/controller/ports.go index c96640e8..ed395c46 100644 --- a/service/server/controller/ports.go +++ b/service/server/controller/ports.go @@ -4,8 +4,8 @@ import ( "fmt" "github.com/gin-gonic/gin" "github.com/v2rayA/v2rayA/common" - "github.com/v2rayA/v2rayA/core/serverObj" - "github.com/v2rayA/v2rayA/core/v2ray" + "github.com/v2rayA/v2rayA/kernel/serverObj" + "github.com/v2rayA/v2rayA/kernel/v2ray" "github.com/v2rayA/v2rayA/db/configure" "github.com/v2rayA/v2rayA/server/service" "net" diff --git a/service/server/controller/setting.go b/service/server/controller/setting.go index bc89c279..2dd7034e 100644 --- a/service/server/controller/setting.go +++ b/service/server/controller/setting.go @@ -3,7 +3,7 @@ package controller import ( "github.com/gin-gonic/gin" "github.com/v2rayA/v2rayA/common" - "github.com/v2rayA/v2rayA/core/v2ray/asset" + "github.com/v2rayA/v2rayA/kernel/v2ray/asset" "github.com/v2rayA/v2rayA/db/configure" "github.com/v2rayA/v2rayA/server/service" ) @@ -46,6 +46,8 @@ func PutSetting(ctx *gin.Context) { common.ResponseError(ctx, logError("mux should be between 1 and 1024")) return } + // 对 DNS 配置字段执行迁移,确保旧格式请求中的缺失字段被填充默认值 + configure.MigrateSetting(&data) err = service.UpdateSetting(&data) if err != nil { common.ResponseError(ctx, logError(err)) diff --git a/service/server/controller/subscription.go b/service/server/controller/subscription.go index 60a5fd4d..8e29699f 100644 --- a/service/server/controller/subscription.go +++ b/service/server/controller/subscription.go @@ -3,7 +3,7 @@ package controller import ( "github.com/gin-gonic/gin" "github.com/v2rayA/v2rayA/common" - "github.com/v2rayA/v2rayA/core/touch" + "github.com/v2rayA/v2rayA/kernel/touch" "github.com/v2rayA/v2rayA/db/configure" "github.com/v2rayA/v2rayA/server/service" ) diff --git a/service/server/controller/touch.go b/service/server/controller/touch.go index 8851877c..f1eaf343 100644 --- a/service/server/controller/touch.go +++ b/service/server/controller/touch.go @@ -3,8 +3,8 @@ package controller import ( "github.com/gin-gonic/gin" "github.com/v2rayA/v2rayA/common" - "github.com/v2rayA/v2rayA/core/touch" - "github.com/v2rayA/v2rayA/core/v2ray" + "github.com/v2rayA/v2rayA/kernel/touch" + "github.com/v2rayA/v2rayA/kernel/v2ray" "github.com/v2rayA/v2rayA/db/configure" "github.com/v2rayA/v2rayA/server/service" ) diff --git a/service/server/controller/version.go b/service/server/controller/version.go index 76dc5b3a..219c7b77 100644 --- a/service/server/controller/version.go +++ b/service/server/controller/version.go @@ -8,10 +8,10 @@ import ( "github.com/gin-gonic/gin" "github.com/v2rayA/v2rayA/common" "github.com/v2rayA/v2rayA/conf" - v2ray "github.com/v2rayA/v2rayA/core/v2ray" - "github.com/v2rayA/v2rayA/core/v2ray/asset/dat" - "github.com/v2rayA/v2rayA/core/v2ray/service" - "github.com/v2rayA/v2rayA/core/v2ray/where" + v2ray "github.com/v2rayA/v2rayA/kernel/v2ray" + "github.com/v2rayA/v2rayA/kernel/v2ray/asset/dat" + "github.com/v2rayA/v2rayA/kernel/v2ray/service" + "github.com/v2rayA/v2rayA/kernel/v2ray/where" "github.com/v2rayA/v2rayA/db/configure" "github.com/v2rayA/v2rayA/pkg/util/privilege" ) diff --git a/service/server/service/connect.go b/service/server/service/connect.go index d09ba96a..8079a904 100644 --- a/service/server/service/connect.go +++ b/service/server/service/connect.go @@ -4,9 +4,9 @@ import ( "errors" "fmt" - "github.com/v2rayA/v2rayA/core/ipforward" - "github.com/v2rayA/v2rayA/core/v2ray" - "github.com/v2rayA/v2rayA/core/v2ray/asset" + "github.com/v2rayA/v2rayA/kernel/ipforward" + "github.com/v2rayA/v2rayA/kernel/v2ray" + "github.com/v2rayA/v2rayA/kernel/v2ray/asset" "github.com/v2rayA/v2rayA/db/configure" "github.com/v2rayA/v2rayA/pkg/util/log" ) diff --git a/service/server/service/import.go b/service/server/service/import.go index b6a03e7d..107faaa7 100644 --- a/service/server/service/import.go +++ b/service/server/service/import.go @@ -12,9 +12,9 @@ import ( "github.com/v2rayA/v2rayA/common" "github.com/v2rayA/v2rayA/common/httpClient" "github.com/v2rayA/v2rayA/common/resolv" - "github.com/v2rayA/v2rayA/core/serverObj" - "github.com/v2rayA/v2rayA/core/touch" - "github.com/v2rayA/v2rayA/core/v2ray" + "github.com/v2rayA/v2rayA/kernel/serverObj" + "github.com/v2rayA/v2rayA/kernel/touch" + "github.com/v2rayA/v2rayA/kernel/v2ray" "github.com/v2rayA/v2rayA/db/configure" ) diff --git a/service/server/service/latency.go b/service/server/service/latency.go index 79897d98..cf0545df 100644 --- a/service/server/service/latency.go +++ b/service/server/service/latency.go @@ -13,9 +13,9 @@ import ( "github.com/v2rayA/v2rayA/common/httpClient" "github.com/v2rayA/v2rayA/common/resolv" - "github.com/v2rayA/v2rayA/core/coreObj" - "github.com/v2rayA/v2rayA/core/serverObj" - "github.com/v2rayA/v2rayA/core/v2ray" + "github.com/v2rayA/v2rayA/kernel/coreObj" + "github.com/v2rayA/v2rayA/kernel/serverObj" + "github.com/v2rayA/v2rayA/kernel/v2ray" "github.com/v2rayA/v2rayA/db/configure" "github.com/v2rayA/v2rayA/pkg/util/log" ) diff --git a/service/server/service/message.go b/service/server/service/message.go index f70b4d76..12ecc4cd 100644 --- a/service/server/service/message.go +++ b/service/server/service/message.go @@ -2,7 +2,7 @@ package service import ( "github.com/gorilla/websocket" - "github.com/v2rayA/v2rayA/core/v2ray" + "github.com/v2rayA/v2rayA/kernel/v2ray" "sync" "time" ) diff --git a/service/server/service/ports.go b/service/server/service/ports.go index 089f6087..853ab2ff 100644 --- a/service/server/service/ports.go +++ b/service/server/service/ports.go @@ -3,7 +3,7 @@ package service import ( "fmt" "github.com/go-leo/slicex" - "github.com/v2rayA/v2rayA/core/v2ray" + "github.com/v2rayA/v2rayA/kernel/v2ray" "github.com/v2rayA/v2rayA/db/configure" "reflect" "strconv" diff --git a/service/server/service/resolve.go b/service/server/service/resolve.go index cdadede8..59b72606 100644 --- a/service/server/service/resolve.go +++ b/service/server/service/resolve.go @@ -2,7 +2,7 @@ package service import ( "fmt" - "github.com/v2rayA/v2rayA/core/serverObj" + "github.com/v2rayA/v2rayA/kernel/serverObj" "net/url" "strings" ) diff --git a/service/server/service/setting.go b/service/server/service/setting.go index fdd98dfc..85cbc0b4 100644 --- a/service/server/service/setting.go +++ b/service/server/service/setting.go @@ -5,9 +5,9 @@ import ( "time" "github.com/v2rayA/v2rayA/conf" - "github.com/v2rayA/v2rayA/core/ipforward" - "github.com/v2rayA/v2rayA/core/v2ray" - "github.com/v2rayA/v2rayA/core/v2ray/asset" + "github.com/v2rayA/v2rayA/kernel/ipforward" + "github.com/v2rayA/v2rayA/kernel/v2ray" + "github.com/v2rayA/v2rayA/kernel/v2ray/asset" "github.com/v2rayA/v2rayA/db/configure" "github.com/v2rayA/v2rayA/pkg/util/log" ) diff --git a/service/server/service/subscription.go b/service/server/service/subscription.go index cb6dd45a..bd8b5432 100644 --- a/service/server/service/subscription.go +++ b/service/server/service/subscription.go @@ -16,8 +16,8 @@ import ( "github.com/v2rayA/v2rayA/common" "github.com/v2rayA/v2rayA/common/httpClient" "github.com/v2rayA/v2rayA/common/resolv" - "github.com/v2rayA/v2rayA/core/serverObj" - "github.com/v2rayA/v2rayA/core/touch" + "github.com/v2rayA/v2rayA/kernel/serverObj" + "github.com/v2rayA/v2rayA/kernel/touch" "github.com/v2rayA/v2rayA/db/configure" "github.com/v2rayA/v2rayA/pkg/util/log" ) diff --git a/service/service_windows.go b/service/service_windows.go index cdb21f20..f88577a0 100644 --- a/service/service_windows.go +++ b/service/service_windows.go @@ -10,7 +10,7 @@ import ( "runtime/debug" "time" - "github.com/v2rayA/v2rayA/core/v2ray" + "github.com/v2rayA/v2rayA/kernel/v2ray" "github.com/v2rayA/v2rayA/db" "github.com/v2rayA/v2rayA/pkg/util/log" "github.com/v2rayA/v2rayA/server/router"