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
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
use crate::client_types::SmtpClientTimeouts;
use pest::iterators::{Pair, Pairs};
use pest::Parser as _;
use pest_derive::*;
use std::time::Duration;

#[derive(Parser)]
#[grammar = "rfc5321.pest"]
struct Parser;

impl Parser {
    pub fn parse_command(text: &str) -> Result<Command, String> {
        let result = Parser::parse(Rule::command, text)
            .map_err(|err| format!("{err:#}"))?
            .next()
            .unwrap();

        match result.as_rule() {
            Rule::mail => Self::parse_mail(result.into_inner()),
            Rule::rcpt => Self::parse_rcpt(result.into_inner()),
            Rule::ehlo => Self::parse_ehlo(result.into_inner()),
            Rule::helo => Self::parse_helo(result.into_inner()),
            Rule::data => Ok(Command::Data),
            Rule::rset => Ok(Command::Rset),
            Rule::quit => Ok(Command::Quit),
            Rule::starttls => Ok(Command::StartTls),
            Rule::vrfy => Self::parse_vrfy(result.into_inner()),
            Rule::expn => Self::parse_expn(result.into_inner()),
            Rule::help => Self::parse_help(result.into_inner()),
            Rule::noop => Self::parse_noop(result.into_inner()),
            Rule::auth => Self::parse_auth(result.into_inner()),
            _ => Err(format!("unexpected {result:?}")),
        }
    }

    fn parse_ehlo(mut pairs: Pairs<Rule>) -> Result<Command, String> {
        let domain = pairs.next().unwrap();
        Ok(Command::Ehlo(Self::parse_domain(domain)?))
    }

    fn parse_helo(mut pairs: Pairs<Rule>) -> Result<Command, String> {
        let domain = pairs.next().unwrap();
        Ok(Command::Helo(Self::parse_domain(domain)?))
    }

    fn parse_vrfy(mut pairs: Pairs<Rule>) -> Result<Command, String> {
        let param = pairs.next().unwrap().as_str().to_string();
        Ok(Command::Vrfy(param))
    }

    fn parse_expn(mut pairs: Pairs<Rule>) -> Result<Command, String> {
        let param = pairs.next().unwrap().as_str().to_string();
        Ok(Command::Expn(param))
    }

    fn parse_help(mut pairs: Pairs<Rule>) -> Result<Command, String> {
        let param = pairs.next().map(|s| s.as_str().to_string());
        Ok(Command::Help(param))
    }

    fn parse_noop(mut pairs: Pairs<Rule>) -> Result<Command, String> {
        let param = pairs.next().map(|s| s.as_str().to_string());
        Ok(Command::Noop(param))
    }

    fn parse_auth(mut pairs: Pairs<Rule>) -> Result<Command, String> {
        let sasl_mech = pairs.next().map(|s| s.as_str().to_string()).unwrap();
        let initial_response = pairs.next().map(|s| s.as_str().to_string());

        Ok(Command::Auth {
            sasl_mech,
            initial_response,
        })
    }

    fn parse_rcpt(mut pairs: Pairs<Rule>) -> Result<Command, String> {
        let forward_path = pairs.next().unwrap().into_inner().next().unwrap();
        let mut no_angles = false;
        let address = match forward_path.as_rule() {
            Rule::path_no_angles => {
                no_angles = true;
                ForwardPath::Path(Self::parse_path(forward_path)?)
            }
            Rule::path => ForwardPath::Path(Self::parse_path(forward_path)?),
            Rule::postmaster => ForwardPath::Postmaster,
            wat => return Err(format!("unexpected {wat:?}")),
        };

        let mut parameters = vec![];

        if let Some(params) = pairs.next() {
            if no_angles {
                return Err(format!(
                    "must enclose address in <> if you want to use ESMTP parameters"
                ));
            }
            for param in params.into_inner() {
                let mut iter = param.into_inner();
                let name = iter.next().unwrap().as_str().to_string();
                let value = iter.next().map(|p| p.as_str().to_string());
                parameters.push(EsmtpParameter { name, value });
            }
        }

        Ok(Command::RcptTo {
            address,
            parameters,
        })
    }

