aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/python/Twisted/py3/twisted/mail/pop3.py
blob: 7b230d20591ee05fa18ebb40ff9360c0f3d61a11 (plain) (blame)
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
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
# -*- test-case-name: twisted.mail.test.test_pop3 -*-
#
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.


"""
Post-office Protocol version 3.

@author: Glyph Lefkowitz
@author: Jp Calderone
"""

import base64
import binascii
import warnings
from hashlib import md5
from typing import Optional

from zope.interface import implementer

from twisted import cred
from twisted.internet import defer, interfaces, task
from twisted.mail import smtp
from twisted.mail._except import POP3ClientError, POP3Error, _POP3MessageDeleted
from twisted.mail.interfaces import (
    IMailboxPOP3 as IMailbox,
    IServerFactoryPOP3 as IServerFactory,
)
from twisted.protocols import basic, policies
from twisted.python import log


# Authentication
@implementer(cred.credentials.IUsernameHashedPassword)
class APOPCredentials:
    """
    Credentials for use in APOP authentication.

    @ivar magic: See L{__init__}
    @ivar username: See L{__init__}
    @ivar digest: See L{__init__}
    """

    def __init__(self, magic, username, digest):
        """
        @type magic: L{bytes}
        @param magic: The challenge string used to encrypt the password.

        @type username: L{bytes}
        @param username: The username associated with these credentials.

        @type digest: L{bytes}
        @param digest: An encrypted version of the user's password.  Should be
            generated as an MD5 hash of the challenge string concatenated with
            the plaintext password.
        """
        self.magic = magic
        self.username = username
        self.digest = digest

    def checkPassword(self, password):
        """
        Validate a plaintext password against the credentials.

        @type password: L{bytes}
        @param password: A plaintext password.

        @rtype: L{bool}
        @return: C{True} if the credentials represented by this object match
        the given password, C{False} if they do not.
        """
        seed = self.magic + password
        myDigest = md5(seed).hexdigest()
        return myDigest == self.digest


class _HeadersPlusNLines:
    """
    A utility class to retrieve the header and some lines of the body of a mail
    message.

    @ivar _file: See L{__init__}
    @ivar _extraLines: See L{__init__}

    @type linecount: L{int}
    @ivar linecount: The number of full lines of the message body scanned.

    @type headers: L{bool}
    @ivar headers: An indication of which part of the message is being scanned.
        C{True} for the header and C{False} for the body.

    @type done: L{bool}
    @ivar done: A flag indicating when the desired part of the message has been
        scanned.

    @type buf: L{bytes}
    @ivar buf: The portion of the message body that has been scanned, up to
        C{n} lines.
    """

    def __init__(self, file, extraLines):
        """
        @type file: file-like object
        @param file: A file containing a mail message.

        @type extraLines: L{int}
        @param extraLines: The number of lines of the message body to retrieve.
        """
        self._file = file
        self._extraLines = extraLines
        self.linecount = 0
        self.headers = 1
        self.done = 0
        self.buf = b""

    def read(self, bytes):
        """
        Scan bytes from the file.

        @type bytes: L{int}
        @param bytes: The number of bytes to read from the file.

        @rtype: L{bytes}
        @return: Each portion of the header as it is scanned.  Then, full lines
            of the message body as they are scanned.  When more than one line
            of the header and/or body has been scanned, the result is the
            concatenation of the lines.  When the scan results in no full
            lines, the empty string is returned.
        """
        if self.done:
            return b""
        data = self._file.read(bytes)
        if not data:
            return data
        if self.headers:
            df, sz = data.find(b"\r\n\r\n"), 4
            if df == -1:
                df, sz = data.find(b"\n\n"), 2
            if df != -1:
                df += sz
                val = data[:df]
                data = data[df:]
                self.linecount = 1
                self.headers = 0
        else:
            val = b""
        if self.linecount > 0:
            dsplit = (self.buf + data).split(b"\n")
            self.buf = dsplit[-1]
            for ln in dsplit[:-1]:
                if self.linecount > self._extraLines:
                    self.done = 1
                    return val
                val += ln + b"\n"
                self.linecount += 1
            return val
        else:
            return data


class _IteratorBuffer:
    """
    An iterator which buffers the elements of a container and periodically
    passes them as input to a writer.

    @ivar write: See L{__init__}.
    @ivar memoryBufferSize: See L{__init__}.

    @type bufSize: L{int}
    @ivar bufSize: The number of bytes currently in the buffer.

    @type lines: L{list} of L{bytes}
    @ivar lines: The buffer, which is a list of strings.

    @type iterator: iterator which yields L{bytes}
    @ivar iterator: An iterator over a container of strings.
    """

    bufSize = 0

    def __init__(self, write, iterable, memoryBufferSize=None):
        """
        @type write: callable that takes L{list} of L{bytes}
        @param write: A writer which is a callable that takes a list of
            strings.

        @type iterable: iterable which yields L{bytes}
        @param iterable: An iterable container of strings.

        @type memoryBufferSize: L{int} or L{None}
        @param memoryBufferSize: The number of bytes to buffer before flushing
            the buffer to the writer.
        """
        self.lines = []
        self.write = write
        self.iterator = iter(iterable)
        if memoryBufferSize is None:
            memoryBufferSize = 2**16
        self.memoryBufferSize = memoryBufferSize

    def __iter__(self):
        """
        Return an iterator.

        @rtype: iterator which yields L{bytes}
        @return: An iterator over strings.
        """
        return self

    def __next__(self):
        """
        Get the next string from the container, buffer it, and possibly send
        the buffer to the writer.

        The contents of the buffer are written when it is full or when no
        further values are available from the container.

        @raise StopIteration: When no further values are available from the
        container.
        """
        try:
            v = next(self.iterator)
        except StopIteration:
            if self.lines:
                self.write(self.lines)
            # Drop some references, in case they're edges in a cycle.
            del self.iterator, self.lines, self.write
            raise
        else:
            if v is not None:
                self.lines.append(v)
                self.bufSize += len(v)
                if self.bufSize > self.memoryBufferSize:
                    self.write(self.lines)
                    self.lines = []
                    self.bufSize = 0

    next = __next__


