summaryrefslogtreecommitdiffstats
path: root/src/plugins/messageservices/imap/imapprotocol.cpp
blob: 630b16edee3dc8568cf0e82a2529ca8c8ff05a4d (plain)
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
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the Qt Messaging Framework.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "imapprotocol.h"

#include "imapauthenticator.h"
#include "imapconfiguration.h"
#include "imapstructure.h"
#include "integerregion.h"
#include "imaptransport.h"

#include <QTemporaryFile>
#include <QFileInfo>
#include <QUrl>
#include <qmaillog.h>
#include <private/longstring_p.h>
#include <qmailaccountconfiguration.h>
#include <qmailmessage.h>
#include <qmailmessageserver.h>
#include <qmailnamespace.h>
#include <qmailtransport.h>
#include <qmaildisconnected.h>
#include <qmailcodec.h>

#ifndef QT_NO_SSL
#include <QSslError>
#endif

// Pack both the source mailbox path and the numeric UID into the UID value
// that we store for IMAP messages.  This will allow us find the owner 
// mailbox, even if the UID is present in multiple nested mailboxes.

static QString messageId(const QString& uid)
{
    int index = 0;
    if ((index = uid.lastIndexOf(UID_SEPARATOR)) != -1)
        return uid.mid(index + 1);
    else
        return uid;
}

static QString messageUid(const QMailFolderId &folderId, const QString &id)
{
    return QString::number(folderId.toULongLong()) + UID_SEPARATOR + id;
}

static QString extractUid(const QString &field, const QMailFolderId &folderId)
{
    QRegExp uidFormat("UID *(\\d+)");
    uidFormat.setCaseSensitivity(Qt::CaseInsensitive);
    if (uidFormat.indexIn(field) != -1) {
        return messageUid(folderId, uidFormat.cap(1));
    }

    return QString();
}

static QDateTime extractDate(const QString& field)
{
    QRegExp dateFormat("INTERNALDATE *\"([^\"]*)\"");
    dateFormat.setCaseSensitivity(Qt::CaseInsensitive);
    if (dateFormat.indexIn(field) != -1) {
        QString date(dateFormat.cap(1));

        QRegExp format("(\\d+)-(\\w{3})-(\\d{4}) (\\d{2}):(\\d{2}):(\\d{2}) ([+-])(\\d{2})(\\d{2})");
        if (format.indexIn(date) != -1) {
            static const QString Months("janfebmaraprmayjunjulaugsepoctnovdec");
            int month = (Months.indexOf(format.cap(2).toLower()) + 3) / 3;

            QDate dateComponent(format.cap(3).toInt(), month, format.cap(1).toInt());
            QTime timeComponent(format.cap(4).toInt(), format.cap(5).toInt(), format.cap(6).toInt());
            int offset = (format.cap(8).toInt() * 3600) + (format.cap(9).toInt() * 60);

            QDateTime timeStamp(dateComponent, timeComponent, Qt::UTC);
            timeStamp = timeStamp.addSecs(offset * (format.cap(7)[0] == '-' ? 1 : -1));
            return timeStamp;
        }
    }

    return QDateTime();
}

static uint extractSize(const QString& field)
{
    QRegExp sizeFormat("RFC822\\.SIZE *(\\d+)");
    sizeFormat.setCaseSensitivity(Qt::CaseInsensitive);
    if (sizeFormat.indexIn(field) != -1) {
        return sizeFormat.cap(1).toUInt();
    }

    return 0;
}

static QStringList extractStructure(const QString& field)
{
    return getMessageStructure(field);
}

static bool parseFlags(const QString& field, MessageFlags& flags)
{
    QRegExp pattern("FLAGS *\\((.*)\\)");
    pattern.setMinimal(true);
    pattern.setCaseSensitivity(Qt::CaseInsensitive);

    if (pattern.indexIn(field) == -1)
        return false;

    QString messageFlags = pattern.cap(1).toLower();

    flags = 0;
    if (messageFlags.indexOf("\\seen") != -1)
        flags |= MFlag_Seen;
    if (messageFlags.indexOf("\\answered") != -1)
        flags |= MFlag_Answered;
    if (messageFlags.indexOf("\\flagged") != -1)
        flags |= MFlag_Flagged;
    if (messageFlags.indexOf("\\deleted") != -1)
        flags |= MFlag_Deleted;
    if (messageFlags.indexOf("\\draft") != -1)
        flags |= MFlag_Draft;
    if (messageFlags.indexOf("\\recent") != -1)
        flags |= MFlag_Recent;
    if (messageFlags.indexOf("$forwarded") != -1)
        flags |= MFlag_Forwarded;

    return true;
}

static int indexOfWithEscape(const QString &str, QChar c, int from, const QString &ignoreEscape)
{
    int index = from;
    int pos = str.indexOf(c, index, Qt::CaseInsensitive);
    if (ignoreEscape.isEmpty()) {
        return pos;
    }
    const int ignoreLength = ignoreEscape.length();
    while (pos + 1 >= ignoreLength) {
        if (str.mid(pos - ignoreLength + 1, ignoreLength) == ignoreEscape) {
            index = pos + 1;
            pos = str.indexOf(c, index, Qt::CaseInsensitive);
            continue;
        } else {
            break;
        }
    }

    return pos;
}

static QString token( QString str, QChar c1, QChar c2, int *index, const QString &ignoreEscape = QString())
{
    int start, stop;

    // The strings we're tokenizing use CRLF as the line delimiters - assume that the
    // caller considers the sequence to be atomic.
    if (c1 == QMailMessage::CarriageReturn)
        c1 = QMailMessage::LineFeed;
    start = indexOfWithEscape(str, c1, *index, ignoreEscape);
    if (start == -1)
        return QString();

    if (c2 == QMailMessage::CarriageReturn)
        c2 = QMailMessage::LineFeed;
    stop = indexOfWithEscape(str, c2, ++start, ignoreEscape);
    if (stop == -1)
        return QString();

    // Exclude the CR if necessary
    if (stop && (str[stop-1] == QMailMessage::CarriageReturn))
        --stop;

    // Bypass the LF if necessary
    *index = stop + 1;

    return str.mid( start, stop - start );
}

static QList<uint> sequenceUids(const QString &sequence)
{
    QList<uint> uids;

    foreach (const QString &uid, sequence.split(",")) {
        int index = uid.indexOf(":");
        if (index != -1) {
            uint first = uid.left(index).toUInt();
            uint last = uid.mid(index + 1).toUInt();
            for ( ; first <= last; ++first)
                uids.append(first);
        } else {
            uids.append(uid.toUInt());
        }
    }

    return uids;
}

static QString searchFlagsToString(MessageFlags flags)
{
    QStringList result;

    if (flags != 0) {
        if (flags & MFlag_Recent)
            result.append("RECENT");
        if (flags & MFlag_Deleted)
            result.append("DELETED");
        if (flags & MFlag_Answered)
            result.append("ANSWERED");
        if (flags & MFlag_Flagged)
            result.append("FLAGGED");
        if (flags & MFlag_Seen)
            result.append("SEEN");
        if (flags & MFlag_Unseen)
            result.append("UNSEEN");
        if (flags & MFlag_Draft)
            result.append("DRAFT");
        if (flags & MFlag_Forwarded)
            result.append("$FORWARDED");
    }

    return result.join(QString(' '));
}

static QString messageFlagsToString(MessageFlags flags)
{
    QStringList result;

    // Note that \Recent flag is ignored as only the server is allowed to modify that flag 
    if (flags != 0) {
        if (flags & MFlag_Deleted)
            result.append("\\Deleted");
        if (flags & MFlag_Answered)
            result.append("\\Answered");
        if (flags & MFlag_Flagged)
            result.append("\\Flagged");
        if (flags & MFlag_Seen)
            result.append("\\Seen");
        if (flags & MFlag_Draft)
            result.append("\\Draft");
        if (flags & MFlag_Forwarded)
            result.append("$Forwarded");
    }

    return result.join(QString(' '));
}

static MessageFlags flagsForMessage(const QMailMessageMetaData &metaData)
{
    MessageFlags result(0);

    if (metaData.status() & (QMailMessage::Read | QMailMessage::ReadElsewhere | QMailMessage::Outgoing)) {
        result |= MFlag_Seen;
    }
    if (metaData.status() & QMailMessage::Important) {
        result |= MFlag_Flagged;
    }
    if (metaData.status() & (QMailMessage::Replied | QMailMessage::RepliedAll)) {
        result |= MFlag_Answered;
    }
    if (metaData.status() & QMailMessage::Forwarded) {
        result |= MFlag_Forwarded;
    }
    if (metaData.status() & QMailMessage::Draft) {
        result |= MFlag_Draft;
    }

    return result;
}


/* Begin state design pattern related classes */

class ImapState;

class ImapContext
{
public:
    ImapContext(ImapProtocol *protocol) { mProtocol = protocol; }
    virtual ~ImapContext() {}

    void continuation(ImapCommand c, const QString &s) { mProtocol->continuation(c, s); }
    void operationCompleted(ImapCommand c, OperationStatus s) { mProtocol->operationCompleted(c, s); }

    virtual QString sendCommand(const QString &cmd) { return mProtocol->sendCommand(cmd); }
    virtual QString sendCommandLiteral(const QString &cmd, uint length) { return mProtocol->sendCommandLiteral(cmd, length); }
    virtual void sendData(const QString &data, bool maskDebug = false) { mProtocol->sendData(data, maskDebug); }
    virtual void sendDataLiteral(const QString &data, uint length) { mProtocol->sendDataLiteral(data, length); }

    ImapProtocol *protocol() { return mProtocol; }
    const ImapMailboxProperties &mailbox() { return mProtocol->mailbox(); }

    LongStream &buffer() { return mProtocol->_stream; }
#ifndef QT_NO_SSL
    void switchToEncrypted() { mProtocol->_transport->switchToEncrypted(); mProtocol->clearResponse(); }
#endif
    bool literalResponseCompleted() { return (mProtocol->literalDataRemaining() == 0); }

    // Update the protocol's mailbox properties
    void setMailbox(const QMailFolder &mailbox) { mProtocol->_mailbox = ImapMailboxProperties(mailbox); }
    void setExists(quint32 n) { mProtocol->_mailbox.exists = n; emit mProtocol->exists(n); }
    quint32 exists() { return mProtocol->_mailbox.exists; }
    void setRecent(quint32 n) { mProtocol->_mailbox.recent = n; emit mProtocol->recent(n); }
    void setUnseen(quint32 n) { mProtocol->_mailbox.unseen = n; }
    void setUidValidity(const QString &validity) { mProtocol->_mailbox.uidValidity = validity; emit mProtocol->uidValidity(validity); }
    void setUidNext(quint32 n) { mProtocol->_mailbox.uidNext = n; }
    void setFlags(const QString &flags) { mProtocol->_mailbox.flags = flags; emit mProtocol->flags(flags); }
    void setUidList(const QStringList &uidList) { mProtocol->_mailbox.uidList = uidList; }
    void setSearchCount(uint count) { mProtocol->_mailbox.searchCount = count; }
    void setMsnList(const QList<uint> &msnList) { mProtocol->_mailbox.msnList = msnList; }
    void setHighestModSeq(const QString &seq) { mProtocol->_mailbox.highestModSeq = seq; mProtocol->_mailbox.noModSeq = false; emit mProtocol->highestModSeq(seq); }
    void setNoModSeq() { mProtocol->_mailbox.noModSeq = true; emit mProtocol->noModSeq(); }
    void setPermanentFlags(const QStringList &flags) { mProtocol->_mailbox.permanentFlags = flags; }
    void setVanished(const QString &vanished) { mProtocol->_mailbox.vanished = vanished; }
    void setChanges(const QList<FlagChange> &changes) { mProtocol->_mailbox.flagChanges = changes; }

    void createMail(const QString& uid, const QDateTime &timeStamp, int size, uint flags, const QString &file, const QStringList& structure) { mProtocol->createMail(uid, timeStamp, size, flags, file, structure); }
    void createPart(const QString& uid, const QString &section, const QString &file, int size) { mProtocol->createPart(uid, section, file, size); }
    void createPartHeader(const QString& uid, const QString &section, const QString &file, int size) { mProtocol->createPartHeader(uid, section, file, size); }

private:
    ImapProtocol *mProtocol;
};


class ImapState : public QObject
{
    Q_OBJECT
    
public:
    ImapState(ImapCommand c, const QString &name)
        : mCommand(c), mName(name), mStatus(OpPending) {}

    virtual ~ImapState() {}

    virtual void init() { mStatus = OpPending; mTag.clear(); }

    virtual QString transmit(ImapContext *) { return QString(); }
    virtual void enter(ImapContext *) {}
    virtual void leave(ImapContext *) { init(); }
    
    virtual bool permitsPipelining() const { return false; }

    virtual bool continuationResponse(ImapContext *c, const QString &line);
    virtual void untaggedResponse(ImapContext *c, const QString &line);
    virtual void taggedResponse(ImapContext *c, const QString &line);
    virtual void literalResponse(ImapContext *c, const QString &line);
    virtual bool appendLiteralData(ImapContext *c, const QString &preceding);

    virtual QString error(const QString &line);
    void log(const QString &note);

    virtual QString tag() { return mTag; }
    virtual void setTag(const QString &tag) { mTag = tag; }

    ImapCommand command() const { return mCommand; }
    void setCommand(ImapCommand c) { mCommand = c; }

    OperationStatus status() const { return mStatus; }
    void setStatus(OperationStatus s) { mStatus = s; }

private:
    ImapCommand mCommand;
    QString mName;
    OperationStatus mStatus;
    QString mTag;
};

bool ImapState::continuationResponse(ImapContext *, const QString &line)
{
    qWarning() << "Unexpected continuation response!" << line;
    return false;
}

void ImapState::untaggedResponse(ImapContext *c, const QString &line)
{
    int index = line.indexOf("[ALERT]", Qt::CaseInsensitive);
    if (index != -1) {
        qWarning() << line.mid(index).toLatin1();
    } else if (line.indexOf("[CAPABILITY", 0) != -1) {
        int start = 0;
        QString temp = token(line, '[', ']', &start);
        QStringList capabilities = temp.mid(12).trimmed().split(' ', QString::SkipEmptyParts);
        c->protocol()->setCapabilities(capabilities);
    } else if (line.indexOf("* CAPABILITY ", 0) != -1) {
        QStringList capabilities = line.mid(13).trimmed().split(' ', QString::SkipEmptyParts);
        c->protocol()->setCapabilities(capabilities);
    }

    c->buffer().append(line);
}

void ImapState::taggedResponse(ImapContext *c, const QString &line)
{
    int index = line.indexOf("[ALERT]", Qt::CaseInsensitive);
    if (index != -1)
        qWarning() << line.mid(index).toLatin1();

    c->operationCompleted(mCommand, mStatus);
}

void ImapState::literalResponse(ImapContext *, const QString &)
{
}

bool ImapState::appendLiteralData(ImapContext *, const QString &)
{
    return true;
}

