Debian Codegraph @

part.go

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 package enmime
2
3 import (
4 "bufio"
5 "bytes"
6 "encoding/base64"
7 "io"
8 "io/ioutil"
9 "mime/quotedprintable"
10 "net/textproto"
11 "strconv"
12 "strings"
13 "time"
14
15 "github.com/gogs/chardet"
16 "github.com/jhillyerd/enmime/internal/coding"
17 "github.com/jhillyerd/enmime/mediatype"
18 "github.com/pkg/errors"
19 )
20
21 const (
22 minCharsetConfidence = 85
23 minCharsetRuneLength = 100
24 )
25
26 // Part represents a node in the MIME multipart tree. The Content-Type, Disposition and File Name
27 // are parsed out of the header for easier access.
28 type Part struct {
29 PartID string // PartID labels this parts position within the tree.
30 Parent *Part // Parent of this part (can be nil.)
31 FirstChild *Part // FirstChild is the top most child of this part.
32 NextSibling *Part // NextSibling of this part.
33 Header textproto.MIMEHeader // Header for this Part.
34
35 Boundary string // Boundary marker used within this part.
36 ContentID string // ContentID header for cid URL scheme.
37 ContentType string // ContentType header without parameters.
38 ContentTypeParams map[string]string // Params, added to ContentType header.
39 Disposition string // Content-Disposition header without parameters.
40 FileName string // The file-name from disposition or type header.
41 FileModDate time.Time // The modification date of the file.
42 Charset string // The content charset encoding, may differ from charset in header.
43 OrigCharset string // The original content charset when a different charset was detected.
44
45 Errors []*Error // Errors encountered while parsing this part.
46 Content []byte // Content after decoding, UTF-8 conversion if applicable.
47 Epilogue []byte // Epilogue contains data following the closing boundary marker.
48 }
49
50 // NewPart creates a new Part object.
51 func NewPart(contentType string) *Part {
52 return &Part{
53 Header: make(textproto.MIMEHeader),
54 ContentType: contentType,
55 ContentTypeParams: make(map[string]string),
56 }
57 }
58
59 // AddChild adds a child part to either FirstChild or the end of the children NextSibling chain.
60 // The child may have siblings and children attached. This method will set the Parent field on
61 // child and all its siblings. Safe to call on nil.
62 func (p *Part) AddChild(child *Part) {
63 if p == child {
64 // Prevent paradox.
65 return
66 }
67 if p != nil {
68 if p.FirstChild == nil {
69 // Make it the first child.
70 p.FirstChild = child
71 } else {
72 // Append to sibling chain.
73 current := p.FirstChild
74 for current.NextSibling != nil {
75 current = current.NextSibling
76 }
77 if current == child {
78 // Prevent infinite loop.
79 return
80 }
81 current.NextSibling = child
82 }
83 }
84 // Update all new first-level children Parent pointers.
85 for c := child; c != nil; c = c.NextSibling {
86 if c == c.NextSibling {
87 // Prevent infinite loop.
88 return
89 }
90 c.Parent = p
91 }
92 }
93
94 // TextContent indicates whether the content is text based on its content type. This value
95 // determines what content transfer encoding scheme to use.
96 func (p *Part) TextContent() bool {
97 if p.ContentType == "" {
98 // RFC 2045: no CT is equivalent to "text/plain; charset=us-ascii"
99 return true
100 }
101 return strings.HasPrefix(p.ContentType, "text/") ||
102 strings.HasPrefix(p.ContentType, ctMultipartPrefix)
103 }
104
105 // setupHeaders reads the header, then populates the MIME header values for this Part.
106 func (p *Part) setupHeaders(r *bufio.Reader, defaultContentType string) error {
107 header, err := readHeader(r, p)
108 if err != nil {
109 return err
110 }
111 p.Header = header
112 ctype := header.Get(hnContentType)
113 if ctype == "" {
114 if defaultContentType == "" {
115 p.addWarning(ErrorMissingContentType, "MIME parts should have a Content-Type header")
116 return nil
117 }
118 ctype = defaultContentType
119 }
120 // Parse Content-Type header.
121 mtype, mparams, minvalidParams, err := mediatype.Parse(ctype)
122 if err != nil {
123 return err
124 }
125 for i := range minvalidParams {
126 p.addWarning(
127 ErrorMalformedHeader,
128 "Content-Type header has malformed parameter %q",
129 minvalidParams[i])
130 }
131 p.ContentType = mtype
132 // Set disposition, filename, charset if available.
133 p.setupContentHeaders(mparams)
134 p.Boundary = mparams[hpBoundary]
135 p.ContentID = coding.FromIDHeader(header.Get(hnContentID))
136 return nil
137 }
138
139 // setupContentHeaders uses Content-Type media params and Content-Disposition headers to populate
140 // the disposition, filename, and charset fields.
141 func (p *Part) setupContentHeaders(mediaParams map[string]string) {
142 // Determine content disposition, filename, character set.
143 disposition, dparams, _, err := mediatype.Parse(p.Header.Get(hnContentDisposition))
144 if err == nil {
145 // Disposition is optional
146 p.Disposition = disposition
147 p.FileName = coding.DecodeExtHeader(dparams[hpFilename])
148 }
149 if p.FileName == "" && mediaParams[hpName] != "" {
150 p.FileName = coding.DecodeExtHeader(mediaParams[hpName])
151 }
152 if p.FileName == "" && mediaParams[hpFile] != "" {
153 p.FileName = coding.DecodeExtHeader(mediaParams[hpFile])
154 }
155 if p.Charset == "" {
156 p.Charset = mediaParams[hpCharset]
157 }
158 if p.FileModDate.IsZero() {
159 p.FileModDate, _ = time.Parse(time.RFC822, mediaParams[hpModDate])
160 }
161 }
162
163 // convertFromDetectedCharset attempts to detect the character set for the given part, and returns
164 // an io.Reader that will convert from that charset to UTF-8. If the charset cannot be detected,
165 // this method adds a warning to the part and automatically falls back to using
166 // `convertFromStatedCharset` and returns the reader from that method.
167 func (p *Part) convertFromDetectedCharset(r io.Reader) (io.Reader, error) {
168 // Attempt to detect character set from part content.
169 var cd *chardet.Detector
170 switch p.ContentType {
171 case "text/html":
172 cd = chardet.NewHtmlDetector()
173 default:
174 cd = chardet.NewTextDetector()
175 }
176
177 buf, err := ioutil.ReadAll(r)
178 if err != nil {
179 return nil, errors.WithStack(err)
180 }
181
182 cs, err := cd.DetectBest(buf)
183 switch err {
184 case nil:
185 // Carry on
186 default:
187 p.addWarning(ErrorCharsetDeclaration, "charset could not be detected: %v", err)
188 }
189
190 // Restore r.
191 r = bytes.NewReader(buf)
192
193 if cs == nil || cs.Confidence < minCharsetConfidence || len(bytes.Runes(buf)) < minCharsetRuneLength {
194 // Low confidence or not enough characters, use declared character set.
195 return p.convertFromStatedCharset(r), nil
196 }
197
198 // Confidence exceeded our threshold, use detected character set.
199 if p.Charset != "" && !strings.EqualFold(cs.Charset, p.Charset) {
200 p.addWarning(ErrorCharsetDeclaration,
201 "declared charset %q, detected %q, confidence %d",
202 p.Charset, cs.Charset, cs.Confidence)
203 }
204
205 if reader, err := coding.NewCharsetReader(cs.Charset, r); err == nil {
206 r = reader
207 p.OrigCharset = p.Charset
208 p.Charset = cs.Charset
209 }
210
211 return r, nil
212 }
213
214 // convertFromStatedCharset returns a reader that will convert from the charset specified for the
215 // current `*Part` to UTF-8. In case of error, or an unhandled character set, a warning will be
216 // added to the `*Part` and the original io.Reader will be returned.
217 func (p *Part) convertFromStatedCharset(r io.Reader) io.Reader {
218 if p.Charset == "" {
219 // US-ASCII. Just read.
220 return r
221 }
222
223 reader, err := coding.NewCharsetReader(p.Charset, r)
224 if err != nil {
225 // Failed to get a conversion reader.
226 p.addWarning(ErrorCharsetConversion, "failed to get reader for charset %q: %v", p.Charset, err)
227 } else {
228 return reader
229 }
230
231 // Try to parse charset again here to see if we can salvage some badly formed
232 // ones like charset="charset=utf-8".
233 charsetp := strings.Split(p.Charset, "=")
234 if strings.EqualFold(charsetp[0], "charset") && len(charsetp) > 1 ||
235 strings.EqualFold(charsetp[0], "iso") && len(charsetp) > 1 {
236 p.Charset = charsetp[1]
237 reader, err = coding.NewCharsetReader(p.Charset, r)
238 if err != nil {
239 // Failed to get a conversion reader.
240 p.addWarning(ErrorCharsetConversion, "failed to get reader for charset %q: %v", p.Charset, err)
241 } else {
242 return reader
243 }
244 }
245
246 return r
247 }
248
249 // decodeContent performs transport decoding (base64, quoted-printable) and charset decoding,
250 // placing the result into Part.Content. IO errors will be returned immediately; other errors
251 // and warnings will be added to Part.Errors.
252 func (p *Part) decodeContent(r io.Reader) error {
253 // contentReader will point to the end of the content decoding pipeline.
254 contentReader := r
255 // b64cleaner aggregates errors, must maintain a reference to it to get them later.
256 var b64cleaner *coding.Base64Cleaner
257 // Build content decoding reader.
258 encoding := p.Header.Get(hnContentEncoding)
259 validEncoding := true
260 switch strings.ToLower(encoding) {
261 case cteQuotedPrintable:
262 contentReader = coding.NewQPCleaner(contentReader)
263 contentReader = quotedprintable.NewReader(contentReader)
264 case cteBase64:
265 b64cleaner = coding.NewBase64Cleaner(contentReader)
266 contentReader = base64.NewDecoder(base64.RawStdEncoding, b64cleaner)
267 case cte8Bit, cte7Bit, cteBinary, "":
268 // No decoding required.
269 default:
270 // Unknown encoding.
271 validEncoding = false
272 p.addWarning(
273 ErrorContentEncoding,
274 "Unrecognized Content-Transfer-Encoding type %q",
275 encoding)
276 }
277 // Build charset decoding reader.
278 if validEncoding && strings.HasPrefix(p.ContentType, "text/") {
279 var err error
280 contentReader, err = p.convertFromDetectedCharset(contentReader)
281 if err != nil {
282 return p.base64CorruptInputCheck(err)
283 }
284 }
285 // Decode and store content.
286 content, err := ioutil.ReadAll(contentReader)
287 if err != nil {
288 return p.base64CorruptInputCheck(errors.WithStack(err))
289 }
290 p.Content = content
291 // Collect base64 errors.
292 if b64cleaner != nil {
293 for _, err := range b64cleaner.Errors {
294 p.addWarning(ErrorMalformedBase64, err.Error())
295 }
296 }
297 // Set empty content-type error.
298 if p.ContentType == "" {
299 p.addWarning(
300 ErrorMissingContentType, "content-type is empty for part id: %s", p.PartID)
301 }
302 return nil
303 }
304
305 // base64CorruptInputCheck will avoid fatal failure on corrupt base64 input
306 //
307 // This is a switch on errors.Cause(err).(type) for base64.CorruptInputError
308 func (p *Part) base64CorruptInputCheck(err error) error {
309 switch errors.Cause(err).(type) {
310 case base64.CorruptInputError:
311 p.Content = nil
312 p.Errors = append(p.Errors, &Error{
313 Name: ErrorMalformedBase64,
314 Detail: err.Error(),
315 Severe: true,
316 })
317 return nil
318 default:
319 return err
320 }
321 }
322
323 // Clone returns a clone of the current Part.
324 func (p *Part) Clone(parent *Part) *Part {
325 if p == nil {
326 return nil
327 }
328
329 newPart := &Part{
330 PartID: p.PartID,
331 Header: p.Header,
332 Parent: parent,
333 Boundary: p.Boundary,
334 ContentID: p.ContentID,
335 ContentType: p.ContentType,
336 Disposition: p.Disposition,
337 FileName: p.FileName,
338 Charset: p.Charset,
339 Errors: p.Errors,
340 Content: p.Content,
341 Epilogue: p.Epilogue,
342 }
343 newPart.FirstChild = p.FirstChild.Clone(newPart)
344 newPart.NextSibling = p.NextSibling.Clone(parent)
345
346 return newPart
347 }
348
349 // ReadParts reads a MIME document from the provided reader and parses it into tree of Part objects.
350 func ReadParts(r io.Reader) (*Part, error) {
351 br := bufio.NewReader(r)
352 root := &Part{PartID: "0"}
353 // Read header; top-level default CT is text/plain us-ascii according to RFC 822.
354 err := root.setupHeaders(br, `text/plain; charset="us-ascii"`)
355 if err != nil {
356 return nil, err
357 }
358 if strings.HasPrefix(root.ContentType, ctMultipartPrefix) {
359 // Content is multipart, parse it.
360 err = parseParts(root, br)
361 if err != nil {
362 return nil, err
363 }
364 } else {
365 // Content is text or data, decode it.
366 if err := root.decodeContent(br); err != nil {
367 return nil, err
368 }
369 }
370 return root, nil
371 }
372
373 // parseParts recursively parses a MIME multipart document and sets each Parts PartID.
374 func parseParts(parent *Part, reader *bufio.Reader) error {
375 firstRecursion := parent.Parent == nil
376 // Loop over MIME boundaries.
377 br := newBoundaryReader(reader, parent.Boundary)
378 for indexPartID := 1; true; indexPartID++ {
379 next, err := br.Next()
380 if err != nil && errors.Cause(err) != io.EOF {
381 return err
382 }
383 if br.unbounded {
384 parent.addWarning(ErrorMissingBoundary, "Boundary %q was not closed correctly",
385 parent.Boundary)
386 }
387 if !next {
388 break
389 }
390 p := &Part{}
391 // Set this Part's PartID, indicating its position within the MIME Part tree.
392 if firstRecursion {
393 p.PartID = strconv.Itoa(indexPartID)
394 } else {
395 p.PartID = parent.PartID + "." + strconv.Itoa(indexPartID)
396 }
397 // Look for part header.
398 bbr := bufio.NewReader(br)
399 if err = p.setupHeaders(bbr, ""); err != nil {
400 return err
401 }
402 // Insert this Part into the MIME tree.
403 parent.AddChild(p)
404 if p.Boundary == "" {
405 // Content is text or data, decode it.
406 if err = p.decodeContent(bbr); err != nil {
407 return err
408 }
409 } else {
410 // Content is another multipart.
411 err = parseParts(p, bbr)
412 if err != nil {
413 return err
414 }
415 }
416 }
417 // Store any content following the closing boundary marker into the epilogue.
418 epilogue, err := ioutil.ReadAll(reader)
419 if err != nil {
420 return errors.WithStack(err)
421 }
422 parent.Epilogue = epilogue
423 // If a Part is "multipart/" Content-Type, it will have .0 appended to its PartID
424 // i.e. it is the root of its MIME Part subtree.
425 if !firstRecursion {
426 parent.PartID += ".0"
427 }
428 return nil
429 }