client.go 7.6 KB

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