endpoint.go 6.8 KB

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