outbound.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  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. "github.com/sagernet/sing/service"
  21. )
  22. func RegisterOutbound(registry *outbound.Registry) {
  23. outbound.Register[option.LegacyWireGuardOutboundOptions](registry, C.TypeWireGuard, NewOutbound)
  24. }
  25. var (
  26. _ adapter.Endpoint = (*Endpoint)(nil)
  27. _ adapter.InterfaceUpdateListener = (*Endpoint)(nil)
  28. )
  29. type Outbound struct {
  30. outbound.Adapter
  31. ctx context.Context
  32. router adapter.Router
  33. logger logger.ContextLogger
  34. localAddresses []netip.Prefix
  35. endpoint *wireguard.Endpoint
  36. }
  37. func NewOutbound(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.LegacyWireGuardOutboundOptions) (adapter.Outbound, error) {
  38. deprecated.Report(ctx, deprecated.OptionWireGuardOutbound)
  39. if options.GSO {
  40. deprecated.Report(ctx, deprecated.OptionWireGuardGSO)
  41. }
  42. outbound := &Outbound{
  43. Adapter: outbound.NewAdapterWithDialerOptions(C.TypeWireGuard, tag, []string{N.NetworkTCP, N.NetworkUDP}, options.DialerOptions),
  44. ctx: ctx,
  45. router: router,
  46. logger: logger,
  47. localAddresses: options.LocalAddress,
  48. }
  49. if options.Detour == "" {
  50. options.IsWireGuardListener = true
  51. } else if options.GSO {
  52. return nil, E.New("gso is conflict with detour")
  53. }
  54. outboundDialer, err := dialer.New(ctx, options.DialerOptions)
  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(service.FromContext[adapter.NetworkManager](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 := router.Lookup(ctx, domain, dns.DomainStrategy(options.DomainStrategy))
  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) InterfaceUpdated() {
  120. o.endpoint.BindUpdate()
  121. return
  122. }
  123. func (o *Outbound) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
  124. switch network {
  125. case N.NetworkTCP:
  126. o.logger.InfoContext(ctx, "outbound connection to ", destination)
  127. case N.NetworkUDP:
  128. o.logger.InfoContext(ctx, "outbound packet connection to ", destination)
  129. }
  130. if destination.IsFqdn() {
  131. destinationAddresses, err := o.router.LookupDefault(ctx, destination.Fqdn)
  132. if err != nil {
  133. return nil, err
  134. }
  135. return N.DialSerial(ctx, o.endpoint, network, destination, destinationAddresses)
  136. } else if !destination.Addr.IsValid() {
  137. return nil, E.New("invalid destination: ", destination)
  138. }
  139. return o.endpoint.DialContext(ctx, network, destination)
  140. }
  141. func (o *Outbound) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
  142. o.logger.InfoContext(ctx, "outbound packet connection to ", destination)
  143. if destination.IsFqdn() {
  144. destinationAddresses, err := o.router.LookupDefault(ctx, destination.Fqdn)
  145. if err != nil {
  146. return nil, err
  147. }
  148. packetConn, _, err := N.ListenSerial(ctx, o.endpoint, destination, destinationAddresses)
  149. if err != nil {
  150. return nil, err
  151. }
  152. return packetConn, err
  153. }
  154. return o.endpoint.ListenPacket(ctx, destination)
  155. }