outbound.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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/outbound"
  9. "github.com/sagernet/sing-box/common/dialer"
  10. C "github.com/sagernet/sing-box/constant"
  11. "github.com/sagernet/sing-box/experimental/deprecated"
  12. "github.com/sagernet/sing-box/log"
  13. "github.com/sagernet/sing-box/option"
  14. "github.com/sagernet/sing-box/transport/wireguard"
  15. tun "github.com/sagernet/sing-tun"
  16. "github.com/sagernet/sing/common"
  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. var _ adapter.OutboundWithPreferredRoutes = (*Outbound)(nil)
  24. func RegisterOutbound(registry *outbound.Registry) {
  25. outbound.Register[option.LegacyWireGuardOutboundOptions](registry, C.TypeWireGuard, NewOutbound)
  26. }
  27. type Outbound struct {
  28. outbound.Adapter
  29. ctx context.Context
  30. dnsRouter adapter.DNSRouter
  31. logger logger.ContextLogger
  32. localAddresses []netip.Prefix
  33. endpoint *wireguard.Endpoint
  34. }
  35. func NewOutbound(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.LegacyWireGuardOutboundOptions) (adapter.Outbound, error) {
  36. deprecated.Report(ctx, deprecated.OptionWireGuardOutbound)
  37. if options.GSO {
  38. deprecated.Report(ctx, deprecated.OptionWireGuardGSO)
  39. }
  40. outbound := &Outbound{
  41. Adapter: outbound.NewAdapterWithDialerOptions(C.TypeWireGuard, tag, []string{N.NetworkTCP, N.NetworkUDP, N.NetworkICMP}, options.DialerOptions),
  42. ctx: ctx,
  43. dnsRouter: service.FromContext[adapter.DNSRouter](ctx),
  44. logger: logger,
  45. localAddresses: options.LocalAddress,
  46. }
  47. if options.Detour != "" && options.GSO {
  48. return nil, E.New("gso is conflict with detour")
  49. }
  50. outboundDialer, err := dialer.NewWithOptions(dialer.Options{
  51. Context: ctx,
  52. Options: options.DialerOptions,
  53. RemoteIsDomain: options.ServerIsDomain() || common.Any(options.Peers, func(it option.LegacyWireGuardPeer) bool {
  54. return it.ServerIsDomain()
  55. }),
  56. ResolverOnDetour: true,
  57. })
  58. if err != nil {
  59. return nil, err
  60. }
  61. peers := common.Map(options.Peers, func(it option.LegacyWireGuardPeer) wireguard.PeerOptions {
  62. return wireguard.PeerOptions{
  63. Endpoint: it.ServerOptions.Build(),
  64. PublicKey: it.PublicKey,
  65. PreSharedKey: it.PreSharedKey,
  66. AllowedIPs: it.AllowedIPs,
  67. // PersistentKeepaliveInterval: time.Duration(it.PersistentKeepaliveInterval),
  68. Reserved: it.Reserved,
  69. }
  70. })
  71. if len(peers) == 0 {
  72. peers = []wireguard.PeerOptions{{
  73. Endpoint: options.ServerOptions.Build(),
  74. PublicKey: options.PeerPublicKey,
  75. PreSharedKey: options.PreSharedKey,
  76. AllowedIPs: []netip.Prefix{netip.PrefixFrom(netip.IPv4Unspecified(), 0), netip.PrefixFrom(netip.IPv6Unspecified(), 0)},
  77. Reserved: options.Reserved,
  78. }}
  79. }
  80. wgEndpoint, err := wireguard.NewEndpoint(wireguard.EndpointOptions{
  81. Context: ctx,
  82. Logger: logger,
  83. System: options.SystemInterface,
  84. Dialer: outboundDialer,
  85. CreateDialer: func(interfaceName string) N.Dialer {
  86. return common.Must1(dialer.NewDefault(ctx, option.DialerOptions{
  87. BindInterface: interfaceName,
  88. }))
  89. },
  90. Name: options.InterfaceName,
  91. MTU: options.MTU,
  92. Address: options.LocalAddress,
  93. PrivateKey: options.PrivateKey,
  94. ResolvePeer: func(domain string) (netip.Addr, error) {
  95. endpointAddresses, lookupErr := outbound.dnsRouter.Lookup(ctx, domain, outboundDialer.(dialer.ResolveDialer).QueryOptions())
  96. if lookupErr != nil {
  97. return netip.Addr{}, lookupErr
  98. }
  99. return endpointAddresses[0], nil
  100. },
  101. Peers: peers,
  102. Workers: options.Workers,
  103. })
  104. if err != nil {
  105. return nil, err
  106. }
  107. outbound.endpoint = wgEndpoint
  108. return outbound, nil
  109. }
  110. func (o *Outbound) Start(stage adapter.StartStage) error {
  111. switch stage {
  112. case adapter.StartStateStart:
  113. return o.endpoint.Start(false)
  114. case adapter.StartStatePostStart:
  115. return o.endpoint.Start(true)
  116. }
  117. return nil
  118. }
  119. func (o *Outbound) Close() error {
  120. return o.endpoint.Close()
  121. }
  122. func (o *Outbound) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
  123. switch network {
  124. case N.NetworkTCP:
  125. o.logger.InfoContext(ctx, "outbound connection to ", destination)
  126. case N.NetworkUDP:
  127. o.logger.InfoContext(ctx, "outbound packet connection to ", destination)
  128. }
  129. if destination.IsFqdn() {
  130. destinationAddresses, err := o.dnsRouter.Lookup(ctx, destination.Fqdn, adapter.DNSQueryOptions{})
  131. if err != nil {
  132. return nil, err
  133. }
  134. return N.DialSerial(ctx, o.endpoint, network, destination, destinationAddresses)
  135. } else if !destination.Addr.IsValid() {
  136. return nil, E.New("invalid destination: ", destination)
  137. }
  138. return o.endpoint.DialContext(ctx, network, destination)
  139. }
  140. func (o *Outbound) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
  141. o.logger.InfoContext(ctx, "outbound packet connection to ", destination)
  142. if destination.IsFqdn() {
  143. destinationAddresses, err := o.dnsRouter.Lookup(ctx, destination.Fqdn, adapter.DNSQueryOptions{})
  144. if err != nil {
  145. return nil, err
  146. }
  147. packetConn, _, err := N.ListenSerial(ctx, o.endpoint, destination, destinationAddresses)
  148. if err != nil {
  149. return nil, err
  150. }
  151. return packetConn, err
  152. }
  153. return o.endpoint.ListenPacket(ctx, destination)
  154. }
  155. func (o *Outbound) PreferredDomain(domain string) bool {
  156. return false
  157. }
  158. func (o *Outbound) PreferredAddress(address netip.Addr) bool {
  159. return o.endpoint.Lookup(address) != nil
  160. }
  161. func (o *Outbound) NewDirectRouteConnection(metadata adapter.InboundContext, routeContext tun.DirectRouteContext, timeout time.Duration) (tun.DirectRouteDestination, error) {
  162. return o.endpoint.NewDirectRouteConnection(metadata, routeContext, timeout)
  163. }