crymap 2.0.1

A simple, secure IMAP server with encrypted data at rest
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
//-
// Copyright (c) 2020, 2023, 2024, 2025 Jason Lingle
//
// This file is part of Crymap.
//
// Crymap is free software: you can  redistribute it and/or modify it under the
// terms of  the GNU General Public  License as published by  the Free Software
// Foundation, either version  3 of the License, or (at  your option) any later
// version.
//
// Crymap is distributed  in the hope that  it will be useful,  but WITHOUT ANY
// WARRANTY; without  even the implied  warranty of MERCHANTABILITY  or FITNESS
// FOR  A PARTICULAR  PURPOSE.  See the  GNU General  Public  License for  more
// details.
//
// You should have received a copy of the GNU General Public License along with
// Crymap. If not, see <http://www.gnu.org/licenses/>.

use std::borrow::Cow;
use std::io;
use std::pin::Pin;
use std::str;
use std::task;
use std::time::{Duration, Instant};

use log::{error, info, warn};
use openssl::ssl::SslAcceptor;
use tokio::io::{
    AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufStream, DuplexStream,
};
use tokio::sync::{mpsc, oneshot};

use super::super::{codes::*, syntax::*};
use super::bridge::*;
use crate::support::{
    append_limit::APPEND_SIZE_LIMIT, async_io::ServerIo, error::Error,
    log_prefix::LogPrefix,
};

pub(super) struct Service {
    pub(super) lmtp: bool,
    /// Whether the `BINARYMIME` extension is offered.
    ///
    /// We don't offer it on outbound SMTP because we don't support downgrading
    /// binary messages to non-binary and it is reasonably expectable that some
    /// implementations that don't offer `BINARYMIME` will in fact have issues
    /// with binary messages. (We also don't support downgrading `8BITMIME` or
    /// `SMTPUTF8`, but systems not supporting 8-bit are extinct; all that
    /// remain are systems that fail to declare their functional support for
    /// these extensions.)
    pub(super) offer_binarymime: bool,
    /// Whether authentication is in use.
    ///
    /// If true, no mail commands can be issued without authentication. If
    /// false, authentication is not permitted.
    pub(super) auth: bool,
    pub(super) send_request: mpsc::Sender<Request>,
}

struct Server {
    io: BufStream<ServerIo>,
    log_prefix: LogPrefix,
    ssl_acceptor: Option<SslAcceptor>,
    service: Service,
    local_host_name: String,

    ineffective_commands: u32,
    deadline_tx: mpsc::Sender<Instant>,
    quit: bool,
    has_helo: bool,
    has_mail_from: bool,
    has_auth: bool,
    recipients: u32,
    sending_data: Option<SendData>,

    /// Whether any UNIX newlines have been seen in commands.
    unix_newlines: bool,
}

pub(super) async fn run(
    io: ServerIo,
    log_prefix: LogPrefix,
    ssl_acceptor: Option<SslAcceptor>,
    service: Service,
    local_host_name: String,
) -> Result<(), Error> {
    let (deadline_tx, deadline_rx) = mpsc::channel(1);

    let mut server = Server {
        io: BufStream::new(io),
        log_prefix,
        ssl_acceptor,
        service,
        local_host_name,

        ineffective_commands: 0,
        deadline_tx,
        quit: false,
        has_helo: false,
        has_mail_from: false,
        has_auth: false,
        recipients: 0,
        sending_data: None,
        unix_newlines: false,
    };

    tokio::select! {
        r = server.run() => r,
        _ = idle_timer(deadline_rx) => {
            Err(Error::Io(io::Error::new(
                io::ErrorKind::TimedOut,
                "Connection idle timer expired",
            )))
        },
    }
}

struct SendData {
    stream: DuplexStream,
    recipient_responses:
        oneshot::Sender<mpsc::Sender<Result<(), SmtpResponse<'static>>>>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ResponseKind {
    /// The last in a series of responses.
    ///
    /// Indicates no continuation and forces a flush.
    Final,
    /// A non-final response which needs to be sent immediately.
    ///
    /// Forces a flush, but also indicates continuation.
    Urgent,
    /// A non-final response that is safe to buffer.
    Delayable,
}

impl ResponseKind {
    fn or_final(self, phinal: bool) -> Self {
        if phinal {
            ResponseKind::Final
        } else {
            self
        }
    }

    fn indicator(self) -> char {
        match self {
            Final => ' ',
            Urgent | Delayable => '-',
        }
    }
}

use self::ResponseKind::*;

macro_rules! require {
    ($this:expr, $($fns:ident = $arg:expr,)* @else $el:block) => {
        $(if let Some(r) = $this.$fns($arg).await { $el; return r; })*
    };
    ($this:expr, $($fns:ident = $arg:expr),*) => {
        require!($this, $($fns = $arg,)* @else {})
    };
}

const MAX_LINE: usize = 1024;

static EXTENSIONS: &[&str] = &[
    "8BITMIME", // RFC 6152
    "AUTH PLAIN",
    "BINARYMIME",          // RFC 3030
    "CHUNKING",            // RFC 3030
    "ENHANCEDSTATUSCODES", // RFC 5248
    "PIPELINING",
    concat_appendlimit!("SIZE "),
    "SMTPUTF8", // RFC 6531
    "STARTTLS",
    "HELP", // The final item must be unconditional
];

impl Server {
    pub(super) async fn run(&mut self) -> Result<(), Error> {
        self.send_greeting().await?;

        let mut buffer = Vec::new();
        while !self.quit {
            self.run_command(&mut buffer).await?;
        }

        Ok(())
    }

