aboutsummaryrefslogtreecommitdiff
path: root/vendor/github.com/emersion/go-smtp/lengthlimit_reader.go
blob: 1513e5647ac1b0a658e9bae422bbcd4f0f922cfb (plain)
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
package smtp

import (
	"errors"
	"io"
)

var ErrTooLongLine = errors.New("smtp: too long a line in input stream")

// lineLimitReader reads from the underlying Reader but restricts
// line length of lines in input stream to a certain length.
//
// If line length exceeds the limit - Read returns ErrTooLongLine
type lineLimitReader struct {
	R         io.Reader
	LineLimit int

	curLineLength int
}

func (r *lineLimitReader) Read(b []byte) (int, error) {
	if r.curLineLength > r.LineLimit && r.LineLimit > 0 {
		return 0, ErrTooLongLine
	}

	n, err := r.R.Read(b)
	if err != nil {
		return n, err
	}

	if r.LineLimit == 0 {
		return n, nil
	}

	for _, chr := range b[:n] {
		if chr == '\n' {
			r.curLineLength = 0
		}
		r.curLineLength++

		if r.curLineLength > r.LineLimit {
			return 0, ErrTooLongLine
		}
	}

	return n, nil
}