forked from corazawaf/coraza
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbody_buffer.go
90 lines (82 loc) · 2.32 KB
/
body_buffer.go
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
82
83
84
85
86
87
88
89
90
// Copyright 2021 Juan Pablo Tosso
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package coraza
import (
"bytes"
"io"
"os"
)
// BodyReader is used to read RequestBody and ResponseBody objects
// It will handle memory usage for buffering and processing
type BodyBuffer struct {
io.Writer //OK?
tmpDir string
buffer *bytes.Buffer
writer *os.File
length int64
memoryLimit int64
}
// Write appends data to the body buffer by chunks
// You may dump io.Readers using io.Copy(br, reader)
func (br *BodyBuffer) Write(data []byte) (n int, err error) {
l := int64(len(data)) + br.length
if l >= br.memoryLimit {
if br.writer == nil {
br.writer, err = os.CreateTemp(br.tmpDir, "body*")
if err != nil {
return 0, err
}
// we dump the previous buffer
br.writer.Write(br.buffer.Bytes())
defer br.buffer.Reset()
}
br.length = l
return br.writer.Write(data)
}
br.length = l
return br.buffer.Write(data)
}
// Reader Returns a working reader for the body buffer in memory or file
func (br *BodyBuffer) Reader() io.Reader {
if br.writer == nil {
return bytes.NewReader(br.buffer.Bytes())
}
_, _ = br.writer.Seek(0, 0)
return br.writer
}
// Size returns the current size of the body buffer
func (br *BodyBuffer) Size() int64 {
return br.length
}
// Close will close all readers and delete temporary files
func (br *BodyBuffer) Close() {
if br.writer == nil {
return
}
br.writer.Close()
if br.writer != nil {
os.Remove(br.writer.Name())
}
}
// NewBodyReader Initializes a body reader
// After writing memLimit bytes to the memory buffer, data will be
// written to a temporary file
// Temporary files will be written to tmpDir
func NewBodyReader(tmpDir string, memLimit int64) *BodyBuffer {
return &BodyBuffer{
buffer: &bytes.Buffer{},
tmpDir: tmpDir,
memoryLimit: memLimit,
}
}