QString ImapState::error(const QString &line) 
{ 
    return line;
}

void ImapState::log(const QString &note)
{
    QString result;
    switch (mStatus) {
    case OpPending: 
        result = "OpPending";
        break;
    case OpFailed: 
        result = "OpFailed";
        break;
    case OpOk: 
        result = "OpOk";
        break;
    case OpNo: 
        result = "OpNo";
        break;
    case OpBad: 
        result = "OpBad";
        break;
    }
    qMailLog(MessagingState) << note << mName << result;
}


// IMAP concrete states

class UnconnectedState : public ImapState
{
    Q_OBJECT

public:
    UnconnectedState() : ImapState(IMAP_Unconnected, "Unconnected") { setStatus(OpOk); }
    virtual void init() { ImapState::init(); setStatus(OpOk); }
};


class InitState : public ImapState
{
    Q_OBJECT

public:
    InitState() : ImapState(IMAP_Init, "Init") {}

    virtual void untaggedResponse(ImapContext *c, const QString &line);
};

void InitState::untaggedResponse(ImapContext *c, const QString &line)
{
    ImapState::untaggedResponse(c, line);

    // We're only waiting for an untagged response here
    setStatus(OpOk);
    c->operationCompleted(command(), status());
}


class CapabilityState : public ImapState
{
    Q_OBJECT

public:
    CapabilityState() : ImapState(IMAP_Capability, "Capability") {}

    virtual QString transmit(ImapContext *c);
    virtual void untaggedResponse(ImapContext *c, const QString &line);
};

QString CapabilityState::transmit(ImapContext *c)
{
    return c->sendCommand("CAPABILITY");
}

void CapabilityState::untaggedResponse(ImapContext *c, const QString &line)
{
    QStringList capabilities;
    if (line.startsWith(QLatin1String("* CAPABILITY"))) {
        capabilities = line.mid(12).trimmed().split(' ', QString::SkipEmptyParts);
        c->protocol()->setCapabilities(capabilities);
    } else {
        ImapState::untaggedResponse(c, line);
    }
}


class StartTlsState : public ImapState
{
    Q_OBJECT

public:
    StartTlsState() : ImapState(IMAP_StartTLS, "StartTLS") {}

    virtual QString transmit(ImapContext *c);
    virtual void taggedResponse(ImapContext *c, const QString &line);
};

QString StartTlsState::transmit(ImapContext *c)
{
    return c->sendCommand("STARTTLS");
}

void StartTlsState::taggedResponse(ImapContext *c, const QString &)
{
#ifndef QT_NO_SSL
    // Switch to encrypted comms mode
    c->switchToEncrypted();
#else
    Q_UNUSED(c)
#endif
}


class LoginState : public ImapState
{
    Q_OBJECT

public:
    LoginState() : ImapState(IMAP_Login, "Login") { LoginState::init(); }

    void setConfiguration(const QMailAccountConfiguration &config, const QStringList &capabilities);

    virtual void init();
    virtual QString transmit(ImapContext *c);
    virtual bool continuationResponse(ImapContext *c, const QString &line);
    virtual void taggedResponse(ImapContext *c, const QString &line);

private:
    QMailAccountConfiguration _config;
    QStringList _capabilities;
};

void LoginState::setConfiguration(const QMailAccountConfiguration &config, const QStringList &capabilities)
{
    _config = config;
    _capabilities = capabilities;
}

void LoginState::init()
{
    ImapState::init();
    _config = QMailAccountConfiguration();
    _capabilities = QStringList();
}

QString LoginState::transmit(ImapContext *c)
{
    return c->sendCommand(ImapAuthenticator::getAuthentication(_config.serviceConfiguration("imap4"), _capabilities));
}

bool LoginState::continuationResponse(ImapContext *c, const QString &received)
{
    // The server input is Base64 encoded
    QByteArray challenge = QByteArray::fromBase64(received.toLatin1());
    QByteArray response(ImapAuthenticator::getResponse(_config.serviceConfiguration("imap4"), challenge));

    if (!response.isEmpty()) {
        c->sendData(response.toBase64(), true);
    }

    return false;
}

void LoginState::taggedResponse(ImapContext *c, const QString &line)
{
    if (line.indexOf("[CAPABILITY", Qt::CaseInsensitive) != -1) {
        int start = 0;
        QString temp = token(line, '[', ']', &start);
        QStringList capabilities = temp.mid(12).trimmed().split(' ', QString::SkipEmptyParts);
        c->protocol()->setCapabilities(capabilities);
    }

    c->protocol()->setAuthenticated(true);
    ImapState::taggedResponse(c, line);
}


class LogoutState : public ImapState
{
    Q_OBJECT

public:
    LogoutState() : ImapState(IMAP_Logout, "Logout") {}

    virtual QString transmit(ImapContext *c);
    virtual void taggedResponse(ImapContext *c, const QString &line);
};

QString LogoutState::transmit(ImapContext *c)
{
    return c->sendCommand("LOGOUT");
}

void LogoutState::taggedResponse(ImapContext *c, const QString &line)
{
    if (status() == OpOk) {
        c->protocol()->setAuthenticated(false);
        c->protocol()->close();
        c->operationCompleted(command(), OpOk);
    } else {
        ImapState::taggedResponse(c, line);
    }
}

class CreateState : public ImapState
{
    Q_OBJECT

public:
    CreateState() : ImapState(IMAP_Create, "Create") {}

    void setMailbox(const QMailFolderId &parentFolderId, const QString &name);

    virtual bool permitsPipelining() const { return true; }
    virtual void init();
    virtual QString transmit(ImapContext *c);
    virtual void leave(ImapContext *c);
    virtual void taggedResponse(ImapContext *c, const QString &line);
    virtual QString error(const QString &line);
signals:
    void folderCreated(const QString &name, bool success);

private:
    QString makePath(ImapContext *c, const QMailFolderId &parent, const QString &name);
    QList<QPair<QMailFolderId, QString> > _mailboxes;
};

void CreateState::setMailbox(const QMailFolderId &parentFolderId, const QString &name)
{
    _mailboxes.append(qMakePair(parentFolderId, name));
}

void CreateState::init()
{
    _mailboxes.clear();
    ImapState::init();
}

QString CreateState::transmit(ImapContext *c)
{  
    const QMailFolderId &parent = _mailboxes.last().first;
    const QString &name = _mailboxes.last().second;

    if(parent.isValid() && c->protocol()->delimiterUnknown()) {
        // We are waiting on delim to create
        return QString();
    }

    if (name.contains(c->protocol()->delimiter())) {
        qWarning() << "Unsupported: folder name contains IMAP delimiter" << name << c->protocol()->delimiter();
        emit folderCreated(makePath(c, parent, name), false);
        c->operationCompleted(command(), OpFailed);
        return QString();
    }

    QString path = makePath(c, parent, name);

    QString cmd("CREATE " + ImapProtocol::quoteString(path));
    return c->sendCommand(cmd);
}

void CreateState::leave(ImapContext *)
{
    ImapState::init();
    _mailboxes.removeFirst();
}

void CreateState::taggedResponse(ImapContext *c, const QString &line)
{
    emit folderCreated(makePath(c, _mailboxes.first().first, _mailboxes.first().second), status() == OpOk);
    ImapState::taggedResponse(c, line);
}

QString CreateState::error(const QString &line)
{
    qWarning() << "CreateState::error:" << line;
    emit folderCreated(_mailboxes.first().second, false);
    return ImapState::error(line);
}

QString CreateState::makePath(ImapContext *c, const QMailFolderId &parent, const QString &name)
{
    QString path;

    if(parent.isValid()) {
        if(!c->protocol()->delimiterUnknown())
            path = QMailFolder(parent).path() + c->protocol()->delimiter();
        else
            qWarning() << "Cannot create a child folder, without a delimiter";

    }
    return (path + QMailCodec::encodeModifiedUtf7(name));
}

class DeleteState : public ImapState
{
    Q_OBJECT

public:
    DeleteState() : ImapState(IMAP_Delete, "Delete") {}

    void setMailbox(QMailFolder mailbox);

    virtual bool permitsPipelining() const { return true; }
    virtual void init();
    virtual QString transmit(ImapContext *c);
    virtual void leave(ImapContext *c);
    virtual void taggedResponse(ImapContext *c, const QString &line);
    virtual QString error(const QString &line);
signals:
    void folderDeleted(const QMailFolder &name, bool success);

private:
    QList<QMailFolder> _mailboxList;
};

void DeleteState::setMailbox(QMailFolder mailbox)
{
    _mailboxList.append(mailbox);
}

void DeleteState::init()
{
    _mailboxList.clear();
    ImapState::init();
}

QString DeleteState::transmit(ImapContext *c)
{
    QString cmd("DELETE " + ImapProtocol::quoteString(_mailboxList.last().path()));
    return c->sendCommand(cmd);
}

void DeleteState::leave(ImapContext *)
{
    ImapState::init();
    _mailboxList.removeFirst();
}

void DeleteState::taggedResponse(ImapContext *c, const QString &line)
{
    emit folderDeleted(_mailboxList.first(), status() == OpOk);
    ImapState::taggedResponse(c, line);
}

QString DeleteState::error(const QString &line)
{
    qWarning() << "DeleteState::error:" << line;
    emit folderDeleted(_mailboxList.first(), false);
    return ImapState::error(line);
}

class RenameState : public ImapState
{
    Q_OBJECT

public:
    RenameState() : ImapState(IMAP_Rename, "Rename") {}

    void setNewMailboxName(const QMailFolder &mailbox, const QString &name);

    virtual bool permitsPipelining() const { return true; }
    virtual void init();
    virtual QString transmit(ImapContext *c);
    virtual void leave(ImapContext *c);
    virtual void taggedResponse(ImapContext *c, const QString &line);
    virtual QString error(const QString &line);
signals:
    void folderRenamed(const QMailFolder &folder, const QString &newPath, bool success);

private:
    QString buildNewPath(ImapContext *c , const QMailFolder &folder, QString &newName);
    QList<QPair<QMailFolder, QString> > _mailboxNames;
};

void RenameState::setNewMailboxName(const QMailFolder &mailbox, const QString &newName)
{
    _mailboxNames.append(qMakePair(mailbox, newName));
}

void RenameState::init()
{
    _mailboxNames.clear();
    ImapState::init();
}

QString RenameState::transmit(ImapContext *c)
{
    if(c->protocol()->delimiterUnknown()) {
        // We are waiting on delim to create
        return QString();
    }

    QString from = _mailboxNames.last().first.path();
    QString to =  buildNewPath(c, _mailboxNames.last().first, _mailboxNames.last().second);
    if (_mailboxNames.last().second.contains(c->protocol()->delimiter())) {
        qWarning() << "Unsupported: new name contains IMAP delimiter" << _mailboxNames.last().second
                   << c->protocol()->delimiter();
        emit folderRenamed(from, to, false);
        c->operationCompleted(command(), OpFailed);
        return QString();
    }

    QString cmd(QString("RENAME %1 %2").arg(ImapProtocol::quoteString(from)).arg( ImapProtocol::quoteString(to)));
    return c->sendCommand(cmd);
}

void RenameState::leave(ImapContext *)
{
    ImapState::init();
    _mailboxNames.removeFirst();
}

void RenameState::taggedResponse(ImapContext *c, const QString &line)
{
    QString path = buildNewPath(c, _mailboxNames.first().first, _mailboxNames.first().second);
    emit folderRenamed(_mailboxNames.first().first, path, status() == OpOk);
    ImapState::taggedResponse(c, line);
}

QString RenameState::error(const QString &line)
{
    qWarning() << "RenameState::error:" << line;
    emit folderRenamed(_mailboxNames.first().first, _mailboxNames.first().second, false);
    return ImapState::error(line);
}

QString RenameState::buildNewPath(ImapContext *c , const QMailFolder &folder, QString &newName)
{
    QString path;
    QString encodedNewName = QMailCodec::encodeModifiedUtf7(newName);
    if(c->protocol()->flatHierarchy() || folder.path().count(c->protocol()->delimiter()) == 0)
        path = encodedNewName;
    else
        path = folder.path().section(c->protocol()->delimiter(), 0, -2) + c->protocol()->delimiter() + encodedNewName;
    return path;
}

class MoveState : public ImapState
{
    Q_OBJECT

public:
    MoveState() : ImapState(IMAP_Move, "Move") {}

    void setNewMailboxParent(const QMailFolder &mailbox, const QMailFolderId &newParentId);

    virtual bool permitsPipelining() const { return true; }
    virtual void init();
    virtual QString transmit(ImapContext *c);
    virtual void leave(ImapContext *c);
    virtual void taggedResponse(ImapContext *c, const QString &line);
    virtual QString error(const QString &line);
signals:
    void folderMoved(const QMailFolder &folder, const QString &newPath,
                     const QMailFolderId &newParentId, bool success);

private:
    QString buildNewPath(ImapContext *c, const QMailFolder &folder, const QMailFolderId &newParentId);
    QList<QPair<QMailFolder, QMailFolderId> > _mailboxParents;
};

void MoveState::setNewMailboxParent(const QMailFolder &mailbox, const QMailFolderId &newParentId)
{
    _mailboxParents.append(qMakePair(mailbox, newParentId));
}

void MoveState::init()
{
    _mailboxParents.clear();
    ImapState::init();
}

QString MoveState::transmit(ImapContext *c)
{
    if (c->protocol()->delimiterUnknown()) {
        // We are waiting on delim to move
        return QString();
    }

    QString from = _mailboxParents.last().first.path();
    QString to =  buildNewPath(c, _mailboxParents.last().first, _mailboxParents.last().second);
    QString cmd(QString("RENAME %1 %2").arg(ImapProtocol::quoteString(from)).arg( ImapProtocol::quoteString(to)));
    return c->sendCommand(cmd);
}

void MoveState::leave(ImapContext *)
{
    ImapState::init();
    _mailboxParents.removeFirst();
}

void MoveState::taggedResponse(ImapContext *c, const QString &line)
{
    QString path = buildNewPath(c, _mailboxParents.first().first, _mailboxParents.first().second);
    emit folderMoved(_mailboxParents.first().first, path, _mailboxParents.first().second, status() == OpOk);
    ImapState::taggedResponse(c, line);
}

QString MoveState::error(const QString &line)
{
    qWarning() << "MoveState::error:" << line;
    emit folderMoved(_mailboxParents.first().first, QString(), _mailboxParents.first().second, false);
    return ImapState::error(line);
}

QString MoveState::buildNewPath(ImapContext *c, const QMailFolder &folder, const QMailFolderId &newParentId)
{
    QString path;
    if (c->protocol()->flatHierarchy() || c->protocol()->delimiter() == 0) {
        path = folder.path();
    } else if (newParentId.isValid()) {
        QMailFolder parentFolder(newParentId);
        path = parentFolder.path() + c->protocol()->delimiter() + folder.path().section(c->protocol()->delimiter(), -1);
    } else {
        path = folder.path().section(c->protocol()->delimiter(), -1);
    }
    return path;
}

