http2.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. package connection
  2. import (
  3. "bufio"
  4. "context"
  5. gojson "encoding/json"
  6. "fmt"
  7. "io"
  8. "net"
  9. "net/http"
  10. "runtime/debug"
  11. "strings"
  12. "sync"
  13. "github.com/pkg/errors"
  14. "github.com/rs/zerolog"
  15. "golang.org/x/net/http2"
  16. "github.com/cloudflare/cloudflared/tracing"
  17. tunnelpogs "github.com/cloudflare/cloudflared/tunnelrpc/pogs"
  18. )
  19. // note: these constants are exported so we can reuse them in the edge-side code
  20. const (
  21. InternalUpgradeHeader = "Cf-Cloudflared-Proxy-Connection-Upgrade"
  22. InternalTCPProxySrcHeader = "Cf-Cloudflared-Proxy-Src"
  23. WebsocketUpgrade = "websocket"
  24. ControlStreamUpgrade = "control-stream"
  25. ConfigurationUpdate = "update-configuration"
  26. )
  27. var errEdgeConnectionClosed = fmt.Errorf("connection with edge closed")
  28. // HTTP2Connection represents a net.Conn that uses HTTP2 frames to proxy traffic from the edge to cloudflared on the
  29. // origin.
  30. type HTTP2Connection struct {
  31. conn net.Conn
  32. server *http2.Server
  33. orchestrator Orchestrator
  34. connOptions *tunnelpogs.ConnectionOptions
  35. observer *Observer
  36. connIndex uint8
  37. log *zerolog.Logger
  38. activeRequestsWG sync.WaitGroup
  39. controlStreamHandler ControlStreamHandler
  40. stoppedGracefully bool
  41. controlStreamErr error // result of running control stream handler
  42. }
  43. // NewHTTP2Connection returns a new instance of HTTP2Connection.
  44. func NewHTTP2Connection(
  45. conn net.Conn,
  46. orchestrator Orchestrator,
  47. connOptions *tunnelpogs.ConnectionOptions,
  48. observer *Observer,
  49. connIndex uint8,
  50. controlStreamHandler ControlStreamHandler,
  51. log *zerolog.Logger,
  52. ) *HTTP2Connection {
  53. return &HTTP2Connection{
  54. conn: conn,
  55. server: &http2.Server{
  56. MaxConcurrentStreams: MaxConcurrentStreams,
  57. },
  58. orchestrator: orchestrator,
  59. connOptions: connOptions,
  60. observer: observer,
  61. connIndex: connIndex,
  62. controlStreamHandler: controlStreamHandler,
  63. log: log,
  64. }
  65. }
  66. // Serve serves an HTTP2 server that the edge can talk to.
  67. func (c *HTTP2Connection) Serve(ctx context.Context) error {
  68. go func() {
  69. <-ctx.Done()
  70. c.close()
  71. }()
  72. c.server.ServeConn(c.conn, &http2.ServeConnOpts{
  73. Context: ctx,
  74. Handler: c,
  75. })
  76. switch {
  77. case c.controlStreamHandler.IsStopped():
  78. return nil
  79. case c.controlStreamErr != nil:
  80. return c.controlStreamErr
  81. default:
  82. c.observer.log.Info().Uint8(LogFieldConnIndex, c.connIndex).Msg("Lost connection with the edge")
  83. return errEdgeConnectionClosed
  84. }
  85. }
  86. func (c *HTTP2Connection) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  87. c.activeRequestsWG.Add(1)
  88. defer c.activeRequestsWG.Done()
  89. connType := determineHTTP2Type(r)
  90. handleMissingRequestParts(connType, r)
  91. respWriter, err := NewHTTP2RespWriter(r, w, connType, c.log)
  92. if err != nil {
  93. c.observer.log.Error().Msg(err.Error())
  94. return
  95. }
  96. originProxy, err := c.orchestrator.GetOriginProxy()
  97. if err != nil {
  98. c.observer.log.Error().Msg(err.Error())
  99. return
  100. }
  101. var requestErr error
  102. switch connType {
  103. case TypeControlStream:
  104. requestErr = c.controlStreamHandler.ServeControlStream(r.Context(), respWriter, c.connOptions, c.orchestrator)
  105. if requestErr != nil {
  106. c.controlStreamErr = requestErr
  107. }
  108. case TypeConfiguration:
  109. requestErr = c.handleConfigurationUpdate(respWriter, r)
  110. case TypeWebsocket, TypeHTTP:
  111. stripWebsocketUpgradeHeader(r)
  112. // Check for tracing on request
  113. tr := tracing.NewTracedHTTPRequest(r, c.connIndex, c.log)
  114. if err := originProxy.ProxyHTTP(respWriter, tr, connType == TypeWebsocket); err != nil {
  115. requestErr = fmt.Errorf("Failed to proxy HTTP: %w", err)
  116. }
  117. case TypeTCP:
  118. host, err := getRequestHost(r)
  119. if err != nil {
  120. requestErr = fmt.Errorf(`cloudflared received a warp-routing request with an empty host value: %w`, err)
  121. break
  122. }
  123. rws := NewHTTPResponseReadWriterAcker(respWriter, respWriter, r)
  124. requestErr = originProxy.ProxyTCP(r.Context(), rws, &TCPRequest{
  125. Dest: host,
  126. CFRay: FindCfRayHeader(r),
  127. LBProbe: IsLBProbeRequest(r),
  128. CfTraceID: r.Header.Get(tracing.TracerContextName),
  129. ConnIndex: c.connIndex,
  130. })
  131. default:
  132. requestErr = fmt.Errorf("Received unknown connection type: %s", connType)
  133. }
  134. if requestErr != nil {
  135. c.log.Error().Err(requestErr).Msg("failed to serve incoming request")
  136. // WriteErrorResponse will return false if status was already written. we need to abort handler.
  137. if !respWriter.WriteErrorResponse() {
  138. c.log.Debug().Msg("Handler aborted due to failure to write error response after status already sent")
  139. panic(http.ErrAbortHandler)
  140. }
  141. }
  142. }
  143. // ConfigurationUpdateBody is the representation followed by the edge to send updates to cloudflared.
  144. type ConfigurationUpdateBody struct {
  145. Version int32 `json:"version"`
  146. Config gojson.RawMessage `json:"config"`
  147. }
  148. func (c *HTTP2Connection) handleConfigurationUpdate(respWriter *http2RespWriter, r *http.Request) error {
  149. var configBody ConfigurationUpdateBody
  150. if err := json.NewDecoder(r.Body).Decode(&configBody); err != nil {
  151. return err
  152. }
  153. resp := c.orchestrator.UpdateConfig(configBody.Version, configBody.Config)
  154. bdy, err := json.Marshal(resp)
  155. if err != nil {
  156. return err
  157. }
  158. _, err = respWriter.Write(bdy)
  159. return err
  160. }
  161. func (c *HTTP2Connection) close() {
  162. // Wait for all serve HTTP handlers to return
  163. c.activeRequestsWG.Wait()
  164. c.conn.Close()
  165. }
  166. type http2RespWriter struct {
  167. r io.Reader
  168. w http.ResponseWriter
  169. flusher http.Flusher
  170. shouldFlush bool
  171. statusWritten bool
  172. respHeaders http.Header
  173. hijackedMutex sync.Mutex
  174. hijackedv bool
  175. log *zerolog.Logger
  176. }
  177. func NewHTTP2RespWriter(r *http.Request, w http.ResponseWriter, connType Type, log *zerolog.Logger) (*http2RespWriter, error) {
  178. flusher, isFlusher := w.(http.Flusher)
  179. if !isFlusher {
  180. respWriter := &http2RespWriter{
  181. r: r.Body,
  182. w: w,
  183. log: log,
  184. }
  185. respWriter.WriteErrorResponse()
  186. return nil, fmt.Errorf("%T doesn't implement http.Flusher", w)
  187. }
  188. return &http2RespWriter{
  189. r: r.Body,
  190. w: w,
  191. flusher: flusher,
  192. shouldFlush: connType.shouldFlush(),
  193. respHeaders: make(http.Header),
  194. log: log,
  195. }, nil
  196. }
  197. func (rp *http2RespWriter) AddTrailer(trailerName, trailerValue string) {
  198. if !rp.statusWritten {
  199. rp.log.Warn().Msg("Tried to add Trailer to response before status written. Ignoring...")
  200. return
  201. }
  202. rp.w.Header().Add(http2.TrailerPrefix+trailerName, trailerValue)
  203. }
  204. func (rp *http2RespWriter) WriteRespHeaders(status int, header http.Header) error {
  205. if rp.hijacked() {
  206. rp.log.Warn().Msg("WriteRespHeaders after hijack")
  207. return nil
  208. }
  209. dest := rp.w.Header()
  210. userHeaders := make(http.Header, len(header))
  211. for name, values := range header {
  212. // lowercase headers for simplicity check
  213. h2name := strings.ToLower(name)
  214. if h2name == "content-length" {
  215. // This header has meaning in HTTP/2 and will be used by the edge,
  216. // so it should be sent *also* as an HTTP/2 response header.
  217. dest[name] = values
  218. }
  219. if h2name == tracing.IntCloudflaredTracingHeader {
  220. // Add cf-int-cloudflared-tracing header outside of serialized userHeaders
  221. dest[tracing.CanonicalCloudflaredTracingHeader] = values
  222. continue
  223. }
  224. if !IsControlResponseHeader(h2name) || IsWebsocketClientHeader(h2name) {
  225. // User headers, on the other hand, must all be serialized so that
  226. // HTTP/2 header validation won't be applied to HTTP/1 header values
  227. userHeaders[name] = values
  228. }
  229. }
  230. // Perform user header serialization and set them in the single header
  231. dest.Set(CanonicalResponseUserHeaders, SerializeHeaders(userHeaders))
  232. rp.setResponseMetaHeader(responseMetaHeaderOrigin)
  233. // HTTP2 removes support for 101 Switching Protocols https://tools.ietf.org/html/rfc7540#section-8.1.1
  234. if status == http.StatusSwitchingProtocols {
  235. status = http.StatusOK
  236. }
  237. rp.w.WriteHeader(status)
  238. if shouldFlush(header) {
  239. rp.shouldFlush = true
  240. }
  241. if rp.shouldFlush {
  242. rp.flusher.Flush()
  243. }
  244. rp.statusWritten = true
  245. return nil
  246. }
  247. func (rp *http2RespWriter) Header() http.Header {
  248. return rp.respHeaders
  249. }
  250. func (rp *http2RespWriter) Flush() {
  251. rp.flusher.Flush()
  252. }
  253. func (rp *http2RespWriter) WriteHeader(status int) {
  254. if rp.hijacked() {
  255. rp.log.Warn().Msg("WriteHeader after hijack")
  256. return
  257. }
  258. rp.WriteRespHeaders(status, rp.respHeaders)
  259. }
  260. func (rp *http2RespWriter) hijacked() bool {
  261. rp.hijackedMutex.Lock()
  262. defer rp.hijackedMutex.Unlock()
  263. return rp.hijackedv
  264. }
  265. func (rp *http2RespWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
  266. if !rp.statusWritten {
  267. return nil, nil, fmt.Errorf("status not yet written before attempting to hijack connection")
  268. }
  269. // Make sure to flush anything left in the buffer before hijacking
  270. if rp.shouldFlush {
  271. rp.flusher.Flush()
  272. }
  273. rp.hijackedMutex.Lock()
  274. defer rp.hijackedMutex.Unlock()
  275. if rp.hijackedv {
  276. return nil, nil, http.ErrHijacked
  277. }
  278. rp.hijackedv = true
  279. conn := &localProxyConnection{rp}
  280. // We return the http2RespWriter here because we want to make sure that we flush after every write
  281. // otherwise the HTTP2 write buffer waits a few seconds before sending.
  282. readWriter := bufio.NewReadWriter(
  283. bufio.NewReader(rp),
  284. bufio.NewWriter(rp),
  285. )
  286. return conn, readWriter, nil
  287. }
  288. func (rp *http2RespWriter) WriteErrorResponse() bool {
  289. if rp.statusWritten {
  290. return false
  291. }
  292. rp.setResponseMetaHeader(responseMetaHeaderCfd)
  293. rp.w.WriteHeader(http.StatusBadGateway)
  294. rp.statusWritten = true
  295. return true
  296. }
  297. func (rp *http2RespWriter) setResponseMetaHeader(value string) {
  298. rp.w.Header().Set(CanonicalResponseMetaHeader, value)
  299. }
  300. func (rp *http2RespWriter) Read(p []byte) (n int, err error) {
  301. return rp.r.Read(p)
  302. }
  303. func (rp *http2RespWriter) Write(p []byte) (n int, err error) {
  304. defer func() {
  305. // Implementer of OriginClient should make sure it doesn't write to the connection after Proxy returns
  306. // Register a recover routine just in case.
  307. if r := recover(); r != nil {
  308. rp.log.Debug().Msgf("Recover from http2 response writer panic, error %s", debug.Stack())
  309. }
  310. }()
  311. n, err = rp.w.Write(p)
  312. if err == nil && rp.shouldFlush {
  313. rp.flusher.Flush()
  314. }
  315. return n, err
  316. }
  317. func (rp *http2RespWriter) Close() error {
  318. return nil
  319. }
  320. func determineHTTP2Type(r *http.Request) Type {
  321. switch {
  322. case isConfigurationUpdate(r):
  323. return TypeConfiguration
  324. case isWebsocketUpgrade(r):
  325. return TypeWebsocket
  326. case IsTCPStream(r):
  327. return TypeTCP
  328. case isControlStreamUpgrade(r):
  329. return TypeControlStream
  330. default:
  331. return TypeHTTP
  332. }
  333. }
  334. func handleMissingRequestParts(connType Type, r *http.Request) {
  335. if connType == TypeHTTP {
  336. // http library has no guarantees that we receive a filled URL. If not, then we fill it, as we reuse the request
  337. // for proxying. For proxying they should not matter since we control the dialer on every egress proxied.
  338. if len(r.URL.Scheme) == 0 {
  339. r.URL.Scheme = "http"
  340. }
  341. if len(r.URL.Host) == 0 {
  342. r.URL.Host = "localhost:8080"
  343. }
  344. }
  345. }
  346. func isControlStreamUpgrade(r *http.Request) bool {
  347. return r.Header.Get(InternalUpgradeHeader) == ControlStreamUpgrade
  348. }
  349. func isWebsocketUpgrade(r *http.Request) bool {
  350. return r.Header.Get(InternalUpgradeHeader) == WebsocketUpgrade
  351. }
  352. func isConfigurationUpdate(r *http.Request) bool {
  353. return r.Header.Get(InternalUpgradeHeader) == ConfigurationUpdate
  354. }
  355. // IsTCPStream discerns if the connection request needs a tcp stream proxy.
  356. func IsTCPStream(r *http.Request) bool {
  357. return r.Header.Get(InternalTCPProxySrcHeader) != ""
  358. }
  359. func stripWebsocketUpgradeHeader(r *http.Request) {
  360. r.Header.Del(InternalUpgradeHeader)
  361. }
  362. // getRequestHost returns the host of the http.Request.
  363. func getRequestHost(r *http.Request) (string, error) {
  364. if r.Host != "" {
  365. return r.Host, nil
  366. }
  367. if r.URL != nil {
  368. return r.URL.Host, nil
  369. }
  370. return "", errors.New("host not set in incoming request")
  371. }