    async fn run_command(&mut self, buffer: &mut Vec<u8>) -> Result<(), Error> {
        let _ = self
            .deadline_tx
            .send(Instant::now() + Duration::from_secs(60))
            .await;
        buffer.clear();

        (&mut self.io)
            .take(MAX_LINE as u64)
            .read_until(b'\n', buffer)
            .await?;
        if buffer.is_empty() {
            return Err(Error::Io(io::Error::new(
                io::ErrorKind::UnexpectedEof,
                "EOF reached at start of command",
            )));
        }

        if !buffer.ends_with(b"\n") {
            if buffer.len() >= MAX_LINE {
                self.send_response(
                    Final,
                    pc::CommandSyntaxError,
                    Some((cc::PermFail, sc::OtherProtocolStatus)),
                    Cow::Borrowed("Command line too long"),
                )
                .await?;

                // Skip the rest of the line
                while !buffer.is_empty() && !buffer.ends_with(b"\n") {
                    buffer.clear();
                    (&mut self.io)
                        .take(MAX_LINE as u64)
                        .read_until(b'\n', buffer)
                        .await?;
                }

                return Ok(());
            } else {
                return Err(Error::Io(io::Error::new(
                    io::ErrorKind::UnexpectedEof,
                    "EOF reached within command",
                )));
            }
        }

        self.ineffective_commands += 1;
        if self.ineffective_commands > 30 {
            warn!(
                "{} Terminating connection after too many non-mail commands",
                self.log_prefix,
            );
            self.send_response(
                Final,
                pc::ServiceClosing,
                None,
                Cow::Borrowed("Too many commands issued without sending mail"),
            )
            .await?;
            self.quit = true;
            return Ok(());
        }

        let line_ending_len = if buffer.ends_with(b"\r\n") {
            2
        } else {
            self.unix_newlines = true;
            1
        };

        let command_line = &buffer[..buffer.len() - line_ending_len];
        if command_line.contains(&0) {
            warn!(
                "{} Remote is speaking binary, closing connection",
                self.log_prefix,
            );
            self.quit = true;
            return Ok(());
        }

        let command_line = match str::from_utf8(command_line) {
            Ok(s) => s,
            Err(_) => {
                warn!("{} Non-UTF-8 command received", self.log_prefix);
                self.send_response(
                    Final,
                    pc::CommandSyntaxError,
                    Some((cc::PermFail, sc::OtherProtocolStatus)),
                    Cow::Borrowed("Malformed UTF-8"),
                )
                .await?;
                return Ok(());
            },
        };

        let command = match command_line.parse::<Command>() {
            Ok(c) => c,
            Err(_) => {
                let mut debug_line = command_line;
                if let Some((truncate_len, _)) =
                    debug_line.char_indices().nth(64)
                {
                    debug_line = &debug_line[..truncate_len];
                }

                warn!(
                    "{} Received bad command {debug_line:?}",
                    self.log_prefix
                );

                if looks_like_known_command(command_line) {
                    self.send_response(
                        Final,
                        pc::ParameterSyntaxError,
                        Some((cc::PermFail, sc::InvalidCommandArguments)),
                        Cow::Borrowed("Unknown command syntax"),
                    )
                    .await?;
                } else {
                    self.send_response(
                        Final,
                        pc::CommandSyntaxError,
                        Some((cc::PermFail, sc::InvalidCommand)),
                        Cow::Borrowed("Unrecognised command"),
                    )
                    .await?;
                }

                return Ok(());
            },
        };

        match command {
            Command::Helo(command, origin) => {
                self.cmd_helo(command, origin).await
            },
            Command::Auth(mechanism, data) => {
                self.cmd_auth(mechanism, data).await
            },
            Command::MailFrom(email, size, warnings) => {
                for warning in warnings {
                    warn!("{} {}", self.log_prefix, warning);
                }
                self.cmd_mail_from(email, size).await
            },
            Command::Recipient(email, warnings) => {
                for warning in warnings {
                    warn!("{} {}", self.log_prefix, warning);
                }
                self.cmd_recipient(email).await
            },
            Command::Data => self.cmd_data().await,
            Command::BinaryData(len, last) => {
                self.cmd_binary_data(len, last).await
            },
            Command::Reset => self.cmd_reset().await,
            Command::Verify => self.cmd_verify().await,
            Command::Expand => self.cmd_expand().await,
            Command::Help => self.cmd_help().await,
            Command::Noop => self.cmd_noop().await,
            Command::Quit => self.cmd_quit().await,
            Command::StartTls => self.cmd_start_tls().await,
            Command::Http => self.cmd_http(),
        }
    }

