1
0

endpoint.go 20 KB

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