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
//! SMTP response parser.
//!
//! Parses multi-line SMTP responses (RFC 5321 Section 4.2) into [`SmtpResponse`],
//! including optional enhanced status codes (RFC 1893 / RFC 2034).
//!
//! # Wire format
//!
//! ```text
//! reply-line = reply-code [ SP textstring ] CRLF
//! reply-code = 3DIGIT             ; RFC 5321 Section 4.2
//! ```
//!
//! Multi-line responses use `-` after the code for continuation lines
//! and SP (or end-of-line) for the final line.

use nom::IResult;
#[cfg(any(test, fuzzing))]
use nom::{
    bytes::streaming::{tag, take_while},
    combinator::opt,
};

use crate::future_release::parse_rfc3339_to_utc_key;
use crate::types::{
    AuthMechanism, DomainOrLiteral, EnhancedStatusCode, ServerCapabilities, SmtpExtension,
    SmtpResponse,
};

/// Parse a complete SMTP response (one or more lines, terminated by a final line
/// with SP or CRLF after the reply code).
///
/// RFC 5321 Section 4.2: Multi-line replies use `-` after the code for continuation
/// and SP for the final line. The code on the final line is used for the response.
/// The first enhanced status code found (RFC 2034 Section 3) is preserved.
#[cfg(any(test, fuzzing))]
pub(crate) fn parse_response(input: &[u8]) -> IResult<&[u8], SmtpResponse> {
    let mut remaining = input;
    let mut lines: Vec<String> = Vec::new();
    let mut first_enhanced: Option<EnhancedStatusCode> = None;
    let mut first_code: Option<u16> = None;
    let mut final_code: u16;

    loop {
        // Parse the 3-digit reply code
        let (rest, code) = reply_code(remaining)?;

        // RFC 5321 Section 4.2: "In a multiline reply, the reply code on
        // each of the lines MUST be the same."
        if let Some(expected) = first_code {
            if code != expected {
                return Err(nom::Err::Error(nom::error::Error::new(
                    remaining,
                    nom::error::ErrorKind::Verify,
                )));
            }
        } else {
            first_code = Some(code);
        }

        // Determine if this is a continuation line (hyphen) or final line (SP or CRLF)
        // RFC 5321 Section 4.2: continuation lines have `-`, final line has SP or goes
        // directly to CRLF.
        if rest.is_empty() {
            // Need more data to determine separator
            return Err(nom::Err::Incomplete(nom::Needed::Unknown));
        }

        let separator = rest[0];
        let is_continuation = separator == b'-';
        let has_space = separator == b' ';

        // Postel's law (RFC 1122 Section 1.2.2): accept bare LF (\n) as
        // a line terminator from non-conformant servers, in addition to \r
        // (which precedes the canonical CRLF).
        if !is_continuation && !has_space && separator != b'\r' && separator != b'\n' {
            return Err(nom::Err::Error(nom::error::Error::new(
                rest,
                nom::error::ErrorKind::Char,
            )));
        }

        // Skip separator (hyphen or space), but not if the separator is
        // \r (CRLF follows) or \n (bare LF line ending).
        let rest = if separator == b'\r' || separator == b'\n' {
            rest
        } else {
            &rest[1..]
        };

        // Try to parse an enhanced status code at the start of the text.
        // RFC 2034 Section 3: enhanced code appears after the reply code and separator.
        // RFC 2034 Section 4: the enhanced code class MUST match the reply code class.
        let pre_esc = rest;
        let (rest_after_esc, enhanced) = opt(enhanced_status_code_with_trailing_space)(rest)?;

        // RFC 2034 Section 3: "Any additional text … if any, SHOULD be a
        // complete line." — try enhanced code without trailing space when
        // the code is the entire text (next byte is a line terminator).
        // Accept both \r (CRLF) and \n (bare LF) per Postel's law
        // (RFC 1122 Section 1.2.2), consistent with bare-LF tolerance
        // at line 73 above.
        let (rest_after_esc, enhanced) = if enhanced.is_none() {
            match enhanced_status_code(rest) {
                Ok((remaining, esc))
                    if remaining.first().is_some_and(|&b| b == b'\r' || b == b'\n') =>
                {
                    (remaining, Some(esc))
                }
                _ => (rest_after_esc, None),
            }
        } else {
            (rest_after_esc, enhanced)
        };

        let text_start = if let Some(ref esc) = enhanced {
            let reply_class = code / 100;
            if u16::from(esc.class) == reply_class {
                // Class matches — keep enhanced code, text starts after it.
                if first_enhanced.is_none() {
                    first_enhanced = Some(*esc);
                }
                rest_after_esc
            } else {
                // Class mismatch (RFC 2034 §4) — discard enhanced code,
                // include its digits in the text.
                pre_esc
            }
        } else {
            rest_after_esc
        };

        // Collect the remaining text up to line terminator.
        let (rest, text_bytes) = take_while(|b: u8| b != b'\r' && b != b'\n')(text_start)?;

        // Consume line terminator: CRLF (RFC 5321 Section 2.3.8) or
        // bare LF (Postel's law — tolerate non-conformant servers).
        let rest = if rest.starts_with(b"\r\n") {
            &rest[2..]
        } else if rest.starts_with(b"\n") {
            &rest[1..]
        } else {
            return Err(nom::Err::Incomplete(nom::Needed::Unknown));
        };

        // Lossy-convert text from bytes to String (servers may send non-UTF-8 data)
        let text = String::from_utf8_lossy(text_bytes).into_owned();
        lines.push(text);

        final_code = code;
        remaining = rest;

        if !is_continuation {
            break;
        }
    }

    Ok((
        remaining,
        SmtpResponse {
            code: final_code,
            enhanced_code: first_enhanced,
            lines,
        },
    ))
}

