| 1 |
package enmime |
| 2 |
|
| 3 |
import ( |
| 4 |
"bufio" |
| 5 |
"bytes" |
| 6 |
stderrors "errors" |
| 7 |
"io" |
| 8 |
"io/ioutil" |
| 9 |
"unicode" |
| 10 |
|
| 11 |
"github.com/pkg/errors" |
| 12 |
) |
| 13 |
|
| 14 |
// This constant needs to be at least 76 for this package to work correctly. This is because |
| 15 |
// \r\n--separator_of_len_70- would fill the buffer and it wouldn't be safe to consume a single byte |
| 16 |
// from it. |
| 17 |
const peekBufferSize = 4096 |
| 18 |
|
| 19 |
var errNoBoundaryTerminator = stderrors.New("expected boundary not present") |
| 20 |
|
| 21 |
type boundaryReader struct { |
| 22 |
finished bool // No parts remain when finished |
| 23 |
partsRead int // Number of parts read thus far |
| 24 |
atPartStart bool // Whether the current part is at its beginning |
| 25 |
r *bufio.Reader // Source reader |
| 26 |
nlPrefix []byte // NL + MIME boundary prefix |
| 27 |
prefix []byte // MIME boundary prefix |
| 28 |
final []byte // Final boundary prefix |
| 29 |
buffer *bytes.Buffer // Content waiting to be read |
| 30 |
unbounded bool // Flag to throw errNoBoundaryTerminator |
| 31 |
} |
| 32 |
|
| 33 |
// newBoundaryReader returns an initialized boundaryReader |
| 34 |
func newBoundaryReader(reader *bufio.Reader, boundary string) *boundaryReader { |
| 35 |
fullBoundary := []byte("\n--" + boundary + "--") |
| 36 |
return &boundaryReader{ |
| 37 |
r: reader, |
| 38 |
nlPrefix: fullBoundary[:len(fullBoundary)-2], |
| 39 |
prefix: fullBoundary[1 : len(fullBoundary)-2], |
| 40 |
final: fullBoundary[1:], |
| 41 |
buffer: new(bytes.Buffer), |
| 42 |
} |
| 43 |
} |
| 44 |
|
| 45 |
// Read returns a buffer containing the content up until boundary |
| 46 |
// |
| 47 |
// Excerpt from io package on io.Reader implementations: |
| 48 |
// |
| 49 |
// type Reader interface { |
| 50 |
// Read(p []byte) (n int, err error) |
| 51 |
// } |
| 52 |
// |
| 53 |
// Read reads up to len(p) bytes into p. It returns the number of |
| 54 |
// bytes read (0 <= n <= len(p)) and any error encountered. Even |
| 55 |
// if Read returns n < len(p), it may use all of p as scratch space |
| 56 |
// during the call. If some data is available but not len(p) bytes, |
| 57 |
// Read conventionally returns what is available instead of waiting |
| 58 |
// for more. |
| 59 |
// |
| 60 |
// When Read encounters an error or end-of-file condition after |
| 61 |
// successfully reading n > 0 bytes, it returns the number of bytes |
| 62 |
// read. It may return the (non-nil) error from the same call or |
| 63 |
// return the error (and n == 0) from a subsequent call. An instance |
| 64 |
// of this general case is that a Reader returning a non-zero number |
| 65 |
// of bytes at the end of the input stream may return either err == EOF |
| 66 |
// or err == nil. The next Read should return 0, EOF. |
| 67 |
// |
| 68 |
// Callers should always process the n > 0 bytes returned before |
| 69 |
// considering the error err. Doing so correctly handles I/O errors |
| 70 |
// that happen after reading some bytes and also both of the allowed |
| 71 |
// EOF behaviors. |
| 72 |
func (b *boundaryReader) Read(dest []byte) (n int, err error) { |
| 73 |
if b.buffer.Len() >= len(dest) { |
| 74 |
// This read request can be satisfied entirely by the buffer. |
| 75 |
n, err = b.buffer.Read(dest) |
| 76 |
if b.atPartStart && n > 0 { |
| 77 |
b.atPartStart = false |
| 78 |
} |
| 79 |
|
| 80 |
return n, err |
| 81 |
} |
| 82 |
|
| 83 |
for i := 0; i < len(dest); i++ { |
| 84 |
var cs []byte |
| 85 |
cs, err = b.r.Peek(1) |
| 86 |
if err != nil && err != io.EOF { |
| 87 |
return 0, errors.WithStack(err) |
| 88 |
} |
| 89 |
// Ensure that we can switch on the first byte of 'cs' without panic. |
| 90 |
if len(cs) > 0 { |
| 91 |
padding := 1 |
| 92 |
check := false |
| 93 |
|
| 94 |
switch cs[0] { |
| 95 |
// Check for carriage return as potential CRLF boundary prefix. |
| 96 |
case '\r': |
| 97 |
padding = 2 |
| 98 |
check = true |
| 99 |
// Check for line feed as potential LF boundary prefix. |
| 100 |
case '\n': |
| 101 |
check = true |
| 102 |
|
| 103 |
default: |
| 104 |
if b.atPartStart { |
| 105 |
// If we're at the very beginning of the part (even before the headers), |
| 106 |
// check to see if there's a delimiter that immediately follows. |
| 107 |
padding = 0 |
| 108 |
check = true |
| 109 |
} |
| 110 |
} |
| 111 |
|
| 112 |
if check { |
| 113 |
var peek []byte |
| 114 |
peek, err = b.r.Peek(len(b.nlPrefix) + padding + 1) |
| 115 |
switch err { |
| 116 |
case nil: |
| 117 |
// Check the whitespace at the head of the peek to avoid checking for a boundary early. |
| 118 |
if bytes.HasPrefix(peek, []byte("\n\n")) || |
| 119 |
bytes.HasPrefix(peek, []byte("\n\r")) || |
| 120 |
bytes.HasPrefix(peek, []byte("\r\n\r")) || |
| 121 |
bytes.HasPrefix(peek, []byte("\r\n\n")) { |
| 122 |
break |
| 123 |
} |
| 124 |
// Check the peek buffer for a boundary delimiter or terminator. |
| 125 |
if b.isDelimiter(peek[padding:]) || b.isTerminator(peek[padding:]) { |
| 126 |
// We have found our boundary terminator, lets write out the final bytes |
| 127 |
// and return io.EOF to indicate that this section read is complete. |
| 128 |
n, err = b.buffer.Read(dest) |
| 129 |
switch err { |
| 130 |
case nil, io.EOF: |
| 131 |
if b.atPartStart && n > 0 { |
| 132 |
b.atPartStart = false |
| 133 |
} |
| 134 |
return n, io.EOF |
| 135 |
default: |
| 136 |
return 0, errors.WithStack(err) |
| 137 |
} |
| 138 |
} |
| 139 |
case io.EOF: |
| 140 |
// We have reached the end without finding a boundary, |
| 141 |
// so we flag the boundary reader to add an error to |
| 142 |
// the errors slice and write what we have to the buffer. |
| 143 |
b.unbounded = true |
| 144 |
default: |
| 145 |
continue |
| 146 |
} |
| 147 |
} |
| 148 |
} |
| 149 |
|
| 150 |
var next byte |
| 151 |
next, err = b.r.ReadByte() |
| 152 |
if err != nil { |
| 153 |
// EOF is not fatal, it just means that we have drained the reader. |
| 154 |
if errors.Is(err, io.EOF) { |
| 155 |
break |
| 156 |
} |
| 157 |
|
| 158 |
return 0, errors.WithStack(err) |
| 159 |
} |
| 160 |
|
| 161 |
if err = b.buffer.WriteByte(next); err != nil { |
| 162 |
return 0, errors.WithStack(err) |
| 163 |
} |
| 164 |
} |
| 165 |
|
| 166 |
// Read the contents of the buffer into the destination slice. |
| 167 |
n, err = b.buffer.Read(dest) |
| 168 |
if b.atPartStart && n > 0 { |
| 169 |
b.atPartStart = false |
| 170 |
} |
| 171 |
return n, err |
| 172 |
} |
| 173 |
|
| 174 |
// Next moves over the boundary to the next part, returns true if there is another part to be read. |
| 175 |
func (b *boundaryReader) Next() (bool, error) { |
| 176 |
if b.finished { |
| 177 |
return false, nil |
| 178 |
} |
| 179 |
if b.partsRead > 0 { |
| 180 |
// Exhaust the current part to prevent errors when moving to the next part. |
| 181 |
_, _ = io.Copy(ioutil.Discard, b) |
| 182 |
} |
| 183 |
for { |
| 184 |
var line []byte = nil |
| 185 |
var err error |
| 186 |
for { |
| 187 |
// Read whole line, handle extra long lines in cycle |
| 188 |
var segment []byte |
| 189 |
segment, err = b.r.ReadSlice('\n') |
| 190 |
if line == nil { |
| 191 |
line = segment |
| 192 |
} else { |
| 193 |
line = append(line, segment...) |
| 194 |
} |
| 195 |
|
| 196 |
if err == nil || err == io.EOF { |
| 197 |
break |
| 198 |
} else if err != bufio.ErrBufferFull || len(segment) == 0 { |
| 199 |
return false, errors.WithStack(err) |
| 200 |
} |
| 201 |
} |
| 202 |
|
| 203 |
if len(line) > 0 && (line[0] == '\r' || line[0] == '\n') { |
| 204 |
// Blank line |
| 205 |
continue |
| 206 |
} |
| 207 |
if b.isTerminator(line) { |
| 208 |
b.finished = true |
| 209 |
return false, nil |
| 210 |
} |
| 211 |
if err != io.EOF && b.isDelimiter(line) { |
| 212 |
// Start of a new part. |
| 213 |
b.partsRead++ |
| 214 |
b.atPartStart = true |
| 215 |
return true, nil |
| 216 |
} |
| 217 |
if err == io.EOF { |
| 218 |
// Intentionally not wrapping with stack. |
| 219 |
return false, io.EOF |
| 220 |
} |
| 221 |
if b.partsRead == 0 { |
| 222 |
// The first part didn't find the starting delimiter, burn off any preamble in front of |
| 223 |
// the boundary. |
| 224 |
continue |
| 225 |
} |
| 226 |
b.finished = true |
| 227 |
return false, errors.WithMessagef(errNoBoundaryTerminator, "expecting boundary %q, got %q", string(b.prefix), string(line)) |
| 228 |
} |
| 229 |
} |
| 230 |
|
| 231 |
// isDelimiter returns true for --BOUNDARY\r\n but not --BOUNDARY-- |
| 232 |
func (b *boundaryReader) isDelimiter(buf []byte) bool { |
| 233 |
idx := bytes.Index(buf, b.prefix) |
| 234 |
if idx == -1 { |
| 235 |
return false |
| 236 |
} |
| 237 |
|
| 238 |
// Fast forward to the end of the boundary prefix. |
| 239 |
buf = buf[idx+len(b.prefix):] |
| 240 |
if len(buf) > 0 { |
| 241 |
if unicode.IsSpace(rune(buf[0])) { |
| 242 |
return true |
| 243 |
} |
| 244 |
} |
| 245 |
|
| 246 |
return false |
| 247 |
} |
| 248 |
|
| 249 |
// isTerminator returns true for --BOUNDARY-- |
| 250 |
func (b *boundaryReader) isTerminator(buf []byte) bool { |
| 251 |
idx := bytes.Index(buf, b.final) |
| 252 |
return idx != -1 |
| 253 |
} |