dialer.go 4.2 KB

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