class ListState : public ImapState
{
    Q_OBJECT
    
public:
    ListState() : ImapState(IMAP_List, "List") { ListState::init(); }

    void setParameters(const QString &reference, const QString &mailbox, bool xlist = false);
    void setDiscoverDelimiter();

    virtual bool permitsPipelining() const { return true; }
    virtual void init();
    virtual QString transmit(ImapContext *c);
    virtual void leave(ImapContext *c);
    virtual void untaggedResponse(ImapContext *c, const QString &line);
    virtual void taggedResponse(ImapContext *c, const QString &line);
    
signals:
    void mailboxListed(const QString &flags, const QString &path);

private:
    struct ListParameters
    {
        ListParameters() : _xlist(false) {}
        
        QString _reference;
        QString _mailbox;
        bool _xlist;
    };
    
    // The list of reference/mailbox pairs we're listing (via multiple commands), in order
    QList<ListParameters> _parameters;
};

void ListState::setParameters(const QString &reference, const QString &mailbox, bool xlist)
{
    ListParameters params;
    params._reference = reference;
    params._mailbox = mailbox;
    params._xlist = xlist;

    _parameters.append(params);
}

void ListState::setDiscoverDelimiter()
{
    setParameters(QString(), QString());
}

void ListState::init()
{
    ImapState::init();
    _parameters.clear();
}

QString ListState::transmit(ImapContext *c)
{
    ListParameters &params(_parameters.last());

    if (!params._reference.isEmpty()) {
        if (c->protocol()->delimiterUnknown()) {
            //Don't do anything, we're waiting on our delimiter.
            return QString();
        }
    }

    QString reference = params._reference;
    QString mailbox = params._mailbox;
    if (!reference.isEmpty())
        reference.append(c->protocol()->delimiter());
    reference = ImapProtocol::quoteString(reference);
    mailbox = ImapProtocol::quoteString(mailbox);

    QString command("LIST");
    if (params._xlist)
        command = "XLIST";
    return c->sendCommand(QString("%1 %2 %3").arg(command).arg(reference).arg(mailbox));
}

void ListState::leave(ImapContext *)
{
    ImapState::init();
    _parameters.removeFirst();
}

void ListState::untaggedResponse(ImapContext *c, const QString &line)
{
    QString str;
    bool isXList(false);
    if (line.startsWith(QLatin1String("* LIST"))) {
        str = line.mid(7);
    } else if (line.startsWith(QLatin1String("* XLIST"))) {
        isXList = true;
        str = line.mid(8);
    } else {
        ImapState::untaggedResponse(c, line);
        return;
    }

    QString flags, path, delimiter;
    int pos, index = 0;

    flags = token(str, '(', ')', &index);

    delimiter = token(str, ' ', ' ', &index);
    if(c->protocol()->delimiterUnknown()) //only figure it out precisely if needed
    {
        if(delimiter == "NIL") {
            c->protocol()->setFlatHierarchy(true);
        } else {
            pos = 0;
            if (!token(delimiter, '"', '"', &pos).isNull()) {
                pos = 0;
                delimiter = token(delimiter, '"', '"', &pos);
            }
            if(delimiter.length() != 1)
                qWarning() << "Delimiter length is" << delimiter.length() << "while should only be 1 character";
            c->protocol()->setDelimiter(*delimiter.begin());
        }
    }

    index--;    //to point back to previous ' ' so we can find it with next search
    path = token(str, ' ', '\n', &index).trimmed();
    pos = 0;
    if (!token(path, '"', '"', &pos, "\\\"").isNull()) {
        pos = 0;
        path = token(path, '"', '"', &pos, "\\\"");
    }

    if (!path.isEmpty()) {
        // Translate the inbox folder to force the path "INBOX" as returned by normal LIST command
        if (isXList && flags.indexOf("Inbox", 0, Qt::CaseInsensitive) != -1) {
            path = "INBOX";
        }
        emit mailboxListed(flags, ImapProtocol::unescapeFolderPath(path));
    }
}

void ListState::taggedResponse(ImapContext *c, const QString &line)
{
    ListParameters &params(_parameters.first());

    if (params._reference.isNull() && params._mailbox.isNull()) {
        // This was a delimiter discovery request - don't report it to the client
    } else {
        ImapState::taggedResponse(c, line);
    }
}


class GenUrlAuthState : public ImapState
{
    Q_OBJECT

public:
    GenUrlAuthState() : ImapState(IMAP_GenUrlAuth, "GenUrlAuth") {}

    void setUrl(const QString &url, const QString &mechanism);

    virtual bool permitsPipelining() const { return true; }
    virtual void init();
    virtual QString transmit(ImapContext *c);
    virtual void leave(ImapContext *c);
    virtual void untaggedResponse(ImapContext *c, const QString &line);

signals:
    void urlAuthorized(const QString &url);

private:
    QList<QPair<QString, QString> > _parameters;
};

void GenUrlAuthState::setUrl(const QString &url, const QString &mechanism)
{
    _parameters.append(qMakePair(url, (mechanism.isEmpty() ? "INTERNAL" : mechanism)));
}

void GenUrlAuthState::init()
{
    ImapState::init();
    _parameters.clear();
}

QString GenUrlAuthState::transmit(ImapContext *c)
{
    const QPair<QString, QString> &params(_parameters.last());

    return c->sendCommand("GENURLAUTH \"" + params.first + "\" " + params.second);
}

void GenUrlAuthState::leave(ImapContext *)
{
    ImapState::init();
    _parameters.removeFirst();
}

void GenUrlAuthState::untaggedResponse(ImapContext *c, const QString &line)
{
    if (!line.startsWith(QLatin1String("* GENURLAUTH"))) {
        ImapState::untaggedResponse(c, line);
        return;
    }

    emit urlAuthorized(QMail::unquoteString(line.mid(13).trimmed()));
}


class AppendState : public ImapState
{
    Q_OBJECT

public:
    AppendState() : ImapState(IMAP_Append, "Append") {}

    void setParameters(const QMailFolder &folder, const QMailMessageId &messageId);

    virtual bool permitsPipelining() const { return true; }
    virtual void init();
    virtual QString transmit(ImapContext *c);
    virtual void leave(ImapContext *c);
    virtual bool continuationResponse(ImapContext *c, const QString &line);
    virtual void taggedResponse(ImapContext *c, const QString &line);

signals:
    void messageCreated(const QMailMessageId&, const QString&);

private:
    struct AppendParameters
    {
        AppendParameters() : mCatenate(false) {}

        QMailFolder mDestination;
        QMailMessageId mMessageId;
        QList<QPair<QByteArray, uint> > mData;
        bool mCatenate;
    };

    QList<AppendParameters> mParameters;
};

void AppendState::setParameters(const QMailFolder &folder, const QMailMessageId &messageId)
{
    AppendParameters params;
    params.mDestination = folder;
    params.mMessageId = messageId;

    mParameters.append(params);
}

void AppendState::init()
{
    ImapState::init();
    mParameters.clear();
}

static QList<QPair<QByteArray, uint> > dataSequence(QList<QMailMessage::MessageChunk> &chunks)
{
    QList<QPair<QByteArray, uint> > result;
    QByteArray sequence;

    while (!chunks.isEmpty()) {
        const QMailMessage::MessageChunk &chunk(chunks.first());

        if (chunk.first == QMailMessage::Text) {
            sequence.append(" TEXT");

            // We can't send any more in this sequence
            uint literalLength = chunk.second.length();
            result.append(qMakePair(sequence, literalLength));

            sequence.clear();
            sequence.append(chunk.second);
        } else if (chunk.first == QMailMessage::Reference) {
            sequence.append(" URL ");
            sequence.append(chunk.second);
        }

        // We're finished with this chunk
        chunks.removeFirst();
    }

    if (!sequence.isEmpty()) {
        result.append(qMakePair(sequence, 0u));
    }

    return result;
}

QString AppendState::transmit(ImapContext *c)
{
    AppendParameters &params(mParameters.last());

    QMailMessage message(params.mMessageId);

    QByteArray cmd;
    QString cmdString("APPEND ");;
    cmdString += ImapProtocol::quoteString(params.mDestination.path());
    cmdString += " (";
    cmdString += messageFlagsToString(flagsForMessage(message));
    cmdString += ") \"";
    cmdString += message.date().toString(QMailTimeStamp::Rfc3501);
    cmdString += "\"";
    cmd = cmdString.toLatin1();


    uint length = 0;

    if (c->protocol()->capabilities().contains("CATENATE")) {
        QList<QMailMessage::MessageChunk> chunks(message.toRfc2822Chunks(QMailMessage::TransmissionFormat));
        if ((chunks.count() == 1) && (chunks.first().first == QMailMessage::Text)) {
            // This is a single piece of text - no benefit to using catenate
            params.mData.append(qMakePair(chunks.first().second, 0u));
            length = params.mData.first().first.length();
        } else {
            params.mData = dataSequence(chunks);
            params.mCatenate = true;

            // Skip the leading space in the first element
            cmd.append(" CATENATE (");
            cmd.append(params.mData.first().first.mid(1));
            length = params.mData.first().second;

            params.mData.removeFirst();
            if (params.mData.isEmpty()) {
                // We have no literal data to send
                cmd.append(")");
                return c->sendCommand(cmd);
            }
        }
    } else {
        params.mData.append(qMakePair(message.toRfc2822(QMailMessage::TransmissionFormat), 0u));
        length = params.mData.first().first.length();
    }

    return c->sendCommandLiteral(cmd, length);
}

void AppendState::leave(ImapContext *)
{
    ImapState::init();
    mParameters.removeFirst();
}

bool AppendState::continuationResponse(ImapContext *c, const QString &)
{
    AppendParameters &params(mParameters.first());

    QPair<QByteArray, uint> data(params.mData.takeFirst());

    if (params.mData.isEmpty()) {
        // This is the last element
        if (params.mCatenate) {
            data.first.append(")");
        }
        c->sendData(data.first);
        return false;
    } else {
        // There is more literal data to follow
        c->sendDataLiteral(data.first, data.second);
        return true;
    }
}

void AppendState::taggedResponse(ImapContext *c, const QString &line)
{
    if (status() == OpOk) {
        // See if we got an APPENDUID response
        QRegExp appenduidResponsePattern("APPENDUID (\\S+) ([^ \\t\\]]+)");
        appenduidResponsePattern.setCaseSensitivity(Qt::CaseInsensitive);
        if (appenduidResponsePattern.indexIn(line) != -1) {
            const AppendParameters &params(mParameters.first());
            emit messageCreated(params.mMessageId, messageUid(params.mDestination.id(), appenduidResponsePattern.cap(2)));
        }
    }
    
    ImapState::taggedResponse(c, line);
}


// Handles untagged responses in the selected IMAP state
class SelectedState : public ImapState
{
    Q_OBJECT

public:
    SelectedState(ImapCommand c, const QString &name) : ImapState(c, name) {}

    virtual void untaggedResponse(ImapContext *c, const QString &line);
};

void SelectedState::untaggedResponse(ImapContext *c, const QString &line)
{
    bool result;

    if (line.indexOf("EXISTS", 0, Qt::CaseInsensitive) != -1) {
        int start = 0;
        QString temp = token(line, ' ', ' ', &start);
        quint32 exists = temp.toUInt(&result);
        if (!result)
            exists = 0;
        c->setExists(exists);
    } else if (line.indexOf("RECENT", 0, Qt::CaseInsensitive) != -1) {
        int start = 0;
        QString temp = token(line, ' ', ' ', &start);
        quint32 recent = temp.toUInt(&result);
        if (!result)
           recent = 0;
        c->setRecent(recent);
    } else if (line.startsWith("* FLAGS", Qt::CaseInsensitive)) {
        int start = 0;
        QString flags = token(line, '(', ')', &start);
        c->setFlags(flags);
    } else if (line.indexOf("UIDVALIDITY", 0, Qt::CaseInsensitive) != -1) {
        int start = 0;
        QString temp = token(line, '[', ']', &start);
        c->setUidValidity(temp.mid(12).trimmed());
    } else if (line.indexOf("UIDNEXT", 0, Qt::CaseInsensitive) != -1) {
        int start = 0;
        QString temp = token(line, '[', ']', &start);
        QString nextStr = temp.mid( 8 );
        quint32 next = nextStr.toUInt(&result);
        if (!result)
            next = 0;
        c->setUidNext(next);
    } else if (line.indexOf("UNSEEN", 0, Qt::CaseInsensitive) != -1) {
        int start = 0;
        QString temp = token(line, '[', ']', &start);
        QString unseenStr = temp.mid( 7 );
        quint32 unseen = unseenStr.toUInt(&result);
        if (!result)
            unseen = 0;
        c->setUnseen(unseen);
    } else if (line.indexOf("HIGHESTMODSEQ", 0, Qt::CaseInsensitive) != -1) {
        int start = 0;
        QString temp = token(line, '[', ']', &start);
        c->setHighestModSeq(temp.mid(14).trimmed());
    } else if (line.indexOf("NOMODSEQ", 0, Qt::CaseInsensitive) != -1) {
        c->setNoModSeq();
    } else if (line.indexOf("PERMANENTFLAGS", 0, Qt::CaseInsensitive) != -1) {
        int start = 0;
        QString temp = token(line, '(', ')', &start);
        c->setPermanentFlags(temp.split(' ', QString::SkipEmptyParts));
    } else {
        ImapState::untaggedResponse(c, line);
    }
    // TODO consider unilateral EXPUNGE notifications
}


class SelectState : public SelectedState
{
    Q_OBJECT

public:
    SelectState() : SelectedState(IMAP_Select, "Select") { SelectState::init(); }

    void setMailbox(const QMailFolder &mailbox);

    virtual bool permitsPipelining() const { return true; }
    virtual void init();
    virtual QString transmit(ImapContext *c);
    virtual void enter(ImapContext *c);
    virtual void leave(ImapContext *);

protected:
    SelectState(ImapCommand c, const QString &name) : SelectedState(c, name) {}

    // The list of mailboxes we're selecting (via multiple commands), in order
    QList<QMailFolder> _mailboxList;
};

void SelectState::setMailbox(const QMailFolder &mailbox)
{
    _mailboxList.append(mailbox);
}

void SelectState::init()
{
    ImapState::init();
    _mailboxList.clear();
}

QString SelectState::transmit(ImapContext *c)
{
    QString cmd("SELECT " + ImapProtocol::quoteString(_mailboxList.last().path()));

    if (c->protocol()->capabilities().contains("CONDSTORE")) {
        cmd.append(" (CONDSTORE)");
    }

    return c->sendCommand(cmd);
}

void SelectState::enter(ImapContext *c)
{
    c->setMailbox(_mailboxList.first());
}

void SelectState::leave(ImapContext *)
{
    ImapState::init();
    _mailboxList.removeFirst();
}


class QResyncState : public SelectState
{
    Q_OBJECT

public:
    QResyncState() : SelectState(IMAP_QResync, "QResync") { init(); }

