File: imap-handle.c

package info (click to toggle)
balsa 2.4.12-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd, wheezy
  • size: 21,456 kB
  • ctags: 8,303
  • sloc: ansic: 93,724; xml: 13,662; sh: 11,146; makefile: 615; awk: 60
file content (4632 lines) | stat: -rw-r--r-- 120,581 bytes parent folder | download | duplicates (2)
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
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
/* libimap library.
 * Copyright (C) 2003-2010 Pawel Salek.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option) 
 * any later version.
 *  
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the  
 * GNU General Public License for more details.
 *  
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  
 * 02111-1307, USA.
 */
#include "config.h"

#define _POSIX_C_SOURCE 199506L
#define _XOPEN_SOURCE 500
#define _BSD_SOURCE     1

#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <glib.h>
#include <glib-object.h>
#include <ctype.h>

#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>
#include <unistd.h>
#include <gmime/gmime-utils.h>

#if defined(HAVE_RES_INIT)
#include <netinet/in.h>
#include <arpa/nameser.h>
#include <resolv.h>
#endif                          /* defined(HAVE_RES_INIT) */

#if defined(USE_TLS)
#include <openssl/ssl.h>
#include <openssl/err.h>
#endif

#include "libimap-marshal.h"
#include "imap-auth.h"
#include "imap-handle.h"
#include "imap-commands.h"
#include "imap_private.h"
#include "siobuf.h"
#include "util.h"

#define ASYNC_DEBUG 0

#define LONG_STRING 512
#define ELEMENTS(x) (sizeof (x) / sizeof(x[0]))

#define IDLE_TIMEOUT 30

#define LIT_TYPE_HANDLE \
    (imap_mbox_handle_get_type())
#define IMAP_MBOX_HANDLE(obj) \
    (G_TYPE_CHECK_INSTANCE_CAST(obj, LIT_TYPE_HANDLE, ImapMboxHandle))
#define IMAP_MBOX_HANDLE_CLASS(klass) \
    (G_TYPE_CHECK_CLASS_CAST(klass, LIT_TYPE_HANDLE, \
                             ImapMboxHandleClass))
#define LIT_IS_HANDLE(obj) \
    (G_TYPE_CHECK_INSTANCE_TYPE(obj, LIT_TYPE_HANDLE))
#define LIT_IS_HANDLE_CLASS(klass) \
    (G_TYPE_CHECK_CLASS_TYPE(klass, LIT_TYPE_HANDLE))


struct _ImapMboxHandleClass {
  GObjectClass parent_class;
  /* Signal */
  void (*fetch_response)(ImapMboxHandle* handle);
  void (*list_response)(ImapMboxHandle* handle, int delim,
                        ImapMboxFlags flags, const gchar* mbox);
  void (*lsub_response)(ImapMboxHandle* handle, int delim,
                        ImapMboxFlags flags, const gchar* mbox);
  void (*expunge_notify)(ImapMboxHandle* handle, int seqno);
  void (*exists_notify)(ImapMboxHandle* handle);
};

enum _ImapHandleSignal {
  FETCH_RESPONSE,
  LIST_RESPONSE,
  LSUB_RESPONSE,
  EXPUNGE_NOTIFY,
  EXISTS_NOTIFY,
  LAST_SIGNAL
};
typedef enum _ImapHandleSignal ImapHandleSignal;

static GObjectClass *parent_class = NULL;
static guint imap_mbox_handle_signals[LAST_SIGNAL] = { 0 };

static void imap_mbox_handle_init(ImapMboxHandle *handle);
static void imap_mbox_handle_class_init(ImapMboxHandleClass * klass);
static void imap_mbox_handle_finalize(GObject* handle);

static ImapResult imap_mbox_connect(ImapMboxHandle* handle);

static ImapResponse ir_handle_response(ImapMboxHandle *h);

static ImapAddress* imap_address_from_string(const gchar *string, gchar **n);
static gchar*       imap_address_to_string(const ImapAddress *addr);

static GType
imap_mbox_handle_get_type()
{
  static GType imap_mbox_handle_type = 0;

  if(!imap_mbox_handle_type) {
    static const GTypeInfo imap_mbox_handle_info = {
      sizeof(ImapMboxHandleClass),
      NULL,               /* base_init */
      NULL,               /* base_finalize */
      (GClassInitFunc) imap_mbox_handle_class_init,
      NULL,               /* class_finalize */
      NULL,               /* class_data */
      sizeof(ImapMboxHandle),
      0,                  /* n_preallocs */
      (GInstanceInitFunc) imap_mbox_handle_init
    };
    imap_mbox_handle_type =
      g_type_register_static(G_TYPE_OBJECT, "ImapMboxHandle",
                             &imap_mbox_handle_info, 0);
  }
  return imap_mbox_handle_type;
}

static void
imap_mbox_handle_init(ImapMboxHandle *handle)
{
  handle->host   = NULL;
  handle->mbox   = NULL;
  handle->timeout = -1;
  handle->state  = IMHS_DISCONNECTED;
  handle->has_capabilities = FALSE;
  handle->exists = 0;
  handle->recent = 0;
  handle->last_msg = NULL;
  handle->msg_cache = NULL;
  handle->flag_cache=  g_array_new(FALSE, TRUE, sizeof(ImapFlagCache));
  handle->doing_logout = FALSE;
#ifdef USE_TLS
  handle->using_tls = 0;
#endif
  handle->tls_mode = IMAP_TLS_ENABLED;
  handle->idle_state = IDLE_INACTIVE;
  handle->cmd_info = NULL;
  handle->status_resps = g_hash_table_new_full(g_str_hash, g_str_equal,
                                               NULL, NULL);

  handle->info_cb  = NULL;
  handle->info_arg = NULL;
  handle->op_cancelled = 0;
  handle->enable_anonymous = 0;
  handle->enable_client_sort = 0;
  handle->enable_binary    = 0;
  handle->enable_idle      = 1;

  handle->has_rights = 0;
  mbox_view_init(&handle->mbox_view);

#if defined(BALSA_USE_THREADS)
  pthread_mutex_init(&handle->mutex, NULL);
#endif
}

static void
imap_mbox_handle_class_init(ImapMboxHandleClass * klass)
{
  GObjectClass *object_class = G_OBJECT_CLASS(klass);
  
  parent_class = g_type_class_peek_parent(klass);
  imap_mbox_handle_signals[FETCH_RESPONSE] = 
    g_signal_new("fetch-response",
                 G_TYPE_FROM_CLASS(object_class),
                 G_SIGNAL_RUN_FIRST,
                 G_STRUCT_OFFSET(ImapMboxHandleClass, fetch_response),
                 NULL, NULL,
                 g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);

  imap_mbox_handle_signals[LIST_RESPONSE] = 
    g_signal_new("list-response",
                 G_TYPE_FROM_CLASS(object_class),
                 G_SIGNAL_RUN_FIRST,
                 G_STRUCT_OFFSET(ImapMboxHandleClass, list_response),
                 NULL, NULL,
                 libimap_VOID__INT_INT_POINTER, G_TYPE_NONE, 3,
                 G_TYPE_INT, G_TYPE_INT, G_TYPE_POINTER);

  imap_mbox_handle_signals[LSUB_RESPONSE] = 
    g_signal_new("lsub-response",
                 G_TYPE_FROM_CLASS(object_class),
                 G_SIGNAL_RUN_FIRST,
                 G_STRUCT_OFFSET(ImapMboxHandleClass, lsub_response),
                 NULL, NULL,
                 libimap_VOID__INT_INT_POINTER, G_TYPE_NONE, 3,
                 G_TYPE_INT, G_TYPE_INT, G_TYPE_POINTER);

  imap_mbox_handle_signals[EXPUNGE_NOTIFY] = 
    g_signal_new("expunge-notify",
                 G_TYPE_FROM_CLASS(object_class),
                 G_SIGNAL_RUN_FIRST,
                 G_STRUCT_OFFSET(ImapMboxHandleClass, expunge_notify),
                 NULL, NULL,
                 g_cclosure_marshal_VOID__INT, G_TYPE_NONE, 1,
		 G_TYPE_INT);

  imap_mbox_handle_signals[EXISTS_NOTIFY] = 
    g_signal_new("exists-notify",
                 G_TYPE_FROM_CLASS(object_class),
                 G_SIGNAL_RUN_FIRST,
                 G_STRUCT_OFFSET(ImapMboxHandleClass, exists_notify),
                 NULL, NULL,
                 g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);

  object_class->finalize = imap_mbox_handle_finalize;
}

ImapMboxHandle*
imap_mbox_handle_new(void)
{
  ImapMboxHandle *handle = g_object_new(LIT_TYPE_HANDLE, NULL);
  return handle;
}

void
imap_handle_set_option(ImapMboxHandle *h, ImapOption opt, gboolean state)
{
  switch(opt) {
  case IMAP_OPT_ANONYMOUS:   h->enable_anonymous   = !!state; break;
  case IMAP_OPT_BINARY:      h->enable_binary      = !!state; break;
  case IMAP_OPT_CLIENT_SORT: h->enable_client_sort = !!state; break;
  case IMAP_OPT_COMPRESS:    h->enable_compress    = !!state; break;
  case IMAP_OPT_IDLE:        h->enable_idle        = !!state; break;
  default: g_warning("imap_set_option: invalid option\n");
  }
}

void
imap_handle_set_infocb(ImapMboxHandle* h, ImapInfoCb cb, void *arg)
{
  h->info_cb  = cb;
  h->info_arg = arg;
}

void
imap_handle_set_usercb(ImapMboxHandle* h, ImapUserCb cb, void *arg)
{
  h->user_cb  = cb;
  h->user_arg = arg;
}

void
imap_handle_set_monitorcb(ImapMboxHandle* h, ImapMonitorCb cb, void*arg)
{
  h->monitor_cb  = cb;
  h->monitor_arg = arg;
}

void
imap_handle_set_flagscb(ImapMboxHandle* h, ImapFlagsCb cb, void* arg)
{
  h->flags_cb  = cb;
  h->flags_arg = arg;
}

/** CmdInfo structure stores information about asynchronously executed
    commands. */
struct CmdInfo {
  unsigned cmdno; /**< Number of the the command */
  ImapResponse rc; /**< response code to the command if it already completed */
  /** complete_cb is executed when the given command is completed.  If
      complete_cb returns true, the corresponding CmdInfo structure
      will be removed from the cmd_info hash.*/
  gboolean (*complete_cb)(ImapMboxHandle *h, void *d);
  void *cb_data; /**< data to be passed on to complete_cb */
  unsigned completed; /**< determines whether the complete_cb has been
                       * executed and rc contains meaningful value. */
};

/** cmdi_get_pending returns number of any pending command. Returns 0
    if there is none. */
static unsigned
cmdi_get_pending(GList *cmd_info)
{
  for(; cmd_info; cmd_info = cmd_info->next) {
    struct CmdInfo *ci = (struct CmdInfo*)cmd_info->data;
    if(!ci->completed)
      return ci->cmdno;
  }
  return 0;
}

static void
cmdi_add_handler(GList **cmd_info, unsigned cmdno,
                 gboolean (*handler)(ImapMboxHandle*h, void *d), void *data)
{
  struct CmdInfo *ci = g_new0(struct CmdInfo, 1);
  ci->cmdno = cmdno;
  ci->complete_cb = handler;
  ci->cb_data = data;
  *cmd_info = g_list_prepend(*cmd_info, ci);
}

static struct CmdInfo*
cmdi_find_by_no(GList *cmd_info, unsigned lastcmd)
{
  for(; cmd_info; cmd_info = cmd_info->next) {
    struct CmdInfo *ci = (struct CmdInfo*)cmd_info->data;
    if(ci->cmdno == lastcmd)
      return ci;
  }
  return NULL;
}

/** fallback handler - consider the command done and remove the
    corresponding CmdInfo structure from the list of pending
    commands. */
static gboolean
cmdi_empty(ImapMboxHandle *h, void *d)
{ return TRUE; }

/** Sets new timeout. Returns the old one. */
int
imap_handle_set_timeout(ImapMboxHandle *h, int milliseconds)
{
  int old_timeout = h->timeout;
  h->timeout = milliseconds;
  if(h->sio)
    sio_set_timeout(h->sio, milliseconds);
  return old_timeout;
}

/** Called with a locked handle. */
static gboolean
async_process_real(ImapMboxHandle *h)
{
  ImapResponse rc = IMR_UNTAGGED;
  unsigned async_cmd;
  int retval;

  async_cmd = cmdi_get_pending(h->cmd_info);
  if(ASYNC_DEBUG) printf("async_process() enter loop\n");
  while( (retval = sio_poll(h->sio, TRUE, FALSE, TRUE)) != -1 &&
         (retval & SIO_READ) != 0) {
    rc=imap_cmd_step(h, async_cmd);
    if(h->idle_state == IDLE_RESPONSE_PENDING) {
      int c;
      if(rc != IMR_RESPOND) {
	g_message("async_process_real() expected IMR_RESPOND but got %d\n", rc);
	imap_handle_disconnect(h);
	return FALSE;
      }
      EAT_LINE(h, c);
      if (c == '\n') {
	h->idle_state = IDLE_ACTIVE;
	if (ASYNC_DEBUG) printf("IDLE is now ACTIVE\n");
      }
    } else if (rc == IMR_UNKNOWN ||
	rc == IMR_SEVERED || rc == IMR_BYE || rc == IMR_PROTOCOL ||
	rc  == IMR_BAD) {
      printf("async_process() got unexpected response %i!\n"
             "Last message was: \"%s\" - shutting down connection.\n",
             rc, h->last_msg);
      imap_handle_disconnect(h);
      return FALSE;
    }
    async_cmd = cmdi_get_pending(h->cmd_info);
    if(ASYNC_DEBUG)
      printf("async_process() loop iteration finished, next async_cmd=%x\n",
           async_cmd);
  }
  if(ASYNC_DEBUG) printf("async_process() loop left\n");
  if(h->idle_state == IDLE_INACTIVE && async_cmd == 0) {
    if(ASYNC_DEBUG) printf("Last async command completed.\n");
    if(h->async_watch_id) {
      g_source_remove(h->async_watch_id);
      h->async_watch_id = 0;
    }
    imap_handle_idle_enable(h, IDLE_TIMEOUT);
  }
  if(ASYNC_DEBUG)
    printf("async_process() sio: %d rc: %d returns %d (%d cmds in queue)\n",
           retval, rc, h->idle_state == IDLE_INACTIVE && async_cmd == 0,
           g_list_length(h->cmd_info));
  return h->idle_state != IDLE_INACTIVE || async_cmd != 0;
}

/* imap_handle_idle_enable: enables calling IDLE command after seconds
   of inactivity. IDLE support consists of three subroutines:

1. imap_handle_idle_{enable,disable}() switch to and from the IDLE
   mode.  switching to the mode is done by registering an idle
   callback idle_start() with 30 seconds delay time.

2. idle start() sends the IDLE command and registers idle_process() to
   be notified whenever data is available on the specified descriptor.

3. async_process() processes the data sent from the server. It is used
   by IDLE and STORE commands, for example. */

static gboolean
async_process(GIOChannel *source, GIOCondition condition, gpointer data)
{
  ImapMboxHandle *h = (ImapMboxHandle*)data;
  gboolean retval_async;

  g_return_val_if_fail(h, FALSE);

  if(ASYNC_DEBUG) printf("async_process() ENTER\n");
  if(HANDLE_TRYLOCK(h) != 0) 
    return FALSE;/* async data on already locked handle? Don't try again. */
  if(ASYNC_DEBUG) printf("async_process() LOCKED\n");
  if(h->state == IMHS_DISCONNECTED) {
    if(ASYNC_DEBUG) printf("async_process() on disconnected\n");
    HANDLE_UNLOCK(h);
    return FALSE;
  }
  if( (condition & G_IO_HUP) == G_IO_HUP) {
      imap_handle_disconnect(h);
      HANDLE_UNLOCK(h);
      return FALSE;
  }
  retval_async = async_process_real(h);

  HANDLE_UNLOCK(h);
  return retval_async;
}

static gboolean
idle_start(gpointer data)
{
  ImapMboxHandle *h = (ImapMboxHandle*)data;
  ImapCmdTag tag;
  unsigned asyncno;

  /* The test below can probably be weaker since it is ok for the
     channel to get disconnected before IDLE gets activated */
  HANDLE_LOCK(h);
  IMAP_REQUIRED_STATE3(h, IMHS_CONNECTED, IMHS_AUTHENTICATED,
                       IMHS_SELECTED, FALSE);

  asyncno = imap_make_tag(tag); sio_write(h->sio, tag, strlen(tag));
  sio_write(h->sio, " IDLE\r\n", 7); sio_flush(h->sio);
  cmdi_add_handler(&h->cmd_info, asyncno, cmdi_empty, NULL);
  if(!h->iochannel) {
    h->iochannel = g_io_channel_unix_new(h->sd);
    g_io_channel_set_encoding(h->iochannel, NULL, NULL);
  }
  if(ASYNC_DEBUG) printf("async_process() registered\n");
  h->async_watch_id = g_io_add_watch(h->iochannel, G_IO_IN|G_IO_HUP,
				     async_process, h);
  h->idle_enable_id = 0;
  h->idle_state = IDLE_RESPONSE_PENDING;

  HANDLE_UNLOCK(h);
  return FALSE;
}

/** Called with handle locked. */
ImapResponse
imap_cmd_issue(ImapMboxHandle* h, const char* cmd)
{
  unsigned async_cmd;
  g_return_val_if_fail(h, IMR_BAD);
  if (h->state == IMHS_DISCONNECTED)
    return IMR_SEVERED;

  /* create sequence for command */
  if (!imap_handle_idle_disable(h)) return IMR_SEVERED;
  if (imap_cmd_start(h, cmd, &async_cmd)<0)
    return IMR_SEVERED;  /* irrecoverable connection error. */

  sio_flush(h->sio);
  if(ASYNC_DEBUG) printf("command '%s' issued.\n", cmd);
  cmdi_add_handler(&h->cmd_info, async_cmd, cmdi_empty, NULL);
  if(!h->iochannel) {
    h->iochannel = g_io_channel_unix_new(h->sd);
    g_io_channel_set_encoding(h->iochannel, NULL, NULL);
  }
  h->async_watch_id = g_io_add_watch(h->iochannel, G_IO_IN|G_IO_HUP,
                                     async_process, h);
  return IMR_OK /* async_cmd */;
}

gboolean
imap_handle_idle_enable(ImapMboxHandle *h, int seconds)
{
  if( !h->enable_idle || !imap_mbox_handle_can_do(h, IMCAP_IDLE))
    return FALSE;
  if(h->idle_state != IDLE_INACTIVE) {
    fprintf(stderr, "IDLE already enabled\n");
    return FALSE;
  }
  if(!h->idle_enable_id)
    h->idle_enable_id = g_timeout_add(seconds*1000, idle_start, h);
  return TRUE;
}

