1
0

outbound.go 5.4 KB

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