def iterateLineGenerator(proto, gen):
    """
    Direct the output of an iterator to the transport of a protocol and arrange
    for iteration to take place.

    @type proto: L{POP3}
    @param proto: A POP3 server protocol.

    @type gen: iterator which yields L{bytes}
    @param gen: An iterator over strings.

    @rtype: L{Deferred <defer.Deferred>}
    @return: A deferred which fires when the iterator finishes.
    """
    coll = _IteratorBuffer(proto.transport.writeSequence, gen)
    return proto.schedule(coll)


def successResponse(response):
    """
    Format an object as a positive response.

    @type response: stringifyable L{object}
    @param response: An object with a string representation.

    @rtype: L{bytes}
    @return: A positive POP3 response string.
    """
    if not isinstance(response, bytes):
        response = str(response).encode("utf-8")
    return b"+OK " + response + b"\r\n"


def formatStatResponse(msgs):
    """
    Format a list of message sizes into a STAT response.

    This generator function is intended to be used with
    L{Cooperator <twisted.internet.task.Cooperator>}.

    @type msgs: L{list} of L{int}
    @param msgs: A list of message sizes.

    @rtype: L{None} or L{bytes}
    @return: Yields none until a result is available, then a string that is
        suitable for use in a STAT response. The string consists of the number
        of messages and the total size of the messages in octets.
    """
    i = 0
    bytes = 0
    for size in msgs:
        i += 1
        bytes += size
        yield None
    yield successResponse(b"%d %d" % (i, bytes))


def formatListLines(msgs):
    """
    Format a list of message sizes for use in a LIST response.

    @type msgs: L{list} of L{int}
    @param msgs: A list of message sizes.

    @rtype: L{bytes}
    @return: Yields a series of strings that are suitable for use as scan
        listings in a LIST response. Each string consists of a message number
        and its size in octets.
    """
    i = 0
    for size in msgs:
        i += 1
        yield b"%d %d\r\n" % (i, size)


def formatListResponse(msgs):
    """
    Format a list of message sizes into a complete LIST response.

    This generator function is intended to be used with
    L{Cooperator <twisted.internet.task.Cooperator>}.

    @type msgs: L{list} of L{int}
    @param msgs: A list of message sizes.

    @rtype: L{bytes}
    @return: Yields a series of strings which make up a complete LIST response.
    """
    yield successResponse(b"%d" % (len(msgs),))
    yield from formatListLines(msgs)
    yield b".\r\n"


def formatUIDListLines(msgs, getUidl):
    """
    Format a list of message sizes for use in a UIDL response.

    @param msgs: See L{formatUIDListResponse}
    @param getUidl: See L{formatUIDListResponse}

    @rtype: L{bytes}
    @return: Yields a series of strings that are suitable for use as unique-id
        listings in a UIDL response. Each string consists of a message number
        and its unique id.
    """
    for i, m in enumerate(msgs):
        if m is not None:
            uid = getUidl(i)
            if not isinstance(uid, bytes):
                uid = str(uid).encode("utf-8")
            yield b"%d %b\r\n" % (i + 1, uid)


def formatUIDListResponse(msgs, getUidl):
    """
    Format a list of message sizes into a complete UIDL response.

    This generator function is intended to be used with
    L{Cooperator <twisted.internet.task.Cooperator>}.

    @type msgs: L{list} of L{int}
    @param msgs: A list of message sizes.

    @type getUidl: one-argument callable returning bytes
    @param getUidl: A callable which takes a message index number and returns
        the UID of the corresponding message in the mailbox.

    @rtype: L{bytes}
    @return: Yields a series of strings which make up a complete UIDL response.
    """
    yield successResponse("")
    yield from formatUIDListLines(msgs, getUidl)
    yield b".\r\n"


