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
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! SMTP command encoder.
//!
//! Serializes SMTP commands into bytes for transmission.
//! All commands are terminated with CRLF per RFC 5321.

use bytes::BytesMut;

use crate::deliver_by::validate_deliver_by_value;
use crate::error::Error;
use crate::future_release::{validate_hold_for_seconds, validate_hold_until_datetime};
use crate::types::{
    BodyType, DeliverByMode, DomainOrLiteral, DsnNotify, DsnRet, ForwardPath, MailFromParams,
    RcptToParams, ReversePath, SmtpAuthParam,
};

/// RFC 5321 Section 4.5.3.1.4: maximum SMTP command line length including CRLF.
const SMTP_MAX_COMMAND_LINE: usize = 512;

/// RFC 3461 Section 5: DSN parameters extend the RCPT TO line length limit.
const SMTP_MAX_RCPT_TO_DSN_LINE: usize = 1012;

/// Maximum total length of a MAIL FROM command line including the extension
/// allowances from RFC 1870, RFC 6152, RFC 6531, RFC 8689, RFC 3461,
/// RFC 4865, RFC 2852, RFC 6758, and RFC 4954.
const SMTP_MAX_MAIL_FROM_LINE: usize = 512 + 26 + 17 + 10 + 11 + 109 + 34 + 17 + 16 + 500;

/// Validate that a string parameter does not contain CR or LF bytes.
///
/// RFC 5321 Section 4.1.2: SMTP commands are terminated by CRLF, so
/// embedded CR/LF in parameter values would split the command line and
/// allow injection of arbitrary SMTP commands. This is a runtime check
/// that ensures encoder safety even when used standalone without the
/// connection layer's validation.
fn validate_no_crlf(value: &str, context: &str) -> Result<(), Error> {
    if value.bytes().any(|b| b == b'\r' || b == b'\n') {
        return Err(Error::Protocol(format!(
            "{context} must not contain CR or LF (RFC 5321 Section 4.1.2)"
        )));
    }
    Ok(())
}

/// Validate that a value contains only printable US-ASCII bytes.
///
/// RFC 5321 Section 4.1.2 constrains SMTP `String` arguments to printable
/// ASCII and excludes ASCII control characters.
fn validate_printable_ascii(value: &str, context: &str) -> Result<(), Error> {
    for &b in value.as_bytes() {
        if b < 0x20 || b == 0x7F {
            return Err(Error::Protocol(format!(
                "{context} contains control character (byte 0x{b:02X}); \
                 only printable US-ASCII is permitted \
                 (RFC 5321 Section 4.1.2)"
            )));
        }
        if b > 0x7F {
            return Err(Error::Protocol(format!(
                "{context} contains non-ASCII characters; \
                 only printable US-ASCII is permitted \
                 (RFC 5321 Section 4.1.2)"
            )));
        }
    }
    Ok(())
}

/// Validate a VRFY/EXPN `String` argument when RFC 6531 `SMTPUTF8` is in use.
///
/// RFC 6531 Section 3.7.4.2 allows VRFY/EXPN `String` arguments to include
/// non-ASCII characters when the `SMTPUTF8` parameter is present, but ASCII
/// control characters remain invalid SMTP command content (RFC 5321 Section 4.1.2).
fn validate_utf8_query_string(value: &str, context: &str) -> Result<(), Error> {
    for &b in value.as_bytes() {
        if b < 0x20 || b == 0x7F {
            return Err(Error::Protocol(format!(
                "{context} contains control character (byte 0x{b:02X}); \
                 SMTPUTF8 does not permit ASCII control characters in VRFY/EXPN arguments \
                 (RFC 5321 Section 4.1.2 / RFC 6531 Section 3.7.4.2)"
            )));
        }
    }
    Ok(())
}

/// Validate an SMTP command line against the base RFC 5321 octet limit.
///
/// RFC 5321 Section 4.5.3.1.4 limits command lines, including the trailing
/// CRLF, to 512 octets.
fn validate_command_line_length(line_len: usize, cmd_name: &str) -> Result<(), Error> {
    if line_len > SMTP_MAX_COMMAND_LINE {
        return Err(Error::Protocol(format!(
            "{cmd_name} command line exceeds 512-octet limit \
             (RFC 5321 Section 4.5.3.1.4): {line_len} octets"
        )));
    }
    Ok(())
}

/// Validate a MAIL FROM line against the extended ESMTP limit.
fn validate_mail_from_line_length(line_len: usize) -> Result<(), Error> {
    if line_len > SMTP_MAX_MAIL_FROM_LINE {
        return Err(Error::Protocol(format!(
            "MAIL FROM command line exceeds {SMTP_MAX_MAIL_FROM_LINE}-octet limit \
             (RFC 5321 Section 4.5.3.1.4 plus registered extension allowances): \
             {line_len} octets"
        )));
    }
    Ok(())
}

/// Validate a RCPT TO line, using RFC 3461's extended limit when DSN
/// parameters are present.
fn validate_rcpt_to_line_length(line_len: usize, has_dsn_params: bool) -> Result<(), Error> {
    let limit = if has_dsn_params {
        SMTP_MAX_RCPT_TO_DSN_LINE
    } else {
        SMTP_MAX_COMMAND_LINE
    };

    if line_len > limit {
        let rfc = if has_dsn_params {
            "RFC 3461 Section 5"
        } else {
            "RFC 5321 Section 4.5.3.1.4"
        };
        return Err(Error::Protocol(format!(
            "RCPT TO command line exceeds {limit}-octet limit ({rfc}): {line_len} octets"
        )));
    }
    Ok(())
}

