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
use std::collections::BTreeMap;
use std::fmt::{Display, Formatter, Write};
use std::str::FromStr;

use anyhow::Result;
use serde::{Deserialize, Serialize};
use sled::IVec;

#[derive(Copy, Clone, Debug)]
pub enum Command {
    /// APOP is used to do digest auth
    ///
    /// # Restrictions
    ///
    /// Only be given in the AUTHORIZATION stqaate after the POP3 greeting or
    /// after an unsuccessful USER or PASS command
    ///
    /// # Discussion
    ///
    /// Normally, each POP3 session starts with a USER/PASS
    /// exchange.  This results in a server/user-id specific
    /// password being sent in the clear onw the network.  For
    /// intermittent use of POP3, this may not introduce a sizable
    /// risk.  However, many POP3 client implementations connect to
    /// the POP3 server on a regular basis -- to check for new
    /// mail.  Further the interval of session initiation may be on
    /// the order of five minutes.  Hence, the risk of password
    /// capture is greatly enhanced.
    ///
    /// An alternate method of authentication is required which
    /// provides for both origin authentication and replay
    /// protection, but which does not involve sending a password
    /// in the clear over the network.  The APOP command provides
    /// this functionality.
    ///
    /// A POP3 server which implements the APOP command will
    /// include a timestamp in its banner greeting.  The syntax of
    /// the timestamp corresponds to the `msg-id' in [RFC822], and
    /// MUST be different each time the POP3 server issues a banner
    /// greeting.  For example, on a UNIX implementation in which a
    /// separate UNIX process is used for each instance of a POP3
    /// server, the syntax of the timestamp might be:
    ///
    /// <process-ID.clock@hostname>
    ///
    /// where `process-ID' is the decimal value of the process's
    /// PID, clock is the decimal value of the system clock, and
    /// hostname is the fully-qualified domain-name corresponding
    /// to the host where the POP3 server is running.
    ///
    /// The POP3 client makes note of this timestamp, and then
    /// issues the APOP command.  The `name' parameter has
    /// identical semantics to the `name' parameter of the USER
    /// command. The `digest' parameter is calculated by applying
    /// the MD5 algorithm [RFC1321] to a string consisting of the
    /// timestamp (including angle-brackets) followed by a shared
    /// secret.  This shared secret is a string known only to the
    /// POP3 client and server.  Great care should be taken to
    /// prevent unauthorized disclosure of the secret, as knowledge
    /// of the secret will allow any entity to successfully
    /// masquerade as the named user.  The `digest' parameter
    /// itself is a 16-octet value which is sent in hexadecimal
    /// format, using lower-case ASCII characters.
    ///
    /// When the POP3 server receives the APOP command, it verifies
    /// the digest provided.  If the digest is correct, the POP3
    /// server issues a positive response, and the POP3 session
    /// enters the TRANSACTION state.  Otherwise, a negative
    /// response is issued and the POP3 session remains in the
    /// AUTHORIZATION state.
    ///
    /// Note that as the length of the shared secret increases, so
    /// does the difficulty of deriving it.  As such, shared
    /// secrets should be long strings (considerably longer than
    /// the 8-character example shown below).
    ///
    /// # Syntax
    ///
    /// ```text
    /// S: +OK POP3 server ready <process-id.clock@hostname>
    /// C: APOP <username> <digest of "<process-id.clock@hostname><password>">
    /// S: +OK [msg]
    /// ```
    ///
    /// # Examples
    ///
    /// ```text
    /// S: +OK POP3 server ready <1896.697170952@dbc.mtview.ca.us>
    /// C: APOP mrose c4c9334bac560ecc979e58001b3e22fb
    /// S: +OK maildrop has 1 message (369 octets)
    /// ```
    ///
    ///  In this example, the shared  secret  is  the  string  `tan-
    ///  staaf'.  Hence, the MD5 algorithm is applied to the string
    ///
    ///     <1896.697170952@dbc.mtview.ca.us>tanstaaf
    ///
    ///  which produces a digest value of
    ///
    ///     c4c9334bac560ecc979e58001b3e22fb
    APOP,
    /// AUTH command indicates an authentication mechanism to the server.
    ///
    /// # Restrictions
    ///
    /// Only be given in the AUTHORIZATION state
    ///
    /// # Discussion
    ///
    /// The AUTH command indicates an authentication mechanism to
    /// the server.  If the server supports the requested
    /// authentication mechanism, it performs an authentication
    /// protocol exchange to authenticate and identify the user.
    /// Optionally, it also negotiates a protection mechanism for
    /// subsequent protocol interactions.  If the requested
    /// authentication mechanism is not supported, the server
    ///
    ///
    /// should reject the AUTH command by sending a negative
    /// response.
    ///
    /// The authentication protocol exchange consists of a series
    /// of server challenges and client answers that are specific
    /// to the authentication mechanism.  A server challenge,
    /// otherwise known as a ready response, is a line consisting
    /// of a "+" character followed by a single space and a BASE64
    /// encoded string.  The client answer consists of a line
    /// containing a BASE64 encoded string.  If the client wishes
    /// to cancel an authentication exchange, it should issue a
    /// line with a single "*".  If the server receives such an
    /// answer, it must reject the AUTH command by sending a
    /// negative response.
    ///
    /// A protection mechanism provides integrity and privacy
    /// protection to the protocol session.  If a protection
    /// mechanism is negotiated, it is applied to all subsequent
    /// data sent over the connection.  The protection mechanism
    /// takes effect immediately following the CRLF that concludes
    /// the authentication exchange for the client, and the CRLF of
    /// the positive response for the server.  Once the protection
    /// mechanism is in effect, the stream of command and response
    /// octets is processed into buffers of ciphertext.  Each
    /// buffer is transferred over the connection as a stream of
    /// octets prepended with a four octet field in network byte
    /// order that represents the length of the following data.
    /// The maximum ciphertext buffer length is defined by the
    /// protection mechanism.
    ///
    /// The server is not required to support any particular
    /// authentication mechanism, nor are authentication mechanisms
    /// required to support any protection mechanisms.  If an AUTH
    /// command fails with a negative response, the session remains
    /// in the AUTHORIZATION state and client may try another
    /// authentication mechanism by issuing another AUTH command,
    /// or may attempt to authenticate by using the USER/PASS or
    /// APOP commands.  In other words, the client may request
    /// authentication types in decreasing order of preference,
    /// with the USER/PASS or APOP command as a last resort.
    ///
    /// Should the client successfully complete the authentication
    /// exchange, the POP3 server issues a positive response and
    /// the POP3 session enters the TRANSACTION state.
    ///
    /// # Syntax
    ///
    /// ## List supported auth methods
    ///
    /// ```text
    /// C: AUTH
    /// S: +OK <msg>
    /// S: <auth>
    /// S: .
    /// ```
    ///
    /// ## Check and start a specific auth
    ///
    /// ```text
    /// C: AUTH <auth>
    /// S: <challenge>
    /// C: <response>
    /// S: +OK <msg>
    /// ```
    ///
    /// # Examples
    ///
    /// ```text
    /// S: +OK POP3 server ready
    /// C: AUTH KERBEROS_V4
    /// S: + AmFYig==
    /// C: BAcAQU5EUkVXLkNNVS5FRFUAOCAsho84kLN3/IJmrMG+25a4DT
    ///    +nZImJjnTNHJUtxAA+o0KPKfHEcAFs9a3CL5Oebe/ydHJUwYFd
    ///    WwuQ1MWiy6IesKvjL5rL9WjXUb9MwT9bpObYLGOKi1Qh
    /// S: + or//EoAADZI=
    /// C: DiAF5A4gA+oOIALuBkAAmw==
    /// S: +OK Kerberos V4 authentication successful
    /// ```
    AUTH,
    /// CAPA returns a list of capabilities supported by the POP3 server
    ///
    /// # Restrictions
    ///
    /// Available in both the AUTHORIZATION and TRANSACTION states
    ///
    /// # Discussion
    ///
    /// An -ERR response indicates the capability command is not
    /// implemented and the client will have to probe for
    /// capabilities as before.
    ///
    /// An +OK response is followed by a list of capabilities, one
    /// per line.  Each capability name MAY be followed by a single
    /// space and a space-separated list of parameters.  Each
    /// capability line is limited to 512 octets (including the
    /// CRLF).  The capability list is terminated by a line
    /// containing a termination octet (".") and a CRLF pair.
    ///
    /// ## Available capabilities
    ///
    /// - TOP
    /// - USER
    /// - SASL
    /// - RESP-CODES
    /// - LOGIN-DELAY
    /// - PIPELINING
    /// - EXPIRE
    /// - UIDL
    /// - IMPLEMENTATION
    ///
    /// # Syntax
    ///
    /// ```text
    /// C: CAPA
    /// S: +OK <msg>
    /// S: <capability>
    /// S: .
    /// ```
    ///
    /// # Examples
    ///
    /// ```text
    /// C: CAPA
    /// S: +OK Capability list follows
    /// S: TOP
    /// S: USER
    /// S: SASL CRAM-MD5 KERBEROS_V4
    /// S: RESP-CODES
    /// S: LOGIN-DELAY 900
    /// S: PIPELINING
    /// S: EXPIRE 60
    /// S: UIDL
    /// S: IMPLEMENTATION Shlemazle-Plotz-v302
    /// S: .
    /// ```
    CAPA,
    /// DELE will delete a mail from maildrop
    ///
    /// # Restrictions
    ///
    /// Only be given in the TRANSACTION state
    ///
    /// # Discussion
    ///
    /// The POP3 server marks the message as deleted.  Any future
    /// reference to the message-number associated with the message
    /// in a POP3 command generates an error.  The POP3 server does
    /// not actually delete the message until the POP3 session
    /// enters the UPDATE state.
    ///
    /// # Syntax
    ///
    /// ```text
    /// C: DELE <id>
    /// S: +OK [msg]
    /// ```
    ///
    /// # Examples
    ///
    /// ```text
    /// C: DELE 1
    /// S: +OK message 1 deleted
    /// ```
    ///
    /// ```text
    /// C: DELE 2
    /// S: -ERR message 2 already deleted
    /// ```
    DELE,
    /// LIST will list maildrop mails
    ///
    /// # Restrictions
    ///
    /// Only be given in the TRANSACTION state
    ///
    /// # Discussion
    ///
    /// If an argument was given and the POP3 server issues a
    /// positive response with a line containing information for
    /// that message.  This line is called a "scan listing" for
    /// that message.
    ///
    /// If no argument was given and the POP3 server issues a
    /// positive response, then the response given is multi-line.
    /// After the initial +OK, for each message in the maildrop,
    /// the POP3 server responds with a line containing
    /// information for that message.  This line is also called a
    /// "scan listing" for that message.  If there are no
    /// messages in the maildrop, then the POP3 server responds
    /// with no scan listings--it issues a positive response
    /// followed by a line containing a termination octet and a
    /// CRLF pair.
    ///
    /// In order to simplify parsing, all POP3 servers are
    /// required to use a certain format for scan listings.  A
    /// scan listing consists of the message-number of the
    /// message, followed by a single space and the exact size of
    /// the message in octets.  Methods for calculating the exact
    /// size of the message are described in the "Message Format"
    /// section below.  This memo makes no requirement on what
    /// follows the message size in the scan listing.  Minimal
    /// implementations should just end that line of the response
    /// with a CRLF pair.  More advanced implementations may
    /// include other information, as parsed from the message.
    ///
    ///    NOTE: This memo STRONGLY discourages implementations
    ///    from supplying additional information in the scan
    ///    listing.  Other, optional, facilities are discussed
    ///    later on which permit the client to parse the messages
    ///    in the maildrop.
    ///
    /// Note that messages marked as deleted are not listed.
    ///
    /// # Syntax
    ///
    /// ## List all mails
    ///
    /// ```text
    /// C: LIST
    /// S: +OK [msg]
    /// S: <id> <size>
    /// S: .
    /// ```
    ///
    /// ## List single mail
    ///
    /// ```text
    /// C: LIST <id>
    /// S: +OK <id> <size>
    /// ```
    ///
    /// # Examples
    ///
    /// ```text
    /// C: LIST
    /// S: +OK 2 messages (320 octets)
    /// S: 1 120
    /// S: 2 200
    /// S: .
    /// ```
    ///
    /// ```text
    /// C: LIST 2
    /// S: +OK 2 200
    /// ```
    ///
    /// ```text
    /// C: LIST 3
    /// S: -ERR no such message, only 2 messages in maildrop
    /// ```
    LIST,
    /// NOOP will do nothing, used to keep heartbeat.
    ///
    /// # Restrictions
    ///
    /// Only be given in the TRANSACTION state
    ///
    /// # Discussion
    ///
    /// The POP3 server does nothing, it merely replies with a positive response.
    ///
    /// # Syntax
    ///
    /// ```text
    /// C: NOOP
    /// S: +OK
    /// ```
    ///
    /// # Examples
    ///
    /// ```text
    /// C: NOOP
    /// S: +OK
    /// ```
    NOOP,
    /// QUIT will terminate this connection by client.
    ///
    /// # Syntax
    ///
    /// ```text
    /// C: QUIT
    /// S: +OK [msg]
    /// ```
    ///
    /// # Examples
    ///
    /// ```text
    /// C: QUIT
    /// S: +OK dewey POP3 server signing off (maildrop empty)
    /// ```
    QUIT,
    /// PASS is used to send password.
    ///
    /// # Restrictions
    ///
    /// Only be given in the AUTHORIZATION state immediately after a successful USER command
    ///
    /// # Discussion
    ///
    /// When the client issues the PASS command, the POP3 server
    /// uses the argument pair from the USER and PASS commands to
    /// determine if the client should be given access to the
    /// appropriate maildrop.
    ///
    /// Since the PASS command has exactly one argument, a POP3
    /// server may treat spaces in the argument as part of the
    /// password, instead of as argument separators.
    ///
    /// # Syntax
    ///
    /// ```text
    /// C: PASS <passowrd>
    /// S: +OK [msg]
    /// ```
    ///
    /// # Examples
    ///
    /// ```text
    /// C: USER mrose
    /// S: +OK mrose is a real hoopy frood
    /// C: PASS secret
    /// S: -ERR maildrop already locked
    /// ```
    ///
    /// ```text
    /// C: USER mrose
    /// S: +OK mrose is a real hoopy frood
    /// C: PASS secret
    /// S: +OK mrose's maildrop has 2 messages (320 octets)
    /// ```
    PASS,
    /// RETR will be used to retrieve a mail
    ///
    /// # Restrictions
    ///
    /// Only be given in the TRANSACTION state
    ///
    /// # Discussion
    ///
    /// If the POP3 server issues a positive response, then the
    /// response given is multi-line.  After the initial +OK, the
    /// POP3 server sends the message corresponding to the given
    /// message-number, being careful to byte-stuff the termination
    /// character (as with all multi-line responses).
    ///
    /// # Syntax
    ///
    /// ```text
    /// C: RETR <id>
    /// S: +OK [msg]
    /// S: <the POP3 server sends the entire message here>
    /// S: .
    /// ```
    ///
    /// # Examples
    ///
    /// ```text
    /// C: RETR 1
    /// S: +OK 120 octets
    /// S: <the POP3 server sends the entire message here>
    /// S: .
    /// ```
    RETR,
    /// RSET will reset the connection to initial state.
    ///
    /// # Restrictions
    ///
    /// Only be given in the TRANSACTION state
    ///
    /// # Discussion
    ///
    /// If any messages have been marked as deleted by the POP3
    /// server, they are unmarked.  The POP3 server then replies
    /// with a positive response.
    ///
    /// # Syntax
    ///
    /// ```text
    /// C: RSET
    /// S: +OK [msg]
    /// ```
    ///
    /// # Examples
    ///
    /// ```text
    /// C: RSET
    /// S: +OK maildrop has 2 messages (320 octets)
    /// ```
    RSET,
    /// STAT will show the stat of maildrop.
    ///
    /// # Restrictions
    ///
    /// Only be given in the TRANSACTION state
    ///
    /// # Discussion
    ///
    /// The POP3 server issues a positive response with a line
    /// containing information for the maildrop.  This line is
    /// called a "drop listing" for that maildrop.
    ///
    /// In order to simplify parsing, all POP3 servers are
    /// required to use a certain format for drop listings.  The
    /// positive response consists of "+OK" followed by a single
    /// space, the number of messages in the maildrop, a single
    /// space, and the size of the maildrop in octets.  This memo
    /// makes no requirement on what follows the maildrop size.
    /// Minimal implementations should just end that line of the
    /// response with a CRLF pair.  More advanced implementations
    /// may include other information.
    ///
    ///     NOTE: This memo STRONGLY discourages implementations
    ///     from supplying additional information in the drop
    ///     listing.  Other, optional, facilities are discussed
    ///     later on which permit the client to parse the messages
    ///     in the maildrop.
    ///
    /// Note that messages marked as deleted are not counted in
    /// either total.
    ///
    /// # Syntax
    ///
    /// ```text
    /// C: STAT
    /// S: OK <count> <size>
    /// ```
    ///
    /// # Examples
    ///
    /// ```text
    /// C: STAT
    /// S: +OK 2 320
    /// ```
    STAT,
    /// TOP will used to send top lines of messages.
    ///
    /// # Restrictions
    ///
    /// Only be given in the TRANSACTION state
    ///
    /// # Discussion
    ///
    /// If the POP3 server issues a positive response, then the
    /// response given is multi-line.  After the initial +OK, the
    /// POP3 server sends the headers of the message, the blank
    /// line separating the headers from the body, and then the
    /// number of lines of the indicated message's body, being
    /// careful to byte-stuff the termination character (as with
    /// all multi-line responses).
    ///
    /// Note that if the number of lines requested by the POP3
    /// client is greater than than the number of lines in the
    /// body, then the POP3 server sends the entire message
    ///
    /// # Syntax
    ///
    /// ```text
    /// C: TOP <id> <lines>
    /// S: +OK
    /// S: <the POP3 server sends the headers of the
    ///    message, a blank line, and the first <lines>
    ///    of the body of the message>
    /// S: .
    /// ```
    ///
    /// # Examples
    ///
    /// ```text
    /// C: TOP 1 10
    /// S: +OK
    /// S: <the POP3 server sends the headers of the
    ///    message, a blank line, and the first 10 lines
    ///    of the body of the message>
    /// S: .
    /// ```
    ///
    /// ```text
    /// C: TOP 100 3
    /// S: -ERR no such message
    /// ```
    TOP,
    /// UIDL will used to do "unique-id listing".
    ///
    /// # Restrictions
    ///
    /// Only be given in the TRANSACTION state
    ///
    /// # Discussion
    /// If an argument was given and the POP3 server issues a positive
    /// response with a line containing information for that message.
    /// This line is called a "unique-id listing" for that message.
    ///
    /// If no argument was given and the POP3 server issues a positive
    /// response, then the response given is multi-line.  After the
    /// initial +OK, for each message in the maildrop, the POP3 server
    /// responds with a line containing information for that message.
    /// This line is called a "unique-id listing" for that message.
    ///
    /// In order to simplify parsing, all POP3 servers are required to
    /// use a certain format for unique-id listings.  A unique-id
    /// listing consists of the message-number of the message,
    /// followed by a single space and the unique-id of the message.
    /// No information follows the unique-id in the unique-id listing.
    ///
    /// The unique-id of a message is an arbitrary server-determined
    /// string, consisting of one to 70 characters in the range 0x21
    /// to 0x7E, which uniquely identifies a message within a
    /// maildrop and which persists across sessions.  This
    /// persistence is required even if a session ends without
    /// entering the UPDATE state.  The server should never reuse an
    /// unique-id in a given maildrop, for as long as the entity
    /// using the unique-id exists.
    ///
    /// Note that messages marked as deleted are not listed.
    ///
    /// While it is generally preferable for server implementations
    /// to store arbitrarily assigned unique-ids in the maildrop,
    /// this specification is intended to permit unique-ids to be
    /// calculated as a hash of the message.  Clients should be able
    /// to handle a situation where two identical copies of a
    /// message in a maildrop have the same unique-id.
    ///
    /// # Syntax
    ///
    /// ## List all mails with unique id
    ///
    /// ```text
    /// C: UIDL
    /// S: +OK
    /// S: <id> <unique-id>
    /// S: .
    /// ```
    ///
    /// ## List single mail with unique id
    ///
    /// ```text
    /// C: UIDL <id>
    /// S: +OK <id> <unique-id>
    /// ```
    ///
    /// # Examples
    ///
    /// ```text
    /// C: UIDL
    /// S: +OK
    /// S: 1 whqtswO00WBw418f9t5JxYwZ
    /// S: 2 QhdPYR:00WBw1Ph7x7
    /// S: .
    /// ```
    ///
    /// ```text
    /// C: UIDL 2
    /// S: +OK 2 QhdPYR:00WBw1Ph7x7
    /// ```
    ///
    /// ```text
    /// C: UIDL 3
    /// S: -ERR no such message, only 2 messages in maildrop
    /// ```
    UIDL,
    /// USER is used to send user name
    ///
    /// # Restrictions
    ///
    /// Only be given in the AUTHORIZATION state after the POP3 greeting or
    /// after an unsuccessful USER or PASS command
    ///
    /// # Discussion
    ///
    /// To authenticate using the USER and PASS command
    /// combination, the client must first issue the USER
    /// command.  If the POP3 server responds with a positive
    /// status indicator ("+OK"), then the client may issue
    /// either the PASS command to complete the authentication,
    /// or the QUIT command to terminate the POP3 session.  If
    /// the POP3 server responds with a negative status indicator
    /// ("-ERR") to the USER command, then the client may either
    /// issue a new authentication command or may issue the QUIT
    /// command.
    ///
    /// The server may return a positive response even though no
    /// such mailbox exists.  The server may return a negative
    /// response if mailbox exists, but does not permit plaintext
    /// password authentication.
    ///
    /// # Syntax
    ///
    /// ```text
    /// C: USER <username>
    /// S: +OK [msg]
    /// ```
    ///
    /// # Examples
    ///
    /// ```text
    /// C: USER frated
    /// S: -ERR sorry, no mailbox for frated here
    /// ```
    ///
    /// ```text
    /// C: USER mrose
    /// S: +OK mrose is a real hoopy frood
    /// ```
    USER,
}

