dialer.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. // +build !confonly
  2. package http
  3. import (
  4. "context"
  5. gotls "crypto/tls"
  6. "net/http"
  7. "net/url"
  8. "sync"
  9. "golang.org/x/net/http2"
  10. "github.com/v2fly/v2ray-core/v4/common"
  11. "github.com/v2fly/v2ray-core/v4/common/buf"
  12. "github.com/v2fly/v2ray-core/v4/common/net"
  13. "github.com/v2fly/v2ray-core/v4/transport/internet"
  14. "github.com/v2fly/v2ray-core/v4/transport/internet/tls"
  15. "github.com/v2fly/v2ray-core/v4/transport/pipe"
  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 {
  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
  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. return cn, nil
  62. },
  63. TLSClientConfig: tlsSettings.GetTLSConfig(tls.WithDestination(dest)),
  64. }
  65. client := &http.Client{
  66. Transport: transport,
  67. }
  68. globalDialerMap[dest] = client
  69. return client
  70. }
  71. // Dial dials a new TCP connection to the given destination.
  72. func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.MemoryStreamConfig) (internet.Connection, error) {
  73. httpSettings := streamSettings.ProtocolSettings.(*Config)
  74. tlsConfig := tls.ConfigFromStreamSettings(streamSettings)
  75. if tlsConfig == nil {
  76. return nil, newError("TLS must be enabled for http transport.").AtWarning()
  77. }
  78. client := getHTTPClient(ctx, dest, tlsConfig)
  79. opts := pipe.OptionsFromContext(ctx)
  80. preader, pwriter := pipe.New(opts...)
  81. breader := &buf.BufferedReader{Reader: preader}
  82. httpMethod := "PUT"
  83. if httpSettings.Method != "" {
  84. httpMethod = httpSettings.Method
  85. }
  86. httpHeaders := make(http.Header)
  87. for _, httpHeader := range httpSettings.Header {
  88. for _, httpHeaderValue := range httpHeader.Value {
  89. httpHeaders.Set(httpHeader.Name, httpHeaderValue)
  90. }
  91. }
  92. request := &http.Request{
  93. Method: httpMethod,
  94. Host: httpSettings.getRandomHost(),
  95. Body: breader,
  96. URL: &url.URL{
  97. Scheme: "https",
  98. Host: dest.NetAddr(),
  99. Path: httpSettings.getNormalizedPath(),
  100. },
  101. Proto: "HTTP/2",
  102. ProtoMajor: 2,
  103. ProtoMinor: 0,
  104. Header: httpHeaders,
  105. }
  106. // Disable any compression method from server.
  107. request.Header.Set("Accept-Encoding", "identity")
  108. response, err := client.Do(request) // nolint: bodyclose
  109. if err != nil {
  110. return nil, newError("failed to dial to ", dest).Base(err).AtWarning()
  111. }
  112. if response.StatusCode != 200 {
  113. return nil, newError("unexpected status", response.StatusCode).AtWarning()
  114. }
  115. bwriter := buf.NewBufferedWriter(pwriter)
  116. common.Must(bwriter.SetBuffered(false))
  117. return net.NewConnection(
  118. net.ConnectionOutput(response.Body),
  119. net.ConnectionInput(bwriter),
  120. net.ConnectionOnClose(common.ChainedClosable{breader, bwriter, response.Body}),
  121. ), nil
  122. }
  123. func init() {
  124. common.Must(internet.RegisterTransportDialer(protocolName, Dial))
  125. }