/// Encode a greeting command (`<cmd> <domain>\r\n`).
///
/// Shared by EHLO (RFC 5321 Section 4.1.1.1), LHLO (RFC 2033 Section 4.2),
/// and HELO (RFC 5321 Section 4.1.1.1).
///
/// The `domain` argument is a pre-validated [`DomainOrLiteral`], so domain
/// syntax, CRLF, and length checks are guaranteed by construction.
///
/// Returns an error if the total command line exceeds 512 octets
/// (RFC 5321 Section 4.5.3.1.4).
fn encode_greeting(buf: &mut BytesMut, cmd: &[u8], domain: &DomainOrLiteral) -> Result<(), Error> {
    let domain_str = domain.as_str();
    // RFC 5321 Section 4.5.3.1.4: maximum command line length is 512 octets
    // including the trailing CRLF.
    let total = cmd.len() + domain_str.len() + 2; // +2 for CRLF
    validate_command_line_length(total, "EHLO/HELO")?;
    buf.extend_from_slice(cmd);
    buf.extend_from_slice(domain_str.as_bytes());
    buf.extend_from_slice(b"\r\n");
    Ok(())
}

/// Encode an EHLO command (RFC 5321 Section 4.1.1.1).
///
/// The `domain` argument is a pre-validated [`DomainOrLiteral`].
/// Returns an error if the total command line exceeds 512 octets
/// (RFC 5321 Section 4.5.3.1.4).
pub(crate) fn encode_ehlo(buf: &mut BytesMut, domain: &DomainOrLiteral) -> Result<(), Error> {
    encode_greeting(buf, b"EHLO ", domain)
}

/// Encode an AUTH PLAIN command with credentials (RFC 4954, RFC 4616).
///
/// Format: `AUTH PLAIN <base64(\0user\0pass)>`
///
/// Used in tests to verify line-length thresholds for the SASL-IR
/// one-step vs two-step decision (RFC 4954 Section 4).
#[cfg(test)]
pub(crate) fn encode_auth_plain(buf: &mut BytesMut, user: &str, pass: &str) {
    use base64::Engine;

    let mut credentials = Vec::with_capacity(1 + user.len() + 1 + pass.len());
    credentials.push(0);
    credentials.extend_from_slice(user.as_bytes());
    credentials.push(0);
    credentials.extend_from_slice(pass.as_bytes());

    let encoded = base64::engine::general_purpose::STANDARD.encode(&credentials);

    buf.extend_from_slice(b"AUTH PLAIN ");
    buf.extend_from_slice(encoded.as_bytes());
    buf.extend_from_slice(b"\r\n");
}

/// Encode an AUTH XOAUTH2 command (Google XOAUTH2 extension).
///
/// Format: `AUTH XOAUTH2 <base64(user=<user>\x01auth=Bearer <token>\x01\x01)>`
///
/// Used in tests to verify line-length thresholds for the SASL-IR
/// one-step vs two-step decision (RFC 4954 Section 4).
#[cfg(test)]
pub(crate) fn encode_auth_xoauth2(buf: &mut BytesMut, user: &str, token: &str) {
    use base64::Engine;

    let sasl_string = format!("user={user}\x01auth=Bearer {token}\x01\x01");
    let encoded = base64::engine::general_purpose::STANDARD.encode(sasl_string.as_bytes());

    buf.extend_from_slice(b"AUTH XOAUTH2 ");
    buf.extend_from_slice(encoded.as_bytes());
    buf.extend_from_slice(b"\r\n");
}

/// Encode an AUTH OAUTHBEARER command (RFC 7628 Section 3.1).
///
/// Format: `AUTH OAUTHBEARER <base64(sasl_payload)>\r\n`
/// SASL payload: `n,,\x01auth=Bearer <token>\x01\x01`
///
/// Used in tests to verify the SASL payload encoding.
#[cfg(test)]
pub(crate) fn encode_auth_oauthbearer(buf: &mut BytesMut, token: &str) {
    use base64::Engine;

    // RFC 7628 Section 3.1: gs2-header is "n,," (no channel binding, no authzid)
    // followed by key-value pairs separated by SOH (\x01).
    let sasl_string = format!("n,,\x01auth=Bearer {token}\x01\x01");
    let encoded = base64::engine::general_purpose::STANDARD.encode(sasl_string.as_bytes());

    buf.extend_from_slice(b"AUTH OAUTHBEARER ");
    buf.extend_from_slice(encoded.as_bytes());
    buf.extend_from_slice(b"\r\n");
}

/// Encode the initial AUTH LOGIN command (draft-murchison-sasl-login).
///
/// Format: `AUTH LOGIN\r\n`
///
/// AUTH LOGIN is a multi-step challenge-response mechanism. The initial
/// command contains no credentials; the server responds with 334 challenges
/// for username and password. The connection layer handles the full SASL
/// exchange following the pattern in RFC 4954 Section 4.
///
/// Used in tests to verify the initial command encoding.
#[cfg(test)]
pub(crate) fn encode_auth_login_initial(buf: &mut BytesMut) {
    buf.extend_from_slice(b"AUTH LOGIN\r\n");
}