impl FromStr for Command {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self> {
        Ok(match s {
            "USER" => Command::USER,
            "PASS" => Command::PASS,
            "STAT" => Command::STAT,
            "UIDL" => Command::UIDL,
            "LIST" => Command::LIST,
            "RETR" => Command::RETR,
            "DELE" => Command::DELE,
            "NOOP" => Command::NOOP,
            "RSET" => Command::RSET,
            "QUIT" => Command::QUIT,
            "APOP" => Command::APOP,
            "TOP" => Command::TOP,
            "AUTH" => Command::AUTH,
            "CAPA" => Command::CAPA,
            _ => return Err(anyhow::anyhow!("invalid command: {}", s)),
        })
    }
}

impl Display for Command {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let v = match self {
            Command::USER => "USER",
            Command::PASS => "PASS",
            Command::STAT => "STAT",
            Command::UIDL => "UIDL",
            Command::LIST => "LIST",
            Command::RETR => "RETR",
            Command::DELE => "DELE",
            Command::NOOP => "NOOP",
            Command::RSET => "RSET",
            Command::QUIT => "QUIT",
            Command::APOP => "APOP",
            Command::TOP => "TOP",
            Command::AUTH => "AUTH",
            Command::CAPA => "CAPA",
        };

        write!(f, "{}", v)
    }
}

