endpoint.go 7.7 KB

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