Debian Codegraph @

header.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 "fmt"
7 "mime"
8 "net/textproto"
9 "strings"
10
11 "github.com/jhillyerd/enmime/internal/coding"
12 "github.com/jhillyerd/enmime/mediatype"
13 "github.com/pkg/errors"
14 )
15
16 const (
17 // Standard MIME content dispositions
18 cdAttachment = "attachment"
19 cdInline = "inline"
20
21 // Standard MIME content types
22 ctAppPrefix = "application/"
23 ctAppOctetStream = "application/octet-stream"
24 ctMultipartAltern = "multipart/alternative"
25 ctMultipartMixed = "multipart/mixed"
26 ctMultipartPrefix = "multipart/"
27 ctMultipartRelated = "multipart/related"
28 ctTextPrefix = "text/"
29 ctTextPlain = "text/plain"
30 ctTextHTML = "text/html"
31
32 // Standard Transfer encodings
33 cte7Bit = "7bit"
34 cte8Bit = "8bit"
35 cteBase64 = "base64"
36 cteBinary = "binary"
37 cteQuotedPrintable = "quoted-printable"
38
39 // Standard MIME header names
40 hnContentDisposition = "Content-Disposition"
41 hnContentEncoding = "Content-Transfer-Encoding"
42 hnContentID = "Content-ID"
43 hnContentType = "Content-Type"
44 hnMIMEVersion = "MIME-Version"
45
46 // Standard MIME header parameters
47 hpBoundary = "boundary"
48 hpCharset = "charset"
49 hpFile = "file"
50 hpFilename = "filename"
51 hpName = "name"
52 hpModDate = "modification-date"
53
54 utf8 = "utf-8"
55 )
56
57 // AddressHeaders is the set of SMTP headers that contain email addresses, used by
58 // Envelope.AddressList(). Key characters must be all lowercase.
59 var AddressHeaders = map[string]bool{
60 "bcc": true,
61 "cc": true,
62 "delivered-to": true,
63 "from": true,
64 "reply-to": true,
65 "to": true,
66 "sender": true,
67 "resent-bcc": true,
68 "resent-cc": true,
69 "resent-from": true,
70 "resent-reply-to": true,
71 "resent-to": true,
72 "resent-sender": true,
73 }
74
75 // Terminology from RFC 2047:
76 // encoded-word: the entire =?charset?encoding?encoded-text?= string
77 // charset: the character set portion of the encoded word
78 // encoding: the character encoding type used for the encoded-text
79 // encoded-text: the text we are decoding
80
81 // ParseMediaType is a more tolerant implementation of Go's mime.ParseMediaType function.
82 //
83 // Tolerances accounted for:
84 // * Missing ';' between content-type and media parameters
85 // * Repeating media parameters
86 // * Unquoted values in media parameters containing 'tspecials' characters
87 func ParseMediaType(ctype string) (mtype string, params map[string]string, invalidParams []string,
88 err error) {
89 // Export of internal function.
90 return mediatype.Parse(ctype)
91 }
92
93 // readHeader reads a block of SMTP or MIME headers and returns a textproto.MIMEHeader.
94 // Header parse warnings & errors will be added to p.Errors, io errors will be returned directly.
95 func readHeader(r *bufio.Reader, p *Part) (textproto.MIMEHeader, error) {
96 // buf holds the massaged output for textproto.Reader.ReadMIMEHeader()
97 buf := &bytes.Buffer{}
98 tp := textproto.NewReader(r)
99 firstHeader := true
100 for {
101 // Pull out each line of the headers as a temporary slice s
102 s, err := tp.ReadLineBytes()
103 if err != nil {
104 buf.Write([]byte{'\r', '\n'})
105 break
106 }
107
108 firstColon := bytes.IndexByte(s, ':')
109 firstSpace := bytes.IndexAny(s, " \t\n\r")
110 if firstSpace == 0 {
111 // Starts with space: continuation
112 buf.WriteByte(' ')
113 buf.Write(textproto.TrimBytes(s))
114 continue
115 }
116 if firstColon == 0 {
117 // Can't parse line starting with colon: skip
118 p.addError(ErrorMalformedHeader, "Header line %q started with a colon", s)
119 continue
120 }
121 if firstColon > 0 {
122 // Contains a colon, treat as a new header line
123 if !firstHeader {
124 // New Header line, end the previous
125 buf.Write([]byte{'\r', '\n'})
126 }
127
128 // Behavior change in net/textproto package in Golang 1.12.10 and 1.13.1:
129 // A space preceding the first colon in a header line is no longer handled
130 // automatically due to CVE-2019-16276 which takes advantage of this
131 // particular violation of RFC-7230 to exploit HTTP/1.1
132 if bytes.Contains(s[:firstColon+1], []byte{' ', ':'}) {
133 s = bytes.Replace(s, []byte{' ', ':'}, []byte{':'}, 1)
134 }
135
136 s = textproto.TrimBytes(s)
137 buf.Write(s)
138 firstHeader = false
139 } else {
140 // No colon: potential non-indented continuation
141 if len(s) > 0 {
142 // Attempt to detect and repair a non-indented continuation of previous line
143 buf.WriteByte(' ')
144 buf.Write(s)
145 p.addWarning(ErrorMalformedHeader, "Continued line %q was not indented", s)
146 } else {
147 // Empty line, finish header parsing
148 buf.Write([]byte{'\r', '\n'})
149 break
150 }
151 }
152 }
153
154 buf.Write([]byte{'\r', '\n'})
155 tr := textproto.NewReader(bufio.NewReader(buf))
156 header, err := tr.ReadMIMEHeader()
157 return header, errors.WithStack(err)
158 }
159
160 // decodeToUTF8Base64Header decodes a MIME header per RFC 2047, reencoding to =?utf-8b?
161 func decodeToUTF8Base64Header(input string) string {
162 if !strings.Contains(input, "=?") {
163 // Don't scan if there is nothing to do here
164 return input
165 }
166
167 // The standard lib performs an incremental inspection of this string, where the
168 // "skipSpace" method only strings.trimLeft for spaces and tabs. Here we have a
169 // hard dependency on space existing and not on next expected rune.
170 //
171 // For resolving #112 with the least change, I will implement the
172 // "quoted display-name" detector, which will resolve the case specific
173 // issue stated in #112, but only in the case of a quoted display-name
174 // followed, without whitespace, by addr-spec.
175 tokens := strings.FieldsFunc(quotedDisplayName(input), whiteSpaceRune)
176 output := make([]string, len(tokens))
177
178 for i, token := range tokens {
179 if len(token) > 4 && strings.Contains(token, "=?") {
180 // Stash parenthesis, they should not be encoded
181 prefix := ""
182 suffix := ""
183 if token[0] == '(' {
184 prefix = "("
185 token = token[1:]
186 }
187 if token[len(token)-1] == ')' {
188 suffix = ")"
189 token = token[:len(token)-1]
190 }
191 // Base64 encode token
192 output[i] = prefix +
193 mime.BEncoding.Encode("UTF-8", coding.DecodeExtHeader(token)) +
194 suffix
195 } else {
196 output[i] = token
197 }
198 }
199
200 // Return space separated tokens
201 return strings.Join(output, " ")
202 }
203
204 func quotedDisplayName(s string) string {
205 if !strings.HasPrefix(s, "\"") {
206 return s
207 }
208 idx := strings.LastIndex(s, "\"")
209 return fmt.Sprintf("%s %s", s[:idx+1], s[idx+1:])
210 }
211
212 // Detects a RFC-822 linear-white-space, passed to strings.FieldsFunc.
213 func whiteSpaceRune(r rune) bool {
214 return r == ' ' || r == '\t' || r == '\r' || r == '\n'
215 }