srdusr
aboutsummaryrefslogtreecommitdiffstats
path: root/internal/proxy/bodyrules.go
blob: 128464c6699e1486c31c0e7347290143ab4b6046 (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
package proxy

import (
	"bytes"
	"io"

	"mitmux/internal/rules"
)

// applyBodyRules reads body fully (bounded by maxCaptureBytes - a body
// rule is opted into deliberately by whoever wrote it, but an unbounded
// read of a maliciously or just accidentally huge body would still be a
// memory-exhaustion vector) and, if it fits, runs bodyRules over it via
// rules.ApplyBody and returns a fresh reader over the result.
//
// If the body is larger than the cap, it's passed straight through
// completely unmodified - reconstructed from the bytes already read
// plus whatever's left on the original reader - rather than rewriting
// only part of it or dropping data. A body a rule can't safely see in
// full is better left alone than partially corrupted; applied=false
// tells the caller not to touch Content-Length, since the original
// length (whatever it was) is still exactly right.
func applyBodyRules(body io.ReadCloser, bodyRules []rules.Rule) (newBody io.ReadCloser, newLength int64, applied bool, err error) {
	if body == nil {
		return body, 0, false, nil
	}

	limited := io.LimitReader(body, maxCaptureBytes+1)
	data, err := io.ReadAll(limited)
	if err != nil {
		body.Close()
		return nil, 0, false, err
	}

	if int64(len(data)) > maxCaptureBytes {
		return struct {
			io.Reader
			io.Closer
		}{io.MultiReader(bytes.NewReader(data), body), body}, 0, false, nil
	}

	body.Close()
	rewritten := rules.ApplyBody(data, bodyRules)
	return io.NopCloser(bytes.NewReader(rewritten)), int64(len(rewritten)), true, nil
}