@implementer(interfaces.IProducer)
class POP3(basic.LineOnlyReceiver, policies.TimeoutMixin):
    """
    A POP3 server protocol.

    @type portal: L{Portal}
    @ivar portal: A portal for authentication.

    @type factory: L{IServerFactory} provider
    @ivar factory: A server factory which provides an interface for querying
        capabilities of the server.

    @type timeOut: L{int}
    @ivar timeOut: The number of seconds to wait for a command from the client
        before disconnecting.

    @type schedule: callable that takes interator and returns
        L{Deferred <defer.Deferred>}
    @ivar schedule: A callable that arranges for an iterator to be
        cooperatively iterated over along with all other iterators which have
        been passed to it such that runtime is divided between all of them.  It
        returns a deferred which fires when the iterator finishes.

    @type magic: L{bytes} or L{None}
    @ivar magic: An APOP challenge.  If not set, an APOP challenge string
        will be generated when a connection is made.

    @type _userIs: L{bytes} or L{None}
    @ivar _userIs: The username sent with the USER command.

    @type _onLogout: no-argument callable or L{None}
    @ivar _onLogout: The function to be executed when the connection is
        lost.

    @type mbox: L{IMailbox} provider
    @ivar mbox: The mailbox for the authenticated user.

    @type state: L{bytes}
    @ivar state: The state which indicates what type of messages are expected
        from the client.  Valid states are 'COMMAND' and 'AUTH'

    @type blocked: L{None} or L{list} of 2-L{tuple} of
        (E{1}) L{bytes} (E{2}) L{tuple} of L{bytes}
    @ivar blocked: A list of blocked commands.  While a response to a command
        is being generated by the server, other commands are blocked.  When
        no command is outstanding, C{blocked} is set to none.  Otherwise, it
        contains a list of information about blocked commands.  Each list
        entry consists of the command and the arguments to the command.

    @type _highest: L{int}
    @ivar _highest: The 1-based index of the highest message retrieved.

    @type _auth: L{IUsernameHashedPassword
        <cred.credentials.IUsernameHashedPassword>} provider
    @ivar _auth: Authorization credentials.
    """

    magic: Optional[bytes] = None
    _userIs = None
    _onLogout = None

    AUTH_CMDS = [b"CAPA", b"USER", b"PASS", b"APOP", b"AUTH", b"RPOP", b"QUIT"]

    portal = None
    factory = None

    # The mailbox we're serving
    mbox = None

    # Set this pretty low -- POP3 clients are expected to log in, download
    # everything, and log out.
    timeOut = 300

    state = "COMMAND"

    # PIPELINE
    blocked = None

    # Cooperate and suchlike.
    schedule = staticmethod(task.coiterate)

    _highest = 0

    def connectionMade(self):
        """
        Send a greeting to the client after the connection has been made.
        """
        if self.magic is None:
            self.magic = self.generateMagic()
        self.successResponse(self.magic)
        self.setTimeout(self.timeOut)
        if getattr(self.factory, "noisy", True):
            log.msg("New connection from " + str(self.transport.getPeer()))

    def connectionLost(self, reason):
        """
        Clean up when the connection has been lost.

        @type reason: L{Failure}
        @param reason: The reason the connection was terminated.
        """
        if self._onLogout is not None:
            self._onLogout()
            self._onLogout = None
        self.setTimeout(None)

    def generateMagic(self):
        """
        Generate an APOP challenge.

        @rtype: L{bytes}
        @return: An RFC 822 message id format string.
        """
        return smtp.messageid()

    def successResponse(self, message=""):
        """
        Send a response indicating success.

        @type message: stringifyable L{object}
        @param message: An object whose string representation should be
            included in the response.
        """
        self.transport.write(successResponse(message))

    def failResponse(self, message=b""):
        """
        Send a response indicating failure.

        @type message: stringifyable L{object}
        @param message: An object whose string representation should be
            included in the response.
        """
        if not isinstance(message, bytes):
            message = str(message).encode("utf-8")
        self.sendLine(b"-ERR " + message)

    def lineReceived(self, line):
        """
        Pass a received line to a state machine function.

        @type line: L{bytes}
        @param line: A received line.
        """
        self.resetTimeout()
        getattr(self, "state_" + self.state)(line)

    def _unblock(self, _):
        """
        Process as many blocked commands as possible.

        If there are no more blocked commands, set up for the next command to
        be sent immediately.

        @type _: L{object}
        @param _: Ignored.
        """
        commands = self.blocked
        self.blocked = None
        while commands and self.blocked is None:
            cmd, args = commands.pop(0)
            self.processCommand(cmd, *args)
        if self.blocked is not None:
            self.blocked.extend(commands)

    def state_COMMAND(self, line):
        """
        Handle received lines for the COMMAND state in which commands from the
        client are expected.

        @type line: L{bytes}
        @param line: A received command.
        """
        try:
            return self.processCommand(*line.split(b" "))
        except (ValueError, AttributeError, POP3Error, TypeError) as e:
            log.err()
            self.failResponse(
                b": ".join(
                    [
                        b"bad protocol or server",
                        e.__class__.__name__.encode("utf-8"),
                        b"".join(e.args),
                    ]
                )
            )

    def processCommand(self, command, *args):
        """
        Dispatch a command from the client for handling.

        @type command: L{bytes}
        @param command: A POP3 command.

        @type args: L{tuple} of L{bytes}
        @param args: Arguments to the command.

        @raise POP3Error: When the command is invalid or the command requires
            prior authentication which hasn't been performed.
        """
        if self.blocked is not None:
            self.blocked.append((command, args))
            return

        command = command.upper()
        authCmd = command in self.AUTH_CMDS
        if not self.mbox and not authCmd:
            raise POP3Error(b"not authenticated yet: cannot do " + command)
        f = getattr(self, "do_" + command.decode("utf-8"), None)
        if f:
            return f(*args)
        raise POP3Error(b"Unknown protocol command: " + command)

    def listCapabilities(self):
        """
        Return a list of server capabilities suitable for use in a CAPA
        response.

        @rtype: L{list} of L{bytes}
        @return: A list of server capabilities.
        """
        baseCaps = [
            b"TOP",
            b"USER",
            b"UIDL",
            b"PIPELINE",
            b"CELERITY",
            b"AUSPEX",
            b"POTENCE",
        ]

        if IServerFactory.providedBy(self.factory):
            # Oh my god.  We can't just loop over a list of these because
            # each has spectacularly different return value semantics!
            try:
                v = self.factory.cap_IMPLEMENTATION()
                if v and not isinstance(v, bytes):
                    v = str(v).encode("utf-8")
            except NotImplementedError:
                pass
            except BaseException:
                log.err()
            else:
                baseCaps.append(b"IMPLEMENTATION " + v)

            try:
                v = self.factory.cap_EXPIRE()
                if v and not isinstance(v, bytes):
                    v = str(v).encode("utf-8")
            except NotImplementedError:
                pass
            except BaseException:
                log.err()
            else:
                if v is None:
                    v = b"NEVER"
                if self.factory.perUserExpiration():
                    if self.mbox:
                        v = str(self.mbox.messageExpiration).encode("utf-8")
                    else:
                        v = v + b" USER"
                baseCaps.append(b"EXPIRE " + v)

            try:
                v = self.factory.cap_LOGIN_DELAY()
                if v and not isinstance(v, bytes):
                    v = str(v).encode("utf-8")
            except NotImplementedError:
                pass
            except BaseException:
                log.err()
            else:
                if self.factory.perUserLoginDelay():
                    if self.mbox:
                        v = str(self.mbox.loginDelay).encode("utf-8")
                    else:
                        v = v + b" USER"
                baseCaps.append(b"LOGIN-DELAY " + v)

            try:
                v = self.factory.challengers
            except AttributeError:
                pass
            except BaseException:
                log.err()
            else:
                baseCaps.append(b"SASL " + b" ".join(v.keys()))
        return baseCaps

    def do_CAPA(self):
        """
        Handle a CAPA command.

        Respond with the server capabilities.
        """
        self.successResponse(b"I can do the following:")
        for cap in self.listCapabilities():
            self.sendLine(cap)
        self.sendLine(b".")

    def do_AUTH(self, args=None):
        """
        Handle an AUTH command.

        If the AUTH extension is not supported, send an error response.  If an
        authentication mechanism was not specified in the command, send a list
        of all supported authentication methods.  Otherwise, send an
        authentication challenge to the client and transition to the
        AUTH state.

        @type args: L{bytes} or L{None}
        @param args: The name of an authentication mechanism.
        """
        if not getattr(self.factory, "challengers", None):
            self.failResponse(b"AUTH extension unsupported")
            return

        if args is None:
            self.successResponse("Supported authentication methods:")
            for a in self.factory.challengers:
                self.sendLine(a.upper())
            self.sendLine(b".")
            return

        auth = self.factory.challengers.get(args.strip().upper())
        if not self.portal or not auth:
            self.failResponse(b"Unsupported SASL selected")
            return

        self._auth = auth()
        chal = self._auth.getChallenge()

        self.sendLine(b"+ " + base64.b64encode(chal))
        self.state = "AUTH"

    def state_AUTH(self, line):
        """
        Handle received lines for the AUTH state in which an authentication
        challenge response from the client is expected.

        Transition back to the COMMAND state.  Check the credentials and
        complete the authorization process with the L{_cbMailbox}
        callback function on success or the L{_ebMailbox} and L{_ebUnexpected}
        errback functions on failure.

        @type line: L{bytes}
        @param line: The challenge response.
        """
        self.state = "COMMAND"
        try:
            parts = base64.b64decode(line).split(None, 1)
        except binascii.Error:
            self.failResponse(b"Invalid BASE64 encoding")
        else:
            if len(parts) != 2:
                self.failResponse(b"Invalid AUTH response")
                return
            self._auth.username = parts[0]
            self._auth.response = parts[1]
            d = self.portal.login(self._auth, None, IMailbox)
            d.addCallback(self._cbMailbox, parts[0])
            d.addErrback(self._ebMailbox)
            d.addErrback(self._ebUnexpected)

    def do_APOP(self, user, digest):
        """
        Handle an APOP command.

        Perform APOP authentication and complete the authorization process with
        the L{_cbMailbox} callback function on success or the L{_ebMailbox}
        and L{_ebUnexpected} errback functions on failure.

        @type user: L{bytes}
        @param user: A username.

        @type digest: L{bytes}
        @param digest: An MD5 digest string.
        """
        d = defer.maybeDeferred(self.authenticateUserAPOP, user, digest)
        d.addCallbacks(
            self._cbMailbox, self._ebMailbox, callbackArgs=(user,)
        ).addErrback(self._ebUnexpected)

    def _cbMailbox(self, result, user):
        """
        Complete successful authentication.

        Save the mailbox and logout function for the authenticated user and
        send a successful response to the client.

        @type result: C{tuple}
        @param result: The first item of the tuple is a
            C{zope.interface.Interface} which is the interface
            supported by the avatar.  The second item of the tuple is a
            L{IMailbox} provider which is the mailbox for the
            authenticated user.  The third item of the tuple is a no-argument
            callable which is a function to be invoked when the session is
            terminated.

        @type user: L{bytes}
        @param user: The user being authenticated.
        """
        (interface, avatar, logout) = result
        if interface is not IMailbox:
            self.failResponse(b"Authentication failed")
            log.err("_cbMailbox() called with an interface other than IMailbox")
            return

        self.mbox = avatar
        self._onLogout = logout
        self.successResponse("Authentication succeeded")
        if getattr(self.factory, "noisy", True):
            log.msg(b"Authenticated login for " + user)

    def _ebMailbox(self, failure):
        """
        Handle an expected authentication failure.

        Send an appropriate error response for a L{LoginDenied} or
        L{LoginFailed} authentication failure.

        @type failure: L{Failure}
        @param failure: The authentication error.
        """
        failure = failure.trap(cred.error.LoginDenied, cred.error.LoginFailed)
        if issubclass(failure, cred.error.LoginDenied):
            self.failResponse("Access denied: " + str(failure))
        elif issubclass(failure, cred.error.LoginFailed):
            self.failResponse(b"Authentication failed")
        if getattr(self.factory, "noisy", True):
            log.msg("Denied login attempt from " + str(self.transport.getPeer()))

    def _ebUnexpected(self, failure):
        """
        Handle an unexpected authentication failure.

        Send an error response for an unexpected authentication failure.

        @type failure: L{Failure}
        @param failure: The authentication error.
        """
        self.failResponse("Server error: " + failure.getErrorMessage())
        log.err(failure)

    def do_USER(self, user):
        """
        Handle a USER command.

        Save the username and send a successful response prompting the client
        for the password.

        @type user: L{bytes}
        @param user: A username.
        """
        self._userIs = user
        self.successResponse(b"USER accepted, send PASS")

    def do_PASS(self, password, *words):
        """
        Handle a PASS command.

        If a USER command was previously received, authenticate the user and
        complete the authorization process with the L{_cbMailbox} callback
        function on success or the L{_ebMailbox} and L{_ebUnexpected} errback
        functions on failure.  If a USER command was not previously received,
        send an error response.

        @type password: L{bytes}
        @param password: A password.

        @type words: L{tuple} of L{bytes}
        @param words: Other parts of the password split by spaces.
        """
        if self._userIs is None:
            self.failResponse(b"USER required before PASS")
            return
        user = self._userIs
        self._userIs = None
        password = b" ".join((password,) + words)
        d = defer.maybeDeferred(self.authenticateUserPASS, user, password)
        d.addCallbacks(
            self._cbMailbox, self._ebMailbox, callbackArgs=(user,)
        ).addErrback(self._ebUnexpected)

    def _longOperation(self, d):
        """
        Stop timeouts and block further command processing while a long
        operation completes.

        @type d: L{Deferred <defer.Deferred>}
        @param d: A deferred which triggers at the completion of a long
            operation.

        @rtype: L{Deferred <defer.Deferred>}
        @return: A deferred which triggers after command processing resumes and
            timeouts restart after the completion of a long operation.
        """
        timeOut = self.timeOut
        self.setTimeout(None)
        self.blocked = []
        d.addCallback(self._unblock)
        d.addCallback(lambda ign: self.setTimeout(timeOut))
        return d

    def _coiterate(self, gen):
        """
        Direct the output of an iterator to the transport and arrange for
        iteration to take place.

        @type gen: iterable which yields L{bytes}
        @param gen: An iterator over strings.

        @rtype: L{Deferred <defer.Deferred>}
        @return: A deferred which fires when the iterator finishes.
        """
        return self.schedule(_IteratorBuffer(self.transport.writeSequence, gen))

    def do_STAT(self):
        """
        Handle a STAT command.

        @rtype: L{Deferred <defer.Deferred>}
        @return: A deferred which triggers after the response to the STAT
            command has been issued.
        """
        d = defer.maybeDeferred(self.mbox.listMessages)

        def cbMessages(msgs):
            return self._coiterate(formatStatResponse(msgs))

        def ebMessages(err):
            self.failResponse(err.getErrorMessage())
            log.msg("Unexpected do_STAT failure:")
            log.err(err)

        return self._longOperation(d.addCallbacks(cbMessages, ebMessages))

    def do_LIST(self, i=None):
        """
        Handle a LIST command.

        @type i: L{bytes} or L{None}
        @param i: A 1-based message index.

        @rtype: L{Deferred <defer.Deferred>}
        @return: A deferred which triggers after the response to the LIST
            command has been issued.
        """
        if i is None:
            d = defer.maybeDeferred(self.mbox.listMessages)

            def cbMessages(msgs):
                return self._coiterate(formatListResponse(msgs))

            def ebMessages(err):
                self.failResponse(err.getErrorMessage())
                log.msg("Unexpected do_LIST failure:")
                log.err(err)

            return self._longOperation(d.addCallbacks(cbMessages, ebMessages))
        else:
            try:
                i = int(i)
                if i < 1:
                    raise ValueError()
            except ValueError:
                if not isinstance(i, bytes):
                    i = str(i).encode("utf-8")
                self.failResponse(b"Invalid message-number: " + i)
            else:
                d = defer.maybeDeferred(self.mbox.listMessages, i - 1)

                def cbMessage(msg):
                    self.successResponse(b"%d %d" % (i, msg))

                def ebMessage(err):
                    errcls = err.check(ValueError, IndexError)
                    if errcls is not None:
                        if errcls is IndexError:
                            # IndexError was supported for a while, but really
                            # shouldn't be.  One error condition, one exception
                            # type.  See ticket #6669.
                            warnings.warn(
                                "twisted.mail.pop3.IMailbox.listMessages may "
                                "not raise IndexError for out-of-bounds "
                                "message numbers: raise ValueError instead.",
                                PendingDeprecationWarning,
                            )
                        invalidNum = i
                        if invalidNum and not isinstance(invalidNum, bytes):
                            invalidNum = str(invalidNum).encode("utf-8")
                        self.failResponse(b"Invalid message-number: " + invalidNum)
                    else:
                        self.failResponse(err.getErrorMessage())
                        log.msg("Unexpected do_LIST failure:")
                        log.err(err)

                d.addCallbacks(cbMessage, ebMessage)
                return self._longOperation(d)

    def do_UIDL(self, i=None):
        """
        Handle a UIDL command.

        @type i: L{bytes} or L{None}
        @param i: A 1-based message index.

        @rtype: L{Deferred <defer.Deferred>}
        @return: A deferred which triggers after the response to the UIDL
            command has been issued.
        """
        if i is None:
            d = defer.maybeDeferred(self.mbox.listMessages)

            def cbMessages(msgs):
                return self._coiterate(
                    formatUIDListResponse(msgs, self.mbox.getUidl),
                )

            def ebMessages(err):
                self.failResponse(err.getErrorMessage())
                log.msg("Unexpected do_UIDL failure:")
                log.err(err)

            return self._longOperation(d.addCallbacks(cbMessages, ebMessages))
        else:
            try:
                i = int(i)
                if i < 1:
                    raise ValueError()
            except ValueError:
                self.failResponse("Bad message number argument")
            else:
                try:
                    msg = self.mbox.getUidl(i - 1)
                except IndexError:
                    # XXX TODO See above comment regarding IndexError.
                    warnings.warn(
                        "twisted.mail.pop3.IMailbox.getUidl may not "
                        "raise IndexError for out-of-bounds message numbers: "
                        "raise ValueError instead.",
                        PendingDeprecationWarning,
                    )
                    self.failResponse("Bad message number argument")
                except ValueError:
                    self.failResponse("Bad message number argument")
                else:
                    if not isinstance(msg, bytes):
                        msg = str(msg).encode("utf-8")
                    self.successResponse(msg)

    def _getMessageFile(self, i):
        """
        Retrieve the size and contents of a message.

        @type i: L{bytes}
        @param i: A 1-based message index.

        @rtype: L{Deferred <defer.Deferred>} which successfully fires with
            2-L{tuple} of (E{1}) L{int}, (E{2}) file-like object
        @return: A deferred which successfully fires with the size of the
            message and a file containing the contents of the message.
        """
        try:
            msg = int(i) - 1
            if msg < 0:
                raise ValueError()
        except ValueError:
            self.failResponse("Bad message number argument")
            return defer.succeed(None)

        sizeDeferred = defer.maybeDeferred(self.mbox.listMessages, msg)

        def cbMessageSize(size):
            if not size:
                return defer.fail(_POP3MessageDeleted())
            fileDeferred = defer.maybeDeferred(self.mbox.getMessage, msg)
            fileDeferred.addCallback(lambda fObj: (size, fObj))
            return fileDeferred

        def ebMessageSomething(err):
            errcls = err.check(_POP3MessageDeleted, ValueError, IndexError)
            if errcls is _POP3MessageDeleted:
                self.failResponse("message deleted")
            elif errcls in (ValueError, IndexError):
                if errcls is IndexError:
                    # XXX TODO See above comment regarding IndexError.
                    warnings.warn(
                        "twisted.mail.pop3.IMailbox.listMessages may not "
                        "raise IndexError for out-of-bounds message numbers: "
                        "raise ValueError instead.",
                        PendingDeprecationWarning,
                    )
                self.failResponse("Bad message number argument")
            else:
                log.msg("Unexpected _getMessageFile failure:")
                log.err(err)
            return None

        sizeDeferred.addCallback(cbMessageSize)
        sizeDeferred.addErrback(ebMessageSomething)
        return sizeDeferred

    def _sendMessageContent(self, i, fpWrapper, successResponse):
        """
        Send the contents of a message.

        @type i: L{bytes}
        @param i: A 1-based message index.

        @type fpWrapper: callable that takes a file-like object and returns
            a file-like object
        @param fpWrapper:

        @type successResponse: callable that takes L{int} and returns
            L{bytes}
        @param successResponse:

        @rtype: L{Deferred}
        @return: A deferred which triggers after the message has been sent.
        """
        d = self._getMessageFile(i)

        def cbMessageFile(info):
            if info is None:
                # Some error occurred - a failure response has been sent
                # already, just give up.
                return

            self._highest = max(self._highest, int(i))
            resp, fp = info
            fp = fpWrapper(fp)
            self.successResponse(successResponse(resp))
            s = basic.FileSender()
            d = s.beginFileTransfer(fp, self.transport, self.transformChunk)

            def cbFileTransfer(lastsent):
                if lastsent != b"\n":
                    line = b"\r\n."
                else:
                    line = b"."
                self.sendLine(line)

            def ebFileTransfer(err):
                self.transport.loseConnection()
                log.msg("Unexpected error in _sendMessageContent:")
                log.err(err)

            d.addCallback(cbFileTransfer)
            d.addErrback(ebFileTransfer)
            return d

        return self._longOperation(d.addCallback(cbMessageFile))

    def do_TOP(self, i, size):
        """
        Handle a TOP command.

        @type i: L{bytes}
        @param i: A 1-based message index.

        @type size: L{bytes}
        @param size: The number of lines of the message to retrieve.

        @rtype: L{Deferred}
        @return: A deferred which triggers after the response to the TOP
            command has been issued.
        """
        try:
            size = int(size)
            if size < 0:
                raise ValueError
        except ValueError:
            self.failResponse("Bad line count argument")
        else:
            return self._sendMessageContent(
                i,
                lambda fp: _HeadersPlusNLines(fp, size),
                lambda size: "Top of message follows",
            )

    def do_RETR(self, i):
        """
        Handle a RETR command.

        @type i: L{bytes}
        @param i: A 1-based message index.

        @rtype: L{Deferred}
        @return: A deferred which triggers after the response to the RETR
            command has been issued.
        """
        return self._sendMessageContent(i, lambda fp: fp, lambda size: "%d" % (size,))

    def transformChunk(self, chunk):
        """
        Transform a chunk of a message to POP3 message format.

        Make sure each line ends with C{'\\r\\n'} and byte-stuff the
        termination character (C{'.'}) by adding an extra one when one appears
        at the beginning of a line.

        @type chunk: L{bytes}
        @param chunk: A string to transform.

        @rtype: L{bytes}
        @return: The transformed string.
        """
        return chunk.replace(b"\n", b"\r\n").replace(b"\r\n.", b"\r\n..")

    def finishedFileTransfer(self, lastsent):
        """
        Send the termination sequence.

        @type lastsent: L{bytes}
        @param lastsent: The last character of the file.
        """
        if lastsent != b"\n":
            line = b"\r\n."
        else:
            line = b"."
        self.sendLine(line)

    def do_DELE(self, i):
        """
        Handle a DELE command.

        Mark a message for deletion and issue a successful response.

        @type i: L{int}
        @param i: A 1-based message index.
        """
        i = int(i) - 1
        self.mbox.deleteMessage(i)
        self.successResponse()

    def do_NOOP(self):
        """
        Handle a NOOP command.

        Do nothing but issue a successful response.
        """
        self.successResponse()

    def do_RSET(self):
        """
        Handle a RSET command.

        Unmark any messages that have been flagged for deletion.
        """
        try:
            self.mbox.undeleteMessages()
        except BaseException:
            log.err()
            self.failResponse()
        else:
            self._highest = 0
            self.successResponse()

    def do_LAST(self):
        """
        Handle a LAST command.

        Respond with the 1-based index of the highest retrieved message.
        """
        self.successResponse(self._highest)

    def do_RPOP(self, user):
        """
        Handle an RPOP command.

        RPOP is not supported.  Send an error response.

        @type user: L{bytes}
        @param user: A username.

        """
        self.failResponse("permission denied, sucker")

    def do_QUIT(self):
        """
        Handle a QUIT command.

        Remove any messages marked for deletion, issue a successful response,
        and drop the connection.
        """
        if self.mbox:
            self.mbox.sync()
        self.successResponse()
        self.transport.loseConnection()

    def authenticateUserAPOP(self, user, digest):
        """
        Perform APOP authentication.

        @type user: L{bytes}
        @param user: The name of the user attempting to log in.

        @type digest: L{bytes}
        @param digest: The challenge response.

        @rtype: L{Deferred <defer.Deferred>} which successfully results in
            3-L{tuple} of (E{1}) L{IMailbox <pop3.IMailbox>}, (E{2})
            L{IMailbox <pop3.IMailbox>} provider, (E{3}) no-argument callable
        @return: A deferred which fires when authentication is complete.  If
            successful, it returns an L{IMailbox <pop3.IMailbox>} interface, a
            mailbox, and a function to be invoked with the session is
            terminated.  If authentication fails, the deferred fails with an
            L{UnathorizedLogin <cred.error.UnauthorizedLogin>} error.

        @raise cred.error.UnauthorizedLogin: When authentication fails.
        """
        if self.portal is not None:
            return self.portal.login(
                APOPCredentials(self.magic, user, digest), None, IMailbox
            )
        raise cred.error.UnauthorizedLogin()

    def authenticateUserPASS(self, user, password):
        """
        Perform authentication for a username/password login.

        @type user: L{bytes}
        @param user: The name of the user attempting to log in.

        @type password: L{bytes}
        @param password: The password to authenticate with.

        @rtype: L{Deferred <defer.Deferred>} which successfully results in
            3-L{tuple} of (E{1}) L{IMailbox <pop3.IMailbox>}, (E{2}) L{IMailbox
            <pop3.IMailbox>} provider, (E{3}) no-argument callable
        @return: A deferred which fires when authentication is complete.  If
            successful, it returns a L{pop3.IMailbox} interface, a mailbox,
            and a function to be invoked with the session is terminated.
            If authentication fails, the deferred fails with an
            L{UnathorizedLogin <cred.error.UnauthorizedLogin>} error.

        @raise cred.error.UnauthorizedLogin: When authentication fails.
        """
        if self.portal is not None:
            return self.portal.login(
                cred.credentials.UsernamePassword(user, password), None, IMailbox
            )
        raise cred.error.UnauthorizedLogin()

    def stopProducing(self):
        # IProducer.stopProducing
        raise NotImplementedError()


