dialer.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. package http
  2. import (
  3. "context"
  4. gotls "crypto/tls"
  5. "net/http"
  6. "net/url"
  7. "sync"
  8. "github.com/xtls/xray-core/common"
  9. "github.com/xtls/xray-core/common/buf"
  10. "github.com/xtls/xray-core/common/net"
  11. "github.com/xtls/xray-core/common/net/cnc"
  12. "github.com/xtls/xray-core/common/session"
  13. "github.com/xtls/xray-core/transport/internet"
  14. "github.com/xtls/xray-core/transport/internet/tls"
  15. "github.com/xtls/xray-core/transport/pipe"
  16. "golang.org/x/net/http2"
  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, sockopt *internet.SocketConfig) (*http.Client, error) {
  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, nil
  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. dctx := context.Background()
  46. dctx = session.ContextWithID(dctx, session.IDFromContext(ctx))
  47. dctx = session.ContextWithOutbound(dctx, session.OutboundFromContext(ctx))
  48. pconn, err := internet.DialSystem(dctx, net.TCPDestination(address, port), sockopt)
  49. if err != nil {
  50. newError("failed to dial to " + addr).Base(err).AtError().WriteToLog()
  51. return nil, err
  52. }
  53. cn := gotls.Client(pconn, tlsConfig)
  54. if err := cn.Handshake(); err != nil {
  55. newError("failed to dial to " + addr).Base(err).AtError().WriteToLog()
  56. return nil, err
  57. }
  58. if !tlsConfig.InsecureSkipVerify {
  59. if err := cn.VerifyHostname(tlsConfig.ServerName); err != nil {
  60. newError("failed to dial to " + addr).Base(err).AtError().WriteToLog()
  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. if !state.NegotiatedProtocolIsMutual {
  69. return nil, newError("http2: could not negotiate protocol mutually").AtError()
  70. }
  71. return cn, nil
  72. },
  73. TLSClientConfig: tlsSettings.GetTLSConfig(tls.WithDestination(dest)),
  74. }
  75. client := &http.Client{
  76. Transport: transport,
  77. }
  78. globalDialerMap[dest] = client
  79. return client, nil
  80. }
  81. // Dial dials a new TCP connection to the given destination.
  82. func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.MemoryStreamConfig) (internet.Connection, error) {
  83. httpSettings := streamSettings.ProtocolSettings.(*Config)
  84. tlsConfig := tls.ConfigFromStreamSettings(streamSettings)
  85. if tlsConfig == nil {
  86. return nil, newError("TLS must be enabled for http transport.").AtWarning()
  87. }
  88. client, err := getHTTPClient(ctx, dest, tlsConfig, streamSettings.SocketSettings)
  89. if err != nil {
  90. return nil, err
  91. }
  92. opts := pipe.OptionsFromContext(ctx)
  93. preader, pwriter := pipe.New(opts...)
  94. breader := &buf.BufferedReader{Reader: preader}
  95. request := &http.Request{
  96. Method: "PUT",
  97. Host: httpSettings.getRandomHost(),
  98. Body: breader,
  99. URL: &url.URL{
  100. Scheme: "https",
  101. Host: dest.NetAddr(),
  102. Path: httpSettings.getNormalizedPath(),
  103. },
  104. Proto: "HTTP/2",
  105. ProtoMajor: 2,
  106. ProtoMinor: 0,
  107. Header: make(http.Header),
  108. }
  109. // Disable any compression method from server.
  110. request.Header.Set("Accept-Encoding", "identity")
  111. response, err := client.Do(request)
  112. if err != nil {
  113. return nil, newError("failed to dial to ", dest).Base(err).AtWarning()
  114. }
  115. if response.StatusCode != 200 {
  116. return nil, newError("unexpected status", response.StatusCode).AtWarning()
  117. }
  118. bwriter := buf.NewBufferedWriter(pwriter)
  119. common.Must(bwriter.SetBuffered(false))
  120. return cnc.NewConnection(
  121. cnc.ConnectionOutput(response.Body),
  122. cnc.ConnectionInput(bwriter),
  123. cnc.ConnectionOnClose(common.ChainedClosable{breader, bwriter, response.Body}),
  124. ), nil
  125. }
  126. func init() {
  127. common.Must(internet.RegisterTransportDialer(protocolName, Dial))
  128. }