gboolean
imap_handle_idle_disable(ImapMboxHandle *h)
{
  if(h->idle_enable_id) {
    g_source_remove(h->idle_enable_id);
    h->idle_enable_id = 0;
  }
  if(h->async_watch_id) {
    g_source_remove(h->async_watch_id);
    h->async_watch_id = 0;
    if(h->sio && h->idle_state == IDLE_RESPONSE_PENDING) {
      int c;
      ImapResponse rc;
      unsigned async_cmd = cmdi_get_pending(h->cmd_info);

      do {
	rc = imap_cmd_step(h, async_cmd);
      } while (rc == IMR_UNTAGGED);
      if(rc != IMR_RESPOND) {
	imap_handle_disconnect(h);
	return FALSE;
      }
      EAT_LINE(h, c);
      if(c == -1) {
	imap_handle_disconnect(h);
	return FALSE;
      }
      h->idle_state = IDLE_ACTIVE;
    }
    if (h->sio &&  h->idle_state == IDLE_ACTIVE) {
      /* we might have been disconnected before */
      sio_write(h->sio,"DONE\r\n",6); sio_flush(h->sio);
      h->idle_state = IDLE_INACTIVE;
    }
  }
  return TRUE;
}

gboolean
imap_handle_op_cancelled(ImapMboxHandle *h)
{
  return h->op_cancelled;
}

/** Called with handle locked. */
void
imap_handle_disconnect(ImapMboxHandle *h)
{
  gboolean still_connected __attribute__ ((__unused__));

  still_connected = imap_handle_idle_disable(h);
  if(h->sio) {
    sio_detach(h->sio); h->sio = NULL;
    imap_compress_release(&h->compress);
  }
  if(h->iochannel) {
    g_io_channel_unref(h->iochannel); h->iochannel = NULL;
  }
  if(h->async_watch_id) {
    g_source_remove(h->async_watch_id);
    h->async_watch_id = 0;
  }
  close(h->sd);
  h->state = IMHS_DISCONNECTED;
}

int imap_mbox_is_disconnected (ImapMboxHandle *h)
{ return IMAP_MBOX_IS_DISCONNECTED(h); }
int imap_mbox_is_connected    (ImapMboxHandle *h)
{ return IMAP_MBOX_IS_CONNECTED(h); }
int imap_mbox_is_authenticated(ImapMboxHandle *h)
{ return IMAP_MBOX_IS_AUTHENTICATED(h); }
int imap_mbox_is_selected     (ImapMboxHandle *h)
{ return IMAP_MBOX_IS_SELECTED(h); }

ImapResult
imap_mbox_handle_connect(ImapMboxHandle* ret, const char *host, int over_ssl)
{
  ImapResult rc;

  g_return_val_if_fail(imap_mbox_is_disconnected(ret), IMAP_CONNECT_FAILED);

  HANDLE_LOCK(ret);
#if !defined(USE_TLS)
  if(over_ssl) {
    imap_mbox_handle_set_msg(ret,"SSL requested but SSL support not compiled");
    HANDLE_UNLOCK(ret);
    return IMAP_UNSECURE;
  }
#else
  ret->over_ssl = over_ssl;
#endif

  g_free(ret->host);   ret->host   = g_strdup(host);

  if( (rc=imap_mbox_connect(ret)) == IMAP_SUCCESS) {
    rc = imap_authenticate(ret);
    if (rc == IMAP_SUCCESS) {
      ImapResponse response = imap_compress(ret);
      if ( !(response == IMR_NO || response == IMR_OK))
        rc = IMAP_PROTOCOL_ERROR;
    }
  }

  HANDLE_UNLOCK(ret);

  return rc;
}

void
imap_mbox_resize_cache(ImapMboxHandle *h, unsigned new_size)
{
  unsigned i;
  if(new_size<h->exists) { /* shrink msg_cache */
    for(i=new_size; i<h->exists; i++) {
      if(h->msg_cache[i])
        imap_message_free(h->msg_cache[i]);
    }
  }
  h->msg_cache = g_realloc(h->msg_cache, new_size*sizeof(ImapMessage*));
  g_array_set_size(h->flag_cache, new_size);
  for(i=h->exists; i<new_size; i++) 
    h->msg_cache[i] = NULL;
  h->exists = new_size;
}

/* imap_mbox_handle_reconnect:
   invalidate cache as late as possible.
*/
ImapResult
imap_mbox_handle_reconnect(ImapMboxHandle* h, gboolean *readonly)
{
  ImapResult rc;
  
  HANDLE_LOCK(h);

  if( (rc=imap_mbox_connect(h)) == IMAP_SUCCESS) {
    if( (rc = imap_authenticate(h)) == IMAP_SUCCESS) {
      ImapResponse response;
      imap_mbox_resize_cache(h, 0); /* invalidate cache */
      mbox_view_dispose(&h->mbox_view); /* FIXME: recreate it here? */

      response = imap_compress(h);
      if (response == IMR_OK || response == IMR_NO) {
        rc = IMAP_SUCCESS;
        if(h->mbox && 
           imap_mbox_select_unlocked(h, h->mbox, readonly) != IMR_OK) {
          rc = IMAP_SELECT_FAILED;
        }

      } else {
        /* compression was apparently attempted but failed. */
        rc = IMAP_PROTOCOL_ERROR;
      }

    }
  }
  HANDLE_UNLOCK(h);
  return rc;
}

/** Drops the connection without waiting for response.  This can be
    called when eg a signal from NetworkManager arrives. */
void
imap_handle_force_disconnect(ImapMboxHandle *h)
{
  HANDLE_LOCK(h);
  imap_handle_disconnect(h);
  HANDLE_UNLOCK(h);
}

ImapTlsMode
imap_handle_set_tls_mode(ImapMboxHandle* r, ImapTlsMode state)
{
  ImapTlsMode res;
  g_return_val_if_fail(r,0);
  res = r->tls_mode;
  r->tls_mode = state;
  return res;
}

const char* imap_msg_flags[6] = { 
  "seen", "answered", "flagged", "deleted", "draft", "recent"
};

struct ListData { 
  ImapListCb cb;
  void * cb_data;
};

int
imap_socket_open(const char* host, const char *def_port)
{
  static const int USEIPV6 = 1;
  int rc, fd = -1;
  
  /* --- IPv4/6 --- */
  /* "65536\0" */
  const char *port;
  char *hostname;
  struct addrinfo hints;
  struct addrinfo* res;
  struct addrinfo* cur;
  
  /* we accept v4 or v6 STREAM sockets */
  memset (&hints, 0, sizeof (hints));

  hints.ai_family = USEIPV6 ? AF_UNSPEC : AF_INET;
  hints.ai_socktype = SOCK_STREAM;

  port = strrchr(host, ':');
  if (port) {
    hostname = g_strndup(host, port-host);
    port ++;
  } else {
    port = def_port;
    hostname = g_strdup(host);
  }
  rc = getaddrinfo(hostname, port, &hints, &res);
#if defined(HAVE_RES_INIT)
  if (rc == EAI_AGAIN) {
    res_init();
    rc = getaddrinfo(hostname, port, &hints, &res);
  }
#endif                          /* defined(HAVE_RES_INIT) */
  g_free(hostname);
  if(rc)
    return -1;
  
  for (cur = res; cur != NULL; cur = cur->ai_next) {
    fd = socket (cur->ai_family, cur->ai_socktype, cur->ai_protocol);
    if (fd >= 0) {
      if ((rc=connect(fd, cur->ai_addr, cur->ai_addrlen)) == 0) {
	break;
      } else {
	close (fd);
        fd = -1;
      }
    }
  }
  freeaddrinfo (res);
  return fd; /* FIXME: provide more info why the connection failed. */
}

static int
imap_timeout_cb(void *arg)
{
  ImapMboxHandle *h = (ImapMboxHandle*)arg;
  int ok = 1;

  /* No reason to lock the handle here: if we get here, we have
     already been performing some operation and keep the handle
     locked. */
  if(h->user_cb) {
    h->user_cb(IME_TIMEOUT, h->user_arg, &ok);
    if(ok) {
      h->op_cancelled = TRUE;
      imap_handle_disconnect(h);
    }
  }

  return ok;
}

static ImapResult
imap_mbox_connect(ImapMboxHandle* handle)
{
  static const int SIO_BUFSZ=8192;
  ImapResponse resp;
  const char *service = "imap";

  /* reset some handle status */
  handle->op_cancelled = FALSE;
  handle->has_capabilities = FALSE;
  handle->can_fetch_body = TRUE;
  handle->idle_state = IDLE_INACTIVE;
  if(handle->sio) {
    sio_detach(handle->sio); handle->sio = NULL;
    imap_compress_release(&handle->compress);
  }

#ifdef USE_TLS
  handle->using_tls = 0;
  if(handle->over_ssl) service = "imaps";
#endif

  handle->sd = imap_socket_open(handle->host, service);
  if(handle->sd<0)
    return IMAP_CONNECT_FAILED;
  
  /* Add buffering to the socket */
  handle->sio = sio_attach(handle->sd, handle->sd, SIO_BUFSZ);
  if (handle->sio == NULL) {
    close(handle->sd);
    return IMAP_NOMEM;
  }
  imap_compress_init(&handle->compress);
  if(handle->timeout>0) {
    sio_set_timeout(handle->sio, handle->timeout);
    sio_set_timeoutcb(handle->sio, imap_timeout_cb, handle);
  }
#ifdef USE_TLS
  if(handle->over_ssl) {
    SSL *ssl = imap_create_ssl();
    if(!ssl) {
      imap_mbox_handle_set_msg(handle,"SSL context could not be created");
      return IMAP_UNSECURE;
    }
    if(imap_setup_ssl(handle->sio, handle->host, ssl,
                      handle->user_cb, handle->user_arg)) 
      handle->using_tls = 1;
    else {
      imap_mbox_handle_set_msg(handle,"SSL negotiation failed");
      imap_handle_disconnect(handle);
      return IMAP_UNSECURE;
    }
  }
#endif
  if(handle->monitor_cb) 
    sio_set_monitorcb(handle->sio, handle->monitor_cb, handle->monitor_arg);

  handle->state = IMHS_CONNECTED;
  if ( (resp=imap_cmd_step(handle, 0)) != IMR_UNTAGGED) {
    g_message("imap_mbox_connect:unexpected initial response(%d):\n%s\n",
	      resp, handle->last_msg);
    imap_handle_disconnect(handle);
    return IMAP_PROTOCOL_ERROR;
  }
  handle->can_fetch_body = 
    (strncmp(handle->last_msg, "Microsoft Exchange", 18) != 0);
#if defined(USE_TLS)
  if(handle->over_ssl)
    resp = IMR_OK; /* secured already with SSL */
  else if(handle->tls_mode != IMAP_TLS_DISABLED &&
          imap_mbox_handle_can_do(handle, IMCAP_STARTTLS)) {
    if( imap_handle_starttls(handle) != IMR_OK) {
      imap_mbox_handle_set_msg(handle,"TLS negotiation failed");
      return IMAP_UNSECURE; /* TLS negotiation error */
    }
    resp = IMR_OK; /* secured with TLS */
  } else
    resp = IMR_NO; /* not over SSL and TLS unavailable */
#else
  resp = IMR_NO;
#endif
  if(handle->tls_mode == IMAP_TLS_REQUIRED && resp != IMR_OK) {
    imap_mbox_handle_set_msg(handle,"TLS required but not available");
    return IMAP_UNSECURE;
  }

  return IMAP_SUCCESS;
}

unsigned
imap_make_tag(ImapCmdTag tag)
{
  static unsigned no = 0; /* MT-locking here */
  sprintf(tag, "%x", ++no);
  return no;
}

static int
imap_get_atom(struct siobuf *sio, char* atom, size_t len)
{
  unsigned i;
  int c = 0;
  for(i=0; i<len-1 && (c=sio_getc(sio)) >=0 && IS_ATOM_CHAR(c); i++)
    atom[i] = c;

  atom[i] = '\0';
  return c;
}

#define IS_FLAG_CHAR(c) (strchr("(){ %*\"]",(c))==NULL&&(c)>0x1f&&(c)!=0x7f)
static int
imap_get_flag(struct siobuf *sio, char* flag, size_t len)
{
  unsigned i;
  int c = 0;
  for(i=0; i<len-1 && (c=sio_getc(sio)) >=0 && IS_FLAG_CHAR(c); i++)
    flag[i] = c;

  if(i<len-1) {
    if (c < 0)
      return c;
  }
  flag[i] = '\0';
  return c;
}

/* we include '+' in TAG_CHAR because we want to treat forced responses
   in same code. This may be wrong. Reconsider.
*/
#define IS_TAG_CHAR(c) (strchr("(){ %\"\\]",(c))==NULL&&(c)>0x1f&&(c)!=0x7f)
static int
imap_cmd_get_tag(struct siobuf *sio, char* tag, size_t len)
{
  unsigned i;
  int c = 0;
  for(i=0; i<len-1 && (c=sio_getc(sio)) >=0 && IS_TAG_CHAR(c); i++) {
    tag[i] = c;
  }
  if(i<len-1) {
    if (c < 0)
      return c;
  }
  tag[i] = '\0';
  return c;
}

  
ImapConnectionState
imap_mbox_handle_get_state(ImapMboxHandle *h)
{
  return h->state; 
}

void
imap_mbox_handle_set_state(ImapMboxHandle *h, ImapConnectionState newstate)
{
  h->state = newstate;
}


unsigned
imap_mbox_handle_get_exists(ImapMboxHandle* handle)
{
  g_return_val_if_fail(handle, 0);
  return mbox_view_is_active(&handle->mbox_view) 
    ? mbox_view_cnt(&handle->mbox_view) : handle->exists;
}

unsigned
imap_mbox_handle_get_validity(ImapMboxHandle* handle)
{
  return handle->uidval;
}
unsigned
imap_mbox_handle_get_uidnext(ImapMboxHandle* handle)
{
  return handle->uidnext;
}

static void
get_delim(ImapMboxHandle* handle, int delim, ImapMboxFlags flags,
          char *folder, int *my_delim)
{
  *my_delim = delim;
}

int
imap_mbox_handle_get_delim(ImapMboxHandle* handle,
                           const char *namespace)
{
  int delim;
  guint handler_id;
  gchar * cmd, *mbx7;

  HANDLE_LOCK(handle);
  /* FIXME: block other list response signals here? */
  handler_id = g_signal_connect(G_OBJECT(handle), "list-response",
				G_CALLBACK(get_delim),
				&delim);

  mbx7 = imap_utf8_to_mailbox(namespace);
  cmd = g_strdup_printf("LIST \"%s\" \"\"", mbx7);
  g_free(mbx7);
  imap_cmd_exec(handle, cmd); /* ignore return code.. */
  g_free(cmd);
  g_signal_handler_disconnect(G_OBJECT(handle), handler_id);
  HANDLE_UNLOCK(handle);
  return delim;

}

char*
imap_mbox_handle_get_last_msg(ImapMboxHandle *handle)
{
  return g_strdup(handle->state == IMHS_DISCONNECTED
		  ? "Connection severed"
		  : (handle->last_msg ? handle->last_msg : "") );
}

void
imap_mbox_handle_connect_notify(ImapMboxHandle* handle,
                                ImapMboxNotifyCb cb, void *data)
{
}

static void
imap_mbox_handle_finalize(GObject* gobject)
{
  ImapMboxHandle* handle = IMAP_MBOX_HANDLE(gobject);
  g_return_if_fail(handle);

  HANDLE_LOCK(handle);
  if(handle->state != IMHS_DISCONNECTED) {
    handle->doing_logout = TRUE;
    imap_cmd_exec(handle, "LOGOUT");
  }
  imap_handle_disconnect(handle);
  g_free(handle->host);    handle->host   = NULL;
  g_free(handle->mbox);    handle->mbox   = NULL;
  g_free(handle->last_msg);handle->last_msg = NULL;

  g_list_foreach(handle->cmd_info, (GFunc)g_free, NULL);
  g_list_free(handle->cmd_info); handle->cmd_info = NULL;
  g_hash_table_destroy(handle->status_resps); handle->status_resps = NULL;

  mbox_view_dispose(&handle->mbox_view);
  imap_mbox_resize_cache(handle, 0);
  g_free(handle->msg_cache); handle->msg_cache = NULL;
  g_array_free(handle->flag_cache, TRUE); handle->flag_cache = NULL;
  g_list_foreach(handle->acls, (GFunc)imap_user_acl_free, NULL);
  g_list_free(handle->acls); handle->acls = NULL;
  g_free(handle->quota_root); handle->quota_root = NULL;

  HANDLE_UNLOCK(handle);
#if defined(BALSA_USE_THREADS)
  pthread_mutex_destroy(&handle->mutex);
#endif

  G_OBJECT_CLASS(parent_class)->finalize(gobject);  
}

typedef void (*ImapTasklet)(ImapMboxHandle*, void*);
struct tasklet {
  ImapTasklet task;
  void *data;
};
static void
imap_handle_add_task(ImapMboxHandle* handle, ImapTasklet task, void* data)
{
  struct tasklet * t = g_new(struct tasklet, 1);
  t->task = task;
  t->data = data;
  handle->tasks = g_slist_prepend(handle->tasks, t);
}

/* care needs to be taken: tasklet can trigger an IMAP command, which
   in turn would call imap_handle_process_tasks. We need to steal the
   pointer to the list.
*/

static void
imap_handle_process_tasks(ImapMboxHandle* handle)
{
  GSList *begin = handle->tasks, *l;

  handle->tasks = NULL;
  for(l = begin; l; l = l->next) {
    struct tasklet *t = (struct tasklet*)l->data;
    t->task(handle, t->data);
  }
  g_slist_foreach(begin, (GFunc)g_free, NULL);
  g_slist_free(begin);
}
    
ImapResponse
imap_mbox_handle_fetch_unlocked(ImapMboxHandle* handle, const gchar *seq, 
                       const gchar* headers[])
{
  char* cmd;
  int i;
  GString* hdr;
  ImapResponse rc;
  
  IMAP_REQUIRED_STATE1_U(handle, IMHS_SELECTED, IMR_BAD);
  hdr = g_string_new(headers[0]);
  for(i=1; headers[i]; i++) {
    if (hdr->str[hdr->len - 1] != '(' && headers[i][0] != ')')
      g_string_append_c(hdr, ' ');
    g_string_append(hdr, headers[i]);
  }
  cmd = g_strdup_printf("FETCH %s (%s)", seq, hdr->str);
  g_string_free(hdr, TRUE);
  rc = imap_cmd_exec(handle, cmd);
  g_free(cmd);
  return rc;
}

