daaki-smtp 0.2.0

An async SMTP client library
Documentation
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
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
//! Validated newtypes for SMTP protocol values.
//!
//! Each type validates its contents on construction so that encoders
//! can accept them without redundant runtime checks. Validation rules
//! are derived from the cited RFC sections.
//!
//! # References
//! - RFC 5321 Section 4.1.2 (Domain, Mailbox, path syntax)
//! - RFC 5321 Section 4.1.3 (address-literal syntax)
//! - RFC 5321 Section 4.5.3.1 (size limits)
//! - RFC 3461 Section 4.4 (ENVID xtext values)

use std::fmt;
use std::net::{Ipv4Addr, Ipv6Addr};

pub use daaki_message::ValidationError;

// ============================================================================
// Domain — RFC 5321 Section 4.1.2
// ============================================================================

/// A validated SMTP domain name.
///
/// RFC 5321 Section 4.1.2: `Domain = sub-domain *("." sub-domain)`.
/// Each label is 1-63 octets of `Let-dig [Ldh-str]`, and the total
/// domain is at most 255 octets (RFC 5321 Section 4.5.3.1.2).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(try_from = "String", into = "String"))]
pub struct Domain(String);

impl Domain {
    /// Create a new `Domain` after validating RFC 5321 Section 4.1.2 syntax.
    pub fn new(s: impl Into<String>) -> Result<Self, ValidationError> {
        let s = s.into();
        validate_domain_syntax(&s)?;
        Ok(Self(s))
    }

    /// Return the domain as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consume and return the inner `String`.
    pub fn into_inner(self) -> String {
        self.0
    }
}

impl AsRef<str> for Domain {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for Domain {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl TryFrom<String> for Domain {
    type Error = ValidationError;
    fn try_from(s: String) -> Result<Self, ValidationError> {
        Self::new(s)
    }
}

impl TryFrom<&str> for Domain {
    type Error = ValidationError;
    fn try_from(s: &str) -> Result<Self, ValidationError> {
        Self::new(s)
    }
}

impl From<Domain> for String {
    fn from(d: Domain) -> Self {
        d.into_inner()
    }
}

// ============================================================================
// AddressLiteral — RFC 5321 Section 4.1.3
// ============================================================================

/// A validated SMTP address-literal (e.g. `[127.0.0.1]` or `[IPv6::1]`).
///
/// RFC 5321 Section 4.1.3: `address-literal = "[" ( IPv4-address-literal /
/// IPv6-addr / General-address-literal ) "]"`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(try_from = "String", into = "String"))]
pub struct AddressLiteral(String);

impl AddressLiteral {
    /// Create a new `AddressLiteral` after validating RFC 5321 Section 4.1.3 syntax.
    ///
    /// The value must include the surrounding `[` and `]` brackets.
    pub fn new(s: impl Into<String>) -> Result<Self, ValidationError> {
        let s = s.into();
        validate_address_literal_syntax(&s)?;
        Ok(Self(s))
    }

    /// Return the address literal as a string slice (including brackets).
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consume and return the inner `String`.
    pub fn into_inner(self) -> String {
        self.0
    }
}

impl AsRef<str> for AddressLiteral {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for AddressLiteral {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl TryFrom<String> for AddressLiteral {
    type Error = ValidationError;
    fn try_from(s: String) -> Result<Self, ValidationError> {
        Self::new(s)
    }
}

impl TryFrom<&str> for AddressLiteral {
    type Error = ValidationError;
    fn try_from(s: &str) -> Result<Self, ValidationError> {
        Self::new(s)
    }
}

impl From<AddressLiteral> for String {
    fn from(a: AddressLiteral) -> Self {
        a.into_inner()
    }
}

// ============================================================================
// DomainOrLiteral — RFC 5321 Section 4.1.1.1
// ============================================================================

/// A validated SMTP domain or address-literal, for use in EHLO/LHLO.
///
/// RFC 5321 Section 4.1.1.1: `ehlo-domain = Domain / address-literal`.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum DomainOrLiteral {
    /// A DNS domain name.
    Domain(Domain),
    /// An address literal (`[IPv4]`, `[IPv6:...]`, or generalized).
    Literal(AddressLiteral),
}

impl DomainOrLiteral {
    /// Create from a string, detecting whether it's a domain or literal.
    pub fn new(s: impl Into<String>) -> Result<Self, ValidationError> {
        let s = s.into();
        if s.is_empty() {
            return Err(ValidationError::new(
                "SMTP greeting domain must not be empty (RFC 5321 Section 4.1.1.1)",
            ));
        }
        if s.starts_with('[') && s.ends_with(']') {
            Ok(Self::Literal(AddressLiteral::new(s)?))
        } else {
            Ok(Self::Domain(Domain::new(s)?))
        }
    }