    fn parse_mail(mut pairs: Pairs<Rule>) -> Result<Command, String> {
        let reverse_path = pairs.next().unwrap().into_inner().next().unwrap();
        let mut no_angles = false;
        let address = match reverse_path.as_rule() {
            Rule::path_no_angles => {
                no_angles = true;
                ReversePath::Path(Self::parse_path(reverse_path)?)
            }
            Rule::path => ReversePath::Path(Self::parse_path(reverse_path)?),
            Rule::null_sender => ReversePath::NullSender,
            wat => return Err(format!("unexpected {wat:?}")),
        };

        let mut parameters = vec![];

        if let Some(params) = pairs.next() {
            if no_angles {
                return Err(format!(
                    "must enclose address in <> if you want to use ESMTP parameters"
                ));
            }
            for param in params.into_inner() {
                let mut iter = param.into_inner();
                let name = iter.next().unwrap().as_str().to_string();
                let value = iter.next().map(|p| p.as_str().to_string());
                parameters.push(EsmtpParameter { name, value });
            }
        }

        Ok(Command::MailFrom {
            address,
            parameters,
        })
    }

    fn parse_path(path: Pair<Rule>) -> Result<MailPath, String> {
        let mut at_domain_list: Vec<String> = vec![];
        for p in path.into_inner() {
            match p.as_rule() {
                Rule::adl => {
                    for pair in p.into_inner() {
                        if let Some(dom) = pair.into_inner().next() {
                            at_domain_list.push(dom.as_str().to_string());
                        }
                    }
                }
                Rule::mailbox => {
                    let mailbox = Self::parse_mailbox(p.into_inner())?;
                    return Ok(MailPath {
                        at_domain_list,
                        mailbox,
                    });
                }
                _ => unreachable!(),
            }
        }
        unreachable!()
    }

    fn parse_domain(domain: Pair<Rule>) -> Result<Domain, String> {
        Ok(match domain.as_rule() {
            Rule::domain => Domain::Name(domain.as_str().to_string()),
            Rule::address_literal => {
                let literal = domain.into_inner().next().unwrap();
                match literal.as_rule() {
                    Rule::ipv4_address_literal => Domain::V4(literal.as_str().to_string()),
                    Rule::ipv6_address_literal => {
                        Domain::V6(literal.into_inner().next().unwrap().as_str().to_string())
                    }
                    Rule::general_address_literal => {
                        let mut literal = literal.into_inner();
                        let tag = literal.next().unwrap().as_str().to_string();
                        let literal = literal.next().unwrap().as_str().to_string();
                        Domain::Tagged { tag, literal }
                    }

                    _ => unreachable!(),
                }
            }
            _ => unreachable!(),
        })
    }