ImapResponse
imap_mbox_handle_fetch_env(ImapMboxHandle* handle, const gchar *seq)
{
  char* cmd;
  ImapResponse rc;
  
  IMAP_REQUIRED_STATE1_U(handle, IMHS_SELECTED, IMR_BAD);
  cmd = g_strdup_printf("FETCH %s (ENVELOPE FLAGS UID)", seq);
  rc = imap_cmd_exec(handle, cmd);
  g_free(cmd);
  return rc;
}


ImapMessage*
imap_mbox_handle_get_msg(ImapMboxHandle* h, unsigned seqno)
{
  g_return_val_if_fail(h, 0);
  g_return_val_if_fail(seqno-1<h->exists, NULL);
  return h->msg_cache[seqno-1];
}

ImapMessage*
imap_mbox_handle_get_msg_v(ImapMboxHandle* h, unsigned no)
{
  g_return_val_if_fail(h, 0);
  g_return_val_if_fail(no-1<h->exists, NULL);
  if(mbox_view_is_active(&h->mbox_view))
    no = mbox_view_get_msg_no(&h->mbox_view, no);
  return h->msg_cache[no-1];
}
unsigned
imap_mbox_get_msg_no(ImapMboxHandle* h, unsigned no)
{
  g_return_val_if_fail(h, 0);
  if(!mbox_view_is_active(&h->mbox_view))
    return no;
  else
    return mbox_view_get_msg_no(&h->mbox_view, no);
}

unsigned
imap_mbox_get_rev_no(ImapMboxHandle* h, unsigned seqno)
{
  if(!mbox_view_is_active(&h->mbox_view))
    return seqno;
  else
    return mbox_view_get_rev_no(&h->mbox_view, seqno);
}


static void
set_view_cb(ImapMboxHandle* handle, unsigned seqno, void*arg)
{
  mbox_view_append_no(&handle->mbox_view, seqno);
}

unsigned
imap_mbox_set_view(ImapMboxHandle *h, ImapMsgFlag fl, gboolean state)
{
  char *flag;
  gchar * cmd;
  const gchar *cmd_prefix;
  void *arg;
  ImapSearchCb cb;
  ImapResponse rc;

  mbox_view_dispose(&h->mbox_view);
  if(fl==0)
    return 1;

  if(imap_mbox_handle_can_do(h, IMCAP_ESEARCH))
    cmd_prefix = "SEARCH RETURN (ALL) ";
  else
    cmd_prefix = "SEARCH ALL ";

  switch(fl) {
  case IMSGF_SEEN:     flag = "SEEN"; break;
  case IMSGF_ANSWERED: flag = "ANSWERED"; break;
  case IMSGF_FLAGGED:  flag = "FLAGGED"; break;
  case IMSGF_DELETED:  flag = "DELETED"; break;
  case IMSGF_DRAFT:    flag = "DRAFT"; break;
  case IMSGF_RECENT:   flag = "RECENT"; break;
  default: return 1;
  }
  cb  = h->search_cb;  h->search_cb  = (ImapSearchCb)set_view_cb;
  arg = h->search_arg; h->search_arg = NULL;
  g_free(h->mbox_view.filter_str);
  h->mbox_view.filter_str = g_strconcat(state ? "" : "UN", flag, NULL);
  cmd = g_strconcat(cmd_prefix, h->mbox_view.filter_str, NULL);
  rc = imap_cmd_exec(h, cmd);
  g_free(cmd);
  h->search_cb = cb; h->search_arg = arg;
  return rc == IMR_OK;
}

const char*
imap_mbox_get_filter(ImapMboxHandle *h)
{
  return h->mbox_view.filter_str ? h->mbox_view.filter_str : "ALL";
}

/* imap_mbox_set_sort:
 */
unsigned
imap_mbox_set_sort(ImapMboxHandle *h, ImapSortKey isr, int ascending)
{
  gchar *cmd;
  const char *field;
  switch(isr) {
  default:
  case IMSO_ARRIVAL: return 1;
  case IMSO_SUBJECT: field = "SUBJECT"; break;
  case IMSO_DATE   : field = "DATE";    break;
  case IMSO_FROM   : field = "FROM";    break;
  }
  cmd= g_strdup_printf("SORT (%s%s) UTF-8 %s", field,
                       ascending ? "" : " REVERSE",
                       imap_mbox_get_filter(h));
  h->mbox_view.entries = 0; /* FIXME: I do not like this! 
                             * we should not be doing such 
                             * low level manipulations here */
  imap_cmd_exec(h, cmd);
  g_free(cmd);
  return 1;
}

/** Parse given source string expected to contain a quoted
    string. Returns the extracted, allocated string. */
static gchar*
get_quoted_string(const gchar *source, gchar const **endpos)
{
  GString *s;
  if(*source == '\0') {
    *endpos = source;
    return NULL;
  }
  if(*source != '"') { /* *source == 'N' */
    *endpos = source+1;
    return NULL;
  }
  source++;
  s = g_string_new("");
  for(;*source && *source != '"'; source++) {
    if(source[0] == '\\' && source[1])
      source++;
    g_string_append_c(s, *source);
  }
  *endpos = *source ? source+1 : source;
  return g_string_free(s, FALSE);
}

/** Appends a source string to res, quoting it with quote characters
    and prefixing any necessary characters in it with backslashes. */
static void
append_quoted_string(GString *res, const gchar *source)
{
  const gchar *p;
  if(source) {
    g_string_append_c(res, '"');
    for(p=source; *p; p++) {
      if(*p == '\\' || *p == '"') g_string_append_c(res, '\\');
      g_string_append_c(res, *p);
    }
    g_string_append_c(res, '"');
  } else {
    g_string_append_c(res, 'N'); /* N for NULL */
  }
}

/* =================================================================== */
/*            IMAP ENVELOPE HANDLING CODE                              */
/* =================================================================== */

ImapEnvelope*
imap_envelope_new()
{
  return g_malloc0(sizeof(ImapEnvelope));
}

static void
imap_envelope_free_data(ImapEnvelope* env)
{
  if(env->subject)     g_free(env->subject);
  if(env->from)        imap_address_free(env->from);
  if(env->sender)      imap_address_free(env->sender);
  if(env->replyto)     imap_address_free(env->replyto);
  if(env->to)          imap_address_free(env->to);
  if(env->cc)          imap_address_free(env->cc);
  if(env->bcc)         imap_address_free(env->bcc);
  if(env->in_reply_to) g_free(env->in_reply_to);
  if(env->message_id)  g_free(env->message_id);
}

void
imap_envelope_free(ImapEnvelope *env)
{
  g_return_if_fail(env);
  imap_envelope_free_data(env);
  g_free(env);
}

static void
concat_str(GString *s, gchar *t)
{
  g_string_append(s, t); g_free(t);
  g_string_append_c(s, ';');
}

gchar*
imap_envelope_to_string(const ImapEnvelope* env)
{
  GString *res;
  gchar *t;

  if(!env)
    return NULL;

  res = g_string_new("");
  g_string_printf(res, "%lu;", (unsigned long)env->date);
  append_quoted_string(res, env->subject);  g_string_append_c(res, ';');
  t = imap_address_to_string(env->from);    concat_str(res, t);
  t = imap_address_to_string(env->sender);  concat_str(res, t);
  t = imap_address_to_string(env->replyto); concat_str(res, t);
  t = imap_address_to_string(env->to);      concat_str(res, t);
  t = imap_address_to_string(env->cc);      concat_str(res, t);
  t = imap_address_to_string(env->bcc);     concat_str(res, t);
  append_quoted_string(res, env->in_reply_to);  g_string_append_c(res, ';');
  append_quoted_string(res, env->message_id);
  return g_string_free(res, FALSE);
}

static ImapEnvelope*
imap_envelope_from_stringi(const gchar *s, gchar const **end)
{
  ImapEnvelope *env;
  gchar *n;
  const gchar *nc = NULL;
  if(!s || !*s)
    return NULL;

  env = imap_envelope_new();
  env->date = strtol(s, &n, 10);
  s = n; if( *s++ != ';') goto done;
  env->subject = get_quoted_string(s, &nc);
  s = nc; if( *s++ != ';') goto done;
  env->from    = imap_address_from_string(s, &n);
  s = n; if( *s++ != ';') goto done;
  env->sender  = imap_address_from_string(s, &n);
  s = n; if( *s++ != ';') goto done;
  env->replyto = imap_address_from_string(s, &n);
  s = n; if( *s++ != ';') goto done;
  env->to      = imap_address_from_string(s, &n);
  s = n; if( *s++ != ';') goto done;
  env->cc      = imap_address_from_string(s, &n);
  s = n; if( *s++ != ';') goto done;
  env->bcc     = imap_address_from_string(s, &n);
  s = n; if( *s++ != ';') goto done;
  env->in_reply_to = get_quoted_string(s, &nc);
  s = nc; if( *s++ != ';') goto done;
  env->message_id  = get_quoted_string(s, &nc);

 done:
  if(end)
    *end = nc;

  return env;
}

ImapEnvelope*
imap_envelope_from_string(const gchar *s)
{
  return imap_envelope_from_stringi(s, NULL);
}

/* ================ BEGIN OF BODY STRUCTURE FUNCTIONS ================== */
ImapBody*
imap_body_new(void)
{
  ImapBody *body = g_malloc0(sizeof(ImapBody));
  body->params = g_hash_table_new_full(g_str_hash, g_str_equal, 
                                       g_free, g_free);
  return body;
}

static void
imap_body_ext_mpart_free (ImapBodyExtMPart * mpart)
{
  /* if (mpart->params) g_hash_table_destroy (mpart->params); */
  g_slist_foreach (mpart->lang, (GFunc) g_free, NULL);
  g_slist_free (mpart->lang);
}

void
imap_body_free(ImapBody* body)
{
  g_free(body->media_basic_name);
  g_free(body->media_subtype);
  g_hash_table_destroy(body->params);
  g_free(body->content_id);
  g_free(body->desc);

  if(body->envelope)
    imap_envelope_free(body->envelope);
  if (body->dsp_params)
    g_hash_table_destroy (body->dsp_params);

  g_free(body->content_dsp_other);
  g_free(body->content_uri);

  /* Ext */
  if(body->media_basic == IMBMEDIA_MULTIPART)
    imap_body_ext_mpart_free(&body->ext.mpart);
  else
    g_free(body->ext.onepart.md5);
  if(body->child) imap_body_free(body->child);
  if(body->next) imap_body_free(body->next);
  g_free(body);
}

void
imap_body_set_desc(ImapBody* body, char* str)
{
  g_free(body->desc);
  body->desc = str;
}

void
imap_body_add_param(ImapBody *body, char *key, char *val)
{
  int c;
  for(c=0; key[c]; c++)
    key[c] = tolower(key[c]);
  g_hash_table_insert(body->params, key, val);
}

const gchar*
imap_body_get_param(ImapBody *body, const gchar *key)
{
  return g_hash_table_lookup(body->params, key);
}

const gchar*
imap_body_get_dsp_param(ImapBody *body, const gchar *key)
{
  return body->dsp_params ? g_hash_table_lookup(body->dsp_params, key) : NULL;
}

gchar*
imap_body_get_mime_type(ImapBody *body)
{
  const gchar* type = NULL;
  gchar *res;
  int i;
  /* We could be returning media_basic_name but we canonize the common
     names ... */
  switch(body->media_basic) {
  case IMBMEDIA_MULTIPART:      type = "multipart"; break;
  case IMBMEDIA_APPLICATION:    type = "application"; break;
  case IMBMEDIA_AUDIO:          type = "audio"; break;
  case IMBMEDIA_IMAGE:          type = "image"; break;
  case IMBMEDIA_MESSAGE_RFC822: return g_strdup("message/rfc822"); break;
  case IMBMEDIA_MESSAGE_OTHER:  type = "message"; break;
  case IMBMEDIA_TEXT:           type = "text"; break;
  case IMBMEDIA_OTHER:          type = body->media_basic_name; break;
  }
  res = g_strconcat(type, "/", body->media_subtype, NULL);
  for(i=0; res[i]; i++)
        res[i] = tolower(res[i]);
  return res;
}

/* imap_body_get_content_type returns entire content-type line
 * available at the time. Observe that since the information is returned in
 * a transformed, canonical form since it is constructed
 * from the FETCH ENVELOPE response. */
static void
append_body_param(gpointer key, gpointer value, gpointer user_data)
{
  GString *r = (GString*)user_data;
  g_string_append(r, "; ");
  g_string_append(r, (char*)key);
  g_string_append(r, "=\"");
  g_string_append(r, (char*)value); /* FIXME: quote differently? */
  g_string_append_c(r, '"');
}

gchar*
imap_body_get_content_type(ImapBody *body)
{
  gchar *mime_type = imap_body_get_mime_type(body);
  GString *res = g_string_new(mime_type);
  g_free(mime_type);
  g_hash_table_foreach(body->params, append_body_param, res);
  return g_string_free(res, FALSE);
}

#if 0
static void
do_indent(int indent)
{ int i; for(i=0; i<indent; i++) putchar(' '); }
static void
print_body_structure(ImapBody *body, int indent)
{
  while(body) {
    gchar *type = imap_body_get_mime_type(body);
    do_indent(indent); printf("%s\n", type);
    g_free(type);
    if(body->child)
      print_body_structure(body->child, indent+3);
    body = body->next;
  }
}
#endif

static ImapBody*
get_body_from_section(ImapBody *body, const char *section)
{
  char * dot;
  int is_parent_a_message = 1;
  do {
    int no = strtol(section, NULL, 10);

    /* printf("Section: %s\n", section); print_body_structure(body, 0); */
    if(body &&
       (body->media_basic == IMBMEDIA_MULTIPART && is_parent_a_message))
      body = body->child;
    while(--no && body)
      body = body->next;
    
    if(!body) return NULL; /* non-existing section */
    dot = strchr(section, '.');
    if(dot) { 
      section = dot+1;
      is_parent_a_message =
        (body->media_basic == IMBMEDIA_MESSAGE_RFC822 ||
         body->media_basic == IMBMEDIA_MESSAGE_OTHER);
      body = body->child;
    }
  } while(dot);
  return body;
}

ImapBody*
imap_message_get_body_from_section(ImapMessage *msg,
                                   const char *section)
{
  /* FIXME: check call arguments! */
  g_return_val_if_fail(section, NULL);
  return get_body_from_section(msg->body, section);
}


unsigned
imap_sequence_length(ImapSequence *i_seq)
{
  unsigned length = 0;
  GList *l;
  for(l = i_seq->ranges; l; l = l->next) {
    ImapUidRange *r = (ImapUidRange*)l->data;
    length += r->hi - r->lo +1;
  }
  return length;
}

unsigned
imap_sequence_nth(ImapSequence *i_seq, unsigned nth)
{
  GList *l;

  g_return_val_if_fail(i_seq->ranges, 0);

  for(l = i_seq->ranges; l; l = l->next) {
    ImapUidRange *r = (ImapUidRange*)l->data;
    unsigned range_length = r->hi - r->lo +1;
    if( nth < range_length)
      return r->lo + nth;
    nth -= range_length;
  }
  g_warning("imap_sequence_nth: too large parameter; returning bogus data\n");
  return 0;
}

void
imap_sequence_foreach(ImapSequence *i_seq,
		      void(*cb)(unsigned uid, void *arg), void *cb_arg)
{
  GList *l;
  for(l = i_seq->ranges; l; l = l->next) {
    unsigned uid;
    ImapUidRange *iur = (ImapUidRange*)l->data;
    for(uid=iur->lo; uid<=iur->hi; uid++)
      cb(uid, cb_arg);
  }
}


void
imap_sequence_release(ImapSequence *i_seq)
{
  g_list_foreach(i_seq->ranges, (GFunc)g_free, NULL);
  i_seq->ranges = NULL;
}

void
imap_body_append_part(ImapBody* body, ImapBody* sibling)
{
  while(body->next)
    body = body->next;
  body->next = sibling;
}

void
imap_body_append_child(ImapBody* body, ImapBody* child)
{
  if(body->child) 
    imap_body_append_part(body->child, child);
  else
    body->child = child;
}
void
imap_body_set_id(ImapBody *body, char *id)
{
  body->content_id = id;
}

static void
append_pair(gpointer key, gpointer value, gpointer user_data)
{
  append_quoted_string(user_data, key);
  append_quoted_string(user_data, value);
}

static void
append_hash(GString *res, GHashTable *hash)
{
  g_string_append_c(res, '{');
  if(hash)
    g_hash_table_foreach(hash, append_pair, res);
  g_string_append_c(res, '}');
}

static GHashTable*
get_hash(const char *s, gchar const **end)
{
  GHashTable *hash = NULL;

  if(!s || *s != '{')
    return NULL;
  s++;
  while(*s && *s != '}') {
    gchar *key, *val;
    key = get_quoted_string(s, &s);
    if(!key)
      break;
    val = get_quoted_string(s, &s);
    if(!hash)
      hash = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
    g_hash_table_insert(hash, key, val);
  }
  if(*s == '}')
    s++;

  if(end)
    *end = s;

  return hash;
}

static void
append_onepart(GString *res, const ImapBodyExt1Part *onepart)
{
  append_quoted_string(res, onepart->md5);
}

static void
append_mpart(GString *res, const ImapBodyExtMPart *mpart)
{
  GSList *l;
  /* append_list */
  g_string_append_c(res, '(');
  for(l=mpart->lang; l; l = l->next)
    append_quoted_string(res, l->data);
  g_string_append_c(res, ')');
}

static GSList*
get_slist(const gchar *s, gchar const **end)
{
  GSList *res = NULL;
  if(!s || *s != '(')
    return NULL;
  s++;
  while( *s && *s != ')') {
    gchar *str = get_quoted_string(s, &s);
    res = g_slist_append(res, str);
  }
  if(*s == ')')
    s++;
  if(end)
    *end = s;
  return res;
}

static void
append_body(GString *res, const ImapBody *body)
{

  g_string_append_printf(res, "(%d %d", body->encoding, body->media_basic);
  append_quoted_string(res, body->media_basic_name);
  append_quoted_string(res, body->media_subtype);
  append_hash(res, body->params);
  g_string_append_printf(res, "%d %d", body->octets, body->lines);
  append_quoted_string(res, body->content_id);
  append_quoted_string(res, body->desc);

  if(body->envelope) {
    gchar *env = imap_envelope_to_string(body->envelope);
    g_string_append_c(res, '(');
    g_string_append(res, env);
    g_free(env);
    g_string_append_c(res, ')');
  } else g_string_append_c(res, 'X');

  g_string_append_printf(res, " %d", body->content_dsp);
  append_hash(res, body->dsp_params);
  append_quoted_string(res, body->content_dsp_other);
  append_quoted_string(res, body->content_uri);
  
  /* Ext */
  if(body->media_basic != IMBMEDIA_MULTIPART)
    append_onepart(res, &body->ext.onepart);
  else
    append_mpart(res, &body->ext.mpart);

  if(body->child) {
    g_string_append_c(res, '(');
    append_body(res, body->child);
    g_string_append_c(res, ')');
  }
  g_string_append_c(res, ')');
  if(body->next) {
    g_string_append_c(res, '+');
    append_body(res, body->next);
  }
}