impl From<&Request> for Command {
    fn from(v: &Request) -> Self {
        match v {
            Request::APOP { .. } => Command::APOP,
            Request::AUTH(_) => Command::AUTH,
            Request::CAPA => Command::CAPA,
            Request::DELE(_) => Command::DELE,
            Request::LIST(_) => Command::LIST,
            Request::NOOP => Command::NOOP,
            Request::PASS(_) => Command::PASS,
            Request::QUIT => Command::QUIT,
            Request::RETR(_) => Command::RETR,
            Request::RSET => Command::RSET,
            Request::STAT => Command::STAT,
            Request::TOP { .. } => Command::TOP,
            Request::UIDL(_) => Command::UIDL,
            Request::USER(_) => Command::USER,
        }
    }
}

impl From<&Response> for Command {
    fn from(v: &Response) -> Self {
        match v {
            Response::AUTH(_) => Command::AUTH,
            Response::CAPA(_) => Command::CAPA,
            Response::DELE => Command::DELE,
            Response::LIST(_) => Command::LIST,
            Response::NOOP => Command::NOOP,
            Response::PASS(_) => Command::PASS,
            Response::QUIT => Command::QUIT,
            Response::RETR(_) => Command::RETR,
            Response::STAT { .. } => Command::STAT,
            Response::RSET => Command::RSET,
            Response::USER(_) => Command::USER,
            // GREET and ERR doesn't have related commend.
            _ => panic!("invalid command for response: {:?}", v),
        }
    }
}