    virtual QString transmit(ImapContext *c);
    virtual void untaggedResponse(ImapContext *c, const QString &line);
    virtual void taggedResponse(ImapContext *c, const QString &line);
    virtual void enter(ImapContext *c);
    virtual void leave(ImapContext *c);

protected:
    QString vanished;
    QList<FlagChange> changes;
};

void QResyncState::enter(ImapContext *c)
{
    vanished.clear();
    changes.clear();
    SelectState::enter(c);
}

void QResyncState::leave(ImapContext *c)
{
    SelectState::leave(c);
}

QString QResyncState::transmit(ImapContext *c)
{
    QMailFolder folder(_mailboxList.last());
    QString cmd("SELECT " + ImapProtocol::quoteString(folder.path()));
    QString uidValidity(folder.customField("qmf-uidvalidity"));
    QString highestModSeq(folder.customField("qmf-highestmodseq"));
    QString minServerUid(folder.customField("qmf-min-serveruid"));
    QString maxServerUid(folder.customField("qmf-max-serveruid"));
    if (!uidValidity.isEmpty() && !highestModSeq.isEmpty() && !minServerUid.isEmpty() && !maxServerUid.isEmpty()) {
        cmd += QString(" (QRESYNC (%1 %2 %3:%4))").arg(uidValidity).arg(highestModSeq).arg(minServerUid).arg(maxServerUid);
    } else {
        cmd.append(" (CONDSTORE)");
    }
    
    return c->sendCommand(cmd);
}

void QResyncState::untaggedResponse(ImapContext *c, const QString &line)
{
    QString str = line;
    QRegExp fetchResponsePattern("\\*\\s+\\d+\\s+(\\w+)");
    QRegExp vanishResponsePattern("\\*\\s+\\VANISHED\\s+\\(EARLIER\\)\\s+(\\S+)");
    vanishResponsePattern.setCaseSensitivity(Qt::CaseInsensitive);
    if ((fetchResponsePattern.indexIn(str) == 0) && (fetchResponsePattern.cap(1).compare("FETCH", Qt::CaseInsensitive) == 0)) {
        QString uid = extractUid(str, c->mailbox().id);
        if (!uid.isEmpty()) {
            MessageFlags flags = 0;
            parseFlags(str, flags);
            changes.append(FlagChange(uid, flags));
        }
    } else if (vanishResponsePattern.indexIn(str) == 0) {
        vanished = vanishResponsePattern.cap(1);
    } else {
        SelectState::untaggedResponse(c, line);
    }
}

void QResyncState::taggedResponse(ImapContext *c, const QString &line)
{
    c->setVanished(vanished);
    c->setChanges(changes);
    vanished.clear();
    changes.clear();
    SelectState::taggedResponse(c, line);
}


// Flag fetching, 
// doesn't call createMail, instead updates properties.flagChanges
class FetchFlagsState : public SelectedState
{
    Q_OBJECT

public:
    FetchFlagsState() : SelectedState(IMAP_FetchFlags, "FetchFlags") { FetchFlagsState::init(); }

    void setProperties(const QString &range, const QString &prefix);

    virtual void init();
    virtual QString transmit(ImapContext *c);
    virtual void untaggedResponse(ImapContext *c, const QString &line);
    virtual void taggedResponse(ImapContext *c, const QString &line);

protected:
    QList<FlagChange> mChanges;
    IntegerRegion mReceivedMessages;
    QString mRange;
    QString mPrefix;
};

void FetchFlagsState::setProperties(const QString &range, const QString &prefix)
{
    mRange = range;
    mPrefix = prefix;
}

void FetchFlagsState::init() 
{ 
    SelectedState::init();
    mChanges.clear();
}

void FetchFlagsState::untaggedResponse(ImapContext *c, const QString &line)
{
    QString str = line;
    QRegExp fetchResponsePattern("\\*\\s+\\d+\\s+(\\w+)");
    if ((fetchResponsePattern.indexIn(str) == 0) && (fetchResponsePattern.cap(1).compare("FETCH", Qt::CaseInsensitive) == 0)) {
        QString uid = extractUid(str, c->mailbox().id);
        if (!uid.isEmpty()) {
            MessageFlags flags = 0;
            parseFlags(str, flags);
            
            bool ok;
            int uidStripped = messageId(uid).toInt(&ok);
            if (!ok)
                return;
            
            mChanges.append(FlagChange(uid, flags));
            mReceivedMessages.add(uidStripped);
        }
    } else {
        SelectedState::untaggedResponse(c, line);
    }
}

void FetchFlagsState::taggedResponse(ImapContext *c, const QString &line)
{
    c->setChanges(mChanges);
    mChanges.clear();
    c->setUidList(mReceivedMessages.toStringList());
    mReceivedMessages.clear();
    SelectedState::taggedResponse(c, line);
}

QString FetchFlagsState::transmit(ImapContext *c)
{
    QString command = QString("FETCH %1 %2").arg(mRange).arg("(FLAGS UID)");
    if (!mPrefix.isEmpty())
        command = mPrefix.simplified() + " " + command;
    return c->sendCommand(command);
}


class ExamineState : public SelectState
{
    Q_OBJECT

public:
    ExamineState() : SelectState(IMAP_Examine, "Examine") { ExamineState::init(); }

    virtual QString transmit(ImapContext *c);
    virtual void enter(ImapContext *c);
};

QString ExamineState::transmit(ImapContext *c)
{
    QString cmd("EXAMINE " + ImapProtocol::quoteString(_mailboxList.last().path()));

    if (c->protocol()->capabilities().contains("CONDSTORE")) {
        cmd.append(" (CONDSTORE)");
    }

    return c->sendCommand(cmd);
}

void ExamineState::enter(ImapContext *c)
{
    // even though we're really in _mailboxList.first() folder, we can't do any (write) operations
    c->setMailbox(QMailFolder());
}

class SearchMessageState : public SelectedState
{
    Q_OBJECT
public:
    SearchMessageState() : SelectedState(IMAP_Search_Message, "Search_Message"), _utf8(false) { }
    virtual bool permitsPipelining() const { return true; }
    void setParameters(const QMailMessageKey &key, const QString &body, const QMailMessageSortKey &sort, bool count);
    virtual QString transmit(ImapContext *c);
    virtual void leave(ImapContext *c);
    virtual bool continuationResponse(ImapContext *c, const QString &line);
    virtual void untaggedResponse(ImapContext *c, const QString &line);
protected:
    bool isPrintable(const QString &s) const;
    QStringList convertValue(const QVariant &value, const QMailMessageKey::Property &property, const QMailKey::Comparator &comparer);
    QStringList combine(const QList<QStringList> &searchKeys, const QMailKey::Combiner &combiner) const;
    QStringList convertKey(const QMailMessageKey &key);

    struct SearchArgument {
        QMailMessageKey key;
        QString body;
        QMailMessageSortKey sort;
        bool count;
    };
    QList<SearchArgument> _searches;
    QStringList _literals;
    bool _utf8;
    bool _esearch;
};

void SearchMessageState::setParameters(const QMailMessageKey &searchKey, const QString &bodyText, const QMailMessageSortKey &sortKey, bool count)
{
    SearchArgument arg;
    arg.key = searchKey;
    arg.body = bodyText;
    arg.sort = sortKey;
    arg.count = count;
    _searches.append(arg);
    _literals.clear();
    _utf8 = false;
    _esearch = false;
}

QString SearchMessageState::transmit(ImapContext *c)
{
    const SearchArgument &search = _searches.last();
    QStringList searchQueries = convertKey(search.key);

    QString prefix = "UID SEARCH ";
    _utf8 |= !(isPrintable(search.body));
    if (search.count && c->protocol()->capabilities().contains("ESEARCH", Qt::CaseInsensitive)) {
        prefix.append("RETURN (COUNT) ");
        _esearch = true;
    }
    if (_utf8)
        prefix.append("CHARSET UTF-8 ");
    if (!search.body.isEmpty())
        prefix.append("OR (");
    searchQueries.prepend(searchQueries.takeFirst().prepend(prefix));

    if (!search.body.isEmpty()) {
        QString tempLast = searchQueries.takeLast();
        QString searchBody = search.body.toUtf8(); //utf8 is backwards compatible with 7 bit ascii
        searchQueries.append(tempLast + QString(") (BODY {%2}").arg(searchBody.size()));
        searchQueries.append(searchBody + ")");
    }

    QString suffix = " NOT DELETED"; //needed because of limitations in fetching deleted messages
    QString tempLast = searchQueries.takeLast();
    searchQueries.append(tempLast.append(suffix));

    QString first = searchQueries.takeFirst();
    _literals = searchQueries;
    return c->sendCommand(first);
}

bool SearchMessageState::continuationResponse(ImapContext *c, const QString &)
{
    c->sendData(_literals.takeFirst());
    return false;
}

bool SearchMessageState::isPrintable(const QString &s) const
{
    for (int i = 0; i < s.length(); ++i) {
        const char c = s[i].toLatin1();
        if (c < 0x20 || c > 0x7e) {
            return false;
        }
    }
    return true;
}

// Sets _utf8 as side effect
QStringList SearchMessageState::convertValue(const QVariant &value, const QMailMessageKey::Property &property,
                                             const QMailKey::Comparator &comparer)
{

    switch(property) {
    case QMailMessageKey::Id:
        break;
    case QMailMessageKey::Type:
        return QStringList(); // TODO: Why are search keys coming in with "message must equal no type"
    case QMailMessageKey::Sender: {
        _utf8 |= !(isPrintable(value.toString()));
        QString sender = value.toString().toUtf8(); // utf8 is backwards compatible with 7 bit ascii
        if (comparer == QMailKey::Equal || comparer == QMailKey::Includes) {
            QStringList result = QStringList(QString("FROM {%1}").arg(sender.size()));
            result.append(QString("%1").arg(QString(sender)));
            return result;
        } else if(comparer == QMailKey::NotEqual || comparer == QMailKey::Excludes) {
            QStringList result = QStringList(QString("NOT (FROM {%1}").arg(sender.size()));
            result.append(QString("%1)").arg(QString(sender)));
            return result;
        } else {
            qWarning() << "Comparer " << comparer << " is unhandled for sender comparison";
        }
        break;
    }
    case QMailMessageKey::ParentFolderId:
        return QStringList();
    case QMailMessageKey::Recipients: {
        _utf8 |= !(isPrintable(value.toString()));
        QString recipients = value.toString().toUtf8(); // utf8 is backwards compatible with 7 bit ascii
        if(comparer == QMailKey::Equal || comparer == QMailKey::Includes) {
            QStringList result = QStringList(QString("OR (BCC {%1}").arg(recipients.size()));
            result.append(QString("%1) (OR (CC {%2}").arg(recipients).arg(recipients.size()));
            result.append(QString("%1) (TO {%2}").arg(recipients).arg(recipients.size()));
            result.append(QString("%1))").arg(recipients));
            return result;
        } else if(comparer == QMailKey::NotEqual || comparer == QMailKey::Excludes) {
            QStringList result = QStringList(QString("NOT (OR (BCC {%1}").arg(recipients.size()));
            result.append(QString("%1) (OR (CC {%2}").arg(recipients).arg(recipients.size()));
            result.append(QString("%1) (TO {%2}").arg(recipients).arg(recipients.size()));
            result.append(QString("%1)))").arg(recipients));
            return result;
        } else {
            qWarning() << "Comparer " << comparer << " is unhandled for recipients comparison";
        }
        break;
    }
    case QMailMessageKey::Subject: {
        _utf8 |=  !(isPrintable(value.toString()));
        QString subject = value.toString().toUtf8(); //utf8 is backwards compatible with 7 bit ascii
        if(comparer == QMailKey::Equal || comparer == QMailKey::Includes) {
            QStringList result = QStringList(QString("SUBJECT {%1}").arg(subject.size()));
            result.append(QString("%1").arg(QString(subject)));
            return result;
        } else if(comparer == QMailKey::NotEqual || comparer == QMailKey::Excludes) {
            QStringList result = QStringList(QString("NOT (SUBJECT {%1}").arg(subject.size()));
            result.append(QString("%1)").arg(QString(subject)));
            return result;
        } else {
            qWarning() << "Comparer " << comparer << " is unhandled for subject comparison";
        }
        break;
    }
    case QMailMessageKey::TimeStamp:
        break;
    case QMailMessageKey::Status:
        break;
    case QMailMessageKey::Conversation:
        break;
    case QMailMessageKey::ReceptionTimeStamp:
        break;
    case QMailMessageKey::ServerUid:
        break;
    case QMailMessageKey::Size: {
        int size = value.toInt();

        if(comparer == QMailKey::GreaterThan)
            return QStringList(QString("LARGER %1").arg(size));
        else if(comparer == QMailKey::LessThan)
            return QStringList(QString("SMALLER %1").arg(size));
        else if(comparer == QMailKey::GreaterThanEqual)
            return QStringList(QString("LARGER %1").arg(size-1)); // imap has no >= search, so convert it to a >
        else if(comparer == QMailKey::LessThanEqual)
            return QStringList(QString("SMALLER %1").arg(size+1)); // ..same with <=
        else if(comparer == QMailKey::Equal) // ..cause real men know how many bytes they're looking for
            return QStringList(QString("LARGER %1 SMALLER %2").arg(size-1).arg(size+1));
        else
            qWarning() << "Unknown comparer: " << comparer << "for size";
        break;
    }
    case QMailMessageKey::ParentAccountId:
        return QStringList();
        break;
    case QMailMessageKey::AncestorFolderIds:
        return QStringList();
        break;
    case QMailMessageKey::ContentType:
        break;
    case QMailMessageKey::PreviousParentFolderId:
        break;
    case QMailMessageKey::ContentScheme:
        break;
    case QMailMessageKey::ContentIdentifier:
        break;
    case QMailMessageKey::InResponseTo:
        break;
    case QMailMessageKey::ResponseType:
        break;
    case QMailMessageKey::Custom:
        break;
    default:
        qWarning() << "Property " << property << " still not handled for search.";
    }
    return QStringList();
}

QStringList SearchMessageState::convertKey(const QMailMessageKey &key)
{
    QStringList result;
    QMailKey::Combiner combiner = key.combiner();

    QList<QMailMessageKey::ArgumentType> args = key.arguments();

    QList<QStringList> argSearches;
    foreach(QMailMessageKey::ArgumentType arg, args) {
        Q_ASSERT(arg.valueList.count() == 1); // shouldn't have more than 1 element.
        QStringList searchKey(convertValue(arg.valueList[0], arg.property, arg.op));
        if (!searchKey.isEmpty()) {
            argSearches.append(searchKey);
        }
    }
    if (argSearches.size())
        result = combine(argSearches, combiner);



    QList<QStringList> subSearchKeys;
    QList<QMailMessageKey> subkeys = key.subKeys();

    foreach(QMailMessageKey subkey, subkeys) {
        QStringList searchKey(convertKey(subkey));
        if (!searchKey.isEmpty())
            subSearchKeys.append(searchKey);
    }
    if(!subSearchKeys.isEmpty()) {
        result += combine(subSearchKeys, combiner);
    }

    return result;
}

