endpoint.go 7.0 KB

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