endpoint.go 7.2 KB

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