dialer.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  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. "v2ray.com/core/common"
  11. "v2ray.com/core/common/buf"
  12. "v2ray.com/core/common/net"
  13. "v2ray.com/core/transport/internet"
  14. "v2ray.com/core/transport/internet/tls"
  15. "v2ray.com/core/transport/pipe"
  16. )
  17. var (
  18. globalDialerMap map[net.Destination]*http.Client
  19. globalDialerAccess sync.Mutex
  20. )
  21. func getHTTPClient(_ 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(context.Background(), 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
  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 := getHTTPClient(ctx, dest, tlsConfig)
  82. opts := pipe.OptionsFromContext(ctx)
  83. preader, pwriter := pipe.New(opts...)
  84. breader := &buf.BufferedReader{Reader: preader}
  85. request := &http.Request{
  86. Method: "PUT",
  87. Host: httpSettings.getRandomHost(),
  88. Body: breader,
  89. URL: &url.URL{
  90. Scheme: "https",
  91. Host: dest.NetAddr(),
  92. Path: httpSettings.getNormalizedPath(),
  93. },
  94. Proto: "HTTP/2",
  95. ProtoMajor: 2,
  96. ProtoMinor: 0,
  97. Header: make(http.Header),
  98. }
  99. // Disable any compression method from server.
  100. request.Header.Set("Accept-Encoding", "identity")
  101. response, err := client.Do(request) // nolint: bodyclose
  102. if err != nil {
  103. return nil, newError("failed to dial to ", dest).Base(err).AtWarning()
  104. }
  105. if response.StatusCode != 200 {
  106. return nil, newError("unexpected status", response.StatusCode).AtWarning()
  107. }
  108. bwriter := buf.NewBufferedWriter(pwriter)
  109. common.Must(bwriter.SetBuffered(false))
  110. return net.NewConnection(
  111. net.ConnectionOutput(response.Body),
  112. net.ConnectionInput(bwriter),
  113. net.ConnectionOnClose(common.ChainedClosable{breader, bwriter, response.Body}),
  114. ), nil
  115. }
  116. func init() {
  117. common.Must(internet.RegisterTransportDialer(protocolName, Dial))
  118. }