#[derive(Debug)]
pub enum Request {
    APOP { username: String, digest: String },
    AUTH(Option<String>),
    CAPA,
    DELE(usize),
    LIST(Option<usize>),
    NOOP,
    PASS(String),
    QUIT,
    RETR(usize),
    RSET,
    STAT,
    TOP { id: usize, lines: usize },
    UIDL(Option<usize>),
    USER(String),
}

impl Request {
    pub fn to_string(&self) -> Result<String> {
        let mut f = String::new();

        match self {
            Request::CAPA | Request::NOOP | Request::QUIT | Request::RSET | Request::STAT => {
                write!(&mut f, "{}\r\n", Command::from(self))?
            }
            Request::DELE(v) => write!(&mut f, "{} {}\r\n", Command::from(self), v)?,
            Request::PASS(v) => write!(&mut f, "{} {}\r\n", Command::from(self), v)?,
            Request::RETR(v) => write!(&mut f, "{} {}\r\n", Command::from(self), v)?,
            Request::USER(v) => write!(&mut f, "{} {}\r\n", Command::from(self), v)?,
            Request::AUTH(v) => match v {
                None => write!(&mut f, "{}\r\n", Command::from(self))?,
                Some(v) => write!(&mut f, "{} {}\r\n", Command::from(self), v)?,
            },
            Request::LIST(v) => match v {
                None => write!(&mut f, "{}\r\n", Command::from(self))?,
                Some(v) => write!(&mut f, "{} {}\r\n", Command::from(self), v)?,
            },
            Request::UIDL(v) => match v {
                None => write!(&mut f, "{}\r\n", Command::from(self))?,
                Some(v) => write!(&mut f, "{} {}\r\n", Command::from(self), v)?,
            },
            Request::APOP { username, digest } => write!(
                &mut f,
                "{} {} {}\r\n",
                Command::from(self),
                username,
                digest
            )?,
            Request::TOP { id, lines } => {
                write!(&mut f, "{} {} {}\r\n", Command::from(self), id, lines)?
            }
        }

        Ok(f)
    }
}

