endpoint.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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. } else if options.GSO {
  49. return nil, E.New("gso is conflict with detour")
  50. }
  51. outboundDialer, err := dialer.New(ctx, options.DialerOptions)
  52. if err != nil {
  53. return nil, err
  54. }
  55. wgEndpoint, err := wireguard.NewEndpoint(wireguard.EndpointOptions{
  56. Context: ctx,
  57. Logger: logger,
  58. System: options.System,
  59. Handler: ep,
  60. UDPTimeout: time.Duration(options.UDPTimeout),
  61. Dialer: outboundDialer,
  62. CreateDialer: func(interfaceName string) N.Dialer {
  63. return common.Must1(dialer.NewDefault(service.FromContext[adapter.NetworkManager](ctx), option.DialerOptions{
  64. BindInterface: interfaceName,
  65. }))
  66. },
  67. Name: options.Name,
  68. MTU: options.MTU,
  69. GSO: options.GSO,
  70. Address: options.Address,
  71. PrivateKey: options.PrivateKey,
  72. ListenPort: options.ListenPort,
  73. ResolvePeer: func(domain string) (netip.Addr, error) {
  74. endpointAddresses, lookupErr := router.Lookup(ctx, domain, dns.DomainStrategy(options.DomainStrategy))
  75. if lookupErr != nil {
  76. return netip.Addr{}, lookupErr
  77. }
  78. return endpointAddresses[0], nil
  79. },
  80. Peers: common.Map(options.Peers, func(it option.WireGuardPeer) wireguard.PeerOptions {
  81. return wireguard.PeerOptions{
  82. Endpoint: M.ParseSocksaddrHostPort(it.Address, it.Port),
  83. PublicKey: it.PublicKey,
  84. PreSharedKey: it.PreSharedKey,
  85. AllowedIPs: it.AllowedIPs,
  86. PersistentKeepaliveInterval: it.PersistentKeepaliveInterval,
  87. Reserved: it.Reserved,
  88. }
  89. }),
  90. Workers: options.Workers,
  91. })
  92. if err != nil {
  93. return nil, err
  94. }
  95. ep.endpoint = wgEndpoint
  96. return ep, nil
  97. }
  98. func (w *Endpoint) Start(stage adapter.StartStage) error {
  99. switch stage {
  100. case adapter.StartStateStart:
  101. return w.endpoint.Start(false)
  102. case adapter.StartStatePostStart:
  103. return w.endpoint.Start(true)
  104. }
  105. return nil
  106. }
  107. func (w *Endpoint) Close() error {
  108. return w.endpoint.Close()
  109. }
  110. func (w *Endpoint) InterfaceUpdated() {
  111. w.endpoint.BindUpdate()
  112. return
  113. }
  114. func (w *Endpoint) PrepareConnection(network string, source M.Socksaddr, destination M.Socksaddr) error {
  115. return w.router.PreMatch(adapter.InboundContext{
  116. Inbound: w.Tag(),
  117. InboundType: w.Type(),
  118. Network: network,
  119. Source: source,
  120. Destination: destination,
  121. })
  122. }
  123. func (w *Endpoint) NewConnectionEx(ctx context.Context, conn net.Conn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
  124. var metadata adapter.InboundContext
  125. metadata.Inbound = w.Tag()
  126. metadata.InboundType = w.Type()
  127. metadata.Source = source
  128. for _, localPrefix := range w.localAddresses {
  129. if localPrefix.Contains(destination.Addr) {
  130. metadata.OriginDestination = destination
  131. if destination.Addr.Is4() {
  132. destination.Addr = netip.AddrFrom4([4]uint8{127, 0, 0, 1})
  133. } else {
  134. destination.Addr = netip.IPv6Loopback()
  135. }
  136. break
  137. }
  138. }
  139. metadata.Destination = destination
  140. w.logger.InfoContext(ctx, "inbound connection from ", source)
  141. w.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination)
  142. w.router.RouteConnectionEx(ctx, conn, metadata, onClose)
  143. }
  144. func (w *Endpoint) NewPacketConnectionEx(ctx context.Context, conn N.PacketConn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
  145. var metadata adapter.InboundContext
  146. metadata.Inbound = w.Tag()
  147. metadata.InboundType = w.Type()
  148. metadata.Source = source
  149. metadata.Destination = destination
  150. for _, localPrefix := range w.localAddresses {
  151. if localPrefix.Contains(destination.Addr) {
  152. metadata.OriginDestination = destination
  153. if destination.Addr.Is4() {
  154. metadata.Destination.Addr = netip.AddrFrom4([4]uint8{127, 0, 0, 1})
  155. } else {
  156. metadata.Destination.Addr = netip.IPv6Loopback()
  157. }
  158. conn = bufio.NewNATPacketConn(bufio.NewNetPacketConn(conn), metadata.OriginDestination, metadata.Destination)
  159. }
  160. }
  161. w.logger.InfoContext(ctx, "inbound packet connection from ", source)
  162. w.logger.InfoContext(ctx, "inbound packet connection to ", destination)
  163. w.router.RoutePacketConnectionEx(ctx, conn, metadata, onClose)
  164. }
  165. func (w *Endpoint) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
  166. switch network {
  167. case N.NetworkTCP:
  168. w.logger.InfoContext(ctx, "outbound connection to ", destination)
  169. case N.NetworkUDP:
  170. w.logger.InfoContext(ctx, "outbound packet connection to ", destination)
  171. }
  172. if destination.IsFqdn() {
  173. destinationAddresses, err := w.router.LookupDefault(ctx, destination.Fqdn)
  174. if err != nil {
  175. return nil, err
  176. }
  177. return N.DialSerial(ctx, w.endpoint, network, destination, destinationAddresses)
  178. } else if !destination.Addr.IsValid() {
  179. return nil, E.New("invalid destination: ", destination)
  180. }
  181. return w.endpoint.DialContext(ctx, network, destination)
  182. }
  183. func (w *Endpoint) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
  184. w.logger.InfoContext(ctx, "outbound packet connection to ", destination)
  185. if destination.IsFqdn() {
  186. destinationAddresses, err := w.router.LookupDefault(ctx, destination.Fqdn)
  187. if err != nil {
  188. return nil, err
  189. }
  190. packetConn, _, err := N.ListenSerial(ctx, w.endpoint, destination, destinationAddresses)
  191. if err != nil {
  192. return nil, err
  193. }
  194. return packetConn, err
  195. }
  196. return w.endpoint.ListenPacket(ctx, destination)
  197. }