client.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. package http
  2. import (
  3. "bufio"
  4. "bytes"
  5. "context"
  6. "encoding/base64"
  7. "io"
  8. "net/http"
  9. "net/url"
  10. "sync"
  11. "text/template"
  12. "github.com/xtls/xray-core/common"
  13. "github.com/xtls/xray-core/common/buf"
  14. "github.com/xtls/xray-core/common/bytespool"
  15. "github.com/xtls/xray-core/common/errors"
  16. "github.com/xtls/xray-core/common/net"
  17. "github.com/xtls/xray-core/common/protocol"
  18. "github.com/xtls/xray-core/common/retry"
  19. "github.com/xtls/xray-core/common/session"
  20. "github.com/xtls/xray-core/common/signal"
  21. "github.com/xtls/xray-core/common/task"
  22. "github.com/xtls/xray-core/core"
  23. "github.com/xtls/xray-core/features/policy"
  24. "github.com/xtls/xray-core/transport"
  25. "github.com/xtls/xray-core/transport/internet"
  26. "github.com/xtls/xray-core/transport/internet/stat"
  27. "github.com/xtls/xray-core/transport/internet/tls"
  28. "golang.org/x/net/http2"
  29. )
  30. type Client struct {
  31. server *protocol.ServerSpec
  32. policyManager policy.Manager
  33. header []*Header
  34. }
  35. type h2Conn struct {
  36. rawConn net.Conn
  37. h2Conn *http2.ClientConn
  38. }
  39. var (
  40. cachedH2Mutex sync.Mutex
  41. cachedH2Conns map[net.Destination]h2Conn
  42. )
  43. // NewClient create a new http client based on the given config.
  44. func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) {
  45. if config.Server == nil {
  46. return nil, errors.New(`no target server found`)
  47. }
  48. server, err := protocol.NewServerSpecFromPB(config.Server)
  49. if err != nil {
  50. return nil, errors.New("failed to get server spec").Base(err)
  51. }
  52. v := core.MustFromContext(ctx)
  53. return &Client{
  54. server: server,
  55. policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
  56. header: config.Header,
  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. outbounds := session.OutboundsFromContext(ctx)
  62. ob := outbounds[len(outbounds)-1]
  63. if !ob.Target.IsValid() {
  64. return errors.New("target not specified.")
  65. }
  66. ob.Name = "http"
  67. ob.CanSpliceCopy = 2
  68. target := ob.Target
  69. targetAddr := target.NetAddr()
  70. if target.Network == net.Network_UDP {
  71. return errors.New("UDP is not supported by HTTP outbound")
  72. }
  73. server := c.server
  74. dest := server.Destination
  75. user := server.User
  76. var conn stat.Connection
  77. mbuf, _ := link.Reader.ReadMultiBuffer()
  78. len := mbuf.Len()
  79. firstPayload := bytespool.Alloc(len)
  80. mbuf, _ = buf.SplitBytes(mbuf, firstPayload)
  81. firstPayload = firstPayload[:len]
  82. buf.ReleaseMulti(mbuf)
  83. defer bytespool.Free(firstPayload)
  84. header, err := fillRequestHeader(ctx, c.header)
  85. if err != nil {
  86. return errors.New("failed to fill out header").Base(err)
  87. }
  88. if err := retry.ExponentialBackoff(5, 100).On(func() error {
  89. netConn, err := setUpHTTPTunnel(ctx, dest, targetAddr, user, dialer, header, firstPayload)
  90. if netConn != nil {
  91. if _, ok := netConn.(*http2Conn); !ok {
  92. if _, err := netConn.Write(firstPayload); err != nil {
  93. netConn.Close()
  94. return err
  95. }
  96. }
  97. conn = stat.Connection(netConn)
  98. }
  99. return err
  100. }); err != nil {
  101. return errors.New("failed to find an available destination").Base(err)
  102. }
  103. defer func() {
  104. if err := conn.Close(); err != nil {
  105. errors.LogInfoInner(ctx, err, "failed to closed connection")
  106. }
  107. }()
  108. p := c.policyManager.ForLevel(0)
  109. if user != nil {
  110. p = c.policyManager.ForLevel(user.Level)
  111. }
  112. var newCtx context.Context
  113. var newCancel context.CancelFunc
  114. if session.TimeoutOnlyFromContext(ctx) {
  115. newCtx, newCancel = context.WithCancel(context.Background())
  116. }
  117. ctx, cancel := context.WithCancel(ctx)
  118. timer := signal.CancelAfterInactivity(ctx, func() {
  119. cancel()
  120. if newCancel != nil {
  121. newCancel()
  122. }
  123. }, p.Timeouts.ConnectionIdle)
  124. requestFunc := func() error {
  125. defer timer.SetTimeout(p.Timeouts.DownlinkOnly)
  126. return buf.Copy(link.Reader, buf.NewWriter(conn), buf.UpdateActivity(timer))
  127. }
  128. responseFunc := func() error {
  129. ob.CanSpliceCopy = 1
  130. defer timer.SetTimeout(p.Timeouts.UplinkOnly)
  131. return buf.Copy(buf.NewReader(conn), link.Writer, buf.UpdateActivity(timer))
  132. }
  133. if newCtx != nil {
  134. ctx = newCtx
  135. }
  136. responseDonePost := task.OnSuccess(responseFunc, task.Close(link.Writer))
  137. if err := task.Run(ctx, requestFunc, responseDonePost); err != nil {
  138. return errors.New("connection ends").Base(err)
  139. }
  140. return nil
  141. }
  142. // fillRequestHeader will fill out the template of the headers
  143. func fillRequestHeader(ctx context.Context, header []*Header) ([]*Header, error) {
  144. if len(header) == 0 {
  145. return header, nil
  146. }
  147. inbound := session.InboundFromContext(ctx)
  148. outbounds := session.OutboundsFromContext(ctx)
  149. ob := outbounds[len(outbounds)-1]
  150. if inbound == nil || ob == nil {
  151. return nil, errors.New("missing inbound or outbound metadata from context")
  152. }
  153. data := struct {
  154. Source net.Destination
  155. Target net.Destination
  156. }{
  157. Source: inbound.Source,
  158. Target: ob.Target,
  159. }
  160. filled := make([]*Header, len(header))
  161. for i, h := range header {
  162. tmpl, err := template.New(h.Key).Parse(h.Value)
  163. if err != nil {
  164. return nil, err
  165. }
  166. var buf bytes.Buffer
  167. if err = tmpl.Execute(&buf, data); err != nil {
  168. return nil, err
  169. }
  170. filled[i] = &Header{Key: h.Key, Value: buf.String()}
  171. }
  172. return filled, nil
  173. }
  174. // setUpHTTPTunnel will create a socket tunnel via HTTP CONNECT method
  175. func setUpHTTPTunnel(ctx context.Context, dest net.Destination, target string, user *protocol.MemoryUser, dialer internet.Dialer, header []*Header, firstPayload []byte) (net.Conn, error) {
  176. req := &http.Request{
  177. Method: http.MethodConnect,
  178. URL: &url.URL{Host: target},
  179. Header: make(http.Header),
  180. Host: target,
  181. }
  182. if user != nil && user.Account != nil {
  183. account := user.Account.(*Account)
  184. auth := account.GetUsername() + ":" + account.GetPassword()
  185. req.Header.Set("Proxy-Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(auth)))
  186. }
  187. for _, h := range header {
  188. req.Header.Set(h.Key, h.Value)
  189. }
  190. connectHTTP1 := func(rawConn net.Conn) (net.Conn, error) {
  191. req.Header.Set("Proxy-Connection", "Keep-Alive")
  192. err := req.Write(rawConn)
  193. if err != nil {
  194. rawConn.Close()
  195. return nil, err
  196. }
  197. resp, err := http.ReadResponse(bufio.NewReader(rawConn), req)
  198. if err != nil {
  199. rawConn.Close()
  200. return nil, err
  201. }
  202. defer resp.Body.Close()
  203. if resp.StatusCode != http.StatusOK {
  204. rawConn.Close()
  205. return nil, errors.New("Proxy responded with non 200 code: " + resp.Status)
  206. }
  207. return rawConn, nil
  208. }
  209. connectHTTP2 := func(rawConn net.Conn, h2clientConn *http2.ClientConn) (net.Conn, error) {
  210. pr, pw := io.Pipe()
  211. req.Body = pr
  212. var pErr error
  213. var wg sync.WaitGroup
  214. wg.Add(1)
  215. go func() {
  216. _, pErr = pw.Write(firstPayload)
  217. wg.Done()
  218. }()
  219. resp, err := h2clientConn.RoundTrip(req)
  220. if err != nil {
  221. rawConn.Close()
  222. return nil, err
  223. }
  224. wg.Wait()
  225. if pErr != nil {
  226. rawConn.Close()
  227. return nil, pErr
  228. }
  229. if resp.StatusCode != http.StatusOK {
  230. rawConn.Close()
  231. return nil, errors.New("Proxy responded with non 200 code: " + resp.Status)
  232. }
  233. return newHTTP2Conn(rawConn, pw, resp.Body), nil
  234. }
  235. cachedH2Mutex.Lock()
  236. cachedConn, cachedConnFound := cachedH2Conns[dest]
  237. cachedH2Mutex.Unlock()
  238. if cachedConnFound {
  239. rc, cc := cachedConn.rawConn, cachedConn.h2Conn
  240. if cc.CanTakeNewRequest() {
  241. proxyConn, err := connectHTTP2(rc, cc)
  242. if err != nil {
  243. return nil, err
  244. }
  245. return proxyConn, nil
  246. }
  247. }
  248. rawConn, err := dialer.Dial(ctx, dest)
  249. if err != nil {
  250. return nil, err
  251. }
  252. iConn := stat.TryUnwrapStatsConn(rawConn)
  253. nextProto := ""
  254. if tlsConn, ok := iConn.(*tls.Conn); ok {
  255. if err := tlsConn.HandshakeContext(ctx); err != nil {
  256. rawConn.Close()
  257. return nil, err
  258. }
  259. nextProto = tlsConn.ConnectionState().NegotiatedProtocol
  260. } else if tlsConn, ok := iConn.(*tls.UConn); ok {
  261. if err := tlsConn.HandshakeContext(ctx); err != nil {
  262. rawConn.Close()
  263. return nil, err
  264. }
  265. nextProto = tlsConn.ConnectionState().NegotiatedProtocol
  266. }
  267. switch nextProto {
  268. case "", "http/1.1":
  269. return connectHTTP1(rawConn)
  270. case "h2":
  271. t := http2.Transport{}
  272. h2clientConn, err := t.NewClientConn(rawConn)
  273. if err != nil {
  274. rawConn.Close()
  275. return nil, err
  276. }
  277. proxyConn, err := connectHTTP2(rawConn, h2clientConn)
  278. if err != nil {
  279. rawConn.Close()
  280. return nil, err
  281. }
  282. cachedH2Mutex.Lock()
  283. if cachedH2Conns == nil {
  284. cachedH2Conns = make(map[net.Destination]h2Conn)
  285. }
  286. cachedH2Conns[dest] = h2Conn{
  287. rawConn: rawConn,
  288. h2Conn: h2clientConn,
  289. }
  290. cachedH2Mutex.Unlock()
  291. return proxyConn, err
  292. default:
  293. return nil, errors.New("negotiated unsupported application layer protocol: " + nextProto)
  294. }
  295. }
  296. func newHTTP2Conn(c net.Conn, pipedReqBody *io.PipeWriter, respBody io.ReadCloser) net.Conn {
  297. return &http2Conn{Conn: c, in: pipedReqBody, out: respBody}
  298. }
  299. type http2Conn struct {
  300. net.Conn
  301. in *io.PipeWriter
  302. out io.ReadCloser
  303. }
  304. func (h *http2Conn) Read(p []byte) (n int, err error) {
  305. return h.out.Read(p)
  306. }
  307. func (h *http2Conn) Write(p []byte) (n int, err error) {
  308. return h.in.Write(p)
  309. }
  310. func (h *http2Conn) Close() error {
  311. h.in.Close()
  312. return h.out.Close()
  313. }
  314. func init() {
  315. common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  316. return NewClient(ctx, config.(*ClientConfig))
  317. }))
  318. }