/// Parse a single SMTP reply code (3 ASCII digits).
///
/// RFC 5321 Section 4.2: `reply-code = %x32-35 %x30-35 %x30-39`
/// - First digit: 2-5 (severity class)
/// - Second digit: 0-9 (Postel's law — relaxed from strict 0-5)
/// - Third digit: 0-9 (fine-grained status)
#[cfg(any(test, fuzzing))]
pub(crate) fn reply_code(input: &[u8]) -> IResult<&[u8], u16> {
    // We need exactly 3 bytes
    if input.len() < 3 {
        return Err(nom::Err::Incomplete(nom::Needed::new(3 - input.len())));
    }

    let d0 = input[0];
    let d1 = input[1];
    let d2 = input[2];

    // All three must be ASCII digits
    if !d0.is_ascii_digit() || !d1.is_ascii_digit() || !d2.is_ascii_digit() {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Digit,
        )));
    }

    // RFC 5321 Section 4.2: reply-code = %x32-35 %x30-35 %x30-39
    // Strict ABNF limits the second digit to 0-5, but per Postel's law
    // we accept 0-9 to tolerate non-conformant servers.  The first digit
    // is still restricted to 2-5 (valid reply classes).
    if !(b'2'..=b'5').contains(&d0) || !d1.is_ascii_digit() {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Verify,
        )));
    }

    let code = u16::from(d0 - b'0') * 100 + u16::from(d1 - b'0') * 10 + u16::from(d2 - b'0');

    Ok((&input[3..], code))
}