    async fn cmd_helo(
        &mut self,
        command: String,
        origin: String,
    ) -> Result<(), Error> {
        require!(self, need_helo = false);

        let extended = !"HELO".eq_ignore_ascii_case(&command);
        self.log_prefix.set_helo(origin.clone());
        info!("{} SMTP {command}", self.log_prefix);

        if !self
            .service_request(RequestPayload::Helo(HeloRequest {
                command,
                host: origin.clone(),
                tls: self.io.get_ref().ssl_string(),
            }))
            .await?
        {
            return Ok(());
        }

        self.send_response(
            Delayable.or_final(!extended),
            pc::Ok,
            None,
            Cow::Owned(format!(
                "{} salutations, {}",
                self.local_host_name, origin
            )),
        )
        .await?;
        self.has_helo = true;

        if extended {
            for (ix, &ext) in EXTENSIONS.iter().enumerate() {
                // RFC 3207 requires not sending STARTTLS after TLS has been
                // negotiated.
                if "STARTTLS" == ext
                    && (self.io.get_ref().is_ssl()
                        || self.ssl_acceptor.is_none())
                {
                    continue;
                }

                if "BINARYMIME" == ext && !self.service.offer_binarymime {
                    continue;
                }

                if ext.starts_with("AUTH ")
                    && (!self.service.auth || !self.io.get_ref().is_ssl())
                {
                    continue;
                }

                self.send_response(
                    Delayable.or_final(ix + 1 == EXTENSIONS.len()),
                    pc::Ok,
                    None,
                    Cow::Borrowed(ext),
                )
                .await?;
            }
        }

        Ok(())
    }

    async fn cmd_auth(
        &mut self,
        mechanism: String,
        data: Option<String>,
    ) -> Result<(), Error> {
        require!(self, need_helo = true, need_mail_from = false);

        if !self.io.get_ref().is_ssl() {
            warn!("{} Rejected attempt to AUTH without TLS", self.log_prefix);
            return self.send_response(
                Final,
                pc::EncryptionRequiredForRequestedAuthenticationMechanism,
                Some((cc::PermFail, sc::EncryptionRequiredForRequestedAuthenticationMechanism)),
                Cow::Borrowed("Have you no shame?"),
            ).await;
        }

        if !self.service.auth {
            warn!(
                "{} Rejected attempt to AUTH on an unauthenticated service",
                self.log_prefix,
            );
            return self
                .send_response(
                    Final,
                    pc::CommandNotImplemented,
                    Some((cc::PermFail, sc::SecurityFeaturesNotSupported)),
                    Cow::Borrowed("Authentication is not supported here"),
                )
                .await;
        }

        if self.has_auth {
            return self
                .send_response(
                    Final,
                    pc::BadSequenceOfCommands,
                    None,
                    Cow::Borrowed("Already authenticated"),
                )
                .await;
        }

        if !mechanism.eq_ignore_ascii_case("PLAIN") {
            warn!(
                "{} Rejected attempt to auth with method {mechanism:?}",
                self.log_prefix,
            );
            return self
                .send_response(
                    Final,
                    pc::CommandParameterNotImplemented,
                    // The obvious thing is to return SecurityFeaturesNotSupported,
                    // but RFC 4954 requires InvalidCommandArguments instead.
                    Some((cc::PermFail, sc::InvalidCommandArguments)),
                    Cow::Borrowed("Unsupported AUTH mechanism"),
                )
                .await;
        }

        let data = match data {
            Some(data) if data != "=" => data,
            _ => {
                self.send_response(
                    Final,
                    pc::ServerChallenge,
                    None,
                    Cow::Borrowed(""),
                )
                .await?;

                let mut buffer = Vec::new();
                (&mut self.io)
                    .take(MAX_LINE as u64)
                    .read_until(b'\n', &mut buffer)
                    .await?;

                if !buffer.ends_with(b"\n") {
                    self.send_response(
                        Final,
                        pc::CommandSyntaxError,
                        Some((
                            cc::PermFail,
                            sc::AuthenticationExchangeLineTooLong,
                        )),
                        Cow::Borrowed("Line too long"),
                    )
                    .await?;
                    return Err(Error::Io(io::Error::other(
                        "Authentication line too long",
                    )));
                }

                let _ = buffer.pop();
                if Some(&b'\r') == buffer.last() {
                    let _ = buffer.pop();
                }

                String::from_utf8_lossy(&buffer).into_owned()
            },
        };

        if data.is_empty() || data == "=" {
            return self
                .send_response(
                    Final,
                    pc::ParameterSyntaxError,
                    Some((cc::PermFail, sc::SyntaxError)),
                    Cow::Borrowed("The empty string is not valid for PLAIN"),
                )
                .await;
        }

        if data == "*" {
            return self
                .send_response(
                    Final,
                    pc::ParameterSyntaxError,
                    None,
                    Cow::Borrowed("SASL aborted"),
                )
                .await;
        }

        let Some(data) = base64::decode(&data)
            .ok()
            .and_then(|d| String::from_utf8(d).ok())
        else {
            return self
                .send_response(
                    Final,
                    pc::CommandSyntaxError,
                    Some((cc::PermFail, sc::SyntaxError)),
                    Cow::Borrowed("Invalid base64"),
                )
                .await;
        };

        // All we currently support is RFC 2595 PLAIN
        // Format is <authorise-id>NUL<authenticate-id<NUL>password
        // <authorise-id> is optional if it is the same as <authenticate-id>.
        let mut parts = data.split('\x00');
        let (Some(authorise), Some(authenticate), Some(password), None) =
            (parts.next(), parts.next(), parts.next(), parts.next())
        else {
            return self
                .send_response(
                    Final,
                    pc::CommandSyntaxError,
                    Some((cc::PermFail, sc::SyntaxError)),
                    Cow::Borrowed("Invalid auth syntax"),
                )
                .await;
        };

        if !authorise.is_empty() && authorise != authenticate {
            return self
                .send_response(
                    Final,
                    pc::AuthenticationCredentialsInvalid,
                    Some((cc::PermFail, sc::AuthenticationCredentialsInvalid)),
                    Cow::Borrowed("authorise-id must match authenticate-id"),
                )
                .await;
        }

        if self
            .service_request(RequestPayload::Auth(AuthRequest {
                userid: authenticate.to_owned(),
                password: password.to_owned(),
            }))
            .await?
        {
            self.has_auth = true;

            self.send_response(
                Final,
                pc::AuthenticationSucceeded,
                Some((cc::Success, sc::OtherSecurity)),
                Cow::Borrowed("OK"),
            )
            .await?;
        }

        Ok(())
    }

