Debian Codegraph @

modules/caddyhttp/reverseproxy/streaming.go

raw symbols SCIP
1 // Copyright 2015 Matthew Holt and The Caddy Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // Most of the code in this file was initially borrowed from the Go
16 // standard library and modified; It had this copyright notice:
17 // Copyright 2011 The Go Authors
18
19 package reverseproxy
20
21 import (
22 "bufio"
23 "context"
24 "errors"
25 "fmt"
26 "io"
27 weakrand "math/rand/v2"
28 "mime"
29 "net/http"
30 "sync"
31 "time"
32 "unsafe"
33
34 "go.uber.org/zap"
35 "go.uber.org/zap/zapcore"
36 "golang.org/x/net/http/httpguts"
37
38 "github.com/caddyserver/caddy/v2/modules/caddyhttp"
39 )
40
41 type h2ReadWriteCloser struct {
42 io.ReadCloser
43 http.ResponseWriter
44 }
45
46 func (rwc h2ReadWriteCloser) Write(p []byte) (n int, err error) {
47 n, err = rwc.ResponseWriter.Write(p)
48 if err != nil {
49 return 0, err
50 }
51
52 //nolint:bodyclose
53 err = http.NewResponseController(rwc.ResponseWriter).Flush()
54 if err != nil {
55 return 0, err
56 }
57 return n, nil
58 }
59
60 func (h *Handler) handleUpgradeResponse(logger *zap.Logger, wg *sync.WaitGroup, rw http.ResponseWriter, req *http.Request, res *http.Response) {
61 reqUpType := upgradeType(req.Header)
62 resUpType := upgradeType(res.Header)
63
64 // Taken from https://github.com/golang/go/commit/5c489514bc5e61ad9b5b07bd7d8ec65d66a0512a
65 // We know reqUpType is ASCII, it's checked by the caller.
66 if !asciiIsPrint(resUpType) {
67 if c := logger.Check(zapcore.DebugLevel, "backend tried to switch to invalid protocol"); c != nil {
68 c.Write(zap.String("backend_upgrade", resUpType))
69 }
70 return
71 }
72 if !asciiEqualFold(reqUpType, resUpType) {
73 if c := logger.Check(zapcore.DebugLevel, "backend tried to switch to unexpected protocol via Upgrade header"); c != nil {
74 c.Write(
75 zap.String("backend_upgrade", resUpType),
76 zap.String("requested_upgrade", reqUpType),
77 )
78 }
79 return
80 }
81
82 backConn, ok := res.Body.(io.ReadWriteCloser)
83 if !ok {
84 logger.Error("internal error: 101 switching protocols response with non-writable body")
85 return
86 }
87
88 // write header first, response headers should not be counted in size
89 // like the rest of handler chain.
90 copyHeader(rw.Header(), res.Header)
91 normalizeWebsocketHeaders(rw.Header())
92
93 var (
94 conn io.ReadWriteCloser
95 brw *bufio.ReadWriter
96 )
97 // websocket over http2 or http3 if extended connect is enabled, assuming backend doesn't support this, the request will be modified to http1.1 upgrade
98 // TODO: once we can reliably detect backend support this, it can be removed for those backends
99 if body, ok := caddyhttp.GetVar(req.Context(), "extended_connect_websocket_body").(io.ReadCloser); ok {
100 req.Body = body
101 rw.Header().Del("Upgrade")
102 rw.Header().Del("Connection")
103 delete(rw.Header(), "Sec-WebSocket-Accept")
104 rw.WriteHeader(http.StatusOK)
105
106 if c := logger.Check(zap.DebugLevel, "upgrading connection"); c != nil {
107 c.Write(zap.Int("http_version", 2))
108 }
109
110 //nolint:bodyclose
111 flushErr := http.NewResponseController(rw).Flush()
112 if flushErr != nil {
113 if c := h.logger.Check(zap.ErrorLevel, "failed to flush http2 websocket response"); c != nil {
114 c.Write(zap.Error(flushErr))
115 }
116 return
117 }
118 conn = h2ReadWriteCloser{req.Body, rw}
119 // bufio is not needed, use minimal buffer
120 brw = bufio.NewReadWriter(bufio.NewReaderSize(conn, 1), bufio.NewWriterSize(conn, 1))
121 } else {
122 rw.WriteHeader(res.StatusCode)
123
124 if c := logger.Check(zap.DebugLevel, "upgrading connection"); c != nil {
125 c.Write(zap.Int("http_version", req.ProtoMajor))
126 }
127
128 var hijackErr error
129 //nolint:bodyclose
130 conn, brw, hijackErr = http.NewResponseController(rw).Hijack()
131 if errors.Is(hijackErr, http.ErrNotSupported) {
132 if c := h.logger.Check(zap.ErrorLevel, "can't switch protocols using non-Hijacker ResponseWriter"); c != nil {
133 c.Write(zap.String("type", fmt.Sprintf("%T", rw)))
134 }
135 return
136 }
137
138 if hijackErr != nil {
139 if c := h.logger.Check(zap.ErrorLevel, "hijack failed on protocol switch"); c != nil {
140 c.Write(zap.Error(hijackErr))
141 }
142 return
143 }
144 }
145
146 // adopted from https://github.com/golang/go/commit/8bcf2834afdf6a1f7937390903a41518715ef6f5
147 backConnCloseCh := make(chan struct{})
148 go func() {
149 // Ensure that the cancellation of a request closes the backend.
150 // See issue https://golang.org/issue/35559.
151 select {
152 case <-req.Context().Done():
153 case <-backConnCloseCh:
154 }
155 backConn.Close()
156 }()
157 defer close(backConnCloseCh)
158
159 start := time.Now()
160 defer func() {
161 conn.Close()
162 if c := logger.Check(zapcore.DebugLevel, "connection closed"); c != nil {
163 c.Write(zap.Duration("duration", time.Since(start)))
164 }
165 }()
166
167 if err := brw.Flush(); err != nil {
168 if c := logger.Check(zapcore.DebugLevel, "response flush"); c != nil {
169 c.Write(zap.Error(err))
170 }
171 return
172 }
173
174 // There may be buffered data in the *bufio.Reader
175 // see: https://github.com/caddyserver/caddy/issues/6273
176 if buffered := brw.Reader.Buffered(); buffered > 0 {
177 data, _ := brw.Peek(buffered)
178 _, err := backConn.Write(data)
179 if err != nil {
180 if c := logger.Check(zapcore.DebugLevel, "backConn write failed"); c != nil {
181 c.Write(zap.Error(err))
182 }
183 return
184 }
185 }
186
187 // Ensure the hijacked client connection, and the new connection established
188 // with the backend, are both closed in the event of a server shutdown. This
189 // is done by registering them. We also try to gracefully close connections
190 // we recognize as websockets.
191 // We need to make sure the client connection messages (i.e. to upstream)
192 // are masked, so we need to know whether the connection is considered the
193 // server or the client side of the proxy.
194 gracefulClose := func(conn io.ReadWriteCloser, isClient bool) func() error {
195 if isWebsocket(req) {
196 return func() error {
197 return writeCloseControl(conn, isClient)
198 }
199 }
200 return nil
201 }
202 deleteFrontConn := h.registerConnection(conn, gracefulClose(conn, false))
203 deleteBackConn := h.registerConnection(backConn, gracefulClose(backConn, true))
204 defer deleteFrontConn()
205 defer deleteBackConn()
206
207 spc := switchProtocolCopier{
208 user: conn,
209 backend: backConn,
210 wg: wg,
211 bufferSize: h.StreamBufferSize,
212 }
213
214 // setup the timeout if requested
215 var timeoutc <-chan time.Time
216 if h.StreamTimeout > 0 {
217 timer := time.NewTimer(time.Duration(h.StreamTimeout))
218 defer timer.Stop()
219 timeoutc = timer.C
220 }
221
222 // when a stream timeout is encountered, no error will be read from errc
223 // a buffer size of 2 will allow both the read and write goroutines to send the error and exit
224 // see: https://github.com/caddyserver/caddy/issues/7418
225 errc := make(chan error, 2)
226 wg.Add(2)
227 go spc.copyToBackend(errc)
228 go spc.copyFromBackend(errc)
229 select {
230 case err := <-errc:
231 if c := logger.Check(zapcore.DebugLevel, "streaming error"); c != nil {
232 c.Write(zap.Error(err))
233 }
234 case time := <-timeoutc:
235 if c := logger.Check(zapcore.DebugLevel, "stream timed out"); c != nil {
236 c.Write(zap.Time("timeout", time))
237 }
238 }
239 }
240
241 // flushInterval returns the p.FlushInterval value, conditionally
242 // overriding its value for a specific request/response.
243 func (h Handler) flushInterval(req *http.Request, res *http.Response) time.Duration {
244 resCTHeader := res.Header.Get("Content-Type")
245 resCT, _, err := mime.ParseMediaType(resCTHeader)
246
247 // For Server-Sent Events responses, flush immediately.
248 // The MIME type is defined in https://www.w3.org/TR/eventsource/#text-event-stream
249 if err == nil && resCT == "text/event-stream" {
250 return -1 // negative means immediately
251 }
252
253 // We might have the case of streaming for which Content-Length might be unset.
254 if res.ContentLength == -1 {
255 return -1
256 }
257
258 // for h2 and h2c upstream streaming data to client (issues #3556 and #3606)
259 if h.isBidirectionalStream(req, res) {
260 return -1
261 }
262
263 return time.Duration(h.FlushInterval)
264 }
265
266 // isBidirectionalStream returns whether we should work in bi-directional stream mode.
267 //
268 // See https://github.com/caddyserver/caddy/pull/3620 for discussion of nuances.
269 func (h Handler) isBidirectionalStream(req *http.Request, res *http.Response) bool {
270 // We have to check the encoding here; only flush headers with identity encoding.
271 // Non-identity encoding might combine with "encode" directive, and in that case,
272 // if body size larger than enc.MinLength, upper level encode handle might have
273 // Content-Encoding header to write.
274 // (see https://github.com/caddyserver/caddy/issues/3606 for use case)
275 ae := req.Header.Get("Accept-Encoding")
276
277 return req.ProtoMajor == 2 &&
278 res.ProtoMajor == 2 &&
279 res.ContentLength == -1 &&
280 (ae == "identity" || ae == "")
281 }
282
283 func (h Handler) copyResponse(dst http.ResponseWriter, src io.Reader, flushInterval time.Duration, logger *zap.Logger) error {
284 var w io.Writer = dst
285
286 if flushInterval != 0 {
287 var mlwLogger *zap.Logger
288 if h.VerboseLogs {
289 mlwLogger = logger.Named("max_latency_writer")
290 } else {
291 mlwLogger = zap.NewNop()
292 }
293 mlw := &maxLatencyWriter{
294 dst: dst,
295 //nolint:bodyclose
296 flush: http.NewResponseController(dst).Flush,
297 latency: flushInterval,
298 logger: mlwLogger,
299 }
300 defer mlw.stop()
301
302 // set up initial timer so headers get flushed even if body writes are delayed
303 mlw.flushPending = true
304 mlw.t = time.AfterFunc(flushInterval, mlw.delayedFlush)
305
306 w = mlw
307 }
308
309 buf := streamingBufPool.Get().(*[]byte)
310 defer streamingBufPool.Put(buf)
311
312 var copyLogger *zap.Logger
313 if h.VerboseLogs {
314 copyLogger = logger
315 } else {
316 copyLogger = zap.NewNop()
317 }
318
319 _, err := h.copyBuffer(w, src, *buf, copyLogger)
320 return err
321 }
322
323 // copyBuffer returns any write errors or non-EOF read errors, and the amount
324 // of bytes written.
325 func (h Handler) copyBuffer(dst io.Writer, src io.Reader, buf []byte, logger *zap.Logger) (int64, error) {
326 if len(buf) == 0 {
327 buf = make([]byte, defaultBufferSize)
328 }
329 var written int64
330 for {
331 logger.Debug("waiting to read from upstream")
332 nr, rerr := src.Read(buf)
333 logger := logger.With(zap.Int("read", nr))
334 if c := logger.Check(zapcore.DebugLevel, "read from upstream"); c != nil {
335 c.Write(zap.Error(rerr))
336 }
337 if rerr != nil && rerr != io.EOF && rerr != context.Canceled {
338 // TODO: this could be useful to know (indeed, it revealed an error in our
339 // fastcgi PoC earlier; but it's this single error report here that necessitates
340 // a function separate from io.CopyBuffer, since io.CopyBuffer does not distinguish
341 // between read or write errors; in a reverse proxy situation, write errors are not
342 // something we need to report to the client, but read errors are a problem on our
343 // end for sure. so we need to decide what we want.)
344 // p.logf("copyBuffer: ReverseProxy read error during body copy: %v", rerr)
345 if c := logger.Check(zapcore.ErrorLevel, "reading from backend"); c != nil {
346 c.Write(zap.Error(rerr))
347 }
348 }
349 if nr > 0 {
350 logger.Debug("writing to downstream")
351 nw, werr := dst.Write(buf[:nr])
352 if nw > 0 {
353 written += int64(nw)
354 }
355 if c := logger.Check(zapcore.DebugLevel, "wrote to downstream"); c != nil {
356 c.Write(
357 zap.Int("written", nw),
358 zap.Int64("written_total", written),
359 zap.Error(werr),
360 )
361 }
362 if werr != nil {
363 return written, fmt.Errorf("writing: %w", werr)
364 }
365 if nr != nw {
366 return written, io.ErrShortWrite
367 }
368 }
369 if rerr != nil {
370 if rerr == io.EOF {
371 return written, nil
372 }
373 return written, fmt.Errorf("reading: %w", rerr)
374 }
375 }
376 }
377
378 // registerConnection holds onto conn so it can be closed in the event
379 // of a server shutdown. This is useful because hijacked connections or
380 // connections dialed to backends don't close when server is shut down.
381 // The caller should call the returned delete() function when the
382 // connection is done to remove it from memory.
383 func (h *Handler) registerConnection(conn io.ReadWriteCloser, gracefulClose func() error) (del func()) {
384 h.connectionsMu.Lock()
385 h.connections[conn] = openConnection{conn, gracefulClose}
386 h.connectionsMu.Unlock()
387 return func() {
388 h.connectionsMu.Lock()
389 delete(h.connections, conn)
390 // if there is no connection left before the connections close timer fires
391 if len(h.connections) == 0 && h.connectionsCloseTimer != nil {
392 // we release the timer that holds the reference to Handler
393 if (*h.connectionsCloseTimer).Stop() {
394 h.logger.Debug("stopped streaming connections close timer - all connections are already closed")
395 }
396 h.connectionsCloseTimer = nil
397 }
398 h.connectionsMu.Unlock()
399 }
400 }
401
402 // closeConnections immediately closes all hijacked connections (both to client and backend).
403 func (h *Handler) closeConnections() error {
404 var err error
405 h.connectionsMu.Lock()
406 defer h.connectionsMu.Unlock()
407
408 for _, oc := range h.connections {
409 if oc.gracefulClose != nil {
410 // this is potentially blocking while we have the lock on the connections
411 // map, but that should be OK since the server has in theory shut down
412 // and we are no longer using the connections map
413 gracefulErr := oc.gracefulClose()
414 if gracefulErr != nil && err == nil {
415 err = gracefulErr
416 }
417 }
418 closeErr := oc.conn.Close()
419 if closeErr != nil && err == nil {
420 err = closeErr
421 }
422 }
423 return err
424 }
425
426 // cleanupConnections closes hijacked connections.
427 // Depending on the value of StreamCloseDelay it does that either immediately
428 // or sets up a timer that will do that later.
429 func (h *Handler) cleanupConnections() error {
430 if h.StreamCloseDelay == 0 {
431 return h.closeConnections()
432 }
433
434 h.connectionsMu.Lock()
435 defer h.connectionsMu.Unlock()
436 // the handler is shut down, no new connection can appear,
437 // so we can skip setting up the timer when there are no connections
438 if len(h.connections) > 0 {
439 delay := time.Duration(h.StreamCloseDelay)
440 h.connectionsCloseTimer = time.AfterFunc(delay, func() {
441 if c := h.logger.Check(zapcore.DebugLevel, "closing streaming connections after delay"); c != nil {
442 c.Write(zap.Duration("delay", delay))
443 }
444 err := h.closeConnections()
445 if err != nil {
446 if c := h.logger.Check(zapcore.ErrorLevel, "failed to closed connections after delay"); c != nil {
447 c.Write(
448 zap.Error(err),
449 zap.Duration("delay", delay),
450 )
451 }
452 }
453 })
454 }
455 return nil
456 }
457
458 // writeCloseControl sends a best-effort Close control message to the given
459 // WebSocket connection. Thanks to @pascaldekloe who provided inspiration
460 // from his simple implementation of this I was able to learn from at:
461 // github.com/pascaldekloe/websocket. Further work for handling masking
462 // taken from github.com/gorilla/websocket.
463 func writeCloseControl(conn io.Writer, isClient bool) error {
464 // Sources:
465 // https://github.com/pascaldekloe/websocket/blob/32050af67a5d/websocket.go#L119
466 // https://github.com/gorilla/websocket/blob/v1.5.0/conn.go#L413
467
468 // For now, we're not using a reason. We might later, though.
469 // The code handling the reason is left in
470 var reason string // max 123 bytes (control frame payload limit is 125; status code takes 2)
471
472 const closeMessage = 8
473 const finalBit = 1 << 7 // Frame header byte 0 bits from Section 5.2 of RFC 6455
474 const maskBit = 1 << 7 // Frame header byte 1 bits from Section 5.2 of RFC 6455
475 const goingAwayUpper uint8 = 1001 >> 8
476 const goingAwayLower uint8 = 1001 & 0xff
477
478 b0 := byte(closeMessage) | finalBit
479 b1 := byte(len(reason) + 2)
480 if isClient {
481 b1 |= maskBit
482 }
483
484 buf := make([]byte, 0, 127)
485 buf = append(buf, b0, b1)
486 msgLength := 4 + len(reason)
487
488 // Both branches below append the "going away" code and reason
489 appendMessage := func(buf []byte) []byte {
490 buf = append(buf, goingAwayUpper, goingAwayLower)
491 buf = append(buf, []byte(reason)...)
492 return buf
493 }
494
495 // When we're the client, we need to mask the message as per
496 // https://www.rfc-editor.org/rfc/rfc6455#section-5.3
497 if isClient {
498 key := newMaskKey()
499 buf = append(buf, key[:]...)
500 msgLength += len(key)
501 buf = appendMessage(buf)
502 maskBytes(key, 0, buf[2+len(key):])
503 } else {
504 buf = appendMessage(buf)
505 }
506
507 // simply best-effort, but return error for logging purposes
508 // TODO: we might need to ensure we are the exclusive writer by this point (io.Copy is stopped)?
509 _, err := conn.Write(buf[:msgLength])
510 return err
511 }
512
513 // Copied from https://github.com/gorilla/websocket/blob/v1.5.0/mask.go
514 func maskBytes(key [4]byte, pos int, b []byte) int {
515 // Mask one byte at a time for small buffers.
516 if len(b) < 2*wordSize {
517 for i := range b {
518 b[i] ^= key[pos&3]
519 pos++
520 }
521 return pos & 3
522 }
523
524 // Mask one byte at a time to word boundary.
525 if n := int(uintptr(unsafe.Pointer(&b[0]))) % wordSize; n != 0 {
526 n = wordSize - n
527 for i := range b[:n] {
528 b[i] ^= key[pos&3]
529 pos++
530 }
531 b = b[n:]
532 }
533
534 // Create aligned word size key.
535 var k [wordSize]byte
536 for i := range k {
537 k[i] = key[(pos+i)&3] // nolint:gosec // false positive, impossible to be out of bounds; see: https://github.com/securego/gosec/issues/1525
538 }
539 kw := *(*uintptr)(unsafe.Pointer(&k))
540
541 // Mask one word at a time.
542 n := (len(b) / wordSize) * wordSize
543 for i := 0; i < n; i += wordSize {
544 *(*uintptr)(unsafe.Add(unsafe.Pointer(&b[0]), i)) ^= kw
545 }
546
547 // Mask one byte at a time for remaining bytes.
548 b = b[n:]
549 for i := range b {
550 b[i] ^= key[pos&3]
551 pos++
552 }
553
554 return pos & 3
555 }
556
557 // Copied from https://github.com/gorilla/websocket/blob/v1.5.0/conn.go#L184
558 func newMaskKey() [4]byte {
559 n := weakrand.Uint32()
560 return [4]byte{byte(n), byte(n >> 8), byte(n >> 16), byte(n >> 24)}
561 }
562
563 // isWebsocket returns true if r looks to be an upgrade request for WebSockets.
564 // It is a fairly naive check.
565 func isWebsocket(r *http.Request) bool {
566 return httpguts.HeaderValuesContainsToken(r.Header["Connection"], "upgrade") &&
567 httpguts.HeaderValuesContainsToken(r.Header["Upgrade"], "websocket")
568 }
569
570 // openConnection maps an open connection to
571 // an optional function for graceful close.
572 type openConnection struct {
573 conn io.ReadWriteCloser
574 gracefulClose func() error
575 }
576
577 type maxLatencyWriter struct {
578 dst io.Writer
579 flush func() error
580 latency time.Duration // non-zero; negative means to flush immediately
581
582 mu sync.Mutex // protects t, flushPending, and dst.Flush
583 t *time.Timer
584 flushPending bool
585 logger *zap.Logger
586 }
587
588 func (m *maxLatencyWriter) Write(p []byte) (n int, err error) {
589 m.mu.Lock()
590 defer m.mu.Unlock()
591 n, err = m.dst.Write(p)
592 if c := m.logger.Check(zapcore.DebugLevel, "wrote bytes"); c != nil {
593 c.Write(zap.Int("n", n), zap.Error(err))
594 }
595 if m.latency < 0 {
596 m.logger.Debug("flushing immediately")
597 //nolint:errcheck
598 m.flush()
599 return n, err
600 }
601 if m.flushPending {
602 m.logger.Debug("delayed flush already pending")
603 return n, err
604 }
605 if m.t == nil {
606 m.t = time.AfterFunc(m.latency, m.delayedFlush)
607 } else {
608 m.t.Reset(m.latency)
609 }
610 if c := m.logger.Check(zapcore.DebugLevel, "timer set for delayed flush"); c != nil {
611 c.Write(zap.Duration("duration", m.latency))
612 }
613 m.flushPending = true
614 return n, err
615 }
616
617 func (m *maxLatencyWriter) delayedFlush() {
618 m.mu.Lock()
619 defer m.mu.Unlock()
620 if !m.flushPending { // if stop was called but AfterFunc already started this goroutine
621 m.logger.Debug("delayed flush is not pending")
622 return
623 }
624 m.logger.Debug("delayed flush")
625 //nolint:errcheck
626 m.flush()
627 m.flushPending = false
628 }
629
630 func (m *maxLatencyWriter) stop() {
631 m.mu.Lock()
632 defer m.mu.Unlock()
633 m.flushPending = false
634 if m.t != nil {
635 m.t.Stop()
636 }
637 }
638
639 // switchProtocolCopier exists so goroutines proxying data back and
640 // forth have nice names in stacks.
641 type switchProtocolCopier struct {
642 user, backend io.ReadWriteCloser
643 wg *sync.WaitGroup
644 bufferSize int
645 }
646
647 func (c switchProtocolCopier) copyFromBackend(errc chan<- error) {
648 _, err := io.CopyBuffer(c.user, c.backend, c.buffer())
649 errc <- err
650 c.wg.Done()
651 }
652
653 func (c switchProtocolCopier) copyToBackend(errc chan<- error) {
654 _, err := io.CopyBuffer(c.backend, c.user, c.buffer())
655 errc <- err
656 c.wg.Done()
657 }
658
659 func (c switchProtocolCopier) buffer() []byte {
660 size := c.bufferSize
661 if size <= 0 {
662 size = defaultBufferSize
663 }
664 return make([]byte, size)
665 }
666
667 var streamingBufPool = sync.Pool{
668 New: func() any {
669 // The Pool's New function should generally only return pointer
670 // types, since a pointer can be put into the return interface
671 // value without an allocation
672 // - (from the package docs)
673 b := make([]byte, defaultBufferSize)
674 return &b
675 },
676 }
677
678 const (
679 defaultBufferSize = 32 * 1024
680 wordSize = int(unsafe.Sizeof(uintptr(0)))
681 )