/// Encode MAIL FROM command (RFC 5321 Section 4.1.1.2).
///
/// If `size` is `Some`, includes the SIZE parameter (RFC 1870).
/// Delegates to [`encode_mail_from_full`] with default parameters.
///
/// The `from` argument is a pre-validated [`ReversePath`].
pub(crate) fn encode_mail_from(
    buf: &mut BytesMut,
    from: &ReversePath,
    size: Option<u64>,
) -> Result<(), Error> {
    let params = MailFromParams {
        size,
        ..MailFromParams::default()
    };
    encode_mail_from_full(buf, from, &params)
}

/// Encode RCPT TO command (RFC 5321 Section 4.1.1.3).
///
/// The `to` argument is a pre-validated [`ForwardPath`] — mailbox syntax,
/// path length, and the special `Postmaster` case are guaranteed by
/// construction.
#[allow(clippy::unnecessary_wraps)]
pub(crate) fn encode_rcpt_to(buf: &mut BytesMut, to: &ForwardPath) -> Result<(), Error> {
    buf.extend_from_slice(b"RCPT TO:<");
    buf.extend_from_slice(to.as_str().as_bytes());
    buf.extend_from_slice(b">\r\n");
    Ok(())
}

/// Encode an extended RCPT TO command with optional ESMTP parameters
/// (RFC 5321 Section 4.1.1.3).
///
/// When `params` is empty, this produces the same output as [`encode_rcpt_to`].
/// Extension-specific parameters (e.g., DSN NOTIFY/ORCPT per RFC 3461
/// Section 4.2) are appended after the address.
///
/// The `to` argument is a pre-validated [`ForwardPath`] — mailbox syntax,
/// path length, and the special `Postmaster` case are guaranteed by
/// construction.
pub(crate) fn encode_rcpt_to_full(
    buf: &mut BytesMut,
    to: &ForwardPath,
    params: &RcptToParams,
) -> Result<(), Error> {
    let to_str = to.as_str();
    let mut line = BytesMut::new();
    let mut has_dsn_params = false;

    line.extend_from_slice(b"RCPT TO:<");
    line.extend_from_slice(to_str.as_bytes());
    line.extend_from_slice(b">");

    // NOTIFY parameter per RFC 3461 Section 4.1
    // Treat Some(vec![]) as absent — an empty NOTIFY= is syntactically
    // invalid (RFC 3461 Section 4.1: notify-esmtp-value requires at
    // least one value).
    if let Some(notify) = &params.notify {
        if !notify.is_empty() {
            has_dsn_params = true;
            line.extend_from_slice(b" NOTIFY=");
            // RFC 3461 Section 4.1: NEVER MUST NOT be used in conjunction
            // with any other NOTIFY value. Reject the combination rather
            // than silently discarding values.
            if notify.iter().any(|n| matches!(n, DsnNotify::Never)) {
                if notify.len() > 1 {
                    return Err(Error::Protocol(
                        "NOTIFY=NEVER must not be combined with other values \
                         (RFC 3461 Section 4.1)"
                            .into(),
                    ));
                }
                line.extend_from_slice(b"NEVER");
            } else {
                let mut first = true;
                #[allow(clippy::needless_continue)]
                for n in notify {
                    if !first {
                        line.extend_from_slice(b",");
                    }
                    first = false;
                    match n {
                        DsnNotify::Success => line.extend_from_slice(b"SUCCESS"),
                        DsnNotify::Failure => line.extend_from_slice(b"FAILURE"),
                        DsnNotify::Delay => line.extend_from_slice(b"DELAY"),
                        // NEVER was already handled above; this branch
                        // is unreachable, but we use `continue` instead of
                        // `unreachable!()` to avoid a panic in production
                        // (workspace rule: no panic!/todo!() in merged code).
                        DsnNotify::Never => continue,
                    }
                }
            }
        }
    }

    // ORCPT parameter per RFC 3461 Section 4.2.
    // RFC 3461 Section 4.2: ORCPT=<addr-type>;<xtext-addr>
    // RFC 3461 Section 4.2: xtext = 1*xchar (non-empty).
    // RFC 6533 Section 3: when the address contains non-ASCII characters
    // (internationalized email), use addr-type "utf-8" instead of "rfc822".
    if let Some(orcpt) = &params.orcpt {
        if orcpt.is_empty() {
            return Err(crate::Error::Protocol(
                "ORCPT value must be non-empty (RFC 3461 Section 4.2: xtext = 1*xchar)".into(),
            ));
        }
        has_dsn_params = true;
        if orcpt.is_ascii() {
            // RFC 3461 Section 4.2: ASCII addresses use rfc822 addr-type
            // with standard xtext encoding.
            line.extend_from_slice(b" ORCPT=rfc822;");
            encode_xtext(&mut line, orcpt);
        } else {
            // RFC 6533 Section 3: internationalized addresses use utf-8
            // addr-type with utf-8-addr-xtext encoding (multi-byte UTF-8
            // passes through literally).
            line.extend_from_slice(b" ORCPT=utf-8;");
            encode_utf8_addr_xtext(&mut line, orcpt);
        }
    }

    line.extend_from_slice(b"\r\n");
    validate_rcpt_to_line_length(line.len(), has_dsn_params)?;
    buf.extend_from_slice(&line);
    Ok(())
}

/// Encode DATA command (RFC 5321 Section 4.1.1.4).
pub(crate) fn encode_data(buf: &mut BytesMut) {
    buf.extend_from_slice(b"DATA\r\n");
}

