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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
use super::header::{Header, HeaderMap};
use super::rfc2047::decode_rfc2047;
use super::results::{ParsingError, ParsingResult};
pub const MIME_LINE_LENGTH: usize = 78;
trait Rfc5322Character {
fn is_special(&self) -> bool;
fn is_vchar(&self) -> bool;
fn is_ftext(&self) -> bool;
fn is_atext(&self) -> bool {
self.is_vchar() && !self.is_special()
}
}
impl Rfc5322Character for char {
fn is_ftext(&self) -> bool {
match *self {
'!'...'9' | ';'...'~' => true,
_ => false,
}
}
fn is_special(&self) -> bool {
match *self {
'(' | ')' | '<' | '>' | '[' | ']' | ':' | ';' | '@' | '\\' | ',' | '.' | '\"' | ' ' => true,
_ => false
}
}
fn is_vchar(&self) -> bool {
match *self {
'!'...'~' => true,
_ => false,
}
}
}
pub struct Rfc5322Parser<'s> {
s: &'s str,
pos: usize,
pos_stack: Vec<usize>,
}
impl<'s> Rfc5322Parser<'s> {
pub fn new(source: &'s str) -> Rfc5322Parser<'s> {
Rfc5322Parser {
s: source,
pos: 0,
pos_stack: Vec::new(),
}
}
pub fn push_position(&mut self) {
self.pos_stack.push(self.pos);
}
pub fn pop_position(&mut self) {
match self.pos_stack.pop() {
Some(pos) => { self.pos = pos; },
None => panic!("Popped position stack too far"),
}
}
pub fn consume_message(&mut self) -> Option<(HeaderMap, String)> {
let mut headers = HeaderMap::new();
while !self.eof() {
let header = self.consume_header();
if let Some(header) = header {
headers.insert(header);
} else {
if !self.eof() && self.peek_linebreak() {
assert!(self.consume_linebreak());
}
break;
}
}
let body = self.s[self.pos..].to_string();
self.pos = self.s.len();
Some((headers, body))
}
pub fn consume_header(&mut self) -> Option<Header> {
let last_pos = self.pos;
let field_name = self.consume_while(|c| { c.is_ftext() });
self.consume_linear_whitespace();
if field_name.len() == 0 || self.eof() || self.peek() != ':' {
self.pos = last_pos;
None
} else {
self.consume_char();
self.consume_linear_whitespace();
let field_value = self.consume_unstructured();
if self.consume_linebreak() == false { return None };
Some(Header::new(field_name, field_value))
}
}
pub fn consume_unstructured(&mut self) -> String {
let mut result = String::new();
while !self.eof() {
if self.peek_linebreak() {
if !self.consume_folding_whitespace() {
break;
}
}
result.push_str(&self.consume_while(|c| {
c.is_vchar() || c == ' ' || c == '\t'
})[..])
}
result
}
pub fn consume_folding_whitespace(&mut self) -> bool {
let current_position = self.pos;
let is_fws = if !self.eof() && self.consume_linebreak() {
match self.consume_char() {
Some(' ') | Some('\t') => true,
_ => false,
}
} else {
false
};
if is_fws {
self.consume_linear_whitespace();
} else {
self.pos = current_position;
}
is_fws
}
pub fn consume_word(&mut self, allow_dot_atom: bool) -> Option<String> {
let p = self.peek();
if p == '"' {
self.consume_quoted_string()
} else {
self.consume_atom(allow_dot_atom)
}
}
pub fn consume_phrase(&mut self, allow_dot_atom: bool) -> Option<String> {
let mut phrase = String::new();
while !self.eof() {
self.consume_linear_whitespace();
let word = match self.consume_word(allow_dot_atom) {
Some(x) => x,
None => break
};
let w_slice = &word[..];
let decoded_word =
if w_slice.starts_with("=?") && w_slice.ends_with("?=") {
match decode_rfc2047(w_slice) {
Some(w) => w,
None => w_slice.to_string(),
}
} else {
w_slice.to_string()
};
if phrase.len() > 0 {
phrase.push_str(" ");
}
phrase.push_str(&decoded_word[..]);
}
if phrase.len() > 0 {
Some(phrase)
} else {
None
}
}
pub fn consume_quoted_string(&mut self) -> Option<String> {
if self.peek() != '"' {
None
} else {
let mut quoted_string = String::new();
let mut inside_escape = false;
let mut terminated = false;
self.consume_char();
while !terminated && !self.eof() {
match self.peek() {
'\\' if !inside_escape => {
self.consume_char();
inside_escape = true;
},
'"' if !inside_escape => {
self.consume_char();
terminated = true;
},
_ => {
if let Some(c) = self.consume_char() {
quoted_string.push(c);
inside_escape = false;
}
else {
return None;
}
},
}
}
if inside_escape || !terminated {
None
} else {
Some(quoted_string)
}
}
}
pub fn consume_atom(&mut self, allow_dot: bool) -> Option<String> {
if !self.peek().is_atext() {
None
} else {
Some(self.consume_while(|c| {
c.is_atext() || (allow_dot && c == '.')
}))
}
}
pub fn consume_linear_whitespace(&mut self) {
self.consume_while(|c| { c == '\t' || c == ' ' });
}
#[inline]
pub fn consume_char(&mut self) -> Option<char> {
if self.eof() {
return None
}
let c = self.peek();
self.pos += c.len_utf8();
Some(c)
}
pub fn consume_linebreak(&mut self) -> bool {
if self.eof() {
return false;
}
let start_pos = self.pos;
match self.consume_char() {
Some('\r') => {
if !self.eof() && self.peek() == '\n' {
self.consume_char();
}
true
},
Some('\n') => true,
_ => { self.pos = start_pos; false }
}
}
pub fn peek_linebreak(&mut self) -> bool {
match self.peek() {
'\r' | '\n' => true,
_ => false
}
}
#[inline]
pub fn consume_while<F: Fn(char) -> bool>(&mut self, test: F) -> String {
let start_pos = self.pos;
while !self.eof() && test(self.peek()) {
self.consume_char();
}
self.s[start_pos..self.pos].to_string()
}
#[inline]
pub fn peek(&self) -> char {
self.s[self.pos..].chars().next().unwrap()
}
#[inline]
pub fn assert_char(&self, c: char) -> ParsingResult<()> {
try!(self.assert_not_eof());
let actual_c = self.peek();
if c == actual_c {
Ok(())
} else {
Err(ParsingError::new(format!("Expected {}, got {}", c, actual_c)))
}
}
#[inline]
pub fn assert_not_eof(&self) -> ParsingResult<()> {
if self.eof() {
Err(ParsingError::new("Reached EOF.".to_string()))
} else {
Ok(())
}
}
#[inline]
pub fn peek_to_end(&self) -> &str {
&self.s[self.pos..]
}
#[inline]
pub fn eof(&self) -> bool {
self.pos >= self.s.len()
}
}
pub struct Rfc5322Builder {
result: String
}
impl Rfc5322Builder {
pub fn new() -> Rfc5322Builder {
Rfc5322Builder {
result: "".to_string(),
}
}
pub fn result(&self) -> &String {
&self.result
}
pub fn emit_raw(&mut self, s: &str) {
self.result.push_str(s);
}
pub fn emit_folded(&mut self, s: &str) {
let mut cur_len = 0;
let mut last_space = 0;
let mut last_cut = 0;
for (pos, c) in s.char_indices() {
match c {
' ' => { last_space = pos; },
'\r' => { cur_len = 0; },
'\n' => { cur_len = 0; },
_ => {},
}
cur_len += 1;
if cur_len >= MIME_LINE_LENGTH && last_space > 0 {
self.emit_raw(&s[last_cut..last_space]);
self.emit_raw("\r\n\t");
cur_len = 0;
last_cut = last_space + s[last_space..].chars().next().unwrap().len_utf8();
last_space = 0;
}
}
self.emit_raw(&s[last_cut..]);
}
}
#[cfg(test)]
mod tests {
use super::*;
struct PhraseTestCase<'s> {
input: &'s str,
output: &'s str,
name: &'s str,
}
#[test]
fn test_parser() {
let mut parser = Rfc5322Parser::new("");
assert!(parser.consume_message().is_some());
let mut parser = Rfc5322Parser::new("\r\n");
assert!(parser.consume_message().is_some());
let mut parser = Rfc5322Parser::new("From: Garbage@-\r\n");
assert!(parser.consume_message().is_some());
let mut parser = Rfc5322Parser::new("From: Garbage@");
assert!(parser.consume_message().is_some());
let mut parser = Rfc5322Parser::new("From: Garnage@-");
assert!(parser.consume_message().is_some());
}
#[test]
fn test_consume_phrase() {
let tests = [
PhraseTestCase {
input: "\"test phrase\"", output: "test phrase",
name: "Simple quoted-string"
},
PhraseTestCase {
input: "\"test \\\"phrase\\\"\"", output: "test \"phrase\"",
name: "quoted-string with escape character"
},
PhraseTestCase {
input: "\"=?utf-8?q?encoded=20q-string?=\"", output: "encoded q-string",
name: "Encoded quoted-string"
},
PhraseTestCase {
input: "atom test", output: "atom test",
name: "Collection of atoms"
},
PhraseTestCase {
input: "=?utf-8?q?encoded=20atom?=", output: "encoded atom",
name: "Encoded atom"
},
PhraseTestCase {
input: "Mix of atoms \"and quoted strings\"", output: "Mix of atoms and quoted strings",
name: "Mix of atoms and quoted strings"
},
PhraseTestCase {
input: "=?utf-8?q?encoded=20atoms?= mixed with \"unencoded\" \"=?utf-8?b?YW5kIGVuY29kZWQgcS1zdHJpbmdz?=\"",
output: "encoded atoms mixed with unencoded and encoded q-strings",
name: "Mix of atoms, q-strings of differing encodings"
},
PhraseTestCase {
input: "\"John Smith\" <test@example.org>", output: "John Smith",
name: "Stop consuming phrase at \"special\" character",
}
];
for t in tests.iter() {
let mut p = Rfc5322Parser::new(t.input);
let phrase = p.consume_phrase(false);
assert!(phrase.is_some(), format!("{} returned Some", t.name));
let test_name = format!("{} == {} for {}", phrase.clone().unwrap(), t.output, t.name);
assert!(phrase.unwrap() == t.output.to_string(), test_name);
}
}
struct MessageTestCase<'s> {
input: &'s str,
headers: Vec<(&'s str, &'s str)>,
body: &'s str,
}
#[test]
fn test_consume_message() {
let tests = vec![
MessageTestCase {
input: "From: \"Joe Blogs\" <joe@example.org>\r\n\r\nBody",
headers: vec![
("From", "\"Joe Blogs\" <joe@example.org>"),
],
body: "Body",
},
MessageTestCase {
input: "From: \"Joe Blogs\" <joe@example.org>\n\nBody",
headers: vec![
("From", "\"Joe Blogs\" <joe@example.org>"),
],
body: "Body",
},
MessageTestCase {
input: "From: \"Joe Blogs\" <joe@example.org>\r\n\r\nMultiline\r\nBody",
headers: vec![
("From", "\"Joe Blogs\" <joe@example.org>"),
],
body: "Multiline\r\nBody",
},
MessageTestCase {
input: "From: \"Joe Blogs\" <joe@example.org>\r\nTo: \"John Doe\" <john@example.org>\r\n\r\nMultiple headers",
headers: vec![
("From", "\"Joe Blogs\" <joe@example.org>"),
("To", "\"John Doe\" <john@example.org>"),
],
body: "Multiple headers",
},
MessageTestCase {
input: "Folded-Header: Some content that is \r\n\t wrapped with a tab.\r\n\r\nFolding whitespace test",
headers: vec![
("Folded-Header", "Some content that is wrapped with a tab."),
],
body: "Folding whitespace test",
},
MessageTestCase {
input: "Folded-Header: Some content that is \r\n wrapped with spaces.\r\n\r\nFolding whitespace test",
headers: vec![
("Folded-Header", "Some content that is wrapped with spaces."),
],
body: "Folding whitespace test",
},
];
for test in tests.iter() {
let mut p = Rfc5322Parser::new(test.input);
let message = p.consume_message();
match message {
Some((headers, body)) => {
assert_eq!(body, test.body.to_string());
for &(header_title, header_value) in test.headers.iter() {
let matching_headers = headers.find(&header_title.to_string()).unwrap();
assert!(matching_headers.iter().filter(|h| {
let val: String = h.get_value().unwrap();
val == header_value.to_string()
}).count() > 0);
}
},
None => panic!("Failed to parse message"),
};
}
}
#[test]
fn test_builder_folding() {
struct BuildFoldTest<'s> {
input: &'s str,
expected: &'s str,
}
let tests = vec![
BuildFoldTest {
input: "A long line that should get folded on a space at some point around here, possibly at this point.",
expected: "A long line that should get folded on a space at some point around here,\r\n\
\tpossibly at this point.",
},
BuildFoldTest {
input: "A long line that should get folded on a space at some point around here, possibly at this point. And yet more content that will get folded onto another line.",
expected: "A long line that should get folded on a space at some point around here,\r\n\
\tpossibly at this point. And yet more content that will get folded onto another\r\n\
\tline.",
},
];
for test in tests.into_iter() {
let mut gen = Rfc5322Builder::new();
gen.emit_folded(test.input);
assert_eq!(gen.result(), &test.expected.to_string());
}
}
}