forked from jhillyerd/enmime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpart.go
297 lines (272 loc) · 8.53 KB
/
part.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
package enmime
import (
"bufio"
"bytes"
"encoding/base64"
"fmt"
"io"
"mime"
"mime/quotedprintable"
"net/textproto"
"strings"
)
// Part represents a node in the MIME multipart tree. The Content-Type, Disposition and File Name
// are parsed out of the header for easier access.
type Part struct {
Header textproto.MIMEHeader // Header for this Part
Parent *Part // Parent of this part (can be nil)
FirstChild *Part // FirstChild is the top most child of this part
NextSibling *Part // NextSibling of this part
ContentType string // ContentType header without parameters
Disposition string // Content-Disposition header without parameters
FileName string // The file-name from disposition or type header
Charset string // The content charset encoding label
Errors []Error // Errors encountered while parsing this part
boundary string // Boundary marker used within this part
rawReader io.Reader // The raw Part content, no decoding or charset conversion
decodedReader io.Reader // The content decoded from quoted-printable or base64
utf8Reader io.Reader // The decoded content converted to UTF-8
}
// NewPart creates a new Part object. It does not update the parents FirstChild attribute.
func NewPart(parent *Part, contentType string) *Part {
return &Part{Parent: parent, ContentType: contentType}
}
// Read returns the decoded & UTF-8 converted content; implements io.Reader.
func (p *Part) Read(b []byte) (n int, err error) {
if p.utf8Reader == nil {
return 0, io.EOF
}
return p.utf8Reader.Read(b)
}
// setupContentHeaders uses Content-Type media params and Content-Disposition headers to populate
// the disposition, filename, and charset fields.
func (p *Part) setupContentHeaders(mediaParams map[string]string) {
// Determine content disposition, filename, character set
disposition, dparams, err := parseMediaType(p.Header.Get(hnContentDisposition))
if err == nil {
// Disposition is optional
p.Disposition = disposition
p.FileName = decodeHeader(dparams[hpFilename])
}
if p.FileName == "" && mediaParams[hpName] != "" {
p.FileName = decodeHeader(mediaParams[hpName])
}
if p.FileName == "" && mediaParams[hpFile] != "" {
p.FileName = decodeHeader(mediaParams[hpFile])
}
if p.Charset == "" {
p.Charset = mediaParams[hpCharset]
}
}
// buildContentReaders sets up the decodedReader and utf8Reader based on the Part headers. If no
// translation is required at a particular stage, the reader will be the same as its predecessor.
// If the content encoding type is not recognized, no effort will be made to do character set
// conversion.
func (p *Part) buildContentReaders(r io.Reader) error {
// Read raw content into buffer
buf := new(bytes.Buffer)
if _, err := buf.ReadFrom(r); err != nil {
return err
}
var contentReader io.Reader = buf
valid := true
// Raw content reader
p.rawReader = contentReader
// Build content decoding reader
encoding := p.Header.Get(hnContentEncoding)
switch strings.ToLower(encoding) {
case "quoted-printable":
contentReader = newQPCleaner(contentReader)
contentReader = quotedprintable.NewReader(contentReader)
case "base64":
contentReader = newBase64Cleaner(contentReader)
contentReader = base64.NewDecoder(base64.StdEncoding, contentReader)
case "8bit", "7bit", "binary", "":
// No decoding required
default:
// Unknown encoding
valid = false
p.addWarning(
errorContentEncoding,
"Unrecognized Content-Transfer-Encoding type %q",
encoding)
}
p.decodedReader = contentReader
if valid {
// decodedReader is good; build character set conversion reader
if p.Charset != "" {
if reader, err := newCharsetReader(p.Charset, contentReader); err == nil {
contentReader = reader
} else {
// Try to parse charset again here to see if we can salvage some badly formed ones
// like charset="charset=utf-8"
charsetp := strings.Split(p.Charset, "=")
if strings.ToLower(charsetp[0]) == "charset" && len(charsetp) > 1 {
p.Charset = charsetp[1]
if reader, err := newCharsetReader(p.Charset, contentReader); err == nil {
contentReader = reader
} else {
// Failed to get a conversion reader
p.addWarning(errorCharsetConversion, err.Error())
}
} else {
// Failed to get a conversion reader
p.addWarning(errorCharsetConversion, err.Error())
}
}
}
}
p.utf8Reader = contentReader
return nil
}
// ReadParts reads a MIME document from the provided reader and parses it into tree of Part objects.
func ReadParts(r io.Reader) (*Part, error) {
br := bufio.NewReader(r)
root := &Part{}
// Read header
header, err := readHeader(br, root)
if err != nil {
return nil, err
}
root.Header = header
// Content-Type
contentType := header.Get(hnContentType)
if contentType == "" {
root.addWarning(
errorMissingContentType,
"MIME parts should have a Content-Type header")
}
mediatype, params, err := parseMediaType(header.Get(hnContentType))
if contentType != "" && err != nil {
return nil, err
}
root.ContentType = mediatype
root.Charset = params[hpCharset]
if strings.HasPrefix(mediatype, ctMultipartPrefix) {
// Content is multipart, parse it
boundary := params[hpBoundary]
err = parseParts(root, br, boundary)
if err != nil {
return nil, err
}
} else {
// Content is text or data, build content reader pipeline
if err := root.buildContentReaders(br); err != nil {
return nil, err
}
}
return root, nil
}
func parseMediaType(ctype string) (string, map[string]string, error) {
// Parse Content-Type header
mtype, mparams, err := mime.ParseMediaType(ctype)
if err != nil {
// Small hack to remove harmless charset duplicate params
mctype := parseBadContentType(ctype, ";")
mtype, mparams, err = mime.ParseMediaType(mctype)
if err != nil {
// Some badly formed content-types forget to send a ; between fields
mctype := parseBadContentType(ctype, " ")
if strings.Contains(mctype, `name=""`) {
mctype = strings.Replace(mctype, `name=""`, `name=" "`, -1)
}
mtype, mparams, err = mime.ParseMediaType(mctype)
if err != nil {
return "", make(map[string]string), err
}
}
}
return mtype, mparams, err
}
func parseBadContentType(ctype, sep string) string {
cp := strings.Split(ctype, sep)
mctype := ""
for _, p := range cp {
if strings.Contains(p, "=") {
params := strings.Split(p, "=")
if !strings.Contains(mctype, params[0]+"=") {
mctype += p + ";"
}
} else {
mctype += p + ";"
}
}
return mctype
}
// parseParts recursively parses a mime multipart document.
func parseParts(parent *Part, reader *bufio.Reader, boundary string) error {
var prevSibling *Part
// Loop over MIME parts
br := newBoundaryReader(reader, boundary)
for {
next, err := br.Next()
if err != nil && err != io.EOF {
return err
}
if !next {
break
}
p := &Part{Parent: parent}
bbr := bufio.NewReader(br)
header, err := readHeader(bbr, p)
p.Header = header
if err == errEmptyHeaderBlock {
// Empty header probably means the part didn't use the correct trailing "--" syntax to
// close its boundary.
if next, err = br.Next(); err != nil {
if err == io.EOF || strings.HasSuffix(err.Error(), "EOF") {
// There are no more Parts, but the error belongs to a sibling or parent,
// because this Part doesn't actually exist.
owner := parent
if prevSibling != nil {
owner = prevSibling
}
owner.addWarning(
errorMissingBoundary,
"Boundary %q was not closed correctly",
boundary)
break
}
return fmt.Errorf("Error at boundary %v: %v", boundary, err)
}
} else if err != nil {
return err
}
ctype := header.Get(hnContentType)
if ctype == "" {
p.addWarning(
errorMissingContentType,
"MIME parts should have a Content-Type header")
} else {
// Parse Content-Type header
mtype, mparams, err := parseMediaType(ctype)
if err != nil {
return err
}
p.ContentType = mtype
// Set disposition, filename, charset if available
p.setupContentHeaders(mparams)
p.boundary = mparams[hpBoundary]
}
// Insert this Part into the MIME tree
if prevSibling != nil {
prevSibling.NextSibling = p
} else {
parent.FirstChild = p
}
prevSibling = p
if p.boundary != "" {
// Content is another multipart
err = parseParts(p, bbr, p.boundary)
if err != nil {
return err
}
} else {
// Content is text or data: build content reader pipeline
if err := p.buildContentReaders(bbr); err != nil {
return err
}
}
}
return nil
}