gchar*
imap_body_to_string(const ImapBody *body)
{
  GString *res;

  if(!body)
    return NULL;

  res = g_string_new("");
  append_body(res, body);
  /* printf("Body converted to : '%s'\n", res->str); */
  return g_string_free(res, FALSE);
}

static ImapBody*
imap_body_from_stringi(const gchar *s, gchar const** end)
{
  ImapBody *body = NULL;
  GHashTable *hash;
  gchar *w;

  if (!s || *s != '(') /* Syntax error */
    goto done;

  s++;
  body = imap_body_new();

  body->encoding    = strtol(s, &w, 10); s = w;
  body->media_basic = strtol(s, &w, 10); s = w;

  body->media_basic_name = get_quoted_string(s, &s);
  body->media_subtype    = get_quoted_string(s, &s);

  hash = get_hash(s, &s);
  if(hash) {
    g_hash_table_destroy(body->params);
    body->params = hash;
  }

  body->octets = strtol(s, &w, 10); s = w;
  body->lines  = strtol(s, &w, 10); s = w;
  body->content_id = get_quoted_string(s, &s);
  body->desc = get_quoted_string(s, &s);
  if(*s == '(') {
    s++;
    body->envelope = imap_envelope_from_stringi(s+1, &s);
    if( *s != ')')
      goto done;
    s++;
  } else s++; /* assuming it points to 'X' */

  body->content_dsp = strtol(s+1, &w, 10); s = w;
  body->dsp_params = get_hash(s, &s);

  body->content_dsp_other = get_quoted_string(s, &s);
  body->content_uri = get_quoted_string(s, &s);
 
  /* Ext */
  if(body->media_basic != IMBMEDIA_MULTIPART)
    body->ext.onepart.md5 = get_quoted_string(s, &s);
  else {
    body->ext.mpart.lang = get_slist(s, &s);
  }

  if(*s == '(') {
    s++;
    body->child = imap_body_from_stringi(s, &s);
    if(*s != ')')
      goto done;
    s++;
  }
  s++; /* Skip trailing ')' of itself */
  if(*s == '+') {
    s++;
    body->next = imap_body_from_stringi(s, &s);
  }

 done:
  if(end)
    *end = s;
  return body;
}

ImapBody*
imap_body_from_string(const gchar *s)
{
  ImapBody *res = imap_body_from_stringi(s, NULL);
#if 0
  gchar *s1 = imap_body_to_string(res);
  if(s && *s)
    printf("Creating body from: '%s'\n"
           "New one is        : '%s'\n",
           s, s1);
  g_free(s1);
#endif
  return res;
}

/* ================ END OF BODY STRUCTURE FUNCTIONS ==================== */


/* =================================================================== */
/*             IMAP MESSAGE HANDLING CODE                              */
/* =================================================================== */

ImapMessage*
imap_message_new(void)
{
  ImapMessage * msg=g_malloc0(sizeof(ImapMessage));
  msg->rfc822size=-1;
  return msg;
}

void
imap_message_free(ImapMessage *msg)
{
  g_return_if_fail(msg);
  if(msg->envelope) imap_envelope_free(msg->envelope);
  if(msg->body)     imap_body_free    (msg->body);
  g_free(msg->fetched_header_fields);
  g_free(msg);
}

void
imap_mbox_handle_msg_deserialize(ImapMboxHandle *h, unsigned msgno,
                                 void *data)
{
  if(msgno>=1 && msgno <=h->exists && !h->msg_cache[msgno-1])
    h->msg_cache[msgno-1] = imap_message_deserialize(data);
}
/* Serialize message itself and the envelope, and the body structure
   if available. */
struct ImapMsgSerialized {
  ssize_t total_size; /* for checksumming */
  /* Message */
  ImapUID      uid;
  ImapMsgFlags flags;
  ImapDate     internal_date; /* delivery date */
  int rfc822size;
  ImapFetchType available_headers;
  gchar fetched_headers_first_char;
};

void*
imap_message_serialize(ImapMessage *imsg)
{
  ssize_t tot_size;
  gchar *ptr;
  gchar *strings[3];
  size_t lengths[3];
  struct ImapMsgSerialized *imes;
  int i;

  if(!imsg->envelope) /* envelope is required */
    return NULL; 
  strings[0] = imsg->fetched_header_fields;
  strings[1] = imap_envelope_to_string(imsg->envelope);
  strings[2] = imap_body_to_string(imsg->body);
  tot_size = sizeof(struct ImapMsgSerialized)-1;
  for(i=0; i<3; i++) {
    lengths[i] = strings[i]  ? strlen(strings[i])  : 0;
    tot_size += lengths[i] + 1;
  }

  imes = g_malloc(tot_size);
  imes->total_size = tot_size;
  /* Message */
  imes->uid           = imsg->uid;
  imes->flags         = imsg->flags;
  imes->internal_date = imsg->internal_date; /* delivery date */
  imes->rfc822size    = imsg->rfc822size;
  imes->available_headers = imsg->available_headers;

  ptr = &imes->fetched_headers_first_char;
  for(i=0; i<3; i++) {
    if(strings[i])
      strcpy(ptr, strings[i]);
    ptr += lengths[i];  *ptr++ = '\0';
  }
  g_free(strings[1]);
  g_free(strings[2]);
  /* printf("Serialization offset: %d (tot size %d may include alignment)\n",
     ptr-(gchar*)imes, tot_size); */
  return imes;
}

/** Convert given blob to an ImapMessage structure, with properly set
    envelope and body structure fields as well. */
ImapMessage*
imap_message_deserialize(void *data)
{
  struct ImapMsgSerialized *imes = (struct ImapMsgSerialized*)data;
  ImapMessage* imsg = imap_message_new();
  gchar *ptr;

  imsg->uid = imes->uid;
  imsg->flags = imes->flags;
  imsg->internal_date = imes->internal_date; /* delivery date */
  imsg->rfc822size = imes->rfc822size;
  imsg->available_headers = imes->available_headers;
  /* Envelope */
  ptr = &imes->fetched_headers_first_char;
  imsg->fetched_header_fields = *ptr ? g_strdup(ptr) : NULL;
  ptr += strlen(ptr) + 1;
  imsg->envelope = imap_envelope_from_string(ptr);
  ptr += strlen(ptr) + 1;
  imsg->body = imap_body_from_string(ptr);
  ptr += strlen(ptr) + 1;
  return imsg;
}

size_t
imap_serialized_message_size(void *data)
{
  struct ImapMsgSerialized *imes = (struct ImapMsgSerialized*)data;
  return imes->total_size;
}

/* =================================================================== */
/*                Imap command processing routines                     */
/* =================================================================== */
#if 0
static ImapResponse
imap_code(const gchar* resp)
{
  if(strncmp(resp+sizeof(ImapCmdTag)+1,"OK", 2) ==0)
    return IMR_OK;
  else if(strncmp(resp+sizeof(ImapCmdTag)+1,"NO", 2) ==0)
    return IMR_NO;
  else  if(strncmp(resp+sizeof(ImapCmdTag)+1,"BAD", 3) ==0) {
    g_warning("Protocol error:\n");
    return IMR_BAD;
  } else return IMR_BAD; /* nothing known */
}
#endif

/* imap_cmd_start sends the command to the server. We do it carefully
 * without using printf because our cmds can be pretty long.
 */
int
imap_cmd_start(ImapMboxHandle* handle, const char* cmd, unsigned *cmdno)
{
  ImapCmdTag tag;
  g_return_val_if_fail(handle, -1);
  
  if(IMAP_MBOX_IS_DISCONNECTED(handle))
    return -1;

  *cmdno = imap_make_tag(tag);
  sio_write(handle->sio, tag, strlen(tag));
  sio_write(handle->sio, " ", 1);
  sio_write(handle->sio, cmd, strlen(cmd));
  sio_write(handle->sio, "\r\n", 2);
  return 1;
}

/* imap_cmd_step:
 * Reads server responses from an IMAP command, detects
 * tagged completion response, handles untagged messages.
 * Reads only as much as needed using buffered input.
 */
ImapResponse
imap_cmd_step(ImapMboxHandle* handle, unsigned lastcmd)
{
  ImapCmdTag tag;
  ImapResponse rc;
  unsigned cmdno;
  struct CmdInfo *ci;

  /* FIXME: sanity test */
  g_return_val_if_fail(handle, IMR_BAD);
  g_return_val_if_fail(handle->state != IMHS_DISCONNECTED, IMR_BAD);

#ifdef USE_TLS
  if(ERR_peek_error()) {
    fprintf(stderr, "OpenSSL error in %s():\n", __FUNCTION__);
    ERR_print_errors_fp(stderr);
    fprintf(stderr, "\nEnd of print_errors - severing the connection...\n");
    imap_handle_disconnect(handle);
    return IMR_SEVERED;
  }
#endif
  ci = cmdi_find_by_no(handle->cmd_info, lastcmd);
  if(ci && ci->completed) {
    /* The response to this command has been encountered earlier,
       send it. */
    printf("Sending stored response to %x and removing info.\n",  lastcmd);
    rc = ci->rc;
    handle->cmd_info = g_list_remove(handle->cmd_info, ci);
    g_free(ci);
    return rc;
  }

  if( imap_cmd_get_tag(handle->sio, tag, sizeof(tag))<0) {
    printf("IMAP connection to %s severed.\n", handle->host);
    imap_handle_disconnect(handle);
    return IMR_SEVERED;
  }
  /* handle untagged messages. The caller still gets its shot afterwards. */
  if (strcmp(tag, "*") == 0) {
    rc = ir_handle_response(handle);
    if(rc == IMR_BYE) {
      return handle->doing_logout ? IMR_UNTAGGED : IMR_BYE;
    }
    return IMR_UNTAGGED;
  }

  /* server demands a continuation response from us */
  if (strcmp(tag, "+") == 0)
    return IMR_RESPOND;

  /* tagged completion code is the only alternative. */
  /* our command tags are hexadecimal numbers */
  if(sscanf(tag, "%x", &cmdno) != 1) {
    printf("scanning '%s' for tag number failed. Cannot recover.\n", tag);
    imap_handle_disconnect(handle);
    return IMR_BAD;
  }

  rc = ir_handle_response(handle);
  /* We check whether we encountered an response to a another,
       possibly asynchronous command, not the one we are currently
       executing. We store the response in the hash table so that we
       can provide a proper response when somebody asks. */
  ci = cmdi_find_by_no(handle->cmd_info, cmdno);
#ifdef DEBUG
  if(lastcmd != cmdno)
    printf("Looking for %x and encountered response to %x (%p)\n",
           lastcmd, cmdno, ci);
#endif
  if(ci) {
    if(ci->complete_cb && !ci->complete_cb(handle, ci->cb_data)) {
      ci->rc = rc;
      ci->completed = 1;
      printf("Cmd %x marked as completed with rc=%d\n", cmdno, rc);
    } else {
#ifdef DEBUG
      printf("CmdInfo for cmd %x removed\n", cmdno);
#endif
      handle->cmd_info = g_list_remove(handle->cmd_info, ci);
      g_free(ci);
    }
  }
  if (handle->state == IMHS_DISCONNECTED)
    return IMR_SEVERED;
  else
    return lastcmd == cmdno ? rc : IMR_UNTAGGED;
}

/**executes a command, and wait for the response from the server.
 * Also, handle untagged responses.
 * Returns ImapResponse.
 */
ImapResponse
imap_cmd_exec_cmdno(ImapMboxHandle* handle, const char* cmd,
		    unsigned *ret_cmdno)
{
  unsigned cmdno;
  ImapResponse rc;

  if(ret_cmdno) *ret_cmdno = 0;

  g_return_val_if_fail(handle, IMR_BAD);
  if (handle->state == IMHS_DISCONNECTED)
    return IMR_SEVERED;

  /* create sequence for command */
  if (!imap_handle_idle_disable(handle)) return IMR_SEVERED;
  if (imap_cmd_start(handle, cmd, &cmdno)<0)
    return IMR_SEVERED;  /* irrecoverable connection error. */

  if(ret_cmdno) *ret_cmdno = cmdno;
  g_return_val_if_fail(handle->state != IMHS_DISCONNECTED && 1, IMR_BAD);
  sio_flush(handle->sio);
  if(handle->state == IMHS_DISCONNECTED)
    return IMR_SEVERED;

  do {
    rc = imap_cmd_step (handle, cmdno);
  } while (rc == IMR_UNTAGGED);

  imap_handle_idle_enable(handle, IDLE_TIMEOUT);

  return rc;
}

/** Executes a set of commands, and wait for the response from the
 * server.  Handles all untagged responses that arrive in meantime.
 * Returns ImapResponse.
 * @param handle the IMAP connection handle
 * @param cmds the NULL-terminated vector of IMAP commands.
 * @param rc_to_return the 0-based number of the "important" IMAP
 * command in the sequence that we want to have the return code for.
 */
ImapResponse
imap_cmd_exec_cmds(ImapMboxHandle* handle, const char** cmds,
		   unsigned rc_to_return)
{
  unsigned cmd_count;
  ImapResponse rc = IMR_OK, ret_rc = IMR_OK;
  unsigned *cmdnos;

  g_return_val_if_fail(handle, IMR_BAD);
  if (handle->state == IMHS_DISCONNECTED)
    return IMR_SEVERED;

  if (!imap_handle_idle_disable(handle)) return IMR_SEVERED;

  for (cmd_count=0; cmds[cmd_count]; ++cmd_count)
    ;
  cmdnos = g_malloc(cmd_count*sizeof(unsigned));
  
  for (cmd_count=0; cmds[cmd_count]; ++cmd_count) {
    if (imap_cmd_start(handle, cmds[cmd_count], &cmdnos[cmd_count])<0) {
      rc = IMR_SEVERED;   /* irrecoverable connection error. */
      break;
    }
  }
  if (rc == IMR_OK) {
    g_return_val_if_fail(handle->state != IMHS_DISCONNECTED && 1, IMR_BAD);
    sio_flush(handle->sio);
    if(handle->state == IMHS_DISCONNECTED)
      rc = IMR_SEVERED;
    else {
      for (cmd_count=0; cmds[cmd_count]; ++cmd_count) {
	do {
	  rc = imap_cmd_step (handle, cmdnos[cmd_count]);
	} while (rc == IMR_UNTAGGED);

	if ( !(rc == IMR_OK || rc == IMR_NO || rc == IMR_BAD) ) {
	  ret_rc = rc;
	  break;
	}

	if (cmd_count == rc_to_return)
	  ret_rc = rc;

      }
    }
  }
  g_free(cmdnos);
      
  imap_handle_idle_enable(handle, IDLE_TIMEOUT);

  return ret_rc;
}

int
imap_handle_write(ImapMboxHandle *conn, const char *buf, size_t len)
{
  g_return_val_if_fail(conn, -1);
  g_return_val_if_fail(conn->sio, -1);

  sio_write(conn->sio, buf, len); /* why it is void? */
  return 0;
}

void
imap_handle_flush(ImapMboxHandle *handle)
{
  g_return_if_fail(handle);
  g_return_if_fail(handle->sio);
  sio_flush(handle->sio);
}

char*
imap_mbox_gets(ImapMboxHandle *h, char* buf, size_t sz)
{
  char* rc;
  g_return_val_if_fail(h, NULL);
  g_return_val_if_fail(h->sio, NULL);

  rc = sio_gets(h->sio, buf, sz);
  if(rc == NULL)
      imap_handle_disconnect(h);
  return rc;
}

const char*
lbi_strerror(ImapResult rc)
{
  switch(rc) {
   
  case IMAP_SUCCESS:        return "action succeeded";
  case IMAP_NOMEM:          return "not enough memory";
  case IMAP_CONNECT_FAILED: return "transport level connect failed";
  case IMAP_PROTOCOL_ERROR: return "unexpected server response";
  case IMAP_AUTH_FAILURE:   return "authentication failure";
  case IMAP_AUTH_UNAVAIL:   return "no supported authentication method available ";
  case IMAP_UNSECURE:       return "secure connection requested but "
                              "could not be established.";
  case IMAP_SELECT_FAILED: return "SELECT command failed";
  default: return "Unknown error";
  }
}

static GString*
imap_get_string_with_lookahead(struct siobuf* sio, int c)
{ /* string */  
  GString *res = NULL;
  if(c=='"') { /* quoted */
    res = g_string_new("");
    while( (c=sio_getc(sio)) != '"' && c != EOF) {
      if(c== '\\')
        c = sio_getc(sio);
      g_string_append_c(res, c);
    }
  } else { /* this MUST be literal */
    char buf[15];
    int len;
    if(c=='~') /* BINARY extension literal8 indicator */
      c = sio_getc(sio);
    if(c!='{') {
      return NULL; /* ERROR */
    }

    c = imap_get_atom(sio, buf, sizeof(buf));
    len = strlen(buf); 
    if(len==0 || buf[len-1] != '}') return NULL;
    buf[len-1] = '\0';
    len = strtol(buf, NULL, 10);
    if( c != 0x0d) { printf("lit1:%d\n",c); return NULL;}
    if( (c=sio_getc(sio)) != 0x0a) { printf("lit1:%d\n",c); return NULL;}
    res = g_string_sized_new(len+1);
    if(len>0) sio_read(sio, res->str, len);
    res->len = len;
    res->str[len] = '\0';
  }
  return res;
}

/* see the spec for the definition of string */
static char*
imap_get_string(struct siobuf* sio)
{
  GString * s = imap_get_string_with_lookahead(sio, sio_getc(sio));
  return s ? g_string_free(s, FALSE) : NULL;
}

static gboolean
imap_is_nil (struct siobuf *sio, int c)
{
  return g_ascii_toupper (c) == 'N' && g_ascii_toupper (sio_getc (sio)) == 'I'
    && g_ascii_toupper (sio_getc (sio)) == 'L';
}

/* see the spec for the definition of nstring */
static char*
imap_get_nstring(struct siobuf* sio)
{
  int c = sio_getc(sio);
  if(toupper(c)=='N') { /* nil */
    sio_getc(sio); sio_getc(sio); /* ignore i and l */
    return NULL;
  } else {
    GString *s = imap_get_string_with_lookahead(sio, c);
    return s ? g_string_free(s, FALSE) : NULL;
  }
}

