client.go 7.8 KB

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