client.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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. if target.Network == net.Network_UDP {
  65. return newError("UDP is not supported by HTTP outbound")
  66. }
  67. var user *protocol.MemoryUser
  68. var conn internet.Connection
  69. if err := retry.ExponentialBackoff(5, 100).On(func() error {
  70. server := c.serverPicker.PickServer()
  71. dest := server.Destination()
  72. user = server.PickUser()
  73. targetAddr := target.NetAddr()
  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: "CONNECT",
  111. URL: &url.URL{Host: target},
  112. Header: make(http.Header),
  113. Host: target,
  114. }).WithContext(ctx)
  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. req.Header.Set("Proxy-Connection", "Keep-Alive")
  121. connectHttp1 := func(rawConn net.Conn) (net.Conn, error) {
  122. req.Proto = "HTTP/1.1"
  123. req.ProtoMajor = 1
  124. req.ProtoMinor = 1
  125. err := req.Write(rawConn)
  126. if err != nil {
  127. rawConn.Close()
  128. return nil, err
  129. }
  130. resp, err := http.ReadResponse(bufio.NewReader(rawConn), req)
  131. if err != nil {
  132. rawConn.Close()
  133. return nil, err
  134. }
  135. if resp.StatusCode != http.StatusOK {
  136. rawConn.Close()
  137. return nil, newError("Proxy responded with non 200 code: " + resp.Status)
  138. }
  139. return rawConn, nil
  140. }
  141. connectHttp2 := func(rawConn net.Conn, h2clientConn *http2.ClientConn) (net.Conn, error) {
  142. req.Proto = "HTTP/2.0"
  143. req.ProtoMajor = 2
  144. req.ProtoMinor = 0
  145. pr, pw := io.Pipe()
  146. req.Body = pr
  147. resp, err := h2clientConn.RoundTrip(req)
  148. if err != nil {
  149. rawConn.Close()
  150. return nil, err
  151. }
  152. if resp.StatusCode != http.StatusOK {
  153. rawConn.Close()
  154. return nil, newError("Proxy responded with non 200 code: " + resp.Status)
  155. }
  156. return newHttp2Conn(rawConn, pw, resp.Body), nil
  157. }
  158. cachedH2Mutex.Lock()
  159. defer cachedH2Mutex.Unlock()
  160. if cachedConn, found := cachedH2Conns[dest]; found {
  161. if cachedConn.rawConn != nil && cachedConn.h2Conn != nil {
  162. rc := cachedConn.rawConn
  163. cc := cachedConn.h2Conn
  164. if cc.CanTakeNewRequest() {
  165. proxyConn, err := connectHttp2(rc, cc)
  166. if err != nil {
  167. return nil, err
  168. }
  169. return proxyConn, nil
  170. }
  171. }
  172. }
  173. rawConn, err := dialer.Dial(ctx, dest)
  174. if err != nil {
  175. return nil, err
  176. }
  177. nextProto := ""
  178. if tlsConn, ok := rawConn.(*tls.Conn); ok {
  179. if err := tlsConn.Handshake(); err != nil {
  180. rawConn.Close()
  181. return nil, err
  182. }
  183. nextProto = tlsConn.ConnectionState().NegotiatedProtocol
  184. }
  185. switch nextProto {
  186. case "":
  187. fallthrough
  188. case "http/1.1":
  189. return connectHttp1(rawConn)
  190. case "h2":
  191. t := http2.Transport{}
  192. h2clientConn, err := t.NewClientConn(rawConn)
  193. if err != nil {
  194. rawConn.Close()
  195. return nil, err
  196. }
  197. proxyConn, err := connectHttp2(rawConn, h2clientConn)
  198. if err != nil {
  199. rawConn.Close()
  200. return nil, err
  201. }
  202. if cachedH2Conns == nil {
  203. cachedH2Conns = make(map[net.Destination]h2Conn)
  204. }
  205. cachedH2Conns[dest] = h2Conn{
  206. rawConn: rawConn,
  207. h2Conn: h2clientConn,
  208. }
  209. return proxyConn, err
  210. default:
  211. return nil, newError("negotiated unsupported application layer protocol: " + nextProto)
  212. }
  213. }
  214. func newHttp2Conn(c net.Conn, pipedReqBody *io.PipeWriter, respBody io.ReadCloser) net.Conn {
  215. return &http2Conn{Conn: c, in: pipedReqBody, out: respBody}
  216. }
  217. type http2Conn struct {
  218. net.Conn
  219. in *io.PipeWriter
  220. out io.ReadCloser
  221. }
  222. func (h *http2Conn) Read(p []byte) (n int, err error) {
  223. return h.out.Read(p)
  224. }
  225. func (h *http2Conn) Write(p []byte) (n int, err error) {
  226. return h.in.Write(p)
  227. }
  228. func (h *http2Conn) Close() error {
  229. h.in.Close()
  230. return h.out.Close()
  231. }
  232. func (h *http2Conn) CloseConn() error {
  233. return h.Conn.Close()
  234. }
  235. func (h *http2Conn) CloseWrite() error {
  236. return h.in.Close()
  237. }
  238. func (h *http2Conn) CloseRead() error {
  239. return h.out.Close()
  240. }
  241. func init() {
  242. common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  243. return NewClient(ctx, config.(*ClientConfig))
  244. }))
  245. }