/* see the spec for the definition of astring */
#define IS_ASTRING_CHAR(c) (strchr("(){ %*\"\\", (c))==0&&(c)>0x1F&&(c)!=0x7F)
static char*
imap_get_astring(struct siobuf *sio, int* lookahead)
{
  char* res;
  int c = sio_getc(sio);

  if(IS_ASTRING_CHAR(c)) {
    GString *str = g_string_new("");
    do {
      g_string_append_c(str, c);
      c = sio_getc(sio);
    } while(IS_ASTRING_CHAR(c));
    res = g_string_free(str, FALSE);
    *lookahead = c;
  } else {
    res = g_string_free(imap_get_string_with_lookahead(sio, c), FALSE);
    *lookahead = sio_getc(sio);
  }
  return res;
}

/* nstring / literal8 as in the BINARY extension */
static GString*
imap_get_binary_string(struct siobuf *sio)
{
  int c = sio_getc(sio);
  if(toupper(c)=='N') { /* nil */
    sio_getc(sio); sio_getc(sio); /* ignore i and l */
    return g_string_new("");
  } else
    return imap_get_string_with_lookahead(sio, c);
}

/* this file contains all the response handlers as defined in
   draft-crspin-imapv-20.txt. 
  
   According to section 7 of this draft, "the client MUST be prepared
   to accept any response at all times".

   The code is closely based on sectin 9 - formal syntax.
*/

#include "imap-handle.h"

static int
ignore_bad_charset(struct siobuf *sio, int c)
{
  while(c==' ') {
    gchar * astring = imap_get_astring(sio, &c); 
    g_free(astring);
  }
  if(c != ')')
    fprintf(stderr,"ignore_bad_charset: expected ')' got '%c'\n", c);
  else c = sio_getc(sio);
  return c;
}

static int
ir_permanent_flags(ImapMboxHandle *h)
{
  int c;
  while( (c=sio_getc(h->sio)) != EOF && c != ']')
    ;
  return c;
}

static int
ir_capability_data(ImapMboxHandle *handle)
{
  /* ordered identically as ImapCapability constants */
  static const char* capabilities[] = {
    "IMAP4", "IMAP4rev1", "STATUS",
    "AUTH=ANONYMOUS", "AUTH=CRAM-MD5", "AUTH=GSSAPI", "AUTH=PLAIN",
    "ACL", "RIGHTS=", "BINARY", "CHILDREN",
    "COMPRESS=DEFLATE",
    "ESEARCH", "IDLE", "LITERAL+",
    "LOGINDISABLED", "MULTIAPPEND", "NAMESPACE", "QUOTA", "SASL-IR",
    "SCAN", "STARTTLS",
    "SORT", "THREAD=ORDEREDSUBJECT", "THREAD=REFERENCES",
    "UIDPLUS", "UNSELECT"
  };
  unsigned x;
  int c;
  char atom[LONG_STRING];

  memset (handle->capabilities, 0, sizeof (handle->capabilities));
  
  do {
    c = imap_get_atom(handle->sio, atom, sizeof(atom));
    for (x=0; x<ELEMENTS(capabilities); x++)
      if (g_ascii_strncasecmp(atom, capabilities[x],
                              strlen(capabilities[x])) == 0) {
	handle->capabilities[x] = 1;
	break;
      }
  } while(c==' ');
  handle->has_capabilities = TRUE;
  return c;
}

typedef void (*ImapUidRangeCb)(ImapUidRange *iur, void *arg);

static ImapResponse
imap_get_sequence(ImapMboxHandle *h, ImapUidRangeCb seq_cb, void *seq_arg)
{
  char value[30];
  gchar *p;
  int offset = 0;
  int c = ' ';

  do {
    size_t value_len;
    if(c != '\r' && c != '\n') /* Dont try to read beyond the line. */
      c = imap_get_atom(h->sio, value + offset, sizeof(value)-offset);
    value_len = strlen(value);

    if(seq_cb) { /* makes sense to parse it ... */
      static const unsigned LENGTH_OF_LARGEST_UNSIGNED = 10;
      ImapUidRange seq;

      for(p=value; *p &&
	    (unsigned)(p-value) <=
	    sizeof(value)-(2*LENGTH_OF_LARGEST_UNSIGNED+1); ) {
	if(sscanf(p, "%u", &seq.lo) != 1)
	  return IMR_PROTOCOL;
	while(*p && isdigit(*p)) p++;
	if( *p == ':') {
	  p++;
	  if(sscanf(p, "%u", &seq.hi) != 1)
	    return c;
	} else seq.hi = seq.lo;

	seq_cb(&seq, seq_arg);

	while(*p && isdigit(*p)) p++;
	if(*p == ',') p++;
      } /* End of for */
	
      /* Reuse what's left. */
      if(*p) {
	offset = value_len - (p-value);
	memmove(value, p, offset+1);
      } else offset = 0;

    } /* End of if(search_cb) */

  }  while (isdigit(c)|| c == ':' || c == ',' || offset);

  if(c != EOF)
    sio_ungetc(h->sio);
  return IMR_OK;
}

static void
append_uid_range(ImapUidRange *iur, GList **dst)
{
  ImapUidRange *iur_copy = g_new(ImapUidRange, 1);
  /* printf("Prepending %u:%u\n", iur->lo, iur->hi); */
  iur_copy->lo = iur->lo;
  iur_copy->hi = iur->hi;
  *dst = g_list_prepend(*dst, iur_copy);
}

static ImapResponse
ir_get_append_copy_uids(ImapMboxHandle *h, gboolean append_only)
{
  int c;
  char buf[12];
  ImapResponse rc;

  if( (c=imap_get_atom(h->sio, buf, sizeof(buf))) == EOF)
    return IMR_PROTOCOL;
  h->uidplus.dst_uid_validity = strtol(buf, NULL, 10);

  if(c != ' ')
    return IMR_PROTOCOL;

  if(!append_only) {
    if( (rc = imap_get_sequence(h, NULL, NULL)) != IMR_OK)
      return rc;
    if( (c=sio_getc(h->sio)) != ' ') {
      printf("Expected ' ' found '%c'\n", c);
      return IMR_PROTOCOL;
    }
  }
  return imap_get_sequence(h, (ImapUidRangeCb)append_uid_range,
			   &h->uidplus.dst);
}

static ImapResponse
ir_resp_text_code(ImapMboxHandle *h)
{
  static const char* resp_text_code[] = {
    "ALERT", "BADCHARSET", "CAPABILITY","PARSE", "PERMANENTFLAGS",
    "READ-ONLY", "READ-WRITE", "TRYCREATE", "UIDNEXT", "UIDVALIDITY",
    "UNSEEN", "APPENDUID", "COPYUID"
  };
  unsigned o;
  char buf[128];
  int c = imap_get_atom(h->sio, buf, sizeof(buf));
  ImapResponse rc = IMR_OK;

  for(o=0; o<ELEMENTS(resp_text_code); o++)
    if(g_ascii_strcasecmp(buf, resp_text_code[o]) == 0) break;

  switch(o) {
  case 0: rc = IMR_ALERT;        break;
  case 1: c = ignore_bad_charset(h->sio, c); break;
  case 2: c = ir_capability_data(h); break;
  case 3: rc = IMR_PARSE;        break;
  case 4: c = ir_permanent_flags(h); break;
  case 5: h->readonly_mbox = TRUE;  /* read-only */; break;
  case 6: h->readonly_mbox = FALSE; /* read-write */; break;
  case 7: /* ignore try-create */; break;
  case 8:
    c = imap_get_atom(h->sio, buf, sizeof(buf));
    h->uidnext = strtol(buf, NULL, 10);
    break;
  case 9:
    c = imap_get_atom(h->sio, buf, sizeof(buf));
    h->uidval = strtol(buf, NULL, 10);
    break;
  case 10:
    c = imap_get_atom(h->sio, buf, sizeof(buf));
    h->unseen =strtol(buf, NULL, 10);
    break;
  case 11: /* APPENDUID */
    if( (rc=ir_get_append_copy_uids(h, TRUE)) != IMR_OK)
      return rc;
    /* printf("APPENDUID: uid_validity=\n"); */
    c = sio_getc(h->sio);
    break;
  case 12: /* COPYUID */
    /* printf("Copyuid\n"); */
    if( (rc=ir_get_append_copy_uids(h, FALSE)) != IMR_OK)
      return rc;
    c = sio_getc(h->sio);
    break;
  default: while( c != ']' && (c=sio_getc(h->sio)) != EOF) ; break;
  }
  if(c != ']')
    printf("ir_resp_text_code, on exit c=%c\n", c);
  return c == ']' ? rc : IMR_PROTOCOL;
}

static ImapResponse
ir_ok(ImapMboxHandle *h)
{
  ImapResponse rc;
  char line[2048];
  int l, c = sio_getc(h->sio);

  if(c == '[') {
    /* look for information response codes here: section 7.1 of the draft */
    rc = ir_resp_text_code(h);
    if(sio_getc(h->sio) != ' ') rc = IMR_PROTOCOL;
    if (sio_gets(h->sio, line, sizeof(line)) == NULL)
      rc = IMR_SEVERED;
  } else {
    line[0] = c;
    if (sio_gets(h->sio, line+1, sizeof(line)-1) == NULL)
      rc = IMR_SEVERED;
    else 
      rc = IMR_OK;
  }
  if(rc == IMR_PARSE)
    rc = IMR_OK;
  else if (rc != IMR_SEVERED && (l=strlen(line))>0 ) {
    line[l-2] = '\0'; 
    imap_mbox_handle_set_msg(h, line);
    if(h->info_cb)
      h->info_cb(h, rc, line, h->info_arg);
    else
      printf("INFO : '%s'\n", line);
    rc = IMR_OK; /* in case it was IMR_ALERT */
  }
  return rc;
}

static ImapResponse
ir_no(ImapMboxHandle *h)
{
  char line[LONG_STRING];

  sio_gets(h->sio, line, sizeof(line));
  /* look for information response codes here: section 7.1 of the draft */
  if( strlen(line)>2) {
    imap_mbox_handle_set_msg(h, line);
    if(h->info_cb)
      h->info_cb(h, IMR_NO, line, h->info_arg);
    else
      printf("WARN : '%s'\n", line);
  }
  return IMR_NO;
}

static ImapResponse
ir_bad(ImapMboxHandle *h)
{
  char line[LONG_STRING];
  sio_gets(h->sio, line, sizeof(line));
  /* look for information response codes here: section 7.1 of the draft */
  if( strlen(line)>2) {
    imap_mbox_handle_set_msg(h, line);
    if(h->info_cb)
      h->info_cb(h, IMR_BAD, line, h->info_arg);
    else
      printf("ERROR: %s\n", line);
  }
  return IMR_BAD;
}

static ImapResponse
ir_preauth(ImapMboxHandle *h)
{
  if(imap_mbox_handle_get_state(h) == IMHS_CONNECTED)
    imap_mbox_handle_set_state(h, IMHS_AUTHENTICATED);
  return IMR_OK;
}

/* ir_bye:
   NOTE: we do not invalidate cache here, it may have use in spite of
   the closed connection.
*/
static ImapResponse
ir_bye(ImapMboxHandle *h)
{
  char line[LONG_STRING];
  sio_gets(h->sio, line, sizeof(line));
  if(!h->doing_logout) {/* it is not we, so it must be the server */
    imap_mbox_handle_set_msg(h, line);
    imap_mbox_handle_set_state(h, IMHS_DISCONNECTED);
    /* we close the connection here unless we are doing logout. */
    if(h->sio) {
      sio_detach(h->sio); h->sio = NULL; 
      imap_compress_release(&h->compress);
    }
    close(h->sd);
  }
  return IMR_BYE;
}

static ImapResponse
ir_check_crlf(ImapMboxHandle *h, int c)
{
  if( c != 0x0d) {
    printf("CR:%d\n",c);
    return IMR_PROTOCOL;
  }
  if( (c=sio_getc(h->sio)) != 0x0a) {
    printf("LF:%d\n",c);
    return IMR_PROTOCOL;
  }
  return IMR_OK;
}

static ImapResponse
ir_capability(ImapMboxHandle *handle)
{
  int c = ir_capability_data(handle);
  return ir_check_crlf(handle, c);
}
/* follow mailbox-list syntax (See rfc) */
static ImapResponse
ir_list_lsub(ImapMboxHandle *h, ImapHandleSignal signal)
{
  const char* mbx_flags[] = {
    "Marked", "Unmarked", "Noselect", "Noinferiors",
    "HasChildren", "HasNoChildren"
  };
  ImapMboxFlags flags = 0;
  char buf[LONG_STRING], *s, *mbx;
  int c, delim;
  ImapResponse rc;

  if(sio_getc(h->sio) != '(') return IMR_PROTOCOL;

  /* [mbx-list-flags] */
  c=sio_getc(h->sio);
  while(c != ')') {
    unsigned i;
    if(c!= '\\') return IMR_PROTOCOL;
    c = imap_get_atom(h->sio, buf, sizeof(buf));
    for(i=0; i< ELEMENTS(mbx_flags); i++) {
      if(g_ascii_strcasecmp(buf, mbx_flags[i]) ==0) {
        IMAP_MBOX_SET_FLAG(flags, i);
        break;
      }
    }
    if( c != ' ' && c != ')') return IMR_PROTOCOL;
    if(c==' ') c = sio_getc(h->sio);
  }
  if(sio_getc(h->sio) != ' ') return IMR_PROTOCOL;
  if( (delim=sio_getc(h->sio)) == '"') 
    { delim=sio_getc(h->sio); while(sio_getc(h->sio)!= '"'); }
  else {
    if(delim            != 'N' ||
       sio_getc(h->sio) != 'I' ||
       sio_getc(h->sio) != 'L') return IMR_PROTOCOL;
    delim = '\0'; /* NIL */
  }
  if(sio_getc(h->sio) != ' ') return IMR_PROTOCOL;
  /* mailbox */
  s = imap_get_astring(h->sio, &c);
  mbx = imap_mailbox_to_utf8(s);
  rc = ir_check_crlf(h, c);
  g_signal_emit(G_OBJECT(h), imap_mbox_handle_signals[signal],
                0, delim, flags, mbx);
  g_free(s);
  g_free(mbx);
  return rc;
}

static ImapResponse
ir_list(ImapMboxHandle *h)
{
  return ir_list_lsub(h, LIST_RESPONSE);
}

static ImapResponse
ir_lsub(ImapMboxHandle *h)
{
  return ir_list_lsub(h, LSUB_RESPONSE);
}

/* 7.2.4 STATUS Response */
const char* imap_status_item_names[5] = {
  "MESSAGES", "RECENT", "UIDNEXT", "UIDVALIDITY", "UNSEEN" };
static ImapResponse
ir_status(ImapMboxHandle *h)
{
  int c;
  char *name;
  struct ImapStatusResult *resp;

  name = imap_get_astring(h->sio, &c);
  resp = g_hash_table_lookup(h->status_resps, name);
  if(c                != ' ') {g_free(name); return IMR_PROTOCOL;}
  if(sio_getc(h->sio) != '(') {g_free(name); return IMR_PROTOCOL;}
  do {
    char item[13], count[13]; /* longest than UIDVALIDITY */
    c = imap_get_atom(h->sio, item, sizeof(item));
    if(c == ')') break;
    if(c != ' ') {g_free(name); return IMR_PROTOCOL;}
    c = imap_get_atom(h->sio, count, sizeof(count));
    /* FIXME: process the response */
    if(resp) {
      unsigned idx, i;
      for(idx=0; idx<ELEMENTS(imap_status_item_names); idx++)
        if(g_ascii_strcasecmp(item, imap_status_item_names[idx]) == 0)
          break;
      for(i= 0; resp[i].item != IMSTAT_NONE; i++) {
        if(resp[i].item == idx) {
          if (sscanf(count, "%u", &resp[i].result) != 1) {
            g_free(name);
            return IMR_PROTOCOL;
          }
          break;
        }
      }
    }
  } while(c == ' ');
  g_free(name);
  /* g_return_val_if-fail(c == ')', IMR_BAD) */
  return ir_check_crlf(h, sio_getc(h->sio));
}

static void
esearch_cb(ImapUidRange *iur, void *arg)
{
  ImapMboxHandle *h = (ImapMboxHandle*)arg;
  unsigned i;
  for(i=iur->lo; i<= iur->hi; i++)
    h->search_cb(h, i, h->search_arg);
}

/** Process ESEARCH response. Consult RFC4466 and RFC4731 before
   modification.  */
static ImapResponse
ir_esearch(ImapMboxHandle *h)
{
  char atom[LONG_STRING];
  int c = sio_getc(h->sio);
  if(c == '(') { /* search correlator */
    gchar *str;
    c = imap_get_atom(h->sio, atom, sizeof(atom));
    if(c == EOF) return IMR_SEVERED;
    if(g_ascii_strcasecmp(atom, "TAG")) { /* TAG is the only acceptable response here! */
      printf("ESearch expected TAG encountered %s\n", atom);
      return IMR_PROTOCOL; 
    }
    if(c != ' ')
      return IMR_PROTOCOL;
    str = imap_get_string(h->sio);
    /* printf("ESearch response for tag %s\n", str); */
    g_free(str);
    if( (c = sio_getc(h->sio)) != ')') {
      return c == EOF ? IMR_SEVERED : IMR_PROTOCOL;
    }
    c = sio_getc(h->sio);
  }
  if(c == EOF) return IMR_SEVERED;  
  if (c == '\r' || c == '\n')
    return ir_check_crlf(h, c);
  /* Now, an atom has to follow */
  c = imap_get_atom(h->sio, atom, sizeof(atom));

  if(g_ascii_strcasecmp(atom, "UID") == 0) {
    c = imap_get_atom(h->sio, atom, sizeof(atom));
  }
  if(c == EOF) return IMR_SEVERED;

  while(c == ' ') { /* search-return-data in rfc4466 speak */
    ImapResponse rc;
    /* atom contains search-modifier-name, time to fetch
       search-return-value. In ESEARCH, it is always an
       tagged-ext-simple=sequence-set/number, which are an atoms, so
       we cut the corners here. We get values in chunks.  The chunk
       size is pretty arbitrary as long as it can fit two largest
       possible 32-bit unsigned numbers and a colon. */
    if ( (rc=imap_get_sequence(h, esearch_cb, h)) != IMR_OK)
      return rc;

    if( (c=sio_getc(h->sio)) == ' ')
      c = imap_get_atom(h->sio, atom, sizeof(atom));
  }

  return ir_check_crlf(h, c);
}

static ImapResponse
ir_search(ImapMboxHandle *h)
{
  int c;
  char seq[12];

  while ((c=imap_get_atom(h->sio, seq, sizeof(seq))), seq[0]) {
    if(h->search_cb)
      h->search_cb(h, strtol(seq, NULL, 10), h->search_arg);
    if(c == '\r') break;
  }
  return ir_check_crlf(h, c);
}

/* ir_sort: sort response handler. clears current view and creates a
   new one.
*/
/* draft-ietf-imapext-sort-13.txt:
 * sort-data = "SORT" *(SP nz-number) */