@implementer(IMailbox)
class Mailbox:
    """
    A base class for mailboxes.
    """

    def listMessages(self, i=None):
        """
        Retrieve the size of a message, or, if none is specified, the size of
        each message in the mailbox.

        @type i: L{int} or L{None}
        @param i: The 0-based index of the message.

        @rtype: L{int}, sequence of L{int}, or L{Deferred <defer.Deferred>}
        @return: The number of octets in the specified message, or, if an
            index is not specified, a sequence of the number of octets for
            all messages in the mailbox or a deferred which fires with
            one of those. Any value which corresponds to a deleted message
            is set to 0.

        @raise ValueError or IndexError: When the index does not correspond to
            a message in the mailbox.  The use of ValueError is preferred.
        """
        return []

    def getMessage(self, i):
        """
        Retrieve a file containing the contents of a message.

        @type i: L{int}
        @param i: The 0-based index of a message.

        @rtype: file-like object
        @return: A file containing the message.

        @raise ValueError or IndexError: When the index does not correspond to
            a message in the mailbox.  The use of ValueError is preferred.
        """
        raise ValueError

    def getUidl(self, i):
        """
        Get a unique identifier for a message.

        @type i: L{int}
        @param i: The 0-based index of a message.

        @rtype: L{bytes}
        @return: A string of printable characters uniquely identifying the
            message for all time.

        @raise ValueError or IndexError: When the index does not correspond to
            a message in the mailbox.  The use of ValueError is preferred.
        """
        raise ValueError

    def deleteMessage(self, i):
        """
        Mark a message for deletion.

        This must not change the number of messages in this mailbox.  Further
        requests for the size of the deleted message should return 0.  Further
        requests for the message itself may raise an exception.

        @type i: L{int}
        @param i: The 0-based index of a message.

        @raise ValueError or IndexError: When the index does not correspond to
            a message in the mailbox.  The use of ValueError is preferred.
        """
        raise ValueError

    def undeleteMessages(self):
        """
        Undelete all messages marked for deletion.

        Any message which can be undeleted should be returned to its original
        position in the message sequence and retain its original UID.
        """
        pass

    def sync(self):
        """
        Discard the contents of any message marked for deletion.
        """
        pass