/// Generate an enhanced status code parser for a given nom mode (streaming or complete).
///
/// RFC 1893 Section 2: `status-code = class "." subject "." detail`
/// - class: single digit, one of 2, 4, 5
/// - subject: 1-3 digit number
/// - detail: 1-3 digit number
///
/// RFC 2034 Section 3: enhanced status codes appear in SMTP responses
/// after the three-digit reply code.
macro_rules! define_enhanced_status_code_parser {
    ($name:ident, $(#[$meta:meta])*, $one_of:path, $tag:path, $take_while1:path) => {
        $(#[$meta])*
        fn $name(input: &[u8]) -> IResult<&[u8], EnhancedStatusCode> {
            // Parse class digit (must be 2, 4, or 5) — RFC 1893 Section 2
            let (rest, class_char) = $one_of("245")(input)?;
            // one_of("245") guarantees the digit is ASCII 2/4/5; the subtraction yields {2, 4, 5}
            #[allow(clippy::cast_possible_truncation)]
            let class = (class_char as u32 - '0' as u32) as u8;

            // Parse '.'
            let (rest, _) = $tag(b".")(rest)?;

            // Parse subject (1-3 digits) — RFC 1893 Section 2
            let (rest, subject_bytes) = $take_while1(|b: u8| b.is_ascii_digit())(rest)?;
            if subject_bytes.len() > 3 {
                return Err(nom::Err::Error(nom::error::Error::new(
                    input,
                    nom::error::ErrorKind::TooLarge,
                )));
            }
            let subject = parse_digits(subject_bytes);

            // Parse '.'
            let (rest, _) = $tag(b".")(rest)?;

            // Parse detail (1-3 digits) — RFC 1893 Section 2
            let (rest, detail_bytes) = $take_while1(|b: u8| b.is_ascii_digit())(rest)?;
            if detail_bytes.len() > 3 {
                return Err(nom::Err::Error(nom::error::Error::new(
                    input,
                    nom::error::ErrorKind::TooLarge,
                )));
            }
            let detail = parse_digits(detail_bytes);

            Ok((
                rest,
                EnhancedStatusCode {
                    class,
                    subject,
                    detail,
                },
            ))
        }
    };
}

define_enhanced_status_code_parser!(
    enhanced_status_code,
    #[cfg(any(test, fuzzing))],
    nom::character::streaming::one_of,
    nom::bytes::streaming::tag,
    nom::bytes::streaming::take_while1
);

/// Parse an enhanced status code followed by a trailing space.
///
/// This ensures we only consume an enhanced code when it's properly delimited,
/// preventing false matches on strings like `2.0` in the text body.
///
/// RFC 2034 Section 3: The enhanced status code is separated from the
/// following text by a single space.
#[cfg(any(test, fuzzing))]
fn enhanced_status_code_with_trailing_space(input: &[u8]) -> IResult<&[u8], EnhancedStatusCode> {
    let (rest, esc) = enhanced_status_code(input)?;
    // Must be followed by a space to be a valid enhanced code in a response line
    let (rest, _) = tag(b" ")(rest)?;
    Ok((rest, esc))
}

/// Convert a slice of ASCII digit bytes to a u16 per RFC 1893 Section 2.
///
/// Used to parse the subject and detail components of enhanced status codes
/// (`class.subject.detail`), where each component is 1-3 ASCII digits.
///
/// # Panics
///
/// This function is only called with validated digit slices of length 1-3,
/// so overflow is impossible for u16 (max value 999).
fn parse_digits(bytes: &[u8]) -> u16 {
    let mut val: u16 = 0;
    for &b in bytes {
        // Caller guarantees all bytes are ASCII digits
        val = val * 10 + u16::from(b - b'0');
    }
    val
}

/// Merge new AUTH mechanisms into an existing `SmtpExtension::Auth` entry,
/// or push a new one if none exists yet.
///
/// RFC 4954 Section 3 / RFC 5321 Section 4.1.1.1: servers may advertise
/// AUTH capabilities across multiple EHLO lines (e.g. the deprecated
/// `AUTH=PLAIN LOGIN` form from RFC 2554 Section 3 alongside the standard
/// `AUTH PLAIN LOGIN` form). Mechanisms are de-duplicated using
/// case-insensitive comparison per RFC 4954 Section 3.
fn merge_or_push_auth(extensions: &mut Vec<SmtpExtension>, new_mechs: Vec<AuthMechanism>) {
    // Look for an existing Auth entry to merge into.
    for ext in extensions.iter_mut() {
        if let SmtpExtension::Auth(existing) = ext {
            for mech in new_mechs {
                // RFC 4954 Section 3: mechanism names are case-insensitive;
                // avoid duplicates using eq_mechanism.
                if !existing.iter().any(|m| m.eq_mechanism(&mech)) {
                    existing.push(mech);
                }
            }
            return;
        }
    }
    // No existing Auth entry — create one.
    extensions.push(SmtpExtension::Auth(new_mechs));
}

/// Parsed representation of one EHLO capability line.
///
/// Keeping unknown tokens distinct lets the caller decide whether to preserve
/// the original line as `Other(...)` or fall back to greeting-name parsing.
enum ParsedEhloLine {
    Extension(SmtpExtension),
    Auth(Vec<AuthMechanism>),
    Unknown,
}

/// Parsed form of RFC 2852 Section 2's optional `min-by-time` EHLO parameter.
enum DeliverByEhloMinimum {
    /// RFC 2852 Section 2 allows the server to omit `min-by-time`.
    Unspecified,
    /// RFC 2852 Section 2 advertises a fixed minimum return-mode by-time.
    Minimum(u64),
}

/// Parse an EHLO decimal parameter constrained to 1-9 ASCII digits.
///
/// RFC 2852 Section 2 (`min-by-time = [1*9DIGIT]`) and RFC 4865 Section 3
/// (`future-release-integer = %x31-39 *8DIGIT`) both cap advertised numeric
/// values at 9 digits. `allow_zero` handles the DELIVERBY minimum's optional
/// zero value while still rejecting zero for FUTURERELEASE's required
/// positive interval.
fn parse_ehlo_decimal_1_to_9_digits(s: &str, allow_zero: bool) -> Option<u64> {
    if s.is_empty() || s.len() > 9 || !s.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    let value = s.parse::<u64>().ok()?;
    if !allow_zero && value == 0 {
        return None;
    }
    Some(value)
}

/// Parse the DELIVERBY EHLO parameter.
///
/// RFC 2852 Section 2:
/// `deliverby-param = min-by-time *( "," extension-token )`
/// `min-by-time = [1*9DIGIT]`
///
/// The numeric minimum is optional and may be followed by extension tokens.
/// Return `None` when the syntax is malformed so the caller can preserve the
/// original EHLO line as `Other(...)` instead of advertising a weakened
/// capability.
fn parse_deliverby_minimum(params: &str) -> Option<DeliverByEhloMinimum> {
    let mut segments = params.split(',');
    let first = segments.next().unwrap_or_default().trim();

    let minimum = if first.is_empty() {
        DeliverByEhloMinimum::Unspecified
    } else {
        DeliverByEhloMinimum::Minimum(parse_ehlo_decimal_1_to_9_digits(first, true)?)
    };

    // RFC 2852 Section 2: trailing extension tokens are optional. Preserve
    // Postel-style tolerance for surrounding ASCII whitespace, but reject
    // empty or syntactically invalid tokens so malformed input does not
    // silently degrade into a valid DELIVERBY advertisement.
    if segments.any(|segment| !is_valid_deliverby_extension_token(segment.trim())) {
        return None;
    }

    Some(minimum)
}

/// RFC 2852 Section 2:
/// `extension-token = 1*<any CHAR excluding SP, COMMA and all control characters (US ASCII 0-31 inclusive)>`
fn is_valid_deliverby_extension_token(token: &str) -> bool {
    !token.is_empty()
        && token.is_ascii()
        && token.bytes().all(|b| b != b' ' && b != b',' && b > 0x1F)
}

/// Parse the FUTURERELEASE EHLO parameters.
///
/// RFC 4865 Section 3 requires both the maximum hold interval and maximum
/// hold-until datetime on the EHLO line:
/// `line = "250-FUTURERELEASE" SP max-future-release-interval SP max-future-release-date-time`
fn parse_future_release_limits(params: &str) -> Option<(u64, String)> {
    let mut parts = params.split_whitespace();
    let interval = parse_ehlo_decimal_1_to_9_digits(parts.next()?, false)?;
    let datetime = parts.next()?;
    // RFC 4865 Section 3 defines max-future-release-date-time as RFC 3339
    // `date-time`. Preserve malformed EHLO lines as `Other(...)` instead of
    // weakening them into FUTURERELEASE support with a bogus bound.
    parse_rfc3339_to_utc_key(datetime)?;
    if parts.next().is_some() {
        return None;
    }
    Some((interval, datetime.to_owned()))
}

/// Parse a single EHLO capability line into a known SMTP extension.
///
/// RFC 5321 Section 4.1.1.1 advertises one extension keyword per line after
/// the greeting. Keywords are case-insensitive per RFC 5321 Section 2.4.
#[allow(clippy::too_many_lines)]
fn parse_ehlo_extension_line(line: &str) -> ParsedEhloLine {
    // Split on first ASCII whitespace to get keyword and optional
    // parameters. Some non-conformant servers use HTAB instead of SP;
    // accept that for interoperability.
    let (keyword, params) = match line.find(|c: char| c.is_ascii_whitespace()) {
        Some(pos) => (&line[..pos], Some(line[pos + 1..].trim())),
        None => (line, None),
    };

    // RFC 5321 Section 2.4: SMTP keywords are case-insensitive.
    let keyword_upper = keyword.to_ascii_uppercase();

    // RFC 2554 Section 3 (obsoleted by RFC 4954 Section 3): some legacy
    // servers advertise AUTH using the deprecated "AUTH=PLAIN LOGIN"
    // form instead of the standard "AUTH PLAIN LOGIN". Normalize by
    // treating the token after '=' as the first SASL mechanism.
    if keyword_upper.starts_with("AUTH=") && keyword_upper.len() > 5 {
        let first_mech = &keyword[5..];
        let all_mechs = match params {
            Some(p) if !p.is_empty() => format!("{first_mech} {p}"),
            _ => first_mech.to_owned(),
        };
        return match parse_auth_mechanism_list(&all_mechs) {
            Some(mechanisms) => ParsedEhloLine::Auth(mechanisms),
            None => ParsedEhloLine::Unknown,
        };
    }

    let has_params = params.is_some_and(|p| !p.is_empty());

    let extension = match keyword_upper.as_str() {
        // RFC 1652 Section 2: the 8BITMIME EHLO keyword has no parameters.
        "8BITMIME" => {
            if has_params {
                return ParsedEhloLine::Unknown;
            }
            SmtpExtension::EightBitMime
        }
        // RFC 1854 Section 2: the PIPELINING EHLO keyword has no parameters.
        "PIPELINING" => {
            if has_params {
                return ParsedEhloLine::Unknown;
            }
            SmtpExtension::Pipelining
        }
        // RFC 1870: Message Size Declaration
        "SIZE" => {
            let size_limit = match params.and_then(|p| if p.is_empty() { None } else { Some(p) }) {
                None => None,
                Some(param) => match param
                    .bytes()
                    .all(|b| b.is_ascii_digit())
                    .then(|| param.parse::<u64>())
                {
                    // RFC 1870 Section 5: a value of 0 means the server
                    // does not have a fixed maximum message size.
                    Some(Ok(0)) => None,
                    Some(Ok(n)) => Some(n),
                    // RFC 1870 Section 3 defines the parameter as a decimal
                    // maximum-size value. Preserve malformed EHLO lines as
                    // unknown instead of weakening them into "no limit".
                    Some(Err(_)) | None => return ParsedEhloLine::Unknown,
                },
            };
            SmtpExtension::Size(size_limit)
        }
        // RFC 3207 Section 2: the STARTTLS EHLO keyword has no parameters.
        "STARTTLS" => {
            if has_params {
                return ParsedEhloLine::Unknown;
            }
            SmtpExtension::StartTls
        }
        // RFC 4954 Section 3: SMTP Service Extension for Authentication.
        // The AUTH keyword MUST be followed by at least one SASL mechanism
        // name. Empty AUTH lines are treated as unknown so callers can
        // preserve the original server text.
        "AUTH" => {
            let Some(raw_mechanisms) = params.filter(|p| !p.is_empty()) else {
                return ParsedEhloLine::Unknown;
            };
            let Some(mechanisms) = parse_auth_mechanism_list(raw_mechanisms) else {
                return ParsedEhloLine::Unknown;
            };
            return ParsedEhloLine::Auth(mechanisms);
        }
        // RFC 3030 Section 2 advertises CHUNKING as a bare EHLO keyword.
        "CHUNKING" => {
            if has_params {
                return ParsedEhloLine::Unknown;
            }
            SmtpExtension::Chunking
        }
        // RFC 3030 Section 3: no parameter is used with the BINARYMIME keyword.
        // RFC 1830 used the legacy "BINARY" spelling for the same extension.
        "BINARYMIME" | "BINARY" => {
            if has_params {
                return ParsedEhloLine::Unknown;
            }
            SmtpExtension::BinaryMime
        }
        // RFC 6531 Section 3.2: clients MUST ignore stray SMTPUTF8 EHLO parameters.
        // Treat the capability as present even if a non-conformant server adds them.
        "SMTPUTF8" => SmtpExtension::SmtpUtf8,
        // RFC 2034 Section 3: the ENHANCEDSTATUSCODES EHLO keyword has no parameters.
        "ENHANCEDSTATUSCODES" => {
            if has_params {
                return ParsedEhloLine::Unknown;
            }
            SmtpExtension::EnhancedStatusCodes
        }
        // Some SMTP servers advertise a legacy, non-standard SASL-IR
        // keyword. RFC 4954 Section 4 already permits AUTH initial
        // responses without a separate SMTP extension, but we preserve
        // the EHLO keyword for compatibility and introspection.
        "SASL-IR" => SmtpExtension::SaslIr,
        // RFC 3461: Delivery Status Notifications
        "DSN" => SmtpExtension::Dsn,
        // RFC 8689: REQUIRETLS per-message TLS enforcement
        "REQUIRETLS" => SmtpExtension::RequireTls,
        // RFC 4865: FUTURERELEASE scheduled delivery
        "FUTURERELEASE" => {
            // RFC 4865 Section 3 makes both EHLO parameters mandatory.
            let Some(raw_params) = params.and_then(|p| if p.is_empty() { None } else { Some(p) })
            else {
                return ParsedEhloLine::Unknown;
            };
            // Some non-conformant servers separate the two parameters with
            // HTAB or repeated SP; recover them from ASCII whitespace, but
            // still require both mandatory fields to be present.
            let Some((max_interval, max_datetime)) = parse_future_release_limits(raw_params) else {
                return ParsedEhloLine::Unknown;
            };
            SmtpExtension::FutureRelease {
                max_interval: Some(max_interval),
                max_datetime: Some(max_datetime),
            }
        }
        // RFC 2852: DELIVERBY time-bound delivery
        "DELIVERBY" => {
            let max_seconds = match params.and_then(|p| if p.is_empty() { None } else { Some(p) }) {
                None => None,
                Some(p) => match parse_deliverby_minimum(p) {
                    Some(DeliverByEhloMinimum::Unspecified) => None,
                    Some(DeliverByEhloMinimum::Minimum(value)) => Some(value),
                    None => return ParsedEhloLine::Unknown,
                },
            };
            SmtpExtension::DeliverBy(max_seconds)
        }
        // RFC 6758: MT-PRIORITY message priority signaling
        "MT-PRIORITY" => SmtpExtension::MtPriority,
        // RFC 5321 Section 4.1.1.6: VRFY command support
        "VRFY" => {
            if has_params {
                return ParsedEhloLine::Unknown;
            }
            SmtpExtension::Vrfy
        }
        // RFC 5321 Section 4.1.1.7: EXPN command support
        "EXPN" => {
            if has_params {
                return ParsedEhloLine::Unknown;
            }
            SmtpExtension::Expn
        }
        // RFC 3865: NO-SOLICITING advertising policy
        "NO-SOLICITING" => {
            let keyword = params
                .and_then(|p| if p.is_empty() { None } else { Some(p) })
                .map(str::to_owned);
            SmtpExtension::NoSoliciting(keyword)
        }
        _ => return ParsedEhloLine::Unknown,
    };

    ParsedEhloLine::Extension(extension)
}

/// Apply a parsed EHLO capability line to the capability accumulator.
fn apply_ehlo_extension(caps: &mut ServerCapabilities, parsed: ParsedEhloLine) {
    match parsed {
        ParsedEhloLine::Extension(extension) => caps.extensions.push(extension),
        ParsedEhloLine::Auth(mechanisms) => merge_or_push_auth(&mut caps.extensions, mechanisms),
        ParsedEhloLine::Unknown => {}
    }
}

/// Parse the EHLO response lines into server capabilities.
///
/// RFC 5321 Section 4.1.1.1: The first line of the EHLO response is the
/// server greeting name. Subsequent lines advertise extensions.
///
/// Each extension keyword is matched case-insensitively per RFC 5321 Section 2.4.
pub(crate) fn parse_ehlo_capabilities(response: &SmtpResponse) -> ServerCapabilities {
    let mut caps = ServerCapabilities::default();
    let single_line_reply = response.lines.len() == 1;

    for (i, line) in response.lines.iter().enumerate() {
        if i == 0 {
            // RFC 5321 Section 4.1.1.1:
            //   ehlo-ok-rsp = "250" SP Domain [ SP ehlo-greet ] CRLF
            let greeting_token = match line.find(|c: char| c.is_ascii_whitespace()) {
                Some(pos) => &line[..pos],
                None => line,
            };

            // In a multi-line reply, the first line is unavoidably ambiguous:
            // a valid server Domain can equal an extension keyword such as
            // "SIZE". Preserve the first token as the greeting name there.
            //
            // For a malformed single-line reply, only recover a known
            // capability when the first token is not even legal `ehlo-domain`
            // syntax. That keeps interoperability for impossible greeting
            // tokens such as `AUTH=PLAIN` without misclassifying valid
            // single-line domains like `SIZE`.
            if single_line_reply && DomainOrLiteral::new(greeting_token).is_err() {
                match parse_ehlo_extension_line(line) {
                    ParsedEhloLine::Unknown => {}
                    parsed => {
                        apply_ehlo_extension(&mut caps, parsed);
                        continue;
                    }
                }
            }

            greeting_token.clone_into(&mut caps.greeting_name);
            continue;
        }

        match parse_ehlo_extension_line(line) {
            ParsedEhloLine::Unknown => caps.extensions.push(SmtpExtension::Other(line.clone())),
            parsed => apply_ehlo_extension(&mut caps, parsed),
        }
    }

    caps
}

/// Parse a whitespace-separated EHLO AUTH mechanism list.
///
/// RFC 4954 Section 3: the AUTH EHLO keyword contains a space-separated list
/// of SASL mechanism names. If any token is not a syntactically valid
/// `sasl-mech` (RFC 4422 Section 3.1), the EHLO line must not be exposed as
/// AUTH capability.
fn parse_auth_mechanism_list(list: &str) -> Option<Vec<AuthMechanism>> {
    let mechanisms = list
        .split_whitespace()
        .map(parse_auth_mechanism)
        .collect::<Option<Vec<_>>>()?;

    (!mechanisms.is_empty()).then_some(mechanisms)
}

/// Parse an auth mechanism name to the corresponding enum variant.
///
/// RFC 4954 Section 3: AUTH mechanism names are case-insensitive.
/// RFC 4422 Section 3.1: `sasl-mech = 1*20mech-char`, where `mech-char`
/// is `A-Z`, `0-9`, `-`, or `_`.
fn parse_auth_mechanism(name: &str) -> Option<AuthMechanism> {
    if !is_valid_sasl_mechanism_name(name) {
        return None;
    }

    Some(match name.to_ascii_uppercase().as_str() {
        "PLAIN" => AuthMechanism::Plain,
        // AUTH LOGIN: de-facto standard (draft-murchison-sasl-login),
        // two-step challenge-response following RFC 4954 Section 4 pattern.
        "LOGIN" => AuthMechanism::Login,
        // RFC 7628 Section 3.1: OAUTHBEARER SASL mechanism.
        "OAUTHBEARER" => AuthMechanism::OAuthBearer,
        "XOAUTH2" => AuthMechanism::XOAuth2,
        _ => AuthMechanism::Other(name.to_owned()),
    })
}

/// Returns `true` if `name` is a syntactically valid SASL mechanism name.
///
/// RFC 4422 Section 3.1 registers mechanism names as `1*20mech-char`.
/// RFC 4954 Section 3 requires SMTP AUTH processing to accept mechanism names
/// case-insensitively, so lower-case ASCII letters are accepted here too.
fn is_valid_sasl_mechanism_name(name: &str) -> bool {
    let len = name.len();
    (1..=20).contains(&len)
        && name
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
}

/// Try to strip an enhanced status code prefix from a response text line.
///
/// If the text starts with a valid enhanced status code followed by a space
/// or end-of-string (RFC 2034 Section 3), AND the enhanced code class matches
/// the reply code class (RFC 2034 Section 4), returns `Some((code, remaining_text))`.
/// Otherwise returns `None` and the text is unchanged.
///
/// `reply_code` is the 3-digit SMTP reply code (e.g. 250, 550) used to
/// validate the enhanced status code class per RFC 2034 Section 4: "The
/// class value MUST match the first digit of the status-code."
///
/// RFC 2034 Section 3: Enhanced status codes appear in SMTP response text
/// after the three-digit reply code and separator. "Any additional text in
/// the reply, if any, SHOULD be a complete line." — the "if any" means
/// trailing text is optional.
pub(crate) fn strip_enhanced_code(
    text: &str,
    reply_code: u16,
) -> Option<(EnhancedStatusCode, &str)> {
    use nom::bytes::complete::tag as tag_complete;

    let bytes = text.as_bytes();
    match enhanced_status_code_complete(bytes) {
        Ok((rest, esc)) => {
            // RFC 2034 Section 4: the enhanced code class MUST match the
            // reply code class. Discard the code if they disagree.
            // reply_code is in 200..=599, so /100 yields 2..=5 which fits in u8.
            #[allow(clippy::cast_possible_truncation)]
            let reply_class = (reply_code / 100) as u8;
            if esc.class != reply_class {
                return None;
            }

            // RFC 2034 Section 3: enhanced code followed by space and text.
            match tag_complete::<_, _, nom::error::Error<&[u8]>>(b" ")(rest) {
                Ok((after_space, _)) => {
                    let consumed = bytes.len() - after_space.len();
                    Some((esc, &text[consumed..]))
                }
                _ => {
                    // RFC 2034 Section 3: text after enhanced code is optional.
                    // Accept the code when it comprises the entire text.
                    if rest.is_empty() {
                        Some((esc, ""))
                    } else {
                        None
                    }
                }
            }
        }
        _ => None,
    }
}

/// Parse an enhanced status code from a complete string (for use in capability
/// parsing or other non-wire contexts).
///
/// RFC 1893 Section 2: Parses the `class.subject.detail` format.
#[cfg(any(test, fuzzing))]
pub(crate) fn parse_enhanced_code_from_str(s: &str) -> Option<EnhancedStatusCode> {
    // Use a complete (non-streaming) parser since we have the full input.
    match enhanced_status_code_complete(s.as_bytes()) {
        Ok(([], esc)) => Some(esc),
        _ => None,
    }
}

// Non-streaming variant of `enhanced_status_code` for use when the full
// input is available (e.g., parsing from owned strings).
//
// RFC 1893 Section 2: `status-code = class "." subject "." detail`
define_enhanced_status_code_parser!(
    enhanced_status_code_complete,
    ,
    nom::character::complete::one_of,
    nom::bytes::complete::tag,
    nom::bytes::complete::take_while1
);

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