QStringList SearchMessageState::combine(const QList<QStringList> &searchKeys, const QMailKey::Combiner &combiner) const
{
    Q_ASSERT(searchKeys.size() >= 1);
    if (searchKeys.size() == 1) {
        return searchKeys.first();
    } else if(combiner == QMailKey::And) {
        // IMAP uses AND so just add a space and we're good to go!
        QStringList result = searchKeys.first();
        for (int i = 1 ; i < searchKeys.count() ; i++) {
            QStringList cur = searchKeys[i];
            if (cur.count()) {
                cur.first().prepend(' ');
                QString last;
                if (result.count()) {
                    last = result.takeLast();
                }
                result.append(last.append(cur.takeFirst()));
                result.append(cur);
            }
        }
        return result;
    } else if(combiner == QMailKey::Or) {
        QStringList result;

        for (int i = 0 ; i < searchKeys.count() ; i++) {
            QStringList cur = searchKeys[i];
            if (cur.count()) {
                if (i == searchKeys.count() - 1) {// the last one
                    cur[cur.count() - 1].append(QString(')').repeated(searchKeys.count() - 1));
                } else {
                    cur.first().prepend("OR (");
                    cur.last().append(") (");
                }
                QString last;
                if (result.count()) {
                    last = result.takeLast();
                }
                result.append(last.append(cur.takeFirst()));
                result.append(cur);
            } // else should not happen
        }

        return result;
    } else if(combiner == QMailKey::None) {
        if(searchKeys.count() != 1) {
            qWarning() << "Attempting to combine more than thing, without a combiner?";
            return QStringList();
        } else {
            return searchKeys.first();
        }
    } else {
        qWarning() << "Unable to combine with an unknown combiner: " << combiner;
        return QStringList();
    }
}


void SearchMessageState::leave(ImapContext *)
{
    _searches.removeFirst();
}

void SearchMessageState::untaggedResponse(ImapContext *c, const QString &line)
{
    if (line.startsWith(QLatin1String("* ESEARCH"))) {
        int index = 8;
        QString temp;
        QString check;
        QString countStr;
        uint count = 0;
        bool ok;
        while (!(temp = token(line, ' ', ' ', &index)).isEmpty()) {
            check = temp;
            index--;
        }
        countStr = token(line, ' ', '\n', &index);
        if (check.toLower() != "count") {
            qWarning() << "Bad ESEARCH result, count expected";
        }
        count = countStr.toUInt(&ok);
        c->setUidList(QStringList());
        c->setSearchCount(count);
    } else if (line.startsWith(QLatin1String("* SEARCH"))) {
        QStringList uidList;

        int index = 7;
        QString temp;
        while (!(temp = token(line, ' ', ' ', &index)).isEmpty()) {
            uidList.append(messageUid(c->mailbox().id, temp));
            index--;
        }
        temp = token(line, ' ', '\n', &index);
        if (!temp.isEmpty())
            uidList.append(messageUid(c->mailbox().id, temp));
        c->setUidList(uidList);
        c->setSearchCount(uidList.count());
    } else {
        SelectedState::untaggedResponse(c, line);
    }
}

class SearchState : public SelectedState
{
    Q_OBJECT

public:
    SearchState() : SelectedState(IMAP_Search, "Search") { SearchState::init(); }

    void setParameters(MessageFlags flags, const QString &range);

    virtual bool permitsPipelining() const { return true; }
    virtual void init();
    virtual QString transmit(ImapContext *c);
    virtual void leave(ImapContext *c);
    virtual void untaggedResponse(ImapContext *c, const QString &line);
    virtual QString error(const QString &line);

private:
    // The list of flags/range pairs we're listing (via multiple commands), in order
    QList<QPair<MessageFlags, QString> > _parameters;
};

void SearchState::setParameters(MessageFlags flags, const QString &range)
{
    _parameters.append(qMakePair(flags, range));
}

void SearchState::init()
{
    SelectedState::init();
    _parameters.clear();
}

QString SearchState::transmit(ImapContext *c)
{
    const QPair<MessageFlags, QString> &params(_parameters.last());

    QString flagStr;
    if ((params.first == 0) && params.second.isEmpty()) {
        flagStr = "ALL";
    } else {
        flagStr = searchFlagsToString(params.first);
    }

    if (!params.second.isEmpty() && !flagStr.isEmpty())
        flagStr.prepend(' ');

    return c->sendCommand(QString("SEARCH %1%2").arg(params.second).arg(flagStr));
}

void SearchState::leave(ImapContext *)
{
    SelectedState::init();
    _parameters.removeFirst();
}

void SearchState::untaggedResponse(ImapContext *c, const QString &line)
{
    if (line.startsWith("* SEARCH")) {
        QList<uint> numbers;

        int index = 7;
        QString temp;
        while (!(temp = token(line, ' ', ' ', &index)).isNull()) {
            numbers.append(temp.toUInt());
            index--;
        }
        temp = token(line, ' ', '\n', &index);
        if (!temp.isNull())
            numbers.append(temp.toUInt());
        c->setMsnList(numbers);
    } else {
        SelectedState::untaggedResponse(c, line);
    }
}

QString SearchState::error(const QString &line)
{
    return line + '\n' + QObject::tr( "This server does not provide a complete "
                       "IMAP4rev1 implementation." );
}


class UidSearchState : public SelectedState
{
    Q_OBJECT

public:
    UidSearchState() : SelectedState(IMAP_UIDSearch, "UIDSearch") { UidSearchState::init(); }

    void setParameters(MessageFlags flags, const QString &range);

    virtual bool permitsPipelining() const { return true; }
    virtual void init();
    virtual QString transmit(ImapContext *c);
    virtual void leave(ImapContext *c);
    virtual void untaggedResponse(ImapContext *c, const QString &line);
    virtual QString error(const QString &line);

private:
    // The list of flags/range pairs we're listing (via multiple commands), in order
    QList<QPair<MessageFlags, QString> > _parameters;
};

void UidSearchState::setParameters(MessageFlags flags, const QString &range)
{
    _parameters.append(qMakePair(flags, range));
}

void UidSearchState::init()
{
    SelectedState::init();
    _parameters.clear();
}

QString UidSearchState::transmit(ImapContext *c)
{
    const QPair<MessageFlags, QString> &params(_parameters.last());

    QString flagStr;
    if ((params.first == 0) && params.second.isEmpty()) {
        flagStr = "ALL";
    } else {
        flagStr = searchFlagsToString(params.first);
    }

    if (!params.second.isEmpty() && !flagStr.isEmpty())
        flagStr.prepend(' ');

    return c->sendCommand(QString("UID SEARCH %1%2").arg(params.second).arg(flagStr));
}

void UidSearchState::leave(ImapContext *)
{
    SelectedState::init();
    _parameters.removeFirst();
}

void UidSearchState::untaggedResponse(ImapContext *c, const QString &line)
{
    if (line.startsWith("* SEARCH")) {
        QStringList uidList;

        int index = 7;
        QString temp;
        while (!(temp = token(line, ' ', ' ', &index)).isNull()) {
            uidList.append(messageUid(c->mailbox().id, temp));
            index--;
        }
        temp = token(line, ' ', '\n', &index);
        if (!temp.isNull())
            uidList.append(messageUid(c->mailbox().id, temp));
        c->setUidList(uidList);
    } else {
        SelectedState::untaggedResponse(c, line);
    }
}

QString UidSearchState::error(const QString &line)
{
    return line + QLatin1String("\n")
        + QObject::tr( "This server does not provide a complete "
                       "IMAP4rev1 implementation." );
}


class UidFetchState : public SelectedState
{
    Q_OBJECT

public:
    UidFetchState() : SelectedState(IMAP_UIDFetch, "UIDFetch") { UidFetchState::init(); }

    void setUidList(const QString &uidList, FetchItemFlags flags);
    void setSection(const QString &uid, const QString &section, int start, int end, FetchItemFlags flags);

    virtual bool permitsPipelining() const { return true; }
    virtual void init();
    virtual QString transmit(ImapContext *c);
    virtual void leave(ImapContext *);
    virtual void untaggedResponse(ImapContext *c, const QString &line);
    virtual void taggedResponse(ImapContext *c, const QString &line);
    virtual void literalResponse(ImapContext *c, const QString &line);
    virtual bool appendLiteralData(ImapContext *c, const QString &preceding);
    
signals:
    void downloadSize(const QString&, int);
    void nonexistentUid(const QString&);

private:
    struct FetchParameters
    {
        FetchParameters();

        int mReadLines;
        int mMessageLength;
        QString mNewMsgUid;
        MessageFlags mNewMsgFlags;
        QDateTime mDate;
        uint mNewMsgSize;
        QStringList mNewMsgStructure;
        IntegerRegion mExpectedMessages;
        IntegerRegion mReceivedMessages;
        FetchItemFlags mDataItems;
        QString mUidList;
        QString mSection;
        int mStart;
        int mEnd;
        QString mDetachedFile;
        int mDetachedSize;
    };

    QList<FetchParameters> mParameters;
    int mCurrentIndex;
    QMap<QString, int> mParametersMap;
    int mLiteralIndex;
    
    static QString fetchResponseElement(const QString &line);

    static const int MAX_LINES = 30;
};

UidFetchState::FetchParameters::FetchParameters()
    : mReadLines(0),
      mMessageLength(0),
      mNewMsgFlags(false),
      mNewMsgSize(0),
      mDataItems(0)
{ 
}

void UidFetchState::init() 
{ 
    SelectedState::init();
    mParametersMap.clear();
    mParameters.clear();
    mCurrentIndex = -1;
    mLiteralIndex = -1;
}

void UidFetchState::setUidList(const QString &uidList, FetchItemFlags flags)
{
    int appendIndex = mParameters.count();
    mParameters.append(FetchParameters());

    mParameters.last().mDataItems = flags;
    mParameters.last().mUidList = uidList;
    mParameters.last().mExpectedMessages = IntegerRegion(uidList);

    foreach (int uid, IntegerRegion::toList(uidList)) {
        mParametersMap.insert(QString::number(uid), appendIndex);
    }
    
    if (mCurrentIndex == -1) {
        mCurrentIndex = 0;
    }
}

void UidFetchState::setSection(const QString &uid, const QString &section, int start, int end, FetchItemFlags flags)
{
    int appendIndex = mParameters.count();
    mParameters.append(FetchParameters());

    mParameters.last().mDataItems = flags;
    mParameters.last().mUidList = uid;
    mParameters.last().mSection = section;
    mParameters.last().mStart = start;
    mParameters.last().mEnd = end;

    QString element(uid + ' ' + (section.isEmpty() ? "TEXT" : section));
    if (flags & F_SectionHeader) {
        element.append(".MIME");
    }
    if (end > 0) {
        element.append(QString("<%1>").arg(QString::number(start)));
    }
    mParametersMap.insert(element, appendIndex);

    if (mCurrentIndex == -1) {
        mCurrentIndex = 0;
    }
}

QString UidFetchState::transmit(ImapContext *c)
{
    const FetchParameters &params(mParameters.last());

    QString flagStr;
    if (params.mDataItems & F_Flags)
        flagStr += " FLAGS";
    if (params.mDataItems & F_Uid)
        flagStr += " UID";
    if (params.mDataItems & F_Date)
        flagStr += " INTERNALDATE";
    if (params.mDataItems & F_Rfc822_Size)
        flagStr += " RFC822.SIZE";
    if (params.mDataItems & F_BodyStructure)
        flagStr += " BODYSTRUCTURE";
    if (params.mDataItems & F_Rfc822_Header)
        flagStr += " RFC822.HEADER";
    if (params.mDataItems & F_Rfc822)
        flagStr += " BODY.PEEK[]";
    if (params.mDataItems & F_SectionHeader) {
        flagStr += " BODY.PEEK[";
        if (params.mSection.isEmpty()) {
            flagStr += "HEADER]";
        } else {
            flagStr += params.mSection + ".MIME]";
        }
    }
    if (params.mDataItems & F_BodySection) {
        flagStr += " BODY.PEEK[";
        if (params.mSection.isEmpty()) {
            flagStr += "TEXT]";
        } else {
            flagStr += params.mSection + "]";
        }
        if (params.mEnd > 0) {
            QString strStart = QString::number(params.mStart);
            QString strLen = QString::number(params.mEnd - params.mStart + 1);
            flagStr += ('<' + strStart + '.' + strLen + '>');
        }
    }

    if (!flagStr.isEmpty())
        flagStr = "(" + flagStr.trimmed() + ")";

    return c->sendCommand(QString("UID FETCH %1 %2").arg(params.mUidList).arg(flagStr));
}

void UidFetchState::leave(ImapContext *)
{
    SelectedState::init();
    ++mCurrentIndex;
}

void UidFetchState::untaggedResponse(ImapContext *c, const QString &line)
{
    QString str = line;
    QRegExp fetchResponsePattern("\\*\\s+\\d+\\s+(\\w+)");
    if ((fetchResponsePattern.indexIn(str) == 0) && (fetchResponsePattern.cap(1).compare("FETCH", Qt::CaseInsensitive) == 0)) {
        QString element(fetchResponseElement(str));
        QMap<QString, int>::iterator it = mParametersMap.find(element);
        if (it != mParametersMap.end()) {
            FetchParameters &fp(mParameters[*it]);

            if (fp.mDataItems & F_Uid) {
                fp.mNewMsgUid = extractUid(str, c->mailbox().id);

                bool ok = false;
                int index = fp.mNewMsgUid.lastIndexOf(UID_SEPARATOR);
                if (index == -1)
                    return;
                int uid = fp.mNewMsgUid.mid(index + 1).toInt(&ok);
                if (!ok)
                    return;
                fp.mReceivedMessages.add(uid);
                fp.mMessageLength = 0;
                
                // See what we can extract from the FETCH response
                fp.mNewMsgFlags = 0;
                if (fp.mDataItems & F_Flags) {
                    parseFlags(str, fp.mNewMsgFlags);
                }

                if (fp.mDataItems & F_Date) {
                    fp.mDate = extractDate(str);
                }

                if (fp.mDataItems & F_Rfc822_Size) {
                    fp.mNewMsgSize = extractSize(str);
                }

                if (!c->literalResponseCompleted()) {
                    // Wait for the literal data to be received
                    mLiteralIndex = *it;
                    return;
                }

                // All message data should be retrieved at this point - create new mail/part
                if (fp.mDataItems & F_BodyStructure) {
                    fp.mNewMsgStructure = extractStructure(str);
                }

                if ((fp.mDataItems & F_BodySection)
                    || (fp.mDataItems & F_SectionHeader)) {
                    if (fp.mDetachedFile.isEmpty()) {
                        // The buffer has not been detached to a file yet
                        fp.mDetachedSize = c->buffer().length();
                        fp.mDetachedFile = c->buffer().detach();
                    }
                    if (fp.mDataItems & F_SectionHeader) {
                        c->createPartHeader(fp.mNewMsgUid, fp.mSection, fp.mDetachedFile, fp.mDetachedSize);
                    } else {
                        c->createPart(fp.mNewMsgUid, fp.mSection, fp.mDetachedFile, fp.mDetachedSize);
                    }
                } else {
                    if (fp.mNewMsgSize == 0) {
                        fp.mNewMsgSize = fp.mDetachedSize;
                    }
                    c->createMail(fp.mNewMsgUid, fp.mDate, fp.mNewMsgSize, fp.mNewMsgFlags, fp.mDetachedFile, fp.mNewMsgStructure);
                }
            }
        } else {
            qWarning() << "untaggedResponse: Unable to find fetch parameters for:" << str;
        }
    } else {
        SelectedState::untaggedResponse(c, line);
    }
}