impl FromStr for Request {
    type Err = anyhow::Error;

    fn from_str(v: &str) -> Result<Self> {
        let v = v.strip_suffix("\r\n").unwrap();

        let vs: Vec<&str> = v.split(' ').filter(|s| !s.is_empty()).collect();
        let cmd = Command::from_str(vs[0])?;

        let req = match cmd {
            Command::USER => {
                if vs.len() != 2 {
                    return Err(anyhow::anyhow!("invalid request for {}: {}", cmd, v));
                }

                Request::USER(vs[1].to_string())
            }
            Command::PASS => {
                if vs.len() != 2 {
                    return Err(anyhow::anyhow!("invalid request for {}: {}", cmd, v));
                }

                Request::PASS(vs[1].to_string())
            }
            Command::STAT => {
                if vs.len() != 1 {
                    return Err(anyhow::anyhow!("invalid request for {}: {}", cmd, v));
                }

                Request::STAT
            }
            Command::UIDL => match vs.len() {
                1 => Request::UIDL(None),
                2 => {
                    let msg = usize::from_str(vs[1])?;

                    Request::UIDL(Some(msg))
                }
                _ => {
                    return Err(anyhow::anyhow!("invalid request for {}: {}", cmd, v));
                }
            },
            Command::LIST => match vs.len() {
                1 => Request::LIST(None),
                2 => {
                    let msg = usize::from_str(vs[1])?;

                    Request::LIST(Some(msg))
                }
                _ => {
                    return Err(anyhow::anyhow!("invalid request for {}: {}", cmd, v));
                }
            },
            Command::RETR => {
                if vs.len() != 2 {
                    return Err(anyhow::anyhow!("invalid request for {}: {}", cmd, v));
                }

                let msg = usize::from_str(vs[1])?;

                Request::RETR(msg)
            }
            Command::DELE => {
                if vs.len() != 2 {
                    return Err(anyhow::anyhow!("invalid request for {}: {}", cmd, v));
                }

                let msg = usize::from_str(vs[1])?;

                Request::DELE(msg)
            }
            Command::NOOP => {
                if vs.len() != 1 {
                    return Err(anyhow::anyhow!("invalid request for {}: {}", cmd, v));
                }

                Request::NOOP
            }
            Command::RSET => {
                if vs.len() != 1 {
                    return Err(anyhow::anyhow!("invalid request for {}: {}", cmd, v));
                }

                Request::RSET
            }
            Command::QUIT => {
                if vs.len() != 1 {
                    return Err(anyhow::anyhow!("invalid request for {}: {}", cmd, v));
                }

                Request::QUIT
            }
            Command::TOP => {
                if vs.len() != 3 {
                    return Err(anyhow::anyhow!("invalid request for {}: {}", cmd, v));
                }

                let id = usize::from_str(vs[1])?;
                let lines = usize::from_str(vs[2])?;

                Request::TOP { id, lines }
            }
            Command::APOP => {
                if vs.len() != 3 {
                    return Err(anyhow::anyhow!("invalid request for {}: {}", cmd, v));
                }

                Request::APOP {
                    username: vs[1].to_string(),
                    digest: vs[2].to_string(),
                }
            }
            Command::AUTH => match vs.len() {
                1 => Request::AUTH(None),
                2 => Request::AUTH(Some(vs[1].to_string())),
                _ => {
                    return Err(anyhow::anyhow!("invalid request for {}: {}", cmd, v));
                }
            },
            Command::CAPA => {
                if vs.len() != 1 {
                    return Err(anyhow::anyhow!("invalid request for {}: {}", cmd, v));
                }

                Request::CAPA
            }
        };

        Ok(req)
    }
}

