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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
//! Private helpers: validation, MAIL FROM / RCPT TO building, EHLO,
//! pipelining, error handling, and internal implementation methods.
//!
//! RFC 5321 (SMTP), RFC 1870 (SIZE), RFC 6152 (8BITMIME), RFC 6531 (SMTPUTF8),
//! RFC 3030 (CHUNKING/BINARYMIME), RFC 3461 (DSN), RFC 4954 (AUTH params),
//! RFC 8689 (REQUIRETLS), RFC 4865 (FUTURERELEASE), RFC 2852 (DELIVERBY),
//! RFC 6758 (MT-PRIORITY).

#[allow(clippy::wildcard_imports)]
use super::*;

impl SmtpConnection {
    // -----------------------------------------------------------------------
    // Private helpers
    // -----------------------------------------------------------------------

    /// Validate that an encoded command line does not exceed the 512-octet
    /// limit (RFC 5321 Section 4.5.3.1.4).
    ///
    /// `line_len` is the number of bytes in the command line including the
    /// terminating CRLF. `cmd_name` is used in the error message.
    ///
    /// For MAIL FROM, use [`validate_mail_from_line_length`] instead —
    /// ESMTP extensions increase the limit beyond 512.
    pub(super) fn validate_command_line_length(
        line_len: usize,
        cmd_name: &str,
    ) -> Result<(), Error> {
        if line_len > Self::SMTP_MAX_COMMAND_LINE {
            return Err(Error::Protocol(format!(
                "{cmd_name} command line exceeds {}-octet limit ({line_len} octets) \
                 (RFC 5321 Section 4.5.3.1.4)",
                Self::SMTP_MAX_COMMAND_LINE
            )));
        }
        Ok(())
    }

    /// Validate that a MAIL FROM command line does not exceed the
    /// ESMTP-extended limit (RFC 5321 Section 4.5.3.1.4).
    ///
    /// ESMTP extensions increase the MAIL FROM limit beyond the base
    /// 512 octets: RFC 1870 Section 4 (+26 for SIZE), RFC 6152
    /// Section 7 (+17 for BODY=), RFC 6531 Section 3.4 (+10 for
    /// SMTPUTF8), RFC 4865 Section 5 (+34 for HOLDFOR/HOLDUNTIL),
    /// and RFC 4954 Section 3 (+500 for AUTH=).
    pub(super) fn validate_mail_from_line_length(line_len: usize) -> Result<(), Error> {
        if line_len > Self::SMTP_MAX_MAIL_FROM_LINE {
            return Err(Error::Protocol(format!(
                "MAIL FROM command line exceeds {}-octet limit ({line_len} octets) \
                 (RFC 5321 Section 4.5.3.1.4 / RFC 1870 Section 4 / \
                 RFC 6152 Section 7 / RFC 6531 Section 3.4 / \
                 RFC 4865 Section 5 / RFC 4954 Section 3)",
                Self::SMTP_MAX_MAIL_FROM_LINE
            )));
        }
        Ok(())
    }

    /// Validate that a RCPT TO command line does not exceed the applicable
    /// line-length limit.
    ///
    /// RFC 5321 Section 4.5.3.1.4: base limit is 512 octets.
    /// RFC 3461 Section 5: when DSN parameters (NOTIFY, ORCPT) are present,
    /// the limit increases by 500 octets to 1012 octets.
    pub(super) fn validate_rcpt_to_line_length(
        line_len: usize,
        has_dsn_params: bool,
    ) -> Result<(), Error> {
        let limit = if has_dsn_params {
            Self::SMTP_MAX_RCPT_TO_DSN_LINE
        } else {
            Self::SMTP_MAX_COMMAND_LINE
        };
        if line_len > limit {
            return Err(Error::Protocol(format!(
                "RCPT TO command line exceeds {limit}-octet limit ({line_len} octets) \
                 (RFC 5321 Section 4.5.3.1.4{})",
                if has_dsn_params {
                    " / RFC 3461 Section 5"
                } else {
                    ""
                }
            )));
        }
        Ok(())
    }

    /// Validate that a recipient address is non-empty.
    ///
    /// RFC 5321 Section 4.1.1.3: `Forward-path = Path = "<" Mailbox ">"`.
    /// Validate sender and recipient addresses for a send operation.
    ///
    /// Shared by `send_with_params`, `send_bdat`, `send_lmtp`, and `send_lmtp_bdat`.
    /// Since the addresses are already validated by the [`ReversePath`] and
    /// [`ForwardPath`] constructors, this only checks that at least one
    /// recipient is present (RFC 5321 Section 3.3).
    ///
    /// RFC 5321 Section 3.3.
    pub(super) fn validate_send_addresses(
        _from: &ReversePath,
        recipients: &[ForwardPath],
    ) -> Result<(), Error> {
        // RFC 5321 Section 3.3: at least one RCPT TO is required.
        if recipients.is_empty() {
            return Err(Error::Protocol(
                "at least one recipient is required (RFC 5321 Section 3.3)".into(),
            ));
        }
        Ok(())
    }

    /// Validate that a string parameter does not contain CR or LF bytes
    /// that could cause SMTP command injection.
    ///
    /// RFC 5321 Section 4.1.2: SMTP command arguments follow the `mailbox`
    /// and `Domain` grammars, which prohibit bare CR and LF.
    pub(super) fn validate_no_crlf(value: &str, param_name: &str) -> Result<(), Error> {
        if value.bytes().any(|b| b == b'\r' || b == b'\n') {
            return Err(Error::Protocol(format!(
                "{param_name} must not contain CR or LF (RFC 5321 Section 4.1.2)"
            )));
        }
        Ok(())
    }