    async fn cmd_mail_from(
        &mut self,
        return_path: String,
        approx_size: Option<u64>,
    ) -> Result<(), Error> {
        require!(self, need_helo = true, need_mail_from = false);
        if self.service.auth && !self.has_auth {
            return self
                .send_response(
                    Final,
                    pc::AuthenticationRequired,
                    Some((cc::PermFail, sc::DeliveryNotAuthorised)),
                    Cow::Borrowed("Authentication required"),
                )
                .await;
        }

        if approx_size.unwrap_or(0) > APPEND_SIZE_LIMIT as u64 {
            return self
                .send_response(
                    Final,
                    pc::ExceededStorageAllocation,
                    Some((cc::PermFail, sc::MessageLengthExceedsLimit)),
                    Cow::Owned(format!(
                        "Maximum message size is {} bytes",
                        APPEND_SIZE_LIMIT
                    )),
                )
                .await;
        }

        if !self
            .service_request(RequestPayload::Mail(MailRequest {
                from: return_path,
            }))
            .await?
        {
            return Ok(());
        }

        info!("{} Start mail transaction", self.log_prefix);
        self.ineffective_commands = 0;
        self.has_mail_from = true;
        self.send_response(
            Final,
            pc::Ok,
            Some((cc::Success, sc::Undefined)),
            Cow::Borrowed("OK"),
        )
        .await
    }

    async fn cmd_recipient(
        &mut self,
        forward_path: String,
    ) -> Result<(), Error> {
        require!(
            self,
            need_helo = true,
            need_mail_from = true,
            need_data = false
        );

        if !self
            .service_request(RequestPayload::Recipient(RecipientRequest {
                to: forward_path,
            }))
            .await?
        {
            return Ok(());
        }

        self.ineffective_commands = 0;
        self.recipients += 1;
        self.send_response(
            Final,
            pc::Ok,
            Some((cc::Success, sc::DestinationAddressValid)),
            Cow::Borrowed("OK"),
        )
        .await
    }

    /// Initiates a data transfer.
    ///
    /// A `Data` request will be executed against the service. If it accepts,
    /// `sending_data` is initialised and this returns `true`. If the transfer
    /// is rejected, `false` is returned.
    async fn start_data_transfer(&mut self) -> Result<bool, Error> {
        let (data_in, data_out) = tokio::io::duplex(4096);
        let (recipients_tx, recipients_rx) = oneshot::channel();
        if !self
            .service_request(RequestPayload::Data(DataRequest {
                data: data_in,
                recipient_responses: recipients_rx,
            }))
            .await?
        {
            return Ok(false);
        }

        self.sending_data = Some(SendData {
            stream: data_out,
            recipient_responses: recipients_tx,
        });
        Ok(true)
    }

    /// Completes a data transfer.
    ///
    /// The data stream to the service is severed, then the responses for each
    /// recipient (LMTP) or singular response (SMTP) are retrieved and sent.
    /// The mail delivery state is reset.
    async fn complete_data_transfer(&mut self) -> Result<(), Error> {
        let sending_data = self.sending_data.take().unwrap();
        drop(sending_data.stream);

        let (recipients_tx, mut recipients_rx) = mpsc::channel(1);
        // If this fails, `recipients_rx` will be a broken channel, and we'll
        // log when we try to get the responses out.
        let _ = sending_data.recipient_responses.send(recipients_tx);

        let need_responses = if self.service.lmtp {
            self.recipients
        } else {
            1
        };

        let mut success = false;
        for i in 0..need_responses {
            let response = recipients_rx
                .recv()
                .await
                .unwrap_or_else(|| {
                    error!(
                    "{} [BUG] Service worker disappeared during data transfer",
                    self.log_prefix,
                );
                    Err(SmtpResponse(
                        pc::TransactionFailed,
                        Some((cc::TempFail, sc::OtherMailSystem)),
                        Cow::Borrowed("Internal server error"),
                    ))
                })
                .err()
                .unwrap_or(SmtpResponse(
                    pc::Ok,
                    Some((cc::Success, sc::Undefined)),
                    Cow::Borrowed("OK"),
                ));
            success |= (200..=299).contains(&(response.0 as i32));
            self.send_response(
                Urgent.or_final(i + 1 == need_responses),
                response.0,
                response.1,
                response.2,
            )
            .await?;
        }

        info!(
            "{} Completed data transfer {}",
            self.log_prefix,
            if success {
                "successfully"
            } else {
                "unsuccessfully"
            },
        );

        self.recipients = 0;
        self.has_mail_from = false;
        Ok(())
    }

