outbound.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  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. outbound := &Outbound{
  40. Adapter: outbound.NewAdapterWithDialerOptions(C.TypeWireGuard, tag, []string{N.NetworkTCP, N.NetworkUDP}, options.DialerOptions),
  41. ctx: ctx,
  42. router: router,
  43. logger: logger,
  44. localAddresses: options.LocalAddress,
  45. }
  46. if options.Detour == "" {
  47. options.IsWireGuardListener = true
  48. } else if options.GSO {
  49. return nil, E.New("gso is conflict with detour")
  50. }
  51. outboundDialer, err := dialer.New(ctx, options.DialerOptions)
  52. if err != nil {
  53. return nil, err
  54. }
  55. peers := common.Map(options.Peers, func(it option.LegacyWireGuardPeer) wireguard.PeerOptions {
  56. return wireguard.PeerOptions{
  57. Endpoint: it.ServerOptions.Build(),
  58. PublicKey: it.PublicKey,
  59. PreSharedKey: it.PreSharedKey,
  60. AllowedIPs: it.AllowedIPs,
  61. // PersistentKeepaliveInterval: time.Duration(it.PersistentKeepaliveInterval),
  62. Reserved: it.Reserved,
  63. }
  64. })
  65. if len(peers) == 0 {
  66. peers = []wireguard.PeerOptions{{
  67. Endpoint: options.ServerOptions.Build(),
  68. PublicKey: options.PeerPublicKey,
  69. PreSharedKey: options.PreSharedKey,
  70. AllowedIPs: []netip.Prefix{netip.PrefixFrom(netip.IPv4Unspecified(), 0), netip.PrefixFrom(netip.IPv6Unspecified(), 0)},
  71. Reserved: options.Reserved,
  72. }}
  73. }
  74. wgEndpoint, err := wireguard.NewEndpoint(wireguard.EndpointOptions{
  75. Context: ctx,
  76. Logger: logger,
  77. System: options.SystemInterface,
  78. Dialer: outboundDialer,
  79. CreateDialer: func(interfaceName string) N.Dialer {
  80. return common.Must1(dialer.NewDefault(service.FromContext[adapter.NetworkManager](ctx), option.DialerOptions{
  81. BindInterface: interfaceName,
  82. }))
  83. },
  84. Name: options.InterfaceName,
  85. MTU: options.MTU,
  86. GSO: options.GSO,
  87. Address: options.LocalAddress,
  88. PrivateKey: options.PrivateKey,
  89. ResolvePeer: func(domain string) (netip.Addr, error) {
  90. endpointAddresses, lookupErr := router.Lookup(ctx, domain, dns.DomainStrategy(options.DomainStrategy))
  91. if lookupErr != nil {
  92. return netip.Addr{}, lookupErr
  93. }
  94. return endpointAddresses[0], nil
  95. },
  96. Peers: peers,
  97. Workers: options.Workers,
  98. })
  99. if err != nil {
  100. return nil, err
  101. }
  102. outbound.endpoint = wgEndpoint
  103. return outbound, nil
  104. }
  105. func (o *Outbound) Start(stage adapter.StartStage) error {
  106. switch stage {
  107. case adapter.StartStateStart:
  108. return o.endpoint.Start(false)
  109. case adapter.StartStatePostStart:
  110. return o.endpoint.Start(true)
  111. }
  112. return nil
  113. }
  114. func (o *Outbound) Close() error {
  115. return o.endpoint.Close()
  116. }
  117. func (o *Outbound) InterfaceUpdated() {
  118. o.endpoint.BindUpdate()
  119. return
  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.router.LookupDefault(ctx, destination.Fqdn)
  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.router.LookupDefault(ctx, destination.Fqdn)
  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. }