    /// Validate a general SMTP `String` argument as printable US-ASCII.
    ///
    /// RFC 5321 Sections 4.1.1.6-4.1.1.7 use `String` for VRFY/EXPN
    /// arguments. This helper enforces the transport-safety constraints:
    /// no ASCII control characters and no non-ASCII bytes.
    pub(super) fn validate_ascii_string(value: &str, param_name: &str) -> Result<(), Error> {
        for &b in value.as_bytes() {
            if b < 0x20 || b == 0x7F {
                return Err(Error::Protocol(format!(
                    "{param_name} 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!(
                    "{param_name} 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 non-ASCII UTF-8 in VRFY/EXPN
    /// arguments when the `SMTPUTF8` parameter is sent, but SMTP command
    /// arguments still must not contain ASCII control characters
    /// (RFC 5321 Section 4.1.2).
    pub(super) fn validate_utf8_string(value: &str, param_name: &str) -> Result<(), Error> {
        for &b in value.as_bytes() {
            if b < 0x20 || b == 0x7F {
                return Err(Error::Protocol(format!(
                    "{param_name} 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 message data for the DATA path.
    ///
    /// Delegates to shared validators for NUL bytes, bare CR/LF, and
    /// line length. The DATA path adds CRLF before the terminating dot,
    /// so trailing-segment length includes +2 for the implicit CRLF.
    ///
    /// # Checks
    /// 1. **RFC 5321 Section 4.5.2** — no NUL bytes (0x00).
    /// 2. **RFC 5321 Section 2.3.8** — no bare CR or bare LF.
    /// 3. **RFC 5321 Section 4.5.3.1.6** — text lines ≤ 1000 octets
    ///    (including CRLF, not counting the transparency dot).
    pub(super) fn validate_data_message(data: &[u8]) -> Result<(), Error> {
        Self::validate_no_nul_bytes_in_data(data)?;
        Self::validate_no_bare_crlf(data)?;
        // DATA adds CRLF before the terminating dot (RFC 5321 Section
        // 4.1.1.4), so the trailing segment's effective length is +2.
        // RFC 5321 Section 4.5.3.1.6: the 1000-octet limit explicitly
        // excludes "the leading dot duplicated for transparency", so
        // dot-stuffing overhead is not counted against the limit.
        Self::validate_text_line_lengths(data, true)?;
        Ok(())
    }

    /// Validate that message data contains no NUL bytes (DATA path).
    ///
    /// RFC 5321 Section 4.5.2: "In the absence of a server-offered
    /// SMTP extension explicitly permitting it, a sending SMTP system
    /// MUST NOT send a message that contains octets with a value of
    /// 0x00."
    pub(super) fn validate_no_nul_bytes_in_data(data: &[u8]) -> Result<(), Error> {
        if data.contains(&0x00) {
            return Err(Error::Protocol(
                "message data contains NUL byte (0x00); \
                 SMTP DATA must not contain NUL octets \
                 (RFC 5321 Section 4.5.2)"
                    .into(),
            ));
        }
        Ok(())
    }

    /// Validate that message data uses CRLF line endings with no bare
    /// CR or bare LF.
    ///
    /// RFC 5321 Section 2.3.8: SMTP uses CRLF as the line ending; a
    /// bare CR (`\r` not followed by `\n`) or bare LF (`\n` not
    /// preceded by `\r`) violates the protocol and can cause
    /// interoperability failures.
    ///
    /// Shared by both the DATA and BDAT (without BINARYMIME) paths.
    /// RFC 3030 Section 3: "The CHUNKING service extension does not
    /// modify in any way the requirements for the content of the
    /// message."
    pub(super) fn validate_no_bare_crlf(data: &[u8]) -> Result<(), Error> {
        for i in 0..data.len() {
            if data[i] == b'\r' && data.get(i + 1) != Some(&b'\n') {
                return Err(Error::Protocol(
                    "message data contains bare CR (\\r not followed by \\n); \
                     SMTP requires CRLF line endings (RFC 5321 Section 2.3.8)"
                        .into(),
                ));
            }
            if data[i] == b'\n' && (i == 0 || data[i - 1] != b'\r') {
                return Err(Error::Protocol(
                    "message data contains bare LF (\\n not preceded by \\r); \
                     SMTP requires CRLF line endings (RFC 5321 Section 2.3.8)"
                        .into(),
                ));
            }
        }
        Ok(())
    }

    /// Validate that no text line exceeds 1000 octets (including CRLF).
    ///
    /// RFC 5321 Section 4.5.3.1.6: "The maximum total length of a text
    /// line including the `<CRLF>` is 1000 octets (not counting the
    /// leading dot duplicated for transparency)."
    ///
    /// `trailing_crlf_padding`: when `true`, the trailing segment
    /// (data not ending with CRLF) has +2 added to its effective
    /// length because the DATA path adds CRLF before the terminating
    /// dot (RFC 5321 Section 4.1.1.4). For BDAT, pass `false` since
    /// no implicit CRLF is appended.
    ///
    /// Shared by both the DATA and BDAT (without BINARYMIME) paths.
    pub(super) fn validate_text_line_lengths(
        data: &[u8],
        trailing_crlf_padding: bool,
    ) -> Result<(), Error> {
        let mut line_start: usize = 0;

        for i in 0..data.len() {
            // RFC 5321 Section 4.5.3.1.6: check line length at each CRLF.
            if data[i] == b'\n' && i > 0 && data[i - 1] == b'\r' {
                let line_len = i + 1 - line_start; // includes CRLF
                if line_len > Self::SMTP_MAX_TEXT_LINE {
                    return Err(Error::Protocol(format!(
                        "message text line exceeds {}-octet limit ({line_len} octets) \
                         (RFC 5321 Section 4.5.3.1.6)",
                        Self::SMTP_MAX_TEXT_LINE
                    )));
                }
                line_start = i + 1;
            }
        }

        // Check the trailing segment (data not ending with CRLF).
        let remaining = data.len() - line_start;
        if remaining > 0 {
            let effective_len = if trailing_crlf_padding {
                // DATA adds CRLF before the terminating dot.
                remaining + 2
            } else {
                remaining
            };
            if effective_len > Self::SMTP_MAX_TEXT_LINE {
                return Err(Error::Protocol(format!(
                    "message text line exceeds {}-octet limit ({effective_len} octets) \
                     (RFC 5321 Section 4.5.3.1.6)",
                    Self::SMTP_MAX_TEXT_LINE
                )));
            }
        }

        Ok(())
    }

    /// RFC 5321 Section 4.5.3.1.6: "The maximum total length of a text
    /// line including the `<CRLF>` is 1000 octets (not counting the
    /// leading dot duplicated for transparency)."
    pub(super) const SMTP_MAX_TEXT_LINE: usize = 1000;

    /// Compute the message size for the RFC 1870 SIZE parameter.
    ///
    /// RFC 1870 Section 5: "The message size is defined as the number
    /// of octets, including CR-LF pairs, but not the SMTP DATA
    /// command's terminating dot or doubled quoting dots."
    /// The SIZE parameter uses the raw message size — dot-stuffing
    /// overhead is SMTP transfer encoding and is excluded.
    ///
    /// RFC 1870 Section 3: SIZE includes "the terminating CRLF of the
    /// last line." When the message does not already end with CRLF, the
    /// sender adds one before the terminating dot (RFC 5321 Section
    /// 4.1.1.4), and this implicit CRLF must be counted.
    pub(super) fn data_message_size(message: &[u8]) -> usize {
        // RFC 1870 Section 5: "The message size is defined as the number
        // of octets, including CR-LF pairs, but not the SMTP DATA
        // command's terminating dot or doubled quoting dots."
        // The SIZE parameter uses the raw message size — dot-stuffing
        // overhead is SMTP transfer encoding and is excluded.
        if message.ends_with(b"\r\n") {
            message.len()
        } else {
            // RFC 1870 Section 3 / RFC 5321 Section 4.1.1.4: the DATA
            // path adds an implicit CRLF before the terminating dot when
            // the message does not already end with CRLF. This implicit
            // CRLF terminates the last line of the message and is part
            // of the message content, so it is included in the size.
            message.len() + 2
        }
    }

    /// Send the MAIL FROM command to the server and check for success.
    ///
    /// RFC 5321 Section 4.1.1.2: Encodes the command with optional ESMTP
    /// parameters, validates command-line length (Section 4.5.3.1.4),
    /// sends it, and verifies the server's response.
    pub(super) async fn send_mail_from(
        inner: &mut SmtpInner,
        from: &ReversePath,
        message: &[u8],
        message_size: usize,
        params: Option<&crate::types::MailFromParams>,
    ) -> Result<(), Error> {
        let mut buf = BytesMut::new();
        let is_8bit = Self::message_contains_8bit(message);
        Self::encode_mail_from_cmd(
            &inner.capabilities,
            &mut buf,
            from,
            message_size,
            params,
            is_8bit,
        )?;
        // RFC 5321 Section 4.5.3.1.4 / RFC 1870 Section 4 / RFC 6152
        // Section 7 / RFC 6531 Section 3.4: MAIL FROM has an extended
        // command line limit to accommodate ESMTP parameters.
        Self::validate_mail_from_line_length(buf.len())?;
        inner.write_all(&buf).await?;
        let resp = inner.read_response().await?;
        if !resp.is_success() {
            return Err(Self::response_to_error(resp));
        }
        Ok(())
    }

    /// Send RCPT TO for each recipient and collect results.
    ///
    /// RFC 5321 Section 4.1.1.3: sends a RCPT TO command for each recipient,
    /// tracking which were accepted and which were rejected. If all recipients
    /// are rejected, resets the transaction (RSET) and returns
    /// [`Error::AllRecipientsFailed`].
    ///
    /// When `rcpt_params` is `Some`, each recipient is paired by index with
    /// its corresponding [`RcptToParams`] and encoded via
    /// [`encode_rcpt_to_full`](crate::codec::encode::encode_rcpt_to_full)
    /// to include DSN parameters (NOTIFY, ORCPT per RFC 3461 Sections 4.1–4.2).
    /// When `None`, the plain [`encode_rcpt_to`](crate::codec::encode::encode_rcpt_to)
    /// is used.
    ///
    /// Returns the list of accepted recipient addresses and the list of
    /// rejected recipients with their server responses (RFC 5321 Section 3.3).
    pub(super) async fn send_rcpt_to_batch(
        inner: &mut SmtpInner,
        recipients: &[ForwardPath],
        rcpt_params: Option<&[crate::types::RcptToParams]>,
    ) -> Result<(Vec<ForwardPath>, Vec<crate::types::RejectedRecipient>), Error> {
        let mut buf = BytesMut::new();
        let mut accepted = Vec::new();
        let mut rejected = Vec::new();
        for (i, fp) in recipients.iter().enumerate() {
            buf.clear();
            if let Some(params) = rcpt_params {
                // RFC 3461 Sections 4.1–4.2: encode with DSN parameters.
                encode::encode_rcpt_to_full(&mut buf, fp, &params[i])?;
            } else {
                encode::encode_rcpt_to(&mut buf, fp)?;
            }
            // RFC 5321 Section 4.5.3.1.4 / RFC 3461 Section 5: validate
            // command line length, using the extended 1012-octet limit when
            // DSN parameters are present for this recipient.
            let has_dsn = rcpt_params.is_some_and(|rp| !rp[i].is_empty());
            Self::validate_rcpt_to_line_length(buf.len(), has_dsn)?;
            inner.write_all(&buf).await?;
            let resp = inner.read_response().await?;
            if resp.is_success() {
                accepted.push(fp.clone());
            } else {
                tracing::debug!(
                    recipient = fp.as_str(),
                    code = resp.code,
                    "RCPT TO rejected"
                );
                rejected.push(crate::types::RejectedRecipient {
                    recipient: fp.clone(),
                    response: resp,
                });
            }
        }

        if accepted.is_empty() {
            // RFC 5321 Section 3.3: abort the mail transaction opened by
            // MAIL FROM so the connection is left in a clean state.
            inner.rset_best_effort().await;
            return Err(Error::AllRecipientsFailed {
                count: recipients.len(),
                // Extract just the responses for the error variant.
                responses: rejected.into_iter().map(|r| r.response).collect(),
            });
        }

        Ok((accepted, rejected))
    }

    /// Validate all prerequisites for the DATA send path and return message size
    /// (RFC 5321 Section 3.3, RFC 3030 Section 2, RFC 1870 Section 3).
    ///
    /// Shared by `send_with_params` and `send_lmtp`. Checks:
    /// - BODY=BINARYMIME is rejected (incompatible with DATA, RFC 3030 Section 2)
    /// - ESMTP params are valid for server capabilities (RFC 5321 Section 2.2.1)
    /// - Message size within server limit (RFC 1870 Sections 3–4)
    /// - DATA message format: CRLF line endings, line length (RFC 5321 Section 2.3.8)
    /// - 7-bit content when required (RFC 1652 Section 1 / RFC 6152 Section 3)
    pub(super) fn validate_data_prerequisites(
        capabilities: &ServerCapabilities,
        message: &[u8],
        params: Option<&crate::types::MailFromParams>,
        is_tls: bool,
    ) -> Result<usize, Error> {
        // RFC 3030 Section 2: "BINARYMIME cannot be used with the DATA
        // command." The DATA path applies dot-stuffing which corrupts
        // binary content.
        if let Some(p) = params {
            if p.body == Some(crate::types::BodyType::BinaryMime) {
                return Err(Error::Protocol(
                    "BODY=BINARYMIME cannot be used with DATA; use BDAT/CHUNKING \
                     instead (RFC 3030 Section 2)"
                        .into(),
                ));
            }
        }
        // RFC 5321 Section 2.2.1: validate ESMTP params against capabilities.
        Self::validate_params(capabilities, params, is_tls)?;
        // RFC 1870 Section 3: SIZE uses the original message size (excluding
        // dot-stuffing overhead, which is protocol overhead per RFC 5321 Section 4.5.2).
        let message_size = Self::data_message_size(message);
        // RFC 1870 Section 4: check message size against server limit.
        Self::check_size_limit(capabilities, message_size)?;
        // RFC 5321 Section 2.3.8: DATA requires CRLF line endings.
        Self::validate_data_message(message)?;
        // RFC 1652 Section 1 / RFC 5321 Section 2.3.1: without 8BITMIME,
        // SMTP is limited to 7-bit content.
        // RFC 6152 Section 3: BODY=7BIT declares content is all 7-bit;
        // enforce this regardless of server capabilities.
        if Self::is_body_declared_7bit(params) || !capabilities.supports_8bitmime() {
            Self::validate_7bit_content(message)?;
        }
        Ok(message_size)
    }

    /// Validate all prerequisites for the BDAT send path
    /// (RFC 3030 Section 3, RFC 1870 Section 4).
    ///
    /// Shared by `send_bdat` and `send_lmtp_bdat`. Checks:
    /// - CHUNKING extension is available (RFC 3030 Section 3)
    /// - ESMTP params are valid for server capabilities (RFC 5321 Section 2.2.1)
    /// - Message size within server limit (RFC 1870 Section 4)
    /// - NUL byte and 7-bit content restrictions (RFC 5321 Section 4.5.2)
    pub(super) fn validate_bdat_prerequisites(
        capabilities: &ServerCapabilities,
        message: &[u8],
        params: Option<&crate::types::MailFromParams>,
        is_tls: bool,
    ) -> Result<(), Error> {
        // RFC 3030 Section 3: CHUNKING extension required.
        if !capabilities.supports_chunking() {
            return Err(Error::Protocol(
                "server does not support CHUNKING (RFC 3030)".into(),
            ));
        }
        // RFC 5321 Section 2.2.1: validate ESMTP params against capabilities.
        // Note: BODY=BINARYMIME is valid with BDAT (RFC 3030 Section 2).
        Self::validate_params(capabilities, params, is_tls)?;
        // RFC 1870 Section 4: check message size against server limit.
        Self::check_size_limit(capabilities, message.len())?;
        // BDAT does not require CRLF line endings or enforce line length limits
        // (RFC 3030 Section 3). However, NUL and 7-bit content restrictions
        // still apply without BINARYMIME/8BITMIME.
        Self::validate_bdat_content(capabilities, message, params)?;
        Ok(())
    }

    /// Validate message content for BDAT/CHUNKING paths.
    ///
    /// RFC 3030 Section 3: "The CHUNKING service extension does not
    /// modify in any way the requirements for the content of the
    /// message." Without BINARYMIME, all standard SMTP content
    /// requirements apply:
    ///
    /// - **RFC 5321 Section 4.5.2** — no NUL bytes.
    /// - **RFC 5321 Section 2.3.8** — no bare CR or bare LF.
    /// - **RFC 5321 Section 4.5.3.1.6** — text lines ≤ 1000 octets
    ///   (including CRLF).
    /// - **RFC 1652 Section 1** — 7-bit content unless 8BITMIME.
    /// - **RFC 6152 Section 3** — BODY=7BIT forces 7-bit.
    ///
    /// RFC 3030 Section 4 allows arbitrary octets for BINARYMIME payloads,
    /// but RFC 3030 Section 2 still requires canonical CRLF line endings for
    /// top-level `text/*` MIME entities.
    pub(super) fn validate_bdat_content(
        capabilities: &ServerCapabilities,
        message: &[u8],
        params: Option<&crate::types::MailFromParams>,
    ) -> Result<(), Error> {
        let is_binary = params.is_some_and(|p| p.body == Some(crate::types::BodyType::BinaryMime));
        if is_binary {
            // RFC 3030 Section 2: a BINARYMIME message is still expected to be
            // canonical MIME. In particular, top-level text/* content MUST use
            // CRLF line endings even though non-text bodies may carry arbitrary
            // octets.
            if Self::binarymime_requires_canonical_text_lines(message) {
                Self::validate_no_bare_crlf(message)?;
            }
            return Ok(());
        }

        Self::validate_no_nul_bytes(message)?;
        // RFC 3030 Section 3: content requirements are unchanged
        // without BINARYMIME — enforce CRLF and line length.
        Self::validate_no_bare_crlf(message)?;
        // BDAT does not append CRLF before a terminator (no dot
        // terminator), so trailing_crlf_padding is false.
        Self::validate_text_line_lengths(message, false)?;
        if Self::is_body_declared_7bit(params) || !capabilities.supports_8bitmime() {
            Self::validate_7bit_content(message)?;
        }
        Ok(())
    }

    /// Returns `true` when a BINARYMIME payload still needs canonical line
    /// validation because its top-level MIME type contains line-oriented
    /// message syntax.
    ///
    /// RFC 3030 Section 2 says the MIME message itself must be properly
    /// formed and specifically calls out `text/*` as requiring
    /// CRLF-terminated lines. The same canonical requirement applies to the
    /// textual structure of `multipart/*` and `message/*` entities, which
    /// carry MIME boundaries, nested headers, and other RFC 5322-style line
    /// syntax. When `Content-Type` is missing or malformed, MIME defaults to
    /// `text/plain` (RFC 2045 Section 5.2), so the conservative choice is to
    /// keep canonical line validation enabled.
    pub(super) fn binarymime_requires_canonical_text_lines(message: &[u8]) -> bool {
        match Self::top_level_mime_type(message) {
            Some(mime_type) => {
                mime_type.starts_with("text/")
                    || mime_type.starts_with("multipart/")
                    || mime_type.starts_with("message/")
            }
            None => true,
        }
    }

    /// Extract the top-level MIME media type from the RFC 5322 header block.
    ///
    /// Returns the normalized `type/subtype` token without parameters, or
    /// `None` when no usable `Content-Type` field is present.
    ///
    /// RFC 2045 Section 5.1 defines `Content-Type`; RFC 2045 Section 5.2
    /// defaults a missing field to `text/plain`.
    pub(super) fn top_level_mime_type(message: &[u8]) -> Option<String> {
        let header_len = Self::header_block_len(message);
        if header_len == 0 {
            return None;
        }

        let content_type = Self::header_field_value(&message[..header_len], "content-type")?;
        let raw_type = content_type
            .split(';')
            .next()
            .unwrap_or_default()
            .trim()
            .to_ascii_lowercase();
        let slash = raw_type.find('/')?;
        let type_part = raw_type[..slash].trim();
        let subtype_part = raw_type[slash + 1..].trim();
        if type_part.is_empty() || subtype_part.is_empty() {
            return None;
        }
        Some(format!("{type_part}/{subtype_part}"))
    }

    /// Extract a case-insensitive RFC 5322 header field value from a header block.
    ///
    /// Continuation lines are unfolded by joining them with a single space
    /// (RFC 5322 Section 2.2.3).
    pub(super) fn header_field_value(header_block: &[u8], target_name: &str) -> Option<String> {
        let mut current_name: Option<String> = None;
        let mut current_value = String::new();

        for raw_line in header_block.split(|&byte| byte == b'\n') {
            let line = raw_line.strip_suffix(b"\r").unwrap_or(raw_line);
            if line.is_empty() {
                break;
            }

            if matches!(line.first(), Some(b' ' | b'\t')) {
                if current_name.as_deref() == Some(target_name) {
                    if !current_value.is_empty() {
                        current_value.push(' ');
                    }
                    current_value.push_str(String::from_utf8_lossy(line).trim());
                }
                continue;
            }

            if current_name.as_deref() == Some(target_name) {
                return Some(current_value);
            }

            let colon = line.iter().position(|&byte| byte == b':')?;
            current_name = Some(String::from_utf8_lossy(&line[..colon]).to_ascii_lowercase());
            current_value.clear();
            current_value.push_str(String::from_utf8_lossy(&line[colon + 1..]).trim());
        }

        (current_name.as_deref() == Some(target_name)).then_some(current_value)
    }

    /// Check if MAIL FROM params declare BODY=7BIT.
    ///
    /// RFC 6152 Section 3: BODY=7BIT declares content is all 7-bit;
    /// the library must enforce this regardless of server capabilities.
    pub(super) fn is_body_declared_7bit(params: Option<&crate::types::MailFromParams>) -> bool {
        params.is_some_and(|p| p.body == Some(crate::types::BodyType::SevenBit))
    }

    /// Validate that message data does not contain NUL bytes.
    ///
    /// RFC 5321 Section 4.5.2: "In the absence of a server-offered SMTP
    /// extension explicitly permitting it, a sending SMTP system MUST NOT
    /// send a message that contains octets with a value of 0x00."
    ///
    /// The BINARYMIME extension (RFC 3030 Section 4) permits NUL bytes;
    /// CHUNKING alone does not.
    pub(super) fn validate_no_nul_bytes(data: &[u8]) -> Result<(), Error> {
        if data.contains(&0x00) {
            return Err(Error::Protocol(
                "message data contains NUL byte (0x00); \
                 SMTP MUST NOT send NUL octets without BINARYMIME \
                 (RFC 5321 Section 4.5.2 / RFC 3030 Section 4)"
                    .into(),
            ));
        }
        Ok(())
    }

    /// Validate that message data contains only 7-bit content.
    ///
    /// RFC 1652 Section 1: "In the absence of [the 8BITMIME] extension,
    /// an SMTP client MUST NOT transmit 8-bit data in the mail body."
    ///
    /// RFC 5321 Section 2.3.1: without 8BITMIME, SMTP is limited to the
    /// transmission of 7-bit US-ASCII content.
    ///
    /// This check applies on non-BINARYMIME send paths whenever the server
    /// does NOT advertise 8BITMIME.
    pub(super) fn validate_7bit_content(data: &[u8]) -> Result<(), Error> {
        for &b in data {
            if b > 0x7F {
                return Err(Error::Protocol(
                    "message contains 8-bit content (bytes > 0x7F) but the server \
                     does not advertise 8BITMIME; use BODY=8BITMIME with a server \
                     that supports it, or encode the message as 7-bit \
                     (RFC 1652 Section 1 / RFC 5321 Section 2.3.1)"
                        .into(),
                ));
            }
        }
        Ok(())
    }

    /// Encode a MAIL FROM command into `buf`, merging caller-supplied
    /// [`MailFromParams`] with the SIZE parameter derived from the server's
    /// advertised capabilities (RFC 1870 Section 3).
    ///
    /// When `params` is `None`, the basic `MAIL FROM:<addr>` form is used
    /// with an optional SIZE parameter. When `params` is `Some`, the
    /// extended form is used, including BODY= (RFC 1652) and SMTPUTF8
    /// (RFC 6531) parameters if set by the caller.
    ///
    /// RFC 6152 Section 3: when the message contains 8-bit data
    /// (`message_is_8bit` is true) and the server supports 8BITMIME,
    /// `BODY=8BITMIME` is automatically included in MAIL FROM — even
    /// when the caller did not supply explicit [`MailFromParams`].
    pub(super) fn encode_mail_from_cmd(
        capabilities: &ServerCapabilities,
        buf: &mut BytesMut,
        from: &ReversePath,
        message_len: usize,
        params: Option<&crate::types::MailFromParams>,
        message_is_8bit: bool,
    ) -> Result<(), Error> {
        if let Some(p) = params {
            // Merge caller params with auto-SIZE.
            let mut merged = p.clone();
            if capabilities.supports_size() && merged.size.is_none() {
                merged.size = Some(message_len as u64);
            }
            // RFC 6531 Section 3.4: "If the SMTPUTF8 MAIL FROM parameter
            // is used, the BODY parameter (RFC 6152) MUST also be used,
            // with a value of '8BITMIME'." Auto-add BODY=8BITMIME when
            // SMTPUTF8 is set and the caller hasn't set a BODY parameter.
            //
            // RFC 6152 Section 3: also auto-declare BODY=8BITMIME when
            // the message contains 8-bit content and the server advertises
            // 8BITMIME.
            if merged.body.is_none()
                && (merged.smtputf8 || (message_is_8bit && capabilities.supports_8bitmime()))
            {
                merged.body = Some(crate::types::BodyType::EightBitMime);
            }
            // RFC 5321 Section 4.5.2: 7-bit is the default encoding.
            // Silently omit the redundant BODY=7BIT parameter when the
            // server does not advertise 8BITMIME or BINARYMIME, since
            // the BODY keyword is an ESMTP extension (RFC 6152 Section 3).
            if merged.body == Some(crate::types::BodyType::SevenBit)
                && !capabilities.supports_8bit_or_binary()
            {
                merged.body = None;
            }
            encode::encode_mail_from_full(buf, from, &merged)?;
        } else if message_is_8bit && capabilities.supports_8bitmime() {
            // RFC 6152 Section 3: "When a client SMTP transmits a message
            // body consisting of 8bit data to a server SMTP, it must also
            // transmit a BODY=8BITMIME parameter on the MAIL FROM command."
            let auto_params = crate::types::MailFromParams {
                size: if capabilities.supports_size() {
                    Some(message_len as u64)
                } else {
                    None
                },
                body: Some(crate::types::BodyType::EightBitMime),
                smtputf8: false,
                ..Default::default()
            };
            encode::encode_mail_from_full(buf, from, &auto_params)?;
        } else {
            let size = if capabilities.supports_size() {
                Some(message_len as u64)
            } else {
                None
            };
            encode::encode_mail_from(buf, from, size)?;
        }
        Ok(())
    }

    /// Check whether message data contains any 8-bit octets (bytes > 0x7F).
    ///
    /// Used to auto-detect 8-bit content for the BODY=8BITMIME declaration
    /// per RFC 6152 Section 3.
    pub(super) fn message_contains_8bit(data: &[u8]) -> bool {
        data.iter().any(|&b| b > 0x7F)
    }

    /// Check whether the RFC 5322 header block contains UTF-8 octets that
    /// require the SMTPUTF8 extension.
    ///
    /// RFC 6531 Section 3.1 item 4 requires the SMTPUTF8 MAIL FROM parameter
    /// when the message being sent is internationalized. RFC 6532 Sections 3.2
    /// and 3.6 permit UTF-8 directly in header fields, so any non-ASCII octet
    /// before the blank-line header/body separator means the message needs
    /// SMTPUTF8 support.
    pub(super) fn message_headers_require_smtputf8(data: &[u8]) -> bool {
        let header_end = Self::header_block_len(data);
        data[..header_end].iter().any(|&b| b > 0x7F)
    }

    /// Determine the length of the leading RFC 5322 header block, if present.
    ///
    /// RFC 5322 Section 2.2: header fields are a sequence of field-name lines
    /// optionally followed by folded continuation lines. Raw BDAT payloads and
    /// malformed messages may omit headers entirely; in those cases this
    /// returns 0 so body octets are not mistaken for header data.
    pub(super) fn header_block_len(data: &[u8]) -> usize {
        let mut offset = 0usize;
        let mut saw_header = false;
        let mut saw_complete_line = false;

        while offset < data.len() {
            let line_end = data[offset..]
                .iter()
                .position(|&byte| byte == b'\n')
                .map_or(data.len(), |idx| offset + idx);
            let line = if line_end > offset && data[line_end.saturating_sub(1)] == b'\r' {
                &data[offset..line_end - 1]
            } else {
                &data[offset..line_end]
            };

            if line.is_empty() {
                return if saw_header { offset } else { 0 };
            }

            let is_continuation = matches!(line.first(), Some(b' ' | b'\t'));
            if is_continuation {
                if !saw_header {
                    return 0;
                }
            } else if Self::looks_like_header_field_line(line) {
                saw_header = true;
            } else {
                return if saw_header { offset } else { 0 };
            }

            if line_end == data.len() {
                // RFC 5322 Section 2.2 models header fields as lines. If the
                // entire payload is a single unterminated header-looking line,
                // treat it conservatively as body data so raw payloads such as
                // `Note: café` are not reclassified as SMTPUTF8 headers.
                return if saw_header && saw_complete_line {
                    data.len()
                } else {
                    0
                };
            }
            saw_complete_line = true;
            offset = line_end + 1;
        }

        if saw_header {
            data.len()
        } else {
            0
        }
    }

    /// Check whether a line begins with a syntactically valid RFC 5322 field name.
    ///
    /// RFC 5322 Section 3.6: `field = field-name ":" unstructured`.
    /// RFC 5322 Section 3.6.8: `field-name = 1*ftext`.
    pub(super) fn looks_like_header_field_line(line: &[u8]) -> bool {
        let Some(colon_idx) = line.iter().position(|&byte| byte == b':') else {
            return false;
        };
        colon_idx > 0
            && line[..colon_idx]
                .iter()
                .all(|&byte| (33..=57).contains(&byte) || (59..=126).contains(&byte))
    }

    /// Check whether a send operation requires the SMTPUTF8 extension.
    ///
    /// RFC 6531 Section 3.1 item 4 requires SMTPUTF8 when the message being
    /// sent is internationalized. RFC 6531 Section 3.3 extends SMTP mailbox
    /// syntax to UTF-8 for MAIL FROM and RCPT TO only when SMTPUTF8 is active.
    pub(super) fn send_requires_smtputf8(
        from: &ReversePath,
        recipients: &[ForwardPath],
        message: &[u8],
    ) -> bool {
        from.requires_smtputf8()
            || recipients.iter().any(ForwardPath::requires_smtputf8)
            || Self::message_headers_require_smtputf8(message)
    }

    /// Merge caller-supplied MAIL FROM parameters with SMTPUTF8 inferred
    /// from the envelope and raw message.
    ///
    /// RFC 6531 Section 3.1 item 4: SMTPUTF8 is required for
    /// internationalized messages.
    /// RFC 6531 Section 3.3: non-ASCII envelope addresses require SMTPUTF8.
    /// RFC 6531 Section 3.4: the MAIL FROM parameter must be present when
    /// SMTPUTF8 is required and supported.
    pub(super) fn effective_mail_from_params(
        capabilities: &ServerCapabilities,
        from: &ReversePath,
        recipients: &[ForwardPath],
        message: &[u8],
        params: Option<&crate::types::MailFromParams>,
    ) -> Result<crate::types::MailFromParams, Error> {
        let mut effective = params.cloned().unwrap_or_default();
        if Self::send_requires_smtputf8(from, recipients, message) {
            if !capabilities.supports_smtputf8() {
                return Err(Error::SmtpUtf8Required);
            }
            effective.smtputf8 = true;
        }
        Ok(effective)
    }

    /// Check message size against the server's advertised SIZE limit.
    ///
    /// RFC 1870 Section 4: the client SHOULD NOT send a message larger
    /// than the server's declared fixed maximum message size.
    pub(super) fn check_size_limit(
        capabilities: &ServerCapabilities,
        message_len: usize,
    ) -> Result<(), Error> {
        if let Some(limit) = capabilities.size_limit() {
            if message_len as u64 > limit {
                return Err(Error::Protocol(format!(
                    "message size ({message_len} bytes) exceeds server SIZE limit \
                     ({limit} bytes) (RFC 1870 Section 4)"
                )));
            }
        }
        Ok(())
    }

    /// Validate that the server advertises support for each ESMTP
    /// extension the caller is requesting via [`MailFromParams`].
    ///
    /// RFC 5321 Section 2.2.1: "An SMTP client MUST NOT use SMTP
    /// service extensions that have not been offered by the server."
    pub(super) fn validate_params(
        capabilities: &ServerCapabilities,
        params: Option<&crate::types::MailFromParams>,
        is_tls: bool,
    ) -> Result<(), Error> {
        let Some(p) = params else { return Ok(()) };
        Self::validate_extension_caps(capabilities, p, is_tls)?;
        Self::validate_smtputf8_body(p)?;
        Self::validate_body_type(capabilities, p)
    }

    /// RFC 5321 Section 2.2.1: "An SMTP client MUST NOT use SMTP service
    /// extensions that have not been offered by the server."
    #[allow(clippy::too_many_lines)]
    pub(super) fn validate_extension_caps(
        capabilities: &ServerCapabilities,
        p: &crate::types::MailFromParams,
        is_tls: bool,
    ) -> Result<(), Error> {
        if p.size.is_some() && !capabilities.supports_size() {
            return Err(Error::Protocol(
                "SIZE parameter requires server SIZE support \
                 (RFC 1870 Section 3 / RFC 5321 Section 2.2.1)"
                    .into(),
            ));
        }
        if p.smtputf8 && !capabilities.supports_smtputf8() {
            return Err(Error::Protocol(
                "SMTPUTF8 parameter requires server SMTPUTF8 support \
                 (RFC 6531 Section 3.4)"
                    .into(),
            ));
        }
        if p.smtputf8 && !capabilities.supports_8bitmime() {
            return Err(Error::Protocol(
                "SMTPUTF8 requires server 8BITMIME support; \
                 the server advertises SMTPUTF8 but not 8BITMIME \
                 (RFC 6531 Section 3.4 / Section 3.2)"
                    .into(),
            ));
        }
        if p.requiretls && !capabilities.supports_requiretls() {
            return Err(Error::Protocol(
                "REQUIRETLS parameter requires server REQUIRETLS support \
                 (RFC 8689 Section 3 / RFC 5321 Section 2.2.1)"
                    .into(),
            ));
        }
        // RFC 8689 Section 3: "the SMTP session used to send a given
        // message MUST itself be TLS-protected."
        if p.requiretls && !is_tls {
            return Err(Error::Protocol(
                "REQUIRETLS requires a TLS-protected session; \
                 the current connection is not encrypted \
                 (RFC 8689 Section 3)"
                    .into(),
            ));
        }
        if (p.ret.is_some() || p.envid.is_some()) && !capabilities.supports_dsn() {
            return Err(Error::Protocol(
                "DSN parameters (RET/ENVID) require server DSN support \
                 (RFC 3461 Section 4 / RFC 5321 Section 2.2.1)"
                    .into(),
            ));
        }
        if p.auth.is_some() && !capabilities.supports_auth_extension() {
            return Err(Error::Protocol(
                "AUTH parameter requires server AUTH support \
                 (RFC 4954 Section 5 / RFC 5321 Section 2.2.1)"
                    .into(),
            ));
        }
        // SmtpAuthParam::Mailbox contains a validated Mailbox newtype that
        // cannot be empty by construction (RFC 5321 Section 4.1.2).
        if (p.hold_for.is_some() || p.hold_until.is_some())
            && !capabilities.supports_future_release()
        {
            return Err(Error::Protocol(
                "HOLDFOR/HOLDUNTIL parameters require server FUTURERELEASE support \
                 (RFC 4865 Section 5 / RFC 5321 Section 2.2.1)"
                    .into(),
            ));
        }
        // RFC 4865 Section 5: HOLDFOR and HOLDUNTIL are mutually exclusive.
        // A MAIL FROM command MUST contain at most one of these parameters.
        if p.hold_for.is_some() && p.hold_until.is_some() {
            return Err(Error::Protocol(
                "HOLDFOR and HOLDUNTIL are mutually exclusive; \
                 only one may be specified per MAIL FROM command \
                 (RFC 4865 Section 5)"
                    .into(),
            ));
        }
        // RFC 4865 Section 4: "the value MUST be less than or equal to the
        // [server-advertised] maximum hold interval."
        if let Some(hold_for) = p.hold_for {
            validate_hold_for_seconds(hold_for)?;
            if let Some(max_interval) = capabilities.future_release_max_interval() {
                if hold_for > max_interval {
                    return Err(Error::Protocol(format!(
                        "HOLDFOR value {hold_for}s exceeds server maximum \
                         {max_interval}s (RFC 4865 Section 4)"
                    )));
                }
            }
        }
        // RFC 4865 Section 4: "the client MUST NOT set a hold-until time
        // that is later than the [server-advertised] max-datetime."
        // Both values are RFC 3339 datetime strings.  We parse them to
        // UTC epoch seconds for correct chronological comparison across
        // timezone offsets.
        if let Some(ref hold_until) = p.hold_until {
            validate_hold_until_datetime(hold_until)?;
            if let Some(max_datetime) = capabilities.future_release_max_datetime() {
                let hold_key = parse_rfc3339_to_utc_key(hold_until).ok_or_else(|| {
                    Error::Protocol(format!(
                        "HOLDUNTIL must be a valid RFC 3339 date-time: {hold_until} \
                         (RFC 4865 Section 5 / RFC 3339 Section 5.6)"
                    ))
                })?;
                let exceeds = match parse_rfc3339_to_utc_key(max_datetime) {
                    Some(max_key) => hold_key > max_key,
                    // Postel's law: if the server advertises a malformed
                    // max-datetime, ignore that malformed bound rather than
                    // reject a valid client parameter.
                    None => false,
                };
                if exceeds {
                    return Err(Error::Protocol(format!(
                        "HOLDUNTIL value {hold_until} exceeds server maximum \
                         {max_datetime} (RFC 4865 Section 4)"
                    )));
                }
            }
        }
        if p.deliver_by.is_some() && !capabilities.supports_deliver_by() {
            return Err(Error::Protocol(
                "BY parameter requires server DELIVERBY support \
                 (RFC 2852 Section 3 / RFC 5321 Section 2.2.1)"
                    .into(),
            ));
        }
        // RFC 2852 Section 2: the EHLO DELIVERBY parameter is the minimum
        // deliver-by time the server will accept for by-mode Return.
        if let Some(ref db) = p.deliver_by {
            validate_deliver_by_value(db)?;
            if db.mode == crate::types::DeliverByMode::Return && db.seconds > 0 {
                if let Some(min_secs) = capabilities.deliver_by_min() {
                    #[allow(clippy::cast_sign_loss)]
                    let secs = db.seconds as u64;
                    if secs < min_secs {
                        return Err(Error::Protocol(format!(
                            "DELIVERBY value {}s is below server minimum \
                             {min_secs}s (RFC 2852 Section 2)",
                            db.seconds
                        )));
                    }
                }
            }
        }
        Self::validate_future_release_deliver_by_relation(p)?;
        if p.mt_priority.is_some() && !capabilities.supports_mt_priority() {
            return Err(Error::Protocol(
                "MT-PRIORITY parameter requires server MT-PRIORITY support \
                 (RFC 6758 Section 4 / RFC 5321 Section 2.2.1)"
                    .into(),
            ));
        }
        // RFC 6758 Section 4: priority values range from -9 to 9 (the full
        // STANAG 4406 range).  Values outside this range are invalid.
        if let Some(v) = p.mt_priority {
            if !(-9..=9).contains(&v) {
                return Err(Error::Protocol(format!(
                    "MT-PRIORITY value {v} is outside the valid range -9..=9 \
                     (RFC 6758 Section 4)"
                )));
            }
        }
        Ok(())
    }

    /// RFC 4865 Section 5.2.1: the future release time MAY NOT be farther
    /// in the future than the DELIVERBY deadline.
    pub(super) fn validate_future_release_deliver_by_relation(
        p: &crate::types::MailFromParams,
    ) -> Result<(), Error> {
        let Some(deliver_by) = p.deliver_by else {
            return Ok(());
        };

        if let Some(hold_for) = p.hold_for {
            match u64::try_from(deliver_by.seconds) {
                Ok(by_seconds) if hold_for <= by_seconds => {}
                _ => {
                    return Err(Error::Protocol(format!(
                        "HOLDFOR value {hold_for}s exceeds DELIVERBY deadline {}s \
                         (RFC 4865 Section 5.2.1)",
                        deliver_by.seconds
                    )));
                }
            }
        }

        if let Some(ref hold_until) = p.hold_until {
            let hold_key = parse_rfc3339_to_utc_key(hold_until).ok_or_else(|| {
                Error::Protocol(format!(
                    "HOLDUNTIL must be a valid RFC 3339 date-time: {hold_until} \
                     (RFC 4865 Section 5 / RFC 3339 Section 5.6)"
                ))
            })?;
            let now = SystemTime::now().duration_since(UNIX_EPOCH).map_err(|_| {
                Error::Protocol(
                    "system clock is before the Unix epoch; cannot validate HOLDUNTIL against DELIVERBY \
                     (RFC 4865 Section 5.2.1)"
                        .into(),
                )
            })?;
            let now_secs = i64::try_from(now.as_secs()).map_err(|_| {
                Error::Protocol(
                    "system clock exceeds supported range for DELIVERBY comparison \
                     (RFC 4865 Section 5.2.1)"
                        .into(),
                )
            })?;
            let deadline_secs = now_secs.checked_add(deliver_by.seconds).ok_or_else(|| {
                Error::Protocol(
                    "DELIVERBY deadline overflow during FUTURERELEASE validation \
                     (RFC 4865 Section 5.2.1)"
                        .into(),
                )
            })?;
            let deadline_key = (deadline_secs, now.subsec_nanos());
            if hold_key > deadline_key {
                return Err(Error::Protocol(format!(
                    "HOLDUNTIL value {hold_until} exceeds DELIVERBY deadline {}s \
                     (RFC 4865 Section 5.2.1)",
                    deliver_by.seconds
                )));
            }
        }

        Ok(())
    }

    /// RFC 6531 Section 3.6: SMTPUTF8 requires 8-bit-capable BODY type.
    ///
    /// BODY=7BIT is incompatible with SMTPUTF8 because internationalized
    /// headers contain non-ASCII octets. Both BODY=8BITMIME (RFC 6152)
    /// and BODY=BINARYMIME (RFC 3030) are valid:
    ///
    /// > The SMTPUTF8 extension MAY be used as follows:
    /// > - with the BODY=8BITMIME parameter [RFC6152], or
    /// > - with the BODY=BINARYMIME parameter, if the SMTP server
    /// >   advertises BINARYMIME [RFC3030].
    pub(super) fn validate_smtputf8_body(p: &crate::types::MailFromParams) -> Result<(), Error> {
        if p.smtputf8 && p.body == Some(crate::types::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(),
            ));
        }
        Ok(())
    }

    /// RFC 6152 Section 3 / RFC 3030 Section 2: BODY type capability checks.
    ///
    /// BODY=7BIT is always accepted regardless of server capabilities
    /// because 7-bit is the default encoding (RFC 5321 Section 4.5.2).
    /// When the server does not advertise 8BITMIME, the encoder silently
    /// omits the redundant `BODY=7BIT` parameter.
    pub(super) fn validate_body_type(
        capabilities: &ServerCapabilities,
        p: &crate::types::MailFromParams,
    ) -> Result<(), Error> {
        // Explicit SevenBit arm kept for RFC-citation documentation;
        // its body matches the wildcard intentionally.
        #[allow(clippy::match_same_arms)]
        match p.body {
            // RFC 5321 Section 4.5.2: 7-bit is the default transfer
            // encoding — BODY=7BIT is a no-op declaration that does not
            // require 8BITMIME.  The encoder silently omits it when the
            // server lacks 8BITMIME support.
            Some(crate::types::BodyType::SevenBit) => {}
            Some(crate::types::BodyType::EightBitMime) if !capabilities.supports_8bitmime() => {
                return Err(Error::Protocol(
                    "BODY=8BITMIME requires server 8BITMIME support \
                     (RFC 6152 Section 3)"
                        .into(),
                ));
            }
            Some(crate::types::BodyType::BinaryMime) if !capabilities.supports_binarymime() => {
                return Err(Error::Protocol(
                    "BODY=BINARYMIME requires server BINARYMIME support \
                     (RFC 3030 Section 2)"
                        .into(),
                ));
            }
            Some(crate::types::BodyType::BinaryMime) if !capabilities.supports_chunking() => {
                return Err(Error::Protocol(
                    "BODY=BINARYMIME requires server CHUNKING support \
                     (RFC 3030 Section 2)"
                        .into(),
                ));
            }
            _ => {}
        }
        Ok(())
    }

    /// Validates that DSN RCPT TO parameters (NOTIFY, ORCPT) are only
    /// used when the server advertises DSN support.
    ///
    /// RFC 5321 Section 2.2.1: "An SMTP client MUST NOT use SMTP service
    /// extensions that have not been offered by the server."
    /// RFC 3461 Sections 4.1–4.2: NOTIFY and ORCPT are DSN extensions.
    pub(super) fn validate_rcpt_params(
        capabilities: &ServerCapabilities,
        rcpt_params: &[crate::types::RcptToParams],
    ) -> Result<(), Error> {
        let has_dsn_params = rcpt_params.iter().any(|p| !p.is_empty());
        if has_dsn_params && !capabilities.supports_dsn() {
            return Err(Error::Protocol(
                "DSN RCPT TO parameters (NOTIFY/ORCPT) require server DSN support \
                 (RFC 3461 Sections 4.1–4.2 / RFC 5321 Section 2.2.1)"
                    .into(),
            ));
        }
        Ok(())
    }

    /// Send EHLO or LHLO on a bare [`SmtpInner`], and parse capabilities.
    ///
    /// Used during both initial connection setup (before the mutex is
    /// constructed) and at runtime (with the guard dereferenced).
    ///
    /// SMTP uses EHLO (RFC 5321 Section 4.1.1.1). If EHLO is rejected,
    /// falls back to HELO (RFC 5321 Section 4.1.4).
    /// LMTP uses LHLO (RFC 2033 Section 4.1) with no HELO fallback.
    pub(super) async fn ehlo_on_inner(
        inner: &mut SmtpInner,
        protocol: Protocol,
    ) -> Result<(), Error> {
        // RFC 5321 Section 4.1.4: if we previously fell back to HELO
        // (server doesn't support ESMTP), continue using HELO for the
        // remainder of the session.  LMTP always uses LHLO.
        if inner.helo_mode && protocol == Protocol::Smtp {
            // RFC 5321 Section 4.1.1.1 publishes `helo = "HELO" SP Domain`
            // but also says that clients without a meaningful domain name
            // SHOULD send an address-literal. The domain is pre-validated
            // by the DomainOrLiteral type.
            let mut buf = BytesMut::new();
            encode::encode_helo(&mut buf, &inner.ehlo_domain)?;
            Self::validate_command_line_length(buf.len(), "HELO")?;
            inner.write_all(&buf).await?;
            let resp = inner.read_response().await?;
            if resp.code != 250 {
                if resp.is_success() {
                    return Err(Error::Protocol(format!(
                        "HELO response must be 250, got {} \
                         (RFC 5321 Section 4.1.1.1)",
                        resp.code
                    )));
                }
                return Err(Self::response_to_error(resp));
            }
            let greeting_name = resp
                .lines
                .first()
                .map(|l| match l.find(' ') {
                    Some(pos) => l[..pos].to_owned(),
                    None => l.clone(),
                })
                .unwrap_or_default();
            inner.capabilities = ServerCapabilities {
                greeting_name,
                ..Default::default()
            };
            return Ok(());
        }

        // The ehlo_domain is pre-validated by the DomainOrLiteral type.
        // RFC 5321 Section 4.1.1.1: the EHLO argument is a Domain or
        // address-literal. RFC 6531 (SMTPUTF8) does NOT extend this grammar.
        let mut buf = BytesMut::new();

        match protocol {
            Protocol::Smtp => encode::encode_ehlo(&mut buf, &inner.ehlo_domain)?,
            Protocol::Lmtp => encode::encode_lhlo(&mut buf, &inner.ehlo_domain)?,
        }
        // RFC 5321 Section 4.5.3.1.4: validate command line length.
        let cmd_name = match protocol {
            Protocol::Smtp => "EHLO",
            Protocol::Lmtp => "LHLO",
        };
        Self::validate_command_line_length(buf.len(), cmd_name)?;
        inner.write_all(&buf).await?;
        let resp = inner.read_response().await?;
        if resp.code == 250 {
            inner.capabilities = Self::parse_capabilities(&resp);
            return Ok(());
        }

        // RFC 5321 Section 4.1.1.1: EHLO success response MUST use
        // reply code 250. A non-250 2xx response does not conform to the
        // ehlo-ok-rsp grammar and must not be used to parse capabilities.
        if resp.is_success() {
            return Err(Error::Protocol(format!(
                "EHLO response must be 250, got {} \
                 (RFC 5321 Section 4.1.1.1)",
                resp.code
            )));
        }

        // RFC 5321 Section 4.1.4: EHLO rejection codes that warrant HELO fallback.
        // 500 = command not recognized (server doesn't speak ESMTP)
        // 501 = syntax error in parameters (server may not understand EHLO format)
        // 502 = command not implemented (server explicitly lacks ESMTP)
        // 504 = command parameter not implemented
        //
        // 550 is deliberately excluded — it indicates a policy rejection
        // of the client identity, not lack of ESMTP support. HELO fallback
        // would be futile and potentially mask the real issue.
        //
        // Other 5xx codes (e.g., 521 "does not accept mail" per RFC 7504,
        // or 554 "transaction failed") indicate problems unrelated to ESMTP
        // support where HELO won't help.
        //
        // Transient (4xx) errors like 421 ("service not available, closing
        // transmission channel") indicate a server-level problem, NOT that
        // the server doesn't support ESMTP. HELO fallback would be futile
        // in that case.
        //
        // LMTP has no HELO fallback (RFC 2033 Section 4.3: HELO is not
        // valid in LMTP).
        let helo_fallback_codes = [500, 501, 502, 504];
        if protocol == Protocol::Lmtp || !helo_fallback_codes.contains(&resp.code) {
            return Err(Self::response_to_error(resp));
        }

        tracing::debug!(
            code = resp.code,
            "EHLO rejected with 5xx, falling back to HELO (RFC 5321 Section 4.1.4)"
        );

        buf.clear();
        encode::encode_helo(&mut buf, &inner.ehlo_domain)?;
        // RFC 5321 Section 4.5.3.1.4: validate command line length.
        Self::validate_command_line_length(buf.len(), "HELO")?;
        inner.write_all(&buf).await?;
        let resp = inner.read_response().await?;
        // RFC 5321 Section 4.1.1.1: helo-ok-rsp = "250" SP Domain
        // [ SP helo-greet ] CRLF — only code 250 is valid for HELO success.
        if resp.code != 250 {
            if resp.is_success() {
                // Non-250 2xx — protocol violation, same treatment as EHLO.
                return Err(Error::Protocol(format!(
                    "HELO response must be 250, got {} \
                     (RFC 5321 Section 4.1.1.1)",
                    resp.code
                )));
            }
            return Err(Self::response_to_error(resp));
        }
        // HELO does not advertise extensions — use empty capabilities,
        // but preserve the server's greeting domain from the HELO response
        // (RFC 5321 Section 4.1.1.1: helo-ok-rsp = "250" SP Domain [ SP helo-greet ] CRLF).
        let greeting_name = resp
            .lines
            .first()
            .map(|l| match l.find(' ') {
                Some(pos) => l[..pos].to_owned(),
                None => l.clone(),
            })
            .unwrap_or_default();
        inner.capabilities = ServerCapabilities {
            greeting_name,
            ..Default::default()
        };
        // RFC 5321 Section 4.1.4: remember that this server doesn't
        // support ESMTP so subsequent rehlo calls use HELO too.
        inner.helo_mode = true;
        Ok(())
    }

    /// Parse EHLO/LHLO response lines into `ServerCapabilities`.
    ///
    /// Delegates to [`decode::parse_ehlo_capabilities`] which handles
    /// case-insensitive keyword matching (RFC 5321 Section 2.4) and
    /// preserves original mechanism names in `AuthMechanism::Other`
    /// (RFC 4954 Section 3).
    pub(super) fn parse_capabilities(response: &SmtpResponse) -> ServerCapabilities {
        decode::parse_ehlo_capabilities(response)
    }

    /// RFC 5321 Section 4.5.3.1.4: maximum total length of a command
    /// line including the command word and the `<CRLF>` is 512 octets.
    pub(super) const SMTP_MAX_COMMAND_LINE: usize = 512;

    /// Maximum total length of a MAIL FROM command line including
    /// ESMTP extension parameters (RFC 5321 Section 4.5.3.1.4).
    ///
    /// ESMTP extensions increase the base 512-octet limit:
    /// - RFC 1870 Section 4: +26 for the SIZE keyword and value
    /// - RFC 6152 Section 7: +17 for the BODY= parameter
    /// - RFC 6531 Section 3.4: +10 for the SMTPUTF8 keyword
    /// - RFC 8689 Section 3: +11 for the REQUIRETLS keyword
    /// - RFC 3461 Section 4.3/4.4: +109 for RET= and ENVID= params
    /// - RFC 4865 Section 5: +34 for HOLDFOR/HOLDUNTIL
    /// - RFC 2852 Section 4: +17 for BY= parameter
    /// - RFC 6758 Section 4: +16 for MT-PRIORITY= parameter
    /// - RFC 4954 Section 3: +500 for AUTH= submitter identity
    pub(super) const SMTP_MAX_MAIL_FROM_LINE: usize =
        512 + 26 + 17 + 10 + 11 + 109 + 34 + 17 + 16 + 500;

    /// RFC 3461 Section 5: maximum total length of a RCPT TO command
    /// line when DSN parameters (NOTIFY, ORCPT) are present.
    ///
    /// RFC 3461 Section 5 increases the RCPT TO line limit by 500 octets
    /// beyond the base 512-octet limit (RFC 5321 Section 4.5.3.1.4),
    /// yielding a maximum of 1012 octets.
    pub(super) const SMTP_MAX_RCPT_TO_DSN_LINE: usize = 1012;

    /// RFC 5321 Section 4.5.3.1.3: maximum total length of a
    /// reverse-path or forward-path including the punctuation
    /// and element separators (i.e., the `<` and `>` delimiters).
    ///
    /// Path-length validation is now performed by [`ReversePath::new`]
    /// and [`ForwardPath::new`] at construction time. This constant is
    /// retained for use in test assertions.
    #[cfg(test)]
    pub(super) const SMTP_MAX_PATH_LENGTH: usize = 256;

    /// Maximum reply line length the client will accept, including the
    /// 3-digit reply code and the terminating CRLF.
    ///
    /// RFC 5321 Section 4.5.3.1.5 specifies a 512-octet limit for
    /// compliant servers. However, per Postel's law ("be liberal in
    /// what you accept"), we use a permissive 8192-octet limit to
    /// tolerate non-conformant servers (e.g., Exchange, Postfix) that
    /// sometimes exceed the RFC limit in practice.
    pub(super) const SMTP_MAX_REPLY_LINE: usize = 8192;

    /// RFC 4954 Section 12: maximum length of an `auth-response` line
    /// (the base64-encoded SASL data sent during a two-step AUTH
    /// exchange), excluding the terminating CRLF.
    pub(super) const SMTP_MAX_AUTH_RESPONSE: usize = 12288;

    /// Maximum response buffer size (64 KiB).
    ///
    /// RFC 5321 Section 4.5.3.1.5 specifies reply lines should be at
    /// most 512 octets. We allow a generous 64 KiB to accommodate
    /// multi-line EHLO responses with many extensions, while still
    /// protecting against a malicious server exhausting memory.
    pub(super) const MAX_RESPONSE_BUFFER: usize = 64 * 1024;

    /// Try to parse a complete SMTP response from the buffer.
    ///
    /// Returns `None` if the buffer does not yet contain a complete response.
    /// On success, returns the parsed [`SmtpResponse`] together with the
    /// number of bytes consumed from `buf`, so the caller can advance past
    /// the response in a single step — eliminating the desynchronization
    /// risk of computing the byte length separately.
    ///
    /// Parses multi-line responses per RFC 5321 Section 4.2.
    pub(super) fn try_parse_response(buf: &[u8]) -> Result<Option<(SmtpResponse, usize)>, Error> {
        let mut lines = Vec::new();
        let mut code: Option<u16> = None;
        let mut first_enhanced: Option<EnhancedStatusCode> = None;
        let mut pos = 0;

        loop {
            // Find the next line ending: CRLF (RFC 5321 Section 2.3.8) or
            // bare LF (Postel's law — tolerate non-conformant servers that
            // omit CR, e.g., misconfigured Postfix, custom implementations).
            let (line_end_offset, terminator_len) = {
                let slice = &buf[pos..];
                // Find the earliest line terminator: CRLF (RFC 5321 Section 2.3.8)
                // or bare LF (Postel's law — tolerate non-conformant servers that
                // omit CR, e.g., misconfigured Postfix, custom implementations).
                // We must find the EARLIEST of the two to avoid merging two logical
                // response lines when bare LF precedes CRLF in the buffer.
                match slice.iter().position(|&b| b == b'\n') {
                    Some(lf_pos) if lf_pos > 0 && slice[lf_pos - 1] == b'\r' => {
                        // CRLF: the line content ends before the CR.
                        (lf_pos - 1, 2)
                    }
                    Some(lf_pos) => {
                        // Bare LF — tolerate per Postel's law (RFC 1122 Section 1.2.2).
                        (lf_pos, 1)
                    }
                    None => return Ok(None), // Incomplete — need more data.
                }
            };

            let line = &buf[pos..pos + line_end_offset];
            let line_total_len = line_end_offset + terminator_len; // line content + terminator

            // RFC 5321 Section 4.5.3.1.5: reply line should not exceed
            // 512 octets. We enforce a permissive limit of 8192 octets
            // per Postel's law to tolerate non-conformant servers.
            if line_total_len > Self::SMTP_MAX_REPLY_LINE {
                return Err(Error::Parse(format!(
                    "reply line exceeds {}-octet limit ({} octets) \
                     (RFC 5321 Section 4.5.3.1.5, relaxed per Postel's law)",
                    Self::SMTP_MAX_REPLY_LINE,
                    line_total_len
                )));
            }

            if line.len() < 3 {
                return Err(Error::Parse("response line too short".into()));
            }

            // Parse 3-digit reply code.
            let code_str = std::str::from_utf8(&line[..3])
                .map_err(|_| Error::Parse("invalid reply code bytes".into()))?;
            let line_code: u16 = code_str
                .parse()
                .map_err(|_| Error::Parse(format!("invalid reply code: {code_str}")))?;

            // 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).
            let d0 = line[0];
            if !(b'2'..=b'5').contains(&d0) {
                return Err(Error::Parse(format!(
                    "reply code {line_code} outside valid range \
                     (RFC 5321 Section 4.2: first digit must be 2-5)"
                )));
            }

            // RFC 5321 Section 4.2: In a multi-line reply, every line MUST
            // use the same reply code.  A mismatch is a server protocol
            // violation, not a client-side parse failure.
            if let Some(c) = code {
                if c != line_code {
                    return Err(Error::Protocol(format!(
                        "reply code changed mid-response: {c} vs {line_code} \
                         (RFC 5321 Section 4.2)"
                    )));
                }
            }
            code = Some(line_code);

            // RFC 5321 Section 4.2: Reply-line separator must be '-'
            // (continuation), SP (final line with text), or absent
            // (code-only final line). Any other byte is invalid.
            let is_final = if line.len() == 3 {
                true // Just the code, no separator.
            } else {
                match line[3] {
                    b'-' => false,
                    b' ' => true,
                    other => {
                        return Err(Error::Parse(format!(
                            "invalid separator byte 0x{other:02X} at position 3 \
                             (RFC 5321 Section 4.2: expected '-' or SP)"
                        )));
                    }
                }
            };

            // Extract text after the separator.
            let raw_text = if line.len() > 4 {
                String::from_utf8_lossy(&line[4..]).into_owned()
            } else {
                String::new()
            };

            // Try to strip an enhanced status code from the start of the text
            // (RFC 2034 Section 3). Preserve only the first one found.
            // RFC 2034 Section 4: the enhanced code class MUST match the
            // reply code class — strip_enhanced_code validates this internally.
            let text = if let Some((esc, rest)) = decode::strip_enhanced_code(&raw_text, line_code)
            {
                if first_enhanced.is_none() {
                    first_enhanced = Some(esc);
                }
                rest.to_owned()
            } else {
                raw_text
            };
            lines.push(text);

            pos += line_end_offset + terminator_len; // Skip past line terminator.

            if is_final {
                let reply_code = code.ok_or_else(|| Error::Parse("empty response".into()))?;
                return Ok(Some((
                    SmtpResponse {
                        code: reply_code,
                        enhanced_code: first_enhanced,
                        lines,
                    },
                    pos,
                )));
            }
        }
    }

    /// Convert a non-success `SmtpResponse` into the appropriate `Error`.
    pub(super) fn response_to_error(resp: SmtpResponse) -> Error {
        let message = resp.text();
        let code = resp.code;
        if resp.is_permanent_error() {
            Error::Permanent {
                code,
                message,
                response: resp,
            }
        } else if resp.is_transient_error() {
            Error::Transient {
                code,
                message,
                response: resp,
            }
        } else {
            Error::Protocol(format!("unexpected response code {code}: {message}"))
        }
    }

    /// Create a default TLS configuration using the system root certificates.
    ///
    /// Installs the ring `CryptoProvider` if no provider has been set yet.
    pub(super) fn default_tls_config() -> Arc<rustls::ClientConfig> {
        // Install ring as the crypto provider (no-op if already installed).
        let _ = rustls::crypto::ring::default_provider().install_default();

        let root_store: rustls::RootCertStore =
            webpki_roots::TLS_SERVER_ROOTS.iter().cloned().collect();
        let config = rustls::ClientConfig::builder()
            .with_root_certificates(root_store)
            .with_no_client_auth();
        Arc::new(config)
    }

    /// Set the domain sent in EHLO/LHLO (RFC 5321 Section 4.1.1.1).
    ///
    /// The argument should be the client's FQDN or, when no FQDN is
    /// available, an address literal (RFC 5321 Section 4.1.4).
    ///
    /// Returns `Error::Protocol` if `domain` is empty or contains
    /// non-printable-ASCII bytes (RFC 5321 Section 4.1.1.1).
    ///
    /// This method acquires the internal mutex.
    pub async fn set_ehlo_domain(&self, domain: &str) -> Result<(), Error> {
        let domain = DomainOrLiteral::new(domain.to_owned())?;
        self.inner.lock().await.ehlo_domain = domain;
        Ok(())
    }
}