File: atom.go

package info (click to toggle)
golang-github-protonmail-gluon 0.17.0-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 16,020 kB
  • sloc: sh: 55; makefile: 5
file content (318 lines) | stat: -rw-r--r-- 7,805 bytes parent folder | download
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
package rfc5322

// 3.2.4.  Quoted Strings

import (
	"fmt"
	"io"
	"mime"

	"github.com/ProtonMail/gluon/rfcparser"
)

func parseDotAtom(p *rfcparser.Parser) (rfcparser.String, error) {
	// dot-atom        =   [CFWS] dot-atom-text [CFWS]
	if _, err := tryParseCFWS(p); err != nil {
		return rfcparser.String{}, err
	}

	atom, err := parseDotAtomText(p)
	if err != nil {
		return rfcparser.String{}, err
	}

	if _, err := tryParseCFWS(p); err != nil {
		return rfcparser.String{}, err
	}

	return atom, nil
}

func parseDotAtomText(p *rfcparser.Parser) (rfcparser.String, error) {
	//  dot-atom-text   =   1*atext *("." 1*atext)
	//  This version has been extended to allow for trailing '.' files.
	if err := p.ConsumeWith(isAText, "expected atext char for dot-atom-text"); err != nil {
		return rfcparser.String{}, err
	}

	atom, err := p.CollectBytesWhileMatchesWithPrevWith(isAText)
	if err != nil {
		return rfcparser.String{}, err
	}

	for {
		if ok, err := p.Matches(rfcparser.TokenTypePeriod); err != nil {
			return rfcparser.String{}, err
		} else if !ok {
			break
		}

		atom.Value = append(atom.Value, '.')

		if p.Check(rfcparser.TokenTypePeriod) {
			return rfcparser.String{}, p.MakeError("invalid token after '.'")
		}

		// Early exit to allow trailing '.'
		if !p.CheckWith(isAText) {
			break
		}

		if err := p.ConsumeWith(isAText, "expected atext char for dot-atom-text"); err != nil {
			return rfcparser.String{}, err
		}

		atomNext, err := p.CollectBytesWhileMatchesWithPrevWith(isAText)
		if err != nil {
			return rfcparser.String{}, err
		}

		atom.Value = append(atom.Value, atomNext.Value...)
	}

	return atom.IntoString(), nil
}

func parseAtom(p *rfcparser.Parser) (parserString, error) {
	// atom            =   [CFWS] 1*atext [CFWS]
	if _, err := tryParseCFWS(p); err != nil {
		return parserString{}, err
	}

	if err := p.ConsumeWith(isAText, "expected atext char for atom"); err != nil {
		return parserString{}, err
	}

	atom, err := p.CollectBytesWhileMatchesWithPrevWith(isAText)
	if err != nil {
		return parserString{}, err
	}

	if _, err := tryParseCFWS(p); err != nil {
		return parserString{}, err
	}

	return parserString{
		String: atom.IntoString(),
		Type:   parserStringTypeOther,
	}, nil
}

var CharsetReader func(charset string, input io.Reader) (io.Reader, error)

func parseEncodedAtom(p *rfcparser.Parser) (parserString, error) {
	// encoded-word = "=?" charset "?" encoding "?" encoded-text "?="
	//
	// charset = token    ; see section 3
	//
	// encoding = token   ; see section 4
	//
	//
	if _, err := tryParseCFWS(p); err != nil {
		return parserString{}, err
	}

	var fullWord string

	startOffset := p.CurrentToken().Offset

	if err := p.ConsumeBytesFold('=', '?'); err != nil {
		return parserString{}, err
	}

	fullWord += "=?"

	charset, err := p.CollectBytesWhileMatchesWith(isEncodedAtomToken)
	if err != nil {
		return parserString{}, err
	}

	fullWord += charset.IntoString().Value

	if err := p.Consume(rfcparser.TokenTypeQuestion, "expected '?' after encoding charset"); err != nil {
		return parserString{}, err
	}

	fullWord += "?"

	if err := p.Consume(rfcparser.TokenTypeChar, "expected char after '?'"); err != nil {
		return parserString{}, err
	}

	encoding := rfcparser.ByteToLower(p.PreviousToken().Value)
	if encoding != 'q' && encoding != 'b' {
		return parserString{}, p.MakeError("encoding should either be 'Q' or 'B'")
	}

	if err := p.Consume(rfcparser.TokenTypeQuestion, "expected '?' after encoding byte"); err != nil {
		return parserString{}, err
	}

	if encoding == 'b' {
		fullWord += "B"
	} else {
		fullWord += "Q"
	}

	fullWord += "?"

	encodedText, err := p.CollectBytesWhileMatchesWith(isEncodedText)
	if err != nil {
		return parserString{}, err
	}

	fullWord += encodedText.IntoString().Value

	if err := p.ConsumeBytesFold('?', '='); err != nil {
		return parserString{}, err
	}

	fullWord += "?="

	if _, err := tryParseCFWS(p); err != nil {
		return parserString{}, err
	}

	decoder := mime.WordDecoder{CharsetReader: CharsetReader}

	decoded, err := decoder.Decode(fullWord)
	if err != nil {
		return parserString{}, p.MakeErrorAtOffset(fmt.Sprintf("failed to decode encoded atom: %v", err), startOffset)
	}

	return parserString{
		String: rfcparser.String{Value: decoded, Offset: startOffset},
		Type:   parserStringTypeEncoded,
	}, nil
}