    async fn cmd_data(&mut self) -> Result<(), Error> {
        require!(
            self,
            need_helo = true,
            need_mail_from = true,
            need_recipients = true,
            need_data = false
        );

        if !self.start_data_transfer().await? {
            return Ok(());
        }

        self.ineffective_commands = 0;
        self.send_response(
            Final,
            pc::StartMailInput,
            None,
            Cow::Borrowed("Go ahead"),
        )
        .await?;

        info!("{} Begin legacy-format data transfer", self.log_prefix);

        let _ = self
            .deadline_tx
            .send(Instant::now() + Duration::from_secs(1800))
            .await;
        {
            let sending_data = self.sending_data.as_mut().unwrap();
            copy_with_dot_stuffing(
                Pin::new(&mut DiscardOnError(&mut sending_data.stream)),
                Pin::new(&mut self.io),
                // If we've seen the client speaking SMTP with UNIX newlines,
                // assume the message may be UNIX, or may at least be
                // terminated with a UNIX-delimited '.'.
                self.unix_newlines,
                // Automatically detect line endings.
                true,
            )
            .await?;
        }

        self.complete_data_transfer().await
    }

    async fn cmd_binary_data(
        &mut self,
        len: u64,
        last: bool,
    ) -> Result<(), Error> {
        // Extend the deadline to account for a 32kbps transfer rate.
        let _ = self
            .deadline_tx
            .send(Instant::now() + Duration::from_secs(30 + len / 4000))
            .await;

        let mut consumed = false;
        let result = self.cmd_binary_data_impl(&mut consumed, len, last).await;
        if !consumed {
            tokio::io::copy(
                &mut (&mut self.io).take(len),
                &mut tokio::io::sink(),
            )
            .await?;
        }

        result
    }

    async fn cmd_binary_data_impl(
        &mut self,
        consumed: &mut bool,
        len: u64,
        last: bool,
    ) -> Result<(), Error> {
        require!(
            self,
            need_helo = true,
            need_mail_from = true,
            need_recipients = true
        );

        self.ineffective_commands = 0;
        if self.sending_data.is_none() {
            if !self.start_data_transfer().await? {
                return Ok(());
            }

            info!("{} Begin binary data transfer", self.log_prefix);
        }

        let abort = {
            let mut src = (&mut self.io).take(len);
            let sending_data = self.sending_data.as_mut().unwrap();
            let result =
                tokio::io::copy(&mut src, &mut sending_data.stream).await;
            // Ensure we actually consume the whole blob
            let _ = tokio::io::copy(&mut src, &mut tokio::io::sink()).await;
            *consumed = true;

            match result {
                Ok(_) => false,
                // BrokenPipe => sending_data.stream is broken
                Err(e) if io::ErrorKind::BrokenPipe == e.kind() => true,
                // Any other error => the server input failed
                Err(e) => return Err(Error::Io(e)),
            }
        };

        if last || abort {
            self.complete_data_transfer().await
        } else {
            self.send_response(
                Final,
                pc::Ok,
                Some((cc::Success, sc::Undefined)),
                Cow::Borrowed("OK"),
            )
            .await
        }
    }

    async fn cmd_reset(&mut self) -> Result<(), Error> {
        self.has_mail_from = false;
        self.recipients = 0;
        self.sending_data = None;
        if self.service_request(RequestPayload::Reset).await? {
            self.send_response(
                Final,
                pc::Ok,
                Some((cc::Success, sc::Undefined)),
                Cow::Borrowed("OK"),
            )
            .await?;
        }

        Ok(())
    }

    async fn cmd_verify(&mut self) -> Result<(), Error> {
        info!("{} Rejected attempt to use VRFY", self.log_prefix);
        self.send_response(
            Final,
            pc::CannotVerify,
            Some((cc::Success, sc::OtherSecurity)),
            Cow::Borrowed("VRFY not supported"),
        )
        .await
    }

    async fn cmd_expand(&mut self) -> Result<(), Error> {
        self.send_response(
            Final,
            pc::ActionNotTakenPermanent,
            Some((cc::PermFail, sc::SystemNotCapableOfSelectedFeatures)),
            Cow::Borrowed("There are no mailing lists here"),
        )
        .await
    }

    async fn cmd_help(&mut self) -> Result<(), Error> {
        self.send_response(
            Delayable,
            pc::HelpMessage,
            Some((cc::Success, sc::Undefined)),
            Cow::Borrowed("You asked me for help"),
        )
        .await?;
        self.send_response(
            Delayable,
            pc::HelpMessage,
            Some((cc::Success, sc::Undefined)),
            Cow::Borrowed("An SMTP server!"),
        )
        .await?;
        self.send_response(
            Delayable,
            pc::HelpMessage,
            Some((cc::Success, sc::Undefined)),
            Cow::Borrowed("What a strange life choice"),
        )
        .await?;
        self.send_response(
            Delayable,
            pc::HelpMessage,
            Some((cc::Success, sc::Undefined)),
            Cow::Borrowed("This is the Crymap SMTP server."),
        )
        .await?;
        self.send_response(
            Final,
            pc::HelpMessage,
            Some((cc::Success, sc::Undefined)),
            Cow::Borrowed("End of HELP"),
        )
        .await
    }

    async fn cmd_noop(&mut self) -> Result<(), Error> {
        self.send_response(
            Final,
            pc::Ok,
            Some((cc::Success, sc::Undefined)),
            Cow::Borrowed("OK"),
        )
        .await
    }

    async fn cmd_quit(&mut self) -> Result<(), Error> {
        self.quit = true;
        let _ = self
            .send_response(
                Final,
                pc::ServiceClosing,
                Some((cc::Success, sc::Undefined)),
                Cow::Borrowed("Bye"),
            )
            .await;
        Ok(())
    }

