forked from jhillyerd/enmime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
inspect.go
189 lines (176 loc) · 4.47 KB
/
inspect.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
package enmime
import (
"bufio"
"bytes"
"fmt"
"io"
"mime"
"net/textproto"
"strings"
"github.com/jhillyerd/enmime/internal/coding"
"github.com/pkg/errors"
)
var defaultHeadersList = []string{
"From",
"To",
"Sender",
"CC",
"BCC",
"Subject",
"Date",
}
// DecodeHeaders returns a limited selection of mime headers for use by user agents
// Default header list:
// "Date", "Subject", "Sender", "From", "To", "CC" and "BCC"
//
// Additional headers provided will be formatted canonically:
// h, err := enmime.DecodeHeaders(b, "content-type", "user-agent")
func DecodeHeaders(b []byte, addtlHeaders ...string) (textproto.MIMEHeader, error) {
b = ensureHeaderBoundary(b)
tr := textproto.NewReader(bufio.NewReader(bytes.NewReader(b)))
headers, err := tr.ReadMIMEHeader()
switch errors.Cause(err) {
case nil, io.EOF:
// carry on, io.EOF is expected
default:
return nil, err
}
headerList := defaultHeadersList
headerList = append(headerList, addtlHeaders...)
res := map[string][]string{}
for _, header := range headerList {
h := textproto.CanonicalMIMEHeaderKey(header)
res[h] = make([]string, 0, len(headers[h]))
for _, value := range headers[h] {
res[h] = append(res[h], rfc2047decode(value))
}
}
return res, nil
}
// ensureHeaderBoundary scans through an rfc822 document to ensure the boundary between headers and body exists
func ensureHeaderBoundary(b []byte) []byte {
slice := bytes.SplitAfter(b, []byte{'\r', '\n'})
dest := make([]byte, 0, len(b)+2)
headers := true
for _, v := range slice {
if headers && (bytes.Contains(v, []byte{':'}) || bytes.HasPrefix(v, []byte{' '}) || bytes.HasPrefix(v, []byte{'\t'})) {
dest = append(dest, v...)
continue
}
if headers {
headers = false
if !bytes.Equal(v, []byte{'\r', '\n'}) {
dest = append(dest, append([]byte{'\r', '\n'}, v...)...)
continue
}
}
dest = append(dest, v...)
}
return dest
}
// rfc2047decode returns a decoded string if the input uses RFC2047 encoding, otherwise it will return the input.
// RFC2047 Example:
// `=?UTF-8?B?bmFtZT0iw7DCn8KUwoo=?=`
func rfc2047decode(s string) string {
s = strings.Map(func(r rune) rune {
if r == '\n' || r == '\r' {
return ' '
}
return r
}, s)
var err error
decoded := false
for {
s, err = rfc2047recurse(s)
switch err {
case nil:
decoded = true
continue
default:
if decoded {
keyValuePair := strings.SplitAfter(s, "=")
if len(keyValuePair) < 2 {
return s
}
// Add quotes as needed
if !strings.HasPrefix(keyValuePair[1], "\"") {
keyValuePair[1] = fmt.Sprintf("\"%s", keyValuePair[1])
}
if !strings.HasSuffix(keyValuePair[1], "\"") {
keyValuePair[1] = fmt.Sprintf("%s\"", keyValuePair[1])
}
return strings.Join(keyValuePair, "")
}
return s
}
}
}
// rfc2047recurse is called for if the value contains content encoded in RFC2047 format and decodes it.
// RFC2047 Example:
// `=?UTF-8?B?bmFtZT0iw7DCn8KUwoo=?=`
func rfc2047recurse(s string) (string, error) {
us := strings.ToUpper(s)
if !strings.Contains(us, "?Q?") && !strings.Contains(us, "?B?") {
return s, io.EOF
}
val, err := decodeHeaderWithError(s)
if err != nil {
return val, err
}
if val == s {
val, err = decodeHeaderWithError(fixRFC2047String(val))
if err != nil {
return val, err
}
if val == s {
return val, io.EOF
}
}
return val, nil
}
// decodeHeaderWithError decodes a single line (per RFC 2047) using Golang's mime.WordDecoder
func decodeHeaderWithError(input string) (string, error) {
dec := new(mime.WordDecoder)
dec.CharsetReader = coding.NewCharsetReader
header, err := dec.DecodeHeader(input)
if err != nil {
return input, err
}
return header, nil
}
// fixRFC2047String removes the following characters from charset and encoding segments of an RFC2047 string:
// '\n', '\r' and ' '
func fixRFC2047String(s string) string {
inString := false
isWithinTerminatingEqualSigns := false
questionMarkCount := 0
sb := &strings.Builder{}
for _, v := range s {
switch v {
case '=':
if questionMarkCount == 3 {
inString = false
} else {
isWithinTerminatingEqualSigns = true
}
sb.WriteRune(v)
case '?':
if isWithinTerminatingEqualSigns {
inString = true
} else {
questionMarkCount++
}
isWithinTerminatingEqualSigns = false
sb.WriteRune(v)
case '\n', '\r', ' ':
if !inString {
sb.WriteRune(v)
}
isWithinTerminatingEqualSigns = false
default:
isWithinTerminatingEqualSigns = false
sb.WriteRune(v)
}
}
return sb.String()
}