1
0

endpoint.go 8.0 KB

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