diff --git a/core/dns/cache.go b/core/dns/cache.go index 98538879..984d0299 100644 --- a/core/dns/cache.go +++ b/core/dns/cache.go @@ -20,16 +20,16 @@ type CacheKey struct { 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 // 预取失败次数 + 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 // 上次预取失败时间 + LastPrefetchFail time.Time // 上次预取失败时间 } // DnsCache DNS 缓存(LRU + TTL 双淘汰) @@ -136,8 +136,9 @@ func (c *DnsCache) Get(key CacheKey) (*DnsResponse, bool) { return nil, false } + now := time.Now() // 检查是否过期 - if time.Now().After(entry.ExpiresAt) { + if now.After(entry.ExpiresAt) { c.removeElement(elem) c.stats.Misses++ c.updateHitRate() @@ -151,15 +152,83 @@ func (c *DnsCache) Get(key CacheKey) (*DnsResponse, bool) { c.stats.Hits++ c.updateHitRate() - // 标记响应来自缓存 - resp := *entry.Response + return copyCachedResponse(entry.Response, now.Sub(entry.StoredAt), c.config.MinTTL), true +} + +func copyCachedResponse(response *DnsResponse, elapsed time.Duration, configuredMinTTL int) *DnsResponse { + resp := *response + if response.RawMsg != nil { + resp.RawMsg = response.RawMsg.Copy() + resp.Answer = resp.RawMsg.Answer + resp.Authority = resp.RawMsg.Ns + resp.Additional = resp.RawMsg.Extra + } else { + resp.Answer = copyRRs(response.Answer) + resp.Authority = copyRRs(response.Authority) + resp.Additional = copyRRs(response.Additional) + } + + minTTL := uint32(DefaultMinTTL) + if configuredMinTTL > 0 { + minTTL = uint32(configuredMinTTL) + } + var elapsedSeconds uint32 + if elapsed > 0 { + elapsedSeconds = uint32(elapsed / time.Second) + } + decreaseRecordTTLs(resp.Answer, elapsedSeconds, minTTL) + decreaseRecordTTLs(resp.Authority, elapsedSeconds, minTTL) + decreaseRecordTTLs(resp.Additional, elapsedSeconds, minTTL) + if len(resp.Answer) > 0 { + resp.TTL = resp.Answer[0].Header().Ttl + for _, rr := range resp.Answer[1:] { + if rr.Header().Ttl < resp.TTL { + resp.TTL = rr.Header().Ttl + } + } + } resp.Cached = true - return &resp, true + return &resp +} + +func copyRRs(records []dns.RR) []dns.RR { + if len(records) == 0 { + return nil + } + copied := make([]dns.RR, len(records)) + for i, rr := range records { + copied[i] = dns.Copy(rr) + } + return copied +} + +func decreaseRecordTTLs(records []dns.RR, elapsed, minTTL uint32) { + for _, rr := range records { + header := rr.Header() + if header.Rrtype == dns.TypeOPT || header.Rrtype == dns.TypeTSIG { + continue + } + if header.Ttl > elapsed { + header.Ttl -= elapsed + } else { + header.Ttl = 0 + } + if header.Ttl < minTTL { + header.Ttl = minTTL + } + } } // Set 设置缓存条目 // 如果键已存在则更新;否则添加新条目。超过最大容量时淘汰最久未使用的条目。 func (c *DnsCache) Set(key CacheKey, resp *DnsResponse, originalTTL uint32) { + if resp != nil && !c.config.NegativeCache { + switch resp.Rcode { + case dns.RcodeNameError, dns.RcodeServerFailure, dns.RcodeRefused: + return + } + } + c.mu.Lock() defer c.mu.Unlock() diff --git a/core/dns/cache_response_test.go b/core/dns/cache_response_test.go new file mode 100644 index 00000000..6781df15 --- /dev/null +++ b/core/dns/cache_response_test.go @@ -0,0 +1,53 @@ +package dns + +import ( + "testing" + "time" + + "github.com/miekg/dns" +) + +func TestCacheHitDecreasesRecordTTLs(t *testing.T) { + config := newTestCacheConfig() + config.MinTTL = 100 + cache := NewDnsCache(config) + key := newTestCacheKey("example.com", TypeA) + response := newTestDNSResponse("example.com", TypeA, dns.RcodeSuccess, 150) + cache.Set(key, response, 150) + + entry := cache.entries[key].Value.(*CacheEntry) + entry.StoredAt = time.Now().Add(-75 * time.Second) + entry.ExpiresAt = time.Now().Add(time.Minute) + + cached, ok := cache.Get(key) + if !ok { + t.Fatal("expected cache hit") + } + if got := cached.Answer[0].Header().Ttl; got != 100 { + t.Errorf("cached answer TTL = %d, want 100", got) + } + if got := cached.RawMsg.Answer[0].Header().Ttl; got != 100 { + t.Errorf("cached raw message TTL = %d, want 100", got) + } + if got := cached.TTL; got != 100 { + t.Errorf("cached response TTL = %d, want 100", got) + } + if got := response.Answer[0].Header().Ttl; got != 150 { + t.Errorf("stored answer TTL = %d, want 150", got) + } +} + +func TestNegativeResponsesAreNotCachedWhenDisabled(t *testing.T) { + for _, rcode := range []int{dns.RcodeNameError, dns.RcodeServerFailure, dns.RcodeRefused} { + config := newTestCacheConfig() + config.NegativeCache = false + cache := NewDnsCache(config) + key := newTestCacheKey("negative.example.com", TypeA) + response := newTestDNSResponse("negative.example.com", TypeA, rcode, 0) + + cache.Set(key, response, 0) + if _, ok := cache.Get(key); ok { + t.Errorf("rcode %d was cached with negative caching disabled", rcode) + } + } +} diff --git a/core/dns/listener.go b/core/dns/listener.go index a369568e..17085d11 100644 --- a/core/dns/listener.go +++ b/core/dns/listener.go @@ -78,37 +78,48 @@ func (l *DnsListener) Start() error { func (l *DnsListener) startPair(addr string) (*serverPair, error) { timeout := time.Duration(l.config.Timeout) * time.Second + udpConn, err := net.ListenPacket("udp", addr) + if err != nil { + return nil, fmt.Errorf("listen udp: %w", err) + } udpSrv := &dns.Server{ Addr: addr, Net: "udp", + PacketConn: udpConn, Handler: dns.HandlerFunc(l.handlePacket), UDPSize: 1452, ReadTimeout: timeout, WriteTimeout: timeout, } + tcpListener, err := net.Listen("tcp", addr) + if err != nil { + _ = udpConn.Close() + return nil, fmt.Errorf("listen tcp: %w", err) + } + tcpSrv := &dns.Server{ + Addr: addr, + Net: "tcp", + Listener: tcpListener, + Handler: dns.HandlerFunc(l.handlePacket), + 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 { + if err := udpSrv.ActivateAndServe(); 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 { + if err := tcpSrv.ActivateAndServe(); err != nil { log.Printf("[dns] TCP listener stopped: %v", err) } }() diff --git a/core/dns/types.go b/core/dns/types.go index 304cc7ff..53ef2cb5 100644 --- a/core/dns/types.go +++ b/core/dns/types.go @@ -5,7 +5,10 @@ package dns import ( + "encoding/json" + "fmt" "net" + "strings" "sync" "time" @@ -28,6 +31,25 @@ const ( TypeSOA QueryType = QueryType(dns.TypeSOA) ) +func (q *QueryType) UnmarshalJSON(data []byte) error { + var name string + if err := json.Unmarshal(data, &name); err == nil { + qtype, ok := dns.StringToType[strings.ToUpper(name)] + if !ok { + return fmt.Errorf("dns: unknown query type %q", name) + } + *q = QueryType(qtype) + return nil + } + + var qtype uint16 + if err := json.Unmarshal(data, &qtype); err != nil { + return fmt.Errorf("dns: invalid query type: %w", err) + } + *q = QueryType(qtype) + return nil +} + // DnsQuery represents a normalized DNS query request. type DnsQuery struct { // Name is the queried domain name (e.g. "www.example.com"). diff --git a/core/dns/types_json_test.go b/core/dns/types_json_test.go new file mode 100644 index 00000000..dd412f0a --- /dev/null +++ b/core/dns/types_json_test.go @@ -0,0 +1,23 @@ +package dns + +import ( + "encoding/json" + "testing" +) + +func TestRuleConfigQueryTypeUnmarshalJSON(t *testing.T) { + var rule RuleConfig + if err := json.Unmarshal([]byte(`{"query_type":["A","AAAA",15]}`), &rule); err != nil { + t.Fatalf("unmarshal rule config: %v", err) + } + + want := []QueryType{TypeA, TypeAAAA, TypeMX} + if len(rule.QueryType) != len(want) { + t.Fatalf("query type count = %d, want %d", len(rule.QueryType), len(want)) + } + for i, qtype := range want { + if rule.QueryType[i] != qtype { + t.Errorf("query type[%d] = %d, want %d", i, rule.QueryType[i], qtype) + } + } +} diff --git a/core/dns/upstream_stub.go b/core/dns/upstream_stub.go index 2e55cbfc..2038a102 100644 --- a/core/dns/upstream_stub.go +++ b/core/dns/upstream_stub.go @@ -3,6 +3,7 @@ package dns import ( "context" "fmt" + "io" "log" "net" "time" @@ -35,6 +36,14 @@ func (m *UpstreamManager) SetDispatcher(d RouteDispatcher) { m.dispatcher = d } +func shouldAttachECS(clientIP net.IP) bool { + return clientIP != nil && + clientIP.IsGlobalUnicast() && + !clientIP.IsPrivate() && + !clientIP.IsLoopback() && + !clientIP.IsLinkLocalUnicast() +} + // 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. @@ -94,7 +103,7 @@ func (m *UpstreamManager) exchangeDirect(upstream *UpstreamInstance, query *DnsQ // checking if one already exists. Calling AddECSSubnet first then SetEdns0 // would create TWO OPT records in the query, causing FORMERR. msg.SetEdns0(4096, true) - if query.ClientIP != nil && query.ClientIP.IsGlobalUnicast() { + if shouldAttachECS(query.ClientIP) { builder := NewResponseBuilder() builder.AddECSSubnet(msg, query.ClientIP) } @@ -238,7 +247,7 @@ func (m *UpstreamManager) exchangeViaProxy(upstream *UpstreamInstance, query *Dn // checking if one already exists. Calling AddECSSubnet first then SetEdns0 // would create TWO OPT records in the query, causing FORMERR. msg.SetEdns0(4096, true) - if query.ClientIP != nil && query.ClientIP.IsGlobalUnicast() { + if shouldAttachECS(query.ClientIP) { builder := NewResponseBuilder() builder.AddECSSubnet(msg, query.ClientIP) } @@ -404,7 +413,7 @@ func (m *UpstreamManager) exchangeViaSocks5(proxyAddr, targetAddr string, msg *d conn.SetReadDeadline(time.Now().Add(5 * time.Second)) // Read the 2-byte length prefix. - if _, err := conn.Read(tcpMsg[:2]); err != nil { + if _, err := io.ReadFull(conn, tcpMsg[:2]); err != nil { return nil, fmt.Errorf("dns read length via socks5: %w", err) } respLen := int(tcpMsg[0])<<8 | int(tcpMsg[1]) @@ -414,13 +423,8 @@ func (m *UpstreamManager) exchangeViaSocks5(proxyAddr, targetAddr string, msg *d // 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 + if _, err := io.ReadFull(conn, respData); err != nil { + return nil, fmt.Errorf("dns read data via socks5: %w", err) } // Unpack the DNS response. @@ -557,7 +561,7 @@ func (m *UpstreamManager) exchangeViaDispatcher(upstream *UpstreamInstance, quer // checking if one already exists. Calling AddECSSubnet first then SetEdns0 // would create TWO OPT records in the query, causing FORMERR. msg.SetEdns0(4096, true) - if query.ClientIP != nil && query.ClientIP.IsGlobalUnicast() { + if shouldAttachECS(query.ClientIP) { builder := NewResponseBuilder() builder.AddECSSubnet(msg, query.ClientIP) } @@ -601,7 +605,7 @@ func (m *UpstreamManager) exchangeViaDispatcher(upstream *UpstreamInstance, quer // Read 2-byte length prefix. conn.SetReadDeadline(time.Now().Add(5 * time.Second)) - if _, err := conn.Read(tcpMsg[:2]); err != nil { + if _, err := io.ReadFull(conn, tcpMsg[:2]); err != nil { return nil, fmt.Errorf("dns read length via dispatcher: %w", err) } respLen := int(tcpMsg[0])<<8 | int(tcpMsg[1]) @@ -611,13 +615,8 @@ func (m *UpstreamManager) exchangeViaDispatcher(upstream *UpstreamInstance, quer // 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 + if _, err := io.ReadFull(conn, respData); err != nil { + return nil, fmt.Errorf("dns read data via dispatcher: %w", err) } rtt := time.Since(start) diff --git a/core/hint/conf/loader.go b/core/hint/conf/loader.go index 25fdfbee..98babe0d 100644 --- a/core/hint/conf/loader.go +++ b/core/hint/conf/loader.go @@ -80,9 +80,10 @@ type extendedJSON struct { // customOutboundJSON is the raw JSON form of an anytls or juicity outbound. type customOutboundJSON struct { - Protocol string `json:"protocol"` - Tag string `json:"tag"` - Settings json.RawMessage `json:"settings"` + Protocol string `json:"protocol"` + Tag string `json:"tag"` + Settings json.RawMessage `json:"settings"` + StreamSettings json.RawMessage `json:"streamSettings"` } // customProtocols is the set of outbound protocols handled by hint/proxy. @@ -151,6 +152,11 @@ func stripCustomOutbounds(raw []byte) ([]byte, []customOutboundJSON, error) { func buildCustomOutbounds(customs []customOutboundJSON) ([]*xray_core.OutboundHandlerConfig, error) { result := make([]*xray_core.OutboundHandlerConfig, 0, len(customs)) for _, c := range customs { + senderSettings, err := buildCustomSenderSettings(c.StreamSettings) + if err != nil { + return nil, errors.New("invalid stream settings for tag ", c.Tag).Base(err) + } + var proxySettings *serial.TypedMessage switch c.Protocol { case "anytls": @@ -182,13 +188,50 @@ func buildCustomOutbounds(customs []customOutboundJSON) ([]*xray_core.OutboundHa } result = append(result, &xray_core.OutboundHandlerConfig{ Tag: c.Tag, - SenderSettings: serial.ToTypedMessage(&xray_proxyman.SenderConfig{}), + SenderSettings: senderSettings, ProxySettings: proxySettings, }) } return result, nil } +func buildCustomSenderSettings(streamSettings json.RawMessage) (*serial.TypedMessage, error) { + if len(streamSettings) == 0 { + return serial.ToTypedMessage(&xray_proxyman.SenderConfig{}), nil + } + + type outboundJSON struct { + Protocol string `json:"protocol"` + Tag string `json:"tag"` + StreamSettings json.RawMessage `json:"streamSettings"` + } + raw, err := json.Marshal(struct { + Outbounds []outboundJSON `json:"outbounds"` + }{ + Outbounds: []outboundJSON{{ + Protocol: "freedom", + Tag: "v2raya-native-sender", + StreamSettings: streamSettings, + }}, + }) + if err != nil { + return nil, err + } + + config, err := conf_serial.DecodeJSONConfig(bytes.NewReader(raw)) + if err != nil { + return nil, err + } + coreConfig, err := config.Build() + if err != nil { + return nil, err + } + if len(coreConfig.Outbound) != 1 || coreConfig.Outbound[0].SenderSettings == nil { + return nil, errors.New("failed to build sender settings") + } + return coreConfig.Outbound[0].SenderSettings, nil +} + // injectMultiObservatory appends the multiobservatory.Config TypedMessage to coreConfig.App. func injectMultiObservatory(coreConfig *xray_core.Config, mo *multiObsJSON) { cfg := &multiobs.Config{} diff --git a/core/hint/proxy/anytls/outbound.go b/core/hint/proxy/anytls/outbound.go index b4cfe6ab..5603244f 100644 --- a/core/hint/proxy/anytls/outbound.go +++ b/core/hint/proxy/anytls/outbound.go @@ -8,6 +8,7 @@ import ( "fmt" "net" "net/netip" + "sync" "time" anytls_padding "anytls/proxy/padding" @@ -31,8 +32,10 @@ import ( // Client is the anytls outbound handler. type Client struct { - config *ClientConfig - sessionClient *session.Client + config *ClientConfig + sessionClient *session.Client + newSessionClient func(internet.Dialer) *session.Client + sessionClientOnce sync.Once } // NewClient creates a new anytls outbound handler. @@ -48,7 +51,6 @@ func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) { passwordHash := make([]byte, 32) copy(passwordHash, hash[:]) - serverAddr := fmt.Sprintf("%s:%d", config.Address, config.Port) sni := config.Sni if sni == "" { sni = config.Address @@ -75,60 +77,58 @@ func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) { } serverDest := xray_net.TCPDestination(xray_net.ParseAddress(config.Address), xray_net.Port(config.Port)) - _ = serverAddr // kept for readability - dialOut := anytls_util.DialOutFunc(func(ctx context.Context) (net.Conn, error) { - rawConn, err := internet.DialSystem(ctx, serverDest, nil) - if err != nil { - // Fallback: plain TCP dial - d := &net.Dialer{Timeout: 10 * time.Second} - rawConn, err = d.DialContext(ctx, "tcp", serverAddr) + newSessionClient := func(dialer internet.Dialer) *session.Client { + dialOut := anytls_util.DialOutFunc(func(ctx context.Context) (net.Conn, error) { + rawConn, err := dialer.Dial(ctx, serverDest) if err != nil { return nil, fmt.Errorf("anytls: failed to dial server: %w", err) } - } - tlsConn := tls.Client(rawConn, tlsCfg) + tlsConn := tls.Client(rawConn, tlsCfg) - // Write password SHA256 + padding (protocol handshake) - b := buf.NewPacket() - defer b.Release() + // Write password SHA256 + padding (protocol handshake) + b := buf.NewPacket() + defer b.Release() - b.Write(passwordHash) - var paddingLen int - if pad := anytls_padding.DefaultPaddingFactory.Load().GenerateRecordPayloadSizes(0); len(pad) > 0 { - paddingLen = pad[0] - } - binary.BigEndian.PutUint16(b.Extend(2), uint16(paddingLen)) - if paddingLen > 0 { - b.WriteZeroN(paddingLen) - } - if _, err = b.WriteTo(tlsConn); err != nil { - tlsConn.Close() - return nil, fmt.Errorf("anytls: failed to write handshake: %w", err) - } + b.Write(passwordHash) + var paddingLen int + if pad := anytls_padding.DefaultPaddingFactory.Load().GenerateRecordPayloadSizes(0); len(pad) > 0 { + paddingLen = pad[0] + } + binary.BigEndian.PutUint16(b.Extend(2), uint16(paddingLen)) + if paddingLen > 0 { + b.WriteZeroN(paddingLen) + } + if _, err = b.WriteTo(tlsConn); err != nil { + tlsConn.Close() + return nil, fmt.Errorf("anytls: failed to write handshake: %w", err) + } - return tlsConn, nil - }) + return tlsConn, nil + }) - bgCtx := context.Background() - sessionClient := session.NewClient( - bgCtx, - dialOut, - &anytls_padding.DefaultPaddingFactory, - 30*time.Second, - 30*time.Second, - minIdle, - ) + return session.NewClient( + context.Background(), + dialOut, + &anytls_padding.DefaultPaddingFactory, + 30*time.Second, + 30*time.Second, + minIdle, + ) + } return &Client{ - config: config, - sessionClient: sessionClient, + config: config, + newSessionClient: newSessionClient, }, nil } // Process implements proxy.Outbound. -func (c *Client) Process(ctx context.Context, link *transport.Link, _ internet.Dialer) error { +func (c *Client) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error { + c.sessionClientOnce.Do(func() { + c.sessionClient = c.newSessionClient(dialer) + }) outbounds := xray_session.OutboundsFromContext(ctx) ob := outbounds[len(outbounds)-1] if !ob.Target.IsValid() { diff --git a/core/hint/proxy/juicity/outbound.go b/core/hint/proxy/juicity/outbound.go index 3dbab2ae..b680eb31 100644 --- a/core/hint/proxy/juicity/outbound.go +++ b/core/hint/proxy/juicity/outbound.go @@ -6,15 +6,18 @@ import ( "fmt" "io" "net" + "strconv" + "strings" + "sync" "github.com/daeuniverse/softwind/netproxy" "github.com/daeuniverse/softwind/protocol" - "github.com/daeuniverse/softwind/protocol/direct" _ "github.com/daeuniverse/softwind/protocol/juicity" // register juicity protocol "github.com/xtls/xray-core/common" xray_buf "github.com/xtls/xray-core/common/buf" "github.com/xtls/xray-core/common/errors" + xray_net "github.com/xtls/xray-core/common/net" xray_session "github.com/xtls/xray-core/common/session" "github.com/xtls/xray-core/common/task" "github.com/xtls/xray-core/transport" @@ -25,8 +28,11 @@ import ( // Client is the juicity outbound handler. type Client struct { - config *ClientConfig - dialer netproxy.Dialer + config *ClientConfig + dialer netproxy.Dialer + newDialer func(internet.Dialer) (netproxy.Dialer, error) + dialerOnce sync.Once + dialerErr error } // NewClient creates a new juicity outbound handler. @@ -70,26 +76,63 @@ func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) { congestion = "bbr" } - dialer, err := protocol.NewDialer("juicity", direct.SymmetricDirect, protocol.Header{ - ProxyAddress: config.Address, - Feature1: congestion, - TlsConfig: tlsCfg, - User: config.Uuid, - Password: config.Password, - IsClient: true, - }) - if err != nil { - return nil, fmt.Errorf("juicity: failed to create dialer: %w", err) + newDialer := func(dialer internet.Dialer) (netproxy.Dialer, error) { + return protocol.NewDialer("juicity", xrayDialer{dialer: dialer}, protocol.Header{ + ProxyAddress: config.Address, + Feature1: congestion, + TlsConfig: tlsCfg, + User: config.Uuid, + Password: config.Password, + IsClient: true, + }) } return &Client{ - config: config, - dialer: dialer, + config: config, + newDialer: newDialer, }, nil } +type xrayDialer struct { + dialer internet.Dialer +} + +func (d xrayDialer) Dial(network, addr string) (netproxy.Conn, error) { + return d.DialContext(context.Background(), network, addr) +} + +func (d xrayDialer) DialContext(ctx context.Context, network, addr string) (netproxy.Conn, error) { + destination, err := xrayDestination(network, addr) + if err != nil { + return nil, err + } + return d.dialer.Dial(ctx, destination) +} + +func xrayDestination(network, addr string) (xray_net.Destination, error) { + host, port, err := net.SplitHostPort(addr) + if err != nil { + return xray_net.Destination{}, fmt.Errorf("juicity: invalid server address %q: %w", addr, err) + } + portNumber, err := strconv.ParseUint(port, 10, 16) + if err != nil { + return xray_net.Destination{}, fmt.Errorf("juicity: invalid server port %q: %w", port, err) + } + address := xray_net.ParseAddress(host) + if strings.HasPrefix(network, "udp") { + return xray_net.UDPDestination(address, xray_net.Port(portNumber)), nil + } + return xray_net.TCPDestination(address, xray_net.Port(portNumber)), nil +} + // Process implements proxy.Outbound. -func (c *Client) Process(ctx context.Context, link *transport.Link, _ internet.Dialer) error { +func (c *Client) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error { + c.dialerOnce.Do(func() { + c.dialer, c.dialerErr = c.newDialer(dialer) + }) + if c.dialerErr != nil { + return errors.New("juicity: failed to create dialer").Base(c.dialerErr) + } outbounds := xray_session.OutboundsFromContext(ctx) ob := outbounds[len(outbounds)-1] if !ob.Target.IsValid() { diff --git a/core/hint/proxy/tuic/outbound.go b/core/hint/proxy/tuic/outbound.go index 3be7319e..a7c9abfb 100644 --- a/core/hint/proxy/tuic/outbound.go +++ b/core/hint/proxy/tuic/outbound.go @@ -5,17 +5,19 @@ import ( "crypto/tls" "fmt" "io" - "net/netip" + "net" + "strconv" "strings" + "sync" outbound_netproxy "github.com/daeuniverse/outbound/netproxy" outbound_protocol "github.com/daeuniverse/outbound/protocol" - "github.com/daeuniverse/outbound/protocol/direct" _ "github.com/daeuniverse/outbound/protocol/tuic" // register tuic protocol "github.com/xtls/xray-core/common" xray_buf "github.com/xtls/xray-core/common/buf" "github.com/xtls/xray-core/common/errors" + xray_net "github.com/xtls/xray-core/common/net" xray_session "github.com/xtls/xray-core/common/session" "github.com/xtls/xray-core/common/task" "github.com/xtls/xray-core/transport" @@ -24,10 +26,12 @@ import ( "github.com/v2rayA/v2raya-core/hint/tlsutil" ) -// Client is the tuic outbound handler. type Client struct { - config *ClientConfig - dialer outbound_netproxy.Dialer + config *ClientConfig + dialer outbound_netproxy.Dialer + newDialer func(internet.Dialer) (outbound_netproxy.Dialer, error) + dialerOnce sync.Once + dialerErr error } // NewClient creates a new tuic outbound handler. @@ -80,27 +84,51 @@ func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) { congestion = "bbr" } - // TUIC uses QUIC/UDP underneath; use a direct UDP dialer as the underlying transport. - nextDialer := direct.NewDirectDialerLaddr(netip.Addr{}, direct.Option{FullCone: false}) - - dialer, err := outbound_protocol.NewDialer("tuic", nextDialer, outbound_protocol.Header{ - ProxyAddress: config.Address, - TlsConfig: tlsCfg, - User: config.Uuid, - Password: config.Password, - Feature1: congestion, - IsClient: true, - }) - if err != nil { - return nil, fmt.Errorf("tuic: failed to create dialer: %w", err) + newDialer := func(dialer internet.Dialer) (outbound_netproxy.Dialer, error) { + return outbound_protocol.NewDialer("tuic", xrayDialer{dialer: dialer}, outbound_protocol.Header{ + ProxyAddress: config.Address, + TlsConfig: tlsCfg, + User: config.Uuid, + Password: config.Password, + Feature1: congestion, + IsClient: true, + }) } return &Client{ - config: config, - dialer: dialer, + config: config, + newDialer: newDialer, }, nil } +type xrayDialer struct { + dialer internet.Dialer +} + +func (d xrayDialer) DialContext(ctx context.Context, network, addr string) (outbound_netproxy.Conn, error) { + destination, err := xrayDestination(network, addr) + if err != nil { + return nil, err + } + return d.dialer.Dial(ctx, destination) +} + +func xrayDestination(network, addr string) (xray_net.Destination, error) { + host, port, err := net.SplitHostPort(addr) + if err != nil { + return xray_net.Destination{}, fmt.Errorf("tuic: invalid server address %q: %w", addr, err) + } + portNumber, err := strconv.ParseUint(port, 10, 16) + if err != nil { + return xray_net.Destination{}, fmt.Errorf("tuic: invalid server port %q: %w", port, err) + } + address := xray_net.ParseAddress(host) + if strings.HasPrefix(network, "udp") { + return xray_net.UDPDestination(address, xray_net.Port(portNumber)), nil + } + return xray_net.TCPDestination(address, xray_net.Port(portNumber)), nil +} + // splitHostPort splits a host:port string, returning host and port separately. // It handles IPv6 addresses in brackets. func splitHostPort(addr string) (host, port string, err error) { @@ -119,7 +147,13 @@ func splitHostPort(addr string) (host, port string, err error) { } // Process implements proxy.Outbound. -func (c *Client) Process(ctx context.Context, link *transport.Link, _ internet.Dialer) error { +func (c *Client) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error { + c.dialerOnce.Do(func() { + c.dialer, c.dialerErr = c.newDialer(dialer) + }) + if c.dialerErr != nil { + return errors.New("tuic: failed to create dialer").Base(c.dialerErr) + } outbounds := xray_session.OutboundsFromContext(ctx) ob := outbounds[len(outbounds)-1] if !ob.Target.IsValid() {