| 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 |
line: |
| 101 |
for { |
| 102 |
// Pull out each line of the headers as a temporary slice s |
| 103 |
s, err := tp.ReadLineBytes() |
| 104 |
if err != nil { |
| 105 |
buf.Write([]byte{'\r', '\n'}) |
| 106 |
break |
| 107 |
} |
| 108 |
|
| 109 |
firstColon := bytes.IndexByte(s, ':') |
| 110 |
firstSpace := bytes.IndexAny(s, " \t\n\r") |
| 111 |
if firstSpace == 0 { |
| 112 |
// Starts with space: continuation |
| 113 |
buf.WriteByte(' ') |
| 114 |
buf.Write(textproto.TrimBytes(s)) |
| 115 |
continue |
| 116 |
} |
| 117 |
if firstColon == 0 { |
| 118 |
// Can't parse line starting with colon: skip |
| 119 |
p.addError(ErrorMalformedHeader, "Header line %q started with a colon", s) |
| 120 |
continue |
| 121 |
} |
| 122 |
if firstColon > 0 { |
| 123 |
// Behavior change in net/textproto package in Golang 1.12.10 and 1.13.1: |
| 124 |
// A space preceding the first colon in a header line is no longer handled |
| 125 |
// automatically due to CVE-2019-16276 which takes advantage of this |
| 126 |
// particular violation of RFC-7230 to exploit HTTP/1.1 |
| 127 |
if bytes.Contains(s[:firstColon+1], []byte{' ', ':'}) { |
| 128 |
s = bytes.Replace(s, []byte{' ', ':'}, []byte{':'}, 1) |
| •129 |
firstColon = bytes.IndexByte(s, ':') |
| 130 |
} |
| 131 |
|
| 132 |
// Behavior change in net/textproto package in Golang 1.20: invalid characters |
| 133 |
// in header keys are no longer allowed; https://github.com/golang/go/issues/53188 |
| 134 |
for _, c := range s[:firstColon] { |
| 135 |
if c != ' ' && !validHeaderFieldByte(c) { |
| 136 |
p.addError( |
| 137 |
ErrorMalformedHeader, "Header name %q contains invalid character %q", s, c) |
| 138 |
continue line |
| 139 |
} |
| 140 |
} |
| 141 |
|
| 142 |
// Contains a colon, treat as a new header line |
| 143 |
if !firstHeader { |
| 144 |
// New Header line, end the previous |
| 145 |
buf.Write([]byte{'\r', '\n'}) |
| 146 |
} |
| 147 |
|
| 148 |
s = textproto.TrimBytes(s) |
| 149 |
buf.Write(s) |
| 150 |
firstHeader = false |
| 151 |
} else { |
| 152 |
// No colon: potential non-indented continuation |
| 153 |
if len(s) > 0 { |
| 154 |
// Attempt to detect and repair a non-indented continuation of previous line |
| 155 |
buf.WriteByte(' ') |
| 156 |
buf.Write(s) |
| 157 |
p.addWarning(ErrorMalformedHeader, "Continued line %q was not indented", s) |
| 158 |
} else { |
| 159 |
// Empty line, finish header parsing |
| 160 |
buf.Write([]byte{'\r', '\n'}) |
| 161 |
break |
| 162 |
} |
| 163 |
} |
| 164 |
} |
| 165 |
|
| 166 |
buf.Write([]byte{'\r', '\n'}) |
| 167 |
tr := textproto.NewReader(bufio.NewReader(buf)) |
| 168 |
header, err := tr.ReadMIMEHeader() |
| 169 |
return header, errors.WithStack(err) |
| 170 |
} |
| 171 |
|
| 172 |
// decodeToUTF8Base64Header decodes a MIME header per RFC 2047, reencoding to =?utf-8b? |
| 173 |
func decodeToUTF8Base64Header(input string) string { |
| 174 |
if !strings.Contains(input, "=?") { |
| 175 |
// Don't scan if there is nothing to do here |
| 176 |
return input |
| 177 |
} |
| 178 |
|
| 179 |
// The standard lib performs an incremental inspection of this string, where the |
| 180 |
// "skipSpace" method only strings.trimLeft for spaces and tabs. Here we have a |
| 181 |
// hard dependency on space existing and not on next expected rune. |
| 182 |
// |
| 183 |
// For resolving #112 with the least change, I will implement the |
| 184 |
// "quoted display-name" detector, which will resolve the case specific |
| 185 |
// issue stated in #112, but only in the case of a quoted display-name |
| 186 |
// followed, without whitespace, by addr-spec. |
| 187 |
tokens := strings.FieldsFunc(quotedDisplayName(input), whiteSpaceRune) |
| 188 |
output := make([]string, len(tokens)) |
| 189 |
|
| 190 |
for i, token := range tokens { |
| 191 |
if len(token) > 4 && strings.Contains(token, "=?") { |
| 192 |
// Stash parenthesis, they should not be encoded |
| 193 |
prefix := "" |
| 194 |
suffix := "" |
| 195 |
if token[0] == '(' { |
| 196 |
prefix = "(" |
| 197 |
token = token[1:] |
| 198 |
} |
| 199 |
if token[len(token)-1] == ')' { |
| 200 |
suffix = ")" |
| 201 |
token = token[:len(token)-1] |
| 202 |
} |
| 203 |
// Base64 encode token |
| 204 |
output[i] = prefix + |
| 205 |
mime.BEncoding.Encode("UTF-8", coding.DecodeExtHeader(token)) + |
| 206 |
suffix |
| 207 |
} else { |
| 208 |
output[i] = token |
| 209 |
} |
| 210 |
} |
| 211 |
|
| 212 |
// Return space separated tokens |
| 213 |
return strings.Join(output, " ") |
| 214 |
} |
| 215 |
|
| 216 |
func quotedDisplayName(s string) string { |
| 217 |
if !strings.HasPrefix(s, "\"") { |
| 218 |
return s |
| 219 |
} |
| 220 |
idx := strings.LastIndex(s, "\"") |
| 221 |
return fmt.Sprintf("%s %s", s[:idx+1], s[idx+1:]) |
| 222 |
} |
| 223 |
|
| 224 |
// Detects a RFC-822 linear-white-space, passed to strings.FieldsFunc. |
| 225 |
func whiteSpaceRune(r rune) bool { |
| 226 |
return r == ' ' || r == '\t' || r == '\r' || r == '\n' |
| 227 |
} |
| •228 |
|
| 229 |
// Mirror of func in net/textproto/reader.go; from go 1.20.0-rc.2 |
| 230 |
func validHeaderFieldByte(c byte) bool { |
| 231 |
// mask is a 128-bit bitmap with 1s for allowed bytes, |
| 232 |
// so that the byte c can be tested with a shift and an and. |
| 233 |
// If c >= 128, then 1<<c and 1<<(c-64) will both be zero, |
| 234 |
// and this function will return false. |
| 235 |
const mask = 0 | |
| 236 |
(1<<(10)-1)<<'0' | |
| 237 |
(1<<(26)-1)<<'a' | |
| 238 |
(1<<(26)-1)<<'A' | |
| 239 |
1<<'!' | |
| 240 |
1<<'#' | |
| 241 |
1<<'$' | |
| 242 |
1<<'%' | |
| 243 |
1<<'&' | |
| 244 |
1<<'\'' | |
| 245 |
1<<'*' | |
| 246 |
1<<'+' | |
| 247 |
1<<'-' | |
| 248 |
1<<'.' | |
| 249 |
1<<'^' | |
| 250 |
1<<'_' | |
| 251 |
1<<'`' | |
| 252 |
1<<'|' | |
| 253 |
1<<'~' |
| 254 |
return ((uint64(1)<<c)&(mask&(1<<64-1)) | |
| 255 |
(uint64(1)<<(c-64))&(mask>>64)) != 0 |
| 256 |
} |