h2mux.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. package connection
  2. import (
  3. "context"
  4. "io"
  5. "net"
  6. "net/http"
  7. "time"
  8. "github.com/cloudflare/cloudflared/h2mux"
  9. tunnelpogs "github.com/cloudflare/cloudflared/tunnelrpc/pogs"
  10. "github.com/cloudflare/cloudflared/websocket"
  11. "github.com/pkg/errors"
  12. "github.com/rs/zerolog"
  13. "golang.org/x/sync/errgroup"
  14. )
  15. const (
  16. muxerTimeout = 5 * time.Second
  17. openStreamTimeout = 30 * time.Second
  18. )
  19. type h2muxConnection struct {
  20. config *Config
  21. muxerConfig *MuxerConfig
  22. muxer *h2mux.Muxer
  23. // connectionID is only used by metrics, and prometheus requires labels to be string
  24. connIndexStr string
  25. connIndex uint8
  26. observer *Observer
  27. gracefulShutdownC <-chan struct{}
  28. stoppedGracefully bool
  29. // newRPCClientFunc allows us to mock RPCs during testing
  30. newRPCClientFunc func(context.Context, io.ReadWriteCloser, *zerolog.Logger) NamedTunnelRPCClient
  31. }
  32. type MuxerConfig struct {
  33. HeartbeatInterval time.Duration
  34. MaxHeartbeats uint64
  35. CompressionSetting h2mux.CompressionSetting
  36. MetricsUpdateFreq time.Duration
  37. }
  38. func (mc *MuxerConfig) H2MuxerConfig(h h2mux.MuxedStreamHandler, log *zerolog.Logger) *h2mux.MuxerConfig {
  39. return &h2mux.MuxerConfig{
  40. Timeout: muxerTimeout,
  41. Handler: h,
  42. IsClient: true,
  43. HeartbeatInterval: mc.HeartbeatInterval,
  44. MaxHeartbeats: mc.MaxHeartbeats,
  45. Log: log,
  46. CompressionQuality: mc.CompressionSetting,
  47. }
  48. }
  49. // NewTunnelHandler returns a TunnelHandler, origin LAN IP and error
  50. func NewH2muxConnection(
  51. config *Config,
  52. muxerConfig *MuxerConfig,
  53. edgeConn net.Conn,
  54. connIndex uint8,
  55. observer *Observer,
  56. gracefulShutdownC <-chan struct{},
  57. ) (*h2muxConnection, error, bool) {
  58. h := &h2muxConnection{
  59. config: config,
  60. muxerConfig: muxerConfig,
  61. connIndexStr: uint8ToString(connIndex),
  62. connIndex: connIndex,
  63. observer: observer,
  64. gracefulShutdownC: gracefulShutdownC,
  65. newRPCClientFunc: newRegistrationRPCClient,
  66. }
  67. // Establish a muxed connection with the edge
  68. // Client mux handshake with agent server
  69. muxer, err := h2mux.Handshake(edgeConn, edgeConn, *muxerConfig.H2MuxerConfig(h, observer.logTransport), h2mux.ActiveStreams)
  70. if err != nil {
  71. recoverable := isHandshakeErrRecoverable(err, connIndex, observer)
  72. return nil, err, recoverable
  73. }
  74. h.muxer = muxer
  75. return h, nil, false
  76. }
  77. func (h *h2muxConnection) ServeNamedTunnel(ctx context.Context, namedTunnel *NamedTunnelConfig, connOptions *tunnelpogs.ConnectionOptions, connectedFuse ConnectedFuse) error {
  78. errGroup, serveCtx := errgroup.WithContext(ctx)
  79. errGroup.Go(func() error {
  80. return h.serveMuxer(serveCtx)
  81. })
  82. errGroup.Go(func() error {
  83. if err := h.registerNamedTunnel(serveCtx, namedTunnel, connOptions); err != nil {
  84. return err
  85. }
  86. connectedFuse.Connected()
  87. return nil
  88. })
  89. errGroup.Go(func() error {
  90. h.controlLoop(serveCtx, connectedFuse, true)
  91. return nil
  92. })
  93. err := errGroup.Wait()
  94. if err == errMuxerStopped {
  95. if h.stoppedGracefully {
  96. return nil
  97. }
  98. h.observer.log.Info().Uint8(LogFieldConnIndex, h.connIndex).Msg("Unexpected muxer shutdown")
  99. }
  100. return err
  101. }
  102. func (h *h2muxConnection) ServeClassicTunnel(ctx context.Context, classicTunnel *ClassicTunnelConfig, credentialManager CredentialManager, registrationOptions *tunnelpogs.RegistrationOptions, connectedFuse ConnectedFuse) error {
  103. errGroup, serveCtx := errgroup.WithContext(ctx)
  104. errGroup.Go(func() error {
  105. return h.serveMuxer(serveCtx)
  106. })
  107. errGroup.Go(func() (err error) {
  108. defer func() {
  109. if err == nil {
  110. connectedFuse.Connected()
  111. }
  112. }()
  113. if classicTunnel.UseReconnectToken && connectedFuse.IsConnected() {
  114. err := h.reconnectTunnel(ctx, credentialManager, classicTunnel, registrationOptions)
  115. if err == nil {
  116. return nil
  117. }
  118. // log errors and proceed to RegisterTunnel
  119. h.observer.log.Err(err).
  120. Uint8(LogFieldConnIndex, h.connIndex).
  121. Msg("Couldn't reconnect connection. Re-registering it instead.")
  122. }
  123. return h.registerTunnel(ctx, credentialManager, classicTunnel, registrationOptions)
  124. })
  125. errGroup.Go(func() error {
  126. h.controlLoop(serveCtx, connectedFuse, false)
  127. return nil
  128. })
  129. err := errGroup.Wait()
  130. if err == errMuxerStopped {
  131. if h.stoppedGracefully {
  132. return nil
  133. }
  134. h.observer.log.Info().Uint8(LogFieldConnIndex, h.connIndex).Msg("Unexpected muxer shutdown")
  135. }
  136. return err
  137. }
  138. func (h *h2muxConnection) serveMuxer(ctx context.Context) error {
  139. // All routines should stop when muxer finish serving. When muxer is shutdown
  140. // gracefully, it doesn't return an error, so we need to return errMuxerShutdown
  141. // here to notify other routines to stop
  142. err := h.muxer.Serve(ctx)
  143. if err == nil {
  144. return errMuxerStopped
  145. }
  146. return err
  147. }
  148. func (h *h2muxConnection) controlLoop(ctx context.Context, connectedFuse ConnectedFuse, isNamedTunnel bool) {
  149. updateMetricsTickC := time.Tick(h.muxerConfig.MetricsUpdateFreq)
  150. var shutdownCompleted <-chan struct{}
  151. for {
  152. select {
  153. case <-h.gracefulShutdownC:
  154. if connectedFuse.IsConnected() {
  155. h.unregister(isNamedTunnel)
  156. }
  157. h.stoppedGracefully = true
  158. h.gracefulShutdownC = nil
  159. shutdownCompleted = h.muxer.Shutdown()
  160. case <-shutdownCompleted:
  161. return
  162. case <-ctx.Done():
  163. // UnregisterTunnel blocks until the RPC call returns
  164. if !h.stoppedGracefully && connectedFuse.IsConnected() {
  165. h.unregister(isNamedTunnel)
  166. }
  167. h.muxer.Shutdown()
  168. // don't wait for shutdown to finish when context is closed, this is the hard termination path
  169. return
  170. case <-updateMetricsTickC:
  171. h.observer.metrics.updateMuxerMetrics(h.connIndexStr, h.muxer.Metrics())
  172. }
  173. }
  174. }
  175. func (h *h2muxConnection) newRPCStream(ctx context.Context, rpcName rpcName) (*h2mux.MuxedStream, error) {
  176. openStreamCtx, openStreamCancel := context.WithTimeout(ctx, openStreamTimeout)
  177. defer openStreamCancel()
  178. stream, err := h.muxer.OpenRPCStream(openStreamCtx)
  179. if err != nil {
  180. return nil, err
  181. }
  182. return stream, nil
  183. }
  184. func (h *h2muxConnection) ServeStream(stream *h2mux.MuxedStream) error {
  185. respWriter := &h2muxRespWriter{stream}
  186. req, reqErr := h.newRequest(stream)
  187. if reqErr != nil {
  188. respWriter.WriteErrorResponse()
  189. return reqErr
  190. }
  191. var sourceConnectionType = TypeHTTP
  192. if websocket.IsWebSocketUpgrade(req) {
  193. sourceConnectionType = TypeWebsocket
  194. }
  195. err := h.config.OriginProxy.Proxy(respWriter, req, sourceConnectionType)
  196. if err != nil {
  197. respWriter.WriteErrorResponse()
  198. return err
  199. }
  200. return nil
  201. }
  202. func (h *h2muxConnection) newRequest(stream *h2mux.MuxedStream) (*http.Request, error) {
  203. req, err := http.NewRequest("GET", "http://localhost:8080", h2mux.MuxedStreamReader{MuxedStream: stream})
  204. if err != nil {
  205. return nil, errors.Wrap(err, "Unexpected error from http.NewRequest")
  206. }
  207. err = h2mux.H2RequestHeadersToH1Request(stream.Headers, req)
  208. if err != nil {
  209. return nil, errors.Wrap(err, "invalid request received")
  210. }
  211. return req, nil
  212. }
  213. type h2muxRespWriter struct {
  214. *h2mux.MuxedStream
  215. }
  216. func (rp *h2muxRespWriter) WriteRespHeaders(status int, header http.Header) error {
  217. headers := h2mux.H1ResponseToH2ResponseHeaders(status, header)
  218. headers = append(headers, h2mux.Header{Name: ResponseMetaHeaderField, Value: responseMetaHeaderOrigin})
  219. return rp.WriteHeaders(headers)
  220. }
  221. func (rp *h2muxRespWriter) WriteErrorResponse() {
  222. _ = rp.WriteHeaders([]h2mux.Header{
  223. {Name: ":status", Value: "502"},
  224. {Name: ResponseMetaHeaderField, Value: responseMetaHeaderCfd},
  225. })
  226. _, _ = rp.Write([]byte("502 Bad Gateway"))
  227. }