NONE, SHORT, FIRST_LONG, LONG = range(4)

NEXT = {}
NEXT[NONE] = NONE
NEXT[SHORT] = NONE
NEXT[FIRST_LONG] = LONG
NEXT[LONG] = NONE


class POP3Client(basic.LineOnlyReceiver):
    """
    A POP3 client protocol.

    @type mode: L{int}
    @ivar mode: The type of response expected from the server.  Choices include
    none (0), a one line response (1), the first line of a multi-line
    response (2), and subsequent lines of a multi-line response (3).

    @type command: L{bytes}
    @ivar command: The command most recently sent to the server.

    @type welcomeRe: L{Pattern <re.Pattern.search>}
    @ivar welcomeRe: A regular expression which matches the APOP challenge in
        the server greeting.

    @type welcomeCode: L{bytes}
    @ivar welcomeCode: The APOP challenge passed in the server greeting.
    """

    mode = SHORT
    command = b"WELCOME"
    import re

    welcomeRe = re.compile(b"<(.*)>")

    def __init__(self):
        """
        Issue deprecation warning.
        """
        import warnings

        warnings.warn(
            "twisted.mail.pop3.POP3Client is deprecated, "
            "please use twisted.mail.pop3.AdvancedPOP3Client "
            "instead.",
            DeprecationWarning,
            stacklevel=3,
        )

    def sendShort(self, command, params=None):
        """
        Send a POP3 command to which a short response is expected.

        @type command: L{bytes}
        @param command: A POP3 command.

        @type params: stringifyable L{object} or L{None}
        @param params: Command arguments.
        """
        if params is not None:
            if not isinstance(params, bytes):
                params = str(params).encode("utf-8")
            self.sendLine(command + b" " + params)
        else:
            self.sendLine(command)
        self.command = command
        self.mode = SHORT

    def sendLong(self, command, params):
        """
        Send a POP3 command to which a long response is expected.

        @type command: L{bytes}
        @param command: A POP3 command.

        @type params: stringifyable L{object}
        @param params: Command arguments.
        """
        if params:
            if not isinstance(params, bytes):
                params = str(params).encode("utf-8")
            self.sendLine(command + b" " + params)
        else:
            self.sendLine(command)
        self.command = command
        self.mode = FIRST_LONG

    def handle_default(self, line):
        """
        Handle responses from the server for which no other handler exists.

        @type line: L{bytes}
        @param line: A received line.
        """
        if line[:-4] == b"-ERR":
            self.mode = NONE

    def handle_WELCOME(self, line):
        """
        Handle a server response which is expected to be a server greeting.

        @type line: L{bytes}
        @param line: A received line.
        """
        code, data = line.split(b" ", 1)
        if code != b"+OK":
            self.transport.loseConnection()
        else:
            m = self.welcomeRe.match(line)
            if m:
                self.welcomeCode = m.group(1)

    def _dispatch(self, command, default, *args):
        """
        Dispatch a response from the server for handling.

        Command X is dispatched to handle_X() if it exists.  If not, it is
        dispatched to the default handler.

        @type command: L{bytes}
        @param command: The command.

        @type default: callable that takes L{bytes} or
            L{None}
        @param default: The default handler.

        @type args: L{tuple} or L{None}
        @param args: Arguments to the handler function.
        """
        try:
            method = getattr(self, "handle_" + command.decode("utf-8"), default)
            if method is not None:
                method(*args)
        except BaseException:
            log.err()

    def lineReceived(self, line):
        """
        Dispatch a received line for processing.

        The choice of function to handle the received line is based on the
        type of response expected to the command sent to the server and how
        much of that response has been received.

        An expected one line response to command X is handled by handle_X().
        The first line of a multi-line response to command X is also handled by
        handle_X().  Subsequent lines of the multi-line response are handled by
        handle_X_continue() except for the last line which is handled by
        handle_X_end().

        @type line: L{bytes}
        @param line: A received line.
        """
        if self.mode == SHORT or self.mode == FIRST_LONG:
            self.mode = NEXT[self.mode]
            self._dispatch(self.command, self.handle_default, line)
        elif self.mode == LONG:
            if line == b".":
                self.mode = NEXT[self.mode]
                self._dispatch(self.command + b"_end", None)
                return
            if line[:1] == b".":
                line = line[1:]
            self._dispatch(self.command + b"_continue", None, line)

    def apopAuthenticate(self, user, password, magic):
        """
        Perform an authenticated login.

        @type user: L{bytes}
        @param user: The username with which to log in.

        @type password: L{bytes}
        @param password: The password with which to log in.

        @type magic: L{bytes}
        @param magic: The challenge provided by the server.
        """
        digest = md5(magic + password).hexdigest().encode("ascii")
        self.apop(user, digest)

    def apop(self, user, digest):
        """
        Send an APOP command to perform authenticated login.

        @type user: L{bytes}
        @param user: The username with which to log in.

        @type digest: L{bytes}
        @param digest: The challenge response with which to authenticate.
        """
        self.sendLong(b"APOP", b" ".join((user, digest)))

    def retr(self, i):
        """
        Send a RETR command to retrieve a message from the server.

        @type i: L{int} or L{bytes}
        @param i: A 0-based message index.
        """
        self.sendLong(b"RETR", i)

    def dele(self, i):
        """
        Send a DELE command to delete a message from the server.

        @type i: L{int} or L{bytes}
        @param i: A 0-based message index.
        """
        self.sendShort(b"DELE", i)

    def list(self, i=""):
        """
        Send a LIST command to retrieve the size of a message or, if no message
        is specified, the sizes of all messages.

        @type i: L{int} or L{bytes}
        @param i: A 0-based message index or the empty string to specify all
            messages.
        """
        self.sendLong(b"LIST", i)

    def uidl(self, i=""):
        """
        Send a UIDL command to retrieve the unique identifier of a message or,
        if no message is specified, the unique identifiers of all messages.

        @type i: L{int} or L{bytes}
        @param i: A 0-based message index or the empty string to specify all
            messages.
        """
        self.sendLong(b"UIDL", i)

    def user(self, name):
        """
        Send a USER command to perform the first half of a plaintext login.

        @type name: L{bytes}
        @param name: The username with which to log in.
        """
        self.sendShort(b"USER", name)

    def password(self, password):
        """
        Perform the second half of a plaintext login.

        @type password: L{bytes}
        @param password: The plaintext password with which to authenticate.
        """
        self.sendShort(b"PASS", password)

    pass_ = password

    def quit(self):
        """
        Send a QUIT command to disconnect from the server.
        """
        self.sendShort(b"QUIT")


from twisted.mail._except import (
    InsecureAuthenticationDisallowed,
    LineTooLong,
    ServerErrorResponse,
    TLSError,
    TLSNotSupportedError,
)
from twisted.mail._pop3client import POP3Client as AdvancedPOP3Client

__all__ = [
    # Interfaces
    "IMailbox",
    "IServerFactory",
    # Exceptions
    "POP3Error",
    "POP3ClientError",
    "InsecureAuthenticationDisallowed",
    "ServerErrorResponse",
    "LineTooLong",
    "TLSError",
    "TLSNotSupportedError",
    # Protocol classes
    "POP3",
    "POP3Client",
    "AdvancedPOP3Client",
    # Misc
    "APOPCredentials",
    "Mailbox",
]