    async fn cmd_start_tls(&mut self) -> Result<(), Error> {
        require!(
            self,
            need_helo = true,
            need_tls = false,
            need_mail_from = false,
            need_recipients = false,
            need_data = false
        );

        if self.ssl_acceptor.is_none() {
            self.send_response(
                Final,
                pc::ActionNotTakenPermanent,
                None,
                Cow::Borrowed("TLS not configured"),
            )
            .await?;
            return Ok(());
        }

        self.send_response(
            Final,
            pc::ServiceReady,
            Some((cc::Success, sc::Undefined)),
            Cow::Borrowed("Switching to TLS"),
        )
        .await?;

        info!("{} Start TLS handshake", self.log_prefix);

        self.has_helo = false;
        self.io
            .get_mut()
            .ssl_accept(&self.ssl_acceptor.take().unwrap())
            .await?;

        info!("{} TLS handshake completed", self.log_prefix);

        Ok(())
    }

    fn cmd_http(&mut self) -> Result<(), Error> {
        // As tempting as it'd be to respond with
        //   HTTP/1.0 418 I'm an SMTP server!
        // we've already sent out the SMTP greeting line.
        warn!(
            "{} Client made an HTTP request, aborting the connection",
            self.log_prefix,
        );
        self.quit = true;
        Ok(())
    }

    async fn need_helo(&mut self, present: bool) -> Option<Result<(), Error>> {
        self.check_need(
            self.has_helo,
            present,
            "Already got HELO",
            "Still waiting for HELO",
        )
        .await
    }

    async fn need_mail_from(
        &mut self,
        present: bool,
    ) -> Option<Result<(), Error>> {
        self.check_need(
            self.has_mail_from,
            present,
            "Already got MAIL FROM",
            "Still waiting for MAIL FROM",
        )
        .await
    }

    async fn need_recipients(
        &mut self,
        present: bool,
    ) -> Option<Result<(), Error>> {
        self.check_need(
            self.recipients > 0,
            present,
            "Already have recipients",
            "No recipients",
        )
        .await
    }

    async fn need_data(&mut self, present: bool) -> Option<Result<(), Error>> {
        self.check_need(
            self.sending_data.is_some(),
            present,
            "Already transferring data",
            "Not currently transferring data",
        )
        .await
    }

    async fn need_tls(&mut self, present: bool) -> Option<Result<(), Error>> {
        self.check_need(
            self.sending_data.is_some(),
            present,
            "Already using TLS",
            "Not using TLS",
        )
        .await
    }

    async fn check_need(
        &mut self,
        current_status: bool,
        desired_status: bool,
        message_if_already_present: &str,
        message_if_missing: &str,
    ) -> Option<Result<(), Error>> {
        if current_status != desired_status {
            Some(
                self.send_response(
                    Final,
                    pc::BadSequenceOfCommands,
                    Some((cc::PermFail, sc::InvalidCommand)),
                    Cow::Borrowed(if current_status {
                        message_if_already_present
                    } else {
                        message_if_missing
                    }),
                )
                .await,
            )
        } else {
            None
        }
    }

    async fn send_greeting(&mut self) -> Result<(), Error> {
        self.send_response(
            Final,
            pc::ServiceReady,
            None,
            Cow::Owned(format!(
                "{} {} {} {}.{}.{} ready",
                self.local_host_name,
                match (self.service.lmtp, self.io.get_ref().is_ssl()) {
                    (false, false) => "ESMTP",
                    (false, true) => "ESMTPS",
                    (true, false) => "LMTP",
                    (true, true) => "LMTPS",
                },
                env!("CARGO_PKG_NAME"),
                env!("CARGO_PKG_VERSION_MAJOR"),
                env!("CARGO_PKG_VERSION_MINOR"),
                env!("CARGO_PKG_VERSION_PATCH"),
            )),
        )
        .await
    }

    async fn send_response(
        &mut self,
        kind: ResponseKind,
        primary_code: PrimaryCode,
        secondary_code: Option<(ClassCode, SubjectCode)>,
        quip: Cow<'_, str>,
    ) -> Result<(), Error> {
        use std::fmt::Write as _;

        if primary_code == pc::ServiceClosing
            || primary_code == pc::ServiceNotAvailableClosing
        {
            self.quit = true;
        }

        let mut s = String::new();
        let _ = write!(s, "{}{}", primary_code as u16, kind.indicator());
        if let Some((class, subject)) = secondary_code {
            let subject = subject as u16;
            let split = if subject >= 100 { 100 } else { 10 };

            let _ = write!(
                s,
                "{}.{}.{} ",
                class as u8,
                subject / split,
                subject % split
            );
        }

        let _ = write!(s, "{}\r\n", quip);

        self.io.write_all(s.as_bytes()).await?;
        match kind {
            Final | Urgent => self.io.flush().await?,
            Delayable => (),
        }

        Ok(())
    }

    /// Send `payload` as a request to the service, and waits for the service's
    /// response.
    ///
    /// If an error occurs or the service rejects the request, the response
    /// produced by the service is sent and `false` is returned. Otherwise,
    /// nothing is sent to the client and `true` is returned.
    async fn service_request(
        &mut self,
        payload: RequestPayload,
    ) -> Result<bool, Error> {
        let (response_tx, response_rx) = oneshot::channel();
        if self
            .service
            .send_request
            .send(Request {
                payload,
                respond: response_tx,
            })
            .await
            .is_err()
        {
            error!("{} [BUG] Service worker disappeared", self.log_prefix);
            self.send_response(
                Final,
                pc::ServiceNotAvailableClosing,
                Some((cc::TempFail, sc::OtherMailSystem)),
                Cow::Borrowed("Internal server error"),
            )
            .await?;
            return Ok(false);
        }

        let Ok(result) = response_rx.await else {
            error!("{} [BUG] Service worker disappeared", self.log_prefix);
            self.send_response(
                Final,
                pc::ServiceNotAvailableClosing,
                Some((cc::TempFail, sc::OtherMailSystem)),
                Cow::Borrowed("Internal server error"),
            )
            .await?;
            return Ok(false);
        };

        if let Err(e) = result {
            self.send_response(Final, e.0, e.1, e.2).await?;
            return Ok(false);
        }

        Ok(true)
    }
}

