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