client.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. package http
  2. import (
  3. "bufio"
  4. "bytes"
  5. "context"
  6. "encoding/base64"
  7. "io"
  8. "net/http"
  9. "net/url"
  10. "sync"
  11. "time"
  12. "golang.org/x/net/http2"
  13. core "github.com/v2fly/v2ray-core/v5"
  14. "github.com/v2fly/v2ray-core/v5/common"
  15. "github.com/v2fly/v2ray-core/v5/common/buf"
  16. "github.com/v2fly/v2ray-core/v5/common/bytespool"
  17. "github.com/v2fly/v2ray-core/v5/common/net"
  18. "github.com/v2fly/v2ray-core/v5/common/protocol"
  19. "github.com/v2fly/v2ray-core/v5/common/retry"
  20. "github.com/v2fly/v2ray-core/v5/common/session"
  21. "github.com/v2fly/v2ray-core/v5/common/signal"
  22. "github.com/v2fly/v2ray-core/v5/common/task"
  23. "github.com/v2fly/v2ray-core/v5/features/policy"
  24. "github.com/v2fly/v2ray-core/v5/proxy"
  25. "github.com/v2fly/v2ray-core/v5/transport"
  26. "github.com/v2fly/v2ray-core/v5/transport/internet"
  27. "github.com/v2fly/v2ray-core/v5/transport/internet/tls"
  28. )
  29. type Client struct {
  30. serverPicker protocol.ServerPicker
  31. policyManager policy.Manager
  32. h1SkipWaitForReply bool
  33. }
  34. type h2Conn struct {
  35. rawConn net.Conn
  36. h2Conn *http2.ClientConn
  37. }
  38. var (
  39. cachedH2Mutex sync.Mutex
  40. cachedH2Conns map[net.Destination]h2Conn
  41. )
  42. // NewClient create a new http client based on the given config.
  43. func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) {
  44. serverList := protocol.NewServerList()
  45. for _, rec := range config.Server {
  46. s, err := protocol.NewServerSpecFromPB(rec)
  47. if err != nil {
  48. return nil, newError("failed to get server spec").Base(err)
  49. }
  50. serverList.AddServer(s)
  51. }
  52. if serverList.Size() == 0 {
  53. return nil, newError("0 target server")
  54. }
  55. v := core.MustFromContext(ctx)
  56. return &Client{
  57. serverPicker: protocol.NewRoundRobinServerPicker(serverList),
  58. policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
  59. h1SkipWaitForReply: config.H1SkipWaitForReply,
  60. }, nil
  61. }
  62. // Process implements proxy.Outbound.Process. We first create a socket tunnel via HTTP CONNECT method, then redirect all inbound traffic to that tunnel.
  63. func (c *Client) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
  64. outbound := session.OutboundFromContext(ctx)
  65. if outbound == nil || !outbound.Target.IsValid() {
  66. return newError("target not specified.")
  67. }
  68. target := outbound.Target
  69. targetAddr := target.NetAddr()
  70. if target.Network == net.Network_UDP {
  71. return newError("UDP is not supported by HTTP outbound")
  72. }
  73. var user *protocol.MemoryUser
  74. var conn internet.Connection
  75. var firstPayload []byte
  76. if reader, ok := link.Reader.(buf.TimeoutReader); ok {
  77. // 0-RTT optimization for HTTP/2: If the payload comes very soon, it can be
  78. // transmitted together. Note we should not get stuck here, as the payload may
  79. // not exist (considering to access MySQL database via a HTTP proxy, where the
  80. // server sends hello to the client first).
  81. waitTime := proxy.FirstPayloadTimeout
  82. if c.h1SkipWaitForReply {
  83. // Some server require first write to be present in client hello.
  84. // Increase timeout to if the client have explicitly requested to skip waiting for reply.
  85. waitTime = time.Second
  86. }
  87. if mbuf, _ := reader.ReadMultiBufferTimeout(waitTime); mbuf != nil {
  88. mlen := mbuf.Len()
  89. firstPayload = bytespool.Alloc(mlen)
  90. mbuf, _ = buf.SplitBytes(mbuf, firstPayload)
  91. firstPayload = firstPayload[:mlen]
  92. buf.ReleaseMulti(mbuf)
  93. defer bytespool.Free(firstPayload)
  94. }
  95. }
  96. if err := retry.ExponentialBackoff(5, 100).On(func() error {
  97. server := c.serverPicker.PickServer()
  98. dest := server.Destination()
  99. user = server.PickUser()
  100. netConn, firstResp, err := setUpHTTPTunnel(ctx, dest, targetAddr, user, dialer, firstPayload, c.h1SkipWaitForReply)
  101. if netConn != nil {
  102. if _, ok := netConn.(*http2Conn); !ok && !c.h1SkipWaitForReply {
  103. if _, err := netConn.Write(firstPayload); err != nil {
  104. netConn.Close()
  105. return err
  106. }
  107. }
  108. if firstResp != nil {
  109. if err := link.Writer.WriteMultiBuffer(firstResp); err != nil {
  110. return err
  111. }
  112. }
  113. conn = internet.Connection(netConn)
  114. }
  115. return err
  116. }); err != nil {
  117. return newError("failed to find an available destination").Base(err)
  118. }
  119. defer func() {
  120. if err := conn.Close(); err != nil {
  121. newError("failed to closed connection").Base(err).WriteToLog(session.ExportIDToError(ctx))
  122. }
  123. }()
  124. p := c.policyManager.ForLevel(0)
  125. if user != nil {
  126. p = c.policyManager.ForLevel(user.Level)
  127. }
  128. ctx, cancel := context.WithCancel(ctx)
  129. timer := signal.CancelAfterInactivity(ctx, cancel, p.Timeouts.ConnectionIdle)
  130. requestFunc := func() error {
  131. defer timer.SetTimeout(p.Timeouts.DownlinkOnly)
  132. return buf.Copy(link.Reader, buf.NewWriter(conn), buf.UpdateActivity(timer))
  133. }
  134. responseFunc := func() error {
  135. defer timer.SetTimeout(p.Timeouts.UplinkOnly)
  136. return buf.Copy(buf.NewReader(conn), link.Writer, buf.UpdateActivity(timer))
  137. }
  138. responseDonePost := task.OnSuccess(responseFunc, task.Close(link.Writer))
  139. if err := task.Run(ctx, requestFunc, responseDonePost); err != nil {
  140. return newError("connection ends").Base(err)
  141. }
  142. return nil
  143. }
  144. // setUpHTTPTunnel will create a socket tunnel via HTTP CONNECT method
  145. func setUpHTTPTunnel(ctx context.Context, dest net.Destination, target string, user *protocol.MemoryUser, dialer internet.Dialer, firstPayload []byte, writeFirstPayloadInH1 bool,
  146. ) (net.Conn, buf.MultiBuffer, error) {
  147. req := &http.Request{
  148. Method: http.MethodConnect,
  149. URL: &url.URL{Host: target},
  150. Header: make(http.Header),
  151. Host: target,
  152. }
  153. if user != nil && user.Account != nil {
  154. account := user.Account.(*Account)
  155. auth := account.GetUsername() + ":" + account.GetPassword()
  156. req.Header.Set("Proxy-Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(auth)))
  157. }
  158. connectHTTP1 := func(rawConn net.Conn) (net.Conn, buf.MultiBuffer, error) {
  159. req.Header.Set("Proxy-Connection", "Keep-Alive")
  160. if !writeFirstPayloadInH1 {
  161. err := req.Write(rawConn)
  162. if err != nil {
  163. rawConn.Close()
  164. return nil, nil, err
  165. }
  166. } else {
  167. buffer := bytes.NewBuffer(nil)
  168. err := req.Write(buffer)
  169. if err != nil {
  170. rawConn.Close()
  171. return nil, nil, err
  172. }
  173. _, err = io.Copy(buffer, bytes.NewReader(firstPayload))
  174. if err != nil {
  175. rawConn.Close()
  176. return nil, nil, err
  177. }
  178. _, err = rawConn.Write(buffer.Bytes())
  179. if err != nil {
  180. rawConn.Close()
  181. return nil, nil, err
  182. }
  183. }
  184. bufferedReader := bufio.NewReader(rawConn)
  185. resp, err := http.ReadResponse(bufferedReader, req)
  186. if err != nil {
  187. rawConn.Close()
  188. return nil, nil, err
  189. }
  190. defer resp.Body.Close()
  191. if resp.StatusCode != http.StatusOK {
  192. rawConn.Close()
  193. return nil, nil, newError("Proxy responded with non 200 code: " + resp.Status)
  194. }
  195. if bufferedReader.Buffered() > 0 {
  196. payload, err := buf.ReadFrom(io.LimitReader(bufferedReader, int64(bufferedReader.Buffered())))
  197. if err != nil {
  198. return nil, nil, newError("unable to drain buffer: ").Base(err)
  199. }
  200. return rawConn, payload, nil
  201. }
  202. return rawConn, nil, nil
  203. }
  204. connectHTTP2 := func(rawConn net.Conn, h2clientConn *http2.ClientConn) (net.Conn, error) {
  205. pr, pw := io.Pipe()
  206. req.Body = pr
  207. var pErr error
  208. var wg sync.WaitGroup
  209. wg.Add(1)
  210. go func() {
  211. _, pErr = pw.Write(firstPayload)
  212. wg.Done()
  213. }()
  214. resp, err := h2clientConn.RoundTrip(req) // nolint: bodyclose
  215. if err != nil {
  216. rawConn.Close()
  217. return nil, err
  218. }
  219. wg.Wait()
  220. if pErr != nil {
  221. rawConn.Close()
  222. return nil, pErr
  223. }
  224. if resp.StatusCode != http.StatusOK {
  225. rawConn.Close()
  226. return nil, newError("Proxy responded with non 200 code: " + resp.Status)
  227. }
  228. return newHTTP2Conn(rawConn, pw, resp.Body), nil
  229. }
  230. cachedH2Mutex.Lock()
  231. cachedConn, cachedConnFound := cachedH2Conns[dest]
  232. cachedH2Mutex.Unlock()
  233. if cachedConnFound {
  234. rc, cc := cachedConn.rawConn, cachedConn.h2Conn
  235. if cc.CanTakeNewRequest() {
  236. proxyConn, err := connectHTTP2(rc, cc)
  237. if err != nil {
  238. return nil, nil, err
  239. }
  240. return proxyConn, nil, nil
  241. }
  242. }
  243. rawConn, err := dialer.Dial(ctx, dest)
  244. if err != nil {
  245. return nil, nil, err
  246. }
  247. iConn := rawConn
  248. if statConn, ok := iConn.(*internet.StatCouterConnection); ok {
  249. iConn = statConn.Connection
  250. }
  251. nextProto := ""
  252. if tlsConn, ok := iConn.(*tls.Conn); ok {
  253. if err := tlsConn.Handshake(); err != nil {
  254. rawConn.Close()
  255. return nil, nil, err
  256. }
  257. nextProto = tlsConn.ConnectionState().NegotiatedProtocol
  258. }
  259. switch nextProto {
  260. case "", "http/1.1":
  261. return connectHTTP1(rawConn)
  262. case "h2":
  263. t := http2.Transport{}
  264. h2clientConn, err := t.NewClientConn(rawConn)
  265. if err != nil {
  266. rawConn.Close()
  267. return nil, nil, err
  268. }
  269. proxyConn, err := connectHTTP2(rawConn, h2clientConn)
  270. if err != nil {
  271. rawConn.Close()
  272. return nil, nil, err
  273. }
  274. cachedH2Mutex.Lock()
  275. if cachedH2Conns == nil {
  276. cachedH2Conns = make(map[net.Destination]h2Conn)
  277. }
  278. cachedH2Conns[dest] = h2Conn{
  279. rawConn: rawConn,
  280. h2Conn: h2clientConn,
  281. }
  282. cachedH2Mutex.Unlock()
  283. return proxyConn, nil, err
  284. default:
  285. return nil, nil, newError("negotiated unsupported application layer protocol: " + nextProto)
  286. }
  287. }
  288. func newHTTP2Conn(c net.Conn, pipedReqBody *io.PipeWriter, respBody io.ReadCloser) net.Conn {
  289. return &http2Conn{Conn: c, in: pipedReqBody, out: respBody}
  290. }
  291. type http2Conn struct {
  292. net.Conn
  293. in *io.PipeWriter
  294. out io.ReadCloser
  295. }
  296. func (h *http2Conn) Read(p []byte) (n int, err error) {
  297. return h.out.Read(p)
  298. }
  299. func (h *http2Conn) Write(p []byte) (n int, err error) {
  300. return h.in.Write(p)
  301. }
  302. func (h *http2Conn) Close() error {
  303. h.in.Close()
  304. return h.out.Close()
  305. }
  306. func init() {
  307. common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  308. return NewClient(ctx, config.(*ClientConfig))
  309. }))
  310. }