outbound.go 4.9 KB

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