void UidFetchState::taggedResponse(ImapContext *c, const QString &line)
{
    if (status() == OpOk) {
        FetchParameters &fp(mParameters[mCurrentIndex]);

        IntegerRegion missingUids = fp.mExpectedMessages.subtract(fp.mReceivedMessages);
        foreach(const QString &uid, missingUids.toStringList()) {
            qWarning() << "Message not found " << uid;
            emit nonexistentUid(messageUid(c->mailbox().id, uid));
        } 
    } 

    SelectedState::taggedResponse(c, line);
}

void UidFetchState::literalResponse(ImapContext *c, const QString &line)
{
    if (!c->literalResponseCompleted()) {
        if (mLiteralIndex != -1) {
            FetchParameters &fp(mParameters[mLiteralIndex]);

            ++fp.mReadLines;
            if ((fp.mDataItems & F_Rfc822) || (fp.mDataItems & F_BodySection)) {
                fp.mMessageLength += line.length();

                if (fp.mReadLines > MAX_LINES) {
                    fp.mReadLines = 0;
                    emit downloadSize(fp.mNewMsgUid, fp.mMessageLength);
                }
            }
        } else {
            qWarning() << "Literal data received with invalid literal index!";
        }
    }
}

bool UidFetchState::appendLiteralData(ImapContext *c, const QString &preceding)
{
    if (mLiteralIndex != -1) {
        FetchParameters &fp(mParameters[mLiteralIndex]);

        // We're finished with this literal data
        mLiteralIndex = -1;

        QRegExp pattern;
        if (fp.mDataItems & F_Rfc822_Header) {
            // If the literal is the header data, keep it in the buffer file
            pattern = QRegExp("RFC822\\.HEADER ");
        } else {
            // If the literal is the body data, keep it in the buffer file
            pattern = QRegExp("BODY\\[\\S*\\] ");
        }

        pattern.setCaseSensitivity(Qt::CaseInsensitive);
        int index = pattern.lastIndexIn(preceding);
        if (index != -1) {
            if ((index + pattern.cap(0).length()) == preceding.length()) {
                // Detach the retrieved data to a file we have ownership of
                fp.mDetachedSize = c->buffer().length();
                fp.mDetachedFile = c->buffer().detach();
                return false;
            }
        }
    } else {
        qWarning() << "Literal data appended with invalid literal index!";
    }

    return true;
}

QString UidFetchState::fetchResponseElement(const QString &line)
{
    QString result;

    QRegExp uidPattern("UID\\s+(\\d+)");
    uidPattern.setCaseSensitivity(Qt::CaseInsensitive);
    if (uidPattern.indexIn(line) != -1) {
        result = uidPattern.cap(1);
    }

    QRegExp bodyPattern("BODY\\[([^\\]]*)\\](<[^>]*>)?");
    bodyPattern.setCaseSensitivity(Qt::CaseInsensitive);
    if (bodyPattern.indexIn(line) != -1) {
        QString section(bodyPattern.cap(1));
        if (!section.isEmpty()) {
            result.append(' ' + section + bodyPattern.cap(2));
        }
    }

    return result;
}


class UidStoreState : public SelectedState
{
    Q_OBJECT

public:
    UidStoreState() : SelectedState(IMAP_UIDStore, "UIDStore") { UidStoreState::init(); }

    void setParameters(MessageFlags flags, bool set, const QString &range);

    virtual bool permitsPipelining() const { return true; }
    virtual void init();
    virtual QString transmit(ImapContext *c);
    virtual void leave(ImapContext *);
    virtual void taggedResponse(ImapContext *c, const QString &line);

signals:
    void messageStored(const QString &uid);

private:
    // The list of flags/range pairs we're storing (via multiple commands), in order
    QList<QPair<QPair<MessageFlags, bool>, QString> > _parameters;
};

void UidStoreState::setParameters(MessageFlags flags, bool set, const QString &range)
{
    _parameters.append(qMakePair(qMakePair(flags, set), range));
}

void UidStoreState::init()
{
    SelectedState::init();
    _parameters.clear();
}

QString UidStoreState::transmit(ImapContext *c)
{
    const QPair<QPair<MessageFlags, bool>, QString> &params(_parameters.last());

    QString flagStr = QString("FLAGS.SILENT (%1)").arg(messageFlagsToString(params.first.first));
    return c->sendCommand(QString("UID STORE %1 %2%3").arg(params.second).arg(params.first.second ? '+' : '-').arg(flagStr));
}

void UidStoreState::leave(ImapContext *)
{
    SelectedState::init();
    _parameters.removeFirst();
}

void UidStoreState::taggedResponse(ImapContext *c, const QString &line)
{
    if (status() == OpOk) {
        const QPair<QPair<MessageFlags, bool>, QString> &params(_parameters.first());

        // Report all UIDs stored
        foreach (uint uid, sequenceUids(params.second))
            emit messageStored(messageUid(c->mailbox().id, QString::number(uid)));
    }

    SelectedState::taggedResponse(c, line);
}


class UidCopyState : public SelectedState
{
    Q_OBJECT

public:
    UidCopyState() : SelectedState(IMAP_UIDCopy, "UIDCopy") { UidCopyState::init(); }

    void setParameters(const QString &range, const QMailFolder &destination);

    virtual bool permitsPipelining() const { return true; }
    virtual void init();
    virtual QString transmit(ImapContext *c);
    virtual void leave(ImapContext *);
    virtual void taggedResponse(ImapContext *c, const QString &line);

signals:
    void messageCopied(const QString&, const QString&);

private:
    // The list of range/mailbox pairs we're copying (via multiple commands), in order
    QList<QPair<QString, QMailFolder> > _parameters;
};

void UidCopyState::setParameters(const QString &range, const QMailFolder &destination)
{
    _parameters.append(qMakePair(range, destination));
}

void UidCopyState::init()
{
    SelectedState::init();
    _parameters.clear();
}

QString UidCopyState::transmit(ImapContext *c)
{
    const QPair<QString, QMailFolder> &params(_parameters.last());

    return c->sendCommand(QString("UID COPY %1 %2").arg(params.first).arg(ImapProtocol::quoteString(params.second.path())));
}

void UidCopyState::leave(ImapContext *)
{
    SelectedState::init();
    _parameters.removeFirst();
}

void UidCopyState::taggedResponse(ImapContext *c, const QString &line)
{
    if (status() == OpOk) {
        const QPair<QString, QMailFolder> &params(_parameters.first());

        // See if we got a COPYUID response
        QRegExp copyuidResponsePattern("COPYUID (\\S+) (\\S+) ([^ \\t\\]]+)");
        copyuidResponsePattern.setCaseSensitivity(Qt::CaseInsensitive);
        if (copyuidResponsePattern.indexIn(line) != -1) {
            QList<uint> copiedUids = sequenceUids(copyuidResponsePattern.cap(2));
            QList<uint> createdUids = sequenceUids(copyuidResponsePattern.cap(3));

            // Report the completed copies
            if (copiedUids.count() != createdUids.count()) {
                qWarning() << "Mismatched COPYUID output:" << copiedUids << "!=" << createdUids;
            } else {
                const QString &mailbox();

                while (!copiedUids.isEmpty()) {
                    QString copiedUid(messageUid(c->mailbox().id, QString::number(copiedUids.takeFirst())));
                    QString createdUid(messageUid(params.second.id(), QString::number(createdUids.takeFirst())));

                    emit messageCopied(copiedUid, createdUid);
                }
            }
        } else {
            // Otherwise, report all UIDs copied, without the created UIDs
            foreach (uint uid, sequenceUids(params.first)) {
                emit messageCopied(messageUid(c->mailbox().id, QString::number(uid)), QString());
            }
        }
    }
    
    SelectedState::taggedResponse(c, line);
}


class ExpungeState : public SelectedState
{
    Q_OBJECT

public:
    ExpungeState() : SelectedState(IMAP_Expunge, "Expunge") {}

    virtual bool permitsPipelining() const { return true; }
    virtual QString transmit(ImapContext *c);
};

QString ExpungeState::transmit(ImapContext *c)
{
    return c->sendCommand("EXPUNGE");
}


class CloseState : public SelectedState
{
    Q_OBJECT

public:
    CloseState() : SelectedState(IMAP_Close, "Close") {}

    virtual bool permitsPipelining() const { return true; }
    virtual QString transmit(ImapContext *c);
    virtual void taggedResponse(ImapContext *c, const QString &line);
};

QString CloseState::transmit(ImapContext *c)
{
    return c->sendCommand("CLOSE");
}

void CloseState::taggedResponse(ImapContext *c, const QString &line)
{
    if (status() == OpOk) {
        // After a close, we no longer have a selected mailbox
        c->setMailbox(QMailFolder());
    }

    ImapState::taggedResponse(c, line);
}

class EnableState : public ImapState
{
    Q_OBJECT

public:
    EnableState() : ImapState(IMAP_Enable, "Enable") {}

    void setExtensions(const QString &extensions);

    virtual bool permitsPipelining() const { return true; }
    virtual void init();
    virtual QString transmit(ImapContext *c);
    virtual void leave(ImapContext *c);
    virtual void taggedResponse(ImapContext *c, const QString &line);

private:
    QStringList _extensionsList;
};

void EnableState::setExtensions(const QString &extensions)
{
    _extensionsList.append(extensions);
}

void EnableState::init()
{
    ImapState::init();
    _extensionsList.clear();
}

QString EnableState::transmit(ImapContext *c)
{
    QString cmd("ENABLE " + _extensionsList.last());
    return c->sendCommand(cmd);
}

void EnableState::leave(ImapContext *)
{
    ImapState::init();
    _extensionsList.removeFirst();
}

void EnableState::taggedResponse(ImapContext *c, const QString &line)
{
    ImapState::taggedResponse(c, line);
}

class NoopState : public SelectedState
{
    Q_OBJECT

public:
    NoopState() : SelectedState(IMAP_Noop, "Noop") {}

    virtual bool permitsPipelining() const { return true; }
    virtual QString transmit(ImapContext *c);
};

QString NoopState::transmit(ImapContext *c)
{
    QString cmd("NOOP");
    return c->sendCommand(cmd);
}

class FullState : public ImapState
{
    Q_OBJECT

public:
    FullState() : ImapState(IMAP_Full, "Full") { setStatus(OpFailed); }
};


class IdleState : public SelectedState
{
    Q_OBJECT

public:
    IdleState() : SelectedState(IMAP_Idle, "Idle") {}

    void done(ImapContext *c);

    virtual QString transmit(ImapContext *c);
    virtual bool continuationResponse(ImapContext *c, const QString &line);
    virtual void untaggedResponse(ImapContext *c, const QString &line);
};

void IdleState::done(ImapContext *c)
{
    c->sendData("DONE");
}

QString IdleState::transmit(ImapContext *c)
{
    return c->sendCommand("IDLE");
}

bool IdleState::continuationResponse(ImapContext *c, const QString &)
{
    c->continuation(command(), QString("idling"));
    return false;
}

void IdleState::untaggedResponse(ImapContext *c, const QString &line)
{
    QString str = line;
    QRegExp idleResponsePattern("\\*\\s+\\d+\\s+(\\w+)");
    quint32 previousExists = c->exists();
    SelectedState::untaggedResponse(c, line);
    if (idleResponsePattern.indexIn(str) == 0) {
        // Treat this event as a continuation point
        if (previousExists < c->exists()) { // '<' to avoid double check for expunges
             c->continuation(command(), QString("newmail"));
        } else if (idleResponsePattern.cap(1).compare("FETCH", Qt::CaseInsensitive) == 0) {
            c->continuation(command(), QString("flagschanged"));
        } else if (idleResponsePattern.cap(1).compare("EXPUNGE", Qt::CaseInsensitive) == 0) {
            c->continuation(command(), QString("flagschanged")); // flags check will find expunged messages
        }
    }
}

class CompressState : public ImapState
{
    Q_OBJECT

public:
    CompressState() : ImapState(IMAP_Compress, "Compress") {}

    virtual QString transmit(ImapContext *c);
    virtual void taggedResponse(ImapContext *c, const QString &line);
    virtual bool permitsPipelining() const { return true; }
};

QString CompressState::transmit(ImapContext *c)
{
    return c->sendCommand("COMPRESS DEFLATE");
}

void CompressState::taggedResponse(ImapContext *c, const QString &line)
{
    Q_UNUSED(line);
    c->protocol()->setCompress(true);
    ImapState::taggedResponse(c, line);
}



class ImapContextFSM : public ImapContext
{
public:
    ImapContextFSM(ImapProtocol *protocol); 

    UnconnectedState unconnectedState;
    InitState initState;
    CapabilityState capabilityState;
    StartTlsState startTlsState;
    LoginState loginState;
    LogoutState logoutState;
    ListState listState;
    GenUrlAuthState genUrlAuthState;
    AppendState appendState;
    SelectState selectState;
    QResyncState qresyncState;
    FetchFlagsState uidFetchFlagsState;
    ExamineState examineState;
    CreateState createState;
    DeleteState deleteState;
    EnableState enableState;
    NoopState noopState;
    RenameState renameState;
    MoveState moveState;
    SearchMessageState searchMessageState;
    SearchState searchState;
    UidSearchState uidSearchState;
    UidFetchState uidFetchState;
    UidStoreState uidStoreState;
    UidCopyState uidCopyState;
    ExpungeState expungeState;
    CloseState closeState;
    FullState fullState;
    IdleState idleState;
    CompressState compressState;

    virtual QString sendCommandLiteral(const QString &cmd, uint length);

    bool continuationResponse(const QString &line) { return state()->continuationResponse(this, line); }
    void untaggedResponse(const QString &line) { state()->untaggedResponse(this, line); }
    void taggedResponse(const QString &line) { state()->taggedResponse(this, line); }
    void literalResponse(const QString &line) { state()->literalResponse(this, line); }
    bool appendLiteralData(const QString &preceding) { return state()->appendLiteralData(this, preceding); }

    QString error(const QString &line) const { return state()->error(line); }

    void log(const QString &note) const { state()->log(note); }
    QString tag() const { return state()->tag(); }
    ImapCommand command() const { return state()->command(); }
    OperationStatus status() const { return state()->status(); }

    void setStatus(OperationStatus status) const { return state()->setStatus(status); }

    ImapState* state() const { return mState; }
    void reset();
    void setState(ImapState* s);
    void stateCompleted();

private:
    ImapState* mState;
    QList<QPair<ImapState*, QString> > mPendingStates;
};

