endpoint.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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-dns"
  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. 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. logger: logger,
  44. localAddresses: options.Address,
  45. }
  46. if options.Detour == "" {
  47. options.IsWireGuardListener = true
  48. }
  49. outboundDialer, err := dialer.New(ctx, options.DialerOptions)
  50. if err != nil {
  51. return nil, err
  52. }
  53. var udpTimeout time.Duration
  54. if options.UDPTimeout != 0 {
  55. udpTimeout = time.Duration(options.UDPTimeout)
  56. } else {
  57. udpTimeout = C.UDPTimeout
  58. }
  59. wgEndpoint, err := wireguard.NewEndpoint(wireguard.EndpointOptions{
  60. Context: ctx,
  61. Logger: logger,
  62. System: options.System,
  63. Handler: ep,
  64. UDPTimeout: udpTimeout,
  65. Dialer: outboundDialer,
  66. CreateDialer: func(interfaceName string) N.Dialer {
  67. return common.Must1(dialer.NewDefault(service.FromContext[adapter.NetworkManager](ctx), option.DialerOptions{
  68. BindInterface: interfaceName,
  69. }))
  70. },
  71. Name: options.Name,
  72. MTU: options.MTU,
  73. Address: options.Address,
  74. PrivateKey: options.PrivateKey,
  75. ListenPort: options.ListenPort,
  76. ResolvePeer: func(domain string) (netip.Addr, error) {
  77. endpointAddresses, lookupErr := router.Lookup(ctx, domain, dns.DomainStrategy(options.DomainStrategy))
  78. if lookupErr != nil {
  79. return netip.Addr{}, lookupErr
  80. }
  81. return endpointAddresses[0], nil
  82. },
  83. Peers: common.Map(options.Peers, func(it option.WireGuardPeer) wireguard.PeerOptions {
  84. return wireguard.PeerOptions{
  85. Endpoint: M.ParseSocksaddrHostPort(it.Address, it.Port),
  86. PublicKey: it.PublicKey,
  87. PreSharedKey: it.PreSharedKey,
  88. AllowedIPs: it.AllowedIPs,
  89. PersistentKeepaliveInterval: it.PersistentKeepaliveInterval,
  90. Reserved: it.Reserved,
  91. }
  92. }),
  93. Workers: options.Workers,
  94. })
  95. if err != nil {
  96. return nil, err
  97. }
  98. ep.endpoint = wgEndpoint
  99. return ep, nil
  100. }
  101. func (w *Endpoint) Start(stage adapter.StartStage) error {
  102. switch stage {
  103. case adapter.StartStateStart:
  104. return w.endpoint.Start(false)
  105. case adapter.StartStatePostStart:
  106. return w.endpoint.Start(true)
  107. }
  108. return nil
  109. }
  110. func (w *Endpoint) Close() error {
  111. return w.endpoint.Close()
  112. }
  113. func (w *Endpoint) InterfaceUpdated() {
  114. w.endpoint.BindUpdate()
  115. return
  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.router.LookupDefault(ctx, destination.Fqdn)
  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.router.LookupDefault(ctx, destination.Fqdn)
  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. }