client.go 6.7 KB

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