    /// Return the value as a string slice.
    pub fn as_str(&self) -> &str {
        match self {
            Self::Domain(d) => d.as_str(),
            Self::Literal(l) => l.as_str(),
        }
    }
}

impl AsRef<str> for DomainOrLiteral {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl fmt::Display for DomainOrLiteral {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl TryFrom<String> for DomainOrLiteral {
    type Error = ValidationError;
    fn try_from(s: String) -> Result<Self, ValidationError> {
        Self::new(s)
    }
}

impl TryFrom<&str> for DomainOrLiteral {
    type Error = ValidationError;
    fn try_from(s: &str) -> Result<Self, ValidationError> {
        Self::new(s)
    }
}

// ============================================================================
// Mailbox — RFC 5321 Section 4.1.2
// ============================================================================

/// A validated SMTP mailbox (`local-part@domain`).
///
/// RFC 5321 Section 4.1.2: `Mailbox = Local-part "@" ( Domain / address-literal )`.
/// Local-part is at most 64 octets (RFC 5321 Section 4.5.3.1.1).
/// The full path (`<mailbox>`) is at most 256 octets (RFC 5321 Section 4.5.3.1.3).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(try_from = "String", into = "String"))]
pub struct Mailbox(String);

impl Mailbox {
    /// Create a new `Mailbox` after validating RFC 5321 Section 4.1.2 syntax.
    ///
    /// The value must be a bare addr-spec (`user@domain`), not a display-name
    /// form like `"User" <user@domain>`.
    pub fn new(s: impl Into<String>) -> Result<Self, ValidationError> {
        let s = s.into();
        validate_mailbox_syntax(&s)?;
        Ok(Self(strip_obsolete_source_route(&s)?.to_string()))
    }

    /// Return the mailbox as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consume and return the inner `String`.
    pub fn into_inner(self) -> String {
        self.0
    }

    /// Returns `true` if this mailbox contains non-ASCII characters,
    /// requiring the SMTPUTF8 extension (RFC 6531 Sections 3.3-3.4).
    pub fn requires_smtputf8(&self) -> bool {
        !self.0.is_ascii()
    }
}

impl AsRef<str> for Mailbox {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for Mailbox {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl TryFrom<String> for Mailbox {
    type Error = ValidationError;
    fn try_from(s: String) -> Result<Self, ValidationError> {
        Self::new(s)
    }
}

impl TryFrom<&str> for Mailbox {
    type Error = ValidationError;
    fn try_from(s: &str) -> Result<Self, ValidationError> {
        Self::new(s)
    }
}

impl From<Mailbox> for String {
    fn from(m: Mailbox) -> Self {
        m.into_inner()
    }
}

// ============================================================================
// ReversePath — RFC 5321 Section 4.1.1.2
// ============================================================================

/// A validated SMTP reverse-path for MAIL FROM.
///
/// RFC 5321 Section 4.1.1.2: `Reverse-path = Path / "<>"`.
/// A null reverse-path (`<>`) indicates a bounce message.
/// Obsolete source routes in `Path` syntax are accepted but ignored per
/// RFC 5321 Section 4.1.2.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ReversePath {
    /// Null reverse-path (`<>`) — bounce/DSN message.
    Null,
    /// A mailbox address.
    Mailbox(Mailbox),
}

impl ReversePath {
    /// Create from a string. An empty string produces `Null`.
    pub fn new(s: impl Into<String>) -> Result<Self, ValidationError> {
        let s = s.into();
        if s.is_empty() {
            Ok(Self::Null)
        } else {
            Ok(Self::Mailbox(Mailbox::new(s)?))
        }
    }

    /// Return the path as a string slice (empty for null path).
    pub fn as_str(&self) -> &str {
        match self {
            Self::Null => "",
            Self::Mailbox(m) => m.as_str(),
        }
    }

