outbound.go 5.2 KB

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