outbound.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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-dns"
  15. "github.com/sagernet/sing/common"
  16. E "github.com/sagernet/sing/common/exceptions"
  17. "github.com/sagernet/sing/common/logger"
  18. M "github.com/sagernet/sing/common/metadata"
  19. N "github.com/sagernet/sing/common/network"
  20. )
  21. func RegisterOutbound(registry *outbound.Registry) {
  22. outbound.Register[option.LegacyWireGuardOutboundOptions](registry, C.TypeWireGuard, NewOutbound)
  23. }
  24. var (
  25. _ adapter.Endpoint = (*Endpoint)(nil)
  26. _ adapter.InterfaceUpdateListener = (*Endpoint)(nil)
  27. )
  28. type Outbound struct {
  29. outbound.Adapter
  30. ctx context.Context
  31. router adapter.Router
  32. logger logger.ContextLogger
  33. localAddresses []netip.Prefix
  34. endpoint *wireguard.Endpoint
  35. }
  36. func NewOutbound(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.LegacyWireGuardOutboundOptions) (adapter.Outbound, error) {
  37. deprecated.Report(ctx, deprecated.OptionWireGuardOutbound)
  38. if options.GSO {
  39. deprecated.Report(ctx, deprecated.OptionWireGuardGSO)
  40. }
  41. outbound := &Outbound{
  42. Adapter: outbound.NewAdapterWithDialerOptions(C.TypeWireGuard, tag, []string{N.NetworkTCP, N.NetworkUDP}, options.DialerOptions),
  43. ctx: ctx,
  44. router: router,
  45. logger: logger,
  46. localAddresses: options.LocalAddress,
  47. }
  48. if options.Detour == "" {
  49. options.IsWireGuardListener = true
  50. } else if options.GSO {
  51. return nil, E.New("gso is conflict with detour")
  52. }
  53. outboundDialer, err := dialer.New(ctx, options.DialerOptions)
  54. if err != nil {
  55. return nil, err
  56. }
  57. peers := common.Map(options.Peers, func(it option.LegacyWireGuardPeer) wireguard.PeerOptions {
  58. return wireguard.PeerOptions{
  59. Endpoint: it.ServerOptions.Build(),
  60. PublicKey: it.PublicKey,
  61. PreSharedKey: it.PreSharedKey,
  62. AllowedIPs: it.AllowedIPs,
  63. // PersistentKeepaliveInterval: time.Duration(it.PersistentKeepaliveInterval),
  64. Reserved: it.Reserved,
  65. }
  66. })
  67. if len(peers) == 0 {
  68. peers = []wireguard.PeerOptions{{
  69. Endpoint: options.ServerOptions.Build(),
  70. PublicKey: options.PeerPublicKey,
  71. PreSharedKey: options.PreSharedKey,
  72. AllowedIPs: []netip.Prefix{netip.PrefixFrom(netip.IPv4Unspecified(), 0), netip.PrefixFrom(netip.IPv6Unspecified(), 0)},
  73. Reserved: options.Reserved,
  74. }}
  75. }
  76. wgEndpoint, err := wireguard.NewEndpoint(wireguard.EndpointOptions{
  77. Context: ctx,
  78. Logger: logger,
  79. System: options.SystemInterface,
  80. Dialer: outboundDialer,
  81. CreateDialer: func(interfaceName string) N.Dialer {
  82. return common.Must1(dialer.NewDefault(ctx, option.DialerOptions{
  83. BindInterface: interfaceName,
  84. }))
  85. },
  86. Name: options.InterfaceName,
  87. MTU: options.MTU,
  88. Address: options.LocalAddress,
  89. PrivateKey: options.PrivateKey,
  90. ResolvePeer: func(domain string) (netip.Addr, error) {
  91. endpointAddresses, lookupErr := router.Lookup(ctx, domain, dns.DomainStrategy(options.DomainStrategy))
  92. if lookupErr != nil {
  93. return netip.Addr{}, lookupErr
  94. }
  95. return endpointAddresses[0], nil
  96. },
  97. Peers: peers,
  98. Workers: options.Workers,
  99. })
  100. if err != nil {
  101. return nil, err
  102. }
  103. outbound.endpoint = wgEndpoint
  104. return outbound, nil
  105. }
  106. func (o *Outbound) Start(stage adapter.StartStage) error {
  107. switch stage {
  108. case adapter.StartStateStart:
  109. return o.endpoint.Start(false)
  110. case adapter.StartStatePostStart:
  111. return o.endpoint.Start(true)
  112. }
  113. return nil
  114. }
  115. func (o *Outbound) Close() error {
  116. return o.endpoint.Close()
  117. }
  118. func (o *Outbound) InterfaceUpdated() {
  119. o.endpoint.BindUpdate()
  120. return
  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.router.LookupDefault(ctx, destination.Fqdn)
  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.router.LookupDefault(ctx, destination.Fqdn)
  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. }