/// Encode the end-of-data terminator (RFC 5321 Section 4.1.1.4).
///
/// The end-of-data sequence is `<CRLF>.<CRLF>` where the first `<CRLF>` is
/// "actually the terminator of the previous line." If `preceding_data` already
/// ends with `\r\n`, only `.\r\n` is emitted; otherwise `\r\n.\r\n` is emitted
/// to ensure the dot appears on a line by itself.
pub(crate) fn encode_data_end(buf: &mut BytesMut, preceding_data: &[u8]) {
    // RFC 5321 Section 4.1.1.4: the first CRLF in <CRLF>.<CRLF> terminates
    // the previous line. Only add it when the data doesn't already end with CRLF.
    if !preceding_data.ends_with(b"\r\n") {
        buf.extend_from_slice(b"\r\n");
    }
    buf.extend_from_slice(b".\r\n");
}

/// Encode STARTTLS command (RFC 3207 Section 4).
pub(crate) fn encode_starttls(buf: &mut BytesMut) {
    buf.extend_from_slice(b"STARTTLS\r\n");
}

/// Encode QUIT command (RFC 5321 Section 4.1.1.10).
pub(crate) fn encode_quit(buf: &mut BytesMut) {
    buf.extend_from_slice(b"QUIT\r\n");
}

/// Encode RSET command (RFC 5321 Section 4.1.1.5).
pub(crate) fn encode_rset(buf: &mut BytesMut) {
    buf.extend_from_slice(b"RSET\r\n");
}

/// Encode NOOP command (RFC 5321 Section 4.1.1.9).
pub(crate) fn encode_noop(buf: &mut BytesMut) {
    buf.extend_from_slice(b"NOOP\r\n");
}

/// Encode a BDAT command (RFC 3030 Section 3).
///
/// Format: `BDAT <size>\r\n` or `BDAT <size> LAST\r\n`.
/// The LAST keyword indicates the final chunk of the message.
pub(crate) fn encode_bdat(buf: &mut BytesMut, size: usize, last: bool) {
    buf.extend_from_slice(b"BDAT ");
    buf.extend_from_slice(size.to_string().as_bytes());
    if last {
        // LAST keyword per RFC 3030 Section 3
        buf.extend_from_slice(b" LAST");
    }
    buf.extend_from_slice(b"\r\n");
}

/// Encode an LHLO command (RFC 2033 Section 4.2).
///
/// LHLO is the LMTP equivalent of EHLO, used to initiate an LMTP session.
///
/// The `domain` argument is a pre-validated [`DomainOrLiteral`].
/// Returns an error if the total command line exceeds 512 octets
/// (RFC 5321 Section 4.5.3.1.4).
pub(crate) fn encode_lhlo(buf: &mut BytesMut, domain: &DomainOrLiteral) -> Result<(), Error> {
    encode_greeting(buf, b"LHLO ", domain)
}

/// Encode a HELO command (RFC 5321 Section 4.1.1.1).
///
/// HELO is the legacy greeting command, used as a fallback when EHLO is rejected
/// by the server. RFC 5321 Section 4.1.1.1 also says that when the client
/// lacks a meaningful domain name, it SHOULD send an address-literal; accept
/// that form here so HELO fallback preserves the configured client identity.
///
/// The `domain` argument is a pre-validated [`DomainOrLiteral`].
/// Returns an error if the total command line exceeds 512 octets
/// (RFC 5321 Section 4.5.3.1.4).
pub(crate) fn encode_helo(buf: &mut BytesMut, domain: &DomainOrLiteral) -> Result<(), Error> {
    encode_greeting(buf, b"HELO ", domain)
}

