dialer.go 4.2 KB

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