client.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package tls
  2. import (
  3. "context"
  4. "net"
  5. "os"
  6. "github.com/sagernet/sing-box/adapter"
  7. "github.com/sagernet/sing-box/common/badtls"
  8. C "github.com/sagernet/sing-box/constant"
  9. "github.com/sagernet/sing-box/option"
  10. M "github.com/sagernet/sing/common/metadata"
  11. N "github.com/sagernet/sing/common/network"
  12. aTLS "github.com/sagernet/sing/common/tls"
  13. )
  14. func NewDialerFromOptions(ctx context.Context, router adapter.Router, dialer N.Dialer, serverAddress string, options option.OutboundTLSOptions) (N.Dialer, error) {
  15. if !options.Enabled {
  16. return dialer, nil
  17. }
  18. config, err := NewClient(ctx, serverAddress, options)
  19. if err != nil {
  20. return nil, err
  21. }
  22. return NewDialer(dialer, config), nil
  23. }
  24. func NewClient(ctx context.Context, serverAddress string, options option.OutboundTLSOptions) (Config, error) {
  25. if !options.Enabled {
  26. return nil, nil
  27. }
  28. if options.ECH != nil && options.ECH.Enabled {
  29. if options.ECH.PQSignatureSchemesEnabled || options.ECH.DynamicRecordSizingDisabled {
  30. return NewECHClient(ctx, serverAddress, options)
  31. }
  32. } else if options.Reality != nil && options.Reality.Enabled {
  33. return NewRealityClient(ctx, serverAddress, options)
  34. } else if options.UTLS != nil && options.UTLS.Enabled {
  35. return NewUTLSClient(ctx, serverAddress, options)
  36. }
  37. return NewSTDClient(ctx, serverAddress, options)
  38. }
  39. func ClientHandshake(ctx context.Context, conn net.Conn, config Config) (Conn, error) {
  40. ctx, cancel := context.WithTimeout(ctx, C.TCPTimeout)
  41. defer cancel()
  42. tlsConn, err := aTLS.ClientHandshake(ctx, conn, config)
  43. if err != nil {
  44. return nil, err
  45. }
  46. readWaitConn, err := badtls.NewReadWaitConn(tlsConn)
  47. if err == nil {
  48. return readWaitConn, nil
  49. } else if err != os.ErrInvalid {
  50. return nil, err
  51. }
  52. return tlsConn, nil
  53. }
  54. type Dialer struct {
  55. dialer N.Dialer
  56. config Config
  57. }
  58. func NewDialer(dialer N.Dialer, config Config) N.Dialer {
  59. return &Dialer{dialer, config}
  60. }
  61. func (d *Dialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
  62. if network != N.NetworkTCP {
  63. return nil, os.ErrInvalid
  64. }
  65. conn, err := d.dialer.DialContext(ctx, network, destination)
  66. if err != nil {
  67. return nil, err
  68. }
  69. return ClientHandshake(ctx, conn, d.config)
  70. }
  71. func (d *Dialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
  72. return nil, os.ErrInvalid
  73. }