forked from sorbits/go.enmime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheader.go
88 lines (78 loc) · 2.01 KB
/
header.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
package enmime
import (
"fmt"
"strings"
"github.com/cention-sany/mime"
)
func debug(format string, args ...interface{}) {
if false {
fmt.Printf(format, args...)
fmt.Println()
}
}
// Terminology from RFC 2047:
// encoded-word: the entire =?charset?encoding?encoded-text?= string
// charset: the character set portion of the encoded word
// encoding: the character encoding type used for the encoded-text
// encoded-text: the text we are decoding
// DecodeHeader (per RFC 2047) using Golang's mime.WordDecoder
func DecodeHeader(input string) string {
if !strings.Contains(input, "=?") {
// Don't scan if there is nothing to do here
return input
}
dec := new(mime.WordDecoder)
dec.CharsetReader = NewCharsetReader
header, err := dec.DecodeHeader(input)
if err != nil {
return input
}
return header
}
// DecodeToUTF8Base64Header decodes a MIME header per RFC 2047, reencoding to =?utf-8b?
func DecodeToUTF8Base64Header(input string) string {
if !strings.Contains(input, "=?") {
// Don't scan if there is nothing to do here
return input
}
debug("input = %q", input)
tokens := strings.FieldsFunc(input, isWhiteSpaceRune)
output := make([]string, len(tokens), len(tokens))
for i, token := range tokens {
if len(token) > 4 && strings.Contains(token, "=?") {
// Stash parenthesis, they should not be encoded
prefix := ""
suffix := ""
if token[0] == '(' {
prefix = "("
token = token[1:]
}
if token[len(token)-1] == ')' {
suffix = ")"
token = token[:len(token)-1]
}
// Base64 encode token
output[i] = prefix + mime.BEncoding.Encode("UTF-8", DecodeHeader(token)) + suffix
} else {
output[i] = token
}
debug("%v %q %q", i, token, output[i])
}
// Return space separated tokens
return strings.Join(output, " ")
}
// Detects a RFC-822 linear-white-space, passed to strings.FieldsFunc
func isWhiteSpaceRune(r rune) bool {
switch r {
case ' ':
return true
case '\t':
return true
case '\r':
return true
case '\n':
return true
default:
return false
}
}