    /// Returns `true` if this is a non-null path with non-ASCII characters,
    /// requiring the SMTPUTF8 extension (RFC 6531 Sections 3.3-3.4).
    pub fn requires_smtputf8(&self) -> bool {
        match self {
            Self::Null => false,
            Self::Mailbox(m) => m.requires_smtputf8(),
        }
    }
}

impl fmt::Display for ReversePath {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl TryFrom<String> for ReversePath {
    type Error = ValidationError;
    fn try_from(s: String) -> Result<Self, ValidationError> {
        Self::new(s)
    }
}

impl TryFrom<&str> for ReversePath {
    type Error = ValidationError;
    fn try_from(s: &str) -> Result<Self, ValidationError> {
        Self::new(s)
    }
}

// ============================================================================
// ForwardPath — RFC 5321 Section 4.1.1.3
// ============================================================================

/// A validated SMTP forward-path for RCPT TO.
///
/// RFC 5321 Section 4.1.1.3: `Forward-path = Path`. Also accepts the
/// special `<Postmaster>` recipient.
/// Obsolete source routes in `Path` syntax are accepted but ignored per
/// RFC 5321 Section 4.1.2.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ForwardPath {
    /// The special `Postmaster` recipient (case-insensitive).
    Postmaster,
    /// A mailbox address.
    Mailbox(Mailbox),
}

impl ForwardPath {
    /// Create from a string. Case-insensitive "postmaster" produces `Postmaster`.
    pub fn new(s: impl Into<String>) -> Result<Self, ValidationError> {
        let s = s.into();
        if s.eq_ignore_ascii_case("postmaster") {
            Ok(Self::Postmaster)
        } else {
            Ok(Self::Mailbox(Mailbox::new(s)?))
        }
    }

    /// Return the path as a string slice.
    pub fn as_str(&self) -> &str {
        match self {
            Self::Postmaster => "Postmaster",
            Self::Mailbox(m) => m.as_str(),
        }
    }

    /// Returns `true` if this is a non-postmaster path with non-ASCII characters.
    pub fn requires_smtputf8(&self) -> bool {
        match self {
            Self::Postmaster => false,
            Self::Mailbox(m) => m.requires_smtputf8(),
        }
    }
}

impl fmt::Display for ForwardPath {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl TryFrom<String> for ForwardPath {
    type Error = ValidationError;
    fn try_from(s: String) -> Result<Self, ValidationError> {
        Self::new(s)
    }
}

impl TryFrom<&str> for ForwardPath {
    type Error = ValidationError;
    fn try_from(s: &str) -> Result<Self, ValidationError> {
        Self::new(s)
    }
}

// ============================================================================
// EnvidValue — RFC 3461 Section 4.4
// ============================================================================

/// A validated DSN ENVID source value.
///
/// RFC 3461 Section 4.4: printable US-ASCII, non-empty, at most 100
/// characters before xtext encoding.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(try_from = "String", into = "String"))]
pub struct EnvidValue(String);

impl EnvidValue {
    /// Consume and return the inner `String`.
    pub fn into_inner(self) -> String {
        self.0
    }

    /// Create a new `EnvidValue` after validating RFC 3461 Section 4.4 constraints.
    pub fn new(s: impl Into<String>) -> Result<Self, ValidationError> {
        let s = s.into();
        if s.is_empty() {
            return Err(ValidationError::new(
                "ENVID value must be non-empty (RFC 3461 Section 4.4: xtext = 1*xchar)",
            ));
        }
        if !s
            .bytes()
            .all(|b| b.is_ascii() && (0x20..=0x7E).contains(&b))
        {
            return Err(ValidationError::new(
                "ENVID source value must contain only printable US-ASCII before xtext encoding \
                 (RFC 3461 Section 4.4)",
            ));
        }
        if s.len() > 100 {
            return Err(ValidationError::new(
                "ENVID value must be at most 100 characters before xtext encoding \
                 (RFC 3461 Section 4.4)",
            ));
        }
        Ok(Self(s))
    }