/// Encode an extended MAIL FROM command with optional ESMTP parameters
/// (RFC 5321 Section 4.1.1.2).
///
/// Supports optional parameters:
/// - `SIZE=<n>` (RFC 1870 Section 3)
/// - `BODY=<type>` (RFC 1652 Section 3, RFC 3030 Section 2)
/// - `SMTPUTF8` (RFC 6531 Section 3.4)
/// - `REQUIRETLS` (RFC 8689 Section 3)
/// - `RET=FULL|HDRS` (RFC 3461 Section 4.3)
/// - `ENVID=<xtext>` (RFC 3461 Section 4.4)
/// - `AUTH=<mailbox>` or `AUTH=<>` (RFC 4954 Section 5)
///
/// The `from` argument is a pre-validated [`ReversePath`] — mailbox syntax,
/// path length, and charset are guaranteed by construction.
#[allow(clippy::too_many_lines)]
pub(crate) fn encode_mail_from_full(
    buf: &mut BytesMut,
    from: &ReversePath,
    params: &MailFromParams,
) -> Result<(), Error> {
    let from_str = from.as_str();
    // RFC 6531 Sections 3.3-3.4: non-ASCII reverse-paths require SMTPUTF8.
    if from.requires_smtputf8() && !params.smtputf8 {
        return Err(Error::Protocol(
            "MAIL FROM address contains non-ASCII characters; RFC 6531 Sections 3.3 and 3.4 require the SMTPUTF8 parameter for internationalized reverse-paths".into(),
        ));
    }
    let mut line = BytesMut::new();
    line.extend_from_slice(b"MAIL FROM:<");
    line.extend_from_slice(from_str.as_bytes());
    line.extend_from_slice(b">");

    // SIZE parameter per RFC 1870 Section 3
    if let Some(size) = params.size {
        line.extend_from_slice(b" SIZE=");
        line.extend_from_slice(size.to_string().as_bytes());
    }

    // RFC 6531 Section 3.4 requires BODY=8BITMIME (or BODY=BINARYMIME per
    // RFC 6531 Section 3.6 / RFC 3030 Section 2) whenever SMTPUTF8 is used.
    let effective_body = match (params.smtputf8, params.body) {
        (true, Some(BodyType::SevenBit)) => {
            return Err(Error::Protocol(
                "BODY=7BIT cannot be used with SMTPUTF8; \
                 RFC 6531 Section 3.6 requires BODY=8BITMIME or \
                 BODY=BINARYMIME when SMTPUTF8 is used"
                    .into(),
            ));
        }
        (true, Some(body)) => Some(body),
        (true, None) => Some(BodyType::EightBitMime),
        (false, body) => body,
    };

    // BODY parameter per RFC 1652 Section 3 / RFC 3030 Section 2
    if let Some(body) = effective_body {
        match body {
            BodyType::SevenBit => line.extend_from_slice(b" BODY=7BIT"),
            BodyType::EightBitMime => line.extend_from_slice(b" BODY=8BITMIME"),
            BodyType::BinaryMime => line.extend_from_slice(b" BODY=BINARYMIME"),
        }
    }

    // SMTPUTF8 parameter per RFC 6531 Section 3.4
    if params.smtputf8 {
        line.extend_from_slice(b" SMTPUTF8");
    }

    // REQUIRETLS parameter per RFC 8689 Section 3
    if params.requiretls {
        line.extend_from_slice(b" REQUIRETLS");
    }

    // RET parameter per RFC 3461 Section 4.3
    if let Some(ret) = &params.ret {
        match ret {
            DsnRet::Full => line.extend_from_slice(b" RET=FULL"),
            DsnRet::Hdrs => line.extend_from_slice(b" RET=HDRS"),
        }
    }

    // ENVID parameter per RFC 3461 Section 4.4.
    // The EnvidValue newtype guarantees printable US-ASCII and at most
    // 100 characters before xtext encoding.
    if let Some(envid) = &params.envid {
        line.extend_from_slice(b" ENVID=");
        encode_xtext(&mut line, envid.as_str());
    }

    // RFC 4865 Section 5: HOLDFOR and HOLDUNTIL are mutually exclusive.
    if params.hold_for.is_some() && params.hold_until.is_some() {
        return Err(Error::Protocol(
            "HOLDFOR and HOLDUNTIL are mutually exclusive; \
             a client MUST NOT send both on the same MAIL FROM command \
             (RFC 4865 Section 5)"
                .into(),
        ));
    }

    // HOLDFOR parameter per RFC 4865 Section 5
    if let Some(hold_for) = params.hold_for {
        validate_hold_for_seconds(hold_for)?;
        line.extend_from_slice(b" HOLDFOR=");
        line.extend_from_slice(hold_for.to_string().as_bytes());
    }

    // HOLDUNTIL parameter per RFC 4865 Section 5.
    // Reject embedded CR/LF to prevent SMTP command injection
    // (RFC 5321 Section 4.1.2: commands are terminated by CRLF).
    if let Some(hold_until) = &params.hold_until {
        validate_no_crlf(hold_until, "HOLDUNTIL datetime")?;
        validate_hold_until_datetime(hold_until)?;
        line.extend_from_slice(b" HOLDUNTIL=");
        line.extend_from_slice(hold_until.as_bytes());
    }

    // BY parameter per RFC 2852 Section 4
    if let Some(deliver_by) = &params.deliver_by {
        validate_deliver_by_value(deliver_by)?;
        line.extend_from_slice(b" BY=");
        line.extend_from_slice(deliver_by.seconds.to_string().as_bytes());
        match deliver_by.mode {
            DeliverByMode::Notify => line.extend_from_slice(b";N"),
            DeliverByMode::Return => line.extend_from_slice(b";R"),
        }
        if deliver_by.trace {
            // RFC 2852 Section 4: by-trace = "T"
            line.extend_from_slice(b"T");
        }
    }

    // MT-PRIORITY parameter per RFC 6758 Section 4
    if let Some(mt_priority) = params.mt_priority {
        // RFC 6758 Section 4: priority values range from -9 to 9.
        if !(-9..=9).contains(&mt_priority) {
            return Err(Error::Protocol(format!(
                "MT-PRIORITY value {mt_priority} out of range -9..9 (RFC 6758 Section 4)"
            )));
        }
        line.extend_from_slice(b" MT-PRIORITY=");
        line.extend_from_slice(mt_priority.to_string().as_bytes());
    }

    // AUTH= parameter per RFC 4954 Section 5
    if let Some(ref auth) = params.auth {
        match auth {
            SmtpAuthParam::Mailbox(mailbox) => {
                // The Mailbox newtype guarantees non-empty, valid addr-spec
                // syntax (RFC 5321 Section 4.1.2). Check ASCII: RFC 4954
                // Section 5 references the SMTP `Mailbox` production, which
                // is US-ASCII. SMTPUTF8 does not extend AUTH=.
                if !mailbox.as_str().is_ascii() {
                    return Err(Error::Protocol(
                        "MAIL FROM AUTH mailbox contains non-ASCII characters; \
                         only printable US-ASCII is permitted \
                         (RFC 4954 Section 5 / RFC 5321 Section 4.1.2)"
                            .into(),
                    ));
                }
                // RFC 4954 Section 5: AUTH=<mailbox> where the mailbox
                // is xtext-encoded per RFC 4954 Section 4.
                line.extend_from_slice(b" AUTH=");
                encode_xtext(&mut line, mailbox.as_str());
            }
            SmtpAuthParam::Empty => {
                // RFC 4954 Section 5: AUTH=<> indicates unknown or
                // unauthenticated origin.
                line.extend_from_slice(b" AUTH=<>");
            }
        }
    }

    line.extend_from_slice(b"\r\n");
    validate_mail_from_line_length(line.len())?;
    buf.extend_from_slice(&line);
    Ok(())
}