/// Wraps `DuplexStream` to silently succeed and consume all data on any error.
struct DiscardOnError<'a>(&'a mut DuplexStream);

impl tokio::io::AsyncWrite for DiscardOnError<'_> {
    fn poll_write(
        self: Pin<&mut Self>,
        ctx: &mut task::Context<'_>,
        buf: &[u8],
    ) -> task::Poll<io::Result<usize>> {
        match Pin::new(&mut *self.get_mut().0).poll_write(ctx, buf) {
            task::Poll::Ready(Err(_)) => task::Poll::Ready(Ok(buf.len())),
            poll => poll,
        }
    }

    fn poll_flush(
        self: Pin<&mut Self>,
        ctx: &mut task::Context<'_>,
    ) -> task::Poll<io::Result<()>> {
        Pin::new(&mut *self.get_mut().0).poll_flush(ctx)
    }

    fn poll_shutdown(
        self: Pin<&mut Self>,
        ctx: &mut task::Context<'_>,
    ) -> task::Poll<io::Result<()>> {
        Pin::new(&mut *self.get_mut().0).poll_shutdown(ctx)
    }
}

/// Copies `src` to `dst`, stripping dot stuffing, consuming up to and
/// including the line with just `.`.
///
/// UNIX line endings will be understood by default and converted to DOS
/// newlines if `unix_lines` is `true`. `unix_lines` will be forced to true if
/// an LF is encountered before a CR unless `detect_line_endings` is false.
///
/// As long as `unix_lines` is false, this implementation requires strict
/// conformance to the use of DOS newlines in exchange for being able to
/// preserve arbitrary binary content exactly.
async fn copy_with_dot_stuffing(
    mut dst: Pin<&mut impl AsyncWriteExt>,
    mut src: Pin<&mut impl AsyncBufReadExt>,
    mut unix_lines: bool,
    mut detect_line_endings: bool,
) -> io::Result<()> {
    /// Write `data` to `dst`, possibly performing line-ending conversion.
    ///
    /// `data` must either be a partial line or the end of a line, including
    /// the input that was read.
    ///
    /// `has_trailing_cr` is set to whether the previous write ended with a
    /// bare CR. `unix_lines` indicates whether conversion is enabled.
    async fn write_with_line_conversion(
        mut dst: Pin<&mut impl AsyncWriteExt>,
        data: &[u8],
        has_trailing_cr: bool,
        unix_lines: bool,
    ) -> io::Result<()> {
        if unix_lines
            && data.ends_with(b"\n")
            && !data.ends_with(b"\r\n")
            && (!has_trailing_cr || b"\n" != data)
        {
            dst.as_mut().write_all(&data[..data.len() - 1]).await?;
            dst.as_mut().write_all(b"\r\n").await?;
        } else {
            // No conversion, no line ending, or it already ends with a DOS
            // line ending.
            dst.write_all(data).await?;
        }

        Ok(())
    }

    // Copy src to dst until a line which is just ".\r\n" is encountered. If a
    // line which is not ".\r\n" is found which begins with '.', the first '.'
    // on the line is removed. The "\r\n" before ".\r\n" is part of the
    // content.
    //
    // To be binary-safe, we need to handle CRLFs strictly, and not treat just
    // any LF as a line ending. E.g., the sequence "\n.\n" may occur by itself
    // in the input and should be part of the message.

    // Whether the next read is reading from the start of the line; i.e., true
    // at the beginning of text and after each CRLF.
    let mut start_of_line = true;
    // Whether the last read ended with CR. This means that if the next read is
    // just \n, we still treat it as a line ending.
    let mut has_trailing_cr = false;

    loop {
        let mut src_buffer = src.as_mut();
        let mut buffer = src_buffer.fill_buf().await?;

        if buffer.is_empty() {
            return Err(io::Error::new(
                io::ErrorKind::UnexpectedEof,
                "EOF encountered in DATA payload",
            ));
        }

        if let Some(eol) = memchr::memchr(b'\n', buffer) {
            buffer = &buffer[..=eol];

            if detect_line_endings {
                // This is our first line-ending. If it's not a DOS newline,
                // perform conversion for the rest of the message.
                if !buffer.ends_with(b"\r\n") && !has_trailing_cr {
                    unix_lines = true;
                }

                detect_line_endings = false;
            }
        }

        let buffer_len = buffer.len();

        if start_of_line {
            // The case of ".\n" at the start of a line is illegal when
            // `!unix_lines`. Assume it's supposed to be the end of the text.
            // In the case of `unix_lines`, it *is* the normal end of text.
            if b".\r\n" == buffer || b".\n" == buffer {
                // End of content
                src.as_mut().consume(buffer_len);
                break;
            }

            if b".\r" == buffer {
                // Maybe end of content, if we can get a \n next.
                src.as_mut().consume(buffer_len);

                let mut extra = [0u8; 1];
                src.as_mut().read_exact(&mut extra).await?;
                if b'\n' == extra[0] {
                    // End of content
                    break;
                }

                // Nope, keep going. The isolated . at the start of the line is
                // illegal, so whether or not we include it is moot.
                dst.write_all(b"\r").await?;
                dst.write_all(&extra).await?;
                has_trailing_cr = b'\r' == extra[0];
                start_of_line = false;
                continue;
            }

            if b"." == buffer {
                // Could be end of content or a stuffed dot.
                src.as_mut().consume(buffer_len);

                let mut extra = [0u8; 2];
                src.as_mut().read_exact(&mut extra[..1]).await?;

                if b'\n' == extra[0] {
                    // ".\n" is illegal with !unix_lines, but is the end of
                    // content with unix_lines, so this is the end of content.
                    break;
                }

                src.as_mut().read_exact(&mut extra[1..]).await?;

                if b"\r\n" == &extra {
                    // End of content
                    break;
                }

                // Nope, keep going. The isolated '.' at the start of the line
                // either is part of dot-stuffing (if extra[0] is '.') or
                // illegal, so just drop it.
                //
                // We know that extra[0] is not '\n', so the only possible line
                // ending is at the end of `extra`.
                write_with_line_conversion(
                    dst.as_mut(),
                    &extra,
                    false, // There was a '.' since the last has_trailing_cr write
                    unix_lines,
                )
                .await?;
                has_trailing_cr = extra.ends_with(b"\r");
                start_of_line = unix_lines && extra.ends_with(b"\n");
                continue;
            }
        }

        // Else, everything inside buffer is content, except possibly a leading
        // '.'.
        let line_contents = if b'.' == buffer[0] && start_of_line {
            &buffer[1..]
        } else {
            buffer
        };
        write_with_line_conversion(
            dst.as_mut(),
            line_contents,
            has_trailing_cr,
            unix_lines,
        )
        .await?;

        start_of_line = buffer.ends_with(b"\r\n")
            || (b"\n" == buffer && has_trailing_cr)
            || (unix_lines && buffer.ends_with(b"\n"));
        has_trailing_cr = buffer.ends_with(b"\r");
        src.as_mut().consume(buffer_len);
    }

    Ok(())
}