#[derive(Debug)]
pub enum Response {
    APOP,
    AUTH(AuthResponse),
    CAPA(Vec<String>),
    DELE,
    GREET(String),
    LIST(ListResponse),
    NOOP,
    PASS(String),
    QUIT,
    RETR(String),
    STAT { count: usize, size: usize },
    RSET,
    TOP(String),
    UIDL(UidlResponse),
    USER(String),

    ERR(String),
}

/// The first is message id.
/// The second is message size in bytes.
#[derive(Debug)]
pub enum ListResponse {
    Single(usize, usize),
    All(Vec<(usize, usize)>),
}

/// The first is message id.
/// The second is message unique id.
#[derive(Debug)]
pub enum UidlResponse {
    Single(usize, String),
    All(BTreeMap<usize, String>),
}

#[derive(Debug)]
pub enum AuthResponse {
    All(Vec<String>),
}

impl Response {
    pub fn to_string(&self) -> Result<String> {
        let mut f = String::new();

        match self {
            Response::APOP | Response::DELE | Response::NOOP | Response::QUIT | Response::RSET => {
                write!(&mut f, "+OK\r\n")?
            }
            Response::GREET(v) | Response::PASS(v) | Response::USER(v) => {
                write!(&mut f, "+OK {}\r\n", v)?
            }
            Response::RETR(v) | Response::TOP(v) => {
                write!(&mut f, "+OK\r\n")?;
                write!(&mut f, "{}", v)?;
                write!(&mut f, ".\r\n")?
            }
            Response::AUTH(v) => match v {
                AuthResponse::All(v) => {
                    write!(&mut f, "+OK {} auth methods\r\n", v.len())?;
                    for v in v.iter() {
                        write!(&mut f, "{}\r\n", v)?;
                    }
                    write!(&mut f, ".\r\n")?
                }
            },
            Response::CAPA(v) => {
                write!(&mut f, "+OK Capability list follows\r\n")?;
                for v in v.iter() {
                    write!(&mut f, "{}\r\n", v)?;
                }
                write!(&mut f, ".\r\n")?
            }
            Response::LIST(v) => match v {
                ListResponse::All(messages) => {
                    write!(&mut f, "+OK {} messages\r\n", messages.len())?;
                    for v in messages.iter() {
                        write!(&mut f, "{} {}\r\n", v.0, v.1)?;
                    }
                    write!(&mut f, ".\r\n")?
                }
                ListResponse::Single(id, size) => write!(&mut f, "+OK {} {}\r\n", id, size * 8)?,
            },
            Response::STAT { count, size } => write!(&mut f, "+OK {} {}\r\n", count, size)?,
            Response::UIDL(v) => match v {
                UidlResponse::Single(id, uid) => {
                    write!(&mut f, "+OK {} {}\r\n", id, uid)?;
                }
                UidlResponse::All(v) => {
                    write!(&mut f, "+OK {} mails\r\n", v.len())?;
                    for (id, uid) in v.iter() {
                        write!(&mut f, "{} {}\r\n", id, uid)?;
                    }
                    write!(&mut f, ".\r\n")?
                }
            },

            Response::ERR(v) => write!(&mut f, "-ERR {}\r\n", v)?,
        }

        Ok(f)
    }