/// Encode a string as xtext per RFC 3461 Section 4.
///
/// xtext encoding replaces `+`, `=`, and characters outside the range
/// `!`–`~` (printable ASCII excluding SP, `+`, and `=`) with `+XX` hex
/// encoding (RFC 3461 Section 4: "xchar = %x21-2A / %x2C-3C / %x3E-7E /
/// hexchar", where hexchar = `+` 2HEXDIG).
fn encode_xtext(buf: &mut BytesMut, s: &str) {
    for &b in s.as_bytes() {
        // RFC 3461 Section 4: xchar = any ASCII CHAR between "!" (33)
        // and "~" (126) inclusive, except for "+" and "=".
        // Numerically: xchar = %x21-2A / %x2C-3C / %x3E-7E
        // Characters outside this range (including '+' = 0x2B, '=' = 0x3D,
        // and SP = 0x20) must be hex-encoded as +XX.
        if b == b'+' || b == b'=' || b <= 0x20 || b > 0x7E {
            buf.extend_from_slice(b"+");
            // RFC 3461 Section 4: hexchar = "+" 2HEXDIG (uppercase per convention)
            buf.extend_from_slice(format!("{b:02X}").as_bytes());
        } else {
            buf.extend_from_slice(&[b]);
        }
    }
}

/// Encode a string as `utf-8-addr-xtext` per RFC 6533 Section 3.
///
/// Unlike RFC 3461 `xtext` encoding (which hex-encodes all bytes outside
/// `!`–`~`), `utf-8-addr-xtext` passes multi-byte UTF-8 characters through
/// literally:
///
/// ```text
/// utf-8-addr-xtext = *( QCHAR / EXT-UTF8-CHAR )
/// QCHAR            = %x21-2A / %x2C-3C / %x3E-5B / %x5D-7E
/// EXT-UTF8-CHAR    = UTF8-2 / UTF8-3 / UTF8-4
/// ```
///
/// QCHAR covers printable ASCII except `+` (0x2B), `=` (0x3D), and `\` (0x5C).
/// Characters outside QCHAR and EXT-UTF8-CHAR (SP, control chars, DEL, `+`,
/// `=`, `\`) are hex-encoded as `+XX` (RFC 6533 Section 3).
fn encode_utf8_addr_xtext(buf: &mut BytesMut, s: &str) {
    for &b in s.as_bytes() {
        if b >= 0x80 {
            // EXT-UTF8-CHAR: multi-byte UTF-8 continuation/lead bytes pass
            // through literally (RFC 6533 Section 3).
            buf.extend_from_slice(&[b]);
        } else if b == b'+' || b == b'=' || b == b'\\' || b <= 0x20 || b > 0x7E {
            // RFC 6533 Section 3: QCHAR excludes +, =, \, SP, control chars,
            // and DEL. Encode as +XX hex.
            buf.extend_from_slice(b"+");
            buf.extend_from_slice(format!("{b:02X}").as_bytes());
        } else {
            // QCHAR: printable ASCII that is not +, =, or \.
            buf.extend_from_slice(&[b]);
        }
    }
}

/// Encode a command of the form `CMD SP arg CRLF`.
///
/// Shared by VRFY (RFC 5321 Section 4.1.1.6) and EXPN (RFC 5321 Section 4.1.1.7).
///
/// Returns an error if `arg` contains CR or LF (RFC 5321 Section 4.1.2),
/// or if the total command line exceeds 512 octets (RFC 5321 Section 4.5.3.1.4).
fn encode_cmd_with_arg(
    buf: &mut BytesMut,
    cmd: &[u8],
    arg: &str,
    smtputf8: bool,
) -> Result<(), Error> {
    if arg.is_empty() {
        return Err(Error::Protocol(
            "SMTP query argument must not be empty \
             (RFC 5321 Sections 4.1.1.6-4.1.1.7)"
                .into(),
        ));
    }
    // Runtime CRLF injection prevention (RFC 5321 Section 4.1.2).
    validate_no_crlf(arg, "SMTP command argument")?;
    if smtputf8 {
        validate_utf8_query_string(arg, "SMTP command argument")?;
    } else {
        validate_printable_ascii(arg, "SMTP command argument")?;
    }

    // RFC 5321 Section 4.1.2: `String = Atom / Quoted-string`.
    // A String containing SP cannot be emitted as a bare Atom, so encode it
    // as a quoted-string and escape DQUOTE / "\" as required by
    // `quoted-pairSMTP`.
    let rendered_arg = render_smtp_string_argument(arg, smtputf8)?;

    // RFC 5321 Section 4.5.3.1.4: command lines MUST NOT exceed 512 octets
    // including the trailing CRLF.
    let total_len = cmd.len() + rendered_arg.len() + if smtputf8 { 9 } else { 0 } + 2; // +9 for " SMTPUTF8", +2 for CRLF
    validate_command_line_length(total_len, "SMTP")?;
    buf.extend_from_slice(cmd);
    buf.extend_from_slice(&rendered_arg);
    if smtputf8 {
        buf.extend_from_slice(b" SMTPUTF8");
    }
    buf.extend_from_slice(b"\r\n");
    Ok(())
}

