client.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package tls
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "net"
  6. "os"
  7. "github.com/sagernet/sing-box/adapter"
  8. "github.com/sagernet/sing-box/common/badtls"
  9. C "github.com/sagernet/sing-box/constant"
  10. "github.com/sagernet/sing-box/option"
  11. M "github.com/sagernet/sing/common/metadata"
  12. N "github.com/sagernet/sing/common/network"
  13. )
  14. func NewDialerFromOptions(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(router, serverAddress, options)
  19. if err != nil {
  20. return nil, err
  21. }
  22. return NewDialer(dialer, config), nil
  23. }
  24. func NewClient(router adapter.Router, 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. return NewECHClient(router, serverAddress, options)
  30. } else if options.UTLS != nil && options.UTLS.Enabled {
  31. return NewUTLSClient(router, serverAddress, options)
  32. } else {
  33. return NewSTDClient(serverAddress, options)
  34. }
  35. }
  36. func ClientHandshake(ctx context.Context, conn net.Conn, config Config) (Conn, error) {
  37. tlsConn := config.Client(conn)
  38. ctx, cancel := context.WithTimeout(ctx, C.TCPTimeout)
  39. defer cancel()
  40. err := tlsConn.HandshakeContext(ctx)
  41. if err != nil {
  42. return nil, err
  43. }
  44. if stdConn, isSTD := tlsConn.(*tls.Conn); isSTD {
  45. var badConn badtls.TLSConn
  46. badConn, err = badtls.Create(stdConn)
  47. if err == nil {
  48. return badConn, nil
  49. }
  50. }
  51. return tlsConn, nil
  52. }
  53. type Dialer struct {
  54. dialer N.Dialer
  55. config Config
  56. }
  57. func NewDialer(dialer N.Dialer, config Config) N.Dialer {
  58. return &Dialer{dialer, config}
  59. }
  60. func (d *Dialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
  61. if network != N.NetworkTCP {
  62. return nil, os.ErrInvalid
  63. }
  64. conn, err := d.dialer.DialContext(ctx, network, destination)
  65. if err != nil {
  66. return nil, err
  67. }
  68. return ClientHandshake(ctx, conn, d.config)
  69. }
  70. func (d *Dialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
  71. return nil, os.ErrInvalid
  72. }