Debian Codegraph @

mediatype/mediatype.go

raw
1 package mediatype
2
3 import (
4 "fmt"
5 "mime"
6 "strings"
7 _utf8 "unicode/utf8"
8
9 "github.com/jhillyerd/enmime/internal/coding"
10 "github.com/jhillyerd/enmime/internal/stringutil"
11 "github.com/pkg/errors"
12 )
13
14 const (
15 // Standard MIME content types
16 ctAppPrefix = "application/"
17 ctAppOctetStream = "application/octet-stream"
18 ctMultipartAltern = "multipart/alternative"
19 ctMultipartMixed = "multipart/mixed"
20 ctMultipartPrefix = "multipart/"
21 ctMultipartRelated = "multipart/related"
22 ctTextPrefix = "text/"
23 ctTextPlain = "text/plain"
24 ctTextHTML = "text/html"
25
26 // Used as a placeholder in case of malformed Content-Type headers
27 ctPlaceholder = "x-not-a-mime-type/x-not-a-mime-type"
28 // Used as a placeholder param value in case of malformed
29 // Content-Type/Content-Disposition parameters that lack values.
30 // E.g.: Content-Type: text/html;iso-8859-1
31 pvPlaceholder = "not-a-param-value"
32
33 utf8 = "utf-8"
34 )
35
36 // Parse is a more tolerant implementation of Go's mime.ParseMediaType function.
37 //
38 // Tolerances accounted for:
39 // * Missing ';' between content-type and media parameters
40 // * Repeating media parameters
41 // * Unquoted values in media parameters containing 'tspecials' characters
42 // * Newline characters
43 func Parse(ctype string) (mtype string, params map[string]string, invalidParams []string, err error) {
44 mtype, params, err = mime.ParseMediaType(
45 fixNewlines(fixUnescapedQuotes(fixUnquotedSpecials(fixMangledMediaType(ctype, ';')))))
46 if err != nil {
47 if err.Error() == "mime: no media type" {
48 return "", nil, nil, nil
49 }
50 return "", nil, nil, errors.WithStack(err)
51 }
52
53 if mtype == ctPlaceholder {
54 mtype = ""
55 }
56 for name, value := range params {
57 if value != pvPlaceholder {
58 continue
59 }
60 invalidParams = append(invalidParams, name)
61 delete(params, name)
62 }
63
64 return mtype, params, invalidParams, err
65 }
66
67 // fixMangledMediaType is used to insert ; separators into media type strings that lack them, and
68 // remove repeated parameters.
69 func fixMangledMediaType(mtype string, sep rune) string {
70 strsep := string([]rune{sep})
71 if mtype == "" {
72 return ""
73 }
74
75 parts := stringutil.SplitQuoted(mtype, sep, '"')
76 mtype = ""
77 if strings.Contains(parts[0], "=") {
78 // A parameter pair at this position indicates we are missing a content-type.
79 parts[0] = fmt.Sprintf("%s%s %s", ctAppOctetStream, strsep, parts[0])
80 parts = strings.Split(strings.Join(parts, strsep), strsep)
81 }
82
83 for i, p := range parts {
84 switch i {
85 case 0:
86 if p == "" {
87 // The content type is completely missing. Put in a placeholder.
88 p = ctPlaceholder
89 }
90 // Check for missing token after slash.
91 if strings.HasSuffix(p, "/") {
92 switch p {
93 case ctTextPrefix:
94 p = ctTextPlain
95 case ctAppPrefix:
96 p = ctAppOctetStream
97 case ctMultipartPrefix:
98 p = ctMultipartMixed
99 default:
100 // Safe default
101 p = ctAppOctetStream
102 }
103 }
104 // Remove extra ctype parts
105 if strings.Count(p, "/") > 1 {
106 ps := strings.SplitN(p, "/", 3)
107 p = strings.Join(ps[0:2], "/")
108 }
109 default:
110 if len(p) == 0 {
111 // Ignore trailing separators.
112 continue
113 }
114
115 if len(strings.TrimSpace(p)) == 0 {
116 // Ignore empty parameters.
117 continue
118 }
119
120 if !strings.Contains(p, "=") {
121 p = p + "=" + pvPlaceholder
122 }
123
124 // RFC-2047 encoded attribute name.
125 p = coding.RFC2047Decode(p)
126
127 pair := strings.SplitAfter(p, "=")
128 if strings.Contains(mtype, strings.TrimSpace(pair[0])) {
129 // Ignore repeated parameters.
130 continue
131 }
132
133 if strings.ContainsAny(pair[0], "()<>@,;:\"\\/[]?") {
134 // Attribute is a strict token and cannot be a quoted-string. If any of the above
135 // characters are present in a token it must be quoted and is therefor an invalid
136 // attribute. Discard the pair.
137 continue
138 }
139 }
140
141 mtype += p
142
143 // Only terminate with semicolon if not the last parameter and if it doesn't already have a
144 // semicolon.
145 if i != len(parts)-1 && !strings.HasSuffix(mtype, ";") {
146 // Remove whitespace between parameter=value and ;
147 mtype = strings.TrimRight(mtype, " \t")
148 mtype += ";"
149 }
150 }
151
152 mtype = strings.TrimSuffix(mtype, ";")
153
154 return mtype
155 }
156
157 // consumeParam takes the the parameter part of a Content-Type header, returns a clean version of
158 // the first parameter (quoted as necessary), and the remainder of the parameter part of the
159 // Content-Type header.
160 //
161 // Given this this header:
162 // `Content-Type: text/calendar; charset=utf-8; method=text/calendar`
163 // `consumeParams` should be given this part:
164 // ` charset=utf-8; method=text/calendar`
165 // And returns (first pass):
166 // `consumed = "charset=utf-8;"`
167 // `rest = " method=text/calendar"`
168 // Capture the `consumed` value (to build a clean Content-Type header value) and pass the value of
169 // `rest` back to `consumeParam`. That second call will return:
170 // `consumed = " method=\"text/calendar\""`
171 // `rest = ""`
172 // Again, use the value of `consumed` to build a clean Content-Type header value. Given that `rest`
173 // is empty, all of the parameters have been consumed successfully.
174 //
175 // If `consumed` is returned empty and `rest` is not empty, then the value of `rest` does not
176 // begin with a parsable parameter. This does not necessarily indicate a problem. For example,
177 // if there is trailing whitespace, it would be returned here.
178 func consumeParam(s string) (consumed, rest string) {
179 i := strings.IndexByte(s, '=')
180 if i < 0 {
181 return "", s
182 }
183
184 // Write out parameter name.
185 param := strings.Builder{}
186 param.WriteString(s[:i+1])
187 s = s[i+1:]
188
189 value := strings.Builder{}
190 valueQuotedOriginally := false
191 valueQuoteAdded := false
192 valueQuoteNeeded := false
193 rfc2047Needed := false
194
195 var r rune
196 findValueStart:
197 for i, r = range s {
198 switch r {
199 case ' ', '\t':
200 // Do not preserve leading whitespace.
201
202 case '"':
203 valueQuotedOriginally = true
204 valueQuoteAdded = true
205 valueQuoteNeeded = true
206 param.WriteRune(r)
207
208 break findValueStart
209
210 case ';':
211 if value.Len() == 0 {
212 // Value was empty, return immediately.
213 param.WriteString(`"";`)
214 return param.String(), s[i+1:]
215 }
216
217 break findValueStart
218
219 default:
220 if r > 127 {
221 rfc2047Needed = true
222 }
223
224 valueQuotedOriginally = false
225 valueQuoteAdded = false
226 value.WriteRune(r)
227
228 break findValueStart
229 }
230 }
231
232 quoteIfUnquoted := func() {
233 if !valueQuoteNeeded {
234 if !valueQuoteAdded {
235 param.WriteByte('"')
236
237 valueQuoteAdded = true
238 }
239
240 valueQuoteNeeded = true
241 }
242 }
243
244 if len(s)-i < 1 {
245 // Parameter value starts at the end of the string, make empty
246 // quoted string to play nice with mime.ParseMediaType.
247 param.WriteString(`""`)
248 } else {
249 // The beginning of the value is not at the end of the string.
250 for _, v := range []byte{'(', ')', '<', '>', '@', ',', ':', '/', '[', ']', '?', '='} {
251 if s[0] == v {
252 quoteIfUnquoted()
253 break
254 }
255 }
256
257 _, runeLength := _utf8.DecodeRuneInString(s[i:])
258 s = s[i+runeLength:]
259 escaped := false
260
261 findValueEnd:
262 for i, r = range s {
263 if escaped {
264 value.WriteRune(r)
265 escaped = false
266 continue
267 }
268
269 switch r {
270 case ';':
271 if valueQuotedOriginally {
272 // We're in a quoted string, so whitespace is allowed.
273 value.WriteRune(r)
274 break
275 }
276
277 // Otherwise, we've reached the end of an unquoted value.
278 rest = s[i:]
279 break findValueEnd
280
281 case ' ', '\t':
282 if valueQuotedOriginally {
283 // We're in a quoted string, so whitespace is allowed.
284 value.WriteRune(r)
285 break
286 }
287
288 // This string contains whitespace, must be quoted.
289 quoteIfUnquoted()
290 value.WriteRune(r)
291
292 case '"':
293 if valueQuotedOriginally {
294 // We're in a quoted value. This is the end of that value.
295 rest = s[i:]
296 break findValueEnd
297 }
298
299 quoteIfUnquoted()
300 value.WriteByte('\\')
301 value.WriteRune(r)
302
303 case '\\':
304 if i < len(s)-1 {
305 // If next char is present, escape it with backslash.
306 value.WriteRune(r)
307 escaped = true
308 quoteIfUnquoted()
309 }
310
311 case '(', ')', '<', '>', '@', ',', ':', '/', '[', ']', '?', '=':
312 quoteIfUnquoted()
313 fallthrough
314
315 default:
316 if r > 127 {
317 rfc2047Needed = true
318 }
319 value.WriteRune(r)
320 }
321 }
322 }
323
324 if value.Len() > 0 {
325 // Convert whole value to RFC2047 if it contains forbidden characters (ASCII > 127)
326 val := value.String()
327 if rfc2047Needed {
328 val = mime.BEncoding.Encode(utf8, val)
329 // RFC 2047 must be quoted
330 quoteIfUnquoted()
331 }
332
333 // Write the value
334 param.WriteString(val)
335 }
336
337 // Add final quote if required
338 if valueQuoteNeeded {
339 param.WriteByte('"')
340 }
341
342 // Write last parsed char if any
343 if rest != "" {
344 if rest[0] != '"' {
345 // When last char is quote, valueQuotedOriginally is surely true and the quote was already written.
346 // Otherwise output the character (; for example)
347 param.WriteByte(rest[0])
348 }
349
350 // Focus the rest of the string
351 rest = rest[1:]
352 }
353
354 return param.String(), rest
355 }
356
357 // fixUnquotedSpecials as defined in RFC 2045, section 5.1:
358 // https://tools.ietf.org/html/rfc2045#section-5.1
359 func fixUnquotedSpecials(s string) string {
360 idx := strings.IndexByte(s, ';')
361 if idx < 0 || idx == len(s) {
362 // No parameters
363 return s
364 }
365
366 clean := strings.Builder{}
367 clean.WriteString(s[:idx+1])
368 s = s[idx+1:]
369
370 for len(s) > 0 {
371 var consumed string
372 consumed, s = consumeParam(s)
373
374 if len(consumed) == 0 {
375 clean.WriteString(s)
376 return clean.String()
377 }
378
379 clean.WriteString(consumed)
380 }
381
382 return clean.String()
383 }
384
385 // fixUnescapedQuotes inspects for unescaped quotes inside of a quoted string and escapes them
386 //
387 // Input: application/rtf; charset=iso-8859-1; name=""V047411.rtf".rtf"
388 // Output: application/rtf; charset=iso-8859-1; name="\"V047411.rtf\".rtf"
389 func fixUnescapedQuotes(hvalue string) string {
390 params := strings.SplitAfter(hvalue, ";")
391 sb := &strings.Builder{}
392
393 for i := 0; i < len(params); i++ {
394 // Inspect for "=" byte.
395 eq := strings.IndexByte(params[i], '=')
396 if eq < 0 {
397 // No "=", must be the content-type or a comment.
398 sb.WriteString(params[i])
399 continue
400 }
401 sb.WriteString(params[i][:eq])
402 param := params[i][eq:]
403 startingQuote := strings.IndexByte(param, '"')
404 closingQuote := strings.LastIndexByte(param, '"')
405
406 // Opportunity to exit early if there are no quotes.
407 if startingQuote < 0 && closingQuote < 0 {
408 // This value is not quoted, write the value and carry on.
409 sb.WriteString(param)
410 continue
411 }
412
413 // Check if only one quote was found in the string.
414 if closingQuote == startingQuote {
415 // Append the next chunk of params here in case of a semicolon mid string.
416 if len(params) > i+1 {
417 param = fmt.Sprintf("%s%s", param, params[i+1])
418 }
419 closingQuote = strings.LastIndexByte(param, '"')
420 i++
421 if closingQuote == startingQuote {
422 sb.WriteString("=\"\"")
423 return sb.String()
424 }
425 }
426
427 // Write the k/v separator back in along with everything up until the first quote.
428 sb.WriteByte('=')
429 sb.WriteByte('"') // Starting quote
430 sb.WriteString(param[1:startingQuote])
431
432 // Get the value, less the outer quotes.
433 rest := param[closingQuote+1:]
434
435 // If there is stuff after the last quote then we should escape the first quote.
436 if len(rest) > 0 && rest != ";" {
437 sb.WriteString("\\\"")
438 }
439
440 param = param[startingQuote+1 : closingQuote]
441 escaped := false
442 for strIdx := range []byte(param) {
443 switch param[strIdx] {
444 case '"':
445 // We are inside of a quoted string, so lets escape this guy if it isn't already escaped.
446 if !escaped {
447 sb.WriteByte('\\')
448 escaped = false
449 }
450 sb.WriteByte(param[strIdx])
451 case '\\':
452 // Something is getting escaped, a quote is the only char that needs
453 // this, so lets assume the following char is a double-quote.
454 escaped = true
455 sb.WriteByte('\\')
456 default:
457 escaped = false
458 sb.WriteByte(param[strIdx])
459 }
460 }
461
462 // If there is stuff after the last quote then we should escape the last quote, apply the
463 // rest and terminate with a quote.
464 switch rest {
465 case ";":
466 sb.WriteByte('"')
467 sb.WriteString(rest)
468 case "":
469 sb.WriteByte('"')
470 default:
471 sb.WriteByte('\\')
472 sb.WriteByte('"')
473 sb.WriteString(rest)
474 sb.WriteByte('"')
475 }
476 }
477
478 return sb.String()
479 }
480
481 // fixNewlines replaces \n with a space and removes \r
482 func fixNewlines(value string) string {
483 value = strings.ReplaceAll(value, "\n", " ")
484 value = strings.ReplaceAll(value, "\r", "")
485 return value
486 }