1package smtp
2
3import (
4 "bufio"
5 "bytes"
6 "errors"
7 "io"
8)
9
10var ErrCRLF = errors.New("invalid bare carriage return or newline")
11
12var errMissingCRLF = errors.New("missing crlf at end of message")
13
14// DataWrite reads data (a mail message) from r, and writes it to smtp
15// connection w with dot stuffing, as required by the SMTP data command.
16//
17// Messages with bare carriage returns or bare newlines result in an error.
18func DataWrite(w io.Writer, r io.Reader) error {
19 // ../rfc/5321:2003
20
21 var prevlast, last byte = '\r', '\n' // Start on a new line, so we insert a dot if the first byte is a dot.
22 // todo: at least for smtp submission we should probably set a max line length, eg 1000 octects including crlf. ../rfc/5321:3512
23 buf := make([]byte, 8*1024)
24 for {
25 nr, err := r.Read(buf)
26 if nr > 0 {
27 // Process buf by writing a line at a time, and checking if the next character
28 // after the line starts with a dot. Insert an extra dot if so.
29 p := buf[:nr]
30 for len(p) > 0 {
31 if p[0] == '.' && prevlast == '\r' && last == '\n' {
32 if _, err := w.Write([]byte{'.'}); err != nil {
33 return err
34 }
35 }
36 // Look for the next newline, or end of buffer.
37 n := 0
38 firstcr := -1
39 for n < len(p) {
40 c := p[n]
41 if c == '\n' {
42 if firstcr < 0 {
43 // Bare newline.
44 return ErrCRLF
45 } else if firstcr != n-1 {
46 // Bare carriage return.
47 return ErrCRLF
48 }
49 n++
50 break
51 } else if c == '\r' && firstcr < 0 {
52 firstcr = n
53 }
54 n++
55 }
56
57 if _, err := w.Write(p[:n]); err != nil {
58 return err
59 }
60 // Keep track of the last two bytes we've written.
61 if n == 1 {
62 prevlast, last = last, p[0]
63 } else {
64 prevlast, last = p[n-2], p[n-1]
65 }
66 p = p[n:]
67 }
68 }
69 if err == io.EOF {
70 break
71 } else if err != nil {
72 return err
73 }
74 }
75 if prevlast != '\r' || last != '\n' {
76 return errMissingCRLF
77 }
78 if _, err := w.Write(dotcrlf); err != nil {
79 return err
80 }
81 return nil
82}
83
84var dotcrlf = []byte(".\r\n")
85
86// DataReader is an io.Reader that reads data from an SMTP DATA command, doing dot
87// unstuffing and returning io.EOF when a bare dot is received. Use NewDataReader.
88//
89// Bare carriage returns, and the sequences "[^\r]\n." and "\n.\n" result in an
90// error.
91type DataReader struct {
92 // ../rfc/5321:2003
93 r *bufio.Reader
94 plast, last byte
95 buf []byte // From previous read.
96 err error // Read error, for after r.buf is exhausted.
97
98 // When we see invalid combinations of CR and LF, we keep reading, and report an
99 // error at the final "\r\n.\r\n". We cannot just stop reading and return an error,
100 // the SMTP protocol would become out of sync.
101 badcrlf bool
102}
103
104// NewDataReader returns an initialized DataReader.
105func NewDataReader(r *bufio.Reader) *DataReader {
106 return &DataReader{
107 r: r,
108 // Set up initial state to accept a message that is only "." and CRLF.
109 plast: '\r',
110 last: '\n',
111 }
112}
113
114// Read implements io.Reader.
115func (r *DataReader) Read(p []byte) (int, error) {
116 wrote := 0
117 for len(p) > 0 {
118 // Read until newline as long as it fits in the buffer.
119 if len(r.buf) == 0 {
120 if r.err != nil {
121 break
122 }
123 // todo: set a max length, eg 1000 octets including crlf excluding potential leading dot. ../rfc/5321:3512
124 r.buf, r.err = r.r.ReadSlice('\n')
125 if r.err == bufio.ErrBufferFull {
126 r.err = nil
127 } else if r.err == io.EOF {
128 // Mark EOF as bad for now. If we see the ending dotcrlf below, err becomes regular
129 // io.EOF again.
130 r.err = io.ErrUnexpectedEOF
131 }
132 }
133 if len(r.buf) > 0 {
134 // Reject bare \r.
135 for i, c := range r.buf {
136 if c == '\r' && (i == len(r.buf) || r.buf[i+1] != '\n') {
137 r.badcrlf = true
138 }
139 }
140
141 // We require crlf. A bare LF is not a line ending for the end of the SMTP
142 // transaction. ../rfc/5321:2032
143 // Bare newlines are accepted as message data, unless around a bare dot. The SMTP
144 // server adds missing carriage returns. We don't reject bare newlines outright,
145 // real-world messages like that occur.
146 if r.plast == '\r' && r.last == '\n' {
147 if bytes.Equal(r.buf, dotcrlf) {
148 r.buf = nil
149 r.err = io.EOF
150 if r.badcrlf {
151 r.err = ErrCRLF
152 }
153 break
154 } else if r.buf[0] == '.' {
155 // Reject "\r\n.\n".
156 if len(r.buf) >= 2 && r.buf[1] == '\n' {
157 r.badcrlf = true
158 }
159 r.buf = r.buf[1:]
160 }
161 } else if r.last == '\n' && (bytes.HasPrefix(r.buf, []byte(".\n")) || bytes.HasPrefix(r.buf, []byte(".\r\n"))) {
162 // Reject "[^\r]\n.\n" and "[^\r]\n.\r\n"
163 r.badcrlf = true
164 }
165 n := len(r.buf)
166 if n > len(p) {
167 n = len(p)
168 }
169 copy(p, r.buf[:n])
170 if n == 1 {
171 r.plast, r.last = r.last, r.buf[0]
172 } else if n > 1 {
173 r.plast, r.last = r.buf[n-2], r.buf[n-1]
174 }
175 p = p[n:]
176 r.buf = r.buf[n:]
177 wrote += n
178 }
179 }
180 return wrote, r.err
181}
182