dialer.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. package splithttp
  2. import (
  3. "bytes"
  4. "context"
  5. gotls "crypto/tls"
  6. "io"
  7. gonet "net"
  8. "net/http"
  9. "net/http/httptrace"
  10. "net/url"
  11. "strconv"
  12. "sync"
  13. "time"
  14. "github.com/xtls/xray-core/common"
  15. "github.com/xtls/xray-core/common/buf"
  16. "github.com/xtls/xray-core/common/errors"
  17. "github.com/xtls/xray-core/common/net"
  18. "github.com/xtls/xray-core/common/signal/done"
  19. "github.com/xtls/xray-core/common/signal/semaphore"
  20. "github.com/xtls/xray-core/common/uuid"
  21. "github.com/xtls/xray-core/transport/internet"
  22. "github.com/xtls/xray-core/transport/internet/stat"
  23. "github.com/xtls/xray-core/transport/internet/tls"
  24. "github.com/xtls/xray-core/transport/pipe"
  25. "golang.org/x/net/http2"
  26. )
  27. type dialerConf struct {
  28. net.Destination
  29. *internet.MemoryStreamConfig
  30. }
  31. type reusedClient struct {
  32. download *http.Client
  33. upload *http.Client
  34. isH2 bool
  35. // pool of net.Conn, created using dialUploadConn
  36. uploadRawPool *sync.Pool
  37. dialUploadConn func(ctxInner context.Context) (net.Conn, error)
  38. }
  39. var (
  40. globalDialerMap map[dialerConf]reusedClient
  41. globalDialerAccess sync.Mutex
  42. )
  43. func getHTTPClient(ctx context.Context, dest net.Destination, streamSettings *internet.MemoryStreamConfig) reusedClient {
  44. globalDialerAccess.Lock()
  45. defer globalDialerAccess.Unlock()
  46. if globalDialerMap == nil {
  47. globalDialerMap = make(map[dialerConf]reusedClient)
  48. }
  49. if client, found := globalDialerMap[dialerConf{dest, streamSettings}]; found {
  50. return client
  51. }
  52. tlsConfig := tls.ConfigFromStreamSettings(streamSettings)
  53. isH2 := tlsConfig != nil && !(len(tlsConfig.NextProtocol) == 1 && tlsConfig.NextProtocol[0] == "http/1.1")
  54. var gotlsConfig *gotls.Config
  55. if tlsConfig != nil {
  56. gotlsConfig = tlsConfig.GetTLSConfig(tls.WithDestination(dest))
  57. }
  58. dialContext := func(ctxInner context.Context) (net.Conn, error) {
  59. conn, err := internet.DialSystem(ctxInner, dest, streamSettings.SocketSettings)
  60. if err != nil {
  61. return nil, err
  62. }
  63. if gotlsConfig != nil {
  64. if fingerprint := tls.GetFingerprint(tlsConfig.Fingerprint); fingerprint != nil {
  65. conn = tls.UClient(conn, gotlsConfig, fingerprint)
  66. if err := conn.(*tls.UConn).HandshakeContext(ctxInner); err != nil {
  67. return nil, err
  68. }
  69. } else {
  70. conn = tls.Client(conn, gotlsConfig)
  71. }
  72. }
  73. return conn, nil
  74. }
  75. var uploadTransport http.RoundTripper
  76. var downloadTransport http.RoundTripper
  77. if isH2 {
  78. downloadTransport = &http2.Transport{
  79. DialTLSContext: func(ctxInner context.Context, network string, addr string, cfg *gotls.Config) (net.Conn, error) {
  80. return dialContext(ctxInner)
  81. },
  82. IdleConnTimeout: 90 * time.Second,
  83. }
  84. uploadTransport = downloadTransport
  85. } else {
  86. httpDialContext := func(ctxInner context.Context, network string, addr string) (net.Conn, error) {
  87. return dialContext(ctxInner)
  88. }
  89. downloadTransport = &http.Transport{
  90. DialTLSContext: httpDialContext,
  91. DialContext: httpDialContext,
  92. IdleConnTimeout: 90 * time.Second,
  93. // chunked transfer download with keepalives is buggy with
  94. // http.Client and our custom dial context.
  95. DisableKeepAlives: true,
  96. }
  97. // we use uploadRawPool for that
  98. uploadTransport = nil
  99. }
  100. client := reusedClient{
  101. download: &http.Client{
  102. Transport: downloadTransport,
  103. },
  104. upload: &http.Client{
  105. Transport: uploadTransport,
  106. },
  107. isH2: isH2,
  108. uploadRawPool: &sync.Pool{},
  109. dialUploadConn: dialContext,
  110. }
  111. globalDialerMap[dialerConf{dest, streamSettings}] = client
  112. return client
  113. }
  114. func init() {
  115. common.Must(internet.RegisterTransportDialer(protocolName, Dial))
  116. }
  117. func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.MemoryStreamConfig) (stat.Connection, error) {
  118. errors.LogInfo(ctx, "dialing splithttp to ", dest)
  119. var requestURL url.URL
  120. transportConfiguration := streamSettings.ProtocolSettings.(*Config)
  121. tlsConfig := tls.ConfigFromStreamSettings(streamSettings)
  122. maxConcurrentUploads := transportConfiguration.GetNormalizedMaxConcurrentUploads()
  123. maxUploadSize := transportConfiguration.GetNormalizedMaxUploadSize()
  124. if tlsConfig != nil {
  125. requestURL.Scheme = "https"
  126. } else {
  127. requestURL.Scheme = "http"
  128. }
  129. requestURL.Host = transportConfiguration.Host
  130. if requestURL.Host == "" {
  131. requestURL.Host = dest.NetAddr()
  132. }
  133. requestURL.Path = transportConfiguration.GetNormalizedPath()
  134. httpClient := getHTTPClient(ctx, dest, streamSettings)
  135. var remoteAddr gonet.Addr
  136. var localAddr gonet.Addr
  137. // this is done when the TCP/UDP connection to the server was established,
  138. // and we can unblock the Dial function and print correct net addresses in
  139. // logs
  140. gotConn := done.New()
  141. var downResponse io.ReadCloser
  142. gotDownResponse := done.New()
  143. sessionIdUuid := uuid.New()
  144. sessionId := sessionIdUuid.String()
  145. go func() {
  146. trace := &httptrace.ClientTrace{
  147. GotConn: func(connInfo httptrace.GotConnInfo) {
  148. remoteAddr = connInfo.Conn.RemoteAddr()
  149. localAddr = connInfo.Conn.LocalAddr()
  150. gotConn.Close()
  151. },
  152. }
  153. // in case we hit an error, we want to unblock this part
  154. defer gotConn.Close()
  155. req, err := http.NewRequestWithContext(
  156. httptrace.WithClientTrace(context.WithoutCancel(ctx), trace),
  157. "GET",
  158. requestURL.String()+sessionId,
  159. nil,
  160. )
  161. if err != nil {
  162. errors.LogInfoInner(ctx, err, "failed to construct download http request")
  163. gotDownResponse.Close()
  164. return
  165. }
  166. req.Header = transportConfiguration.GetRequestHeader()
  167. response, err := httpClient.download.Do(req)
  168. gotConn.Close()
  169. if err != nil {
  170. errors.LogInfoInner(ctx, err, "failed to send download http request")
  171. gotDownResponse.Close()
  172. return
  173. }
  174. if response.StatusCode != 200 {
  175. response.Body.Close()
  176. errors.LogInfo(ctx, "invalid status code on download:", response.Status)
  177. gotDownResponse.Close()
  178. return
  179. }
  180. // skip "ooooooooook" response
  181. trashHeader := []byte{0}
  182. for {
  183. _, err = io.ReadFull(response.Body, trashHeader)
  184. if err != nil {
  185. response.Body.Close()
  186. errors.LogInfoInner(ctx, err, "failed to read initial response")
  187. gotDownResponse.Close()
  188. return
  189. }
  190. if trashHeader[0] == 'k' {
  191. break
  192. }
  193. }
  194. downResponse = response.Body
  195. gotDownResponse.Close()
  196. }()
  197. uploadUrl := requestURL.String() + sessionId + "/"
  198. uploadPipeReader, uploadPipeWriter := pipe.New(pipe.WithSizeLimit(maxUploadSize))
  199. go func() {
  200. requestsLimiter := semaphore.New(int(maxConcurrentUploads))
  201. var requestCounter int64
  202. // by offloading the uploads into a buffered pipe, multiple conn.Write
  203. // calls get automatically batched together into larger POST requests.
  204. // without batching, bandwidth is extremely limited.
  205. for {
  206. chunk, err := uploadPipeReader.ReadMultiBuffer()
  207. if err != nil {
  208. break
  209. }
  210. <-requestsLimiter.Wait()
  211. url := uploadUrl + strconv.FormatInt(requestCounter, 10)
  212. requestCounter += 1
  213. go func() {
  214. defer requestsLimiter.Signal()
  215. req, err := http.NewRequest("POST", url, &buf.MultiBufferContainer{MultiBuffer: chunk})
  216. if err != nil {
  217. errors.LogInfoInner(ctx, err, "failed to send upload")
  218. uploadPipeReader.Interrupt()
  219. return
  220. }
  221. req.ContentLength = int64(chunk.Len())
  222. req.Header = transportConfiguration.GetRequestHeader()
  223. if httpClient.isH2 {
  224. resp, err := httpClient.upload.Do(req)
  225. if err != nil {
  226. errors.LogInfoInner(ctx, err, "failed to send upload")
  227. uploadPipeReader.Interrupt()
  228. return
  229. }
  230. defer resp.Body.Close()
  231. if resp.StatusCode != 200 {
  232. errors.LogInfo(ctx, "failed to send upload, bad status code:", resp.Status)
  233. uploadPipeReader.Interrupt()
  234. return
  235. }
  236. } else {
  237. var uploadConn any
  238. // stringify the entire HTTP/1.1 request so it can be
  239. // safely retried. if instead req.Write is called multiple
  240. // times, the body is already drained after the first
  241. // request
  242. requestBytes := new(bytes.Buffer)
  243. common.Must(req.Write(requestBytes))
  244. for {
  245. uploadConn = httpClient.uploadRawPool.Get()
  246. newConnection := uploadConn == nil
  247. if newConnection {
  248. uploadConn, err = httpClient.dialUploadConn(context.WithoutCancel(ctx))
  249. if err != nil {
  250. errors.LogInfoInner(ctx, err, "failed to connect upload")
  251. uploadPipeReader.Interrupt()
  252. return
  253. }
  254. }
  255. _, err = uploadConn.(net.Conn).Write(requestBytes.Bytes())
  256. // if the write failed, we try another connection from
  257. // the pool, until the write on a new connection fails.
  258. // failed writes to a pooled connection are normal when
  259. // the connection has been closed in the meantime.
  260. if err == nil {
  261. break
  262. } else if newConnection {
  263. errors.LogInfoInner(ctx, err, "failed to send upload")
  264. uploadPipeReader.Interrupt()
  265. return
  266. }
  267. }
  268. httpClient.uploadRawPool.Put(uploadConn)
  269. }
  270. }()
  271. }
  272. }()
  273. // we want to block Dial until we know the remote address of the server,
  274. // for logging purposes
  275. <-gotConn.Wait()
  276. // necessary in order to send larger chunks in upload
  277. bufferedUploadPipeWriter := buf.NewBufferedWriter(uploadPipeWriter)
  278. bufferedUploadPipeWriter.SetBuffered(false)
  279. lazyDownload := &LazyReader{
  280. CreateReader: func() (io.ReadCloser, error) {
  281. <-gotDownResponse.Wait()
  282. if downResponse == nil {
  283. return nil, errors.New("downResponse failed")
  284. }
  285. return downResponse, nil
  286. },
  287. }
  288. conn := splitConn{
  289. writer: bufferedUploadPipeWriter,
  290. reader: lazyDownload,
  291. remoteAddr: remoteAddr,
  292. localAddr: localAddr,
  293. }
  294. return stat.Connection(&conn), nil
  295. }