    fn parse_mailbox(mut mailbox: Pairs<Rule>) -> Result<Mailbox, String> {
        let local_part = mailbox.next().unwrap().as_str().to_string();
        let domain = Self::parse_domain(mailbox.next().unwrap())?;
        Ok(Mailbox { local_part, domain })
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ReversePath {
    Path(MailPath),
    NullSender,
}

impl TryFrom<&str> for ReversePath {
    type Error = &'static str;
    fn try_from(s: &str) -> Result<Self, Self::Error> {
        if s.is_empty() {
            Ok(Self::NullSender)
        } else {
            let fields: Vec<&str> = s.split('@').collect();
            if fields.len() == 2 {
                Ok(Self::Path(MailPath {
                    at_domain_list: vec![],
                    mailbox: Mailbox {
                        local_part: fields[0].to_string(),
                        domain: Domain::Name(fields[1].to_string()),
                    },
                }))
            } else {
                Err("wrong number of @ signs")
            }
        }
    }
}

impl ToString for ReversePath {
    fn to_string(&self) -> String {
        match self {
            Self::Path(p) => p.to_string(),
            Self::NullSender => "".to_string(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ForwardPath {
    Path(MailPath),
    Postmaster,
}

impl TryFrom<&str> for ForwardPath {
    type Error = &'static str;
    fn try_from(s: &str) -> Result<Self, Self::Error> {
        if s.is_empty() {
            Err("cannot send to null sender")
        } else if s.eq_ignore_ascii_case("postmaster") {
            Ok(Self::Postmaster)
        } else {
            let fields: Vec<&str> = s.split('@').collect();
            if fields.len() == 2 {
                Ok(Self::Path(MailPath {
                    at_domain_list: vec![],
                    mailbox: Mailbox {
                        local_part: fields[0].to_string(),
                        domain: Domain::Name(fields[1].to_string()),
                    },
                }))
            } else {
                Err("wrong number of @ signs")
            }
        }
    }
}

impl ToString for ForwardPath {
    fn to_string(&self) -> String {
        match self {
            Self::Path(p) => p.to_string(),
            Self::Postmaster => "postmaster".to_string(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MailPath {
    pub at_domain_list: Vec<String>,
    pub mailbox: Mailbox,
}

impl ToString for MailPath {
    fn to_string(&self) -> String {
        // Note: RFC5321 says about at_domain_list:
        // Note that this form, the so-called "source
        // route", MUST BE accepted, SHOULD NOT be
        // generated, and SHOULD be ignored.
        // So we don't include it in the stringified
        // version of MailPath
        self.mailbox.to_string()
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Mailbox {
    pub local_part: String,
    pub domain: Domain,
}

impl ToString for Mailbox {
    fn to_string(&self) -> String {
        let domain = self.domain.to_string();
        format!("{}@{}", self.local_part, domain)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Domain {
    Name(String),
    V4(String),
    V6(String),
    Tagged { tag: String, literal: String },
}

impl ToString for Domain {
    fn to_string(&self) -> String {
        match self {
            Self::Name(name) => name.to_string(),
            Self::V4(addr) => format!("[{addr}]"),
            Self::V6(addr) => format!("[IPv6:{addr}]"),
            Self::Tagged { tag, literal } => format!("[{tag}:{literal}]"),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EsmtpParameter {
    pub name: String,
    pub value: Option<String>,
}

impl ToString for EsmtpParameter {
    fn to_string(&self) -> String {
        match &self.value {
            Some(value) => format!("{}={}", self.name, value),
            None => self.name.to_string(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Command {
    Ehlo(Domain),
    Helo(Domain),
    MailFrom {
        address: ReversePath,
        parameters: Vec<EsmtpParameter>,
    },
    RcptTo {
        address: ForwardPath,
        parameters: Vec<EsmtpParameter>,
    },
    Data,
    DataDot,
    Rset,
    Quit,
    Vrfy(String),
    Expn(String),
    Help(Option<String>),
    Noop(Option<String>),
    StartTls,
    Auth {
        sasl_mech: String,
        initial_response: Option<String>,
    },
}

impl Command {
    pub fn parse(line: &str) -> Result<Self, String> {
        Parser::parse_command(line)
    }

    pub fn encode(&self) -> String {
        match self {
            Self::Ehlo(domain) => format!("EHLO {}\r\n", domain.to_string()),
            Self::Helo(domain) => format!("HELO {}\r\n", domain.to_string()),
            Self::MailFrom {
                address,
                parameters,
            } => {
                let mut params = String::new();
                for p in parameters {
                    params.push(' ');
                    params.push_str(&p.to_string());
                }

                format!("MAIL FROM:<{}>{params}\r\n", address.to_string())
            }
            Self::RcptTo {
                address,
                parameters,
            } => {
                let mut params = String::new();
                for p in parameters {
                    params.push(' ');
                    params.push_str(&p.to_string());
                }

                format!("RCPT TO:<{}>{params}\r\n", address.to_string())
            }
            Self::Data => "DATA\r\n".to_string(),
            Self::DataDot => ".\r\n".to_string(),
            Self::Rset => "RSET\r\n".to_string(),
            Self::Quit => "QUIT\r\n".to_string(),
            Self::StartTls => "STARTTLS\r\n".to_string(),
            Self::Vrfy(param) => format!("VRFY {param}\r\n"),
            Self::Expn(param) => format!("EXPN {param}\r\n"),
            Self::Help(Some(param)) => format!("HELP {param}\r\n"),
            Self::Help(None) => format!("HELP\r\n"),
            Self::Noop(Some(param)) => format!("NOOP {param}\r\n"),
            Self::Noop(None) => format!("NOOP\r\n"),
            Self::Auth {
                sasl_mech,
                initial_response: None,
            } => format!("AUTH {sasl_mech}\r\n"),
            Self::Auth {
                sasl_mech,
                initial_response: Some(resp),
            } => format!("AUTH {sasl_mech} {resp}\r\n"),
        }
    }

    /// Timeouts for reading the response
    pub fn client_timeout(&self, timeouts: &SmtpClientTimeouts) -> Duration {
        match self {
            Self::Helo(_) | Self::Ehlo(_) => timeouts.ehlo_timeout,
            Self::MailFrom { .. } => timeouts.mail_from_timeout,
            Self::RcptTo { .. } => timeouts.rcpt_to_timeout,
            Self::Data { .. } => timeouts.data_timeout,
            Self::DataDot => timeouts.data_dot_timeout,
            Self::Rset => timeouts.rset_timeout,
            Self::StartTls => timeouts.starttls_timeout,
            Self::Quit | Self::Vrfy(_) | Self::Expn(_) | Self::Help(_) | Self::Noop(_) => {
                timeouts.idle_timeout
            }
            Self::Auth { .. } => timeouts.auth_timeout,
        }
    }

    /// Timeouts for writing the request
    pub fn client_timeout_request(&self, timeouts: &SmtpClientTimeouts) -> Duration {
        let one_minute = Duration::from_secs(60);
        self.client_timeout(timeouts).min(one_minute)
    }
}

pub fn is_valid_domain(text: &str) -> bool {
    Parser::parse(Rule::complete_domain, text).is_ok()
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn parse_single_verbs() {
        assert_eq!(Parser::parse_command("data").unwrap(), Command::Data,);
        assert_eq!(Parser::parse_command("Quit").unwrap(), Command::Quit,);
        assert_eq!(Parser::parse_command("rset").unwrap(), Command::Rset,);
    }

    #[test]
    fn parse_vrfy() {
        assert_eq!(
            Parser::parse_command("VRFY someone").unwrap(),
            Command::Vrfy("someone".to_string())
        );
    }

    #[test]
    fn parse_expn() {
        assert_eq!(
            Parser::parse_command("expn someone").unwrap(),
            Command::Expn("someone".to_string())
        );
    }

    #[test]
    fn parse_help() {
        assert_eq!(Parser::parse_command("help").unwrap(), Command::Help(None),);
        assert_eq!(
            Parser::parse_command("help me").unwrap(),
            Command::Help(Some("me".to_string())),
        );
    }

    #[test]
    fn parse_noop() {
        assert_eq!(Parser::parse_command("noop").unwrap(), Command::Noop(None),);
        assert_eq!(
            Parser::parse_command("noop param").unwrap(),
            Command::Noop(Some("param".to_string())),
        );
    }

    #[test]
    fn parse_ehlo() {
        assert_eq!(
            Parser::parse_command("EHLO there").unwrap(),
            Command::Ehlo(Domain::Name("there".to_string()))
        );
        assert_eq!(
            Parser::parse_command("EHLO [127.0.0.1]").unwrap(),
            Command::Ehlo(Domain::V4("127.0.0.1".to_string()))
        );
    }

    #[test]
    fn parse_helo() {
        assert_eq!(
            Parser::parse_command("HELO there").unwrap(),
            Command::Helo(Domain::Name("there".to_string()))
        );
        // The spec says that we cannot use address literals with,
        // HELO, but some tools will still submit it and some MTAs
        // will accept it, so we do too.
        assert_eq!(
            Parser::parse_command("EHLO [127.0.0.1]").unwrap(),
            Command::Ehlo(Domain::V4("127.0.0.1".to_string()))
        );
    }

    #[test]
    fn parse_auth() {
        assert_eq!(
            Parser::parse_command("AUTH PLAIN dGVzdAB0ZXN0ADEyMzQ=").unwrap(),
            Command::Auth {
                sasl_mech: "PLAIN".to_string(),
                initial_response: Some("dGVzdAB0ZXN0ADEyMzQ=".to_string()),
            }
        );
        assert_eq!(
            Parser::parse_command("AUTH PLAIN").unwrap(),
            Command::Auth {
                sasl_mech: "PLAIN".to_string(),
                initial_response: None,
            }
        );
    }

    #[test]
    fn parse_rcpt_to() {
        assert_eq!(
            Parser::parse_command("Rcpt To:<user@host>").unwrap(),
            Command::RcptTo {
                address: ForwardPath::Path(MailPath {
                    at_domain_list: vec![],
                    mailbox: Mailbox {
                        local_part: "user".to_string(),
                        domain: Domain::Name("host".to_string())
                    }
                }),
                parameters: vec![],
            }
        );
        assert_eq!(
            Parser::parse_command("Rcpt To:user@host").unwrap(),
            Command::RcptTo {
                address: ForwardPath::Path(MailPath {
                    at_domain_list: vec![],
                    mailbox: Mailbox {
                        local_part: "user".to_string(),
                        domain: Domain::Name("host".to_string())
                    }
                }),
                parameters: vec![],
            }
        );

        assert_eq!(
            Parser::parse_command("Rcpt To:  user@host").unwrap(),
            Command::RcptTo {
                address: ForwardPath::Path(MailPath {
                    at_domain_list: vec![],
                    mailbox: Mailbox {
                        local_part: "user".to_string(),
                        domain: Domain::Name("host".to_string())
                    }
                }),
                parameters: vec![],
            }
        );

        assert_eq!(
            Parser::parse_command("Rcpt To:<admin@[2001:aaaa:bbbbb]>").unwrap(),
            Command::RcptTo {
                address: ForwardPath::Path(MailPath {
                    at_domain_list: vec![],
                    mailbox: Mailbox {
                        local_part: "admin".to_string(),
                        domain: Domain::Tagged {
                            tag: "2001".to_string(),
                            literal: "aaaa:bbbbb".to_string()
                        }
                    }
                }),
                parameters: vec![],
            }
        );

        assert_eq!(
            Domain::Tagged {
                tag: "2001".to_string(),
                literal: "aaaa:bbbbb".to_string()
            }
            .to_string(),
            "[2001:aaaa:bbbbb]".to_string()
        );

        assert_eq!(
            Parser::parse_command("Rcpt To:<\"asking for trouble\"@host.name>").unwrap(),
            Command::RcptTo {
                address: ForwardPath::Path(MailPath {
                    at_domain_list: vec![],
                    mailbox: Mailbox {
                        local_part: "\"asking for trouble\"".to_string(),
                        domain: Domain::Name("host.name".to_string())
                    }
                }),
                parameters: vec![],
            }
        );

        assert_eq!(
            Parser::parse_command("Rcpt To:<PostMastER>").unwrap(),
            Command::RcptTo {
                address: ForwardPath::Postmaster,
                parameters: vec![],
            }
        );

        assert_eq!(
            Parser::parse_command("Rcpt To:<user@host> woot").unwrap(),
            Command::RcptTo {
                address: ForwardPath::Path(MailPath {
                    at_domain_list: vec![],
                    mailbox: Mailbox {
                        local_part: "user".to_string(),
                        domain: Domain::Name("host".to_string())
                    }
                }),
                parameters: vec![EsmtpParameter {
                    name: "woot".to_string(),
                    value: None
                }],
            }
        );

        assert_eq!(
            Parser::parse_command("Rcpt To:user@host woot").unwrap_err(),
            "must enclose address in <> if you want to use ESMTP parameters".to_string()
        );
    }

    #[test]
    fn parse_mail_from() {
        assert_eq!(
            Parser::parse_command("Mail FROM:<user@host>").unwrap(),
            Command::MailFrom {
                address: ReversePath::Path(MailPath {
                    at_domain_list: vec![],
                    mailbox: Mailbox {
                        local_part: "user".to_string(),
                        domain: Domain::Name("host".to_string())
                    }
                }),
                parameters: vec![],
            }
        );

        assert_eq!(
            Parser::parse_command("Mail FROM:user@host").unwrap(),
            Command::MailFrom {
                address: ReversePath::Path(MailPath {
                    at_domain_list: vec![],
                    mailbox: Mailbox {
                        local_part: "user".to_string(),
                        domain: Domain::Name("host".to_string())
                    }
                }),
                parameters: vec![],
            }
        );

        assert_eq!(
            Parser::parse_command("Mail FROM:user@host foo bar=baz").unwrap_err(),
            "must enclose address in <> if you want to use ESMTP parameters".to_string()
        );

        assert_eq!(
            Parser::parse_command("Mail FROM:<user@host> foo bar=baz").unwrap(),
            Command::MailFrom {
                address: ReversePath::Path(MailPath {
                    at_domain_list: vec![],
                    mailbox: Mailbox {
                        local_part: "user".to_string(),
                        domain: Domain::Name("host".to_string())
                    }
                }),
                parameters: vec![
                    EsmtpParameter {
                        name: "foo".to_string(),
                        value: None,
                    },
                    EsmtpParameter {
                        name: "bar".to_string(),
                        value: Some("baz".to_string()),
                    }
                ],
            }
        );

        assert_eq!(
            Parser::parse_command("mail from:<user@[10.0.0.1]>").unwrap(),
            Command::MailFrom {
                address: ReversePath::Path(MailPath {
                    at_domain_list: vec![],
                    mailbox: Mailbox {
                        local_part: "user".to_string(),
                        domain: Domain::V4("10.0.0.1".to_string())
                    }
                }),
                parameters: vec![],
            }
        );

        assert_eq!(
            Parser::parse_command("mail from:<user@[IPv6:::1]>").unwrap(),
            Command::MailFrom {
                address: ReversePath::Path(MailPath {
                    at_domain_list: vec![],
                    mailbox: Mailbox {
                        local_part: "user".to_string(),
                        domain: Domain::V6("::1".to_string())
                    }
                }),
                parameters: vec![],
            }
        );

        assert_eq!(
            Mailbox {
                local_part: "user".to_string(),
                domain: Domain::V6("::1".to_string())
            }
            .to_string(),
            "user@[IPv6:::1]".to_string()
        );

        assert_eq!(
            Parser::parse_command("mail from:<user@[future:something]>").unwrap(),
            Command::MailFrom {
                address: ReversePath::Path(MailPath {
                    at_domain_list: vec![],
                    mailbox: Mailbox {
                        local_part: "user".to_string(),
                        domain: Domain::Tagged {
                            tag: "future".to_string(),
                            literal: "something".to_string()
                        }
                    }
                }),
                parameters: vec![],
            }
        );

        assert_eq!(
            Parser::parse_command("MAIL FROM:<@hosta.int,@jkl.org:userc@d.bar.org>").unwrap(),
            Command::MailFrom {
                address: ReversePath::Path(MailPath {
                    at_domain_list: vec!["hosta.int".to_string(), "jkl.org".to_string()],
                    mailbox: Mailbox {
                        local_part: "userc".to_string(),
                        domain: Domain::Name("d.bar.org".to_string())
                    }
                }),
                parameters: vec![],
            }
        );
    }

    #[test]
    fn parse_domain() {
        assert!(is_valid_domain("hello"));
        assert!(is_valid_domain("he-llo"));
        assert!(is_valid_domain("he.llo"));
        assert!(is_valid_domain("he.llo-"));
    }
}

/* ABNF from RFC 5321

mail = "MAIL FROM:" Reverse-path [SP Mail-parameters] CRLF

rcpt = "RCPT TO:" ( "<Postmaster@" Domain ">" / "<Postmaster>" /
                Forward-path ) [SP Rcpt-parameters] CRLF

                Note that, in a departure from the usual rules for
                local-parts, the "Postmaster" string shown above is
                treated as case-insensitive.

Reverse-path   = Path / "<>"
Forward-path   = Path
Path           = "<" [ A-d-l ":" ] Mailbox ">"
A-d-l          = At-domain *( "," At-domain )
                  ; Note that this form, the so-called "source
                  ; route", MUST BE accepted, SHOULD NOT be
                  ; generated, and SHOULD be ignored.
At-domain      = "@" Domain
Mail-parameters  = esmtp-param *(SP esmtp-param)

   Rcpt-parameters  = esmtp-param *(SP esmtp-param)

   esmtp-param    = esmtp-keyword ["=" esmtp-value]

   esmtp-keyword  = (ALPHA / DIGIT) *(ALPHA / DIGIT / "-")

   esmtp-value    = 1*(%d33-60 / %d62-126)
                  ; any CHAR excluding "=", SP, and control
                  ; characters.  If this string is an email address,
                  ; i.e., a Mailbox, then the "xtext" syntax [32]
                  ; SHOULD be used.

   Keyword        = Ldh-str

   Argument       = Atom

   Domain         = sub-domain *("." sub-domain)
   sub-domain     = Let-dig [Ldh-str]

   Let-dig        = ALPHA / DIGIT

   Ldh-str        = *( ALPHA / DIGIT / "-" ) Let-dig

   address-literal  = "[" ( IPv4-address-literal /
                    IPv6-address-literal /
                    General-address-literal ) "]"
                    ; See Section 4.1.3

   Mailbox        = Local-part "@" ( Domain / address-literal )

   Local-part     = Dot-string / Quoted-string
                  ; MAY be case-sensitive


   Dot-string     = Atom *("."  Atom)

   Atom           = 1*atext

   Quoted-string  = DQUOTE *QcontentSMTP DQUOTE

   QcontentSMTP   = qtextSMTP / quoted-pairSMTP

   quoted-pairSMTP  = %d92 %d32-126
                    ; i.e., backslash followed by any ASCII
                    ; graphic (including itself) or SPace

   qtextSMTP      = %d32-33 / %d35-91 / %d93-126
                  ; i.e., within a quoted string, any
                  ; ASCII graphic or space is permitted
                  ; without blackslash-quoting except
                  ; double-quote and the backslash itself.

   String         = Atom / Quoted-string


      IPv4-address-literal  = Snum 3("."  Snum)

   IPv6-address-literal  = "IPv6:" IPv6-addr

   General-address-literal  = Standardized-tag ":" 1*dcontent

   Standardized-tag  = Ldh-str
                     ; Standardized-tag MUST be specified in a
                     ; Standards-Track RFC and registered with IANA


   dcontent       = %d33-90 / ; Printable US-ASCII
                  %d94-126 ; excl. "[", "\", "]"

   Snum           = 1*3DIGIT
                  ; representing a decimal integer
                  ; value in the range 0 through 255

   IPv6-addr      = IPv6-full / IPv6-comp / IPv6v4-full / IPv6v4-comp

   IPv6-hex       = 1*4HEXDIG

   IPv6-full      = IPv6-hex 7(":" IPv6-hex)

   IPv6-comp      = [IPv6-hex *5(":" IPv6-hex)] "::"
                  [IPv6-hex *5(":" IPv6-hex)]
                  ; The "::" represents at least 2 16-bit groups of
                  ; zeros.  No more than 6 groups in addition to the
                  ; "::" may be present.

   IPv6v4-full    = IPv6-hex 5(":" IPv6-hex) ":" IPv4-address-literal

   IPv6v4-comp    = [IPv6-hex *3(":" IPv6-hex)] "::"
                  [IPv6-hex *3(":" IPv6-hex) ":"]
                  IPv4-address-literal
                  ; The "::" represents at least 2 16-bit groups of
                  ; zeros.  No more than 4 groups in addition to the
                  ; "::" and IPv4-address-literal may be present.


   ehlo           = "EHLO" SP ( Domain / address-literal ) CRLF
   helo           = "HELO" SP Domain CRLF

   ehlo-ok-rsp    = ( "250" SP Domain [ SP ehlo-greet ] CRLF )
                    / ( "250-" Domain [ SP ehlo-greet ] CRLF
                    *( "250-" ehlo-line CRLF )
                    "250" SP ehlo-line CRLF )

   ehlo-greet     = 1*(%d0-9 / %d11-12 / %d14-127)
                    ; string of any characters other than CR or LF

   ehlo-line      = ehlo-keyword *( SP ehlo-param )

   ehlo-keyword   = (ALPHA / DIGIT) *(ALPHA / DIGIT / "-")
                    ; additional syntax of ehlo-params depends on
                    ; ehlo-keyword

   ehlo-param     = 1*(%d33-126)
                    ; any CHAR excluding <SP> and all
                    ; control characters (US-ASCII 0-31 and 127
                    ; inclusive)

    data = "DATA" CRLF
    rset = "RSET" CRLF
    vrfy = "VRFY" SP String CRLF
    expn = "EXPN" SP String CRLF
    help = "HELP" [ SP String ] CRLF
    noop = "NOOP" [ SP String ] CRLF
quit = "QUIT" CRLF


*/