outbound.go 5.2 KB

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