static ImapResponse
ir_sort(ImapMboxHandle *h)
{
  int c;
  char seq[12];
  while ((c=imap_get_atom(h->sio, seq, sizeof(seq))), seq[0]) {
    mbox_view_append_no(&h->mbox_view, strtol(seq, NULL, 10));
    if(c == '\r') break;
  }
  return ir_check_crlf(h, c);
}

static ImapResponse
ir_flags(ImapMboxHandle *h)
{
  /* FIXME: implement! */
  int c; EAT_LINE(h, c);
  return IMR_OK;
}

static ImapResponse
ir_exists(ImapMboxHandle *h, unsigned seqno)
{
  unsigned old_exists = h->exists;
  ImapResponse rc = ir_check_crlf(h, sio_getc(h->sio));
  imap_mbox_resize_cache(h, seqno);
  mbox_view_resize(&h->mbox_view, old_exists, seqno);

  g_signal_emit(G_OBJECT(h), imap_mbox_handle_signals[EXISTS_NOTIFY], 0);
                
  return rc;
}

static ImapResponse
ir_recent(ImapMboxHandle *h, unsigned seqno)
{
  h->recent = seqno;
  /* FIXME: send a signal here! */
  return ir_check_crlf(h, sio_getc(h->sio));
}

static ImapResponse
ir_expunge(ImapMboxHandle *h, unsigned seqno)
{
  ImapResponse rc = ir_check_crlf(h, sio_getc(h->sio));
  g_signal_emit(G_OBJECT(h), imap_mbox_handle_signals[EXPUNGE_NOTIFY],
		0, seqno);
  
  g_array_remove_index(h->flag_cache, seqno-1);
  if(h->msg_cache[seqno-1] != NULL)
    imap_message_free(h->msg_cache[seqno-1]);
  while(seqno<h->exists) {
    h->msg_cache[seqno-1] = h->msg_cache[seqno];
    seqno++;
  }
  h->exists--;
  mbox_view_expunge(&h->mbox_view, seqno);
  return rc;
}

static void
flags_tasklet(ImapMboxHandle *h, void *data)
{
  unsigned seqno = GPOINTER_TO_UINT(data);
  if(h->flags_cb)
    h->flags_cb(1, &seqno, h->flags_arg);
}

#define CREATE_IMSG_IF_NEEDED(h,seqno) \
  if((h)->msg_cache[seqno-1] == NULL) \
     (h)->msg_cache[(seqno)-1] = imap_message_new();

static ImapResponse
ir_msg_att_flags(ImapMboxHandle *h, int c, unsigned seqno)
{
  unsigned i;
  ImapMessage *msg;
  ImapFlagCache *flags;

  if(sio_getc(h->sio) != '(') return IMR_PROTOCOL;
  CREATE_IMSG_IF_NEEDED(h, seqno);
  msg = h->msg_cache[seqno-1];
  msg->flags = 0;

  do {
    char buf[LONG_STRING];
    c = imap_get_flag(h->sio, buf, sizeof(buf));
    for(i=0; i<ELEMENTS(imap_msg_flags); i++)
      if(buf[0] == '\\' && g_ascii_strcasecmp(imap_msg_flags[i], buf+1) == 0) {
        msg->flags |= 1<<i;
        break;
      }
  } while(c!=-1 && c != ')');

  flags = &g_array_index(h->flag_cache, ImapFlagCache, seqno-1);
  flags->flag_values = msg->flags;
  flags->known_flags = ~0; /* all of them are known */

  if(h->flags_cb)
    imap_handle_add_task(h, flags_tasklet, GUINT_TO_POINTER(seqno));
  return IMR_OK;
}

/* RFC 2087, sect. 5.2: "<mailbox> [<quota root> [<quota root> ...}}" */
static ImapResponse
ir_quotaroot(ImapMboxHandle *h)
{
  int eol;
  char *mbox;
  ImapResponse retval = IMR_NO;
  char *mbx7 = imap_utf8_to_mailbox(h->mbox);

  free(h->quota_root);
  h->quota_root = NULL;

  /* get the mailbox and the first quota root */
  mbox = imap_get_astring(h->sio, &eol);
  if (mbox) {
    if (strcmp(mbox, mbx7))
      fprintf(stderr, "expected QUOTAROOT for %s, not for %s\n", mbx7, mbox);
    else {
      if (eol == ' ')
        h->quota_root = imap_get_astring(h->sio, &eol);
      if (eol != '\n')
        EAT_LINE(h, eol);
      retval = IMR_OK;
    }
  }
  free(mbx7);
  free(mbox);
  return retval;
}

/* RFC 2087, sect. 5.1: "<mailbox> [<resource> [<resource> ...}}" */
static ImapResponse
ir_quota(ImapMboxHandle *h)
{
  int c;
  char *root;
  ImapResponse retval = IMR_NO;

  /* get the root */
  root = imap_get_astring(h->sio, &c);
  h->quota_max_k = h->quota_used_k = 0;
  if (root) {
    if (strcmp(root, h->quota_root))
      fprintf(stderr, "expected QUOTA for %s, not for %s\n", h->quota_root,
              root);
    else {
      while ((c = sio_getc(h->sio)) != -1 && c == ' ');
      if (c == '(') {
        do {
          char resource[32];
          char usage[16];
          char limit[16];
          
          c = imap_get_atom(h->sio, resource, 32);
          if (c == ' ') {
            imap_get_atom(h->sio, usage, 16);
            c = imap_get_atom(h->sio, limit, 16);

            /* ignore other limits than 'STORAGE' */
            if (!strcmp(resource, "STORAGE")) {
              char *endptr1;
              char *endptr2;

              h->quota_used_k = strtoul(usage, &endptr1, 10);
              h->quota_max_k = strtoul(limit, &endptr2, 10);
              if (*endptr1 != '\0' || *endptr2 != '\0') {
                fprintf(stderr, "bad QUOTA '%s %s %s'\n", resource, usage,
                        limit);
                h->quota_max_k = h->quota_used_k = 0;
                c = ')';
              } else
                retval = IMR_OK;
            }
          }
        } while (c != ')');
      }
      EAT_LINE(h, c);
    }
  }

  free(root);
  return retval;
}

/** \brief Interpret a RFC 4314 ACL
 *
 * \param h IMAP mailbox handle
 * \param eject a string containing all characters which shall terminate
 *        scanning the ACL
 * \param acl filled with the extracted ACL's, or IMAP_ACL_NONE on error
 * \param eol if not NULL, filled with 1 or 0 to indicate if the end of line
 *        has been reached
 * \return IMAP response code
 *
 * Scan h's input stream for valid ACL flags (lrswipkxtea).  Note that 'c', 'd'
 * and cr are ignored according to RFC 4314, sect. 2.1.1.
 * But note also that a server that complies with the older RFC 2086 and not
 * with RFC 4314 uses 'c' and 'd'; we can distinguish this case because it
 * does not advertise "RIGHTS=" capability.
 */
static ImapResponse
extract_acl(ImapMboxHandle *h, const char *eject, ImapAclType *acl, int *eol)
{
  static const char* rights = "lrswipkxtea";
  static const char* ignore = "cd\r";
  int c;
  char* p;

  if (!imap_mbox_handle_can_do(h, IMCAP_RIGHTS)) {
    /* workaround for RFC 2086- but not RFC 4314-compliant server */
    rights = "lrswipkxteacd";
  }
  *acl = IMAP_ACL_NONE;
  while ((c = sio_getc(h->sio)) != -1 && !strchr(eject, c)) {
    if ((p = strchr(rights, c))) {
      *acl |= 1 << (p - rights);
    } else if (!strchr(ignore, c)) {
      EAT_LINE(h, c);
      if (eol)
        *eol = TRUE;
      return IMR_NO;
    }
  }
  if (eol)
    *eol = (c == '\n');
  return IMR_OK;
}

/* RFC 4314, sect. 3.8: "<mailbox> <rights>" */
static ImapResponse
ir_myrights(ImapMboxHandle *h)
{
  int eol;
  char *mbox;
  ImapResponse retval = IMR_NO;
  char *mbx7 = imap_utf8_to_mailbox(h->mbox);

  mbox = imap_get_astring(h->sio, &eol);
  if (mbox && eol == ' ') {
    if (strcmp(mbox, mbx7))
      fprintf(stderr, "expected MYRIGHTS for %s, not for %s\n", mbx7, mbox);
    else {
      retval = extract_acl(h, "\n", &h->rights, NULL);
      h->has_rights = 1;
    }
  }
  free(mbx7);
  free(mbox);
  return retval;
}

/* helper: free an ImapUserAclType */
void
imap_user_acl_free(ImapUserAclType *acl)
{
  if (acl)
    g_free(acl->uid);
  g_free(acl);
}

/* RFC 4314, sect. 3.6: "<mailbox> [[<uid> <rights>] <uid> <rights> ...]" */
static ImapResponse
ir_getacl(ImapMboxHandle *h)
{
  char *mbox;
  char *mbx7;
  ImapResponse retval;
  int eol;

  g_list_foreach(h->acls, (GFunc)imap_user_acl_free, NULL);
  g_list_free(h->acls);
  h->acls = NULL;

  mbox = imap_get_astring(h->sio, &eol);
  if (!mbox)
    return IMR_NO;

  mbx7 = imap_utf8_to_mailbox(h->mbox);
  if (strcmp(mbox, mbx7)) {
    fprintf(stderr, "expected ACL for %s, not for %s\n", mbx7, mbox);
    retval = IMR_NO;
  } else if (eol == '\n') {
    retval = IMR_OK;
  } else {
    int c;
    GString *uid;

    retval = IMR_OK;
    do {
      ImapAclType acl_flags;
      ImapUserAclType *acl;

      uid = g_string_new("");
      while ((c = sio_getc(h->sio)) != -1 && c != '\n' && c != ' ')
        uid = g_string_append_c(uid, c);
      if (c != ' ') {
        g_string_free(uid, TRUE);
        EAT_LINE(h, c);
        retval = IMR_NO;
      } else {
        if (extract_acl(h, " \n", &acl_flags, &eol) != IMR_OK) {
          g_string_free(uid, TRUE);
          retval = IMR_NO;
        } else {
          acl = g_new(ImapUserAclType, 1);
          acl->uid = g_string_free(uid, FALSE);
          acl->acl = acl_flags;
          h->acls = g_list_append(h->acls, acl);
        }
      }
    } while (retval == IMR_OK && !eol);
  }
  free(mbox);
  free(mbx7);
  return retval;
}

ImapAddress*
imap_address_new(gchar *name, gchar *addr_spec)
{
  ImapAddress *res = g_new(ImapAddress, 1);
  res->name = name;
  res->addr_spec = addr_spec;
  res->next = NULL;
  return res;
}

void
imap_address_free(ImapAddress* addr)
{
  while(addr) {
    ImapAddress* next = addr->next;
    g_free(addr->name);
    g_free(addr->addr_spec);
    g_free(addr);
    addr = next;
  }
}

static ImapAddress*
imap_address_from_string(const gchar *string, gchar **n)
{
  const gchar *t;
  gchar *comment, *mailbox;
  ImapAddress *res = NULL;

  comment = get_quoted_string(string, &t);
  if(*t == ' ') {
    mailbox = get_quoted_string(t+1, &t);
    if(comment || mailbox) {
      res = imap_address_new(comment, mailbox);
      if(*t == ' ')
        res->next = imap_address_from_string(t+1, (gchar**)&t);
    }
  } else g_free(comment);

  if(n)
    *n = (gchar*)t;
  return res;
}

static gchar*
imap_address_to_string(const ImapAddress *addr)
{
  GString *res = g_string_sized_new(4);

  for(; addr; addr = addr->next) {
    if(addr->name) {
      append_quoted_string(res, addr->name);
    } else g_string_append_c(res, 'N');
    g_string_append_c(res, ' ');
    if(addr->addr_spec) {
      append_quoted_string(res, addr->addr_spec);
    } else g_string_append_c(res, 'N');
    g_string_append_c(res, ' ');
  }
  g_string_append(res, "N N");
  return g_string_free(res, FALSE);
}

/* imap_get_address: returns null if no beginning of address is found
   (eg., when end of list is found instead).
*/
static ImapAddress*
imap_get_address(struct siobuf* sio)
{
  char *addr[4], *p;
  ImapAddress *res = NULL;
  int i, c;

  /* DEERFIELD's IMAP SERVER sends address lists wrong. 
   * but we do not enable the workaround by default. */
#define WORKAROUND_FOR_NON_COMPLIANT_DEERFIELD_IMAP_SERVER 1
#if WORKAROUND_FOR_NON_COMPLIANT_DEERFIELD_IMAP_SERVER
  while((c=sio_getc (sio))==' ')
    ;
#else
  c=sio_getc (sio);
#endif
  if(c != '(') {
    sio_ungetc(sio);
    return NULL;
  }
  
  for(i=0; i<4; i++) {
    addr[i] = imap_get_nstring(sio);
    if( (c=sio_getc(sio)) != ' '); /* error if i < 3 but do nothing */
  }

  if (addr[0] && (p = strchr(addr[0], '\r'))) {
    /* Server sent a folded string--unfold it */
    char *q;
    for (q = p; *q; q++) {
      if (*q == '\r') {
        while (p > addr[0] && (p[-1] == ' ' || p[-1] == '\t')) --p;
        do q++;
        while (*q == '\n' || *q == ' ' || *q == '\t');
        if (!*q) break;
        /* Replace FWS with a single space */
        *p++ = ' ';
      }
      *p++ = *q;
    }
    *p = '\0';
  }

  if(c == ')') {
    if(addr[2] == NULL) /* end group */
      res = imap_address_new(NULL, NULL);
    else if(addr[3] == NULL) { /* begin group */
      res = imap_address_new(addr[2], NULL);
      addr[2] = NULL;
    } else {
      gchar * addr_spec = g_strconcat(addr[2], "@", addr[3], NULL);
      res = imap_address_new(addr[0], addr_spec);
      addr[0] = NULL;
    }
  }
  for(i=0; i<4; i++)
    if(addr[i]) g_free(addr[i]);
  return res;
}

static ImapResponse
imap_get_addr_list (struct siobuf *sio, ImapAddress ** list)
{
  int c;
  ImapAddress *res;
  ImapAddress **addr;

  if ((c=sio_getc (sio)) != '(') {
    if (imap_is_nil(sio, c)) return IMR_OK;
    else return IMR_PROTOCOL;
  }

  res = NULL;
  addr = &res;
  while ((*addr = imap_get_address (sio)) != NULL)
    addr = &(*addr)->next;
  if (sio_getc (sio) != ')') {
    imap_address_free (res);
    return IMR_PROTOCOL;
  }

  if (list)
    *list = res;
  else
    imap_address_free (res);

  return IMR_OK;
}

static ImapResponse
ir_envelope(struct siobuf *sio, ImapEnvelope *env)
{
  int c;
  char *date, *str;

  c=sio_getc(sio);

#define GMAIL_BUG_20100725 1
#if GMAIL_BUG_20100725 == 1
  /* GMAIL returns sometimes NIL instead of the envelope. */
  if (c == 'N') {
      printf("GMail message/rfc822 bug detected.\n");      
      env = NULL;
      if (sio_getc(sio) == 'I' &&
          sio_getc(sio) == 'L') return IMR_PARSE;
  }
#endif /* GMAIL_BUG_20100725 */
  if( c != '(') {
      printf("envelope's ( expected but got '%c'\n", c);
      return IMR_PROTOCOL;
  }

  date = imap_get_nstring(sio);
  if(date) {
    if(env) env->date = g_mime_utils_header_decode_date(date, NULL);
    g_free(date);
  }
  if( (c=sio_getc(sio)) != ' ') return IMR_PROTOCOL;
  str = imap_get_nstring(sio);
  if(env) env->subject = str; else g_free(str);
  if( (c=sio_getc(sio)) != ' ') return IMR_PROTOCOL;
  if(imap_get_addr_list(sio, env ? &env->from : NULL) != IMR_OK)
    return IMR_PROTOCOL;
  if( (c=sio_getc(sio)) != ' ') return IMR_PROTOCOL;
  if(imap_get_addr_list(sio, env ? &env->sender : NULL) != IMR_OK)
    return IMR_PROTOCOL;
  if( (c=sio_getc(sio)) != ' ') return IMR_PROTOCOL;
  if(imap_get_addr_list(sio, env ? &env->replyto : NULL) != IMR_OK)
    return IMR_PROTOCOL;
  if( (c=sio_getc(sio)) != ' ') return IMR_PROTOCOL;
  if(imap_get_addr_list(sio, env ? &env->to : NULL) != IMR_OK)
    return IMR_PROTOCOL;
  if( (c=sio_getc(sio)) != ' ') return IMR_PROTOCOL;
  if(imap_get_addr_list(sio, env ? &env->cc : NULL) != IMR_OK)
    return IMR_PROTOCOL;
  if( (c=sio_getc(sio)) != ' ') return IMR_PROTOCOL;
  if(imap_get_addr_list(sio, env ? &env->bcc : NULL) != IMR_OK)
    return IMR_PROTOCOL;
  if( (c=sio_getc(sio)) != ' ') return IMR_PROTOCOL;
  str = imap_get_nstring(sio);
  if(env) env->in_reply_to = str; else g_free(str);
  if( (c=sio_getc(sio)) != ' ') { printf("c=%c\n",c); return IMR_PROTOCOL;}
  str = imap_get_nstring(sio);
  if(env) env->message_id = str; else g_free(str);
  if( (c=sio_getc(sio)) != ')') { printf("c=%d\n",c);return IMR_PROTOCOL;}
  return IMR_OK;
}

static ImapResponse
ir_msg_att_envelope(ImapMboxHandle *h, int c, unsigned seqno)
{
  ImapMessage *msg;
  ImapEnvelope *env;

  CREATE_IMSG_IF_NEEDED(h, seqno);
  msg = h->msg_cache[seqno-1];
  if(msg->envelope) env = NULL;
  else {
    msg->envelope = env = imap_envelope_new();
  }
  return ir_envelope(h->sio, env);
}

static ImapResponse
ir_msg_att_internaldate(ImapMboxHandle *h, int c, unsigned seqno)
{
  return IMR_OK;
}
static ImapResponse
ir_msg_att_rfc822(ImapMboxHandle *h, int c, unsigned seqno)
{
  gchar *str = imap_get_nstring(h->sio);
  if(str && h->body_cb)
    h->body_cb(seqno, IMAP_BODY_TYPE_RFC822, str, strlen(str), h->body_arg);
  g_free(str);
  return IMR_OK;
}