/// Render an SMTP `String` argument per RFC 5321 Section 4.1.2.
///
/// Bare atoms may be sent unchanged. Any argument that is not a valid SMTP
/// `Atom` is rendered as a quoted-string, escaping `"` and `\` per
/// `quoted-pairSMTP`.
fn render_smtp_string_argument(arg: &str, smtputf8: bool) -> Result<Vec<u8>, Error> {
    let bytes = arg.as_bytes();
    let already_quoted = bytes.len() >= 2 && bytes[0] == b'"' && bytes[bytes.len() - 1] == b'"';
    if already_quoted {
        validate_smtp_quoted_string(arg, smtputf8)?;
        return Ok(bytes.to_vec());
    }
    if arg.chars().all(|ch| is_smtp_atom_char(ch, smtputf8)) {
        return Ok(bytes.to_vec());
    }

    let mut rendered = Vec::with_capacity(bytes.len() + 2);
    rendered.push(b'"');
    for &byte in bytes {
        if byte == b'\\' || byte == b'"' {
            rendered.push(b'\\');
        }
        rendered.push(byte);
    }
    rendered.push(b'"');
    Ok(rendered)
}

/// Validate an already-quoted SMTP `String` argument.
///
/// RFC 5321 Section 4.1.2 defines `Quoted-string = DQUOTE *QcontentSMTP DQUOTE`.
/// Within the quoted content, `"` must be escaped and `\` must be followed by
/// another character (`quoted-pairSMTP`). RFC 6531 Section 3.7.4.2 permits
/// UTF-8 content when SMTPUTF8 is in use, but it does not relax the quoting
/// rules themselves.
pub(crate) fn validate_smtp_quoted_string(value: &str, smtputf8: bool) -> Result<(), Error> {
    let Some(inner) = value
        .strip_prefix('"')
        .and_then(|rest| rest.strip_suffix('"'))
    else {
        return Err(Error::Protocol(
            "SMTP quoted-string must begin and end with DQUOTE \
             (RFC 5321 Section 4.1.2)"
                .into(),
        ));
    };

    let bytes = inner.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        match bytes[i] {
            b'\\' => {
                if i + 1 >= bytes.len() {
                    return Err(Error::Protocol(
                        "SMTP quoted-string must not end with a bare backslash \
                         (RFC 5321 Section 4.1.2)"
                            .into(),
                    ));
                }
                let next = bytes[i + 1];
                // RFC 5321 Section 4.1.2: quoted-pairSMTP = %d92 %d32-126.
                // The valid range after backslash is SP (0x20) through
                // tilde (0x7E). HTAB (0x09) is NOT included despite being
                // WSP — the ABNF explicitly restricts to %d32-126.
                // RFC 6531 Section 3.3 extends qtextSMTP with UTF-8 but does
                // not extend quoted-pairSMTP, so escaped bytes remain within
                // %d32-126 even when SMTPUTF8 is in use.
                if !(0x20..=0x7E).contains(&next) {
                    return Err(Error::Protocol(
                        "SMTP quoted-string contains an invalid escaped byte; \
                         quoted-pairSMTP permits only %d32-126 after '\\' \
                         (RFC 5321 Section 4.1.2 / RFC 6531 Section 3.3)"
                            .into(),
                    ));
                }
                i += 2;
            }
            b'"' => {
                return Err(Error::Protocol(
                    "SMTP quoted-string contains an unescaped DQUOTE \
                     (RFC 5321 Section 4.1.2)"
                        .into(),
                ));
            }
            b if b.is_ascii() => i += 1,
            _ if smtputf8 => {
                let ch_len = inner[i..].chars().next().map_or(1, char::len_utf8);
                i += ch_len;
            }
            _ => {
                return Err(Error::Protocol(
                    "SMTP quoted-string contains non-ASCII data without SMTPUTF8 \
                     (RFC 5321 Section 4.1.2 / RFC 6531 Section 3.7.4.2)"
                        .into(),
                ));
            }
        }
    }

    Ok(())
}

/// Returns whether `ch` is permitted in an SMTP `Atom`.
///
/// RFC 5321 Section 4.1.2 defines `String = Atom / Quoted-string` and imports
/// `atext` from RFC 5322 Section 3.2.3. RFC 6531 Section 3.3 extends `atext`
/// with `UTF8-non-ascii` when SMTPUTF8 is in use.
fn is_smtp_atom_char(ch: char, smtputf8: bool) -> bool {
    match ch {
        'A'..='Z'
        | 'a'..='z'
        | '0'..='9'
        | '!'
        | '#'
        | '$'
        | '%'
        | '&'
        | '\''
        | '*'
        | '+'
        | '-'
        | '/'
        | '='
        | '?'
        | '^'
        | '_'
        | '`'
        | '{'
        | '|'
        | '}'
        | '~' => true,
        _ if smtputf8 && !ch.is_ascii() => true,
        _ => false,
    }
}

/// Encode a VRFY command (RFC 5321 Section 4.1.1.6).
///
/// Format: `VRFY SP String CRLF`
/// Asks the server to verify whether the argument identifies a user
/// or mailbox. Many servers disable VRFY for security reasons (RFC 5321
/// Section 3.5.3), returning 252 or 502.
///
/// Returns an error if `address` contains CR or LF (RFC 5321 Section 4.1.2),
/// or if the total command line exceeds 512 octets (RFC 5321 Section 4.5.3.1.4).
pub(crate) fn encode_vrfy(buf: &mut BytesMut, address: &str) -> Result<(), Error> {
    encode_cmd_with_arg(buf, b"VRFY ", address, false)
}