    pub fn from_str(content: &str, req: &Request) -> Result<Response> {
        if !content.starts_with("-ERR") || !content.starts_with("+OK") {
            return Err(anyhow::anyhow!(
                "invalid response for {:?}: {}",
                req,
                content
            ));
        }

        if content.starts_with("-ERR") {
            let v = content.strip_prefix("-ERR ").unwrap();
            let v = v.strip_suffix("\r\n").unwrap();

            return Ok(Response::ERR(v.to_string()));
        }

        let vs: Vec<&str> = content.split("\r\n").filter(|s| !s.is_empty()).collect();

        let cmd = Command::from(req);
        let resp = match cmd {
            Command::USER => {
                if vs.len() != 1 {
                    return Err(anyhow::anyhow!("invalid response for {}: {}", cmd, content));
                }

                Response::USER(vs[0].strip_prefix("+OK ").unwrap().to_string())
            }
            Command::PASS => {
                if vs.len() != 1 {
                    return Err(anyhow::anyhow!("invalid response for {}: {}", cmd, content));
                }

                Response::PASS(vs[0].strip_prefix("+OK ").unwrap().to_string())
            }
            Command::STAT => {
                if vs.len() != 1 {
                    return Err(anyhow::anyhow!("invalid response for {}: {}", cmd, content));
                }

                let vs: Vec<&str> = vs[0].split(' ').collect();

                if vs.len() != 3 {
                    return Err(anyhow::anyhow!("invalid response for {}: {}", cmd, content));
                }

                Response::STAT {
                    count: usize::from_str(vs[1])?,
                    size: usize::from_str(vs[2])?,
                }
            }
            Command::UIDL => match req {
                Request::UIDL(v) => match v {
                    None => {
                        if vs.len() < 2 {
                            return Err(anyhow::anyhow!(
                                "invalid response for {}: {}",
                                cmd,
                                content
                            ));
                        }

                        let mut m = BTreeMap::new();
                        for v in vs[1..vs.len() - 1].iter() {
                            let ids: Vec<&str> = v.splitn(2, ' ').collect();
                            if ids.len() != 2 {
                                return Err(anyhow::anyhow!("invalid response for {}: {}", cmd, v));
                            }

                            m.insert(usize::from_str(ids[0])?, ids[1].to_string());
                        }

                        Response::UIDL(UidlResponse::All(m))
                    }
                    Some(_) => {
                        if vs.len() != 1 {
                            return Err(anyhow::anyhow!(
                                "invalid response for {}: {}",
                                cmd,
                                content
                            ));
                        }

                        let vs: Vec<&str> = vs[0].split(' ').collect();

                        if vs.len() != 3 {
                            return Err(anyhow::anyhow!(
                                "invalid response for {}: {}",
                                cmd,
                                content
                            ));
                        }

                        Response::UIDL(UidlResponse::Single(
                            usize::from_str(vs[1])?,
                            String::from(vs[2]),
                        ))
                    }
                },
                _ => {
                    return Err(anyhow::anyhow!("invalid response for {}: {}", cmd, content));
                }
            },
            Command::LIST => match req {
                Request::LIST(v) => match v {
                    None => {
                        if vs.len() < 2 {
                            return Err(anyhow::anyhow!(
                                "invalid response for {}: {}",
                                cmd,
                                content
                            ));
                        }
                        let mut messages = Vec::new();

                        for v in vs[1..vs.len() - 1].iter() {
                            let ids: Vec<&str> = v.splitn(2, ' ').collect();
                            if ids.len() != 2 {
                                return Err(anyhow::anyhow!("invalid response for {}: {}", cmd, v));
                            }

                            messages.push((usize::from_str(ids[0])?, usize::from_str(ids[1])? / 8));
                        }

                        Response::LIST(ListResponse::All(messages))
                    }
                    Some(_) => {
                        if vs.len() != 3 {
                            return Err(anyhow::anyhow!(
                                "invalid response for {}: {}",
                                cmd,
                                content
                            ));
                        }

                        Response::LIST(ListResponse::Single(
                            usize::from_str(vs[1])?,
                            usize::from_str(vs[2])? / 8,
                        ))
                    }
                },
                _ => {
                    return Err(anyhow::anyhow!("invalid response for {}: {}", cmd, content));
                }
            },
            Command::RETR => {
                if vs.len() < 2 {
                    return Err(anyhow::anyhow!("invalid response for {}: {}", cmd, content));
                }

                Response::RETR(vs[1..vs.len() - 1].join(""))
            }
            Command::DELE => {
                if vs.len() != 1 {
                    return Err(anyhow::anyhow!("invalid response for {}: {}", cmd, content));
                }

                Response::DELE
            }
            Command::NOOP => {
                if vs.len() != 1 {
                    return Err(anyhow::anyhow!("invalid response for {}: {}", cmd, content));
                }

                Response::NOOP
            }
            Command::RSET => {
                if vs.len() != 1 {
                    return Err(anyhow::anyhow!("invalid response for {}: {}", cmd, content));
                }

                Response::RSET
            }
            Command::QUIT => {
                if vs.len() != 1 {
                    return Err(anyhow::anyhow!("invalid response for {}: {}", cmd, content));
                }

                Response::QUIT
            }
            Command::TOP => {
                if vs.len() < 2 {
                    return Err(anyhow::anyhow!("invalid response for {}: {}", cmd, content));
                }

                Response::TOP(vs[1..vs.len() - 1].join(""))
            }
            Command::APOP => {
                if vs.len() != 1 {
                    return Err(anyhow::anyhow!("invalid response for {}: {}", cmd, content));
                }

                Response::APOP
            }
            Command::AUTH => {
                if vs.len() != 1 {
                    return Err(anyhow::anyhow!("invalid response for {}: {}", cmd, content));
                }

                unimplemented!()
            }
            Command::CAPA => {
                if vs.len() < 2 {
                    return Err(anyhow::anyhow!("invalid response for {}: {}", cmd, content));
                }

                let mut caps = Vec::new();

                for v in vs[1..vs.len() - 1].iter() {
                    caps.push(v.to_string())
                }

                Response::CAPA(caps)
            }
        };

        Ok(resp)
    }
}