static ImapResponse
ir_msg_att_rfc822_header(ImapMboxHandle *h, int c, unsigned seqno)
{
  return IMR_OK;
}
static ImapResponse
ir_msg_att_rfc822_text(ImapMboxHandle *h, int c, unsigned seqno)
{
  return IMR_OK;
}
static ImapResponse
ir_msg_att_rfc822_size(ImapMboxHandle *h, int c, unsigned seqno)
{
  char buf[12];
  ImapMessage *msg;

  c = imap_get_atom(h->sio, buf, sizeof(buf));

  if(c!= -1) sio_ungetc(h->sio);

  CREATE_IMSG_IF_NEEDED(h, seqno);
  msg = h->msg_cache[seqno-1];
  
  msg->rfc822size = strtol(buf, NULL, 10);  
  return IMR_OK;
}

static ImapResponse
ir_media(struct siobuf* sio, ImapMediaBasic *imb, ImapBody *body)
{
  gchar *type, *subtype;

  type    = imap_get_string(sio);
  if(!type) return IMR_PROTOCOL;

  if(sio_getc(sio) != ' ') { g_free(type); return IMR_PROTOCOL; }
  subtype = imap_get_string(sio);
  /* printf("media: %s/%s\n", type, subtype); */
  if     (g_ascii_strcasecmp(type, "APPLICATION") ==0) *imb = IMBMEDIA_APPLICATION;
  else if(g_ascii_strcasecmp(type, "AUDIO") ==0)       *imb = IMBMEDIA_AUDIO;
  else if(g_ascii_strcasecmp(type, "IMAGE") ==0)       *imb = IMBMEDIA_IMAGE;
  else if(g_ascii_strcasecmp(type, "MESSAGE") ==0) {
    if(g_ascii_strcasecmp(subtype, "RFC822") == 0)
      *imb = IMBMEDIA_MESSAGE_RFC822;
    else
      *imb = IMBMEDIA_MESSAGE_OTHER;
  }
  else if(g_ascii_strcasecmp(type, "TEXT") ==0)        *imb = IMBMEDIA_TEXT;
  else 
    *imb = IMBMEDIA_OTHER;

  if(body) {
    body->media_basic_name = type;
    body->media_basic = *imb;
    body->media_subtype = subtype;
  } else {
    g_free(type);
    g_free(subtype);
  }
  return IMR_OK;
}

static ImapResponse
ir_body_fld_param_hash(struct siobuf* sio, GHashTable * params)
{
  int c;
  gchar *key, *val;
  if( (c=sio_getc(sio)) == '(') {
    do {
      key = imap_get_string(sio);
      if(sio_getc(sio) != ' ') { g_free(key); return IMR_PROTOCOL; }
      val = imap_get_string(sio);
      if(params) {
        for(c=0; key[c]; c++)
          key[c] = tolower(key[c]);
        g_hash_table_insert(params, key, val);
      } else {
        g_free(key); g_free(val);
      }
    } while( (c=sio_getc(sio)) != ')' && c != EOF);
  } else if(toupper(c) != 'N' || toupper(sio_getc(sio)) != 'I' ||
            toupper(sio_getc(sio)) != 'L') return IMR_PROTOCOL;
  return IMR_OK;
}

static ImapResponse
ir_body_fld_param(struct siobuf* sio, ImapBody *body)
{
  return ir_body_fld_param_hash(sio, body ? body->params : NULL);
}

static ImapResponse
ir_body_fld_id(struct siobuf* sio, ImapBody *body)
{
  gchar* id = imap_get_nstring(sio);

  if(body)
    imap_body_set_id(body, id);
  else g_free(id);

  return IMR_OK;
}

static ImapResponse
ir_body_fld_desc(struct siobuf* sio, ImapBody *body)
{
  gchar* desc = imap_get_nstring(sio);
  if(body)
    imap_body_set_desc(body, desc);
  else g_free(desc);

  return IMR_OK;
}

static ImapResponse
ir_body_fld_enc(struct siobuf* sio, ImapBody *body)
{
  gchar* str = imap_get_string(sio);
  ImapBodyEncoding enc;

  /* if(!str) return IMR_PROTOCOL; required - but forgive this error */
  if     (str == NULL) enc = IMBENC_OTHER;
  else if(g_ascii_strcasecmp(str, "7BIT")==0)             enc = IMBENC_7BIT;
  else if(g_ascii_strcasecmp(str, "8BIT")==0)             enc = IMBENC_8BIT;
  else if(g_ascii_strcasecmp(str, "BINARY")==0)           enc = IMBENC_BINARY;
  else if(g_ascii_strcasecmp(str, "BASE64")==0)           enc = IMBENC_BASE64;
  else if(g_ascii_strcasecmp(str, "QUOTED-PRINTABLE")==0) enc = IMBENC_QUOTED;
  else enc = IMBENC_OTHER;
  if(body)
    body->encoding = enc;
  g_free(str);
  return IMR_OK;
}

static ImapResponse
ir_body_fld_octets(struct siobuf* sio, ImapBody *body)
{
  char buf[12];
  int c = imap_get_atom(sio, buf, sizeof(buf));

  if(c!= -1) sio_ungetc(sio);
  if(body) body->octets = strtol(buf, NULL, 10);  
  
  return IMR_OK;
}

static ImapResponse
ir_body_fields(struct siobuf* sio, ImapBody *body)
{
  ImapResponse rc;
  int c;

  if( (rc=ir_body_fld_param (sio, body))!=IMR_OK) return rc;
  if(sio_getc(sio) != ' ') return IMR_PROTOCOL;
  if( (rc=ir_body_fld_id    (sio, body))!=IMR_OK) return rc;
  if((c=sio_getc(sio)) != ' ') { printf("err=%c\n", c); return IMR_PROTOCOL; }
  if( (rc=ir_body_fld_desc  (sio, body))!=IMR_OK) return rc;
  if(sio_getc(sio) != ' ') return IMR_PROTOCOL;
  if( (rc=ir_body_fld_enc   (sio, body))!=IMR_OK) return rc;
  if(sio_getc(sio) != ' ') return IMR_PROTOCOL;
  if( (rc=ir_body_fld_octets(sio, body))!=IMR_OK) return rc;

  return IMR_OK;
}

static ImapResponse
ir_body_fld_lines(struct siobuf* sio, ImapBody* body)
{
  char buf[12];
  int c = imap_get_atom(sio, buf, sizeof(buf));

  if(c!= -1) sio_ungetc(sio);
  if(body) body->lines = strtol(buf, NULL, 10);  
  
  return IMR_OK;
}

/* body_fld_dsp = "(" string SP body_fld_param ")" / nil */
static ImapResponse
ir_body_fld_dsp (struct siobuf *sio, ImapBody * body)
{
  ImapResponse rc;
  int c;
  char *str;

  if ((c = sio_getc (sio)) != '(')
    {
      /* nil */
      if (!imap_is_nil (sio, c))
	return IMR_PROTOCOL;
      return IMR_OK;
    }

  /* "(" string */
  str = imap_get_string (sio);
  if (body)
    {
      if (!g_ascii_strcasecmp (str, "inline"))
	body->content_dsp = IMBDISP_INLINE;
      else if (!g_ascii_strcasecmp (str, "attachment"))
	body->content_dsp = IMBDISP_ATTACHMENT;
      else
	{
	  body->content_dsp = IMBDISP_OTHER;
	  body->content_dsp_other = g_strdup (str);
	}
    }
  g_free (str);

  /* SP body_fld_param ")" */
  if (sio_getc (sio) != ' ')
    return IMR_PROTOCOL;
  if (body)
    {
      body->dsp_params =
	g_hash_table_new_full (g_str_hash, g_str_equal, g_free,
			       g_free);
      rc = ir_body_fld_param_hash (sio, body->dsp_params);
    }
  else
    rc = ir_body_fld_param_hash (sio, NULL);

  if (rc != IMR_OK)
    return rc;

  if (sio_getc (sio) != ')')
    return IMR_PROTOCOL;

  return IMR_OK;
}

/* body-fld-lang = nstring / "(" string *(SP string) ")" */
static ImapResponse
ir_body_fld_lang (struct siobuf *sio, ImapBody * body)
{
  int c;

  c = sio_getc (sio);

  if (c != '(')
    {
      /* nstring */
      char *str;

      sio_ungetc (sio);
      str = imap_get_nstring (sio);
      if (str && body)
	body->ext.mpart.lang = g_slist_append (NULL, str);
      else
	g_free (str);

      return IMR_OK;
    }

  /* string *(SP string) ")" */
  do
    {
      char *str = imap_get_string (sio);
      if (body)
	body->ext.mpart.lang = g_slist_append (body->ext.mpart.lang, str);
      else
	g_free (str);
      c = sio_getc (sio);
      if (c != ' ' && c != ')')
	return IMR_PROTOCOL;
    }
  while (c != ')');

  return IMR_OK;
}

/* body-extension = nstring / number /
 *                  "(" body-extension *(SP body-extension) ")"
 */
static ImapResponse
ir_body_extension (struct siobuf *sio, ImapBody * body)
{
  ImapResponse rc;
  int c;

  c = sio_getc (sio);
  if (c == '(')
    {
      /* "(" body-extension *(SP body-extension) ")" */
      do
	{
	  rc = ir_body_extension (sio, body);
	  if (rc != IMR_OK)
	    return rc;
	  c = sio_getc (sio);
	  if (c != ' ' && c != ')')
	    return IMR_PROTOCOL;
	}
      while (c != ')');
    }
  else if (isdigit (c))
    {
      /* number */
      while (isdigit (sio_getc (sio)))
	;
      sio_ungetc (sio);
    }
  else
    /* nstring */
    g_free(imap_get_nstring(sio));

  return IMR_OK;
}

enum _ImapBodyExtensibility {
    IMB_NON_EXTENSIBLE,
    IMB_EXTENSIBLE,
    IMB_EXTENSIBLE_BUGGY_GMAIL
};
typedef enum _ImapBodyExtensibility ImapBodyExtensibility;

/* body-ext-mpart  = body-fld-param [SP body-fld-dsp [SP body-fld-lang
 *                   [SP body-fld-loc *(SP body-extension)]]]
 *                   ; MUST NOT be returned on non-extensible
 *                   ; "BODY" fetch
 */

static ImapResponse
ir_body_ext_mpart (struct siobuf *sio, ImapBody * body,
		   ImapBodyExtensibility type)
{
  ImapResponse rc;
  char *str;

  if (type == IMB_NON_EXTENSIBLE)
    return IMR_PROTOCOL;

  /* body_fld_param */
  if (body)
    {
      /* body->ext.mpart.params =
	g_hash_table_new_full (g_str_hash, g_str_equal, g_free,
        g_free); */
      rc = ir_body_fld_param_hash (sio, body->params);
    }
  else
    rc = ir_body_fld_param_hash (sio, NULL);

  if (rc != IMR_OK)
    return rc;

  /* [SP */
  if (sio_getc (sio) != ' ')
    {
      sio_ungetc (sio);
      return IMR_OK;
    }

  /* body_fld_dsp */
  rc = ir_body_fld_dsp (sio, body);
  if (rc != IMR_OK)
    return rc;

  /* [SP */
  if (sio_getc (sio) != ' ')
    {
      sio_ungetc (sio);
      return IMR_OK;
    }

  /* body_fld_lang */
  rc = ir_body_fld_lang (sio, body);
  if (rc != IMR_OK)
    return rc;

  /* [SP */
  if (sio_getc (sio) != ' ')
    {
      sio_ungetc (sio);
      return IMR_OK;
    }

  /* body-fld-loc */
  str = imap_get_nstring (sio);
  if (body)
    body->content_uri = str;
  else
    g_free(str);

  /* (SP body-extension)]]] */
  while (sio_getc (sio) == ' ')
    {
      rc = ir_body_extension (sio, body);
      if (rc != IMR_OK)
	return rc;
    }
  sio_ungetc (sio);

  return IMR_OK;
}

/* body-ext-1part  = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
 *                   [SP body-fld-loc *(SP body-extension)]]]
 *                   ; MUST NOT be returned on non-extensible
 *                   ; "BODY" fetch
 */
static ImapResponse
ir_body_ext_1part (struct siobuf *sio, ImapBody * body,
		   ImapBodyExtensibility type)
{
  ImapResponse rc;
  char *str;

  if (type == IMB_NON_EXTENSIBLE)
    return IMR_PROTOCOL;
#define GMAIL_BUG_20080601 1
#if GMAIL_BUG_20080601
  /* GMail sends number of lines on some parts like application/pgp-signature */
  { int c = sio_getc(sio);
    if(c == -1)
      return IMR_PROTOCOL;
    sio_ungetc(sio);
    if(isdigit(c)) { 
      char buf[20];
      printf("Incorrect GMail number-of-lines entry detected. "
	     "Working around.\n");
      c = imap_get_atom(sio, buf, sizeof(buf));
      if(c != ' ')
	return IMR_PROTOCOL;
    }
  }
#endif
  /* body_fld_md5 = nstring */
  if (type == IMB_EXTENSIBLE_BUGGY_GMAIL)
    str = NULL;
  else {
    str = imap_get_nstring (sio);
    if (body && str)
        body->ext.onepart.md5 = str;
    else
        g_free (str);

    /* [SP */
    if (sio_getc(sio) != ' ')
      {
        sio_ungetc (sio);
        return IMR_OK;
     }
  }
  /* body_fld_dsp */
  rc = ir_body_fld_dsp (sio, body);
  if (rc != IMR_OK)
    return rc;

  /* [SP */
  if (sio_getc (sio) != ' ')
    {
      sio_ungetc (sio);
      return IMR_OK;
    }

  /* body_fld_lang */
  rc = ir_body_fld_lang (sio, body);
  if (rc != IMR_OK)
    return rc;

  /* [SP */
  if (sio_getc (sio) != ' ')
    {
      sio_ungetc (sio);
      return IMR_OK;
    }

  /* body-fld-loc */
  str = imap_get_nstring (sio);
  if (body)
    body->content_uri = str;
  else
    g_free(str);

  /* (SP body-extension)]]] */
  while (sio_getc (sio) == ' ')
    {
      rc = ir_body_extension (sio, body);
      if (rc != IMR_OK)
	return rc;
    }
  sio_ungetc (sio);

  return IMR_OK;
}

/* body-type-mpart = 1*body SP media-subtype
 *                   [SP body-ext-mpart]
 */
static ImapResponse ir_body (struct siobuf *sio, int c, ImapBody * body,
			     ImapBodyExtensibility type);
static ImapResponse
ir_body_type_mpart (struct siobuf *sio, ImapBody * body,
		    ImapBodyExtensibility type)
{
  ImapResponse rc;
  gchar *str;
  int c;

  if (body)
    body->media_basic = IMBMEDIA_MULTIPART;

  /* 1*body */
  c = sio_getc (sio);
  do
    {
      ImapBody *b = body ? imap_body_new () : NULL;
      rc = ir_body (sio, c, b, type);
      if (body)
	imap_body_append_child (body, b);
      if (rc != IMR_OK)
	return rc;
    }
  while ((c = sio_getc (sio)) == '(');

  /* SP */
  if (c != ' ')
    return IMR_PROTOCOL;

  /* media-subtype = string */
  str = imap_get_string (sio);
  if (body)
    {
      g_assert (body->media_subtype == NULL);
      body->media_subtype = str;
    }
  else
    g_free (str);

  /* [SP */
  if (sio_getc (sio) != ' ')
    {
      sio_ungetc (sio);
      return IMR_OK;
    }

  /* body-ext-mpart] */
  rc = ir_body_ext_mpart (sio, body, type);
  if (rc != IMR_OK)
    return rc;

  return IMR_OK;
}

/* body-type-1part = (body-type-basic / body-type-msg / body-type-text)
 *                   [SP body-ext-1part]
 */
static ImapResponse
ir_body_type_1part (struct siobuf *sio, ImapBody * body,
		    ImapBodyExtensibility type)
{
  ImapResponse rc;
  ImapMediaBasic media_type;
  ImapEnvelope *env;
  ImapBody *b;

  /* body-type-basic = media-basic SP body-fields 
   * body-type-msg   = media-message SP body-fields SP envelope
   *                   SP body SP body-fld-lines 
   * body-type-text  = media-text SP body-fields SP body-fld-lines */
  if ((rc = ir_media (sio, &media_type, body)) != IMR_OK)
    return rc;
  if (sio_getc (sio) != ' ')
    return IMR_PROTOCOL;
  if ((rc = ir_body_fields (sio, body)) != IMR_OK)
    return rc;

  switch (media_type)
    {
    case IMBMEDIA_APPLICATION:
    case IMBMEDIA_AUDIO:
    case IMBMEDIA_IMAGE:
    case IMBMEDIA_MESSAGE_OTHER:
    case IMBMEDIA_OTHER:
    case IMBMEDIA_MULTIPART:	/*FIXME: check this one */
      break;
    case IMBMEDIA_MESSAGE_RFC822:
      if (sio_getc (sio) != ' ')
	return IMR_PROTOCOL;
      env = body ? imap_envelope_new () : NULL;
      rc = ir_envelope (sio, env);
#if GMAIL_BUG_20100725
      if (rc == IMR_PARSE)
          break;
#endif /* GMAIL_BUG_20100725 */
      if (rc != IMR_OK)
	{
	  if (env)
	    imap_envelope_free (env);
	  return rc;
	}
      if (sio_getc (sio) != ' ')
        return IMR_PROTOCOL;
      if (body)
	{
	  b = imap_body_new ();
	  body->envelope = env;
	}
      else
	b = NULL;
      rc = ir_body (sio, sio_getc (sio), b, type);
      if (body)
	imap_body_append_child (body, b);
      if (rc != IMR_OK)
	return rc;
      if (sio_getc (sio) != ' ')
	return IMR_PROTOCOL;
      if ((rc = ir_body_fld_lines (sio, body)) != IMR_OK)
	return rc;
      break;
    case IMBMEDIA_TEXT:
      if (sio_getc (sio) != ' ')
	return IMR_PROTOCOL;
      if ((rc = ir_body_fld_lines (sio, body)) != IMR_OK)
	return rc;
    }

  /* [SP */
  if (sio_getc (sio) != ' ')
    {
      sio_ungetc (sio);
      return IMR_OK;
    }

  /* body-ext-1part] */
#if GMAIL_BUG_20100725
  rc = ir_body_ext_1part (sio, body,
                          (rc == IMR_PARSE ? IMB_EXTENSIBLE_BUGGY_GMAIL : type));
#else  /* GMAIL_BUG_20100725 */
  rc = ir_body_ext_1part (sio, body, type);
#endif /* GMAIL_BUG_20100725 */
  if (rc != IMR_OK)
    return rc;

  return IMR_OK;
}

