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