#[derive(Debug, Copy, Clone)]
pub enum State {
    AUTHORIZATION,
    TRANSACTION,
    /// When the client issues the QUIT command from the TRANSACTION state,
    /// the POP3 session enters the UPDATE state.  (Note that if the client
    /// issues the QUIT command from the AUTHORIZATION state, the POP3
    /// session terminates but does NOT enter the UPDATE state.)
    ///
    /// If a session terminates for some reason other than a client-issued
    /// QUIT command, the POP3 session does NOT enter the UPDATE state and
    /// MUST not remove any messages from the maildrop.
    UPDATE,
}

/// MessageMeta stores related message metadata.
///
/// `status` is the message's current committed status
/// `next_status` is the message's not committed status
///
/// - `next_status` is None means the message's status is up to date.
/// - `next_status` is Some means the message's status has been updated, `status` could
///   be replace be `next_status` is user send `QUIT` or dropped if user close the
///   connection or send `REST`
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MessageMeta {
    pub id: usize,
    pub uid: String,
    pub size: usize,
    pub path: String,
    pub status: MessageStatus,
    next_status: Option<MessageStatus>,
}

impl MessageMeta {
    pub fn is_fetched(&self) -> bool {
        match self.next_status {
            None => self.status.fetched,
            Some(v) => v.fetched,
        }
    }
    pub fn is_deleted(&self) -> bool {
        match self.next_status {
            None => self.status.deleted,
            Some(v) => v.deleted,
        }
    }

    pub fn set_fetched(&mut self) {
        self.next_status.unwrap_or_default().fetched = true
    }
    pub fn set_deleted(&mut self) {
        self.next_status.unwrap_or_default().deleted = true
    }
}

impl From<sled::IVec> for MessageMeta {
    fn from(v: IVec) -> Self {
        bincode::deserialize(v.as_ref()).expect("deserialize MessageMeta failed")
    }
}

impl Into<sled::IVec> for MessageMeta {
    fn into(self) -> IVec {
        IVec::from(bincode::serialize(&self).expect("serialize MessageMeta failed"))
    }
}

#[derive(Debug, Copy, Clone, Default, Serialize, Deserialize)]
pub struct MessageStatus {
    // Whether or not this message has been fetched by client.
    pub fetched: bool,
    // Whether or not his message has been deleted by client.
    pub deleted: bool,
}