endpoint.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  1. package tailscale
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "fmt"
  6. "net"
  7. "net/http"
  8. "net/netip"
  9. "net/url"
  10. "os"
  11. "path/filepath"
  12. "reflect"
  13. "runtime"
  14. "strings"
  15. "sync/atomic"
  16. "syscall"
  17. "time"
  18. "github.com/sagernet/gvisor/pkg/tcpip"
  19. "github.com/sagernet/gvisor/pkg/tcpip/adapters/gonet"
  20. "github.com/sagernet/gvisor/pkg/tcpip/header"
  21. "github.com/sagernet/gvisor/pkg/tcpip/stack"
  22. "github.com/sagernet/gvisor/pkg/tcpip/transport/icmp"
  23. "github.com/sagernet/gvisor/pkg/tcpip/transport/tcp"
  24. "github.com/sagernet/gvisor/pkg/tcpip/transport/udp"
  25. "github.com/sagernet/sing-box/adapter"
  26. "github.com/sagernet/sing-box/adapter/endpoint"
  27. "github.com/sagernet/sing-box/common/dialer"
  28. C "github.com/sagernet/sing-box/constant"
  29. "github.com/sagernet/sing-box/log"
  30. "github.com/sagernet/sing-box/option"
  31. "github.com/sagernet/sing-box/route/rule"
  32. "github.com/sagernet/sing-tun"
  33. "github.com/sagernet/sing-tun/ping"
  34. "github.com/sagernet/sing/common"
  35. "github.com/sagernet/sing/common/bufio"
  36. "github.com/sagernet/sing/common/control"
  37. E "github.com/sagernet/sing/common/exceptions"
  38. F "github.com/sagernet/sing/common/format"
  39. "github.com/sagernet/sing/common/logger"
  40. M "github.com/sagernet/sing/common/metadata"
  41. N "github.com/sagernet/sing/common/network"
  42. "github.com/sagernet/sing/service"
  43. "github.com/sagernet/sing/service/filemanager"
  44. "github.com/sagernet/tailscale/ipn"
  45. tsDNS "github.com/sagernet/tailscale/net/dns"
  46. "github.com/sagernet/tailscale/net/netmon"
  47. "github.com/sagernet/tailscale/net/tsaddr"
  48. "github.com/sagernet/tailscale/tsnet"
  49. "github.com/sagernet/tailscale/types/ipproto"
  50. "github.com/sagernet/tailscale/version"
  51. "github.com/sagernet/tailscale/wgengine"
  52. "github.com/sagernet/tailscale/wgengine/filter"
  53. "github.com/sagernet/tailscale/wgengine/router"
  54. "github.com/sagernet/tailscale/wgengine/wgcfg"
  55. "go4.org/netipx"
  56. )
  57. var (
  58. _ adapter.OutboundWithPreferredRoutes = (*Endpoint)(nil)
  59. _ adapter.DirectRouteOutbound = (*Endpoint)(nil)
  60. )
  61. func init() {
  62. version.SetVersion("sing-box " + C.Version)
  63. }
  64. func RegisterEndpoint(registry *endpoint.Registry) {
  65. endpoint.Register[option.TailscaleEndpointOptions](registry, C.TypeTailscale, NewEndpoint)
  66. }
  67. type Endpoint struct {
  68. endpoint.Adapter
  69. ctx context.Context
  70. router adapter.Router
  71. logger logger.ContextLogger
  72. dnsRouter adapter.DNSRouter
  73. network adapter.NetworkManager
  74. platformInterface adapter.PlatformInterface
  75. server *tsnet.Server
  76. stack *stack.Stack
  77. icmpForwarder *tun.ICMPForwarder
  78. filter *atomic.Pointer[filter.Filter]
  79. onReconfigHook wgengine.ReconfigListener
  80. cfg *wgcfg.Config
  81. dnsCfg *tsDNS.Config
  82. routeDomains common.TypedValue[map[string]bool]
  83. routePrefixes atomic.Pointer[netipx.IPSet]
  84. acceptRoutes bool
  85. exitNode string
  86. exitNodeAllowLANAccess bool
  87. advertiseRoutes []netip.Prefix
  88. advertiseExitNode bool
  89. udpTimeout time.Duration
  90. }
  91. func NewEndpoint(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.TailscaleEndpointOptions) (adapter.Endpoint, error) {
  92. stateDirectory := options.StateDirectory
  93. if stateDirectory == "" {
  94. stateDirectory = "tailscale"
  95. }
  96. hostname := options.Hostname
  97. if hostname == "" {
  98. osHostname, _ := os.Hostname()
  99. osHostname = strings.TrimSpace(osHostname)
  100. hostname = osHostname
  101. }
  102. if hostname == "" {
  103. hostname = "sing-box"
  104. }
  105. stateDirectory = filemanager.BasePath(ctx, os.ExpandEnv(stateDirectory))
  106. stateDirectory, _ = filepath.Abs(stateDirectory)
  107. for _, advertiseRoute := range options.AdvertiseRoutes {
  108. if advertiseRoute.Addr().IsUnspecified() && advertiseRoute.Bits() == 0 {
  109. return nil, E.New("`advertise_routes` cannot be default, use `advertise_exit_node` instead.")
  110. }
  111. }
  112. if options.AdvertiseExitNode && options.ExitNode != "" {
  113. return nil, E.New("cannot advertise an exit node and use an exit node at the same time.")
  114. }
  115. var udpTimeout time.Duration
  116. if options.UDPTimeout != 0 {
  117. udpTimeout = time.Duration(options.UDPTimeout)
  118. } else {
  119. udpTimeout = C.UDPTimeout
  120. }
  121. var remoteIsDomain bool
  122. if options.ControlURL != "" {
  123. controlURL, err := url.Parse(options.ControlURL)
  124. if err != nil {
  125. return nil, E.Cause(err, "parse control URL")
  126. }
  127. remoteIsDomain = M.IsDomainName(controlURL.Hostname())
  128. } else {
  129. // controlplane.tailscale.com
  130. remoteIsDomain = true
  131. }
  132. outboundDialer, err := dialer.NewWithOptions(dialer.Options{
  133. Context: ctx,
  134. Options: options.DialerOptions,
  135. RemoteIsDomain: remoteIsDomain,
  136. ResolverOnDetour: true,
  137. NewDialer: true,
  138. })
  139. if err != nil {
  140. return nil, err
  141. }
  142. dnsRouter := service.FromContext[adapter.DNSRouter](ctx)
  143. server := &tsnet.Server{
  144. Dir: stateDirectory,
  145. Hostname: hostname,
  146. Logf: func(format string, args ...any) {
  147. logger.Trace(fmt.Sprintf(format, args...))
  148. },
  149. UserLogf: func(format string, args ...any) {
  150. logger.Debug(fmt.Sprintf(format, args...))
  151. },
  152. Ephemeral: options.Ephemeral,
  153. AuthKey: options.AuthKey,
  154. ControlURL: options.ControlURL,
  155. Dialer: &endpointDialer{Dialer: outboundDialer, logger: logger},
  156. LookupHook: func(ctx context.Context, host string) ([]netip.Addr, error) {
  157. return dnsRouter.Lookup(ctx, host, outboundDialer.(dialer.ResolveDialer).QueryOptions())
  158. },
  159. DNS: &dnsConfigurtor{},
  160. HTTPClient: &http.Client{
  161. Transport: &http.Transport{
  162. ForceAttemptHTTP2: true,
  163. DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
  164. return outboundDialer.DialContext(ctx, network, M.ParseSocksaddr(address))
  165. },
  166. TLSClientConfig: &tls.Config{
  167. RootCAs: adapter.RootPoolFromContext(ctx),
  168. },
  169. },
  170. },
  171. }
  172. return &Endpoint{
  173. Adapter: endpoint.NewAdapter(C.TypeTailscale, tag, []string{N.NetworkTCP, N.NetworkUDP, N.NetworkICMP}, nil),
  174. ctx: ctx,
  175. router: router,
  176. logger: logger,
  177. dnsRouter: dnsRouter,
  178. network: service.FromContext[adapter.NetworkManager](ctx),
  179. platformInterface: service.FromContext[adapter.PlatformInterface](ctx),
  180. server: server,
  181. acceptRoutes: options.AcceptRoutes,
  182. exitNode: options.ExitNode,
  183. exitNodeAllowLANAccess: options.ExitNodeAllowLANAccess,
  184. advertiseRoutes: options.AdvertiseRoutes,
  185. advertiseExitNode: options.AdvertiseExitNode,
  186. udpTimeout: udpTimeout,
  187. }, nil
  188. }
  189. func (t *Endpoint) Start(stage adapter.StartStage) error {
  190. if stage != adapter.StartStateStart {
  191. return nil
  192. }
  193. if t.platformInterface != nil {
  194. err := t.network.UpdateInterfaces()
  195. if err != nil {
  196. return err
  197. }
  198. netmon.RegisterInterfaceGetter(func() ([]netmon.Interface, error) {
  199. return common.Map(t.network.InterfaceFinder().Interfaces(), func(it control.Interface) netmon.Interface {
  200. return netmon.Interface{
  201. Interface: &net.Interface{
  202. Index: it.Index,
  203. MTU: it.MTU,
  204. Name: it.Name,
  205. HardwareAddr: it.HardwareAddr,
  206. Flags: it.Flags,
  207. },
  208. AltAddrs: common.Map(it.Addresses, func(it netip.Prefix) net.Addr {
  209. return &net.IPNet{
  210. IP: it.Addr().AsSlice(),
  211. Mask: net.CIDRMask(it.Bits(), it.Addr().BitLen()),
  212. }
  213. }),
  214. }
  215. }), nil
  216. })
  217. if runtime.GOOS == "android" {
  218. setAndroidProtectFunc(t.platformInterface)
  219. }
  220. }
  221. err := t.server.Start()
  222. if err != nil {
  223. return err
  224. }
  225. t.server.ExportLocalBackend().ExportEngine().(wgengine.ExportedUserspaceEngine).SetOnReconfigListener(t.onReconfig)
  226. ipStack := t.server.ExportNetstack().ExportIPStack()
  227. gErr := ipStack.SetSpoofing(tun.DefaultNIC, true)
  228. if gErr != nil {
  229. return gonet.TranslateNetstackError(gErr)
  230. }
  231. gErr = ipStack.SetPromiscuousMode(tun.DefaultNIC, true)
  232. if gErr != nil {
  233. return gonet.TranslateNetstackError(gErr)
  234. }
  235. ipStack.SetTransportProtocolHandler(tcp.ProtocolNumber, tun.NewTCPForwarder(t.ctx, ipStack, t).HandlePacket)
  236. ipStack.SetTransportProtocolHandler(udp.ProtocolNumber, tun.NewUDPForwarder(t.ctx, ipStack, t, t.udpTimeout).HandlePacket)
  237. icmpForwarder := tun.NewICMPForwarder(t.ctx, ipStack, t, t.udpTimeout)
  238. ipStack.SetTransportProtocolHandler(icmp.ProtocolNumber4, icmpForwarder.HandlePacket)
  239. ipStack.SetTransportProtocolHandler(icmp.ProtocolNumber6, icmpForwarder.HandlePacket)
  240. t.stack = ipStack
  241. t.icmpForwarder = icmpForwarder
  242. localBackend := t.server.ExportLocalBackend()
  243. perfs := &ipn.MaskedPrefs{
  244. Prefs: ipn.Prefs{
  245. RouteAll: t.acceptRoutes,
  246. },
  247. RouteAllSet: true,
  248. ExitNodeIPSet: true,
  249. AdvertiseRoutesSet: true,
  250. }
  251. if len(t.advertiseRoutes) > 0 {
  252. perfs.AdvertiseRoutes = t.advertiseRoutes
  253. }
  254. if t.advertiseExitNode {
  255. perfs.AdvertiseRoutes = append(perfs.AdvertiseRoutes, tsaddr.ExitRoutes()...)
  256. }
  257. _, err = localBackend.EditPrefs(perfs)
  258. if err != nil {
  259. return E.Cause(err, "update prefs")
  260. }
  261. t.filter = localBackend.ExportFilter()
  262. go t.watchState()
  263. return nil
  264. }
  265. func (t *Endpoint) watchState() {
  266. localBackend := t.server.ExportLocalBackend()
  267. localBackend.WatchNotifications(t.ctx, ipn.NotifyInitialState, nil, func(roNotify *ipn.Notify) (keepGoing bool) {
  268. if roNotify.State != nil && *roNotify.State != ipn.NeedsLogin && *roNotify.State != ipn.NoState {
  269. return false
  270. }
  271. authURL := localBackend.StatusWithoutPeers().AuthURL
  272. if authURL != "" {
  273. t.logger.Info("Waiting for authentication: ", authURL)
  274. if t.platformInterface != nil {
  275. err := t.platformInterface.SendNotification(&adapter.Notification{
  276. Identifier: "tailscale-authentication",
  277. TypeName: "Tailscale Authentication Notifications",
  278. TypeID: 10,
  279. Title: "Tailscale Authentication",
  280. Body: F.ToString("Tailscale outbound[", t.Tag(), "] is waiting for authentication."),
  281. OpenURL: authURL,
  282. })
  283. if err != nil {
  284. t.logger.Error("send authentication notification: ", err)
  285. }
  286. }
  287. return false
  288. }
  289. return true
  290. })
  291. if t.exitNode != "" {
  292. localBackend.WatchNotifications(t.ctx, ipn.NotifyInitialState, nil, func(roNotify *ipn.Notify) (keepGoing bool) {
  293. if roNotify.State == nil || *roNotify.State != ipn.Running {
  294. return true
  295. }
  296. status, err := common.Must1(t.server.LocalClient()).Status(t.ctx)
  297. if err != nil {
  298. t.logger.Error("set exit node: ", err)
  299. return
  300. }
  301. perfs := &ipn.MaskedPrefs{
  302. Prefs: ipn.Prefs{
  303. ExitNodeAllowLANAccess: t.exitNodeAllowLANAccess,
  304. },
  305. ExitNodeIPSet: true,
  306. ExitNodeAllowLANAccessSet: true,
  307. }
  308. err = perfs.SetExitNodeIP(t.exitNode, status)
  309. if err != nil {
  310. t.logger.Error("set exit node: ", err)
  311. return true
  312. }
  313. _, err = localBackend.EditPrefs(perfs)
  314. if err != nil {
  315. t.logger.Error("set exit node: ", err)
  316. return true
  317. }
  318. return false
  319. })
  320. }
  321. }
  322. func (t *Endpoint) Close() error {
  323. netmon.RegisterInterfaceGetter(nil)
  324. if runtime.GOOS == "android" {
  325. setAndroidProtectFunc(nil)
  326. }
  327. return common.Close(common.PtrOrNil(t.server))
  328. }
  329. func (t *Endpoint) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
  330. switch network {
  331. case N.NetworkTCP:
  332. t.logger.InfoContext(ctx, "outbound connection to ", destination)
  333. case N.NetworkUDP:
  334. t.logger.InfoContext(ctx, "outbound packet connection to ", destination)
  335. }
  336. if destination.IsFqdn() {
  337. destinationAddresses, err := t.dnsRouter.Lookup(ctx, destination.Fqdn, adapter.DNSQueryOptions{})
  338. if err != nil {
  339. return nil, err
  340. }
  341. return N.DialSerial(ctx, t, network, destination, destinationAddresses)
  342. }
  343. addr := tcpip.FullAddress{
  344. NIC: 1,
  345. Port: destination.Port,
  346. Addr: addressFromAddr(destination.Addr),
  347. }
  348. var networkProtocol tcpip.NetworkProtocolNumber
  349. if destination.IsIPv4() {
  350. networkProtocol = header.IPv4ProtocolNumber
  351. } else {
  352. networkProtocol = header.IPv6ProtocolNumber
  353. }
  354. switch N.NetworkName(network) {
  355. case N.NetworkTCP:
  356. tcpConn, err := gonet.DialContextTCP(ctx, t.stack, addr, networkProtocol)
  357. if err != nil {
  358. return nil, err
  359. }
  360. return tcpConn, nil
  361. case N.NetworkUDP:
  362. udpConn, err := gonet.DialUDP(t.stack, nil, &addr, networkProtocol)
  363. if err != nil {
  364. return nil, err
  365. }
  366. return udpConn, nil
  367. default:
  368. return nil, E.Extend(N.ErrUnknownNetwork, network)
  369. }
  370. }
  371. func (t *Endpoint) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
  372. t.logger.InfoContext(ctx, "outbound packet connection to ", destination)
  373. if destination.IsFqdn() {
  374. destinationAddresses, err := t.dnsRouter.Lookup(ctx, destination.Fqdn, adapter.DNSQueryOptions{})
  375. if err != nil {
  376. return nil, err
  377. }
  378. packetConn, _, err := N.ListenSerial(ctx, t, destination, destinationAddresses)
  379. if err != nil {
  380. return nil, err
  381. }
  382. return packetConn, err
  383. }
  384. addr4, addr6 := t.server.TailscaleIPs()
  385. bind := tcpip.FullAddress{
  386. NIC: 1,
  387. }
  388. var networkProtocol tcpip.NetworkProtocolNumber
  389. if destination.IsIPv4() {
  390. if !addr4.IsValid() {
  391. return nil, E.New("missing Tailscale IPv4 address")
  392. }
  393. networkProtocol = header.IPv4ProtocolNumber
  394. bind.Addr = addressFromAddr(addr4)
  395. } else {
  396. if !addr6.IsValid() {
  397. return nil, E.New("missing Tailscale IPv6 address")
  398. }
  399. networkProtocol = header.IPv6ProtocolNumber
  400. bind.Addr = addressFromAddr(addr6)
  401. }
  402. udpConn, err := gonet.DialUDP(t.stack, &bind, nil, networkProtocol)
  403. if err != nil {
  404. return nil, err
  405. }
  406. return udpConn, nil
  407. }
  408. func (t *Endpoint) PrepareConnection(network string, source M.Socksaddr, destination M.Socksaddr, routeContext tun.DirectRouteContext, timeout time.Duration) (tun.DirectRouteDestination, error) {
  409. tsFilter := t.filter.Load()
  410. if tsFilter != nil {
  411. var ipProto ipproto.Proto
  412. switch N.NetworkName(network) {
  413. case N.NetworkTCP:
  414. ipProto = ipproto.TCP
  415. case N.NetworkUDP:
  416. ipProto = ipproto.UDP
  417. case N.NetworkICMP:
  418. if !destination.IsIPv6() {
  419. ipProto = ipproto.ICMPv4
  420. } else {
  421. ipProto = ipproto.ICMPv6
  422. }
  423. }
  424. response := tsFilter.Check(source.Addr, destination.Addr, destination.Port, ipProto)
  425. switch response {
  426. case filter.Drop:
  427. return nil, syscall.ECONNREFUSED
  428. case filter.DropSilently:
  429. return nil, tun.ErrDrop
  430. }
  431. }
  432. var ipVersion uint8
  433. if !destination.IsIPv6() {
  434. ipVersion = 4
  435. } else {
  436. ipVersion = 6
  437. }
  438. routeDestination, err := t.router.PreMatch(adapter.InboundContext{
  439. Inbound: t.Tag(),
  440. InboundType: t.Type(),
  441. IPVersion: ipVersion,
  442. Network: network,
  443. Source: source,
  444. Destination: destination,
  445. }, routeContext, timeout)
  446. if err != nil {
  447. if !rule.IsRejected(err) {
  448. t.logger.Warn(E.Cause(err, "link ", network, " connection from ", source.AddrString(), " to ", destination.AddrString()))
  449. }
  450. }
  451. return routeDestination, err
  452. }
  453. func (t *Endpoint) NewConnectionEx(ctx context.Context, conn net.Conn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
  454. var metadata adapter.InboundContext
  455. metadata.Inbound = t.Tag()
  456. metadata.InboundType = t.Type()
  457. metadata.Source = source
  458. addr4, addr6 := t.server.TailscaleIPs()
  459. switch destination.Addr {
  460. case addr4:
  461. destination.Addr = netip.AddrFrom4([4]uint8{127, 0, 0, 1})
  462. case addr6:
  463. destination.Addr = netip.IPv6Loopback()
  464. }
  465. metadata.Destination = destination
  466. t.logger.InfoContext(ctx, "inbound connection from ", source)
  467. t.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination)
  468. t.router.RouteConnectionEx(ctx, conn, metadata, onClose)
  469. }
  470. func (t *Endpoint) NewPacketConnectionEx(ctx context.Context, conn N.PacketConn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
  471. var metadata adapter.InboundContext
  472. metadata.Inbound = t.Tag()
  473. metadata.InboundType = t.Type()
  474. metadata.Source = source
  475. metadata.Destination = destination
  476. addr4, addr6 := t.server.TailscaleIPs()
  477. switch destination.Addr {
  478. case addr4:
  479. metadata.OriginDestination = destination
  480. destination.Addr = netip.AddrFrom4([4]uint8{127, 0, 0, 1})
  481. conn = bufio.NewNATPacketConn(bufio.NewNetPacketConn(conn), metadata.OriginDestination, metadata.Destination)
  482. case addr6:
  483. metadata.OriginDestination = destination
  484. destination.Addr = netip.IPv6Loopback()
  485. conn = bufio.NewNATPacketConn(bufio.NewNetPacketConn(conn), metadata.OriginDestination, metadata.Destination)
  486. }
  487. t.logger.InfoContext(ctx, "inbound packet connection from ", source)
  488. t.logger.InfoContext(ctx, "inbound packet connection to ", destination)
  489. t.router.RoutePacketConnectionEx(ctx, conn, metadata, onClose)
  490. }
  491. func (t *Endpoint) NewDirectRouteConnection(metadata adapter.InboundContext, routeContext tun.DirectRouteContext, timeout time.Duration) (tun.DirectRouteDestination, error) {
  492. inet4Address, inet6Address := t.server.TailscaleIPs()
  493. if metadata.Destination.Addr.Is4() && !inet4Address.IsValid() || metadata.Destination.Addr.Is6() && !inet6Address.IsValid() {
  494. return nil, E.New("Tailscale is not ready yet")
  495. }
  496. ctx := log.ContextWithNewID(t.ctx)
  497. destination, err := ping.ConnectGVisor(
  498. ctx, t.logger,
  499. metadata.Source.Addr, metadata.Destination.Addr,
  500. routeContext,
  501. t.stack,
  502. inet4Address, inet6Address,
  503. timeout,
  504. )
  505. if err != nil {
  506. return nil, err
  507. }
  508. t.logger.InfoContext(ctx, "linked ", metadata.Network, " connection from ", metadata.Source.AddrString(), " to ", metadata.Destination.AddrString())
  509. return destination, nil
  510. }
  511. func (t *Endpoint) PreferredDomain(domain string) bool {
  512. routeDomains := t.routeDomains.Load()
  513. if routeDomains == nil {
  514. return false
  515. }
  516. return routeDomains[strings.ToLower(domain)]
  517. }
  518. func (t *Endpoint) PreferredAddress(address netip.Addr) bool {
  519. routePrefixes := t.routePrefixes.Load()
  520. if routePrefixes == nil {
  521. return false
  522. }
  523. return routePrefixes.Contains(address)
  524. }
  525. func (t *Endpoint) Server() *tsnet.Server {
  526. return t.server
  527. }
  528. func (t *Endpoint) onReconfig(cfg *wgcfg.Config, routerCfg *router.Config, dnsCfg *tsDNS.Config) {
  529. if cfg == nil || dnsCfg == nil {
  530. return
  531. }
  532. if (t.cfg != nil && reflect.DeepEqual(t.cfg, cfg)) && (t.dnsCfg != nil && reflect.DeepEqual(t.dnsCfg, dnsCfg)) {
  533. return
  534. }
  535. var inet4Address, inet6Address netip.Addr
  536. for _, address := range cfg.Addresses {
  537. if address.Addr().Is4() {
  538. inet4Address = address.Addr()
  539. } else if address.Addr().Is6() {
  540. inet6Address = address.Addr()
  541. }
  542. }
  543. t.icmpForwarder.SetLocalAddresses(inet4Address, inet6Address)
  544. t.cfg = cfg
  545. t.dnsCfg = dnsCfg
  546. routeDomains := make(map[string]bool)
  547. for fqdn := range dnsCfg.Routes {
  548. routeDomains[fqdn.WithoutTrailingDot()] = true
  549. }
  550. for _, fqdn := range dnsCfg.SearchDomains {
  551. routeDomains[fqdn.WithoutTrailingDot()] = true
  552. }
  553. t.routeDomains.Store(routeDomains)
  554. var builder netipx.IPSetBuilder
  555. for _, peer := range cfg.Peers {
  556. for _, allowedIP := range peer.AllowedIPs {
  557. builder.AddPrefix(allowedIP)
  558. }
  559. }
  560. t.routePrefixes.Store(common.Must1(builder.IPSet()))
  561. if t.onReconfigHook != nil {
  562. t.onReconfigHook(cfg, routerCfg, dnsCfg)
  563. }
  564. }
  565. func addressFromAddr(destination netip.Addr) tcpip.Address {
  566. if destination.Is6() {
  567. return tcpip.AddrFrom16(destination.As16())
  568. } else {
  569. return tcpip.AddrFrom4(destination.As4())
  570. }
  571. }
  572. type endpointDialer struct {
  573. N.Dialer
  574. logger logger.ContextLogger
  575. }
  576. func (d *endpointDialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
  577. switch N.NetworkName(network) {
  578. case N.NetworkTCP:
  579. d.logger.InfoContext(ctx, "output connection to ", destination)
  580. case N.NetworkUDP:
  581. d.logger.InfoContext(ctx, "output packet connection to ", destination)
  582. }
  583. return d.Dialer.DialContext(ctx, network, destination)
  584. }
  585. func (d *endpointDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
  586. d.logger.InfoContext(ctx, "output packet connection")
  587. return d.Dialer.ListenPacket(ctx, destination)
  588. }
  589. type dnsConfigurtor struct {
  590. baseConfig tsDNS.OSConfig
  591. }
  592. func (c *dnsConfigurtor) SetDNS(cfg tsDNS.OSConfig) error {
  593. c.baseConfig = cfg
  594. return nil
  595. }
  596. func (c *dnsConfigurtor) SupportsSplitDNS() bool {
  597. return true
  598. }
  599. func (c *dnsConfigurtor) GetBaseConfig() (tsDNS.OSConfig, error) {
  600. return c.baseConfig, nil
  601. }
  602. func (c *dnsConfigurtor) Close() error {
  603. return nil
  604. }