endpoint.go 21 KB

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