dialer.go 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. package http
  2. import (
  3. "context"
  4. gotls "crypto/tls"
  5. "net/http"
  6. "net/url"
  7. "sync"
  8. "github.com/xtls/xray-core/common"
  9. "github.com/xtls/xray-core/common/buf"
  10. "github.com/xtls/xray-core/common/net"
  11. "github.com/xtls/xray-core/common/net/cnc"
  12. "github.com/xtls/xray-core/transport/internet"
  13. "github.com/xtls/xray-core/transport/internet/tls"
  14. "github.com/xtls/xray-core/transport/pipe"
  15. "golang.org/x/net/http2"
  16. )
  17. var (
  18. globalDialerMap map[net.Destination]*http.Client
  19. globalDialerAccess sync.Mutex
  20. )
  21. func getHTTPClient(ctx context.Context, dest net.Destination, tlsSettings *tls.Config) (*http.Client, error) {
  22. globalDialerAccess.Lock()
  23. defer globalDialerAccess.Unlock()
  24. if globalDialerMap == nil {
  25. globalDialerMap = make(map[net.Destination]*http.Client)
  26. }
  27. if client, found := globalDialerMap[dest]; found {
  28. return client, nil
  29. }
  30. transport := &http2.Transport{
  31. DialTLS: func(network string, addr string, tlsConfig *gotls.Config) (net.Conn, error) {
  32. rawHost, rawPort, err := net.SplitHostPort(addr)
  33. if err != nil {
  34. return nil, err
  35. }
  36. if len(rawPort) == 0 {
  37. rawPort = "443"
  38. }
  39. port, err := net.PortFromString(rawPort)
  40. if err != nil {
  41. return nil, err
  42. }
  43. address := net.ParseAddress(rawHost)
  44. pconn, err := internet.DialSystem(ctx, net.TCPDestination(address, port), nil)
  45. if err != nil {
  46. return nil, err
  47. }
  48. cn := gotls.Client(pconn, tlsConfig)
  49. if err := cn.Handshake(); err != nil {
  50. return nil, err
  51. }
  52. if !tlsConfig.InsecureSkipVerify {
  53. if err := cn.VerifyHostname(tlsConfig.ServerName); err != nil {
  54. return nil, err
  55. }
  56. }
  57. state := cn.ConnectionState()
  58. if p := state.NegotiatedProtocol; p != http2.NextProtoTLS {
  59. return nil, newError("http2: unexpected ALPN protocol " + p + "; want q" + http2.NextProtoTLS).AtError()
  60. }
  61. if !state.NegotiatedProtocolIsMutual {
  62. return nil, newError("http2: could not negotiate protocol mutually").AtError()
  63. }
  64. return cn, nil
  65. },
  66. TLSClientConfig: tlsSettings.GetTLSConfig(tls.WithDestination(dest)),
  67. }
  68. client := &http.Client{
  69. Transport: transport,
  70. }
  71. globalDialerMap[dest] = client
  72. return client, nil
  73. }
  74. // Dial dials a new TCP connection to the given destination.
  75. func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.MemoryStreamConfig) (internet.Connection, error) {
  76. httpSettings := streamSettings.ProtocolSettings.(*Config)
  77. tlsConfig := tls.ConfigFromStreamSettings(streamSettings)
  78. if tlsConfig == nil {
  79. return nil, newError("TLS must be enabled for http transport.").AtWarning()
  80. }
  81. client, err := getHTTPClient(ctx, dest, tlsConfig)
  82. if err != nil {
  83. return nil, err
  84. }
  85. opts := pipe.OptionsFromContext(ctx)
  86. preader, pwriter := pipe.New(opts...)
  87. breader := &buf.BufferedReader{Reader: preader}
  88. request := &http.Request{
  89. Method: "PUT",
  90. Host: httpSettings.getRandomHost(),
  91. Body: breader,
  92. URL: &url.URL{
  93. Scheme: "https",
  94. Host: dest.NetAddr(),
  95. Path: httpSettings.getNormalizedPath(),
  96. },
  97. Proto: "HTTP/2",
  98. ProtoMajor: 2,
  99. ProtoMinor: 0,
  100. Header: make(http.Header),
  101. }
  102. // Disable any compression method from server.
  103. request.Header.Set("Accept-Encoding", "identity")
  104. response, err := client.Do(request)
  105. if err != nil {
  106. return nil, newError("failed to dial to ", dest).Base(err).AtWarning()
  107. }
  108. if response.StatusCode != 200 {
  109. return nil, newError("unexpected status", response.StatusCode).AtWarning()
  110. }
  111. bwriter := buf.NewBufferedWriter(pwriter)
  112. common.Must(bwriter.SetBuffered(false))
  113. return cnc.NewConnection(
  114. cnc.ConnectionOutput(response.Body),
  115. cnc.ConnectionInput(bwriter),
  116. cnc.ConnectionOnClose(common.ChainedClosable{breader, bwriter, response.Body}),
  117. ), nil
  118. }
  119. func init() {
  120. common.Must(internet.RegisterTransportDialer(protocolName, Dial))
  121. }