    /// Return the value as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl AsRef<str> for EnvidValue {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for EnvidValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl TryFrom<String> for EnvidValue {
    type Error = ValidationError;
    fn try_from(s: String) -> Result<Self, ValidationError> {
        Self::new(s)
    }
}

impl TryFrom<&str> for EnvidValue {
    type Error = ValidationError;
    fn try_from(s: &str) -> Result<Self, ValidationError> {
        Self::new(s)
    }
}

impl From<EnvidValue> for String {
    fn from(e: EnvidValue) -> Self {
        e.into_inner()
    }
}

// ============================================================================
// XtextSafe — RFC 5321 Section 4.1.2
// ============================================================================

/// A validated printable US-ASCII string for use in SMTP command arguments.
///
/// RFC 5321 Section 4.1.2: SMTP `String` arguments must contain only
/// printable US-ASCII characters (0x20-0x7E), excluding control characters.
/// Must also be non-empty.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(try_from = "String", into = "String"))]
pub struct XtextSafe(String);

impl XtextSafe {
    /// Consume and return the inner `String`.
    pub fn into_inner(self) -> String {
        self.0
    }

    /// Create a new `XtextSafe` after validating printable ASCII constraints.
    pub fn new(s: impl Into<String>) -> Result<Self, ValidationError> {
        let s = s.into();
        if s.is_empty() {
            return Err(ValidationError::new(
                "SMTP query argument must not be empty \
                 (RFC 5321 Sections 4.1.1.6-4.1.1.7)",
            ));
        }
        for &b in s.as_bytes() {
            if b < 0x20 || b == 0x7F {
                return Err(ValidationError::new(format!(
                    "SMTP argument contains control character (byte 0x{b:02X}); \
                     only printable US-ASCII is permitted (RFC 5321 Section 4.1.2)"
                )));
            }
            if b > 0x7F {
                return Err(ValidationError::new(
                    "SMTP argument contains non-ASCII characters; \
                     only printable US-ASCII is permitted (RFC 5321 Section 4.1.2)",
                ));
            }
        }
        // Note: CR (0x0D) and LF (0x0A) are already rejected by the
        // `b < 0x20` control-character check above, so no separate
        // CR/LF guard is needed.
        Ok(Self(s))
    }

