Debian Codegraph @

internal/coding/headerext.go

raw
1 package coding
2
3 import (
4 "fmt"
5 "io"
6 "mime"
7 "strings"
8 )
9
10 // DecodeExtHeader decodes a single line (per RFC 2047, aka Message Header Extensions) using Golang's
11 // mime.WordDecoder.
12 func DecodeExtHeader(input string) string {
13 if !strings.Contains(input, "=?") {
14 // Don't scan if there is nothing to do here
15 return input
16 }
17
18 dec := new(mime.WordDecoder)
19 dec.CharsetReader = NewCharsetReader
20 header, err := dec.DecodeHeader(input)
21 if err != nil {
22 return input
23 }
24
25 return header
26 }
27
28 // RFC2047Decode returns a decoded string if the input uses RFC2047 encoding, otherwise it will
29 // return the input.
30 //
31 // RFC2047 Example: `=?UTF-8?B?bmFtZT0iw7DCn8KUwoo=?=`
32 func RFC2047Decode(s string) string {
33 // Convert CR/LF to spaces.
34 s = strings.Map(func(r rune) rune {
35 if r == '\n' || r == '\r' {
36 return ' '
37 }
38 return r
39 }, s)
40
41 var err error
42 decoded := false
43 for {
44 s, err = rfc2047Recurse(s)
45 switch err {
46 case nil:
47 decoded = true
48 continue
49
50 default:
51 if decoded {
52 keyValuePair := strings.SplitAfter(s, "=")
53 if len(keyValuePair) < 2 {
54 return s
55 }
56
57 // Add quotes as needed.
58 if !strings.HasPrefix(keyValuePair[1], "\"") {
59 keyValuePair[1] = fmt.Sprintf("\"%s", keyValuePair[1])
60 }
61 if !strings.HasSuffix(keyValuePair[1], "\"") {
62 keyValuePair[1] = fmt.Sprintf("%s\"", keyValuePair[1])
63 }
64
65 return strings.Join(keyValuePair, "")
66 }
67
68 return s
69 }
70 }
71 }
72
73 // rfc2047Recurse is called for if the value contains content encoded in RFC2047 format and decodes
74 // it.
75 func rfc2047Recurse(s string) (string, error) {
76 us := strings.ToUpper(s)
77 if !strings.Contains(us, "?Q?") && !strings.Contains(us, "?B?") {
78 return s, io.EOF
79 }
80
81 var val string
82 if val = DecodeExtHeader(s); val == s {
83 if val = DecodeExtHeader(fixRFC2047String(val)); val == s {
84 return val, io.EOF
85 }
86 }
87
88 return val, nil
89 }
90
91 // fixRFC2047String removes the following characters from charset and encoding segments of an
92 // RFC2047 string: '\n', '\r' and ' '
93 func fixRFC2047String(s string) string {
94 inString := false
95 isWithinTerminatingEqualSigns := false
96 questionMarkCount := 0
97 sb := &strings.Builder{}
98 for _, v := range s {
99 switch v {
100 case '=':
101 if questionMarkCount == 3 {
102 inString = false
103 } else {
104 isWithinTerminatingEqualSigns = true
105 }
106 sb.WriteRune(v)
107
108 case '?':
109 if isWithinTerminatingEqualSigns {
110 inString = true
111 } else {
112 questionMarkCount++
113 }
114 isWithinTerminatingEqualSigns = false
115 sb.WriteRune(v)
116
117 case '\n', '\r', ' ':
118 if !inString {
119 sb.WriteRune(v)
120 }
121 isWithinTerminatingEqualSigns = false
122
123 default:
124 isWithinTerminatingEqualSigns = false
125 sb.WriteRune(v)
126 }
127 }
128
129 return sb.String()
130 }