endpoint.go 6.8 KB

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