endpoint.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. package wireguard
  2. import (
  3. "context"
  4. "net"
  5. "net/netip"
  6. "time"
  7. "github.com/sagernet/sing-box/adapter"
  8. "github.com/sagernet/sing-box/adapter/endpoint"
  9. "github.com/sagernet/sing-box/common/dialer"
  10. C "github.com/sagernet/sing-box/constant"
  11. "github.com/sagernet/sing-box/log"
  12. "github.com/sagernet/sing-box/option"
  13. "github.com/sagernet/sing-box/transport/wireguard"
  14. "github.com/sagernet/sing-dns"
  15. "github.com/sagernet/sing/common"
  16. "github.com/sagernet/sing/common/bufio"
  17. E "github.com/sagernet/sing/common/exceptions"
  18. "github.com/sagernet/sing/common/logger"
  19. M "github.com/sagernet/sing/common/metadata"
  20. N "github.com/sagernet/sing/common/network"
  21. "github.com/sagernet/sing/service"
  22. )
  23. func RegisterEndpoint(registry *endpoint.Registry) {
  24. endpoint.Register[option.WireGuardEndpointOptions](registry, C.TypeWireGuard, NewEndpoint)
  25. }
  26. var (
  27. _ adapter.Endpoint = (*Endpoint)(nil)
  28. _ adapter.InterfaceUpdateListener = (*Endpoint)(nil)
  29. )
  30. type Endpoint struct {
  31. endpoint.Adapter
  32. ctx context.Context
  33. router adapter.Router
  34. logger logger.ContextLogger
  35. localAddresses []netip.Prefix
  36. endpoint *wireguard.Endpoint
  37. }
  38. func NewEndpoint(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.WireGuardEndpointOptions) (adapter.Endpoint, error) {
  39. ep := &Endpoint{
  40. Adapter: endpoint.NewAdapterWithDialerOptions(C.TypeWireGuard, tag, []string{N.NetworkTCP, N.NetworkUDP}, options.DialerOptions),
  41. ctx: ctx,
  42. router: router,
  43. logger: logger,
  44. localAddresses: options.Address,
  45. }
  46. if options.Detour == "" {
  47. options.IsWireGuardListener = true
  48. }
  49. outboundDialer, err := dialer.New(ctx, options.DialerOptions)
  50. if err != nil {
  51. return nil, err
  52. }
  53. wgEndpoint, err := wireguard.NewEndpoint(wireguard.EndpointOptions{
  54. Context: ctx,
  55. Logger: logger,
  56. System: options.System,
  57. Handler: ep,
  58. UDPTimeout: time.Duration(options.UDPTimeout),
  59. Dialer: outboundDialer,
  60. CreateDialer: func(interfaceName string) N.Dialer {
  61. return common.Must1(dialer.NewDefault(service.FromContext[adapter.NetworkManager](ctx), option.DialerOptions{
  62. BindInterface: interfaceName,
  63. }))
  64. },
  65. Name: options.Name,
  66. MTU: options.MTU,
  67. Address: options.Address,
  68. PrivateKey: options.PrivateKey,
  69. ListenPort: options.ListenPort,
  70. ResolvePeer: func(domain string) (netip.Addr, error) {
  71. endpointAddresses, lookupErr := router.Lookup(ctx, domain, dns.DomainStrategy(options.DomainStrategy))
  72. if lookupErr != nil {
  73. return netip.Addr{}, lookupErr
  74. }
  75. return endpointAddresses[0], nil
  76. },
  77. Peers: common.Map(options.Peers, func(it option.WireGuardPeer) wireguard.PeerOptions {
  78. return wireguard.PeerOptions{
  79. Endpoint: M.ParseSocksaddrHostPort(it.Address, it.Port),
  80. PublicKey: it.PublicKey,
  81. PreSharedKey: it.PreSharedKey,
  82. AllowedIPs: it.AllowedIPs,
  83. PersistentKeepaliveInterval: it.PersistentKeepaliveInterval,
  84. Reserved: it.Reserved,
  85. }
  86. }),
  87. Workers: options.Workers,
  88. })
  89. if err != nil {
  90. return nil, err
  91. }
  92. ep.endpoint = wgEndpoint
  93. return ep, nil
  94. }
  95. func (w *Endpoint) Start(stage adapter.StartStage) error {
  96. switch stage {
  97. case adapter.StartStateStart:
  98. return w.endpoint.Start(false)
  99. case adapter.StartStatePostStart:
  100. return w.endpoint.Start(true)
  101. }
  102. return nil
  103. }
  104. func (w *Endpoint) Close() error {
  105. return w.endpoint.Close()
  106. }
  107. func (w *Endpoint) InterfaceUpdated() {
  108. w.endpoint.BindUpdate()
  109. return
  110. }
  111. func (w *Endpoint) PrepareConnection(network string, source M.Socksaddr, destination M.Socksaddr) error {
  112. return w.router.PreMatch(adapter.InboundContext{
  113. Inbound: w.Tag(),
  114. InboundType: w.Type(),
  115. Network: network,
  116. Source: source,
  117. Destination: destination,
  118. })
  119. }
  120. func (w *Endpoint) NewConnectionEx(ctx context.Context, conn net.Conn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
  121. var metadata adapter.InboundContext
  122. metadata.Inbound = w.Tag()
  123. metadata.InboundType = w.Type()
  124. metadata.Source = source
  125. for _, localPrefix := range w.localAddresses {
  126. if localPrefix.Contains(destination.Addr) {
  127. metadata.OriginDestination = destination
  128. if destination.Addr.Is4() {
  129. destination.Addr = netip.AddrFrom4([4]uint8{127, 0, 0, 1})
  130. } else {
  131. destination.Addr = netip.IPv6Loopback()
  132. }
  133. break
  134. }
  135. }
  136. metadata.Destination = destination
  137. w.logger.InfoContext(ctx, "inbound connection from ", source)
  138. w.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination)
  139. w.router.RouteConnectionEx(ctx, conn, metadata, onClose)
  140. }
  141. func (w *Endpoint) NewPacketConnectionEx(ctx context.Context, conn N.PacketConn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
  142. var metadata adapter.InboundContext
  143. metadata.Inbound = w.Tag()
  144. metadata.InboundType = w.Type()
  145. metadata.Source = source
  146. metadata.Destination = destination
  147. for _, localPrefix := range w.localAddresses {
  148. if localPrefix.Contains(destination.Addr) {
  149. metadata.OriginDestination = destination
  150. if destination.Addr.Is4() {
  151. metadata.Destination.Addr = netip.AddrFrom4([4]uint8{127, 0, 0, 1})
  152. } else {
  153. metadata.Destination.Addr = netip.IPv6Loopback()
  154. }
  155. conn = bufio.NewNATPacketConn(bufio.NewNetPacketConn(conn), metadata.OriginDestination, metadata.Destination)
  156. }
  157. }
  158. w.logger.InfoContext(ctx, "inbound packet connection from ", source)
  159. w.logger.InfoContext(ctx, "inbound packet connection to ", destination)
  160. w.router.RoutePacketConnectionEx(ctx, conn, metadata, onClose)
  161. }
  162. func (w *Endpoint) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
  163. switch network {
  164. case N.NetworkTCP:
  165. w.logger.InfoContext(ctx, "outbound connection to ", destination)
  166. case N.NetworkUDP:
  167. w.logger.InfoContext(ctx, "outbound packet connection to ", destination)
  168. }
  169. if destination.IsFqdn() {
  170. destinationAddresses, err := w.router.LookupDefault(ctx, destination.Fqdn)
  171. if err != nil {
  172. return nil, err
  173. }
  174. return N.DialSerial(ctx, w.endpoint, network, destination, destinationAddresses)
  175. } else if !destination.Addr.IsValid() {
  176. return nil, E.New("invalid destination: ", destination)
  177. }
  178. return w.endpoint.DialContext(ctx, network, destination)
  179. }
  180. func (w *Endpoint) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
  181. w.logger.InfoContext(ctx, "outbound packet connection to ", destination)
  182. if destination.IsFqdn() {
  183. destinationAddresses, err := w.router.LookupDefault(ctx, destination.Fqdn)
  184. if err != nil {
  185. return nil, err
  186. }
  187. packetConn, _, err := N.ListenSerial(ctx, w.endpoint, destination, destinationAddresses)
  188. if err != nil {
  189. return nil, err
  190. }
  191. return packetConn, err
  192. }
  193. return w.endpoint.ListenPacket(ctx, destination)
  194. }