mirror of
https://github.com/shtorm-7/sing-box-extended.git
synced 2026-12-01 14:18:36 +00:00
merge: Merge upstream v1.14.6
This commit is contained in:
@@ -59,7 +59,13 @@ func NewOutbound(ctx context.Context, router adapter.Router, logger log.ContextL
|
||||
return nil, E.New("tcp_fast_open is not supported with anytls outbound")
|
||||
}
|
||||
|
||||
tlsConfig, err := tls.NewClient(ctx, logger, options.Server, common.PtrValueOrDefault(options.TLS))
|
||||
tlsConfig, err := tls.NewClientWithOptions(tls.ClientOptions{
|
||||
Context: ctx,
|
||||
Logger: logger,
|
||||
ServerAddress: options.Server,
|
||||
Options: common.PtrValueOrDefault(options.TLS),
|
||||
DomainResolver: options.DomainResolver,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -84,15 +84,16 @@ func (h *Inbound) Start(stage adapter.StartStage, scope *adapter.Scope) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *Inbound) References() []string {
|
||||
var references []string
|
||||
func (h *Inbound) References() (outbounds []string, dnsServers []string) {
|
||||
for _, inbound := range h.inbounds {
|
||||
referrer, isReferrer := inbound.(adapter.Referrer)
|
||||
if isReferrer {
|
||||
references = append(references, referrer.References()...)
|
||||
referencedOutbounds, referencedDNSServers := referrer.References()
|
||||
outbounds = append(outbounds, referencedOutbounds...)
|
||||
dnsServers = append(dnsServers, referencedDNSServers...)
|
||||
}
|
||||
}
|
||||
return references
|
||||
return outbounds, dnsServers
|
||||
}
|
||||
|
||||
func (h *Inbound) connHandler(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) error {
|
||||
|
||||
@@ -89,17 +89,18 @@ func (h *Outbound) Start(stage adapter.StartStage, scope *adapter.Scope) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *Outbound) References() []string {
|
||||
var references []string
|
||||
func (h *Outbound) References() (outbounds []string, dnsServers []string) {
|
||||
for _, outbound := range h.outbounds {
|
||||
referrer, isReferrer := outbound.(adapter.Referrer)
|
||||
if isReferrer {
|
||||
references = append(references, referrer.References()...)
|
||||
referencedOutbounds, referencedDNSServers := referrer.References()
|
||||
outbounds = append(outbounds, referencedOutbounds...)
|
||||
dnsServers = append(dnsServers, referencedDNSServers...)
|
||||
} else {
|
||||
references = append(references, outbound.Dependencies()...)
|
||||
outbounds = append(outbounds, outbound.Dependencies()...)
|
||||
}
|
||||
}
|
||||
return references
|
||||
return outbounds, dnsServers
|
||||
}
|
||||
|
||||
func (h *Outbound) SetKeepIdleConnections(keep bool) {
|
||||
|
||||
@@ -347,7 +347,7 @@ func (b *backendLinux) batchReadLoop() {
|
||||
if !tun.IsRecoverableReadError(err) {
|
||||
return
|
||||
}
|
||||
readRetry.Wait(err)
|
||||
readRetry.Wait()
|
||||
} else {
|
||||
readRetry.Reset()
|
||||
}
|
||||
|
||||
@@ -29,40 +29,47 @@ var (
|
||||
|
||||
func enableBridgeForwarding(logger logger.ContextLogger, tunName string, inet4 bool, inet6 bool) []sysctlState {
|
||||
var restore []sysctlState
|
||||
enable := func(path string) bool {
|
||||
enable := func(path string, prepare func() []sysctlState) {
|
||||
content, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
logger.Debug(E.Cause(err, "read ", path))
|
||||
return false
|
||||
return
|
||||
}
|
||||
value := strings.TrimSpace(string(content))
|
||||
if value == "1" {
|
||||
return false
|
||||
return
|
||||
}
|
||||
var prepared []sysctlState
|
||||
if prepare != nil {
|
||||
prepared = prepare()
|
||||
}
|
||||
err = os.WriteFile(path, []byte("1"), 0o644)
|
||||
if err != nil {
|
||||
logger.Debug(E.Cause(err, "enable ", path))
|
||||
return false
|
||||
restoreBridgeForwarding(prepared)
|
||||
return
|
||||
}
|
||||
restore = append(restore, sysctlState{name: path, value: value})
|
||||
return true
|
||||
restore = append(restore, prepared...)
|
||||
}
|
||||
if inet4 {
|
||||
enable("/proc/sys/net/ipv4/ip_forward")
|
||||
enable("/proc/sys/net/ipv4/ip_forward", nil)
|
||||
}
|
||||
if inet6 {
|
||||
if enable("/proc/sys/net/ipv6/conf/all/forwarding") {
|
||||
restore = append(restore, overruleAcceptRA(logger)...)
|
||||
}
|
||||
enable("/proc/sys/net/ipv6/conf/all/forwarding", func() []sysctlState {
|
||||
return overruleAcceptRA(logger)
|
||||
})
|
||||
}
|
||||
_ = os.WriteFile("/proc/sys/net/ipv4/conf/"+tunName+"/rp_filter", []byte("2"), 0o644)
|
||||
return restore
|
||||
}
|
||||
|
||||
// Writing conf/all/forwarding copies forwarding=1 to conf/default and to every
|
||||
// existing interface (addrconf_fixup_forwarding), and ipv6_accept_ra() then
|
||||
// requires accept_ra=2 on a forwarding interface; raise interfaces left at the
|
||||
// host default of 1 so SLAAC (e.g. on PPPoE WANs) survives forwarding.
|
||||
// Writing conf/all/forwarding=1 purges RA-learned default routes on every
|
||||
// interface whose accept_ra is not 2 (rt6_purge_dflt_routers) and copies
|
||||
// forwarding=1 to conf/default and every existing interface
|
||||
// (addrconf_fixup_forwarding), after which ipv6_accept_ra() requires
|
||||
// accept_ra=2; raise interfaces left at the host default of 1 beforehand so
|
||||
// SLAAC default routes (e.g. on PPPoE WANs) survive.
|
||||
// conf/default is included so interfaces created afterwards inherit 2.
|
||||
func overruleAcceptRA(logger logger.ContextLogger) []sysctlState {
|
||||
var restore []sysctlState
|
||||
|
||||
@@ -49,16 +49,14 @@ func NewInbound(ctx context.Context, router adapter.Router, logger log.ContextLo
|
||||
return nil, E.Cause(err, "build cloudflared tunnel dialer")
|
||||
}
|
||||
dnsRouter := service.FromContext[adapter.DNSRouter](ctx)
|
||||
controlResolver := newRouterResolver(dnsRouter, controlDialer.(dialer.ResolveDialer).QueryOptions())
|
||||
tunnelResolver := newRouterResolver(dnsRouter, tunnelDialer.(dialer.ResolveDialer).QueryOptions())
|
||||
|
||||
service, err := cloudflared.NewService(cloudflared.ServiceOptions{
|
||||
Logger: logger,
|
||||
ConnectionDialer: &routerDialer{ctx: ctx, router: router, tag: tag},
|
||||
ControlDialer: controlDialer,
|
||||
TunnelDialer: tunnelDialer,
|
||||
ControlResolver: controlResolver,
|
||||
TunnelResolver: tunnelResolver,
|
||||
ControlResolver: &routerResolver{dnsRouter: dnsRouter, queryOptions: controlDialer.(dialer.ResolveDialer).QueryOptions()},
|
||||
TunnelResolver: &routerResolver{dnsRouter: dnsRouter, queryOptions: tunnelDialer.(dialer.ResolveDialer).QueryOptions()},
|
||||
ICMPHandler: &icmpRouterHandler{router: router, logger: logger, tag: tag},
|
||||
ConnContext: func(connCtx context.Context) context.Context {
|
||||
return adapter.WithContext(connCtx, &adapter.InboundContext{
|
||||
@@ -79,17 +77,25 @@ func NewInbound(ctx context.Context, router adapter.Router, logger log.ContextLo
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var dnsReferences []string
|
||||
for _, dialerOptions := range []option.DialerOptions{options.ControlDialer, options.TunnelDialer} {
|
||||
if dialerOptions.DomainResolver != nil && dialerOptions.DomainResolver.Server != "" {
|
||||
dnsReferences = append(dnsReferences, dialerOptions.DomainResolver.Server)
|
||||
}
|
||||
}
|
||||
return &Inbound{
|
||||
Adapter: inbound.NewAdapter(C.TypeCloudflared, tag),
|
||||
service: service,
|
||||
references: common.FilterNotDefault([]string{options.ControlDialer.Detour, options.TunnelDialer.Detour}),
|
||||
Adapter: inbound.NewAdapter(C.TypeCloudflared, tag),
|
||||
service: service,
|
||||
references: common.FilterNotDefault([]string{options.ControlDialer.Detour, options.TunnelDialer.Detour}),
|
||||
dnsReferences: dnsReferences,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type Inbound struct {
|
||||
inbound.Adapter
|
||||
service *cloudflared.Service
|
||||
references []string
|
||||
service *cloudflared.Service
|
||||
references []string
|
||||
dnsReferences []string
|
||||
}
|
||||
|
||||
func (i *Inbound) Start(stage adapter.StartStage, scope *adapter.Scope) error {
|
||||
@@ -114,7 +120,7 @@ type routerDialer struct {
|
||||
// (router_pipe.go dialRouterTCPWithMetadata, origin_dial.go dialWarpPacketConnection), while the
|
||||
// routing and the outbound dial behind the pipe are still in progress, so only its deadline is
|
||||
// honoured, and only until the outbound handshake is reported.
|
||||
func (d *routerDialer) routeContext(ctx context.Context) (context.Context, func(), func()) {
|
||||
func (d *routerDialer) routeContext(ctx context.Context) (context.Context, func(), N.CloseHandlerFunc) {
|
||||
routeCtx, cancel := context.WithCancelCause(context.WithoutCancel(ctx))
|
||||
stopShutdown := context.AfterFunc(d.ctx, func() {
|
||||
cancel(context.Cause(d.ctx))
|
||||
@@ -130,7 +136,7 @@ func (d *routerDialer) routeContext(ctx context.Context) (context.Context, func(
|
||||
connectTimeout.Stop()
|
||||
}
|
||||
}
|
||||
closed := func() {
|
||||
closed := func(error) {
|
||||
connected()
|
||||
stopShutdown()
|
||||
}
|
||||
@@ -193,10 +199,7 @@ func (d *routerDialer) newMetadata(network string, destination M.Socksaddr) adap
|
||||
func (d *routerDialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
|
||||
input, output := pipe.Pipe()
|
||||
routeCtx, connected, closed := d.routeContext(ctx)
|
||||
go d.router.RouteConnectionEx(routeCtx, &routedConn{Conn: output, connected: connected}, d.newMetadata(N.NetworkTCP, destination), N.OnceClose(func(it error) {
|
||||
closed()
|
||||
input.Close()
|
||||
}))
|
||||
go d.router.RouteConnectionEx(routeCtx, &routedConn{Conn: output, connected: connected}, d.newMetadata(N.NetworkTCP, destination), closed)
|
||||
return input, nil
|
||||
}
|
||||
|
||||
@@ -204,10 +207,7 @@ func (d *routerDialer) ListenPacket(ctx context.Context, destination M.Socksaddr
|
||||
input, output := pipe.Pipe()
|
||||
routeCtx, connected, closed := d.routeContext(ctx)
|
||||
routerConn := &routedPacketConn{PacketConn: bufio.NewUnbindPacketConn(output), connected: connected}
|
||||
go d.router.RoutePacketConnectionEx(routeCtx, routerConn, d.newMetadata(N.NetworkUDP, destination), N.OnceClose(func(it error) {
|
||||
closed()
|
||||
input.Close()
|
||||
}))
|
||||
go d.router.RoutePacketConnectionEx(routeCtx, routerConn, d.newMetadata(N.NetworkUDP, destination), closed)
|
||||
return bufio.NewUnbindPacketConn(input), nil
|
||||
}
|
||||
|
||||
@@ -259,8 +259,8 @@ func (h *icmpRouterHandler) RouteICMPFlow(source netip.Addr, destination netip.A
|
||||
}
|
||||
}
|
||||
|
||||
func (i *Inbound) References() []string {
|
||||
return i.references
|
||||
func (i *Inbound) References() ([]string, []string) {
|
||||
return i.references, i.dnsReferences
|
||||
}
|
||||
|
||||
var (
|
||||
|
||||
@@ -10,8 +10,11 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
"github.com/sagernet/sing/common"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
|
||||
mDNS "github.com/miekg/dns"
|
||||
"golang.org/x/net/dns/dnsmessage"
|
||||
)
|
||||
|
||||
type routerResolver struct {
|
||||
@@ -19,10 +22,6 @@ type routerResolver struct {
|
||||
queryOptions adapter.DNSQueryOptions
|
||||
}
|
||||
|
||||
func newRouterResolver(dnsRouter adapter.DNSRouter, queryOptions adapter.DNSQueryOptions) *routerResolver {
|
||||
return &routerResolver{dnsRouter: dnsRouter, queryOptions: queryOptions}
|
||||
}
|
||||
|
||||
func (r *routerResolver) LookupNetIP(ctx context.Context, host string) ([]netip.Addr, error) {
|
||||
return r.dnsRouter.Lookup(ctx, strings.TrimSuffix(host, "."), r.queryOptions)
|
||||
}
|
||||
@@ -55,3 +54,28 @@ func (r *routerResolver) LookupSRV(ctx context.Context, service, proto, name str
|
||||
})
|
||||
return records, nil
|
||||
}
|
||||
|
||||
func (r *routerResolver) LookupTXT(ctx context.Context, name string) ([]string, error) {
|
||||
message := &mDNS.Msg{}
|
||||
message.SetQuestion(mDNS.Fqdn(name), mDNS.TypeTXT)
|
||||
response, err := r.dnsRouter.Exchange(ctx, message, r.queryOptions)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rawResponse, err := response.Pack()
|
||||
if err != nil {
|
||||
return nil, E.Cause(err, "pack TXT response")
|
||||
}
|
||||
var parsedResponse dnsmessage.Message
|
||||
err = parsedResponse.Unpack(rawResponse)
|
||||
if err != nil {
|
||||
return nil, E.Cause(err, "unpack TXT response")
|
||||
}
|
||||
return common.FilterIsInstance(parsedResponse.Answers, func(it dnsmessage.Resource) (string, bool) {
|
||||
record, isTXT := it.Body.(*dnsmessage.TXTResource)
|
||||
if !isTXT {
|
||||
return "", false
|
||||
}
|
||||
return strings.Join(record.TXT, ""), true
|
||||
}), nil
|
||||
}
|
||||
|
||||
+54
-19
@@ -10,12 +10,14 @@ import (
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
"github.com/sagernet/sing-box/adapter/outbound"
|
||||
"github.com/sagernet/sing-box/common/dialer"
|
||||
"github.com/sagernet/sing-box/common/iponly"
|
||||
C "github.com/sagernet/sing-box/constant"
|
||||
"github.com/sagernet/sing-box/log"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
"github.com/sagernet/sing-tun"
|
||||
"github.com/sagernet/sing-tun/ping"
|
||||
"github.com/sagernet/sing/common"
|
||||
"github.com/sagernet/sing/common/bufio"
|
||||
"github.com/sagernet/sing/common/control"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
"github.com/sagernet/sing/common/logger"
|
||||
@@ -29,21 +31,26 @@ func RegisterOutbound(registry *outbound.Registry) {
|
||||
}
|
||||
|
||||
var (
|
||||
_ N.ParallelDialer = (*Outbound)(nil)
|
||||
_ dialer.ParallelNetworkDialer = (*Outbound)(nil)
|
||||
_ dialer.DirectDialer = (*Outbound)(nil)
|
||||
_ adapter.FlowOutbound = (*Outbound)(nil)
|
||||
_ adapter.InterfaceUpdateListener = (*Outbound)(nil)
|
||||
_ N.ParallelDialer = (*Outbound)(nil)
|
||||
_ dialer.ParallelNetworkDialer = (*Outbound)(nil)
|
||||
_ dialer.PacketDialerWithDestination = (*Outbound)(nil)
|
||||
_ dialer.DirectDialer = (*Outbound)(nil)
|
||||
_ adapter.FlowOutbound = (*Outbound)(nil)
|
||||
_ adapter.InterfaceUpdateListener = (*Outbound)(nil)
|
||||
)
|
||||
|
||||
type parallelResolveDialer interface {
|
||||
dialer.ParallelNetworkDialer
|
||||
dialer.PacketDialerWithDestination
|
||||
}
|
||||
|
||||
type Outbound struct {
|
||||
outbound.Adapter
|
||||
ctx context.Context
|
||||
logger logger.ContextLogger
|
||||
network adapter.NetworkManager
|
||||
dialer dialer.ParallelInterfaceDialer
|
||||
dialer parallelResolveDialer
|
||||
domainStrategy C.DomainStrategy
|
||||
fallbackDelay time.Duration
|
||||
isEmpty bool
|
||||
myAddresses common.TypedValue[[]netip.Prefix]
|
||||
icmpPort *ping.Port
|
||||
@@ -70,8 +77,7 @@ func NewOutbound(ctx context.Context, router adapter.Router, logger log.ContextL
|
||||
network: service.FromContext[adapter.NetworkManager](ctx),
|
||||
//nolint:staticcheck
|
||||
domainStrategy: C.DomainStrategy(options.DomainStrategy),
|
||||
fallbackDelay: time.Duration(options.FallbackDelay),
|
||||
dialer: outboundDialer.(dialer.ParallelInterfaceDialer),
|
||||
dialer: outboundDialer.(parallelResolveDialer),
|
||||
isEmpty: reflect.DeepEqual(options.DialerOptions, option.DialerOptions{
|
||||
AbstractDialerOptions: option.AbstractDialerOptions{UDPFragmentDefault: true},
|
||||
}),
|
||||
@@ -81,9 +87,10 @@ func NewOutbound(ctx context.Context, router adapter.Router, logger log.ContextL
|
||||
return nil, E.New("Proxy Protocol is deprecated and removed in sing-box 1.6.0")
|
||||
}
|
||||
if defaultDialer, isDefaultDialer := common.Cast[*dialer.DefaultDialer](outbound.dialer); isDefaultDialer {
|
||||
icmpControl := defaultDialer.ICMPControl()
|
||||
outbound.icmpPort = ping.NewPort(ctx, logger, func(destination netip.Addr) control.Func {
|
||||
return defaultDialer.DialerForICMPDestination(destination).Control
|
||||
}, 0)
|
||||
return icmpControl
|
||||
}, C.ICMPTimeout, C.ICMPFlowMax)
|
||||
}
|
||||
return outbound, nil
|
||||
}
|
||||
@@ -121,7 +128,12 @@ func (h *Outbound) fetchMyAddresses() {
|
||||
continue
|
||||
}
|
||||
found = true
|
||||
myAddresses = append(myAddresses, myInterface.Addresses...)
|
||||
for _, prefix := range myInterface.Addresses {
|
||||
if prefix.Addr().Is6() && prefix.Addr().IsLinkLocalUnicast() {
|
||||
prefix = netip.PrefixFrom(prefix.Addr(), prefix.Addr().BitLen())
|
||||
}
|
||||
myAddresses = append(myAddresses, prefix)
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return
|
||||
@@ -182,8 +194,31 @@ func (h *Outbound) ListenPacket(ctx context.Context, destination M.Socksaddr) (n
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
func (h *Outbound) ListenPacketWithDestination(ctx context.Context, destination M.Socksaddr) (net.PacketConn, netip.Addr, error) {
|
||||
if h.isMyLoopbackAddress(destination.Addr) {
|
||||
return nil, netip.Addr{}, E.New("loopback connection to TUN range")
|
||||
}
|
||||
ctx, metadata := adapter.ExtendContext(ctx)
|
||||
metadata.Outbound = h.Tag()
|
||||
metadata.Destination = destination
|
||||
h.logger.InfoContext(ctx, "outbound packet connection")
|
||||
conn, destinationAddress, err := h.dialer.ListenPacketWithDestination(ctx, destination)
|
||||
if err != nil {
|
||||
return nil, netip.Addr{}, err
|
||||
}
|
||||
packetConn := iponly.NewPacketConn(h.logger, conn)
|
||||
if destinationAddress.IsValid() && !metadata.UDPDisableDomainUnmapping {
|
||||
return bufio.NewNATPacketConn(packetConn, M.SocksaddrFrom(destinationAddress, destination.Port), destination), netip.Addr{}, nil
|
||||
}
|
||||
return packetConn, destinationAddress, nil
|
||||
}
|
||||
|
||||
func (h *Outbound) PreMatchFlow(network string, destination netip.Addr) adapter.PreMatchAction {
|
||||
if network == N.NetworkICMP && h.icmpPort != nil {
|
||||
if h.isMyLoopbackAddress(destination) {
|
||||
h.logger.Error("reject ", network, " connection to ", destination, ": loopback connection to TUN range")
|
||||
return adapter.PreMatchReject
|
||||
}
|
||||
return adapter.PreMatchFlow
|
||||
}
|
||||
return adapter.PreMatchContinue
|
||||
@@ -210,7 +245,7 @@ func (h *Outbound) WritePackets(packets [][]byte) error {
|
||||
}
|
||||
|
||||
func (h *Outbound) DialParallel(ctx context.Context, network string, destination M.Socksaddr, destinationAddresses []netip.Addr) (net.Conn, error) {
|
||||
if h.isMyLoopbackAddress(destinationAddresses...) {
|
||||
if h.isMyLoopbackAddress(destinationAddresses...) || destination.IsIP() && h.isMyLoopbackAddress(destination.Addr) {
|
||||
return nil, E.New("loopback connection to TUN range")
|
||||
}
|
||||
ctx, metadata := adapter.ExtendContext(ctx)
|
||||
@@ -223,11 +258,11 @@ func (h *Outbound) DialParallel(ctx context.Context, network string, destination
|
||||
case N.NetworkUDP:
|
||||
h.logger.InfoContext(ctx, "outbound packet connection to ", destination)
|
||||
}
|
||||
return dialer.DialParallelNetwork(ctx, h.dialer, network, destination, destinationAddresses, len(destinationAddresses) > 0 && destinationAddresses[0].Is6(), nil, nil, nil, h.fallbackDelay)
|
||||
return h.dialer.DialParallelNetwork(ctx, network, destination, destinationAddresses, nil, nil, nil, 0)
|
||||
}
|
||||
|
||||
func (h *Outbound) DialParallelNetwork(ctx context.Context, network string, destination M.Socksaddr, destinationAddresses []netip.Addr, networkStrategy *C.NetworkStrategy, networkType []C.InterfaceType, fallbackNetworkType []C.InterfaceType, fallbackDelay time.Duration) (net.Conn, error) {
|
||||
if h.isMyLoopbackAddress(destinationAddresses...) {
|
||||
if h.isMyLoopbackAddress(destinationAddresses...) || destination.IsIP() && h.isMyLoopbackAddress(destination.Addr) {
|
||||
return nil, E.New("loopback connection to TUN range")
|
||||
}
|
||||
ctx, metadata := adapter.ExtendContext(ctx)
|
||||
@@ -240,22 +275,22 @@ func (h *Outbound) DialParallelNetwork(ctx context.Context, network string, dest
|
||||
case N.NetworkUDP:
|
||||
h.logger.InfoContext(ctx, "outbound packet connection to ", destination)
|
||||
}
|
||||
return dialer.DialParallelNetwork(ctx, h.dialer, network, destination, destinationAddresses, len(destinationAddresses) > 0 && destinationAddresses[0].Is6(), networkStrategy, networkType, fallbackNetworkType, fallbackDelay)
|
||||
return h.dialer.DialParallelNetwork(ctx, network, destination, destinationAddresses, networkStrategy, networkType, fallbackNetworkType, fallbackDelay)
|
||||
}
|
||||
|
||||
func (h *Outbound) ListenSerialNetworkPacket(ctx context.Context, destination M.Socksaddr, destinationAddresses []netip.Addr, networkStrategy *C.NetworkStrategy, networkType []C.InterfaceType, fallbackNetworkType []C.InterfaceType, fallbackDelay time.Duration) (net.PacketConn, netip.Addr, error) {
|
||||
if h.isMyLoopbackAddress(destinationAddresses...) {
|
||||
if h.isMyLoopbackAddress(destinationAddresses...) || destination.IsIP() && h.isMyLoopbackAddress(destination.Addr) {
|
||||
return nil, netip.Addr{}, E.New("loopback connection to TUN range")
|
||||
}
|
||||
ctx, metadata := adapter.ExtendContext(ctx)
|
||||
metadata.Outbound = h.Tag()
|
||||
metadata.Destination = destination
|
||||
h.logger.InfoContext(ctx, "outbound packet connection")
|
||||
conn, newDestination, err := dialer.ListenSerialNetworkPacket(ctx, h.dialer, destination, destinationAddresses, networkStrategy, networkType, fallbackNetworkType, fallbackDelay)
|
||||
conn, newDestination, err := h.dialer.ListenSerialNetworkPacket(ctx, destination, destinationAddresses, networkStrategy, networkType, fallbackNetworkType, fallbackDelay)
|
||||
if err != nil {
|
||||
return nil, netip.Addr{}, err
|
||||
}
|
||||
return conn, newDestination, nil
|
||||
return iponly.NewPacketConn(h.logger, conn), newDestination, nil
|
||||
}
|
||||
|
||||
func (h *Outbound) IsEmpty() bool {
|
||||
|
||||
+48
-32
@@ -4,6 +4,8 @@ import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
C "github.com/sagernet/sing-box/constant"
|
||||
@@ -19,49 +21,58 @@ import (
|
||||
mDNS "github.com/miekg/dns"
|
||||
)
|
||||
|
||||
func HandleStreamDNSRequest(ctx context.Context, router adapter.DNSRouter, conn net.Conn, metadata adapter.InboundContext) error {
|
||||
var queryLength uint16
|
||||
err := binary.Read(conn, binary.BigEndian, &queryLength)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if queryLength == 0 {
|
||||
return dns.RcodeFormatError
|
||||
}
|
||||
buffer := buf.NewSize(int(queryLength))
|
||||
defer buffer.Release()
|
||||
_, err = buffer.ReadFullFrom(conn, int(queryLength))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var message mDNS.Msg
|
||||
err = message.Unpack(buffer.Bytes())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
metadataInQuery := metadata
|
||||
router.ExchangeAsync(adapter.WithContext(ctx, &metadataInQuery), &message, adapter.DNSQueryOptions{}, func(response *mDNS.Msg, err error) {
|
||||
func NewDNSConnection(ctx context.Context, router adapter.DNSRouter, conn net.Conn, metadata adapter.InboundContext) error {
|
||||
metadata.Destination = M.Socksaddr{}
|
||||
var writeAccess sync.Mutex
|
||||
for {
|
||||
conn.SetReadDeadline(time.Now().Add(C.DNSTimeout))
|
||||
var queryLength uint16
|
||||
err := binary.Read(conn, binary.BigEndian, &queryLength)
|
||||
if err != nil {
|
||||
conn.Close()
|
||||
return
|
||||
return err
|
||||
}
|
||||
go writeStreamResponse(conn, response)
|
||||
})
|
||||
return nil
|
||||
if queryLength == 0 {
|
||||
return dns.RcodeFormatError
|
||||
}
|
||||
buffer := buf.NewSize(int(queryLength))
|
||||
_, err = buffer.ReadFullFrom(conn, int(queryLength))
|
||||
if err != nil {
|
||||
buffer.Release()
|
||||
return err
|
||||
}
|
||||
var message mDNS.Msg
|
||||
err = message.Unpack(buffer.Bytes())
|
||||
buffer.Release()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
metadataInQuery := metadata
|
||||
router.ExchangeAsync(adapter.WithContext(ctx, &metadataInQuery), &message, adapter.DNSQueryOptions{}, func(response *mDNS.Msg, err error) {
|
||||
if err != nil {
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
go writeStreamResponse(conn, &writeAccess, response)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func writeStreamResponse(conn net.Conn, response *mDNS.Msg) {
|
||||
func writeStreamResponse(conn net.Conn, writeAccess *sync.Mutex, response *mDNS.Msg) {
|
||||
responseLength := response.Len()
|
||||
responseBuffer := buf.NewSize(3 + responseLength)
|
||||
defer responseBuffer.Release()
|
||||
responseBuffer.Resize(2, 0)
|
||||
n, err := response.PackBuffer(responseBuffer.FreeBytes())
|
||||
compressedResponse := response.Copy()
|
||||
compressedResponse.Compress = true
|
||||
rawMessage, err := compressedResponse.PackBuffer(responseBuffer.FreeBytes())
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
responseBuffer.Truncate(len(n))
|
||||
binary.BigEndian.PutUint16(responseBuffer.ExtendHeader(2), uint16(len(n)))
|
||||
common.Must1(responseBuffer.Write(rawMessage))
|
||||
binary.BigEndian.PutUint16(responseBuffer.ExtendHeader(2), uint16(len(rawMessage)))
|
||||
writeAccess.Lock()
|
||||
conn.Write(responseBuffer.Bytes())
|
||||
writeAccess.Unlock()
|
||||
}
|
||||
|
||||
func NewDNSPacketConnection(ctx context.Context, router adapter.DNSRouter, conn N.PacketConn, cachedPackets []*N.PacketBuffer, metadata adapter.InboundContext) error {
|
||||
@@ -70,7 +81,6 @@ func NewDNSPacketConnection(ctx context.Context, router adapter.DNSRouter, conn
|
||||
rearHeadroom := N.CalculateRearHeadroom(conn)
|
||||
var reader N.PacketReader = conn
|
||||
var counters []N.CountFunc
|
||||
cachedPackets = common.Reverse(cachedPackets)
|
||||
for {
|
||||
reader, counters = N.UnwrapCountPacketReader(reader, counters)
|
||||
if cachedReader, isCached := reader.(N.CachedPacketReader); isCached {
|
||||
@@ -88,6 +98,7 @@ func NewDNSPacketConnection(ctx context.Context, router adapter.DNSRouter, conn
|
||||
}
|
||||
fastClose, cancel := context.WithCancelCause(ctx)
|
||||
timeout := canceler.New(fastClose, cancel, C.DNSTimeout)
|
||||
var writeAccess sync.Mutex
|
||||
var group task.Group
|
||||
group.Append0(func(_ context.Context) error {
|
||||
for {
|
||||
@@ -138,7 +149,9 @@ func NewDNSPacketConnection(ctx context.Context, router adapter.DNSRouter, conn
|
||||
cancel(truncateErr)
|
||||
return
|
||||
}
|
||||
writeAccess.Lock()
|
||||
writeErr := conn.WritePacket(responseBuffer, destination)
|
||||
writeAccess.Unlock()
|
||||
if writeErr != nil {
|
||||
cancel(writeErr)
|
||||
}
|
||||
@@ -156,6 +169,7 @@ func newDNSPacketConnection(ctx context.Context, router adapter.DNSRouter, conn
|
||||
rearHeadroom := N.CalculateRearHeadroom(conn)
|
||||
fastClose, cancel := context.WithCancelCause(ctx)
|
||||
timeout := canceler.New(fastClose, cancel, C.DNSTimeout)
|
||||
var writeAccess sync.Mutex
|
||||
var group task.Group
|
||||
group.Append0(func(_ context.Context) error {
|
||||
for {
|
||||
@@ -208,7 +222,9 @@ func newDNSPacketConnection(ctx context.Context, router adapter.DNSRouter, conn
|
||||
cancel(truncateErr)
|
||||
return
|
||||
}
|
||||
writeAccess.Lock()
|
||||
writeErr := conn.WritePacket(responseBuffer, destination)
|
||||
writeAccess.Unlock()
|
||||
if writeErr != nil {
|
||||
cancel(writeErr)
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"context"
|
||||
"net"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
"github.com/sagernet/sing-box/adapter/outbound"
|
||||
@@ -44,17 +43,10 @@ func (d *Outbound) ListenPacket(ctx context.Context, destination M.Socksaddr) (n
|
||||
}
|
||||
|
||||
func (d *Outbound) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
|
||||
metadata.Destination = M.Socksaddr{}
|
||||
for {
|
||||
conn.SetReadDeadline(time.Now().Add(C.DNSTimeout))
|
||||
err := HandleStreamDNSRequest(ctx, d.router, conn, metadata)
|
||||
if err != nil {
|
||||
conn.Close()
|
||||
if onClose != nil {
|
||||
onClose(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
err := NewDNSConnection(ctx, d.router, conn, metadata)
|
||||
conn.Close()
|
||||
if onClose != nil {
|
||||
onClose(err)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -69,15 +69,16 @@ func (h *Inbound) Start(stage adapter.StartStage, scope *adapter.Scope) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *Inbound) References() []string {
|
||||
var references []string
|
||||
func (h *Inbound) References() (outbounds []string, dnsServers []string) {
|
||||
for _, inbound := range h.inbounds {
|
||||
referrer, isReferrer := inbound.(adapter.Referrer)
|
||||
if isReferrer {
|
||||
references = append(references, referrer.References()...)
|
||||
referencedOutbounds, referencedDNSServers := referrer.References()
|
||||
outbounds = append(outbounds, referencedOutbounds...)
|
||||
dnsServers = append(dnsServers, referencedDNSServers...)
|
||||
}
|
||||
}
|
||||
return references
|
||||
return outbounds, dnsServers
|
||||
}
|
||||
|
||||
func (h *Inbound) connHandler(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) error {
|
||||
|
||||
@@ -79,17 +79,18 @@ func (f *Failover) Start(stage adapter.StartStage, scope *adapter.Scope) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *Failover) References() []string {
|
||||
var references []string
|
||||
func (f *Failover) References() (outbounds []string, dnsServers []string) {
|
||||
for _, outbound := range f.outbounds {
|
||||
referrer, isReferrer := outbound.(adapter.Referrer)
|
||||
if isReferrer {
|
||||
references = append(references, referrer.References()...)
|
||||
referencedOutbounds, referencedDNSServers := referrer.References()
|
||||
outbounds = append(outbounds, referencedOutbounds...)
|
||||
dnsServers = append(dnsServers, referencedDNSServers...)
|
||||
} else {
|
||||
references = append(references, outbound.Dependencies()...)
|
||||
outbounds = append(outbounds, outbound.Dependencies()...)
|
||||
}
|
||||
}
|
||||
return references
|
||||
return outbounds, dnsServers
|
||||
}
|
||||
|
||||
func (f *Failover) SetKeepIdleConnections(keep bool) {
|
||||
|
||||
@@ -2,6 +2,7 @@ package group
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -73,10 +74,14 @@ func (s *Fallback) Start(stage adapter.StartStage, scope *adapter.Scope) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Fallback) Now() string {
|
||||
func (s *Fallback) Selected(network string) adapter.Outbound {
|
||||
s.mtx.Lock()
|
||||
defer s.mtx.Unlock()
|
||||
return s.lastUsedOutbound
|
||||
return s.outbounds[s.lastUsedOutbound]
|
||||
}
|
||||
|
||||
func (s *Fallback) AttachConnection(closer io.Closer) func() {
|
||||
return func() {}
|
||||
}
|
||||
|
||||
func (s *Fallback) All() []string {
|
||||
|
||||
+28
-46
@@ -2,8 +2,10 @@ package group
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net"
|
||||
"regexp"
|
||||
"slices"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
"github.com/sagernet/sing-box/adapter/outbound"
|
||||
@@ -25,17 +27,14 @@ func RegisterSelector(registry *outbound.Registry) {
|
||||
}
|
||||
|
||||
var (
|
||||
_ adapter.OutboundGroup = (*Selector)(nil)
|
||||
_ adapter.Referrer = (*Selector)(nil)
|
||||
_ adapter.ConnectionHandler = (*Selector)(nil)
|
||||
_ adapter.PacketConnectionHandler = (*Selector)(nil)
|
||||
_ adapter.OutboundGroup = (*Selector)(nil)
|
||||
_ adapter.Referrer = (*Selector)(nil)
|
||||
)
|
||||
|
||||
type Selector struct {
|
||||
outbound.Adapter
|
||||
ctx context.Context
|
||||
outbound adapter.OutboundManager
|
||||
connection adapter.ConnectionManager
|
||||
logger logger.ContextLogger
|
||||
tags []string
|
||||
defaultTag string
|
||||
@@ -60,7 +59,6 @@ func NewSelector(ctx context.Context, router adapter.Router, logger log.ContextL
|
||||
Adapter: outbound.NewAdapter(C.TypeSelector, tag, []string{N.NetworkTCP, N.NetworkUDP}, options.Outbounds),
|
||||
ctx: ctx,
|
||||
outbound: service.FromContext[adapter.OutboundManager](ctx),
|
||||
connection: service.FromContext[adapter.ConnectionManager](ctx),
|
||||
logger: logger,
|
||||
tags: options.Outbounds,
|
||||
defaultTag: options.Default,
|
||||
@@ -78,6 +76,11 @@ func NewSelector(ctx context.Context, router adapter.Router, logger log.ContextL
|
||||
include: (*regexp.Regexp)(options.Include),
|
||||
useAllProviders: options.UseAllProviders,
|
||||
}
|
||||
for i, tag := range outbound.tags {
|
||||
if slices.Contains(outbound.tags[:i], tag) {
|
||||
return nil, E.New("duplicate tag: ", tag)
|
||||
}
|
||||
}
|
||||
return outbound, nil
|
||||
}
|
||||
|
||||
@@ -134,20 +137,24 @@ func (s *Selector) Start(stage adapter.StartStage, scope *adapter.Scope) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Selector) Now() string {
|
||||
selected := s.selected.Load()
|
||||
if selected == nil {
|
||||
return s.tags[0]
|
||||
}
|
||||
return selected.Tag()
|
||||
}
|
||||
|
||||
func (s *Selector) All() []string {
|
||||
return s.tags
|
||||
}
|
||||
|
||||
func (s *Selector) References() []string {
|
||||
return []string{s.Now()}
|
||||
func (s *Selector) Selected(network string) adapter.Outbound {
|
||||
return s.selected.Load()
|
||||
}
|
||||
|
||||
func (s *Selector) AttachConnection(closer io.Closer) func() {
|
||||
return s.interruptGroup.Add(closer, true)
|
||||
}
|
||||
|
||||
func (s *Selector) References() ([]string, []string) {
|
||||
selected := s.selected.Load()
|
||||
if selected == nil {
|
||||
return s.tags[:1], nil
|
||||
}
|
||||
return []string{selected.Tag()}, nil
|
||||
}
|
||||
|
||||
func (s *Selector) SelectOutbound(tag string) bool {
|
||||
@@ -190,40 +197,15 @@ func (s *Selector) ListenPacket(ctx context.Context, destination M.Socksaddr) (n
|
||||
return s.interruptGroup.NewPacketConn(conn, interrupt.IsExternalConnectionFromContext(ctx), interrupt.IsProviderConnectionFromContext(ctx)), nil
|
||||
}
|
||||
|
||||
func (s *Selector) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
|
||||
ctx = interrupt.ContextWithIsExternalConnection(ctx)
|
||||
selected := s.selected.Load()
|
||||
conn = s.interruptGroup.NewConn(conn, interrupt.IsExternalConnectionFromContext(ctx), interrupt.IsProviderConnectionFromContext(ctx))
|
||||
if outboundHandler, isHandler := selected.(adapter.ConnectionHandler); isHandler {
|
||||
outboundHandler.NewConnection(ctx, conn, metadata, onClose)
|
||||
} else {
|
||||
s.connection.NewConnection(ctx, s, conn, metadata, onClose)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Selector) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
|
||||
ctx = interrupt.ContextWithIsExternalConnection(ctx)
|
||||
selected := s.selected.Load()
|
||||
conn = s.interruptGroup.NewSingPacketConn(conn, interrupt.IsExternalConnectionFromContext(ctx), interrupt.IsProviderConnectionFromContext(ctx))
|
||||
if outboundHandler, isHandler := selected.(adapter.PacketConnectionHandler); isHandler {
|
||||
outboundHandler.NewPacketConnection(ctx, conn, metadata, onClose)
|
||||
} else {
|
||||
s.connection.NewPacketConnection(ctx, s, conn, metadata, onClose)
|
||||
}
|
||||
}
|
||||
|
||||
func RealTag(outboundManager adapter.OutboundManager, detour adapter.Outbound) string {
|
||||
tag := detour.Tag()
|
||||
func RealTag(detour adapter.Outbound, network string) string {
|
||||
for {
|
||||
group, isGroup := detour.(adapter.OutboundGroup)
|
||||
if !isGroup {
|
||||
return tag
|
||||
return detour.Tag()
|
||||
}
|
||||
tag = group.Now()
|
||||
var loaded bool
|
||||
detour, loaded = outboundManager.Outbound(tag)
|
||||
if !loaded {
|
||||
return tag
|
||||
detour = group.Selected(network)
|
||||
if detour == nil {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+103
-77
@@ -2,9 +2,11 @@ package group
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"maps"
|
||||
"net"
|
||||
"regexp"
|
||||
"slices"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
@@ -40,7 +42,6 @@ type URLTest struct {
|
||||
outbound.Adapter
|
||||
ctx context.Context
|
||||
outbound adapter.OutboundManager
|
||||
connection adapter.ConnectionManager
|
||||
logger log.ContextLogger
|
||||
tags []string
|
||||
link string
|
||||
@@ -67,7 +68,6 @@ func NewURLTest(ctx context.Context, router adapter.Router, logger log.ContextLo
|
||||
Adapter: outbound.NewAdapter(C.TypeURLTest, tag, []string{N.NetworkTCP, N.NetworkUDP}, options.Outbounds),
|
||||
ctx: ctx,
|
||||
outbound: service.FromContext[adapter.OutboundManager](ctx),
|
||||
connection: service.FromContext[adapter.ConnectionManager](ctx),
|
||||
logger: logger,
|
||||
tags: options.Outbounds,
|
||||
link: options.URL,
|
||||
@@ -85,6 +85,11 @@ func NewURLTest(ctx context.Context, router adapter.Router, logger log.ContextLo
|
||||
include: (*regexp.Regexp)(options.Include),
|
||||
useAllProviders: options.UseAllProviders,
|
||||
}
|
||||
for i, tag := range outbound.tags {
|
||||
if slices.Contains(outbound.tags[:i], tag) {
|
||||
return nil, E.New("duplicate tag: ", tag)
|
||||
}
|
||||
}
|
||||
return outbound, nil
|
||||
}
|
||||
|
||||
@@ -137,32 +142,43 @@ func (s *URLTest) Start(stage adapter.StartStage, scope *adapter.Scope) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *URLTest) Now() string {
|
||||
if s.group.selectedOutboundTCP != nil {
|
||||
return s.group.selectedOutboundTCP.Tag()
|
||||
} else if s.group.selectedOutboundUDP != nil {
|
||||
return s.group.selectedOutboundUDP.Tag()
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (s *URLTest) All() []string {
|
||||
return s.tags
|
||||
}
|
||||
|
||||
func (s *URLTest) References() []string {
|
||||
func (s *URLTest) Selected(network string) adapter.Outbound {
|
||||
var outbound adapter.Outbound
|
||||
if network == N.NetworkUDP {
|
||||
outbound = s.group.selectedOutboundUDP.Load()
|
||||
} else {
|
||||
outbound = s.group.selectedOutboundTCP.Load()
|
||||
}
|
||||
if outbound == nil {
|
||||
outbound, _ = s.group.Select(network)
|
||||
}
|
||||
return outbound
|
||||
}
|
||||
|
||||
func (s *URLTest) AttachConnection(closer io.Closer) func() {
|
||||
s.group.Touch()
|
||||
return s.group.interruptGroup.Add(closer, true)
|
||||
}
|
||||
|
||||
func (s *URLTest) References() ([]string, []string) {
|
||||
group := s.group
|
||||
if group == nil {
|
||||
return nil
|
||||
return nil, nil
|
||||
}
|
||||
var references []string
|
||||
if group.selectedOutboundTCP != nil {
|
||||
references = append(references, group.selectedOutboundTCP.Tag())
|
||||
selectedOutboundTCP := group.selectedOutboundTCP.Load()
|
||||
selectedOutboundUDP := group.selectedOutboundUDP.Load()
|
||||
if selectedOutboundTCP != nil {
|
||||
references = append(references, selectedOutboundTCP.Tag())
|
||||
}
|
||||
if group.selectedOutboundUDP != nil && group.selectedOutboundUDP != group.selectedOutboundTCP {
|
||||
references = append(references, group.selectedOutboundUDP.Tag())
|
||||
if selectedOutboundUDP != nil && selectedOutboundUDP != selectedOutboundTCP {
|
||||
references = append(references, selectedOutboundUDP.Tag())
|
||||
}
|
||||
return references
|
||||
return references, nil
|
||||
}
|
||||
|
||||
func (s *URLTest) URLTest(ctx context.Context) (map[string]uint16, error) {
|
||||
@@ -174,7 +190,9 @@ func (s *URLTest) CheckOutbounds() {
|
||||
}
|
||||
|
||||
func (s *URLTest) PerformUpdateCheck() {
|
||||
s.group.performUpdateCheck()
|
||||
if s.group.performUpdateCheck() {
|
||||
s.group.history.NotifyUpdated()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *URLTest) InterfaceUpdated(ctx context.Context) {
|
||||
@@ -200,9 +218,9 @@ func (s *URLTest) DialContext(ctx context.Context, network string, destination M
|
||||
var outbound adapter.Outbound
|
||||
switch N.NetworkName(network) {
|
||||
case N.NetworkTCP:
|
||||
outbound = s.group.selectedOutboundTCP
|
||||
outbound = s.group.selectedOutboundTCP.Load()
|
||||
case N.NetworkUDP:
|
||||
outbound = s.group.selectedOutboundUDP
|
||||
outbound = s.group.selectedOutboundUDP.Load()
|
||||
default:
|
||||
return nil, E.Extend(N.ErrUnknownNetwork, network)
|
||||
}
|
||||
@@ -217,13 +235,16 @@ func (s *URLTest) DialContext(ctx context.Context, network string, destination M
|
||||
return s.group.interruptGroup.NewConn(conn, interrupt.IsExternalConnectionFromContext(ctx), interrupt.IsProviderConnectionFromContext(ctx)), nil
|
||||
}
|
||||
s.logger.ErrorContext(ctx, err)
|
||||
s.group.history.DeleteURLTestHistory(outbound.Tag())
|
||||
if !E.IsClosedOrCanceled(err) {
|
||||
s.group.history.DeleteURLTestHistory(RealTag(outbound, N.NetworkName(network)))
|
||||
s.PerformUpdateCheck()
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func (s *URLTest) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
|
||||
s.group.Touch()
|
||||
outbound := s.group.selectedOutboundUDP
|
||||
outbound := s.group.selectedOutboundUDP.Load()
|
||||
if outbound == nil {
|
||||
outbound, _ = s.group.Select(N.NetworkUDP)
|
||||
}
|
||||
@@ -235,22 +256,13 @@ func (s *URLTest) ListenPacket(ctx context.Context, destination M.Socksaddr) (ne
|
||||
return s.group.interruptGroup.NewPacketConn(conn, interrupt.IsExternalConnectionFromContext(ctx), interrupt.IsProviderConnectionFromContext(ctx)), nil
|
||||
}
|
||||
s.logger.ErrorContext(ctx, err)
|
||||
s.group.history.DeleteURLTestHistory(outbound.Tag())
|
||||
if !E.IsClosedOrCanceled(err) {
|
||||
s.group.history.DeleteURLTestHistory(RealTag(outbound, N.NetworkUDP))
|
||||
s.PerformUpdateCheck()
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func (s *URLTest) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
|
||||
ctx = interrupt.ContextWithIsExternalConnection(ctx)
|
||||
conn = s.group.interruptGroup.NewConn(conn, interrupt.IsExternalConnectionFromContext(ctx), interrupt.IsProviderConnectionFromContext(ctx))
|
||||
s.connection.NewConnection(ctx, s, conn, metadata, onClose)
|
||||
}
|
||||
|
||||
func (s *URLTest) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
|
||||
ctx = interrupt.ContextWithIsExternalConnection(ctx)
|
||||
conn = s.group.interruptGroup.NewSingPacketConn(conn, interrupt.IsExternalConnectionFromContext(ctx), interrupt.IsProviderConnectionFromContext(ctx))
|
||||
s.connection.NewPacketConnection(ctx, s, conn, metadata, onClose)
|
||||
}
|
||||
|
||||
func (s *URLTest) onProviderUpdated(tag string) error {
|
||||
_, loaded := s.providers[tag]
|
||||
if !loaded {
|
||||
@@ -321,15 +333,16 @@ type URLTestGroup struct {
|
||||
idleTimeout time.Duration
|
||||
history *urltest.HistoryStorage
|
||||
checking atomic.Bool
|
||||
selectedOutboundTCP adapter.Outbound
|
||||
selectedOutboundUDP adapter.Outbound
|
||||
selectedOutboundTCP common.TypedValue[adapter.Outbound]
|
||||
selectedOutboundUDP common.TypedValue[adapter.Outbound]
|
||||
interruptGroup *interrupt.Group
|
||||
interruptExternalConnections bool
|
||||
access sync.Mutex
|
||||
updateAccess sync.Mutex
|
||||
ticker *time.Ticker
|
||||
close chan struct{}
|
||||
started bool
|
||||
started atomic.Bool
|
||||
closed atomic.Bool
|
||||
lastActive common.TypedValue[time.Time]
|
||||
}
|
||||
|
||||
@@ -370,17 +383,20 @@ func NewURLTestGroup(ctx context.Context, outboundManager adapter.OutboundManage
|
||||
func (g *URLTestGroup) PostStart() {
|
||||
g.access.Lock()
|
||||
defer g.access.Unlock()
|
||||
g.started = true
|
||||
g.started.Store(true)
|
||||
g.lastActive.Store(time.Now())
|
||||
go g.CheckOutbounds(g.ctx, false)
|
||||
}
|
||||
|
||||
func (g *URLTestGroup) Touch() {
|
||||
if !g.started {
|
||||
if !g.started.Load() {
|
||||
return
|
||||
}
|
||||
g.access.Lock()
|
||||
defer g.access.Unlock()
|
||||
if g.closed.Load() {
|
||||
return
|
||||
}
|
||||
if g.ticker != nil {
|
||||
g.lastActive.Store(time.Now())
|
||||
return
|
||||
@@ -394,13 +410,15 @@ func (g *URLTestGroup) Touch() {
|
||||
func (g *URLTestGroup) Close() error {
|
||||
g.access.Lock()
|
||||
defer g.access.Unlock()
|
||||
if g.ticker == nil {
|
||||
if g.closed.Swap(true) {
|
||||
return nil
|
||||
}
|
||||
g.ticker.Stop()
|
||||
g.ticker = nil
|
||||
g.pause.UnregisterCallback(g.pauseCallback)
|
||||
g.pauseCallback = nil
|
||||
if g.ticker != nil {
|
||||
g.ticker.Stop()
|
||||
g.ticker = nil
|
||||
g.pause.UnregisterCallback(g.pauseCallback)
|
||||
g.pauseCallback = nil
|
||||
}
|
||||
close(g.close)
|
||||
return nil
|
||||
}
|
||||
@@ -408,27 +426,24 @@ func (g *URLTestGroup) Close() error {
|
||||
func (g *URLTestGroup) Select(network string) (adapter.Outbound, bool) {
|
||||
var minDelay uint16
|
||||
var minOutbound adapter.Outbound
|
||||
var selectedOutbound adapter.Outbound
|
||||
switch network {
|
||||
case N.NetworkTCP:
|
||||
if g.selectedOutboundTCP != nil {
|
||||
if history := g.history.LoadURLTestHistory(RealTag(g.outbound, g.selectedOutboundTCP)); history != nil {
|
||||
minOutbound = g.selectedOutboundTCP
|
||||
minDelay = history.Delay
|
||||
}
|
||||
}
|
||||
selectedOutbound = g.selectedOutboundTCP.Load()
|
||||
case N.NetworkUDP:
|
||||
if g.selectedOutboundUDP != nil {
|
||||
if history := g.history.LoadURLTestHistory(RealTag(g.outbound, g.selectedOutboundUDP)); history != nil {
|
||||
minOutbound = g.selectedOutboundUDP
|
||||
minDelay = history.Delay
|
||||
}
|
||||
selectedOutbound = g.selectedOutboundUDP.Load()
|
||||
}
|
||||
if selectedOutbound != nil {
|
||||
if history := g.history.LoadURLTestHistory(RealTag(selectedOutbound, network)); history != nil {
|
||||
minOutbound = selectedOutbound
|
||||
minDelay = history.Delay
|
||||
}
|
||||
}
|
||||
for _, detour := range g.outbounds {
|
||||
if !common.Contains(detour.Network(), network) {
|
||||
continue
|
||||
}
|
||||
history := g.history.LoadURLTestHistory(RealTag(g.outbound, detour))
|
||||
history := g.history.LoadURLTestHistory(RealTag(detour, network))
|
||||
if history == nil {
|
||||
continue
|
||||
}
|
||||
@@ -488,12 +503,11 @@ func (g *URLTestGroup) urlTest(ctx context.Context, force bool) (map[string]uint
|
||||
return make(map[string]uint16), nil
|
||||
}
|
||||
defer g.checking.Store(false)
|
||||
result := URLTestOutbounds(ctx, g.outbound, g.history, g.logger, g.outbounds, g.link, g.interval, force)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
default:
|
||||
result := urlTestOutbounds(ctx, g.outbound, g.history, g.logger, g.outbounds, g.link, g.interval, force)
|
||||
if ctx.Err() == nil {
|
||||
g.performUpdateCheck()
|
||||
}
|
||||
g.history.NotifyUpdated()
|
||||
return result, nil
|
||||
}
|
||||
|
||||
@@ -512,9 +526,17 @@ type urlTestBatch struct {
|
||||
groups []adapter.OutboundGroup
|
||||
access sync.Mutex
|
||||
result map[string]uint16
|
||||
stored map[string]*adapter.URLTestHistory
|
||||
deleted []string
|
||||
}
|
||||
|
||||
func URLTestOutbounds(ctx context.Context, outboundManager adapter.OutboundManager, history *urltest.HistoryStorage, logger log.Logger, outbounds []adapter.Outbound, link string, interval time.Duration, force bool) map[string]uint16 {
|
||||
result := urlTestOutbounds(ctx, outboundManager, history, logger, outbounds, link, interval, force)
|
||||
history.NotifyUpdated()
|
||||
return result
|
||||
}
|
||||
|
||||
func urlTestOutbounds(ctx context.Context, outboundManager adapter.OutboundManager, history *urltest.HistoryStorage, logger log.Logger, outbounds []adapter.Outbound, link string, interval time.Duration, force bool) map[string]uint16 {
|
||||
b, _ := batch.New(ctx, batch.WithConcurrencyNum[any](10))
|
||||
testBatch := &urlTestBatch{
|
||||
ctx: ctx,
|
||||
@@ -524,11 +546,13 @@ func URLTestOutbounds(ctx context.Context, outboundManager adapter.OutboundManag
|
||||
batch: b,
|
||||
checked: make(map[string]bool),
|
||||
result: make(map[string]uint16),
|
||||
stored: make(map[string]*adapter.URLTestHistory),
|
||||
}
|
||||
testBatch.test(outbounds, link, interval, force)
|
||||
b.Wait()
|
||||
history.UpdateURLTestHistory(testBatch.stored, testBatch.deleted)
|
||||
for _, outboundGroup := range testBatch.groups {
|
||||
groupHistory := history.LoadURLTestHistory(RealTag(outboundManager, outboundGroup))
|
||||
groupHistory := history.LoadURLTestHistory(RealTag(outboundGroup, N.NetworkTCP))
|
||||
if groupHistory != nil {
|
||||
testBatch.result[outboundGroup.Tag()] = groupHistory.Delay
|
||||
}
|
||||
@@ -585,14 +609,16 @@ func (b *urlTestBatch) test(outbounds []adapter.Outbound, link string, interval
|
||||
return nil, nil
|
||||
}
|
||||
b.logger.Debug("outbound ", tag, " unavailable: ", testResult.err)
|
||||
b.history.DeleteURLTestHistory(tag)
|
||||
b.access.Lock()
|
||||
b.deleted = append(b.deleted, tag)
|
||||
b.access.Unlock()
|
||||
} else {
|
||||
b.logger.Debug("outbound ", tag, " available: ", testResult.delay, "ms")
|
||||
b.history.StoreURLTestHistory(tag, &adapter.URLTestHistory{
|
||||
b.access.Lock()
|
||||
b.stored[tag] = &adapter.URLTestHistory{
|
||||
Time: time.Now(),
|
||||
Delay: testResult.delay,
|
||||
})
|
||||
b.access.Lock()
|
||||
}
|
||||
b.result[tag] = testResult.delay
|
||||
b.access.Unlock()
|
||||
}
|
||||
@@ -602,31 +628,31 @@ func (b *urlTestBatch) test(outbounds []adapter.Outbound, link string, interval
|
||||
}
|
||||
}
|
||||
|
||||
func (g *URLTestGroup) performUpdateCheck() {
|
||||
func (g *URLTestGroup) performUpdateCheck() bool {
|
||||
g.updateAccess.Lock()
|
||||
defer g.updateAccess.Unlock()
|
||||
var (
|
||||
updated bool
|
||||
selected bool
|
||||
)
|
||||
if outbound, exists := g.Select(N.NetworkTCP); outbound != nil && (g.selectedOutboundTCP == nil || (exists && outbound != g.selectedOutboundTCP)) {
|
||||
if g.selectedOutboundTCP != nil {
|
||||
selectedOutboundTCP := g.selectedOutboundTCP.Load()
|
||||
if outbound, _ := g.Select(N.NetworkTCP); outbound != nil && outbound != selectedOutboundTCP {
|
||||
if selectedOutboundTCP != nil {
|
||||
updated = true
|
||||
}
|
||||
g.selectedOutboundTCP = outbound
|
||||
g.selectedOutboundTCP.Store(outbound)
|
||||
selected = true
|
||||
}
|
||||
if outbound, exists := g.Select(N.NetworkUDP); outbound != nil && (g.selectedOutboundUDP == nil || (exists && outbound != g.selectedOutboundUDP)) {
|
||||
if g.selectedOutboundUDP != nil {
|
||||
selectedOutboundUDP := g.selectedOutboundUDP.Load()
|
||||
if outbound, _ := g.Select(N.NetworkUDP); outbound != nil && outbound != selectedOutboundUDP {
|
||||
if selectedOutboundUDP != nil {
|
||||
updated = true
|
||||
}
|
||||
g.selectedOutboundUDP = outbound
|
||||
g.selectedOutboundUDP.Store(outbound)
|
||||
selected = true
|
||||
}
|
||||
if updated {
|
||||
g.interruptGroup.Interrupt(g.interruptExternalConnections)
|
||||
}
|
||||
if selected {
|
||||
g.history.NotifyUpdated()
|
||||
}
|
||||
return selected
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
std_bufio "bufio"
|
||||
"context"
|
||||
"net"
|
||||
|
||||
@@ -99,9 +98,12 @@ func (h *Inbound) NewConnection(ctx context.Context, conn net.Conn, metadata ada
|
||||
}
|
||||
conn = tlsConn
|
||||
}
|
||||
err := http.HandleConnectionEx(ctx, conn, std_bufio.NewReader(conn), h.authenticator, adapter.NewUpstreamHandler(metadata, h.newUserConnection, h.streamUserPacketConnection), metadata.Source, onClose)
|
||||
err := http.HandleConnectionEx(ctx, conn, http.NewReader(conn), h.authenticator, adapter.NewUpstreamHandler(metadata, h.newUserConnection, h.streamUserPacketConnection), metadata.Source, onClose)
|
||||
if err != nil {
|
||||
N.CloseOnHandshakeFailure(conn, onClose, err)
|
||||
conn.Close()
|
||||
if onClose != nil {
|
||||
onClose(err)
|
||||
}
|
||||
h.logger.ErrorContext(ctx, E.Cause(err, "process connection from ", metadata.Source))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,7 +34,13 @@ func NewOutbound(ctx context.Context, router adapter.Router, logger log.ContextL
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
detour, err := tls.NewDialerFromOptions(ctx, logger, outboundDialer, options.Server, common.PtrValueOrDefault(options.TLS))
|
||||
detour, err := tls.NewDialerFromOptions(outboundDialer, tls.ClientOptions{
|
||||
Context: ctx,
|
||||
Logger: logger,
|
||||
ServerAddress: options.Server,
|
||||
Options: common.PtrValueOrDefault(options.TLS),
|
||||
DomainResolver: options.DomainResolver,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -42,12 +48,13 @@ func NewOutbound(ctx context.Context, router adapter.Router, logger log.ContextL
|
||||
Adapter: outbound.NewAdapterWithDialerOptions(C.TypeHTTP, tag, []string{N.NetworkTCP}, options.DialerOptions),
|
||||
logger: logger,
|
||||
client: sHTTP.NewClient(sHTTP.Options{
|
||||
Dialer: detour,
|
||||
Server: options.ServerOptions.Build(),
|
||||
Username: options.Username,
|
||||
Password: options.Password,
|
||||
Path: options.Path,
|
||||
Headers: options.Headers.Build(),
|
||||
Dialer: detour,
|
||||
Server: options.ServerOptions.Build(),
|
||||
Username: options.Username,
|
||||
Password: options.Password,
|
||||
Path: options.Path,
|
||||
Headers: options.Headers.Build(),
|
||||
HandshakeTimeout: C.TCPTimeout,
|
||||
}),
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -43,7 +43,13 @@ func NewOutbound(ctx context.Context, router adapter.Router, logger log.ContextL
|
||||
if options.TLS == nil || !options.TLS.Enabled {
|
||||
return nil, C.ErrTLSRequired
|
||||
}
|
||||
tlsConfig, err := tls.NewClient(ctx, logger, options.Server, common.PtrValueOrDefault(options.TLS))
|
||||
tlsConfig, err := tls.NewClientWithOptions(tls.ClientOptions{
|
||||
Context: ctx,
|
||||
Logger: logger,
|
||||
ServerAddress: options.Server,
|
||||
Options: common.PtrValueOrDefault(options.TLS),
|
||||
DomainResolver: options.DomainResolver,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -54,7 +54,13 @@ func NewOutbound(ctx context.Context, router adapter.Router, logger log.ContextL
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tlsConfig, err := tls.NewClient(ctx, logger, tlsServerAddress, tlsOptions)
|
||||
tlsConfig, err := tls.NewClientWithOptions(tls.ClientOptions{
|
||||
Context: ctx,
|
||||
Logger: logger,
|
||||
ServerAddress: tlsServerAddress,
|
||||
Options: tlsOptions,
|
||||
DomainResolver: options.DomainResolver,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -100,7 +100,7 @@ func (h *Outbound) Start(stage adapter.StartStage, scope *adapter.Scope) error {
|
||||
return h.router.Start(stage, scope)
|
||||
}
|
||||
|
||||
func (h *Outbound) References() []string {
|
||||
func (h *Outbound) References() ([]string, []string) {
|
||||
return h.router.References()
|
||||
}
|
||||
|
||||
|
||||
@@ -100,7 +100,7 @@ func (h *Outbound) Start(stage adapter.StartStage, scope *adapter.Scope) error {
|
||||
return h.router.Start(stage, scope)
|
||||
}
|
||||
|
||||
func (h *Outbound) References() []string {
|
||||
func (h *Outbound) References() ([]string, []string) {
|
||||
return h.router.References()
|
||||
}
|
||||
|
||||
|
||||
@@ -96,7 +96,7 @@ func (h *Outbound) Start(stage adapter.StartStage, scope *adapter.Scope) error {
|
||||
return h.router.Start(stage, scope)
|
||||
}
|
||||
|
||||
func (h *Outbound) References() []string {
|
||||
func (h *Outbound) References() ([]string, []string) {
|
||||
return h.router.References()
|
||||
}
|
||||
|
||||
|
||||
@@ -76,7 +76,7 @@ func (h *Outbound) Start(stage adapter.StartStage, scope *adapter.Scope) error {
|
||||
return h.router.Start(stage, scope)
|
||||
}
|
||||
|
||||
func (h *Outbound) References() []string {
|
||||
func (h *Outbound) References() ([]string, []string) {
|
||||
return h.router.References()
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package mixed
|
||||
|
||||
import (
|
||||
std_bufio "bufio"
|
||||
"context"
|
||||
"net"
|
||||
"time"
|
||||
@@ -104,7 +103,6 @@ func (h *Inbound) UpdateUsers(users []auth.User) {
|
||||
|
||||
func (h *Inbound) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
|
||||
err := h.newConnection(ctx, conn, metadata, onClose)
|
||||
N.CloseOnHandshakeFailure(conn, onClose, err)
|
||||
if err != nil {
|
||||
if E.IsClosedOrCanceled(err) {
|
||||
h.logger.DebugContext(ctx, "connection closed: ", err)
|
||||
@@ -118,21 +116,33 @@ func (h *Inbound) newConnection(ctx context.Context, conn net.Conn, metadata ada
|
||||
if h.tlsConfig != nil {
|
||||
tlsConn, err := tls.ServerHandshake(ctx, conn, h.tlsConfig)
|
||||
if err != nil {
|
||||
return E.Cause(err, "TLS handshake")
|
||||
err = E.Cause(err, "TLS handshake")
|
||||
N.CloseOnHandshakeFailure(conn, onClose, err)
|
||||
return err
|
||||
}
|
||||
conn = tlsConn
|
||||
}
|
||||
reader := std_bufio.NewReader(conn)
|
||||
reader := http.NewReader(conn)
|
||||
headerBytes, err := reader.Peek(1)
|
||||
if err != nil {
|
||||
return E.Cause(err, "peek first byte")
|
||||
err = E.Cause(err, "peek first byte")
|
||||
N.CloseOnHandshakeFailure(conn, onClose, err)
|
||||
return err
|
||||
}
|
||||
switch headerBytes[0] {
|
||||
case socks4.Version, socks5.Version:
|
||||
return socks.HandleConnectionEx(ctx, conn, reader, h.authenticator, adapter.NewUpstreamHandler(metadata, h.newUserConnection, h.streamUserPacketConnection), h.listener, h.udpTimeout, metadata.Source, onClose)
|
||||
err = socks.HandleConnectionEx(ctx, conn, reader.Reader, h.authenticator, adapter.NewUpstreamHandler(metadata, h.newUserConnection, h.streamUserPacketConnection), h.listener, h.udpTimeout, metadata.Source, onClose)
|
||||
N.CloseOnHandshakeFailure(conn, onClose, err)
|
||||
default:
|
||||
return http.HandleConnectionEx(ctx, conn, reader, h.authenticator, adapter.NewUpstreamHandler(metadata, h.newUserConnection, h.streamUserPacketConnection), metadata.Source, onClose)
|
||||
err = http.HandleConnectionEx(ctx, conn, reader, h.authenticator, adapter.NewUpstreamHandler(metadata, h.newUserConnection, h.streamUserPacketConnection), metadata.Source, onClose)
|
||||
if err != nil {
|
||||
conn.Close()
|
||||
}
|
||||
if onClose != nil {
|
||||
onClose(err)
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (h *Inbound) newUserConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
|
||||
|
||||
+111
-24
@@ -6,7 +6,9 @@ import (
|
||||
"context"
|
||||
"encoding/pem"
|
||||
"net"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/sagernet/cronet-go"
|
||||
_ "github.com/sagernet/cronet-go/all"
|
||||
@@ -33,12 +35,20 @@ func RegisterOutbound(registry *outbound.Registry) {
|
||||
outbound.Register[option.NaiveOutboundOptions](registry, C.TypeNaive, NewOutbound)
|
||||
}
|
||||
|
||||
var (
|
||||
_ adapter.OutboundWithMultiplex = (*Outbound)(nil)
|
||||
_ adapter.IdleConnectionKeeper = (*Outbound)(nil)
|
||||
)
|
||||
|
||||
type Outbound struct {
|
||||
outbound.Adapter
|
||||
ctx context.Context
|
||||
logger logger.ContextLogger
|
||||
client *cronet.NaiveClient
|
||||
uotClient *uot.Client
|
||||
ctx context.Context
|
||||
logger logger.ContextLogger
|
||||
client *cronet.NaiveClient
|
||||
uotClient *uot.Client
|
||||
streamAccess sync.Mutex
|
||||
streams int
|
||||
closeIdle bool
|
||||
}
|
||||
|
||||
func NewOutbound(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.NaiveOutboundOptions) (adapter.Outbound, error) {
|
||||
@@ -198,27 +208,26 @@ func NewOutbound(ctx context.Context, router adapter.Router, logger log.ContextL
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var uotClient *uot.Client
|
||||
uotOptions := common.PtrValueOrDefault(options.UDPOverTCP)
|
||||
if uotOptions.Enabled {
|
||||
uotClient = &uot.Client{
|
||||
Dialer: &naiveDialer{client},
|
||||
Version: uotOptions.Version,
|
||||
}
|
||||
}
|
||||
var networks []string
|
||||
if uotClient != nil {
|
||||
if uotOptions.Enabled {
|
||||
networks = []string{N.NetworkTCP, N.NetworkUDP}
|
||||
} else {
|
||||
networks = []string{N.NetworkTCP}
|
||||
}
|
||||
return &Outbound{
|
||||
Adapter: outbound.NewAdapterWithDialerOptions(C.TypeNaive, tag, networks, options.DialerOptions),
|
||||
ctx: ctx,
|
||||
logger: logger,
|
||||
client: client,
|
||||
uotClient: uotClient,
|
||||
}, nil
|
||||
outbound := &Outbound{
|
||||
Adapter: outbound.NewAdapterWithDialerOptions(C.TypeNaive, tag, networks, options.DialerOptions),
|
||||
ctx: ctx,
|
||||
logger: logger,
|
||||
client: client,
|
||||
}
|
||||
if uotOptions.Enabled {
|
||||
outbound.uotClient = &uot.Client{
|
||||
Dialer: (*naiveDialer)(outbound),
|
||||
Version: uotOptions.Version,
|
||||
}
|
||||
}
|
||||
return outbound, nil
|
||||
}
|
||||
|
||||
func (h *Outbound) Start(stage adapter.StartStage, scope *adapter.Scope) error {
|
||||
@@ -238,7 +247,7 @@ func (h *Outbound) DialContext(ctx context.Context, network string, destination
|
||||
switch N.NetworkName(network) {
|
||||
case N.NetworkTCP:
|
||||
h.logger.InfoContext(ctx, "outbound connection to ", destination)
|
||||
return h.client.DialContext(ctx, network, destination)
|
||||
return h.dialStream(ctx, destination)
|
||||
case N.NetworkUDP:
|
||||
if h.uotClient == nil {
|
||||
return nil, E.New("UDP is not supported unless UDP over TCP is enabled")
|
||||
@@ -257,18 +266,96 @@ func (h *Outbound) ListenPacket(ctx context.Context, destination M.Socksaddr) (n
|
||||
return h.uotClient.ListenPacket(ctx, destination)
|
||||
}
|
||||
|
||||
func (h *Outbound) MultiplexEnabled() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (h *Outbound) InterfaceUpdated(ctx context.Context) {
|
||||
h.client.CloseAllConnections()
|
||||
}
|
||||
|
||||
func (h *Outbound) SetKeepIdleConnections(keep bool) {
|
||||
h.streamAccess.Lock()
|
||||
h.closeIdle = !keep
|
||||
h.streamAccess.Unlock()
|
||||
if !keep {
|
||||
h.CloseIdleConnections()
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Outbound) CloseIdleConnections() {
|
||||
h.streamAccess.Lock()
|
||||
defer h.streamAccess.Unlock()
|
||||
if h.streams == 0 {
|
||||
h.client.CloseAllConnections()
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Outbound) dialStream(ctx context.Context, destination M.Socksaddr) (net.Conn, error) {
|
||||
h.streamAccess.Lock()
|
||||
h.streams++
|
||||
h.streamAccess.Unlock()
|
||||
keepSession := adapter.KeepSessionFromContext(ctx)
|
||||
connection, err := h.client.DialEarly(ctx, destination)
|
||||
if err != nil {
|
||||
h.releaseStream(keepSession)
|
||||
return nil, err
|
||||
}
|
||||
err = connection.HandshakeContext(ctx)
|
||||
if err != nil {
|
||||
connection.Close()
|
||||
h.releaseStream(keepSession)
|
||||
return nil, err
|
||||
}
|
||||
return &streamConn{NaiveConn: connection, onClose: func() { h.releaseStream(keepSession) }}, nil
|
||||
}
|
||||
|
||||
func (h *Outbound) releaseStream(keepSession bool) {
|
||||
h.streamAccess.Lock()
|
||||
defer h.streamAccess.Unlock()
|
||||
h.streams--
|
||||
if h.closeIdle && !keepSession && h.streams == 0 {
|
||||
h.client.CloseAllConnections()
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Outbound) Client() *cronet.NaiveClient {
|
||||
return h.client
|
||||
}
|
||||
|
||||
type naiveDialer struct {
|
||||
*cronet.NaiveClient
|
||||
}
|
||||
type naiveDialer Outbound
|
||||
|
||||
func (d *naiveDialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
|
||||
return d.NaiveClient.DialContext(ctx, network, destination)
|
||||
if N.NetworkName(network) != N.NetworkTCP {
|
||||
return nil, os.ErrInvalid
|
||||
}
|
||||
return (*Outbound)(d).dialStream(ctx, destination)
|
||||
}
|
||||
|
||||
func (d *naiveDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
|
||||
return nil, os.ErrInvalid
|
||||
}
|
||||
|
||||
type streamConn struct {
|
||||
cronet.NaiveConn
|
||||
closeOnce sync.Once
|
||||
onClose func()
|
||||
}
|
||||
|
||||
func (c *streamConn) Close() error {
|
||||
err := c.NaiveConn.Close()
|
||||
c.closeOnce.Do(c.onClose)
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *streamConn) Upstream() any {
|
||||
return c.NaiveConn
|
||||
}
|
||||
|
||||
func (c *streamConn) ReaderReplaceable() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (c *streamConn) WriterReplaceable() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -46,6 +46,9 @@ type Endpoint struct {
|
||||
loopContext context.Context
|
||||
cancelLoop context.CancelFunc
|
||||
dnsRouter adapter.DNSRouter
|
||||
outboundManager adapter.OutboundManager
|
||||
detour string
|
||||
clientOptions openconnect.ClientOptions
|
||||
client *openconnect.Client
|
||||
device openconnecttransport.Device
|
||||
server string
|
||||
@@ -107,10 +110,12 @@ func NewEndpoint(ctx context.Context, router adapter.Router, logger log.ContextL
|
||||
router: router,
|
||||
logger: logger,
|
||||
},
|
||||
loopContext: loopContext,
|
||||
cancelLoop: cancelLoop,
|
||||
dnsRouter: service.FromContext[adapter.DNSRouter](ctx),
|
||||
statusUpdated: make(chan struct{}),
|
||||
loopContext: loopContext,
|
||||
cancelLoop: cancelLoop,
|
||||
dnsRouter: service.FromContext[adapter.DNSRouter](ctx),
|
||||
outboundManager: service.FromContext[adapter.OutboundManager](ctx),
|
||||
detour: options.Detour,
|
||||
statusUpdated: make(chan struct{}),
|
||||
}
|
||||
openConnectEndpoint.state.Store(new(clientState))
|
||||
success := false
|
||||
@@ -187,6 +192,7 @@ func NewEndpoint(ctx context.Context, router adapter.Router, logger log.ContextL
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
openConnectEndpoint.clientOptions = clientOptions
|
||||
openConnectEndpoint.client = client
|
||||
success = true
|
||||
return openConnectEndpoint, nil
|
||||
@@ -336,6 +342,7 @@ func (e *Endpoint) buildClientOptions(options option.OpenConnectEndpointOptions,
|
||||
},
|
||||
FormEntries: formEntries,
|
||||
Dialer: outboundDialer,
|
||||
ProxiedDialer: options.Detour != "",
|
||||
Logger: e.logger,
|
||||
OnTunnelConfiguration: e.handleTunnelConfiguration,
|
||||
}, nil
|
||||
@@ -418,6 +425,21 @@ func (e *Endpoint) updateState(update func(state *clientState)) {
|
||||
func (e *Endpoint) Start(stage adapter.StartStage, scope *adapter.Scope) error {
|
||||
switch stage {
|
||||
case adapter.StartStateInitialize:
|
||||
if e.clientOptions.ProxiedDialer {
|
||||
detour, loaded := e.outboundManager.Outbound(e.detour)
|
||||
if loaded && detour.Type() == C.TypeDirect {
|
||||
e.clientOptions.ProxiedDialer = false
|
||||
client, err := openconnect.NewClient(e.clientOptions)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = e.client.Close()
|
||||
if err != nil {
|
||||
return E.Cause(err, "close client")
|
||||
}
|
||||
e.client = client
|
||||
}
|
||||
}
|
||||
scope.Add(func() error {
|
||||
e.notifyStatusUpdated()
|
||||
return nil
|
||||
@@ -478,10 +500,10 @@ func (e *Endpoint) readLoop(ctx context.Context) {
|
||||
err = e.device.WriteInboundBuffers(packetBuffers)
|
||||
buf.ReleaseMulti(packetBuffers)
|
||||
if err != nil {
|
||||
err = E.Cause(err, "write packet to device")
|
||||
e.logger.Error(err)
|
||||
e.setTerminalError(err)
|
||||
return
|
||||
if E.IsCanceled(err) || ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
e.logger.Debug(E.Cause(err, "write packet to device"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -230,6 +230,10 @@ func (t *DNSTransport) updateConfiguration(configuration openconnecttransport.Co
|
||||
}
|
||||
}
|
||||
|
||||
func (t *DNSTransport) References() ([]string, []string) {
|
||||
return []string{t.endpointTag}, nil
|
||||
}
|
||||
|
||||
func (t *DNSTransport) Reset() {
|
||||
t.access.RLock()
|
||||
resolvers := t.collectResolversLocked()
|
||||
|
||||
@@ -654,10 +654,10 @@ func (c *ClientEndpoint) readLoop(ctx context.Context) {
|
||||
err = c.device.WriteInboundBuffers(packetBuffers)
|
||||
buf.ReleaseMulti(packetBuffers)
|
||||
if err != nil {
|
||||
err = E.Cause(err, "write packet to device")
|
||||
c.logger.Error(err)
|
||||
c.setTerminalError(err)
|
||||
return
|
||||
if E.IsCanceled(err) || ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
c.logger.Debug(E.Cause(err, "write packet to device"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -277,6 +277,10 @@ func (t *DNSTransport) createResolver(server ovpntransport.DNSServer, address ne
|
||||
return dnsTransport.NewHTTPSRaw(t.TransportAdapter, t.logger, t.dialer, destination, http.Header{}, M.SocksaddrFrom(address.Addr(), port), tlsConfig), nil
|
||||
}
|
||||
|
||||
func (t *DNSTransport) References() ([]string, []string) {
|
||||
return []string{t.endpointTag}, nil
|
||||
}
|
||||
|
||||
func (t *DNSTransport) Reset() {
|
||||
t.access.RLock()
|
||||
resolvers := t.collectResolversLocked()
|
||||
|
||||
@@ -627,8 +627,10 @@ func (s *ServerEndpoint) readLoop(ctx context.Context) {
|
||||
err = s.device.WriteInboundBuffers(packetBuffers)
|
||||
buf.ReleaseMulti(packetBuffers)
|
||||
if err != nil {
|
||||
s.logger.Error(E.Cause(err, "write packet to device"))
|
||||
return
|
||||
if E.IsCanceled(err) || ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
s.logger.Debug(E.Cause(err, "write packet to device"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,10 +7,10 @@ import (
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
"github.com/sagernet/sing-box/adapter/inbound"
|
||||
"github.com/sagernet/sing-box/common/listener"
|
||||
"github.com/sagernet/sing-box/common/redir"
|
||||
C "github.com/sagernet/sing-box/constant"
|
||||
"github.com/sagernet/sing-box/log"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
"github.com/sagernet/sing/common/control"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
N "github.com/sagernet/sing/common/network"
|
||||
)
|
||||
@@ -55,7 +55,7 @@ func (h *Redirect) Start(stage adapter.StartStage, scope *adapter.Scope) error {
|
||||
}
|
||||
|
||||
func (h *Redirect) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
|
||||
destination, err := redir.GetOriginalDestination(conn)
|
||||
destination, err := control.GetOriginalDestination(conn)
|
||||
if err != nil {
|
||||
conn.Close()
|
||||
h.logger.ErrorContext(ctx, "process connection from ", conn.RemoteAddr(), ": get redirect destination: ", err)
|
||||
@@ -64,6 +64,7 @@ func (h *Redirect) NewConnection(ctx context.Context, conn net.Conn, metadata ad
|
||||
metadata.Inbound = h.Tag()
|
||||
metadata.InboundType = h.Type()
|
||||
metadata.Destination = M.SocksaddrFromNetIP(destination)
|
||||
metadata.OriginDestination = metadata.Destination
|
||||
h.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination)
|
||||
h.router.RouteConnectionEx(ctx, conn, metadata, onClose)
|
||||
}
|
||||
|
||||
+41
-13
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"net"
|
||||
"net/netip"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
@@ -129,7 +130,7 @@ func (t *TProxy) preparePacketConnection(source M.Socksaddr, destination M.Socks
|
||||
destination: destination,
|
||||
}
|
||||
return true, ctx, writer, func(it error) {
|
||||
common.Close(common.PtrOrNil(writer.conn))
|
||||
writer.close()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -138,31 +139,58 @@ type tproxyPacketWriter struct {
|
||||
listener *listener.Listener
|
||||
source netip.AddrPort
|
||||
destination M.Socksaddr
|
||||
access sync.Mutex
|
||||
conn *net.UDPConn
|
||||
closed bool
|
||||
}
|
||||
|
||||
func (w *tproxyPacketWriter) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error {
|
||||
defer buffer.Release()
|
||||
conn := w.conn
|
||||
if w.destination == destination && conn != nil {
|
||||
_, err := conn.WriteToUDPAddrPort(buffer.Bytes(), w.source)
|
||||
if destination != w.destination {
|
||||
conn, err := w.listenPacket(destination)
|
||||
if err != nil {
|
||||
w.conn = nil
|
||||
return err
|
||||
}
|
||||
defer conn.Close()
|
||||
return common.Error(conn.WriteToUDPAddrPort(buffer.Bytes(), w.source))
|
||||
}
|
||||
conn, err := w.cachedConn()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return common.Error(conn.WriteToUDPAddrPort(buffer.Bytes(), w.source))
|
||||
}
|
||||
|
||||
func (w *tproxyPacketWriter) cachedConn() (*net.UDPConn, error) {
|
||||
w.access.Lock()
|
||||
defer w.access.Unlock()
|
||||
if w.closed {
|
||||
return nil, net.ErrClosed
|
||||
}
|
||||
if w.conn == nil {
|
||||
conn, err := w.listenPacket(w.destination)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
w.conn = conn
|
||||
}
|
||||
return w.conn, nil
|
||||
}
|
||||
|
||||
func (w *tproxyPacketWriter) listenPacket(destination M.Socksaddr) (*net.UDPConn, error) {
|
||||
var listenConfig net.ListenConfig
|
||||
listenConfig.Control = control.Append(listenConfig.Control, control.ReuseAddr())
|
||||
listenConfig.Control = control.Append(listenConfig.Control, redir.TProxyWriteBack())
|
||||
packetConn, err := w.listener.ListenPacket(listenConfig, w.ctx, "udp", destination.String())
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
udpConn := packetConn.(*net.UDPConn)
|
||||
if w.destination == destination {
|
||||
w.conn = udpConn
|
||||
} else {
|
||||
defer udpConn.Close()
|
||||
}
|
||||
return common.Error(udpConn.WriteToUDPAddrPort(buffer.Bytes(), w.source))
|
||||
return packetConn.(*net.UDPConn), nil
|
||||
}
|
||||
|
||||
func (w *tproxyPacketWriter) close() {
|
||||
w.access.Lock()
|
||||
defer w.access.Unlock()
|
||||
w.closed = true
|
||||
common.Close(common.PtrOrNil(w.conn))
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"context"
|
||||
"net"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
@@ -36,14 +35,17 @@ var (
|
||||
|
||||
type MultiInbound struct {
|
||||
inbound.Adapter
|
||||
ctx context.Context
|
||||
router adapter.ConnectionRouterEx
|
||||
logger logger.ContextLogger
|
||||
listener *listener.Listener
|
||||
service shadowsocks.MultiService[int]
|
||||
usersAccess sync.RWMutex
|
||||
users []option.ShadowsocksUser
|
||||
tracker adapter.SSMTracker
|
||||
ctx context.Context
|
||||
router adapter.ConnectionRouterEx
|
||||
logger logger.ContextLogger
|
||||
listener *listener.Listener
|
||||
service shadowsocks.MultiService[multiUser]
|
||||
tracker adapter.SSMTracker
|
||||
}
|
||||
|
||||
type multiUser struct {
|
||||
index int
|
||||
name string
|
||||
}
|
||||
|
||||
func newMultiInbound(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.ShadowsocksInboundOptions) (*MultiInbound, error) {
|
||||
@@ -64,9 +66,9 @@ func newMultiInbound(ctx context.Context, router adapter.Router, logger log.Cont
|
||||
} else {
|
||||
udpTimeout = C.UDPTimeout
|
||||
}
|
||||
var service shadowsocks.MultiService[int]
|
||||
var service shadowsocks.MultiService[multiUser]
|
||||
if common.Contains(shadowaead_2022.List, options.Method) {
|
||||
service, err = shadowaead_2022.NewMultiServiceWithPassword[int](
|
||||
service, err = shadowaead_2022.NewMultiServiceWithPassword[multiUser](
|
||||
options.Method,
|
||||
options.Password,
|
||||
int64(udpTimeout.Seconds()),
|
||||
@@ -74,7 +76,7 @@ func newMultiInbound(ctx context.Context, router adapter.Router, logger log.Cont
|
||||
ntp.TimeFuncFromContext(ctx),
|
||||
)
|
||||
} else if common.Contains(shadowaead.List, options.Method) {
|
||||
service, err = shadowaead.NewMultiService[int](
|
||||
service, err = shadowaead.NewMultiService[multiUser](
|
||||
options.Method,
|
||||
int64(udpTimeout.Seconds()),
|
||||
adapter.NewLegacyUpstreamHandler(adapter.InboundContext{}, inbound.newConnection, inbound.newPacketConnection, inbound),
|
||||
@@ -86,8 +88,8 @@ func newMultiInbound(ctx context.Context, router adapter.Router, logger log.Cont
|
||||
return nil, err
|
||||
}
|
||||
if len(options.Users) > 0 {
|
||||
err = service.UpdateUsersWithPasswords(common.MapIndexed(options.Users, func(index int, user option.ShadowsocksUser) int {
|
||||
return index
|
||||
err = service.UpdateUsersWithPasswords(common.MapIndexed(options.Users, func(index int, user option.ShadowsocksUser) multiUser {
|
||||
return multiUser{index: index, name: user.Name}
|
||||
}), common.Map(options.Users, func(user option.ShadowsocksUser) string {
|
||||
return user.Password
|
||||
}))
|
||||
@@ -96,7 +98,6 @@ func newMultiInbound(ctx context.Context, router adapter.Router, logger log.Cont
|
||||
}
|
||||
}
|
||||
inbound.service = service
|
||||
inbound.users = options.Users
|
||||
inbound.listener = listener.New(listener.Options{
|
||||
Context: ctx,
|
||||
Logger: logger,
|
||||
@@ -126,29 +127,9 @@ func (h *MultiInbound) SetTracker(tracker adapter.SSMTracker) {
|
||||
}
|
||||
|
||||
func (h *MultiInbound) UpdateUsers(users []string, uPSKs []string) error {
|
||||
h.usersAccess.Lock()
|
||||
defer h.usersAccess.Unlock()
|
||||
err := h.service.UpdateUsersWithPasswords(common.MapIndexed(users, func(index int, user string) int {
|
||||
return index
|
||||
return h.service.UpdateUsersWithPasswords(common.MapIndexed(users, func(index int, user string) multiUser {
|
||||
return multiUser{index: index, name: user}
|
||||
}), uPSKs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
h.users = common.Map(users, func(user string) option.ShadowsocksUser {
|
||||
return option.ShadowsocksUser{
|
||||
Name: user,
|
||||
}
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *MultiInbound) userName(userIndex int) string {
|
||||
h.usersAccess.RLock()
|
||||
defer h.usersAccess.RUnlock()
|
||||
if userIndex >= len(h.users) {
|
||||
return ""
|
||||
}
|
||||
return h.users[userIndex].Name
|
||||
}
|
||||
|
||||
//nolint:staticcheck
|
||||
@@ -173,17 +154,17 @@ func (h *MultiInbound) NewPacket(buffer *buf.Buffer, source M.Socksaddr) {
|
||||
}
|
||||
|
||||
func (h *MultiInbound) newConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
|
||||
userIndex, loaded := auth.UserFromContext[int](ctx)
|
||||
user, loaded := auth.UserFromContext[multiUser](ctx)
|
||||
if !loaded {
|
||||
return os.ErrInvalid
|
||||
}
|
||||
user := h.userName(userIndex)
|
||||
if user == "" {
|
||||
user = F.ToString(userIndex)
|
||||
userName := user.name
|
||||
if userName == "" {
|
||||
userName = F.ToString(user.index)
|
||||
} else {
|
||||
metadata.User = user
|
||||
metadata.User = userName
|
||||
}
|
||||
h.logger.InfoContext(ctx, "[", user, "] inbound connection to ", metadata.Destination)
|
||||
h.logger.InfoContext(ctx, "[", userName, "] inbound connection to ", metadata.Destination)
|
||||
metadata.Inbound = h.Tag()
|
||||
metadata.InboundType = h.Type()
|
||||
//nolint:staticcheck
|
||||
@@ -196,19 +177,19 @@ func (h *MultiInbound) newConnection(ctx context.Context, conn net.Conn, metadat
|
||||
}
|
||||
|
||||
func (h *MultiInbound) newPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error {
|
||||
userIndex, loaded := auth.UserFromContext[int](ctx)
|
||||
user, loaded := auth.UserFromContext[multiUser](ctx)
|
||||
if !loaded {
|
||||
return os.ErrInvalid
|
||||
}
|
||||
user := h.userName(userIndex)
|
||||
if user == "" {
|
||||
user = F.ToString(userIndex)
|
||||
userName := user.name
|
||||
if userName == "" {
|
||||
userName = F.ToString(user.index)
|
||||
} else {
|
||||
metadata.User = user
|
||||
metadata.User = userName
|
||||
}
|
||||
ctx = log.ContextWithNewID(ctx)
|
||||
h.logger.InfoContext(ctx, "[", user, "] inbound packet connection from ", metadata.Source)
|
||||
h.logger.InfoContext(ctx, "[", user, "] inbound packet connection to ", metadata.Destination)
|
||||
h.logger.InfoContext(ctx, "[", userName, "] inbound packet connection from ", metadata.Source)
|
||||
h.logger.InfoContext(ctx, "[", userName, "] inbound packet connection to ", metadata.Destination)
|
||||
metadata.Inbound = h.Tag()
|
||||
metadata.InboundType = h.Type()
|
||||
//nolint:staticcheck
|
||||
|
||||
@@ -148,6 +148,6 @@ func (h *inboundHandler) NewConnectionEx(ctx context.Context, conn net.Conn, sou
|
||||
h.router.RouteConnectionEx(ctx, conn, metadata, onClose)
|
||||
}
|
||||
|
||||
func (h *Inbound) References() []string {
|
||||
return h.references
|
||||
func (h *Inbound) References() ([]string, []string) {
|
||||
return h.references, nil
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"github.com/sagernet/sing-box/option"
|
||||
"github.com/sagernet/sing-shadowtls"
|
||||
"github.com/sagernet/sing/common"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
N "github.com/sagernet/sing/common/network"
|
||||
)
|
||||
@@ -38,12 +39,21 @@ func NewOutbound(ctx context.Context, router adapter.Router, logger log.ContextL
|
||||
if options.Version == 0 {
|
||||
options.Version = 1
|
||||
}
|
||||
if options.Version != 2 && options.TLS.ECH != nil && options.TLS.ECH.Enabled {
|
||||
return nil, E.New("ECH is only supported in ShadowTLS v2")
|
||||
}
|
||||
|
||||
if options.Version == 1 {
|
||||
options.TLS.MinVersion = "1.2"
|
||||
options.TLS.MaxVersion = "1.2"
|
||||
}
|
||||
tlsConfig, err := tls.NewClient(ctx, logger, options.Server, common.PtrValueOrDefault(options.TLS))
|
||||
tlsConfig, err := tls.NewClientWithOptions(tls.ClientOptions{
|
||||
Context: ctx,
|
||||
Logger: logger,
|
||||
ServerAddress: options.Server,
|
||||
Options: common.PtrValueOrDefault(options.TLS),
|
||||
DomainResolver: options.DomainResolver,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -55,17 +65,24 @@ func NewOutbound(ctx context.Context, router adapter.Router, logger log.ContextL
|
||||
return common.Error(tls.ClientHandshake(ctx, conn, tlsConfig))
|
||||
}
|
||||
case 3:
|
||||
if idConfig, loaded := tlsConfig.(tls.WithSessionIDGenerator); loaded {
|
||||
if _, loaded := tlsConfig.(tls.WithSessionIDGenerator); loaded {
|
||||
tlsHandshakeFunc = func(ctx context.Context, conn net.Conn, sessionIDGenerator shadowtls.TLSSessionIDGeneratorFunc) error {
|
||||
idConfig.SetSessionIDGenerator(sessionIDGenerator)
|
||||
return common.Error(tls.ClientHandshake(ctx, conn, tlsConfig))
|
||||
handshakeConfig := tlsConfig.Clone()
|
||||
handshakeConfig.(tls.WithSessionIDGenerator).SetSessionIDGenerator(sessionIDGenerator)
|
||||
return common.Error(tls.ClientHandshake(ctx, conn, handshakeConfig))
|
||||
}
|
||||
} else {
|
||||
stdTLSConfig, err := tlsConfig.STDConfig()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tlsHandshakeFunc = shadowtls.DefaultTLSHandshakeFunc(options.Password, stdTLSConfig)
|
||||
defaultHandshakeFunc := shadowtls.DefaultTLSHandshakeFunc(options.Password, stdTLSConfig)
|
||||
handshakeTimeout := tlsConfig.HandshakeTimeout()
|
||||
tlsHandshakeFunc = func(ctx context.Context, conn net.Conn, sessionIDGenerator shadowtls.TLSSessionIDGeneratorFunc) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, handshakeTimeout)
|
||||
defer cancel()
|
||||
return defaultHandshakeFunc(ctx, conn, sessionIDGenerator)
|
||||
}
|
||||
}
|
||||
}
|
||||
outboundDialer, err := dialer.New(ctx, options.DialerOptions, options.ServerIsDomain())
|
||||
|
||||
@@ -112,6 +112,9 @@ func (h *Outbound) DialContext(ctx context.Context, network string, destination
|
||||
switch networkName {
|
||||
case N.NetworkTCP:
|
||||
h.logger.InfoContext(ctx, "outbound connection to ", destination)
|
||||
if h.reuse {
|
||||
return h.client.DialContext(adapter.ContextForMultiplexSession(ctx), destination)
|
||||
}
|
||||
return h.client.DialContext(ctx, destination)
|
||||
case N.NetworkUDP:
|
||||
h.logger.InfoContext(ctx, "outbound packet connection to ", destination)
|
||||
|
||||
@@ -50,11 +50,13 @@ func NewOutbound(ctx context.Context, router adapter.Router, logger log.ContextL
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
client := socks.NewClient(outboundDialer, options.ServerOptions.Build(), version, options.Username, options.Password)
|
||||
client.SetHandshakeTimeout(C.TCPTimeout)
|
||||
outbound := &Outbound{
|
||||
Adapter: outbound.NewAdapterWithDialerOptions(C.TypeSOCKS, tag, options.Network.Build(), options.DialerOptions),
|
||||
dnsRouter: service.FromContext[adapter.DNSRouter](ctx),
|
||||
logger: logger,
|
||||
client: socks.NewClient(outboundDialer, options.ServerOptions.Build(), version, options.Username, options.Password),
|
||||
client: client,
|
||||
resolve: version == socks.Version4,
|
||||
}
|
||||
uotOptions := common.PtrValueOrDefault(options.UDPOverTCP)
|
||||
|
||||
+14
-15
@@ -141,24 +141,23 @@ func (s *Outbound) connect(ctx context.Context) (client *ssh.Client, err error)
|
||||
return s.client, nil
|
||||
}
|
||||
|
||||
conn, err := s.dialer.DialContext(ctx, N.NetworkTCP, s.serverAddr)
|
||||
conn, err := s.dialer.DialContext(adapter.ContextForMultiplexSession(ctx), N.NetworkTCP, s.serverAddr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if ctx.Done() != nil {
|
||||
handshakeConn := conn
|
||||
stopContext := context.AfterFunc(ctx, func() {
|
||||
_ = handshakeConn.Close()
|
||||
})
|
||||
defer func() {
|
||||
if !stopContext() {
|
||||
s.client = nil
|
||||
s.clientConn = nil
|
||||
client = nil
|
||||
err = ctx.Err()
|
||||
}
|
||||
}()
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, C.TCPTimeout)
|
||||
defer cancel()
|
||||
stopContext := context.AfterFunc(ctx, func() {
|
||||
_ = conn.Close()
|
||||
})
|
||||
defer func() {
|
||||
if !stopContext() {
|
||||
s.client = nil
|
||||
s.clientConn = nil
|
||||
client = nil
|
||||
err = E.Cause(ctx.Err(), "connect to ssh server")
|
||||
}
|
||||
}()
|
||||
config := &ssh.ClientConfig{
|
||||
User: s.user,
|
||||
Auth: s.authMethod,
|
||||
|
||||
@@ -24,7 +24,10 @@ func RegisterCertificateProvider(registry *certificate.Registry) {
|
||||
certificate.Register[option.TailscaleCertificateProviderOptions](registry, C.TypeTailscale, NewCertificateProvider)
|
||||
}
|
||||
|
||||
var _ adapter.CertificateProviderService = (*CertificateProvider)(nil)
|
||||
var (
|
||||
_ adapter.CertificateProviderService = (*CertificateProvider)(nil)
|
||||
_ adapter.Referrer = (*CertificateProvider)(nil)
|
||||
)
|
||||
|
||||
type CertificateProvider struct {
|
||||
certificate.Adapter
|
||||
@@ -63,6 +66,10 @@ func NewCertificateProvider(ctx context.Context, _ log.ContextLogger, tag string
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (p *CertificateProvider) References() ([]string, []string) {
|
||||
return []string{p.endpointTag}, nil
|
||||
}
|
||||
|
||||
func (p *CertificateProvider) Start(stage adapter.StartStage, scope *adapter.Scope) error {
|
||||
if stage != adapter.StartStateStart {
|
||||
return nil
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
@@ -28,6 +29,7 @@ import (
|
||||
"github.com/sagernet/sing/service"
|
||||
nDNS "github.com/sagernet/tailscale/net/dns"
|
||||
nDNSResolver "github.com/sagernet/tailscale/net/dns/resolver"
|
||||
"github.com/sagernet/tailscale/net/tsaddr"
|
||||
"github.com/sagernet/tailscale/types/dnstype"
|
||||
"github.com/sagernet/tailscale/util/dnsname"
|
||||
"github.com/sagernet/tailscale/wgengine/router"
|
||||
@@ -55,9 +57,8 @@ type DNSTransport struct {
|
||||
access sync.RWMutex
|
||||
routePrefixes []netip.Prefix
|
||||
routes map[string][]adapter.DNSTransport
|
||||
hosts map[string][]netip.Addr
|
||||
magicHosts nDNSResolver.MagicDNSHosts
|
||||
searchDomains []string
|
||||
domains tailnetDomains
|
||||
defaultResolvers []adapter.DNSTransport
|
||||
resolverScope *adapter.Scope
|
||||
}
|
||||
@@ -100,8 +101,8 @@ func (t *DNSTransport) Start(stage adapter.StartStage, scope *adapter.Scope) err
|
||||
resolverScope := t.resolverScope
|
||||
t.routePrefixes = nil
|
||||
t.routes = nil
|
||||
t.hosts = nil
|
||||
t.magicHosts = nil
|
||||
t.domains = tailnetDomains{}
|
||||
t.defaultResolvers = nil
|
||||
t.resolverScope = nil
|
||||
t.access.Unlock()
|
||||
@@ -113,6 +114,10 @@ func (t *DNSTransport) Start(stage adapter.StartStage, scope *adapter.Scope) err
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *DNSTransport) References() ([]string, []string) {
|
||||
return []string{t.endpointTag}, nil
|
||||
}
|
||||
|
||||
func (t *DNSTransport) Reset() {
|
||||
t.access.RLock()
|
||||
transports := t.collectResolversLocked()
|
||||
@@ -148,13 +153,7 @@ func (t *DNSTransport) updateDNSServers(routeConfig *router.Config, dnsConfig *n
|
||||
}
|
||||
routes[mDNS.CanonicalName(domain.WithTrailingDot())] = myResolvers
|
||||
}
|
||||
hosts := make(map[string][]netip.Addr)
|
||||
for domain, addresses := range dnsConfig.Hosts {
|
||||
hosts[domain.WithTrailingDot()] = addresses
|
||||
}
|
||||
searchDomains := common.Map(dnsConfig.SearchDomains, func(it dnsname.FQDN) string {
|
||||
return it.WithTrailingDot()
|
||||
})
|
||||
domains := newTailnetDomains(dnsConfig)
|
||||
var defaultResolvers []adapter.DNSTransport
|
||||
for _, resolver := range dnsConfig.DefaultResolvers {
|
||||
myResolver, err := t.createResolver(resolverScope, directDialerOnce, resolver)
|
||||
@@ -168,9 +167,8 @@ func (t *DNSTransport) updateDNSServers(routeConfig *router.Config, dnsConfig *n
|
||||
oldResolverScope := t.resolverScope
|
||||
t.routePrefixes = routePrefixes
|
||||
t.routes = routes
|
||||
t.hosts = hosts
|
||||
t.magicHosts = t.endpoint.server.ExportLocalBackend().ExportMagicDNSHosts()
|
||||
t.searchDomains = searchDomains
|
||||
t.domains = domains
|
||||
t.defaultResolvers = defaultResolvers
|
||||
t.resolverScope = resolverScope
|
||||
t.access.Unlock()
|
||||
@@ -180,10 +178,10 @@ func (t *DNSTransport) updateDNSServers(routeConfig *router.Config, dnsConfig *n
|
||||
}
|
||||
|
||||
if len(defaultResolvers) > 0 {
|
||||
t.logger.Notice("updated ", len(routes), " routes, ", len(hosts), " hosts, ", len(searchDomains), " search domains, default resolvers: ",
|
||||
t.logger.Notice("updated ", len(routes), " routes, ", len(dnsConfig.Hosts), " hosts, ", len(domains.searchDomains), " search domains, default resolvers: ",
|
||||
strings.Join(common.Map(dnsConfig.DefaultResolvers, func(it *dnstype.Resolver) string { return it.Addr }), " "))
|
||||
} else {
|
||||
t.logger.Notice("updated ", len(routes), " routes, ", len(hosts), " hosts, ", len(searchDomains), " search domains")
|
||||
t.logger.Notice("updated ", len(routes), " routes, ", len(dnsConfig.Hosts), " hosts, ", len(domains.searchDomains), " search domains")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -287,26 +285,86 @@ func (t *DNSTransport) Raw() bool {
|
||||
|
||||
func (t *DNSTransport) PreferredDomain(domain string) bool {
|
||||
t.access.RLock()
|
||||
hosts := t.hosts
|
||||
domains := t.domains
|
||||
magicHosts := t.magicHosts
|
||||
routes := t.routes
|
||||
searchDomains := t.searchDomains
|
||||
t.access.RUnlock()
|
||||
if _, loaded := lookupHosts(hosts, magicHosts, domain); loaded {
|
||||
return domains.match(magicHosts, mDNS.CanonicalName(domain), t.acceptSearchDomain)
|
||||
}
|
||||
|
||||
type tailnetDomains struct {
|
||||
hosts map[string][]netip.Addr
|
||||
searchDomains []string
|
||||
localSuffixes []string
|
||||
forwardedSuffixes []string
|
||||
}
|
||||
|
||||
func newTailnetDomains(dnsConfig *nDNS.Config) tailnetDomains {
|
||||
domains := tailnetDomains{
|
||||
hosts: make(map[string][]netip.Addr, len(dnsConfig.Hosts)),
|
||||
searchDomains: common.Map(dnsConfig.SearchDomains, func(it dnsname.FQDN) string {
|
||||
return mDNS.CanonicalName(it.WithTrailingDot())
|
||||
}),
|
||||
}
|
||||
for domain, addresses := range dnsConfig.Hosts {
|
||||
domains.hosts[mDNS.CanonicalName(domain.WithTrailingDot())] = addresses
|
||||
}
|
||||
for domain, resolvers := range dnsConfig.Routes {
|
||||
suffix := mDNS.CanonicalName(domain.WithTrailingDot())
|
||||
if len(resolvers) == 0 {
|
||||
domains.localSuffixes = append(domains.localSuffixes, suffix)
|
||||
} else {
|
||||
domains.forwardedSuffixes = append(domains.forwardedSuffixes, suffix)
|
||||
}
|
||||
}
|
||||
common.SortBy(domains.forwardedSuffixes, func(it string) int {
|
||||
return -mDNS.CountLabel(it)
|
||||
})
|
||||
return domains
|
||||
}
|
||||
|
||||
func (d tailnetDomains) match(magicHosts nDNSResolver.MagicDNSHosts, domain string, expandSearchDomains bool) bool {
|
||||
routeSuffix, _ := d.matchRoute(domain)
|
||||
if routeSuffix != "" {
|
||||
return true
|
||||
}
|
||||
if t.acceptSearchDomain && len(searchDomains) > 0 && mDNS.CountLabel(domain) == 1 {
|
||||
_, loaded := lookupHosts(d.hosts, magicHosts, domain)
|
||||
if loaded {
|
||||
return true
|
||||
}
|
||||
canonicalDomain := mDNS.CanonicalName(domain)
|
||||
for suffix := range routes {
|
||||
if matchDomainSuffix(canonicalDomain, suffix) {
|
||||
if !expandSearchDomains || mDNS.CountLabel(domain) != 1 {
|
||||
return false
|
||||
}
|
||||
for _, searchDomain := range d.searchDomains {
|
||||
expandedDomain := domain + searchDomain
|
||||
_, loaded = lookupHosts(d.hosts, magicHosts, expandedDomain)
|
||||
if loaded {
|
||||
return true
|
||||
}
|
||||
_, forwarded := d.matchRoute(expandedDomain)
|
||||
if forwarded {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Tailscale's resolver answers names under resolver-less routes from hosts only
|
||||
// and returns NXDOMAIN for the rest without forwarding, even when a forwarded
|
||||
// route such as ts.net also matches; otherwise the longest forwarded route wins.
|
||||
func (d tailnetDomains) matchRoute(domain string) (suffix string, forwarded bool) {
|
||||
for _, localSuffix := range d.localSuffixes {
|
||||
if matchDomainSuffix(domain, localSuffix) {
|
||||
return localSuffix, false
|
||||
}
|
||||
}
|
||||
for _, forwardedSuffix := range d.forwardedSuffixes {
|
||||
if matchDomainSuffix(domain, forwardedSuffix) {
|
||||
return forwardedSuffix, true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
func matchDomainSuffix(domain string, suffix string) bool {
|
||||
if suffix == "." || suffix == "" {
|
||||
return true
|
||||
@@ -349,7 +407,7 @@ func (t *DNSTransport) ExchangeAsync(ctx context.Context, message *mDNS.Msg, cal
|
||||
|
||||
func (t *DNSTransport) exchangeWithSearchDomains(ctx context.Context, message *mDNS.Msg, callback func(response *mDNS.Msg, err error)) {
|
||||
t.access.RLock()
|
||||
searchDomains := t.searchDomains
|
||||
searchDomains := t.domains.searchDomains
|
||||
t.access.RUnlock()
|
||||
if len(searchDomains) == 0 {
|
||||
callback(nil, dns.RcodeNameError)
|
||||
@@ -393,13 +451,14 @@ func (t *DNSTransport) exchangeOnce(ctx context.Context, message *mDNS.Msg, allo
|
||||
question := message.Question[0]
|
||||
|
||||
t.access.RLock()
|
||||
hosts := t.hosts
|
||||
domains := t.domains
|
||||
magicHosts := t.magicHosts
|
||||
routes := t.routes
|
||||
defaultResolvers := t.defaultResolvers
|
||||
t.access.RUnlock()
|
||||
|
||||
addresses, hostsLoaded := lookupHosts(hosts, magicHosts, question.Name)
|
||||
canonicalName := mDNS.CanonicalName(question.Name)
|
||||
addresses, hostsLoaded := lookupHosts(domains.hosts, magicHosts, canonicalName)
|
||||
if hostsLoaded {
|
||||
switch question.Qtype {
|
||||
case mDNS.TypeA, mDNS.TypeAAAA:
|
||||
@@ -409,23 +468,21 @@ func (t *DNSTransport) exchangeOnce(ctx context.Context, message *mDNS.Msg, allo
|
||||
}
|
||||
return
|
||||
}
|
||||
canonicalName := mDNS.CanonicalName(question.Name)
|
||||
for domainSuffix, transports := range routes {
|
||||
if matchDomainSuffix(canonicalName, domainSuffix) {
|
||||
if len(transports) == 0 {
|
||||
callback(&mDNS.Msg{
|
||||
MsgHdr: mDNS.MsgHdr{
|
||||
Id: message.Id,
|
||||
Rcode: mDNS.RcodeNameError,
|
||||
Response: true,
|
||||
},
|
||||
Question: []mDNS.Question{question},
|
||||
}, nil)
|
||||
return
|
||||
}
|
||||
transport.ExchangeSequential(ctx, resolverExchangers(transports, message), nil, callback)
|
||||
return
|
||||
}
|
||||
routeSuffix, forwarded := domains.matchRoute(canonicalName)
|
||||
if forwarded {
|
||||
transport.ExchangeSequential(ctx, resolverExchangers(routes[routeSuffix], message), nil, callback)
|
||||
return
|
||||
}
|
||||
if routeSuffix != "" {
|
||||
callback(&mDNS.Msg{
|
||||
MsgHdr: mDNS.MsgHdr{
|
||||
Id: message.Id,
|
||||
Rcode: mDNS.RcodeNameError,
|
||||
Response: true,
|
||||
},
|
||||
Question: []mDNS.Question{question},
|
||||
}, nil)
|
||||
return
|
||||
}
|
||||
if allowDefaultResolvers {
|
||||
if len(defaultResolvers) > 0 {
|
||||
@@ -439,6 +496,14 @@ func (t *DNSTransport) exchangeOnce(ctx context.Context, message *mDNS.Msg, allo
|
||||
}
|
||||
|
||||
func lookupHosts(hosts map[string][]netip.Addr, magicHosts nDNSResolver.MagicDNSHosts, name string) ([]netip.Addr, bool) {
|
||||
fqdn, err := dnsname.ToFQDN(name)
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
viaAddress, isVia := lookupViaHost(fqdn)
|
||||
if isVia {
|
||||
return []netip.Addr{viaAddress}, true
|
||||
}
|
||||
addresses, loaded := hosts[name]
|
||||
if loaded {
|
||||
return addresses, true
|
||||
@@ -446,10 +511,6 @@ func lookupHosts(hosts map[string][]netip.Addr, magicHosts nDNSResolver.MagicDNS
|
||||
if magicHosts == nil {
|
||||
return nil, false
|
||||
}
|
||||
fqdn, err := dnsname.ToFQDN(name)
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
addresses, loaded = magicHosts.LookupHost(fqdn)
|
||||
if loaded {
|
||||
return addresses, true
|
||||
@@ -462,6 +523,26 @@ func lookupHosts(hosts map[string][]netip.Addr, magicHosts nDNSResolver.MagicDNS
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// Tailscale's resolver answers <a-b-c-d>-via-<site ID>, bare or under ts.net or
|
||||
// tailscale.net, with its 4via6 address ahead of hosts and routes.
|
||||
func lookupViaHost(fqdn dnsname.FQDN) (netip.Addr, bool) {
|
||||
firstLabel, parent, _ := strings.Cut(fqdn.WithoutTrailingDot(), ".")
|
||||
addressLabel, siteIDLabel, isVia := strings.Cut(firstLabel, "-via-")
|
||||
if !isVia || parent != "" && !dnsname.HasSuffix(parent, "ts.net") && !dnsname.HasSuffix(parent, "tailscale.net") {
|
||||
return netip.Addr{}, false
|
||||
}
|
||||
address, err := netip.ParseAddr(strings.ReplaceAll(addressLabel, "-", "."))
|
||||
if err != nil || !address.Is4() {
|
||||
return netip.Addr{}, false
|
||||
}
|
||||
siteID, err := strconv.ParseUint(siteIDLabel, 0, 32)
|
||||
if err != nil {
|
||||
return netip.Addr{}, false
|
||||
}
|
||||
viaPrefix := common.Must1(tsaddr.MapVia(uint32(siteID), netip.PrefixFrom(address, 32)))
|
||||
return viaPrefix.Addr(), true
|
||||
}
|
||||
|
||||
func resolverExchangers(resolvers []adapter.DNSTransport, message *mDNS.Msg) []transport.AsyncExchanger {
|
||||
return common.Map(resolvers, func(resolver adapter.DNSTransport) transport.AsyncExchanger {
|
||||
return func(ctx context.Context, callback func(response *mDNS.Msg, err error)) {
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
@@ -49,6 +50,7 @@ import (
|
||||
_ "github.com/sagernet/tailscale/feature/relayserver"
|
||||
"github.com/sagernet/tailscale/ipn"
|
||||
tsDNS "github.com/sagernet/tailscale/net/dns"
|
||||
nDNSResolver "github.com/sagernet/tailscale/net/dns/resolver"
|
||||
"github.com/sagernet/tailscale/net/netmon"
|
||||
"github.com/sagernet/tailscale/net/netns"
|
||||
"github.com/sagernet/tailscale/net/tsaddr"
|
||||
@@ -68,6 +70,7 @@ var (
|
||||
_ adapter.OutboundWithPreferredRoutes = (*Endpoint)(nil)
|
||||
_ adapter.InterfaceUpdateListener = (*Endpoint)(nil)
|
||||
_ adapter.Referrer = (*Endpoint)(nil)
|
||||
_ adapter.OutboundWithMultiplex = (*Endpoint)(nil)
|
||||
_ dialer.PacketDialerWithDestination = (*Endpoint)(nil)
|
||||
_ tun.Port = (*Endpoint)(nil)
|
||||
)
|
||||
@@ -98,12 +101,10 @@ type Endpoint struct {
|
||||
onReconfigHook wgengine.ReconfigListener
|
||||
sshReconfigHook wgengine.ReconfigListener
|
||||
|
||||
cfg *wgcfg.Config
|
||||
routerCfg *router.Config
|
||||
dnsCfg *tsDNS.Config
|
||||
routeDomains common.TypedValue[map[string]bool]
|
||||
routeSuffixes common.TypedValue[[]string]
|
||||
searchDomains atomic.Bool
|
||||
cfg *wgcfg.Config
|
||||
routerCfg *router.Config
|
||||
dnsCfg *tsDNS.Config
|
||||
domains atomic.Pointer[tailnetDomains]
|
||||
|
||||
acceptRoutes bool
|
||||
exitNode string
|
||||
@@ -248,11 +249,11 @@ func NewEndpoint(ctx context.Context, router adapter.Router, logger log.ContextL
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (t *Endpoint) References() []string {
|
||||
func (t *Endpoint) References() ([]string, []string) {
|
||||
if t.detour == "" {
|
||||
return nil
|
||||
return nil, nil
|
||||
}
|
||||
return []string{t.detour}
|
||||
return []string{t.detour}, nil
|
||||
}
|
||||
|
||||
func (t *Endpoint) Start(stage adapter.StartStage, scope *adapter.Scope) error {
|
||||
@@ -283,8 +284,11 @@ func (t *Endpoint) start(scope *adapter.Scope) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if interfaceMonitor := t.network.InterfaceMonitor(); interfaceMonitor != nil {
|
||||
interfaceFinder := t.network.InterfaceFinder()
|
||||
netmon.RegisterInterfaceGetter(func() ([]netmon.Interface, error) {
|
||||
return common.Map(t.network.InterfaceFinder().Interfaces(), func(it control.Interface) netmon.Interface {
|
||||
return common.Map(interfaceFinder.Interfaces(), func(it control.Interface) netmon.Interface {
|
||||
return netmon.Interface{
|
||||
Interface: &net.Interface{
|
||||
Index: it.Index,
|
||||
@@ -306,6 +310,20 @@ func (t *Endpoint) start(scope *adapter.Scope) error {
|
||||
netmon.RegisterInterfaceGetter(nil)
|
||||
return nil
|
||||
})
|
||||
netmon.SetDefaultRouteFunc(func() (netmon.DefaultRouteDetails, error) {
|
||||
defaultInterface := interfaceMonitor.DefaultInterface()
|
||||
if defaultInterface == nil {
|
||||
return netmon.DefaultRouteDetails{}, nil
|
||||
}
|
||||
return netmon.DefaultRouteDetails{
|
||||
InterfaceName: defaultInterface.Name,
|
||||
InterfaceIndex: defaultInterface.Index,
|
||||
}, nil
|
||||
})
|
||||
scope.Add(func() error {
|
||||
netmon.SetDefaultRouteFunc(nil)
|
||||
return nil
|
||||
})
|
||||
}
|
||||
if t.systemInterface {
|
||||
mtu := t.systemInterfaceMTU
|
||||
@@ -426,6 +444,25 @@ func (t *Endpoint) postStart(scope *adapter.Scope) error {
|
||||
return err
|
||||
}
|
||||
scope.Add(t.server.Close)
|
||||
if t.network.InterfaceMonitor() != nil {
|
||||
netMon := t.server.Sys().NetMon.Get()
|
||||
interfaceFinder := t.network.InterfaceFinder()
|
||||
var interfacesAccess sync.Mutex
|
||||
lastInterfaces := interfaceFinder.Interfaces()
|
||||
interfaceUpdateElement := interfaceFinder.RegisterInterfaceUpdateCallback(func(interfaces []control.Interface) {
|
||||
interfacesAccess.Lock()
|
||||
changed := !slices.EqualFunc(lastInterfaces, interfaces, control.Interface.Equals)
|
||||
lastInterfaces = interfaces
|
||||
interfacesAccess.Unlock()
|
||||
if changed {
|
||||
netMon.Poll()
|
||||
}
|
||||
})
|
||||
scope.Add(func() error {
|
||||
interfaceFinder.UnregisterInterfaceUpdateCallback(interfaceUpdateElement)
|
||||
return nil
|
||||
})
|
||||
}
|
||||
fallbackTCPCloser := t.server.RegisterFallbackTCPHandler(func(src, dst netip.AddrPort) (handler func(net.Conn), intercept bool) {
|
||||
return func(conn net.Conn) {
|
||||
ctx := log.ContextWithNewID(t.ctx)
|
||||
@@ -742,6 +779,10 @@ func (t *Endpoint) Logout(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *Endpoint) MultiplexEnabled() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (t *Endpoint) InterfaceUpdated(ctx context.Context) {
|
||||
if !t.started.Load() {
|
||||
return
|
||||
@@ -939,26 +980,19 @@ func (t *Endpoint) NewPacketConnectionEx(ctx context.Context, conn N.PacketConn,
|
||||
}
|
||||
|
||||
func (t *Endpoint) PreferredDomain(metadata *adapter.InboundContext, domain string) bool {
|
||||
routeDomains := t.routeDomains.Load()
|
||||
if routeDomains == nil {
|
||||
domains := t.domains.Load()
|
||||
if domains == nil {
|
||||
return false
|
||||
}
|
||||
domain = strings.ToLower(domain)
|
||||
if routeDomains[domain] {
|
||||
canonicalDomain := mDNS.CanonicalName(domain)
|
||||
if slices.Contains(domains.searchDomains, canonicalDomain) {
|
||||
return true
|
||||
}
|
||||
var magicHosts nDNSResolver.MagicDNSHosts
|
||||
if t.started.Load() {
|
||||
magicHosts := t.server.ExportLocalBackend().ExportMagicDNSHosts()
|
||||
if _, found := lookupHosts(nil, magicHosts, domain); found {
|
||||
return true
|
||||
}
|
||||
magicHosts = t.server.ExportLocalBackend().ExportMagicDNSHosts()
|
||||
}
|
||||
for _, suffix := range t.routeSuffixes.Load() {
|
||||
if matchDomainSuffix(domain, suffix) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return !strings.Contains(domain, ".") && t.searchDomains.Load()
|
||||
return domains.match(magicHosts, canonicalDomain, !strings.Contains(domain, "."))
|
||||
}
|
||||
|
||||
func (t *Endpoint) PreferredAddress(metadata *adapter.InboundContext, address netip.Addr) bool {
|
||||
@@ -992,20 +1026,8 @@ func (t *Endpoint) onReconfig(cfg *wgcfg.Config, routerCfg *router.Config, dnsCf
|
||||
t.routerCfg = routerCfg
|
||||
t.dnsCfg = dnsCfg
|
||||
|
||||
routeDomains := make(map[string]bool)
|
||||
for fqdn := range dnsCfg.Hosts {
|
||||
routeDomains[fqdn.WithoutTrailingDot()] = true
|
||||
}
|
||||
for _, fqdn := range dnsCfg.SearchDomains {
|
||||
routeDomains[fqdn.WithoutTrailingDot()] = true
|
||||
}
|
||||
routeSuffixes := make([]string, 0, len(dnsCfg.Routes))
|
||||
for fqdn := range dnsCfg.Routes {
|
||||
routeSuffixes = append(routeSuffixes, strings.ToLower(fqdn.WithoutTrailingDot()))
|
||||
}
|
||||
t.routeDomains.Store(routeDomains)
|
||||
t.routeSuffixes.Store(routeSuffixes)
|
||||
t.searchDomains.Store(len(dnsCfg.SearchDomains) > 0)
|
||||
domains := newTailnetDomains(dnsCfg)
|
||||
t.domains.Store(&domains)
|
||||
|
||||
if t.onReconfigHook != nil {
|
||||
t.onReconfigHook(cfg, routerCfg, dnsCfg)
|
||||
@@ -1085,5 +1107,7 @@ func (t *peerDNSQueryHandler) HandlePeerDNSQuery(ctx context.Context, query []by
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return response.Pack()
|
||||
compressedResponse := response.Copy()
|
||||
compressedResponse.Compress = true
|
||||
return compressedResponse.Pack()
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
|
||||
gliderssh "github.com/sagernet/gliderssh"
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
)
|
||||
|
||||
func isPrivilegedUser() bool {
|
||||
@@ -21,10 +22,21 @@ func requestedUserMatchesProcess(localUser *adapter.PlatformUser) (bool, error)
|
||||
return localUser.Uid == os.Getuid() && localUser.Gid == os.Getgid(), nil
|
||||
}
|
||||
|
||||
// verifyShellIdentity is a no-op on Unix: spawned shells and sftp-server drop to the
|
||||
// requested user via setCredential, so the child already runs as that user.
|
||||
func verifyShellIdentity(_ adapter.PlatformInterface, _ *adapter.PlatformUser) error {
|
||||
return nil
|
||||
func verifyShellIdentity(platformInterface adapter.PlatformInterface, localUser *adapter.PlatformUser) error {
|
||||
if platformInterface != nil && platformInterface.UsePlatformShell() {
|
||||
return nil
|
||||
}
|
||||
match, err := requestedUserMatchesProcess(localUser)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if match {
|
||||
return nil
|
||||
}
|
||||
if !isPrivilegedUser() {
|
||||
return E.New("switching to local user ", localUser.Username, " requires sing-box to run as root")
|
||||
}
|
||||
return checkSwitchUserPrivilege(localUser)
|
||||
}
|
||||
|
||||
func systemHostKeyPath() string {
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
//go:build with_gvisor && linux
|
||||
|
||||
package tailssh
|
||||
|
||||
import (
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
func checkSwitchUserPrivilege(localUser *adapter.PlatformUser) error {
|
||||
header := unix.CapUserHeader{Version: unix.LINUX_CAPABILITY_VERSION_3}
|
||||
var data [2]unix.CapUserData
|
||||
err := unix.Capget(&header, &data[0])
|
||||
if err != nil {
|
||||
return E.Cause(err, "query process capabilities")
|
||||
}
|
||||
const required = 1<<unix.CAP_SETUID | 1<<unix.CAP_SETGID
|
||||
if data[0].Effective&required != required {
|
||||
return E.New("switching to local user ", localUser.Username, " requires CAP_SETUID and CAP_SETGID")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
//go:build with_gvisor && !windows && !linux
|
||||
|
||||
package tailssh
|
||||
|
||||
import "github.com/sagernet/sing-box/adapter"
|
||||
|
||||
func checkSwitchUserPrivilege(_ *adapter.PlatformUser) error {
|
||||
return nil
|
||||
}
|
||||
@@ -4,7 +4,6 @@ package tailscale
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"sync"
|
||||
@@ -75,9 +74,6 @@ func (a *tunDeviceAdapter) Read(bufs [][]byte, sizes []int, offset int) (count i
|
||||
a.debugPacket("read", readBuf[singTun.PacketOffset:n])
|
||||
return 1, nil
|
||||
}
|
||||
if errors.Is(err, singTun.ErrTooManySegments) {
|
||||
err = wgTun.ErrTooManySegments
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
|
||||
|
||||
+28
-17
@@ -39,7 +39,6 @@ type Outbound struct {
|
||||
proxy *proxybridge.Bridge
|
||||
startConf *tor.StartConf
|
||||
options map[string]string
|
||||
events chan control.Event
|
||||
socksClient *socks.Client
|
||||
}
|
||||
|
||||
@@ -133,7 +132,6 @@ func (t *Outbound) Start(stage adapter.StartStage, scope *adapter.Scope) error {
|
||||
}
|
||||
|
||||
var torLogEvents = []control.EventCode{
|
||||
control.EventCodeLogDebug,
|
||||
control.EventCodeLogErr,
|
||||
control.EventCodeLogInfo,
|
||||
control.EventCodeLogNotice,
|
||||
@@ -141,21 +139,34 @@ var torLogEvents = []control.EventCode{
|
||||
}
|
||||
|
||||
func (t *Outbound) start(scope *adapter.Scope) error {
|
||||
t.events = make(chan control.Event, 8)
|
||||
scope.Add(func() error {
|
||||
close(t.events)
|
||||
return nil
|
||||
})
|
||||
torInstance, err := tor.Start(t.ctx, t.startConf)
|
||||
torInstance, err := tor.Start(context.WithoutCancel(t.ctx), t.startConf)
|
||||
if err != nil {
|
||||
return E.New(strings.ToLower(err.Error()))
|
||||
}
|
||||
controlConn := torInstance.Control
|
||||
events := make(chan control.Event, 8)
|
||||
eventLoopDone := make(chan struct{})
|
||||
go t.recvLoop(events)
|
||||
scope.Add(func() error {
|
||||
<-eventLoopDone
|
||||
close(events)
|
||||
return nil
|
||||
})
|
||||
scope.Add(torInstance.Close)
|
||||
err = torInstance.Control.AddEventListener(t.events, torLogEvents...)
|
||||
err = t.configure(controlConn, events)
|
||||
go func() {
|
||||
for controlConn.HandleNextEvent() == nil {
|
||||
}
|
||||
close(eventLoopDone)
|
||||
}()
|
||||
return err
|
||||
}
|
||||
|
||||
func (t *Outbound) configure(controlConn *control.Conn, events chan<- control.Event) error {
|
||||
err := controlConn.AddEventListener(events, torLogEvents...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
go t.recvLoop()
|
||||
proxyPort := "127.0.0.1:" + F.ToString(t.proxy.Port())
|
||||
proxyUsername := t.proxy.Username()
|
||||
proxyPassword := t.proxy.Password()
|
||||
@@ -167,7 +178,7 @@ func (t *Outbound) start(scope *adapter.Scope) error {
|
||||
control.NewKeyVal("Socks5ProxyUsername", proxyUsername),
|
||||
control.NewKeyVal("Socks5ProxyPassword", proxyPassword),
|
||||
}
|
||||
err = torInstance.Control.ResetConf(confOptions...)
|
||||
err = controlConn.ResetConf(confOptions...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -179,17 +190,17 @@ func (t *Outbound) start(scope *adapter.Scope) error {
|
||||
"Socks5ProxyPassword":
|
||||
continue
|
||||
}
|
||||
err = torInstance.Control.SetConf(control.NewKeyVal(key, value))
|
||||
err = controlConn.SetConf(control.NewKeyVal(key, value))
|
||||
if err != nil {
|
||||
return E.Cause(err, "set ", key, "=", value)
|
||||
}
|
||||
}
|
||||
}
|
||||
err = torInstance.EnableNetwork(t.ctx, true)
|
||||
err = controlConn.SetConf(control.NewKeyVal("DisableNetwork", "0"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
info, err := torInstance.Control.GetInfo("net/listeners/socks")
|
||||
info, err := controlConn.GetInfo("net/listeners/socks")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -202,13 +213,13 @@ func (t *Outbound) start(scope *adapter.Scope) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *Outbound) recvLoop() {
|
||||
for rawEvent := range t.events {
|
||||
func (t *Outbound) recvLoop(events <-chan control.Event) {
|
||||
for rawEvent := range events {
|
||||
switch event := rawEvent.(type) {
|
||||
case *control.LogEvent:
|
||||
event.Raw = strings.ToLower(event.Raw)
|
||||
switch event.Severity {
|
||||
case control.EventCodeLogDebug, control.EventCodeLogInfo:
|
||||
case control.EventCodeLogInfo:
|
||||
t.logger.Trace(event.Raw)
|
||||
case control.EventCodeLogNotice:
|
||||
if strings.Contains(event.Raw, "disablenetwork") || strings.Contains(event.Raw, "socks listener") {
|
||||
|
||||
@@ -273,6 +273,6 @@ func (h *inboundTransportHandler) NewConnectionEx(ctx context.Context, conn net.
|
||||
(*Inbound)(h).NewConnection(ctx, conn, metadata, onClose)
|
||||
}
|
||||
|
||||
func (h *Inbound) References() []string {
|
||||
return h.references
|
||||
func (h *Inbound) References() ([]string, []string) {
|
||||
return h.references, nil
|
||||
}
|
||||
|
||||
@@ -58,17 +58,20 @@ func NewOutbound(ctx context.Context, router adapter.Router, logger log.ContextL
|
||||
}
|
||||
if options.TLS != nil {
|
||||
outbound.tlsConfig, err = tls.NewClientWithOptions(tls.ClientOptions{
|
||||
Context: ctx,
|
||||
Logger: logger,
|
||||
ServerAddress: options.Server,
|
||||
Options: common.PtrValueOrDefault(options.TLS),
|
||||
Context: ctx,
|
||||
Logger: logger,
|
||||
ServerAddress: options.Server,
|
||||
Options: common.PtrValueOrDefault(options.TLS),
|
||||
DomainResolver: options.DomainResolver,
|
||||
KTLSCompatible: common.PtrValueOrDefault(options.Transport).Type == "" &&
|
||||
!common.PtrValueOrDefault(options.Multiplex).Enabled,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
outbound.tlsDialer = tls.NewDialer(outboundDialer, outbound.tlsConfig)
|
||||
if outbound.tlsConfig != nil {
|
||||
outbound.tlsDialer = tls.NewDialer(outboundDialer, outbound.tlsConfig)
|
||||
}
|
||||
}
|
||||
if options.Transport != nil {
|
||||
outbound.transport, err = v2ray.NewClientTransport(ctx, logger, outbound.dialer, outbound.serverAddr, common.PtrValueOrDefault(options.Transport), outbound.tlsConfig)
|
||||
|
||||
@@ -47,7 +47,13 @@ func NewOutbound(ctx context.Context, router adapter.Router, logger log.ContextL
|
||||
if options.TLS == nil || !options.TLS.Enabled {
|
||||
return nil, C.ErrTLSRequired
|
||||
}
|
||||
tlsConfig, err := tls.NewClient(ctx, logger, options.Server, common.PtrValueOrDefault(options.TLS))
|
||||
tlsConfig, err := tls.NewClientWithOptions(tls.ClientOptions{
|
||||
Context: ctx,
|
||||
Logger: logger,
|
||||
ServerAddress: options.Server,
|
||||
Options: common.PtrValueOrDefault(options.TLS),
|
||||
DomainResolver: options.DomainResolver,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
+64
-25
@@ -5,7 +5,6 @@ import (
|
||||
"net"
|
||||
"net/netip"
|
||||
"os"
|
||||
"runtime"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -46,10 +45,13 @@ type Inbound struct {
|
||||
udpFiltering tun.NATFiltering
|
||||
udpNATMax uint32
|
||||
dnsHijackAddress []netip.Addr
|
||||
dnsHijackByPort bool
|
||||
redirectDNSAddress netip.Addr
|
||||
stack string
|
||||
tunIf tun.Tun
|
||||
tunStack tun.Stack
|
||||
platformInterface adapter.PlatformInterface
|
||||
usePlatformInterface bool
|
||||
platformOptions option.TunPlatformOptions
|
||||
enableAutoRedirect bool
|
||||
disableNFTables bool
|
||||
@@ -101,6 +103,7 @@ func NewInbound(ctx context.Context, router adapter.Router, logger log.ContextLo
|
||||
})
|
||||
|
||||
platformInterface := service.FromContext[adapter.PlatformInterface](ctx)
|
||||
usePlatformInterface := platformInterface != nil && platformInterface.UsePlatformInterface()
|
||||
if options.NetNs != "" && !C.IsLinux {
|
||||
return nil, E.New("`netns` is only supported on Linux")
|
||||
}
|
||||
@@ -117,7 +120,7 @@ func NewInbound(ctx context.Context, router adapter.Router, logger log.ContextLo
|
||||
}
|
||||
}
|
||||
var enableGSO bool
|
||||
if C.IsLinux && platformInterface == nil {
|
||||
if C.IsLinux && !usePlatformInterface {
|
||||
enableGSO = (options.Stack == "gvisor" && tunMTU < 49152)
|
||||
}
|
||||
var udpTimeout time.Duration
|
||||
@@ -143,7 +146,7 @@ func NewInbound(ctx context.Context, router adapter.Router, logger log.ContextLo
|
||||
}
|
||||
|
||||
tableIndex := options.IPRoute2TableIndex
|
||||
if tableIndex == 0 {
|
||||
if tableIndex == 0 && options.AutoRoute {
|
||||
tableIndex = tun.DefaultIPRoute2TableIndex
|
||||
}
|
||||
ruleIndex := options.IPRoute2RuleIndex
|
||||
@@ -232,13 +235,14 @@ func NewInbound(ctx context.Context, router adapter.Router, logger log.ContextLo
|
||||
Logger: logger,
|
||||
EXP_MultiPendingPackets: multiPendingPackets,
|
||||
},
|
||||
udpTimeout: udpTimeout,
|
||||
udpMapping: tun.NATMapping(options.UDPMapping),
|
||||
udpFiltering: tun.NATFiltering(options.UDPFiltering),
|
||||
udpNATMax: options.UDPNATMax,
|
||||
stack: options.Stack,
|
||||
platformInterface: platformInterface,
|
||||
platformOptions: common.PtrValueOrDefault(options.Platform),
|
||||
udpTimeout: udpTimeout,
|
||||
udpMapping: tun.NATMapping(options.UDPMapping),
|
||||
udpFiltering: tun.NATFiltering(options.UDPFiltering),
|
||||
udpNATMax: options.UDPNATMax,
|
||||
stack: options.Stack,
|
||||
platformInterface: platformInterface,
|
||||
usePlatformInterface: usePlatformInterface,
|
||||
platformOptions: common.PtrValueOrDefault(options.Platform),
|
||||
}
|
||||
for _, routeAddressSet := range options.RouteAddressSet {
|
||||
ruleSet, loaded := router.RuleSet(routeAddressSet)
|
||||
@@ -264,6 +268,13 @@ func NewInbound(ctx context.Context, router adapter.Router, logger log.ContextLo
|
||||
disableNFTables, parseErr := strconv.ParseBool(os.Getenv("DISABLE_NFTABLES"))
|
||||
inbound.enableAutoRedirect = true
|
||||
inbound.disableNFTables = parseErr == nil && disableNFTables
|
||||
inbound.dnsHijackByPort = inbound.tunOptions.DNSModeOrDefault() == tun.DNSModeHijack && len(options.DNSAddress) == 0
|
||||
if inbound.tunOptions.DNSModeOrDefault() == tun.DNSModeHijack && len(options.DNSAddress) > 0 {
|
||||
inet6DNSAddress, _ := inbound.tunOptions.Inet6DNSAddress()
|
||||
if len(inet6DNSAddress) > 0 {
|
||||
inbound.redirectDNSAddress = inet6DNSAddress[0]
|
||||
}
|
||||
}
|
||||
if !C.IsAndroid {
|
||||
inbound.tunOptions.AutoRedirectMarkMode = true
|
||||
if options.NetNs == "" {
|
||||
@@ -326,7 +337,7 @@ func (t *Inbound) Start(stage adapter.StartStage, scope *adapter.Scope) error {
|
||||
t.dnsHijackAddress = append(inet4DNSAddress, inet6DNSAddress...)
|
||||
}
|
||||
case adapter.StartStateStart:
|
||||
if t.platformInterface == nil &&
|
||||
if !t.usePlatformInterface &&
|
||||
((C.IsLinux && !t.tunOptions.GSO) || (C.IsDarwin && !t.tunOptions.EXP_MultiPendingPackets)) {
|
||||
outboundManager := service.FromContext[adapter.OutboundManager](t.ctx)
|
||||
endpointManager := service.FromContext[adapter.EndpointManager](t.ctx)
|
||||
@@ -381,7 +392,7 @@ func (t *Inbound) Start(stage adapter.StartStage, scope *adapter.Scope) error {
|
||||
return E.Cause(err, "initialize auto-redirect")
|
||||
}
|
||||
}
|
||||
if t.platformInterface == nil || C.IsWindows {
|
||||
if !t.usePlatformInterface {
|
||||
for _, routeRuleSet := range t.routeRuleSet {
|
||||
ipSets := routeRuleSet.ExtractIPSet()
|
||||
if len(ipSets) == 0 {
|
||||
@@ -416,7 +427,7 @@ func (t *Inbound) Start(stage adapter.StartStage, scope *adapter.Scope) error {
|
||||
var tunInterface tun.Tun
|
||||
monitor := taskmonitor.New(t.logger, C.StartTimeout)
|
||||
tunOptions := t.tunOptions
|
||||
if t.autoRedirect == nil && !(runtime.GOOS == "android" && t.platformInterface != nil) {
|
||||
if t.autoRedirect == nil {
|
||||
for _, ipSet := range t.routeAddressSet {
|
||||
for _, prefix := range ipSet.Prefixes() {
|
||||
if prefix.Addr().Is4() {
|
||||
@@ -437,7 +448,7 @@ func (t *Inbound) Start(stage adapter.StartStage, scope *adapter.Scope) error {
|
||||
}
|
||||
}
|
||||
monitor.Start("open interface")
|
||||
if t.platformInterface != nil && t.platformInterface.UsePlatformInterface() {
|
||||
if t.usePlatformInterface {
|
||||
tunInterface, err = t.platformInterface.OpenInterface(&tunOptions, t.platformOptions)
|
||||
} else {
|
||||
tunInterface, err = tun.New(tunOptions)
|
||||
@@ -525,6 +536,20 @@ func (t *Inbound) InterfaceUpdated(ctx context.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
func (t *Inbound) FlushSystemDNSCache() {
|
||||
linuxTUN, isLinuxTUN := t.tunIf.(tun.LinuxTUN)
|
||||
if !isLinuxTUN {
|
||||
return
|
||||
}
|
||||
serviceManager := service.FromContext[adapter.ServiceManager](t.ctx)
|
||||
if slices.ContainsFunc(serviceManager.Services(), func(it adapter.Service) bool {
|
||||
return it.Type() == C.TypeResolved
|
||||
}) {
|
||||
return
|
||||
}
|
||||
linuxTUN.FlushDNSCache()
|
||||
}
|
||||
|
||||
func (t *Inbound) JudgeFlow(network uint8, source netip.AddrPort, destination netip.AddrPort, firstPacket []byte) tun.FlowVerdict {
|
||||
if slices.Contains(t.dnsHijackAddress, destination.Addr()) {
|
||||
if network == uint8(header.UDPProtocolNumber) {
|
||||
@@ -532,9 +557,20 @@ func (t *Inbound) JudgeFlow(network uint8, source netip.AddrPort, destination ne
|
||||
}
|
||||
return tun.FlowVerdict{Action: tun.ActionAccept}
|
||||
}
|
||||
if t.dnsHijackByPort && destination.Port() == 53 &&
|
||||
(network == uint8(header.TCPProtocolNumber) || network == uint8(header.UDPProtocolNumber)) {
|
||||
if network == uint8(header.UDPProtocolNumber) {
|
||||
return tun.FlowVerdict{Action: tun.ActionHijackDNS}
|
||||
}
|
||||
return tun.FlowVerdict{Action: tun.ActionAccept}
|
||||
}
|
||||
return adapter.JudgeFlow(t.router, t.tag, C.TypeTun, network, source, destination, firstPacket)
|
||||
}
|
||||
|
||||
func (t *Inbound) isDNSHijackDestination(destination M.Socksaddr) bool {
|
||||
return slices.Contains(t.dnsHijackAddress, destination.Addr) || t.dnsHijackByPort && destination.Port == 53
|
||||
}
|
||||
|
||||
func (t *Inbound) NewDNSPacket(payload []byte, source M.Socksaddr, destination M.Socksaddr, writer N.PacketWriter) {
|
||||
ctx := log.ContextWithNewID(t.ctx)
|
||||
var metadata adapter.InboundContext
|
||||
@@ -555,7 +591,7 @@ func (t *Inbound) NewConnectionEx(ctx context.Context, conn net.Conn, source M.S
|
||||
metadata.InboundType = C.TypeTun
|
||||
metadata.Source = source
|
||||
metadata.Destination = destination
|
||||
if slices.Contains(t.dnsHijackAddress, destination.Addr) {
|
||||
if t.isDNSHijackDestination(destination) {
|
||||
metadata.Protocol = C.ProtocolDNS
|
||||
}
|
||||
if metadata.Protocol == C.ProtocolDNS {
|
||||
@@ -574,10 +610,8 @@ func (t *Inbound) NewPacketConnectionEx(ctx context.Context, conn N.PacketConn,
|
||||
metadata.InboundType = C.TypeTun
|
||||
metadata.Source = source
|
||||
metadata.Destination = destination
|
||||
for _, dnsHijackAddress := range t.dnsHijackAddress {
|
||||
if destination.Addr == dnsHijackAddress {
|
||||
metadata.Protocol = C.ProtocolDNS
|
||||
}
|
||||
if t.isDNSHijackDestination(destination) {
|
||||
metadata.Protocol = C.ProtocolDNS
|
||||
}
|
||||
if metadata.Protocol == C.ProtocolDNS {
|
||||
t.logger.InfoContext(ctx, "inbound DNS packet connection from ", metadata.Source)
|
||||
@@ -594,17 +628,22 @@ func (t *autoRedirectHandler) JudgeFlow(network uint8, source netip.AddrPort, de
|
||||
return (*Inbound)(t).JudgeFlow(network, source, destination, firstPacket)
|
||||
}
|
||||
|
||||
func (t *autoRedirectHandler) redirectDNSDestination(source M.Socksaddr, destination M.Socksaddr) M.Socksaddr {
|
||||
if t.redirectDNSAddress.IsValid() && destination.Port == 53 && source.Addr.Is6() && source.Addr.IsLinkLocalUnicast() {
|
||||
return M.SocksaddrFrom(t.redirectDNSAddress, 53)
|
||||
}
|
||||
return destination
|
||||
}
|
||||
|
||||
func (t *autoRedirectHandler) NewConnectionEx(ctx context.Context, conn net.Conn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
|
||||
ctx = log.ContextWithNewID(ctx)
|
||||
var metadata adapter.InboundContext
|
||||
metadata.Inbound = t.tag
|
||||
metadata.InboundType = C.TypeTun
|
||||
metadata.Source = source
|
||||
metadata.Destination = destination
|
||||
for _, dnsHijackAddress := range t.dnsHijackAddress {
|
||||
if destination.Addr == dnsHijackAddress {
|
||||
metadata.Protocol = C.ProtocolDNS
|
||||
}
|
||||
metadata.Destination = t.redirectDNSDestination(source, destination)
|
||||
if (*Inbound)(t).isDNSHijackDestination(metadata.Destination) {
|
||||
metadata.Protocol = C.ProtocolDNS
|
||||
}
|
||||
if metadata.Protocol == C.ProtocolDNS {
|
||||
t.logger.InfoContext(ctx, "inbound redirect DNS connection from ", metadata.Source)
|
||||
@@ -620,5 +659,5 @@ func (t *autoRedirectHandler) NewPacketConnectionEx(ctx context.Context, conn N.
|
||||
}
|
||||
|
||||
func (t *autoRedirectHandler) NewDNSPacket(payload []byte, source M.Socksaddr, destination M.Socksaddr, writer N.PacketWriter) {
|
||||
(*Inbound)(t).NewDNSPacket(payload, source, destination, writer)
|
||||
(*Inbound)(t).NewDNSPacket(payload, source, t.redirectDNSDestination(source, destination), writer)
|
||||
}
|
||||
|
||||
@@ -357,6 +357,6 @@ func (h *inboundTransportHandler) NewConnectionEx(ctx context.Context, conn net.
|
||||
(*Inbound)(h).newConnectionExInternal(ctx, conn, metadata, onClose, false)
|
||||
}
|
||||
|
||||
func (h *Inbound) References() []string {
|
||||
return h.references
|
||||
func (h *Inbound) References() ([]string, []string) {
|
||||
return h.references, nil
|
||||
}
|
||||
|
||||
@@ -69,10 +69,11 @@ func NewOutbound(ctx context.Context, router adapter.Router, logger log.ContextL
|
||||
}
|
||||
if options.TLS != nil {
|
||||
outbound.tlsConfig, err = tls.NewClientWithOptions(tls.ClientOptions{
|
||||
Context: ctx,
|
||||
Logger: logger,
|
||||
ServerAddress: options.Server,
|
||||
Options: common.PtrValueOrDefault(options.TLS),
|
||||
Context: ctx,
|
||||
Logger: logger,
|
||||
ServerAddress: options.Server,
|
||||
Options: common.PtrValueOrDefault(options.TLS),
|
||||
DomainResolver: options.DomainResolver,
|
||||
KTLSCompatible: common.PtrValueOrDefault(options.Transport).Type == "" &&
|
||||
!common.PtrValueOrDefault(options.Multiplex).Enabled &&
|
||||
options.Flow == "",
|
||||
@@ -80,7 +81,9 @@ func NewOutbound(ctx context.Context, router adapter.Router, logger log.ContextL
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
outbound.tlsDialer = tls.NewDialer(outboundDialer, outbound.tlsConfig)
|
||||
if outbound.tlsConfig != nil {
|
||||
outbound.tlsDialer = tls.NewDialer(outboundDialer, outbound.tlsConfig)
|
||||
}
|
||||
}
|
||||
if options.Transport != nil {
|
||||
outbound.transport, err = v2ray.NewClientTransport(ctx, logger, outbound.dialer, outbound.serverAddr, common.PtrValueOrDefault(options.Transport), outbound.tlsConfig)
|
||||
|
||||
@@ -59,7 +59,13 @@ func NewOutbound(ctx context.Context, router adapter.Router, logger log.ContextL
|
||||
serverAddr: options.ServerOptions.Build(),
|
||||
}
|
||||
if options.TLS != nil {
|
||||
outbound.tlsConfig, err = tls.NewClient(ctx, logger, options.Server, common.PtrValueOrDefault(options.TLS))
|
||||
outbound.tlsConfig, err = tls.NewClientWithOptions(tls.ClientOptions{
|
||||
Context: ctx,
|
||||
Logger: logger,
|
||||
ServerAddress: options.Server,
|
||||
Options: common.PtrValueOrDefault(options.TLS),
|
||||
DomainResolver: options.DomainResolver,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -106,12 +106,14 @@ func (c *ClientEndpoint) Start(stage adapter.StartStage, scope *adapter.Scope) e
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *ClientEndpoint) References() []string {
|
||||
func (c *ClientEndpoint) IsEndpoint() {}
|
||||
|
||||
func (c *ClientEndpoint) References() ([]string, []string) {
|
||||
referrer, isReferrer := c.outbound.(adapter.Referrer)
|
||||
if isReferrer {
|
||||
return referrer.References()
|
||||
}
|
||||
return c.outbound.Dependencies()
|
||||
return c.outbound.Dependencies(), nil
|
||||
}
|
||||
|
||||
func (c *ClientEndpoint) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
|
||||
|
||||
@@ -107,15 +107,18 @@ func (s *ServerEndpoint) Start(stage adapter.StartStage, scope *adapter.Scope) e
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *ServerEndpoint) References() []string {
|
||||
var references []string
|
||||
func (s *ServerEndpoint) IsEndpoint() {}
|
||||
|
||||
func (s *ServerEndpoint) References() (outbounds []string, dnsServers []string) {
|
||||
for _, inbound := range s.inbounds {
|
||||
referrer, isReferrer := inbound.(adapter.Referrer)
|
||||
if isReferrer {
|
||||
references = append(references, referrer.References()...)
|
||||
referencedOutbounds, referencedDNSServers := referrer.References()
|
||||
outbounds = append(outbounds, referencedOutbounds...)
|
||||
dnsServers = append(dnsServers, referencedDNSServers...)
|
||||
}
|
||||
}
|
||||
return references
|
||||
return outbounds, dnsServers
|
||||
}
|
||||
|
||||
func (s *ServerEndpoint) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
|
||||
|
||||
@@ -29,6 +29,7 @@ import (
|
||||
var (
|
||||
_ adapter.OutboundWithPreferredRoutes = (*Endpoint)(nil)
|
||||
_ adapter.InterfaceUpdateListener = (*Endpoint)(nil)
|
||||
_ adapter.OutboundWithMultiplex = (*Endpoint)(nil)
|
||||
_ dialer.PacketDialerWithDestination = (*Endpoint)(nil)
|
||||
)
|
||||
|
||||
@@ -188,6 +189,10 @@ func (w *Endpoint) Start(stage adapter.StartStage, scope *adapter.Scope) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *Endpoint) MultiplexEnabled() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (w *Endpoint) InterfaceUpdated(ctx context.Context) {
|
||||
if !w.started.Load() {
|
||||
return
|
||||
@@ -229,7 +234,7 @@ func (w *Endpoint) DetachReturn(returnPath tun.Return) error {
|
||||
|
||||
func (w *Endpoint) JudgeFlow(network uint8, source netip.AddrPort, destination netip.AddrPort, firstPacket []byte) tun.FlowVerdict {
|
||||
for _, localPrefix := range w.localAddresses {
|
||||
if localPrefix.Contains(destination.Addr()) {
|
||||
if destination.Addr() == localPrefix.Addr() {
|
||||
return tun.FlowVerdict{Action: tun.ActionAccept}
|
||||
}
|
||||
}
|
||||
@@ -262,7 +267,7 @@ func (w *Endpoint) NewConnectionEx(ctx context.Context, conn net.Conn, source M.
|
||||
metadata.InboundType = w.Type()
|
||||
metadata.Source = source
|
||||
for _, localPrefix := range w.localAddresses {
|
||||
if localPrefix.Contains(destination.Addr) {
|
||||
if destination.Addr == localPrefix.Addr() {
|
||||
metadata.OriginDestination = destination
|
||||
if destination.Addr.Is4() {
|
||||
destination.Addr = netip.AddrFrom4([4]uint8{127, 0, 0, 1})
|
||||
@@ -285,7 +290,7 @@ func (w *Endpoint) NewPacketConnectionEx(ctx context.Context, conn N.PacketConn,
|
||||
metadata.Source = source
|
||||
metadata.Destination = destination
|
||||
for _, localPrefix := range w.localAddresses {
|
||||
if localPrefix.Contains(destination.Addr) {
|
||||
if destination.Addr == localPrefix.Addr() {
|
||||
metadata.OriginDestination = destination
|
||||
if destination.Addr.Is4() {
|
||||
metadata.Destination.Addr = netip.AddrFrom4([4]uint8{127, 0, 0, 1})
|
||||
|
||||
Reference in New Issue
Block a user