ImapContextFSM::ImapContextFSM(ImapProtocol *protocol)
    : ImapContext(protocol),
      mState(&unconnectedState)
{ 
    reset();
}

QString ImapContextFSM::sendCommandLiteral(const QString &cmd, uint length)
{ 
    QString tag(ImapContext::sendCommandLiteral(cmd, length));

    if (protocol()->capabilities().contains("LITERAL+")) {
        // Send the continuation immediately
        while (continuationResponse(QString())) {
            // Keep sending continuations until there are no more
        }
    }

    return tag;
}

void ImapContextFSM::reset()
{
    // Clear any existing state we have accumulated
    while (!mPendingStates.isEmpty()) {
        QPair<ImapState*, QString> state(mPendingStates.takeFirst());
        state.first->init();
    }

    mState->init();
    mState = &unconnectedState;  
}

void ImapContextFSM::setState(ImapState* s)
{
    if (!mPendingStates.isEmpty() || (mState->status() == OpPending)) {
        // This state is not yet active, but its command will be pipelined
        if (!s->permitsPipelining()) {
            qMailLog(IMAP) << protocol()->objectName() << "Unable to issue command simultaneously:" << s->command();
            operationCompleted(s->command(), OpFailed);
        } else {
            s->log(protocol()->objectName() + "Tx:");
            QString tag = s->transmit(this);
            mPendingStates.append(qMakePair(s, tag));
        }
    } else {
        mState->leave(this);
        mState = s;

        // We can enter the new state and transmit its command
        mState->log(protocol()->objectName() + "Begin:");
        QString tag = mState->transmit(this);
        mState->enter(this);
        mState->setTag(tag);
    }
}

void ImapContextFSM::stateCompleted()
{
    if (!mPendingStates.isEmpty() && (mState->status() != OpPending)) {
        // Advance to the next state
        QPair<ImapState *, QString> nextState(mPendingStates.takeFirst());

        // See if we should close the existing state
        mState->leave(this);
        mState = nextState.first;

        // We can now enter the new state
        if (nextState.second.isEmpty()) {
            // This state has not transmitted a command yet
            mState->log(protocol()->objectName() + "Tx:");
            nextState.second = mState->transmit(this);
        }

        mState->log(protocol()->objectName() + "Begin:");
        mState->enter(this);
        mState->setTag(nextState.second);
    }
}


/* End state design pattern classes */

ImapProtocol::ImapProtocol()
    : _fsm(new ImapContextFSM(this)),
      _transport(0),
      _literalDataRemaining(0),
      _flatHierarchy(false),
      _delimiter(0),
      _authenticated(false),
      _receivedCapabilities(false)
{
    connect(&_incomingDataTimer, SIGNAL(timeout()), this, SLOT(incomingData()));
    connect(&_fsm->listState, SIGNAL(mailboxListed(QString, QString)),
            this, SIGNAL(mailboxListed(QString, QString)));
    connect(&_fsm->genUrlAuthState, SIGNAL(urlAuthorized(QString)),
            this, SIGNAL(urlAuthorized(QString)));
    connect(&_fsm->appendState, SIGNAL(messageCreated(QMailMessageId, QString)),
            this, SIGNAL(messageCreated(QMailMessageId, QString)));
    connect(&_fsm->uidFetchState, SIGNAL(downloadSize(QString, int)), 
            this, SIGNAL(downloadSize(QString, int)));
    connect(&_fsm->uidFetchState, SIGNAL(nonexistentUid(QString)), 
            this, SIGNAL(nonexistentUid(QString)));
    connect(&_fsm->uidStoreState, SIGNAL(messageStored(QString)), 
            this, SIGNAL(messageStored(QString)));
    connect(&_fsm->uidCopyState, SIGNAL(messageCopied(QString, QString)), 
            this, SIGNAL(messageCopied(QString, QString)));
    connect(&_fsm->createState, SIGNAL(folderCreated(QString, bool)),
            this, SIGNAL(folderCreated(QString, bool)));
    connect(&_fsm->deleteState, SIGNAL(folderDeleted(QMailFolder, bool)),
            this, SIGNAL(folderDeleted(QMailFolder, bool)));
    connect(&_fsm->renameState, SIGNAL(folderRenamed(QMailFolder, QString, bool)),
            this, SIGNAL(folderRenamed(QMailFolder, QString, bool)));
    connect(&_fsm->moveState, SIGNAL(folderMoved(QMailFolder, QString, QMailFolderId, bool)),
            this, SIGNAL(folderMoved(QMailFolder, QString, QMailFolderId, bool)));
}

ImapProtocol::~ImapProtocol()
{
    delete _transport;
    delete _fsm;
}

bool ImapProtocol::open( const ImapConfiguration& config, qint64 bufferSize)
{
    if ( _transport && _transport->inUse() ) {
        QString msg("Cannot open account; transport in use");
        qMailLog(IMAP) << objectName() << msg;
        emit connectionError(QMailServiceAction::Status::ErrConnectionInUse, msg);
        return false;
    }

    _fsm->reset(); // Recover from previously severed connection
    _fsm->setState(&_fsm->initState);

    _errorList.clear();

    _requestCount = 0;
    _stream.reset();
    _literalDataRemaining = 0;
    _precedingLiteral.clear();

    _mailbox = ImapMailboxProperties();
    _authenticated = false;
    _receivedCapabilities = false;

    if (!_transport) {
        _transport = new ImapTransport("IMAP");

        connect(_transport, SIGNAL(updateStatus(QString)),
                this, SIGNAL(updateStatus(QString)));
        connect(_transport, SIGNAL(errorOccurred(int,QString)),
                this, SLOT(errorHandling(int,QString)));
        connect(_transport, SIGNAL(connected(QMailTransport::EncryptType)),
                this, SLOT(connected(QMailTransport::EncryptType)));
        connect(_transport, SIGNAL(readyRead()),
                this, SLOT(incomingData()));
    }

    qMailLog(IMAP) << objectName() << "About to open connection" << config.mailUserName() << config.mailServer(); // useful to see object name
    _transport->open( config.mailServer(), config.mailPort(), static_cast<QMailTransport::EncryptType>(config.mailEncryption()));
    if (bufferSize) {
        qMailLog(IMAP) << objectName() << "Setting read buffer size to" << bufferSize;
        _transport->socket().setReadBufferSize(bufferSize);
    }

    return true;
}

void ImapProtocol::close()
{
    if (_transport)
        _transport->imapClose();
    _stream.reset();
    _fsm->reset();

    _mailbox = ImapMailboxProperties();
    _authenticated = false;
    _receivedCapabilities = false;
}

bool ImapProtocol::connected() const
{
    return (_transport && _transport->connected());
}

bool ImapProtocol::encrypted() const
{
    return (_transport && _transport->isEncrypted());
}

bool ImapProtocol::inUse() const
{
    return (_transport && _transport->inUse());
}

bool ImapProtocol::delimiterUnknown() const
{
    return !flatHierarchy() && delimiter().isNull();
}

bool ImapProtocol::flatHierarchy() const
{
    return _flatHierarchy;
}

void ImapProtocol::setFlatHierarchy(bool flat)
{
    _flatHierarchy = flat;
}

QChar ImapProtocol::delimiter() const
{
    return _delimiter;
}

void ImapProtocol::setDelimiter(QChar delimiter)
{
    _delimiter = delimiter;
}

bool ImapProtocol::compress() const
{
    return _transport->compress();
}

void ImapProtocol::setCompress(bool comp)
{
    _transport->setCompress(comp);
}

bool ImapProtocol::authenticated() const
{
    return _authenticated;
}

void ImapProtocol::setAuthenticated(bool auth)
{
    _authenticated = auth;
}

// capabilities info has been sent by server, possibly as a result of unsolicited response.
bool ImapProtocol::receivedCapabilities() const
{
    return _receivedCapabilities;
}

void ImapProtocol::setReceivedCapabilities(bool received)
{
    _receivedCapabilities = received;
}

bool ImapProtocol::loggingOut() const
{
    return _fsm->state() == &_fsm->logoutState;
}

const QStringList &ImapProtocol::capabilities() const
{
    return _capabilities;
}

void ImapProtocol::setCapabilities(const QStringList &newCapabilities)
{
    setReceivedCapabilities(true);
    _capabilities = newCapabilities;
}

bool ImapProtocol::supportsCapability(const QString& name) const
{
    return _capabilities.contains(name);
}

void ImapProtocol::sendCapability()
{
    _fsm->setState(&_fsm->capabilityState);
}

void ImapProtocol::sendStartTLS()
{
    _fsm->setState(&_fsm->startTlsState);
}

void ImapProtocol::sendLogin( const QMailAccountConfiguration &config )
{
    _fsm->loginState.setConfiguration(config, _capabilities);
    _fsm->setState(&_fsm->loginState);
}

void ImapProtocol::sendLogout()
{
    _fsm->setState(&_fsm->logoutState);
}

void ImapProtocol::sendNoop()
{
    _fsm->setState(&_fsm->noopState);
}

void ImapProtocol::sendIdle()
{
    _fsm->setState(&_fsm->idleState);
}

void ImapProtocol::sendIdleDone()
{
    if (_fsm->state() == &_fsm->idleState)
        _fsm->idleState.done(_fsm);
}

void ImapProtocol::sendCompress()
{
    _fsm->setState(&_fsm->compressState);
}

void ImapProtocol::sendList( const QMailFolder &reference, const QString &mailbox )
{
    QString path;
    if (!reference.path().isEmpty()) {
        path = reference.path();
    }

    if (!path.isEmpty()) {
        // If we don't have the delimiter for this account, we need to discover it
        if (delimiterUnknown()) {
            sendDiscoverDelimiter();
        }
    }


    // Now request the actual list
    _fsm->listState.setParameters(path, mailbox, capabilities().contains("XLIST"));
    _fsm->setState(&_fsm->listState);
}

void ImapProtocol::sendDiscoverDelimiter()
{
    _fsm->listState.setDiscoverDelimiter();
    _fsm->setState(&_fsm->listState);
}

void ImapProtocol::sendGenUrlAuth(const QMailMessagePart::Location &location, bool bodyOnly, const QString &mechanism)
{
    QString dataUrl(url(location, true, bodyOnly));

    _fsm->genUrlAuthState.setUrl(dataUrl, mechanism);
    _fsm->setState(&_fsm->genUrlAuthState);
}

void ImapProtocol::sendAppend(const QMailFolder &mailbox, const QMailMessageId &messageId)
{
    _fsm->appendState.setParameters(mailbox, messageId);
    _fsm->setState(&_fsm->appendState);
}

void ImapProtocol::sendSelect(const QMailFolder &mailbox)
{
    _fsm->selectState.setMailbox(mailbox);
    _fsm->setState(&_fsm->selectState);
}

void ImapProtocol::sendQResync(const QMailFolder &mailbox)
{
    _fsm->qresyncState.setMailbox(mailbox);
    _fsm->setState(&_fsm->qresyncState);
}

void ImapProtocol::sendExamine(const QMailFolder &mailbox)
{
    _fsm->examineState.setMailbox(mailbox);
    _fsm->setState(&_fsm->examineState);
}

void ImapProtocol::sendCreate(const QMailFolderId &parentFolderId, const QString &name)
{
    QString mailboxPath;
    if(parentFolderId.isValid())
    {
        if (delimiterUnknown()) {
            sendDiscoverDelimiter();
        }
    }
    _fsm->createState.setMailbox(parentFolderId, name);
    _fsm->setState(&_fsm->createState);
}

void ImapProtocol::sendDelete(const QMailFolder &mailbox)
{
    _fsm->deleteState.setMailbox(mailbox);
    _fsm->setState(&_fsm->deleteState);
}

void ImapProtocol::sendRename(const QMailFolder &mailbox, const QString &newName)
{
    if (delimiterUnknown()) {
        sendDiscoverDelimiter();
    }
    _fsm->renameState.setNewMailboxName(mailbox, newName);
    _fsm->setState(&_fsm->renameState);
}

void ImapProtocol::sendMove(const QMailFolder &mailbox, const QMailFolderId &newParentId)
{
    if (delimiterUnknown()) {
        sendDiscoverDelimiter();
    }
    _fsm->moveState.setNewMailboxParent(mailbox, newParentId);
    _fsm->setState(&_fsm->moveState);
}

void ImapProtocol::sendSearchMessages(const QMailMessageKey &key, const QString &body, const QMailMessageSortKey &sort, bool count)
{
    _fsm->searchMessageState.setParameters(key, body, sort, count);
    _fsm->setState(&_fsm->searchMessageState);
}


void ImapProtocol::sendSearch(MessageFlags flags, const QString &range)
{
    _fsm->searchState.setParameters(flags, range);
    _fsm->setState(&_fsm->searchState);
}

void ImapProtocol::sendUidSearch(MessageFlags flags, const QString &range)
{
    _fsm->uidSearchState.setParameters(flags, range);
    _fsm->setState(&_fsm->uidSearchState);
}

void ImapProtocol::sendFetchFlags(const QString &range, const QString &prefix)
{
    _fsm->uidFetchFlagsState.setProperties(range, prefix);
    _fsm->setState(&_fsm->uidFetchFlagsState);
}

void ImapProtocol::sendUidFetch(FetchItemFlags items, const QString &uidList)
{
    _fsm->uidFetchState.setUidList(uidList, (items | F_Flags));
    _fsm->setState(&_fsm->uidFetchState);
}

void ImapProtocol::sendUidFetchSection(const QString &uid, const QString &section, int start, int end)
{
    _fsm->uidFetchState.setSection(uid, section, start, end, (F_Uid | F_BodySection));
    _fsm->setState(&_fsm->uidFetchState);
}

void ImapProtocol::sendUidFetchSectionHeader(const QString &uid, const QString &section)
{
    _fsm->uidFetchState.setSection(uid, section, 0, -1, (F_Uid | F_SectionHeader));
    _fsm->setState(&_fsm->uidFetchState);
}

void ImapProtocol::sendUidStore(MessageFlags flags, bool set, const QString &range)
{
    _fsm->uidStoreState.setParameters(flags, set, range);
    _fsm->setState(&_fsm->uidStoreState);
}

void ImapProtocol::sendUidCopy(const QString &range, const QMailFolder &destination)
{
    _fsm->uidCopyState.setParameters(range, destination);
    _fsm->setState(&_fsm->uidCopyState);
}

void ImapProtocol::sendExpunge()
{
    _fsm->setState(&_fsm->expungeState);
}

void ImapProtocol::sendClose()
{
    _fsm->setState(&_fsm->closeState);
}

void ImapProtocol::sendEnable(const QString &extensions)
{
    _fsm->enableState.setExtensions(extensions);
    _fsm->setState(&_fsm->enableState);
}

void ImapProtocol::connected(QMailTransport::EncryptType encryptType)
{
#ifndef QT_NO_SSL
    if (encryptType == QMailTransport::Encrypt_TLS) {
        emit completed(IMAP_StartTLS, OpOk);
    }
#else
    Q_UNUSED(encryptType);
#endif
}