/* body = "(" (body-type-1part / body-type-mpart) ")" */
static ImapResponse
ir_body (struct siobuf *sio, int c, ImapBody * body,
	 ImapBodyExtensibility type)
{
  ImapResponse rc;

  if (c != '(')
    return IMR_PROTOCOL;

  c = sio_getc (sio);
  sio_ungetc (sio);
  if (c == '(')
    rc = ir_body_type_mpart (sio, body, type);
  else
    rc = ir_body_type_1part (sio, body, type);
  if (rc != IMR_OK)
    return rc;

  if (sio_getc (sio) != ')')
    return IMR_PROTOCOL;

  return IMR_OK;
}

/* read [section] and following string. FIXME: other kinds of body. */ 
static ImapResponse
ir_body_section(struct siobuf *sio, unsigned seqno,
		ImapFetchBodyType body_type,
		ImapFetchBodyInternalCb body_cb, void *arg)
{
  char buf[80];
  GString *bs;
  int i, c = imap_get_atom(sio, buf, sizeof(buf));

  for(i=0; buf[i] && (isdigit((int)buf[i]) || buf[i] == '.'); i++)
    ;
  if(i>0 && isalpha(buf[i])) /* we have \[[.0-9]something] */
    body_type = IMAP_BODY_TYPE_HEADER;

  if(c != ']') { puts("] expected"); return IMR_PROTOCOL; }
  if(sio_getc(sio) != ' ') { puts("space expected"); return IMR_PROTOCOL;}
  bs = imap_get_binary_string(sio);
  if(bs) {
    if(bs->str && body_cb)
      body_cb(seqno, body_type, bs->str, bs->len, arg);
    g_string_free(bs, TRUE);
  }
  return IMR_OK;
}

static ImapResponse
ir_body_header_fields(ImapMboxHandle *h, unsigned seqno)
{
  ImapMessage *msg;
  char *tmp;
  int c;

  if(sio_getc(h->sio) != '(') return IMR_PROTOCOL;

  while ((tmp = imap_get_astring(h->sio, &c))) {
      /* nothing (yet?) */;
    g_free(tmp);
    if (c == ')')
      break;
  }
  if(c != ')') return IMR_PROTOCOL;
  if(sio_getc(h->sio) != ']') return IMR_PROTOCOL;
  if(sio_getc(h->sio) != ' ') return IMR_PROTOCOL;

  tmp = imap_get_nstring(h->sio);
  if(h->body_cb) {
    if(tmp) h->body_cb(seqno, IMAP_BODY_TYPE_HEADER,
		       tmp, strlen(tmp), h->body_arg);
    g_free(tmp);
  } else {
    CREATE_IMSG_IF_NEEDED(h, seqno);
    msg = h->msg_cache[seqno-1];
    g_free(msg->fetched_header_fields);
    msg->fetched_header_fields = tmp;
  }
  return IMR_OK;
}

static ImapResponse
ir_msg_att_body(ImapMboxHandle *h, int c, unsigned seqno)
{
  ImapMessage *msg;
  ImapResponse rc;
  char buf[19];	/* Just large enough to hold "HEADER.FIELDS.NOT". */

  switch(c) {
  case '[': 
    c = sio_getc (h->sio);
    sio_ungetc (h->sio);
    if(isdigit (c)) {
      rc = ir_body_section(h->sio, seqno, IMAP_BODY_TYPE_BODY,
			   h->body_cb, h->body_arg);
      break;
    }
    c = imap_get_atom(h->sio, buf, sizeof buf);
    if (c == ']' &&
        (g_ascii_strcasecmp(buf, "HEADER") == 0 ||
         g_ascii_strcasecmp(buf, "TEXT") == 0)) {
      ImapFetchBodyType body_type = 
	(g_ascii_strcasecmp(buf, "TEXT") == 0)
	? IMAP_BODY_TYPE_TEXT : IMAP_BODY_TYPE_HEADER;
      sio_ungetc (h->sio); /* put the ']' back */
      rc = ir_body_section(h->sio, seqno, body_type, h->body_cb, h->body_arg);
    } else {
      if (c == ' ' && 
          (g_ascii_strcasecmp(buf, "HEADER.FIELDS") == 0 ||
           g_ascii_strcasecmp(buf, "HEADER.FIELDS.NOT") == 0))
        rc = ir_body_header_fields(h, seqno);
      else
        rc = IMR_PROTOCOL;
    }
    break;
  case ' ':
    CREATE_IMSG_IF_NEEDED(h, seqno);
    msg = h->msg_cache[seqno-1];
    rc = ir_body(h->sio, sio_getc(h->sio),
                 msg->body ? NULL : (msg->body = imap_body_new()), 
		 IMB_NON_EXTENSIBLE);
    break;
  default: rc = IMR_PROTOCOL; break;
  }
  return rc;
}

static ImapResponse
ir_msg_att_bodystructure(ImapMboxHandle *h, int c, unsigned seqno)
{
  ImapMessage *msg;
  ImapResponse rc;

  switch(c) {
  case ' ':
    CREATE_IMSG_IF_NEEDED(h, seqno);
    msg = h->msg_cache[seqno-1];
    rc = ir_body(h->sio, sio_getc(h->sio),
                 msg->body ? NULL : (msg->body = imap_body_new()), 
		 IMB_EXTENSIBLE);
    break;
  default: rc = IMR_PROTOCOL; break;
  }
  return rc;
}

static ImapResponse
ir_msg_att_uid(ImapMboxHandle *h, int c, unsigned seqno)
{
  char buf[12];
  c = imap_get_atom(h->sio, buf, sizeof(buf));

  if(c!= -1) sio_ungetc(h->sio);
  CREATE_IMSG_IF_NEEDED(h, seqno);
  h->msg_cache[seqno-1]->uid = strtol(buf, NULL, 10);
  return IMR_OK;
}

static ImapResponse
ir_fetch_seq(ImapMboxHandle *h, unsigned seqno)
{
  static const struct {
    const gchar* name;
    ImapResponse (*handler)(ImapMboxHandle *h, int c, unsigned seqno);
  } msg_att[] = {
    { "FLAGS",         ir_msg_att_flags },
    { "ENVELOPE",      ir_msg_att_envelope },
    { "INTERNALDATE",  ir_msg_att_internaldate }, 
    { "RFC822",        ir_msg_att_rfc822 },     
    { "RFC822.HEADER", ir_msg_att_rfc822_header }, 
    { "RFC822.TEXT",   ir_msg_att_rfc822_text }, 
    { "RFC822.SIZE",   ir_msg_att_rfc822_size }, 
    { "BINARY",        ir_msg_att_body }, 
    { "BODY",          ir_msg_att_body }, 
    { "BODYSTRUCTURE", ir_msg_att_bodystructure }, 
    { "UID",           ir_msg_att_uid }
  };
  char atom[LONG_STRING]; /* make sure LONG_STRING is longer than all */
                          /* strings above */
  unsigned i;
  int c = 0;
  ImapResponse rc;

  if(seqno<1 || seqno > h->exists) return IMR_PROTOCOL;
  if(sio_getc(h->sio) != '(') return IMR_PROTOCOL;
  do {
    for(i=0; i<sizeof(atom)-1 && (c = sio_getc(h->sio)) != -1; i++) {
      c = toupper(c);
      if( !( (c >='A' && c<='Z') || (c >='0' && c<='9') || c == '.') ) break;
      atom[i] = c;
    }
    atom[i] = '\0';
    for(i=0; i<ELEMENTS(msg_att); i++) {
      if(g_ascii_strcasecmp(atom, msg_att[i].name) == 0) {
        if( (rc=msg_att[i].handler(h, c, seqno)) != IMR_OK)
          return rc;
        break;
      }
    }
    c=sio_getc(h->sio);
  } while( c!= EOF && c == ' ');
  if(c!=')') return IMR_PROTOCOL;
  return ir_check_crlf(h, sio_getc(h->sio));
}

static ImapResponse
ir_fetch(ImapMboxHandle *h)
{
  char buf[12];
  unsigned seqno;
  int i;

  i = imap_get_atom(h->sio, buf, sizeof(buf));
  seqno = strtol(buf, NULL, 10);
  if(seqno == 0) return IMR_PROTOCOL;
  if(i != ' ') return IMR_PROTOCOL;
  return ir_fetch_seq(h, seqno);
}

/* THREAD response handling code.
   Example:    S: * THREAD (2)(3 6 (4 23)(44 7 96))
   
   The first thread consists only of message 2.  The second thread
   consists of the messages 3 (parent) and 6 (child), after which it
   splits into two subthreads; the first of which contains messages 4
   (child of 6, sibling of 44) and 23 (child of 4), and the second of
   which contains messages 44 (child of 6, sibling of 4), 7 (child of
   44), and 96 (child of 7).  Since some later messages are parents
   of earlier messages, the messages were probably moved from some
   other mailbox at different times.
   
   -- 2
   
   -- 3
     \-- 6
         |-- 4
         |   \-- 23
         |
         \-- 44
             \-- 7
                \-- 96
*/
static ImapResponse
ir_thread_sub(ImapMboxHandle *h, GNode *parent, int last)
{
  char buf[12];
  unsigned seqno;
  int c;
  GNode *item;
  ImapResponse rc = IMR_OK;

  c = imap_get_atom(h->sio, buf, sizeof(buf));

  seqno = strtol(buf, NULL, 10);
  if(seqno == 0 && c == '(') {
      while (c == '(') {
	  rc = ir_thread_sub(h, parent, c);
	  if (rc!=IMR_OK) {
	      return rc;
	  }
	  c=sio_getc(h->sio);
          if(c<0) return IMR_SEVERED;
      }
      return rc;
  }
  if(seqno == 0) return IMR_PROTOCOL;
  item = g_node_append_data(parent, GUINT_TO_POINTER(seqno));
  if (c == ' ') {
      rc = ir_thread_sub(h, item, c);
  }

  return rc;
}

static ImapResponse
ir_thread(ImapMboxHandle *h)
{
  GNode *root;
  int c;
  ImapResponse rc = IMR_OK;
  
  c=sio_getc(h->sio);
  if(h->thread_root)
    g_node_destroy(h->thread_root);
  h->thread_root = NULL;
  root = g_node_new(NULL);
  while (c == '(') {
    rc=ir_thread_sub(h, root, c);
    if (rc!=IMR_OK)
      break;
    c=sio_getc(h->sio);
  }
  if (rc == IMR_OK)
    rc = ir_check_crlf(h, c);

  if (rc != IMR_OK)
      g_node_destroy(root);
  else
      h->thread_root = root;

  return rc;
}


/* response dispatch code */
static const struct {
  const gchar *response;
  int keyword_len;
  ImapResponse (*handler)(ImapMboxHandle *h);
} ResponseHandlers[] = {
  { "OK",         2, ir_ok },
  { "NO",         2, ir_no },
  { "BAD",        3, ir_bad },
  { "PREAUTH",    7, ir_preauth },
  { "BYE",        3, ir_bye },
  { "CAPABILITY",10, ir_capability },
  { "LIST",       4, ir_list },
  { "LSUB",       4, ir_lsub },
  { "STATUS",     6, ir_status },
  { "ESEARCH",    7, ir_esearch },
  { "SEARCH",     6, ir_search },
  { "SORT",       4, ir_sort   },
  { "THREAD",     6, ir_thread },
  { "FLAGS",      5, ir_flags  },
  { "FETCH",      5, ir_fetch  },
  { "MYRIGHTS",   8, ir_myrights },
  { "ACL",        3, ir_getacl },
  { "QUOTAROOT",  9, ir_quotaroot },
  { "QUOTA",      5, ir_quota }
};
static const struct {
  const gchar *response;
  int keyword_len;
  ImapResponse (*handler)(ImapMboxHandle *h, unsigned seqno);
} NumHandlers[] = {
  { "EXISTS",     6, ir_exists },
  { "RECENT",     6, ir_recent },
  { "EXPUNGE",    7, ir_expunge },
  { "FETCH",      5, ir_fetch_seq }
};
  
/* the public interface: */
static ImapResponse
ir_handle_response(ImapMboxHandle *h)
{
  int c;
  char atom[LONG_STRING];
  unsigned i, seqno;
  ImapResponse rc = IMR_BAD; /* unknown response is really an error */

  c = imap_get_atom(h->sio, atom, sizeof(atom));
  if( isdigit(atom[0]) ) {
    if (c != ' ')
      return IMR_PROTOCOL;
    seqno = strtol(atom, NULL, 10);
    c = imap_get_atom(h->sio, atom, sizeof(atom));
    if (c == 0x0d)
      sio_ungetc(h->sio);
    for(i=0; i<ELEMENTS(NumHandlers); i++) {
      if(g_ascii_strncasecmp(atom, NumHandlers[i].response, 
                             NumHandlers[i].keyword_len) == 0) {
        rc = NumHandlers[i].handler(h, seqno);
        break;
      }
    }
  } else {
    if (c == 0x0d)
      sio_ungetc(h->sio);
    for(i=0; i<ELEMENTS(ResponseHandlers); i++) {
      if(g_ascii_strncasecmp(atom, ResponseHandlers[i].response, 
                             ResponseHandlers[i].keyword_len) == 0) {
        rc = ResponseHandlers[i].handler(h);
        break;
      }
    }
  }
  imap_handle_process_tasks(h);
  return rc;
}

GNode*
imap_mbox_handle_get_thread_root(ImapMboxHandle* handle)
{
  g_return_val_if_fail(handle, NULL);
  return handle->thread_root;
}

gchar*
imap_coalesce_seq_range(int lo, int hi, ImapCoalesceFunc incl, void *data)
{
  GString * res = g_string_sized_new(16);
  enum { BEGIN, LASTOUT, LASTIN, RANGE } mode = BEGIN;
  int seq;
  unsigned prev =0, num = 0;

  for(seq=lo; seq<=hi+1; seq++) {
    if(seq<=hi && (num=incl(seq, data)) != 0) {
      switch(mode) {
      case BEGIN: 
        g_string_append_printf(res, "%u", num);
        mode = LASTIN; break;
      case RANGE:
        if(num!=prev+1) {
          g_string_append_printf(res, ":%u,%u", prev, num);
          mode = LASTIN;
        }
        break;
      case LASTIN: 
        if(num==prev+1) {
          mode = RANGE;
          break;
        } /* else fall through */
      case LASTOUT: 
        g_string_append_printf(res, ",%u", num);
        mode = LASTIN; break;
      }
    } else {
      switch(mode) {
      case BEGIN:
      case LASTOUT: break;
      case LASTIN: mode = LASTOUT; break;
      case RANGE: 
        g_string_append_printf(res, ":%u", prev);
        mode = LASTOUT;
        break;
      }
    }
    prev = num;
  }
  return g_string_free(res, mode == BEGIN);
}

unsigned
imap_coalesce_func_simple(int i, unsigned msgno[])
{
  return msgno[i];
}

gchar*
imap_coalesce_set(int cnt, unsigned *seqnos)
{
 return imap_coalesce_seq_range(0, cnt-1,
				(ImapCoalesceFunc)imap_coalesce_func_simple,
				seqnos);
}


/* =================================================================== */
/*               MboxView routines                                     */
/* =================================================================== */
#ifdef DEEP_MBOX_VIEW_IMPLEMENTATION_OUT_OF_BALSA
#define MBOX_VIEW_IS_ACTIVE(mv) ((mv)->arr != NULL)
#else
#define MBOX_VIEW_IS_ACTIVE(mv) 0
#endif
void
mbox_view_init(MboxView *mv)
{
  mv->arr = NULL;
  mv->allocated = mv->entries = 0;
  mv->filter_str = NULL;
}

/* mbox_view_resize:
   When new messages appear in the mailbox, we need to resize the view
   as well. We assume that the new messages fulfill the filtering
   condition which does not have to be true. In principle, we should
   apply the filter for them as well. We do it next time.
*/
void
mbox_view_resize(MboxView *mv, unsigned old_exists, unsigned new_exists)
{

  if( !MBOX_VIEW_IS_ACTIVE(mv) ) return;
  if(old_exists>new_exists) {
    unsigned src, dest;
    /* entries (new_exists, old_exists] removed */
    /* this probably will never get called without earlier EXPUNGE */
    for(dest=src=0; src<mv->entries; src++) {
      if(mv->arr[src]<=new_exists)
        mv->arr[dest++] = mv->arr[src];
    }
    mv->entries = dest;
  } else {
    /* entries (old_exists, new_exists] added */
    /* FIXME: we should apply the filter below, instead of assuming
     * that all the messages match the filter.
     * but, since we may be in the response handler.
     * Queue new request? Idea of tasklets? */
    int delta, i;
    if(new_exists>mv->allocated) {
      mv->allocated = mv->allocated ? mv->allocated*2 : 16;
      mv->arr = g_realloc(mv->arr, mv->allocated*sizeof(unsigned));
    }
    delta = new_exists - old_exists;
    for(i=0; i<delta; i++)
      mv->arr[mv->entries+i] = old_exists+1+i;
  mv->entries += delta;
  }
}

void
mbox_view_expunge(MboxView *mv, unsigned seqno)
{
  unsigned i;

  if( !MBOX_VIEW_IS_ACTIVE(mv) ) return;
  for(i=0; i<mv->entries && mv->arr[i] != seqno; i++)
    ;
  for(; i<mv->entries-1; i++)
    mv->arr[i] = mv->arr[i+1];
  mv->entries = i;
}

void
mbox_view_dispose(MboxView *mv)
{
  g_free(mv->arr);
  mv->arr = NULL;
  mv->allocated = mv->entries = 0;
  g_free(mv->filter_str); mv->filter_str = NULL;
}

void
mbox_view_append_no(MboxView *mv, unsigned seqno)
{
  if(mv->allocated == mv->entries) {
    mv->allocated = mv->allocated ? mv->allocated*2 : 16;
    mv->arr = g_realloc(mv->arr, mv->allocated*sizeof(unsigned));
  }
  mv->arr[mv->entries++] = seqno;
}

gboolean
mbox_view_is_active(MboxView *mv)
{
  return MBOX_VIEW_IS_ACTIVE(mv);
}

unsigned
mbox_view_cnt(MboxView *mv)
{
  return mv->entries;
}

unsigned
mbox_view_get_msg_no(MboxView *mv, unsigned msgno)
{
  return mv->arr[msgno-1];
}

unsigned
mbox_view_get_rev_no(MboxView *mv, unsigned seqno)
{
  unsigned lo = 0, hi = mv->entries-1;
  if(mv->entries == 0) return 0;
  if(seqno<mv->arr[lo] || seqno>mv->arr[hi]) return 0;
  while(lo<=hi) {
    if(seqno == mv->arr[lo])
      return lo+1;
    else if(seqno == mv->arr[hi])
      return hi+1;
    else {
      unsigned mid = (lo+hi)/2;
      if(seqno<mv->arr[mid])
        hi=mid-1;
      else if(seqno>mv->arr[mid])
        lo=mid+1;
      else return mid+1;
    }
  }
  return 0;
}

const char*
mbox_view_get_str(MboxView *mv)
{
  return mv->filter_str ? mv->filter_str : "";
}