client.go 7.4 KB

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