void ImapProtocol::errorHandling(int status, QString msg)
{
    _mailbox = ImapMailboxProperties();

    if (msg.isEmpty())
        msg = tr("Connection failed");

    if (_fsm->command() != IMAP_Logout)
        emit connectionError(status, msg);
}

void ImapProtocol::sendData(const QString &cmd, bool maskDebug)
{
    QByteArray output(cmd.toLatin1());
    output.append("\r\n");
    _transport->imapWrite(&output);

    if (maskDebug) {
        qMailLog(IMAP) << objectName() << (compress() ? "SENDC:" : "SEND") << "SEND: <login hidden>";
    } else {
        QString logCmd(cmd);
        QRegExp authExp("^[^\\s]+\\sAUTHENTICATE\\s[^\\s]+\\s");
        if (authExp.indexIn(cmd) != -1) {
            logCmd = cmd.left(authExp.matchedLength()) + "<password hidden>";
        } else {
            QRegExp loginExp("^[^\\s]+\\sLOGIN\\s[^\\s]+\\s");
            if (loginExp.indexIn(cmd) != -1) {
                logCmd = cmd.left(loginExp.matchedLength()) + "<password hidden>";
            }
        }
        qMailLog(IMAP) << objectName() << (compress() ? "SENDC:" : "SEND") << qPrintable(logCmd);}
}

void ImapProtocol::sendDataLiteral(const QString &cmd, uint length)
{
    QString trailer(" {%1%2}");
    trailer = trailer.arg(length);
    trailer = trailer.arg(capabilities().contains("LITERAL+") ? "+" : "");

    sendData(cmd + trailer);
}

QString ImapProtocol::sendCommand(const QString &cmd)
{
    QString tag = newCommandId();

    _stream.reset();
    sendData(tag + ' ' + cmd);

    return tag;
}

QString ImapProtocol::sendCommandLiteral(const QString &cmd, uint length)
{
    QString trailer(" {%1%2}");
    trailer = trailer.arg(length);
    trailer = trailer.arg(capabilities().contains("LITERAL+") ? "+" : "");

    return sendCommand(cmd + trailer);
}

void ImapProtocol::incomingData()
{
    if (!_lineBuffer.isEmpty() && _transport->imapCanReadLine()) {
        processResponse(QString::fromLatin1(_lineBuffer + _transport->imapReadLine()));
        _lineBuffer.clear();
    }

    int readLines = 0;
    while (_transport->imapCanReadLine()) {
        processResponse(QString::fromLatin1(_transport->imapReadLine()));

        readLines++;
        if (readLines >= MAX_LINES) {
            _incomingDataTimer.start(0);
            return;
        }
    }

    if (_transport->bytesAvailable()) {
        // If there is an incomplete line, read it from the socket buffer to ensure we get readyRead signal next time
        _lineBuffer.append(_transport->readAll());
    }

    _incomingDataTimer.stop();
}

void ImapProtocol::continuation(ImapCommand command, const QString &recv)
{
    clearResponse();

    emit continuationRequired(command, recv);
}

void ImapProtocol::operationCompleted(ImapCommand command, OperationStatus status)
{
    _fsm->state()->log(objectName() + "End:");
    clearResponse();

    emit completed(command, status);
}

void ImapProtocol::clearResponse()
{
    _stream.reset();
}

int ImapProtocol::literalDataRemaining() const
{
    return _literalDataRemaining;
}

void ImapProtocol::setLiteralDataRemaining(int literalDataRemaining)
{
    _literalDataRemaining = literalDataRemaining;
}

QString ImapProtocol::precedingLiteral() const
{
    return _precedingLiteral;
}

void ImapProtocol::setPrecedingLiteral(const QString &line)
{
    _precedingLiteral = line;
}

bool ImapProtocol::checkSpace()
{
    if (_stream.status() == LongStream::OutOfSpace) {
        _lastError += LongStream::errorMessage( QString('\n') );
        clearResponse();
        return false;
    }

    return true;
}

void ImapProtocol::processResponse(QString line)
{
    int outstandingLiteralData = literalDataRemaining();
    if (outstandingLiteralData > 0) {
        // This should be a literal data response
        QString literal, remainder;

        // See if there is any line data trailing the embedded literal data
        int excess = line.length() - outstandingLiteralData;
        if (excess > 0) {
            literal = line.left(outstandingLiteralData);
            remainder = line.right(excess);
        } else {
            literal = line;
        }

        // Process the literal data line
        if (literal.length() > 1) {
            qMailLog(ImapData) << objectName() << qPrintable(literal.left(literal.length() - 2));
        }

        _stream.append(literal);
        if (!checkSpace()) {
            _fsm->setState(&_fsm->fullState);
            operationCompleted(_fsm->command(), _fsm->status());
        }

        outstandingLiteralData -= literal.length();
        setLiteralDataRemaining(outstandingLiteralData);

        _fsm->literalResponse(literal);

        if (outstandingLiteralData == 0) {
            // We have received all the literal data
            qMailLog(IMAP) << objectName() << qPrintable(QString("RECV: <%1 literal bytes received>").arg(_stream.length()));
            if (remainder.length() > 2) {
                qMailLog(IMAP) << objectName() << "RECV:" << qPrintable(remainder.left(remainder.length() - 2));
            }

            _unprocessedInput = precedingLiteral();
            if (_fsm->appendLiteralData(precedingLiteral())) {
                // Append this literal data to the preceding line data
                _unprocessedInput.append(_stream.readAll());
            }

            setPrecedingLiteral(QString());

            if (remainder.endsWith("\n")) {
                // Is this trailing part followed by a literal data segment?
                QRegExp literalPattern("\\{(\\d*)\\}\\r?\\n");
                int literalIndex = literalPattern.indexIn(remainder);
                if (literalIndex != -1) {
                    // We are waiting for literal data to complete this line
                    setPrecedingLiteral(_unprocessedInput + remainder.left(literalIndex));
                    setLiteralDataRemaining(literalPattern.cap(1).toInt());
                    _stream.reset();
                }

                // Process the line that contained the literal data
                nextAction(_unprocessedInput + remainder);
                _unprocessedInput.clear();
            } else {
                _unprocessedInput.append(remainder);
            }
        }
    } else {
        if (line.length() > 1) {
            qMailLog(IMAP) << objectName() << "RECV:" << qPrintable(line.left(line.length() - 2));
        }

        // Is this line followed by a literal data segment?
        QRegExp literalPattern("\\{(\\d*)\\}\\r?\\n");
        int literalIndex = literalPattern.indexIn(line);
        if (literalIndex != -1) {
            // We are waiting for literal data to complete this line
            setPrecedingLiteral(line.left(literalIndex));
            setLiteralDataRemaining(literalPattern.cap(1).toInt());
            _stream.reset();
        }

        // Do we have any preceding input to add to this?
        if (!_unprocessedInput.isEmpty()) {
            line.prepend(_unprocessedInput);
            _unprocessedInput.clear();
        }

        // Process this line
        nextAction(line);
    }
}

void ImapProtocol::nextAction(const QString &line)
{
    // We have a completed line to process
    if (!_fsm->tag().isEmpty() && line.startsWith(_fsm->tag())) {
        // Tagged response
        _fsm->setStatus(commandResponse(line));
        if (_fsm->status() != OpOk) {
            _lastError = _fsm->error(line);
            _fsm->log(objectName() + "End:");
            operationCompleted(_fsm->command(), _fsm->status());
            return;
        }
        
        _fsm->taggedResponse(line);
        clearResponse();

        // This state has now completed
        _fsm->stateCompleted();
    } else {
        if ((line.length() > 0) && (line.at(0) == '+')) {
            // Continuation
            _fsm->continuationResponse(line.mid(1).trimmed());
        } else {
            // Untagged response
            _fsm->untaggedResponse(line);
            if (!checkSpace()) {
                _fsm->setState(&_fsm->fullState);
                operationCompleted(_fsm->command(), _fsm->status());
            }
        }
    }
}

QString ImapProtocol::newCommandId()
{
    QString id, out;

    _requestCount++;
    id.setNum( _requestCount );
    out = "a";
    out = out.leftJustified( 4 - id.length(), '0' );
    out += id;
    return out;
}

QString ImapProtocol::commandId( QString in )
{
    int pos = in.indexOf(' ');
    if (pos == -1)
        return "";

    return in.left( pos ).trimmed();
}

OperationStatus ImapProtocol::commandResponse( QString in )
{
    QString old = in;
    int start = in.indexOf( ' ' );
    start = in.indexOf( ' ', start );
    int stop = in.indexOf( ' ', start + 1 );
    if (start == -1 || stop == -1) {
        qMailLog(IMAP) << objectName() << qPrintable("could not parse command response: " + in);
        return OpFailed;
    }

    in = in.mid( start, stop - start ).trimmed().toUpper();
    OperationStatus status = OpFailed;

    if (in == "OK")
        status = OpOk;
    if (in == "NO")
        status = OpNo;
    if (in == "BAD")
        status = OpBad;

    return status;
}

QString ImapProtocol::uid( const QString &identifier )
{
    return messageId(identifier);
}

QString ImapProtocol::url(const QMailMessagePart::Location &location, bool absolute, bool bodyOnly)
{
    QString result;

    QMailMessageId id(location.containingMessageId());
    QMailMessageMetaData metaData(id);
    QMailAccountConfiguration config(metaData.parentAccountId());
    ImapConfiguration imapCfg(config);

    if (metaData.parentAccountId().isValid()) {
        if (absolute) {
            result.append("imap://");

            if (!imapCfg.mailUserName().isEmpty()) {
                result.append(QUrl::toPercentEncoding(imapCfg.mailUserName()));
                result.append('@');
            }
            result.append(imapCfg.mailServer());
            
            if (imapCfg.mailPort() != 143) {
                result.append(':').append(QString::number(imapCfg.mailPort()));
            }
        }
        
        result.append('/');

        if (QMailDisconnected::sourceFolderId(metaData).isValid()) {
            QMailFolder folder(QMailDisconnected::sourceFolderId(metaData));

            result.append(folder.path()).append('/');
        }

        result.append(";uid=").append(uid(metaData.serverUid()));

        if (location.isValid(false)) {
            result.append("/;section=").append(location.toString(false));
        } else if (bodyOnly) {
            result.append("/;section=TEXT");
        }
        
        if (!imapCfg.mailUserName().isEmpty()) {
            result.append(";urlauth=submit+");
            result.append(QUrl::toPercentEncoding(imapCfg.mailUserName()));
        } else {
            qWarning() << "url auth, no user name found";
        }
    }

    return result;
}

// Remove escape characters when receiving from IMAP
QString ImapProtocol::unescapeFolderPath(const QString &path)
{
    QString result(path);
    QString::iterator it = result.begin();
    while (it != result.end()) {
        if ((*it) == '\\') {
            int pos = (it - result.begin());
            result.remove(pos, 1);
            it = result.begin() + pos;
            if (it == result.end()) {
                break;
            }
        }
        ++it;
    }
    return result;
}

// Ensure a string is quoted, if required for IMAP transmission
QString ImapProtocol::quoteString(const QString& input)
{
    // We can't easily catch controls other than those caught by \\s...
    QRegExp atomSpecials("[\\(\\)\\{\\s\\*%\\\\\"\\]]");

    // The empty string must be quoted
    if (input.isEmpty())
        return QString("\"\"");

    if (atomSpecials.indexIn(input) == -1)
        return input;
        
    // We need to quote this string because it is not an atom
    QString result(input);

    QString::iterator it = result.begin();
    while (it != result.end()) {
        // We need to escape any characters specially treated in quotes
        if ((*it) == '\\' || (*it) == '"') {
            int pos = (it - result.begin());
            result.insert(pos, '\\');
            it = result.begin() + (pos + 1);
        }
        ++it;
    }

    return QMail::quoteString(result);
}

QByteArray ImapProtocol::quoteString(const QByteArray& input)
{
    return quoteString(QString(input)).toLatin1();
}

void ImapProtocol::createMail(const QString &uid, const QDateTime &timeStamp, int size, uint flags, const QString &detachedFile, const QStringList& structure)
{
    QMailMessage mail;
    if ( !structure.isEmpty() ) {
        mail = QMailMessage::fromSkeletonRfc2822File( detachedFile );
        bool wellFormed = setMessageContentFromStructure( structure, &mail );

        if (wellFormed && (mail.multipartType() != QMailMessage::MultipartNone)) {
            mail.setStatus( QMailMessage::ContentAvailable, true );
            mail.setSize( size );
        }

        // If we're fetching the structure, this is the first we've seen of this message
        mail.setStatus( QMailMessage::New, true );
    } else {
        // No structure - we're fetching the body of a message we already know about
        mail = QMailMessage::fromRfc2822File( detachedFile );
        mail.setStatus( QMailMessage::ContentAvailable, true );
    }

    if (mail.status() & QMailMessage::ContentAvailable) {
        // ContentAvailable must also imply partial content available
        mail.setStatus( QMailMessage::PartialContentAvailable, true );
    }

    if (flags & MFlag_Seen) {
        mail.setStatus( QMailMessage::ReadElsewhere, true );
        mail.setStatus( QMailMessage::Read, true );
    }
    if (flags & MFlag_Flagged) {
        mail.setStatus( QMailMessage::ImportantElsewhere, true );
        mail.setStatus( QMailMessage::Important, true );
    }
    if (flags & MFlag_Answered) {
        mail.setStatus( QMailMessage::Replied, true );
    }
    if (flags & MFlag_Deleted) {
        mail.setStatus( QMailMessage::Removed, true);
    }

    mail.setMessageType( QMailMessage::Email );
    mail.setSize( size );
    mail.setServerUid( uid.trimmed() );
    mail.setReceivedDate( QMailTimeStamp( timeStamp ) );

    // The file we wrote to is detached, and the mailstore can assume ownership

    emit messageFetched(mail, detachedFile, !structure.isEmpty());

    // Workaround for message buffer file being deleted
    QFileInfo newFile(_fsm->buffer().fileName());
    if (!newFile.exists()) {
        qWarning() << "Unable to find message buffer file";
        _fsm->buffer().detach();
    }
}

void ImapProtocol::createPart(const QString &uid, const QString &section, const QString &detachedFile, int size)
{
    emit dataFetched(uid, section, detachedFile, size);

    // Workaround for message part buffer file being deleted
    QFileInfo newFile(_fsm->buffer().fileName());
    if (!newFile.exists()) {
        qWarning() << "Unable to find message part buffer file";
        _fsm->buffer().detach();
    }
}

void ImapProtocol::createPartHeader(const QString &uid, const QString &section, const QString &detachedFile, int size)
{
    emit partHeaderFetched(uid, section, detachedFile, size);

    // Workaround for message part buffer file being deleted
    QFileInfo newFile(_fsm->buffer().fileName());
    if (!newFile.exists()) {
        qWarning() << "Unable to find message part buffer file";
        _fsm->buffer().detach();
    }
}

#include "imapprotocol.moc"