/// Encode a VRFY command with the RFC 6531 `SMTPUTF8` parameter.
///
/// Format: `VRFY SP String SP "SMTPUTF8" CRLF`
/// This form permits non-ASCII characters in the `String` argument and enables
/// UTF-8 strings in the corresponding server reply (RFC 6531 Section 3.7.4.2).
pub(crate) fn encode_vrfy_smtputf8(buf: &mut BytesMut, address: &str) -> Result<(), Error> {
    encode_cmd_with_arg(buf, b"VRFY ", address, true)
}

/// Encode an EXPN command (RFC 5321 Section 4.1.1.7).
///
/// Format: `EXPN SP String CRLF`
/// Asks the server to expand a mailing list name. Many servers disable
/// EXPN for security reasons (RFC 5321 Section 3.5.3), returning 252
/// or 502.
///
/// Returns an error if `list_name` contains CR or LF (RFC 5321 Section 4.1.2),
/// or if the total command line exceeds 512 octets (RFC 5321 Section 4.5.3.1.4).
pub(crate) fn encode_expn(buf: &mut BytesMut, list_name: &str) -> Result<(), Error> {
    encode_cmd_with_arg(buf, b"EXPN ", list_name, false)
}

/// Encode an EXPN command with the RFC 6531 `SMTPUTF8` parameter.
///
/// Format: `EXPN SP String SP "SMTPUTF8" CRLF`
/// This form permits non-ASCII characters in the `String` argument and enables
/// UTF-8 strings in the corresponding server reply (RFC 6531 Section 3.7.4.2).
pub(crate) fn encode_expn_smtputf8(buf: &mut BytesMut, list_name: &str) -> Result<(), Error> {
    encode_cmd_with_arg(buf, b"EXPN ", list_name, true)
}

/// Encode a HELP command without an argument (RFC 5321 Section 4.1.1.8).
///
/// Format: `HELP CRLF`
pub(crate) fn encode_help(buf: &mut BytesMut) {
    buf.extend_from_slice(b"HELP\r\n");
}

/// Encode a HELP command with a topic argument (RFC 5321 Section 4.1.1.8).
///
/// Format: `HELP SP String CRLF`
///
/// Returns an error if `topic` contains CR or LF (RFC 5321 Section 4.1.2),
/// or if the total command line exceeds 512 octets (RFC 5321
/// Section 4.5.3.1.4).
pub(crate) fn encode_help_with_arg(buf: &mut BytesMut, topic: &str) -> Result<(), Error> {
    encode_cmd_with_arg(buf, b"HELP ", topic, false)
}

/// Perform dot-stuffing on message data for DATA command.
///
/// Per RFC 5321 Section 4.5.2: any line beginning with `.` must have an
/// additional `.` prepended. Lines are delimited by CRLF (RFC 5321
/// Section 2.3.8), so only a `\n` preceded by `\r` counts as a line
/// boundary.
pub(crate) fn dot_stuff(data: &[u8]) -> Vec<u8> {
    let mut result = Vec::with_capacity(data.len().saturating_add(data.len() / 50));
    let mut at_line_start = true;
    let mut prev_cr = false;

    for &byte in data {
        if at_line_start && byte == b'.' {
            result.push(b'.');
        }
        result.push(byte);
        // RFC 5321 Section 2.3.8: lines are terminated by CRLF, not bare LF.
        at_line_start = byte == b'\n' && prev_cr;
        prev_cr = byte == b'\r';
    }

    result
}

/// Dot-stuff message data and append the DATA terminator in a single buffer.
///
/// Combines [`dot_stuff`] and the end-of-data terminator
/// (`<CRLF>.<CRLF>` per RFC 5321 Section 4.1.1.4) into one contiguous
/// `Vec<u8>` so the caller can send the body and terminator in a single
/// write+flush operation (RFC 5321 Section 4.5.2).
///
/// When the dot-stuffed output already ends with `\r\n`, only `.\r\n`
/// is appended; otherwise `\r\n.\r\n` is appended to ensure the dot
/// appears on a line by itself.
pub(crate) fn dot_stuff_and_terminate(data: &[u8]) -> Vec<u8> {
    let mut result = dot_stuff(data);
    // RFC 5321 Section 4.1.1.4: the first CRLF in <CRLF>.<CRLF> is
    // "actually the terminator of the previous line." Only add it when
    // the data doesn't already end with CRLF.
    if !result.ends_with(b"\r\n") {
        result.extend_from_slice(b"\r\n");
    }
    // RFC 5321 Section 4.1.1.4: end-of-data indicator = "." CRLF.
    result.extend_from_slice(b".\r\n");
    result
}

/// Calculate the size of dot-stuffed message data without allocating.
///
/// Returns the number of bytes that [`dot_stuff`] would produce for
/// `data`. Useful for pre-allocating buffers for dot-stuffed output.
///
/// Per RFC 5321 Section 4.5.2: any line beginning with `.` has an
/// additional `.` prepended. Lines are delimited by CRLF (RFC 5321
/// Section 2.3.8).
#[cfg(test)]
pub(crate) fn dot_stuff_size(data: &[u8]) -> usize {
    let mut size = data.len();
    let mut at_line_start = true;
    let mut prev_cr = false;

    for &byte in data {
        if at_line_start && byte == b'.' {
            size += 1;
        }
        at_line_start = byte == b'\n' && prev_cr;
        prev_cr = byte == b'\r';
    }

    size
}

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