    /// Return the value as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl AsRef<str> for XtextSafe {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for XtextSafe {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl TryFrom<String> for XtextSafe {
    type Error = ValidationError;
    fn try_from(s: String) -> Result<Self, ValidationError> {
        Self::new(s)
    }
}

impl TryFrom<&str> for XtextSafe {
    type Error = ValidationError;
    fn try_from(s: &str) -> Result<Self, ValidationError> {
        Self::new(s)
    }
}

impl From<XtextSafe> for String {
    fn from(x: XtextSafe) -> Self {
        x.into_inner()
    }
}

// ============================================================================
// Validation helpers (internal)
// ============================================================================

/// Validate RFC 5321 Section 4.1.2 `Domain` syntax.
fn validate_domain_syntax(domain: &str) -> Result<(), ValidationError> {
    if domain.is_empty() {
        return Err(ValidationError::new(
            "domain must not be empty (RFC 5321 Section 4.1.2)",
        ));
    }
    // RFC 5321 Section 4.5.3.1.2: domain ≤ 255 octets.
    if domain.len() > 255 {
        return Err(ValidationError::new(format!(
            "domain exceeds 255-octet limit (RFC 5321 Section 4.5.3.1.2): {} octets",
            domain.len()
        )));
    }
    if domain.starts_with('[') && domain.ends_with(']') {
        return Err(ValidationError::new(
            "value is an address-literal, not a domain (RFC 5321 Section 4.1.2)",
        ));
    }
    for label in domain.split('.') {
        validate_domain_label(label)?;
    }
    Ok(())
}

/// Validate an SMTP mailbox/source-route domain when RFC 6531 SMTPUTF8 is in use.
///
/// RFC 6531 Section 3.3 extends RFC 5321 Section 4.1.2 `sub-domain` with
/// `U-label`, so mailbox domains may contain UTF-8 labels. ASCII labels still
/// follow the RFC 5321 LDH rules, while non-ASCII labels are accepted
/// conservatively for SMTPUTF8 paths.
pub(crate) fn validate_smtputf8_domain_syntax(domain: &str) -> Result<(), ValidationError> {
    if domain.is_empty() {
        return Err(ValidationError::new(
            "domain must not be empty (RFC 5321 Section 4.1.2 / RFC 6531 Section 3.3)",
        ));
    }
    // RFC 5321 Section 4.5.3.1.2 applies to mailbox domains as well.
    if domain.len() > 255 {
        return Err(ValidationError::new(format!(
            "domain exceeds 255-octet limit (RFC 5321 Section 4.5.3.1.2): {} octets",
            domain.len()
        )));
    }
    if domain.starts_with('[') && domain.ends_with(']') {
        return Err(ValidationError::new(
            "value is an address-literal, not a domain (RFC 5321 Section 4.1.2)",
        ));
    }

    for label in domain.split('.') {
        if label.is_empty() {
            return Err(ValidationError::new(
                "domain contains an empty label (RFC 5321 Section 4.1.2 / RFC 6531 Section 3.3)",
            ));
        }
        if label.is_ascii() {
            validate_domain_label(label)?;
            continue;
        }
        // RFC 6531 Section 3.3 extends `sub-domain` with `U-label`.
        // RFC 5321 Section 4.5.3.1.2 / RFC 1035 Section 2.3.4: each label
        // must be at most 63 octets, regardless of whether it contains
        // non-ASCII code points.
        if label.len() > 63 {
            return Err(ValidationError::new(format!(
                "domain label exceeds 63-octet limit \
                 (RFC 5321 Section 4.5.3.1.2 / RFC 6531 Section 3.3): {} octets",
                label.len()
            )));
        }
        // Preserve the RFC 5321 hyphen placement rule for the ASCII LDH
        // portion while allowing UTF-8 code points in the label body.
        if label.starts_with('-') || label.ends_with('-') {
            return Err(ValidationError::new(
                "domain labels must begin and end with a letter or digit \
                 (RFC 5321 Section 4.1.2 / RFC 6531 Section 3.3)",
            ));
        }
        for ch in label.chars() {
            if ch.is_ascii() && !(ch.is_ascii_alphanumeric() || ch == '-') {
                return Err(ValidationError::new(format!(
                    "domain label contains invalid character {ch:?}; \
                     only letters, digits, '-', and UTF-8 U-label code points \
                     are permitted (RFC 5321 Section 4.1.2 / RFC 6531 Section 3.3)"
                )));
            }
        }
    }
    Ok(())
}

/// Validate a single DNS label per RFC 5321 Section 4.1.2 / RFC 1035 Section 2.3.4.
fn validate_domain_label(label: &str) -> Result<(), ValidationError> {
    if label.is_empty() {
        return Err(ValidationError::new(
            "domain contains an empty label (RFC 5321 Section 4.1.2)",
        ));
    }
    // RFC 1035 Section 2.3.4: labels are at most 63 octets.
    if label.len() > 63 {
        return Err(ValidationError::new(format!(
            "domain label exceeds 63-octet limit \
             (RFC 1035 Section 2.3.4 / RFC 5321 Section 4.1.2): {} octets",
            label.len()
        )));
    }
    let bytes = label.as_bytes();
    // RFC 5321 Section 4.1.2: Let-dig = ALPHA / DIGIT
    if !bytes[0].is_ascii_alphanumeric() || !bytes[bytes.len() - 1].is_ascii_alphanumeric() {
        return Err(ValidationError::new(
            "domain labels must begin and end with a letter or digit \
             (RFC 5321 Section 4.1.2)",
        ));
    }
    // RFC 5321 Section 4.1.2: Ldh-str = *( ALPHA / DIGIT / "-" ) Let-dig
    for &b in bytes {
        if !(b.is_ascii_alphanumeric() || b == b'-') {
            return Err(ValidationError::new(format!(
                "domain label contains invalid character {:?}; \
                 only letters, digits, and '-' are permitted (RFC 5321 Section 4.1.2)",
                b as char
            )));
        }
    }
    Ok(())
}

/// Validate RFC 5321 Section 4.1.3 `address-literal` syntax.
fn validate_address_literal_syntax(literal: &str) -> Result<(), ValidationError> {
    // RFC 5321 Section 4.5.3.1.2: ≤ 255 octets.
    if literal.len() > 255 {
        return Err(ValidationError::new(format!(
            "address-literal exceeds 255-octet limit \
             (RFC 5321 Section 4.5.3.1.2): {} octets",
            literal.len()
        )));
    }

    let Some(body) = literal.strip_prefix('[').and_then(|s| s.strip_suffix(']')) else {
        return Err(ValidationError::new(
            "address-literal must be enclosed in '[' and ']' (RFC 5321 Section 4.1.3)",
        ));
    };

    if body.is_empty() {
        return Err(ValidationError::new(
            "address-literal must not be empty (RFC 5321 Section 4.1.3)",
        ));
    }

    // IPv4
    if body.parse::<Ipv4Addr>().is_ok() {
        return Ok(());
    }

    // IPv6
    if body.len() >= 5 && body[..5].eq_ignore_ascii_case("IPv6:") {
        return body[5..].parse::<Ipv6Addr>().map(|_| ()).map_err(|_| {
            ValidationError::new("invalid IPv6 address in address-literal (RFC 5321 Section 4.1.3)")
        });
    }

    // General-address-literal = Standardized-tag ":" 1*dcontent
    let Some((tag, value)) = body.split_once(':') else {
        return Err(ValidationError::new(
            "address-literal must be IPv4, IPv6, or generalized tag:value syntax \
             (RFC 5321 Section 4.1.3)",
        ));
    };

    validate_ldh_str(tag)?;

    if value.is_empty() {
        return Err(ValidationError::new(
            "generalized address-literal must contain data after ':' \
             (RFC 5321 Section 4.1.3)",
        ));
    }
    for &b in value.as_bytes() {
        // RFC 5321 Section 4.1.3: dcontent = %d33-90 / %d94-126.
        if !((33..=90).contains(&b) || (94..=126).contains(&b)) {
            return Err(ValidationError::new(format!(
                "address-literal contains invalid data byte 0x{b:02X} \
                 (RFC 5321 Section 4.1.3)"
            )));
        }
    }
    Ok(())
}

/// Validate an Ldh-str tag per RFC 5321 Section 4.1.3.
fn validate_ldh_str(tag: &str) -> Result<(), ValidationError> {
    if tag.is_empty() {
        return Err(ValidationError::new(
            "generalized address-literal tag must not be empty (RFC 5321 Section 4.1.3)",
        ));
    }
    let bytes = tag.as_bytes();
    // RFC 5321 Section 4.1.3: Standardized-tag = Ldh-str, and Ldh-str is
    // `*( ALPHA / DIGIT / "-" ) Let-dig`, so only the trailing byte is
    // required to be alphanumeric.
    if !bytes[bytes.len() - 1].is_ascii_alphanumeric() {
        return Err(ValidationError::new(
            "generalized address-literal tag must end with a letter or digit \
             (RFC 5321 Section 4.1.3: Standardized-tag = Ldh-str)",
        ));
    }
    for &b in bytes {
        if !(b.is_ascii_alphanumeric() || b == b'-') {
            return Err(ValidationError::new(format!(
                "generalized address-literal tag contains invalid character {:?} \
                 (RFC 5321 Section 4.1.3)",
                b as char
            )));
        }
    }
    Ok(())
}

/// RFC 5321 Section 4.1.2: `Path = "<" [ A-d-l ":" ] Mailbox ">"`.
///
/// The obsolete `A-d-l` source route MUST be accepted, SHOULD NOT be
/// generated, and SHOULD be ignored. This helper validates any source route
/// that is present and returns the mailbox portion to validate and store.
fn strip_obsolete_source_route(address: &str) -> Result<&str, ValidationError> {
    if !address.starts_with('@') {
        return Ok(address);
    }

    let Some((route, mailbox)) = address.split_once(':') else {
        return Err(ValidationError::new(
            "obsolete source route must end with ':' before the mailbox \
             (RFC 5321 Section 4.1.2)",
        ));
    };
    if mailbox.is_empty() {
        return Err(ValidationError::new(
            "obsolete source route must be followed by a mailbox \
             (RFC 5321 Section 4.1.2)",
        ));
    }

    for at_domain in route.split(',') {
        let Some(domain) = at_domain.strip_prefix('@') else {
            return Err(ValidationError::new(
                "obsolete source route entries must be @domain tokens \
                 (RFC 5321 Section 4.1.2)",
            ));
        };
        validate_smtputf8_domain_syntax(domain)?;
    }

    Ok(mailbox)
}

/// Validate RFC 5321 Section 4.1.2 `Mailbox` syntax.
fn validate_mailbox_syntax(address: &str) -> Result<(), ValidationError> {
    // RFC 5321 Section 4.1.2 defines `Path = "<" [ A-d-l ":" ] Mailbox ">"`,
    // so the 256-octet path limit includes any obsolete source route that is
    // present on the input.
    if address.len() > 254 {
        return Err(ValidationError::new(format!(
            "mailbox exceeds 256-octet path limit including <> \
             (RFC 5321 Section 4.5.3.1.3): {} octets",
            address.len() + 2
        )));
    }

    let address = strip_obsolete_source_route(address)?;

    if address != address.trim() {
        return Err(ValidationError::new(
            "mailbox must not contain leading or trailing whitespace \
             (RFC 5321 Section 4.1.2)",
        ));
    }

    // Parse as an addr-spec and reject display-name forms.
    match address.parse::<daaki_message::Address>() {
        Ok(parsed) if parsed.name.is_none() && parsed.email == address => {}
        Ok(_) => {
            return Err(ValidationError::new(
                "mailbox must be a bare addr-spec, not a name-addr or comment form \
                 (RFC 5321 Section 4.1.2)",
            ));
        }
        Err(err) => {
            return Err(ValidationError::new(format!(
                "mailbox is syntactically invalid: {err} (RFC 5321 Section 4.1.2)"
            )));
        }
    }

    // RFC 5321 Section 4.1.3 defines SMTP address-literals more narrowly than
    // RFC 5322 header-address domain-literals. The shared message parser is
    // intentionally liberal for header syntax, so SMTP mailbox validation must
    // re-check any bracketed domain against RFC 5321's IPv4 / IPv6 /
    // generalized-literal grammar.
    if let Some(at_pos) = address.rfind('@') {
        let local_part = &address[..at_pos];
        let domain = &address[at_pos + 1..];
        if local_part.starts_with('"') && local_part.ends_with('"') {
            validate_smtp_quoted_local_part(local_part)?;
        }
        if domain.starts_with('[') && domain.ends_with(']') {
            validate_address_literal_syntax(domain)?;
        }

        // RFC 5321 Section 4.5.3.1.1: local-part ≤ 64 octets.
        if local_part.len() > 64 {
            return Err(ValidationError::new(format!(
                "local-part exceeds 64-octet limit \
                 (RFC 5321 Section 4.5.3.1.1): {} octets",
                local_part.len()
            )));
        }
    }

    Ok(())
}

/// Validates an SMTP quoted local-part per RFC 5321 Section 4.1.2.
///
/// SMTP quoted local-parts use `Quoted-string = DQUOTE *QcontentSMTP DQUOTE`,
/// where `QcontentSMTP = qtextSMTP / quoted-pairSMTP`. Unlike RFC 5322 header
/// quoted-strings, SMTP does not permit HTAB/FWS inside a mailbox local-part.
/// RFC 6531 Section 3.3 extends `qtextSMTP` with UTF-8 non-ASCII, but it does
/// not extend `quoted-pairSMTP`, which remains ASCII-only.
///
/// # References
/// - RFC 5321 Section 4.1.2
/// - RFC 6531 Section 3.3
fn validate_smtp_quoted_local_part(local_part: &str) -> Result<(), ValidationError> {
    let Some(inner) = local_part
        .strip_prefix('"')
        .and_then(|value| value.strip_suffix('"'))
    else {
        return Err(ValidationError::new(
            "quoted local-part must be enclosed in double quotes \
             (RFC 5321 Section 4.1.2)",
        ));
    };

    let bytes = inner.as_bytes();
    let mut index = 0;
    while index < bytes.len() {
        let byte = bytes[index];
        if byte == b'\\' {
            index += 1;
            if index >= bytes.len() {
                return Err(ValidationError::new(
                    "quoted local-part has trailing backslash \
                     (RFC 5321 Section 4.1.2 quoted-pairSMTP)",
                ));
            }

            let escaped = bytes[index];
            if !(0x20..=0x7E).contains(&escaped) {
                return Err(ValidationError::new(format!(
                    "quoted local-part contains invalid escaped byte 0x{escaped:02X}; \
                     quoted-pairSMTP permits only ASCII space or VCHAR \
                     (RFC 5321 Section 4.1.2)"
                )));
            }
        } else if byte == b'"' || byte == b'\\' {
            return Err(ValidationError::new(
                "quoted local-part contains an unescaped quote or backslash \
                 (RFC 5321 Section 4.1.2 qtextSMTP)",
            ));
        } else if byte == b'\t' || byte < 0x20 || byte == 0x7F {
            return Err(ValidationError::new(format!(
                "quoted local-part contains control character 0x{byte:02X}; \
                 qtextSMTP permits ASCII space/graphics or UTF-8 non-ASCII only \
                 (RFC 5321 Section 4.1.2 / RFC 6531 Section 3.3)"
            )));
        }
        index += 1;
    }

    Ok(())
}

#[cfg(test)]
#[path = "validated_tests.rs"]
mod tests;