srdusr
aboutsummaryrefslogtreecommitdiffstats
path: root/internal/proxy/capture.go
blob: ec4dc8d528b0cc0669f52c734f6729d8befc7c93 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package proxy

import (
	"bytes"
	"io"
	"net/http"
)

// cappedTee wraps an io.Reader, copying up to maxCaptureBytes of what
// passes through into an internal buffer while still passing everything
// through unmodified and unbounded to the real reader. Used to capture a
// bounded sample of a body for reconstruction when exact wire capture
// isn't available (the HTTP/2 leg - see below).
type cappedTee struct {
	r   io.Reader
	buf bytes.Buffer
}

func newCappedTee(r io.Reader) *cappedTee {
	return &cappedTee{r: r}
}

func (c *cappedTee) Read(p []byte) (int, error) {
	n, err := c.r.Read(p)
	if n > 0 {
		if room := maxCaptureBytes - c.buf.Len(); room > 0 {
			end := n
			if end > room {
				end = room
			}
			c.buf.Write(p[:end])
		}
	}
	return n, err
}

// captureRequest returns the raw bytes of r for storage. When tee is
// non-nil (an HTTP/1.1 client connection), the bytes are exactly what
// was read off the wire. Otherwise (HTTP/2, which has no single "raw
// bytes" representation - it's multiplexed, HPACK-compressed framing)
// it's a reconstruction from the parsed request, exact=false.
func captureRequest(r *http.Request, tee *teeConn, bodyCap *cappedTee) (raw []byte, exact bool) {
	if tee != nil {
		return tee.Take(), true
	}

	dump := r.Clone(r.Context())
	if bodyCap != nil {
		dump.Body = io.NopCloser(bytes.NewReader(bodyCap.buf.Bytes()))
		dump.ContentLength = int64(bodyCap.buf.Len())
	} else {
		dump.Body = http.NoBody
		dump.ContentLength = 0
	}
	var buf bytes.Buffer
	if err := dump.Write(&buf); err != nil {
		return nil, false
	}
	return buf.Bytes(), false
}

// captureResponse reconstructs raw response bytes from the parsed
// response for the HTTP/2 upstream case - the exact-capture path
// (HTTP/1.1 upstream) is handled directly in forward() via the
// teeConn's own Take(), which is the only reason this one doesn't also
// need a *teeConn parameter.
func captureResponse(resp *http.Response, bodyCap *cappedTee) (raw []byte, exact bool) {
	dump := *resp
	if bodyCap != nil {
		dump.Body = io.NopCloser(bytes.NewReader(bodyCap.buf.Bytes()))
		dump.ContentLength = int64(bodyCap.buf.Len())
	} else {
		dump.Body = http.NoBody
		dump.ContentLength = 0
	}
	var buf bytes.Buffer
	if err := dump.Write(&buf); err != nil {
		return nil, false
	}
	return buf.Bytes(), false
}