1
0

endpoint.go 7.0 KB

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