dialer.go 4.0 KB

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