func isEncodedAtomToken(tokenType rfcparser.TokenType) bool {
	// token = 1*<Any CHAR except SPACE, CTLs, and especials>
	//
	// specials = "(" / ")" / "<" / ">" / "@" / "," / ";" / ":" / "
	// <"> / "/" / "[" / "]" / "?" / "." / "="
	if rfcparser.IsCTL(tokenType) {
		return false
	}

	switch tokenType { //nolint:exhaustive
	case rfcparser.TokenTypeEOF:
		fallthrough
	case rfcparser.TokenTypeError:
		fallthrough
	case rfcparser.TokenTypeSP:
		fallthrough
	case rfcparser.TokenTypeLParen:
		fallthrough
	case rfcparser.TokenTypeRParen:
		fallthrough
	case rfcparser.TokenTypeLess:
		fallthrough
	case rfcparser.TokenTypeGreater:
		fallthrough
	case rfcparser.TokenTypeAt:
		fallthrough
	case rfcparser.TokenTypeComma:
		fallthrough
	case rfcparser.TokenTypeSemicolon:
		fallthrough
	case rfcparser.TokenTypeColon:
		fallthrough
	case rfcparser.TokenTypeDQuote:
		fallthrough
	case rfcparser.TokenTypeSlash:
		fallthrough
	case rfcparser.TokenTypeLBracket:
		fallthrough
	case rfcparser.TokenTypeRBracket:
		fallthrough
	case rfcparser.TokenTypeQuestion:
		fallthrough
	case rfcparser.TokenTypePeriod:
		fallthrough
	case rfcparser.TokenTypeEqual:
		return false
	default:
		return true
	}
}

func isEncodedText(tokenType rfcparser.TokenType) bool {
	//  encoded-text = 1*<Any printable ASCII character other than "?"
	//                     or SPACE>
	//                  ; (but see "Use of encoded-words in message
	//                  ; headers", section 5)
	//
	if rfcparser.IsCTL(tokenType) ||
		tokenType == rfcparser.TokenTypeSP ||
		tokenType == rfcparser.TokenTypeQuestion ||
		tokenType == rfcparser.TokenTypeEOF ||
		tokenType == rfcparser.TokenTypeError ||
		tokenType == rfcparser.TokenTypeExtendedChar {
		return false
	}

	return true
}

func isAText(tokenType rfcparser.TokenType) bool {
	//     atext           =   ALPHA / DIGIT /    ; Printable US-ASCII
	//                         "!" / "#" /        ;  characters not including
	//                         "$" / "%" /        ;  specials.  Used for atoms.
	//                         "&" / "'" /
	//                         "*" / "+" /
	//                         "-" / "/" /
	//                         "=" / "?" /
	//                         "^" / "_" /
	//                         "`" / "{" /
	//                         "|" / "}" /
	//                         "~"
	switch tokenType { //nolint:exhaustive
	case rfcparser.TokenTypeDigit:
		fallthrough
	case rfcparser.TokenTypeChar:
		fallthrough
	case rfcparser.TokenTypeExclamation:
		fallthrough
	case rfcparser.TokenTypeHash:
		fallthrough
	case rfcparser.TokenTypeDollar:
		fallthrough
	case rfcparser.TokenTypePercent:
		fallthrough
	case rfcparser.TokenTypeAmpersand:
		fallthrough
	case rfcparser.TokenTypeSQuote:
		fallthrough
	case rfcparser.TokenTypeAsterisk:
		fallthrough
	case rfcparser.TokenTypePlus:
		fallthrough
	case rfcparser.TokenTypeMinus:
		fallthrough
	case rfcparser.TokenTypeSlash:
		fallthrough
	case rfcparser.TokenTypeEqual:
		fallthrough
	case rfcparser.TokenTypeQuestion:
		fallthrough
	case rfcparser.TokenTypeCaret:
		fallthrough
	case rfcparser.TokenTypeUnderscore:
		fallthrough
	case rfcparser.TokenTyeBacktick:
		fallthrough
	case rfcparser.TokenTypeLCurly:
		fallthrough
	case rfcparser.TokenTypeRCurly:
		fallthrough
	case rfcparser.TokenTypePipe:
		fallthrough
	case rfcparser.TokenTypeExtendedChar: // RFC6532
		fallthrough
	case rfcparser.TokenTypeTilde:
		return true
	default:
		return false
	}
}