// Runs until either the deadline channel is closed or the current deadline has
// expired. Used to force-close idle connections.
async fn idle_timer(mut deadline_rx: mpsc::Receiver<Instant>) {
    let mut deadline = Instant::now() + Duration::from_secs(30);

    loop {
        match tokio::time::timeout_at(deadline.into(), deadline_rx.recv()).await
        {
            Err(_) => return,   // Timed out
            Ok(None) => return, // Done
            Ok(Some(d)) => deadline = d,
        }
    }
}

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

    use super::*;

    fn copy_with_dot_stuffing_sync(
        stuffed: &[u8],
        buffer_size: usize,
        unix_lines: bool,
        detect_line_endings: bool,
    ) -> Vec<u8> {
        let mut decoded_bytes = Vec::<u8>::new();
        let mut reader =
            tokio::io::BufReader::with_capacity(buffer_size, stuffed);
        futures::executor::block_on(copy_with_dot_stuffing(
            Pin::new(&mut decoded_bytes),
            Pin::new(&mut reader),
            unix_lines,
            detect_line_endings,
        ))
        .unwrap();

        decoded_bytes
    }

    proptest! {
        #![proptest_config(ProptestConfig {
            cases: 4096,
            ..ProptestConfig::default()
        })]

        #[test]
        fn binary_dot_stuffing_decodes_properly(
            content in "[x.\r\n]{0,100}\r\n",
            buffer_size in 1usize..=32,
        ) {
            let mut stuffed = content.replace("\r\n.", "\r\n..");
            if stuffed.starts_with(".") {
                stuffed = format!(".{}", stuffed);
            }
            stuffed.push_str(".\r\n");

            let decoded_bytes = copy_with_dot_stuffing_sync(
                stuffed.as_bytes(),
                buffer_size,
                // For this test, never do line ending conversion.
                false,
                false,
            );

            assert_eq!(content, str::from_utf8(&decoded_bytes).unwrap());
        }

        #[test]
        fn text_dot_stuffing_decodes_properly(
            content in "[x.\r\n]{0,100}\r\n",
            buffer_size in 1usize..=32,
        ) {
            let mut stuffed = content.replace("\n.", "\n..");
            if stuffed.starts_with(".") {
                stuffed = format!(".{}", stuffed);
            }
            stuffed.push_str(".\n");

            let decoded_bytes = copy_with_dot_stuffing_sync(
                stuffed.as_bytes(),
                buffer_size,
                // For this test, always do line ending conversion.
                true,
                false,
            );

            let converted_content = content.replace("\r\n", "\n")
                .replace("\n", "\r\n");
            assert_eq!(
                converted_content,
                str::from_utf8(&decoded_bytes).unwrap(),
            );
        }
    }

    #[test]
    fn dot_stuffing_line_ending_detection() {
        assert_eq!(
            b"foo\r\nbar\n.\r\n".to_vec(),
            copy_with_dot_stuffing_sync(
                b"foo\r\nbar\n.\r\n.\r\n",
                64,
                false,
                true,
            ),
        );
        assert_eq!(
            b"foo\r\nbar\r\nbaz\r\n".to_vec(),
            copy_with_dot_stuffing_sync(
                b"foo\nbar\r\nbaz\n.\n",
                64,
                false,
                true,
            ),
        );
    }
}