outbound.go 5.4 KB

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