summaryrefslogtreecommitdiff
path: root/src/imapcommands.c
blob: 54b66a4d7ef7bda9ad380965d6076bb3fdd7a29a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
/*
 Copyright (C) 1999-2004 IC & S  dbmail@ic-s.nl
 Copyright (c) 2004-2010 NFG Net Facilities Group BV support@nfg.nl

 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 of the License, 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

/* 
 *
 * imapcommands.c
 * 
 * IMAP server command implementations
 */

#include "dbmail.h"
#define THIS_MODULE "imap"

#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif

extern db_param_t _db_params;
#define DBPFX _db_params.pfx

extern serverConfig_t *server_conf;
extern int selfpipe[2];
extern GAsyncQueue *queue;
extern const char *imap_flag_desc[];
extern const char *imap_flag_desc_escaped[];
extern const char AcceptedMailboxnameChars[];

int imap_before_smtp = 0;

struct cmd_t {
	gboolean silent;
	int action;
	int flaglist[IMAP_NFLAGS];
	GList *keywords;
	u64_t mailbox_id;
};

cmd_t cmd_new(void)
{
	return (cmd_t)g_malloc0(sizeof(cmd_t));
}

void cmd_free(cmd_t *cmd)
{
	assert(cmd && *cmd);
	if ((*cmd)->keywords)
		g_list_destroy((*cmd)->keywords);
	(*cmd)->keywords = NULL;
	g_free((*cmd));	
}

/* 
 * push a message onto the queue and notify the
 * event-loop by sending a char into the selfpipe
 */

#define SESSION_GET \
	ImapSession *self = D->session

#define SESSION_RETURN \
	D->session->command_state = TRUE; \
	g_async_queue_push(queue, (gpointer)D); \
	if (selfpipe[1] > -1) { \
		if (write(selfpipe[1], "Q", 1) != 1) { /* ignore */; } \
	} \
	return;

#define SESSION_OK \
	if (self->state != CLIENTSTATE_ERROR) \
		dbmail_imap_session_buff_printf(self, \
				"%s OK %s%s completed\r\n", \
				self->tag, self->use_uid ? "UID " : "", \
				self->command)
/*
 * RETURN VALUES _ic_ functions:
 *
 * -1 Fatal error, close connection to user
 *  0 Succes
 *  1 Non-fatal error, connection stays alive
 */

/* 
 * ANY-STATE COMMANDS: capability, starttls, noop, logout, id
 */
/*
 * _ic_capability()
 *
 * returns a string to the client containing the server capabilities
 */
// a trivial silly thread example
void _ic_capability_enter(dm_thread_data *D)
{
	SESSION_GET;
	dbmail_imap_session_buff_printf(self, "* %s %s\r\n", self->command, Capa_as_string(self->capa));
	SESSION_OK;
	SESSION_RETURN;
}

int _ic_capability(ImapSession *self)
{
	if (!check_state_and_args(self, 0, 0, CLIENTSTATE_ANY)) return 1;
	dm_thread_data_push((gpointer)self, _ic_capability_enter, _ic_cb_leave, NULL);
	return 0;
}

int _ic_starttls(ImapSession *self)
{
	int i;
	if (!check_state_and_args(self, 0, 0, CLIENTSTATE_ANY)) return 1;
	if (! server_conf->ssl) {
		ci_write(self->ci, "%s NO TLS not available\r\n", self->tag);
		return 1;
	}
	if (self->ci->ssl_state) {
		ci_write(self->ci, "%s NO TLS already active\r\n", self->tag);
		return 1;
	}
	ci_write(self->ci, "%s OK Begin TLS now\r\n", self->tag);
	i = ci_starttls(self->ci);
	if (i < 0) i = 0;

	if (i == 0) return 3; /* done */

	return i;
}

/*
 * _ic_noop()
 *
 * performs No operation
 */

void _ic_noop_enter(dm_thread_data *D) 
{
	SESSION_GET;
	if (self->state == CLIENTSTATE_SELECTED)
		dbmail_imap_session_mailbox_status(self, TRUE);
	SESSION_OK;
	SESSION_RETURN;
}


int _ic_noop(ImapSession *self)
{
	if (!check_state_and_args(self, 0, 0, CLIENTSTATE_ANY)) return 1;
	dm_thread_data_push((gpointer)self, _ic_noop_enter, _ic_cb_leave, NULL);
	return 0;
}

/*
 * _ic_logout()
 *
 * prepares logout from IMAP-server
 */
int _ic_logout(ImapSession *self)
{
	if (!check_state_and_args(self, 0, 0, CLIENTSTATE_ANY)) return 1;
	dbmail_imap_session_set_state(self, CLIENTSTATE_LOGOUT);
	TRACE(TRACE_NOTICE, "[%p] userid:[%llu]", self, self->userid);
	return 2;
}

void _ic_id_enter(dm_thread_data *D)
{
	SESSION_GET;
	struct utsname buf;
	memset(&buf, 0, sizeof(buf));
	uname(&buf);
	dbmail_imap_session_buff_printf(self, "* ID (\"name\" \"dbmail\" \"version\" \"%s\""
		" \"os\" \"%s\" \"os-version\" \"%s\")\r\n", VERSION, &buf.sysname, &buf.release);
	SESSION_OK;
	SESSION_RETURN;
}

int _ic_id(ImapSession *self)
{
	if (!check_state_and_args(self, 1, 0, CLIENTSTATE_ANY)) return 1;
	dm_thread_data_push((gpointer)self, _ic_id_enter, _ic_cb_leave, NULL);
	return 0;
}
/*
 * PRE-AUTHENTICATED STATE COMMANDS
 * login, authenticate
 */

/* _ic_login()
 *
 * Performs login-request handling.
 */
int _ic_login(ImapSession *self)
{
	return _ic_authenticate(self);
}


/* _ic_authenticate()
 * 
 * performs authentication using LOGIN mechanism:
 */
void _ic_authenticate_enter(dm_thread_data *D)
{
	int err;
	SESSION_GET;
	if ((err = dbmail_imap_session_handle_auth(self,self->args[self->args_idx],self->args[self->args_idx+1]))) {
		D->status = err;
		SESSION_RETURN;
	}
	if (imap_before_smtp) 
		db_log_ip(self->ci->src_ip);

	dbmail_imap_session_buff_printf(self, "* CAPABILITY %s\r\n", Capa_as_string(self->capa));
	SESSION_OK;
	SESSION_RETURN;
}

int _ic_authenticate(ImapSession *self)
{
	if (self->command_type == IMAP_COMM_AUTH) {
		if (!check_state_and_args(self, 1, 3, CLIENTSTATE_NON_AUTHENTICATED)) return 1;
		/* check authentication method */
		if ( (! MATCH(self->args[self->args_idx], "login")) && \
			(! MATCH(self->args[self->args_idx], "cram-md5")) ) {
			dbmail_imap_session_buff_printf(self, "%s NO Invalid authentication mechanism specified\r\n", self->tag);
			return 1;
		}
		self->args_idx++;
	} else {
		if (!check_state_and_args(self, 2, 2, CLIENTSTATE_NON_AUTHENTICATED)) return 1;
	}

	dm_thread_data_push((gpointer)self, _ic_authenticate_enter, _ic_cb_leave, NULL);
	return 0;
}


/* 
 * AUTHENTICATED STATE COMMANDS 
 * select, examine, create, delete, rename, subscribe, 
 * unsubscribe, list, lsub, status, append
 */

/* _ic_select()
 * 
 * select a specified mailbox
 */
static gboolean mailbox_first_unseen(gpointer key, gpointer value, gpointer data)
{
	MessageInfo *msginfo = (MessageInfo *)value;
	if (msginfo->flags[IMAPFLAG_SEEN]) return FALSE; 
	*(u64_t *)data = *(u64_t *)key;
	return TRUE;
}

static int imap_session_mailbox_close(ImapSession *self)
{
	// flush recent messages from previous select
	dbmail_imap_session_set_state(self,CLIENTSTATE_AUTHENTICATED);
	if (self->mailbox) {
		dbmail_mailbox_free(self->mailbox);
		self->mailbox = NULL;
	}

	return 0;
}

static int mailbox_check_acl(ImapSession *self, MailboxState_T S, ACLRight_t acl)
{
	int access = acl_has_right(S, self->userid, acl);
	if (access < 0) {
		dbmail_imap_session_buff_printf(self, "* BYE internal database error\r\n");
		return -1;
	}
	if (access == 0) {
		dbmail_imap_session_buff_printf(self, "%s NO permission denied\r\n", self->tag);
		return 1;
	}
	TRACE(TRACE_DEBUG,"access granted");
	return 0;

}


static gboolean mailbox_build_recent(u64_t *uid, MessageInfo *msginfo, ImapSession *self)
{
	if (msginfo->flags[IMAP_FLAG_RECENT])
		self->recent = g_list_prepend(self->recent, g_strdup_printf("%llu", *uid));
	return FALSE;
}


static int imap_session_mailbox_open(ImapSession * self, const char * mailbox)
{
	int err;
	u64_t mailbox_idnr = 0;

	/* get the mailbox_idnr */
	db_findmailbox(mailbox, self->userid, &mailbox_idnr);
	
	/* create missing INBOX for this authenticated user */
	if ((! mailbox_idnr ) && (strcasecmp(mailbox, "INBOX")==0)) {
		TRACE(TRACE_INFO, "[%p] Auto-creating INBOX for user id [%llu]", self, self->userid);
		err = db_createmailbox("INBOX", self->userid, &mailbox_idnr);
	}
	
	if (! mailbox_idnr) {
		dbmail_imap_session_buff_printf(self, "%s NO specified mailbox does not exist\r\n", self->tag);
		return 1; /* error */
	}

	/* new mailbox structure */
	self->mailbox = dbmail_mailbox_new(mailbox_idnr);

	/* fetch mailbox metadata */
	self->mailbox->mbstate = dbmail_imap_session_mbxinfo_lookup(self, mailbox_idnr, TRUE);

	/* check if user has right to select mailbox */
	if (mailbox_check_acl(self, self->mailbox->mbstate, ACL_RIGHT_READ) == 1) {
		dbmail_imap_session_set_state(self,CLIENTSTATE_AUTHENTICATED);
		return DM_EGENERAL;
	}
	
	if (self->command_type == IMAP_COMM_SELECT) {
		// SELECT
		MailboxState_setPermission(self->mailbox->mbstate,IMAPPERM_READWRITE);
	} else {
		// EXAMINE
		MailboxState_setPermission(self->mailbox->mbstate,IMAPPERM_READ);
	}

	/* check if mailbox is selectable */
	if (MailboxState_noSelect(self->mailbox->mbstate)) return DM_EGENERAL;

	/* build list of recent messages */
        if (MailboxState_getPermission(self->mailbox->mbstate) == IMAPPERM_READWRITE && MailboxState_getMsginfo(self->mailbox->mbstate)) {
		GTree *info = MailboxState_getMsginfo(self->mailbox->mbstate);
		g_tree_foreach(info, (GTraverseFunc)mailbox_build_recent, self);
		TRACE(TRACE_DEBUG, "build list of [%d] [%d] recent messages...", g_tree_nnodes(info), g_list_length(self->recent));
	}

	return 0;
}

static void _ic_select_enter(dm_thread_data *D)
{
	int err;
	char *flags;
	const char *okarg;
	MailboxState_T S;
	SESSION_GET;

	/* close the currently opened mailbox */
	imap_session_mailbox_close(self);

	if ((err = imap_session_mailbox_open(self, self->args[self->args_idx]))) {
		D->status = err;
		SESSION_RETURN;
	}	
	dbmail_imap_session_set_state(self,CLIENTSTATE_SELECTED);

	S = self->mailbox->mbstate;

	dbmail_imap_session_buff_printf(self, "* %u EXISTS\r\n", MailboxState_getExists(S));
	dbmail_imap_session_buff_printf(self, "* %u RECENT\r\n", MailboxState_getRecent(S));

	/* flags */
	flags = MailboxState_flags(S);
	dbmail_imap_session_buff_printf(self, "* FLAGS (%s)\r\n", flags);
	dbmail_imap_session_buff_printf(self, "* OK [PERMANENTFLAGS (%s \\*)] Flags allowed.\r\n", flags);
	g_free(flags);

	/* UIDNEXT */
	dbmail_imap_session_buff_printf(self, "* OK [UIDNEXT %llu] Predicted next UID\r\n",
		MailboxState_getUidnext(S));
	
	/* UID */
	dbmail_imap_session_buff_printf(self, "* OK [UIDVALIDITY %llu] UID value\r\n",
		MailboxState_getId(S));

	if (MailboxState_getExists(S)) { 
		/* show msn of first unseen msg (if present) */
		GTree *uids = MailboxState_getIds(S);
		GTree *info = MailboxState_getMsginfo(S);
		u64_t key = 0, *msn = NULL;
		g_tree_foreach(info, (GTraverseFunc)mailbox_first_unseen, &key);
		if ( (key > 0) && (msn = g_tree_lookup(uids, &key)))
			dbmail_imap_session_buff_printf(self, "* OK [UNSEEN %llu] first unseen message\r\n", *msn);
	}

	if (self->command_type == IMAP_COMM_SELECT) 
		okarg = "READ-WRITE";
	else
		okarg = "READ-ONLY";

	dbmail_imap_session_buff_printf(self, "%s OK [%s] %s completed\r\n", self->tag, okarg, self->command);

	SESSION_RETURN;
}

int _ic_select(ImapSession *self) 
{
	if (!check_state_and_args(self, 1, 1, CLIENTSTATE_AUTHENTICATED)) return 1;
	dm_thread_data_push((gpointer)self, _ic_select_enter, _ic_cb_leave, NULL);
	return 0;
}


int _ic_examine(ImapSession *self)
{
	return _ic_select(self);
}

/*
 * _ic_create()
 *
 * create a mailbox
 */

void _ic_create_enter(dm_thread_data *D)
{
	/* Create the mailbox and its parents. */
	int result;
	u64_t mboxid;
	const char *message;
	SESSION_GET;

	result = db_mailbox_create_with_parents(self->args[self->args_idx], BOX_COMMANDLINE, self->userid, &mboxid, &message);

	if (result > 0)
		dbmail_imap_session_buff_printf(self, "%s NO %s\r\n", self->tag, message);
	else if (result < 0)
		dbmail_imap_session_buff_printf(self, "* BYE internal dbase error\r\n");
	else
		SESSION_OK;

	SESSION_RETURN;
}


int _ic_create(ImapSession *self)
{
	if (!check_state_and_args(self, 1, 1, CLIENTSTATE_AUTHENTICATED)) return 1;
	dm_thread_data_push((gpointer)self, _ic_create_enter, _ic_cb_leave, NULL);
	return DM_SUCCESS;
}


/* _ic_delete()
 *
 * deletes a specified mailbox
 */
static int imap_session_mailbox_check_acl(ImapSession * self, u64_t idnr,  ACLRight_t acl)
{
	int result;
	MailboxState_T S = dbmail_imap_session_mbxinfo_lookup(self, idnr, FALSE);
	if ((result = mailbox_check_acl(self, S, acl)) == 1)
		dbmail_imap_session_set_state(self,CLIENTSTATE_AUTHENTICATED);
	return result;
}

void _ic_delete_enter(dm_thread_data *D)
{
	int result;
	u64_t mailbox_idnr;
	GList *children = NULL;
	SESSION_GET;
	char *mailbox = self->args[0];
	unsigned nchildren = 0;
	
	/* check if there is an attempt to delete inbox */
	if (MATCH(self->args[0], "INBOX")) {
		dbmail_imap_session_buff_printf(self, "%s NO cannot delete special mailbox INBOX\r\n", self->tag);
		D->status=1;
		SESSION_RETURN;
	}

	if (! (db_findmailbox(mailbox, self->userid, &mailbox_idnr)) ) {
		dbmail_imap_session_buff_printf(self, "%s NO mailbox doesn't exists\r\n", self->tag);
		D->status=1;
		SESSION_RETURN;
	}

	/* Check if the user has ACL delete rights to this mailbox */
	if ((result = imap_session_mailbox_check_acl(self, mailbox_idnr, ACL_RIGHT_DELETE))) {
		D->status=result;
		SESSION_RETURN;
	}
	
	/* check for children of this mailbox */
	if ((result = db_listmailboxchildren(mailbox_idnr, self->userid, &children)) == DM_EQUERY) {
		TRACE(TRACE_ERR, "[%p] cannot retrieve list of mailbox children", self);
		dbmail_imap_session_buff_printf(self, "* BYE dbase/memory error\r\n");
		D->status= -1;
		SESSION_RETURN;
	}

	children = g_list_first(children);
	nchildren = g_list_length(children);
	g_list_destroy(children);

	if (nchildren > 0) {
		TRACE(TRACE_DEBUG, "mailbox has children [%d]", nchildren);
		/* mailbox has inferior names; error if \noselect specified */


		result = db_isselectable(mailbox_idnr);
		if (result == FALSE) {
			dbmail_imap_session_buff_printf(self, "%s NO mailbox is non-selectable\r\n", self->tag);
			SESSION_RETURN;
		}
		if (result == DM_EQUERY) {
			dbmail_imap_session_buff_printf(self, "* BYE internal dbase error\r\n");
			D->status= -1;	/* fatal */
			SESSION_RETURN;
		}

		/* mailbox has inferior names; remove all msgs and set noselect flag */
		{
			C c; volatile int t = DM_SUCCESS;
			u64_t mailbox_size;
			MailboxState_T S = dbmail_imap_session_mbxinfo_lookup(self, mailbox_idnr, FALSE);

			if (! mailbox_is_writable(mailbox_idnr)) {
				D->status=DM_EQUERY;
				SESSION_RETURN;
			}

			if (db_get_mailbox_size(mailbox_idnr, 0, &mailbox_size) == DM_EQUERY) {
				D->status=DM_EQUERY;
				SESSION_RETURN;
			}

			/* update messages in this mailbox: mark as deleted (status MESSAGE_STATUS_PURGE) */
			c = db_con_get();
			TRY
				db_begin_transaction(c);
				db_exec(c, "UPDATE %smessages SET status=%d WHERE mailbox_idnr = %llu", DBPFX, MESSAGE_STATUS_PURGE, mailbox_idnr);
				db_exec(c, "UPDATE %smailboxes SET no_select = 1 WHERE mailbox_idnr = %llu", DBPFX, mailbox_idnr);
				db_commit_transaction(c);
			CATCH(SQLException)
				LOG_SQLERROR;
				t = DM_EQUERY;
			FINALLY
				db_con_close(c);
			END_TRY;

			if (t == DM_EQUERY) {
				D->status=t;
				SESSION_RETURN;
			}

			MailboxState_setNoSelect(S, TRUE);
			db_mailbox_seq_update(mailbox_idnr);
			if (! dm_quota_user_dec(self->userid, mailbox_size)) {
				D->status=DM_EQUERY;
				SESSION_RETURN;
			}
		}

		/* check if this was the currently selected mailbox */
		if (self->mailbox && self->mailbox->mbstate && (mailbox_idnr == MailboxState_getId(self->mailbox->mbstate))) 
			dbmail_imap_session_set_state(self,CLIENTSTATE_AUTHENTICATED);

		/* ok done */
		SESSION_OK;
		SESSION_RETURN;
	}

	/* ok remove mailbox */
	if (db_delete_mailbox(mailbox_idnr, 0, 1)) {
		dbmail_imap_session_buff_printf(self,"%s NO DELETE failed\r\n", self->tag);
		D->status=DM_EGENERAL;
		SESSION_RETURN;
	}

	/* check if this was the currently selected mailbox */
	if (self->mailbox && self->mailbox->mbstate && (mailbox_idnr == MailboxState_getId(self->mailbox->mbstate))) 
		dbmail_imap_session_set_state(self, CLIENTSTATE_AUTHENTICATED);

	SESSION_OK;
	SESSION_RETURN;
}

int _ic_delete(ImapSession *self) 
{
	if (!check_state_and_args(self, 1, 1, CLIENTSTATE_AUTHENTICATED)) return 1;
	dm_thread_data_push((gpointer)self, _ic_delete_enter, _ic_cb_leave, NULL);
	return 0;
}
/* _ic_rename()
 *
 * renames a specified mailbox
 */
static int mailbox_rename(MailboxState_T M, const char *newname)
{
	if ( (db_setmailboxname(MailboxState_getId(M), newname)) == DM_EQUERY) return DM_EQUERY;
	MailboxState_setName(M, newname);
	return DM_SUCCESS;
}
void _ic_rename_enter(dm_thread_data *D)
{
	SESSION_GET;
	GList *children = NULL;
	u64_t mboxid, newmboxid;
	u64_t parentmboxid = 0;
	size_t oldnamelen;
	int i, result;
	char newname[IMAP_MAX_MAILBOX_NAMELEN];
	MailboxState_T M;


	if (! (db_findmailbox(self->args[0], self->userid, &mboxid))) {
		dbmail_imap_session_buff_printf(self, "%s NO mailbox does not exist\r\n", self->tag);
		D->status = 1;
		SESSION_RETURN;
	}

	/* check if new name is valid */
        if (!checkmailboxname(self->args[1])) {
	        dbmail_imap_session_buff_printf(self, "%s NO new mailbox name contains invalid characters\r\n", self->tag);
		D->status = 1;
		SESSION_RETURN;
        }

	if ((db_findmailbox(self->args[1], self->userid, &newmboxid))) {
		dbmail_imap_session_buff_printf(self, "%s NO new mailbox already exists\r\n", self->tag);
		D->status = 1;
		SESSION_RETURN;
	}

	oldnamelen = strlen(self->args[0]);

	/* check if new name would invade structure as in
	 * test (exists)
	 * rename test test/testing
	 * would create test/testing but delete test
	 */
	if (strncasecmp(self->args[0], self->args[1], (int) oldnamelen) == 0 &&
	    strlen(self->args[1]) > oldnamelen && self->args[1][oldnamelen] == '/') {
		dbmail_imap_session_buff_printf(self, "%s NO new mailbox would invade mailbox structure\r\n", self->tag);
		D->status = 1;
		SESSION_RETURN;
	}

	/* check if structure of new name is valid */
	/* i.e. only last part (after last '/' can be nonexistent) */
	for (i = strlen(self->args[1]) - 1; i >= 0 && self->args[1][i] != '/'; i--);
	if (i >= 0) {
		self->args[1][i] = '\0';	/* note: original char was '/' */

		if (! db_findmailbox(self->args[1], self->userid, &parentmboxid)) {
			/* parent mailbox does not exist */
			dbmail_imap_session_buff_printf(self, "%s NO new mailbox would invade mailbox structure\r\n", self->tag);
			D->status = 1;
			SESSION_RETURN;
		}

		/* ok, reset arg */
		self->args[1][i] = '/';
	}

	/* Check if the user has ACL delete rights to old name, 
	 * and create rights to the parent of the new name, or
	 * if the user just owns both mailboxes. */
	if ((result = imap_session_mailbox_check_acl(self, mboxid, ACL_RIGHT_DELETE))) {
		D->status = result;
		SESSION_RETURN;
	}

	if (!parentmboxid) {
		TRACE(TRACE_DEBUG, "[%p] Destination is a top-level mailbox; not checking right to CREATE.", self);
	} else {
		TRACE(TRACE_DEBUG, "[%p] Checking right to CREATE under [%llu]", self, parentmboxid);
		if ((result = imap_session_mailbox_check_acl(self, parentmboxid, ACL_RIGHT_CREATE))) {
			D->status = result;
			SESSION_RETURN;
		}

		TRACE(TRACE_DEBUG, "[%p] We have the right to CREATE under [%llu]", self, parentmboxid);
	}

	/* check if it is INBOX to be renamed */
	if (MATCH(self->args[0], "INBOX")) {
		/* ok, renaming inbox */
		/* this means creating a new mailbox and moving all the INBOX msgs to the new mailbox */
		/* inferior names of INBOX are left unchanged */
		result = db_createmailbox(self->args[1], self->userid, &newmboxid);
		if (result == -1) {
			dbmail_imap_session_buff_printf(self, "* BYE internal dbase error\r\n");
			D->status = DM_EQUERY;
			SESSION_RETURN;
		}

		result = db_movemsg(newmboxid, mboxid);
		if (result == -1) {
			dbmail_imap_session_buff_printf(self, "* BYE internal dbase error\r\n");
			D->status = result;
			SESSION_RETURN;
		}

		SESSION_OK;
		SESSION_RETURN;
	}

	/* check for inferior names */
	result = db_listmailboxchildren(mboxid, self->userid, &children);
	if (result == -1) {
		dbmail_imap_session_buff_printf(self, "* BYE internal dbase error\r\n");
		D->status = result;
		SESSION_RETURN;
	}

	/* replace name for each child */
	children = g_list_first(children);
	while (children) {
		u64_t childid = *(u64_t *)children->data;
		const char *tname;
		M = dbmail_imap_session_mbxinfo_lookup(self, childid, FALSE);
		tname = MailboxState_getName(M);

		g_snprintf(newname, IMAP_MAX_MAILBOX_NAMELEN, "%s%s", self->args[1], &tname[oldnamelen]);
		if ((mailbox_rename(M, newname)) != DM_SUCCESS) {
			dbmail_imap_session_buff_printf(self, "* BYE error renaming mailbox\r\n");
			g_list_destroy(children);
			D->status = DM_EGENERAL;
			SESSION_RETURN;
		}
		if (! g_list_next(children)) break;
		children = g_list_next(children);
	}

	if (children) g_list_destroy(children);

	/* now replace name */
	M = dbmail_imap_session_mbxinfo_lookup(self, mboxid, FALSE);
	if ((mailbox_rename(M, self->args[1])) != DM_SUCCESS) {
		dbmail_imap_session_buff_printf(self, "* BYE error renaming mailbox\r\n");
		D->status = DM_EGENERAL;
		SESSION_RETURN;
	}

	SESSION_OK;
	SESSION_RETURN;
}

int _ic_rename(ImapSession *self)
{
	if (!check_state_and_args(self, 2, 2, CLIENTSTATE_AUTHENTICATED)) return 1;
	dm_thread_data_push((gpointer)self, _ic_rename_enter, _ic_cb_leave, NULL);
	return 0;
}



/*
 * _ic_subscribe()
 *
 * subscribe to a specified mailbox
 */
void _ic_subscribe_enter(dm_thread_data *D)
{
	SESSION_GET;
	u64_t mboxid;
	int result = 0;
	
	if (! (db_findmailbox(self->args[0], self->userid, &mboxid))) {
		dbmail_imap_session_buff_printf(self, "%s OK %s on mailbox that does not exist\r\n", self->tag, self->command);
		SESSION_RETURN;
	}

	/* check for the lookup-right. RFC is unclear about which right to
	   use, so I guessed it should be lookup */

	if (imap_session_mailbox_check_acl(self, mboxid, ACL_RIGHT_LOOKUP)) {
		D->status = 1;
		SESSION_RETURN;
	}

	if (self->command_type == IMAP_COMM_SUBSCRIBE) {
		result = db_subscribe(mboxid, self->userid);
	} else {
		result = db_unsubscribe(mboxid, self->userid);
	}

	if (result == DM_EQUERY) {
		dbmail_imap_session_buff_printf(self, "* BYE internal dbase error\r\n");
		D->status = DM_EQUERY;
		SESSION_RETURN;
	}

	SESSION_OK;
	SESSION_RETURN;

}
int _ic_subscribe(ImapSession *self)
{
	if (!check_state_and_args(self, 1, 1, CLIENTSTATE_AUTHENTICATED)) return 1;
	dm_thread_data_push((gpointer)self, _ic_subscribe_enter, _ic_cb_leave, NULL);
	return 0;
}

int _ic_unsubscribe(ImapSession *self)
{
	return _ic_subscribe(self);
}

/*
 * _ic_list()
 *
 * executes a list command
 */
void _ic_list_enter(dm_thread_data *D)
{
	SESSION_GET;
	int list_is_lsub = 0;
	GList *plist = NULL, *children = NULL;
	GTree *shown = NULL;
	char *pstring = NULL;
	MailboxState_T M = NULL;
	size_t slen;
	unsigned i;
	char *pattern;
	char *mailbox = g_new0(char, IMAP_MAX_MAILBOX_NAMELEN);

	/* check if self->args are both empty strings, i.e. A001 LIST "" "" 
	   this has special meaning; show root & delimiter */
	if (strlen(self->args[0]) == 0 && strlen(self->args[1]) == 0) {
		dbmail_imap_session_buff_printf(self, "* %s (\\NoSelect) \"/\" \"\"\r\n", self->command);
		SESSION_OK;
		SESSION_RETURN;
	}

	/* check the reference name, should contain only accepted mailboxname chars */
	for (i = 0, slen = strlen(AcceptedMailboxnameChars); self->args[0][i]; i++) {
		if (index(AcceptedMailboxnameChars, self->args[0][i]) == NULL) {
			dbmail_imap_session_buff_printf(self, "%s BAD reference name contains invalid characters\r\n", self->tag);
			D->status = 1;
			SESSION_RETURN;
		}
	}
	pattern = g_strdup_printf("%s%s", self->args[0], self->args[1]);

	TRACE(TRACE_INFO, "[%p] search with pattern: [%s]", self, pattern);

	if (self->command_type == IMAP_COMM_LSUB) list_is_lsub = 1;

	D->status = db_findmailbox_by_regex(self->userid, pattern, &children, list_is_lsub);
	if (D->status == -1) {
		dbmail_imap_session_buff_printf(self, "* BYE internal dbase error\r\n");
		SESSION_RETURN;
	} else if (D->status == 1) {
		dbmail_imap_session_buff_printf(self, "%s BAD invalid pattern specified\r\n", self->tag);
		SESSION_RETURN;
	}

	shown = g_tree_new_full((GCompareDataFunc)dm_strcmpdata,NULL,(GDestroyNotify)g_free,NULL);

	while ((! D->status) && children) {
		gboolean show = FALSE;

		memset(mailbox, 0, IMAP_MAX_MAILBOX_NAMELEN);

		u64_t mailbox_id = *(u64_t *)children->data;
		if ( (D->status = db_getmailboxname(mailbox_id, self->userid, mailbox)) != DM_SUCCESS) {
			break;
		}

		// avoid fully loading mailbox here
		M = MailboxState_new(0);
		MailboxState_setId(M, mailbox_id);
		MailboxState_preload(M);
		MailboxState_setName(M, mailbox);

		/* Enforce match of mailbox to pattern. */
		TRACE(TRACE_DEBUG,"test if [%s] matches [%s]", mailbox, pattern);
		if (! listex_match(pattern, mailbox, MAILBOX_SEPARATOR, 0)) {
			if (g_str_has_suffix(pattern,"%")) {
				/*
				   If the "%" wildcard is the last character of a mailbox name argument, matching levels
				   of hierarchy are also returned.  If these levels of hierarchy are not also selectable 
				   mailboxes, they are returned with the \Noselect mailbox name attribute
				   */

				TRACE(TRACE_DEBUG, "mailbox [%s] doesn't match pattern [%s]", mailbox, pattern);
				char *m = NULL, **p = g_strsplit(mailbox,MAILBOX_SEPARATOR,0);
				int l = g_strv_length(p);
				while (l > 1) {
					if (p[l]) {
						g_free(p[l]);
						p[l] = NULL;
					}
					m = g_strjoinv(MAILBOX_SEPARATOR,p);
					if (listex_match(pattern, m, MAILBOX_SEPARATOR, 0)) {
						TRACE(TRACE_DEBUG,"[%s] matches [%s]", m, pattern);

						MailboxState_setName(M, m);
						MailboxState_setNoSelect(M, TRUE);
						MailboxState_setNoChildren(M, FALSE);
						show = TRUE;
						break;
					}
					g_free(m);
					l--;
				}
				g_strfreev(p);
			}
		} else {
			show = TRUE;
		}

		if (show && MailboxState_getName(M) && (! g_tree_lookup(shown, MailboxState_getName(M)))) {
			char *s = g_strdup(MailboxState_getName(M));
			TRACE(TRACE_DEBUG,"[%s]", s);
			g_tree_insert(shown, s, s);

			plist = NULL;
			if (MailboxState_noSelect(M))
				plist = g_list_append(plist, g_strdup("\\noselect"));
			if (MailboxState_noInferiors(M))
				plist = g_list_append(plist, g_strdup("\\noinferiors"));
			if (MailboxState_noChildren(M))
				plist = g_list_append(plist, g_strdup("\\hasnochildren"));
			else
				plist = g_list_append(plist, g_strdup("\\haschildren"));

			/* show */
			pstring = dbmail_imap_plist_as_string(plist);
			dbmail_imap_session_buff_printf(self, "* %s %s \"%s\" \"%s\"\r\n", self->command, 
					pstring, MAILBOX_SEPARATOR, MailboxState_getName(M));

			g_list_destroy(plist);
			g_free(pstring);
		}

		MailboxState_free(&M);

		if (! g_list_next(children)) break;
		children = g_list_next(children);
	}

	g_free(mailbox);

	if (shown) g_tree_destroy(shown);
	if (children) g_list_destroy(children);
	g_free(pattern);

	if (! D->status) dbmail_imap_session_buff_printf(self, "%s OK %s completed\r\n", self->tag, self->command);

	SESSION_RETURN;
}

int _ic_list(ImapSession *self)
{

	if (!check_state_and_args(self, 2, 2, CLIENTSTATE_AUTHENTICATED)) return 1;
	dm_thread_data_push((gpointer)self, _ic_list_enter, _ic_cb_leave, NULL);
	return 0;
}

/*
 * _ic_lsub()
 *
 * list subscribed mailboxes
 */
int _ic_lsub(ImapSession *self)
{
	return _ic_list(self);
}


/*
 * _ic_status()
 *
 * inquire the status of a mailbox
 */
static void _ic_status_enter(dm_thread_data *D)
{
	SESSION_GET;
	MailboxState_T M;
	u64_t id;
	int i, endfound, result;
	GList *plst = NULL;
	gchar *pstring, *astring;
	
	if (self->args[1][0] != '(') {
		dbmail_imap_session_buff_printf(self, "%s BAD argument list should be parenthesed\r\n", self->tag);
		D->status = 1;
		SESSION_RETURN;
	}

	/* check final arg: should be ')' and no new '(' in between */
	for (i = 2, endfound = 0; self->args[i]; i++) {
		if (self->args[i][0] == ')') {
			endfound = i;
			break;
		} else if (self->args[i][0] == '(') {
			dbmail_imap_session_buff_printf(self, "%s BAD too many parentheses specified\r\n", self->tag);
			D->status = 1;
			SESSION_RETURN;
		}
	}

	if (endfound == 2) {
		dbmail_imap_session_buff_printf(self, "%s BAD argument list empty\r\n", self->tag);
		D->status = 1;
		SESSION_RETURN;
	}
	if (self->args[endfound + 1]) {
		dbmail_imap_session_buff_printf(self, "%s BAD argument list too long\r\n", self->tag);
		D->status = 1;
		SESSION_RETURN;
	}

	/* check if mailbox exists */
	if (! db_findmailbox(self->args[0], self->userid, &id)) {
		/* create missing INBOX for this authenticated user */
		if ((! id ) && (MATCH(self->args[0], "INBOX"))) {
			TRACE(TRACE_INFO, "[%p] Auto-creating INBOX for user id [%llu]", self, self->userid);
			db_createmailbox("INBOX", self->userid, &id);
		}
		if (! id) {
			dbmail_imap_session_buff_printf(self, "%s NO specified mailbox does not exist\r\n", self->tag);
			D->status = 1;
			SESSION_RETURN;
		}
	}

	if (! (M = dbmail_imap_session_mbxinfo_lookup(self, id, FALSE))) {
		dbmail_imap_session_buff_printf(self, "%s NO specified mailbox does not exist\r\n", self->tag);
		D->status = 1;
		SESSION_RETURN;
	}

	if ((result = mailbox_check_acl(self, M, ACL_RIGHT_READ))) {
		D->status = result;
		SESSION_RETURN;
	}

	for (i = 2; self->args[i]; i++) {
		if (MATCH(self->args[i], "messages"))
			plst = g_list_append_printf(plst,"MESSAGES %u", MailboxState_getExists(M));
		else if (MATCH(self->args[i], "recent"))
			plst = g_list_append_printf(plst,"RECENT %u", MailboxState_getRecent(M));
		else if (MATCH(self->args[i], "unseen"))
			plst = g_list_append_printf(plst,"UNSEEN %u", MailboxState_getUnseen(M));
		else if (MATCH(self->args[i], "uidnext"))
			plst = g_list_append_printf(plst,"UIDNEXT %llu", MailboxState_getUidnext(M));
		else if (MATCH(self->args[i], "uidvalidity"))
			plst = g_list_append_printf(plst,"UIDVALIDITY %llu", MailboxState_getId(M));
		else if (MATCH(self->args[i], ")"))
			break;
		else {
			dbmail_imap_session_buff_printf(self, "\r\n%s BAD option '%s' specified\r\n",
				self->tag, self->args[i]);
			D->status = 1;
			SESSION_RETURN;
		}
	}
	astring = dbmail_imap_astring_as_string(self->args[0]);
	pstring = dbmail_imap_plist_as_string(plst); 
	g_list_destroy(plst);

	dbmail_imap_session_buff_printf(self, "* STATUS %s %s\r\n", astring, pstring);	
	g_free(astring); g_free(pstring);

	SESSION_OK;
	SESSION_RETURN;
}

int _ic_status(ImapSession *self)
{
	if (!check_state_and_args(self, 3, 0, CLIENTSTATE_AUTHENTICATED)) return 1;
	dm_thread_data_push((gpointer)self, _ic_status_enter, _ic_cb_leave, NULL);
	return 0;
}

/* _ic_idle
 *
 */

#define IDLE_TIMEOUT 30
int _ic_idle(ImapSession *self)
{
	if (!check_state_and_args(self, 0, 0, CLIENTSTATE_AUTHENTICATED)) return 1;

	int idle_timeout = IDLE_TIMEOUT;
	field_t val;

	GETCONFIGVALUE("idle_timeout", "IMAP", val);
	if ( strlen(val) && (idle_timeout = atoi(val)) <= 0 ) {
		TRACE(TRACE_ERR, "[%p] illegal value for idle_timeout [%s]", self, val);
		idle_timeout = IDLE_TIMEOUT;	
	}
	
	TRACE(TRACE_DEBUG,"[%p] start IDLE [%s]", self, self->tag);
	self->ci->timeout->tv_sec = idle_timeout;
	self->command_state = IDLE;
	dbmail_imap_session_buff_printf(self, "+ idling\r\n");
	dbmail_imap_session_mailbox_status(self,TRUE);
	dbmail_imap_session_buff_flush(self);

	return 0;
}

/* _ic_append()
 *
 * append a message to a mailbox
 */

void _ic_append_enter(dm_thread_data *D)
{
	u64_t mboxid, message_id = 0;
	int i, j, result;
	timestring_t sqldate;
	int flaglist[IMAP_NFLAGS], flagcount = 0;
	GList *keywords = NULL;
	MailboxState_T M;
	SESSION_GET;
	char *message;

	memset(flaglist,0,sizeof(flaglist));

	/* find the mailbox to place the message */
	if (! db_findmailbox(self->args[0], self->userid, &mboxid)) {
		dbmail_imap_session_buff_printf(self, "%s NO [TRYCREATE]\r\n", self->tag);
		D->status = 1;
		SESSION_RETURN;
	}

	M = dbmail_imap_session_mbxinfo_lookup(self, mboxid, FALSE);

	/* check if user has right to append to  mailbox */
	if ((result = imap_session_mailbox_check_acl(self, mboxid, ACL_RIGHT_INSERT))) {
		D->status = result;
		SESSION_RETURN;
	}

	i = 1;

	/* check if a flag list has been specified */
	if (self->args[i][0] == '(') {
		/* ok fetch the flags specified */
		TRACE(TRACE_DEBUG, "[%p] flag list found:", self);

		i++;
		while (self->args[i] && self->args[i][0] != ')') {
			TRACE(TRACE_DEBUG, "[%p] [%s]", self, self->args[i]);
			for (j = 0; j < IMAP_NFLAGS; j++) {
				if (MATCH(self->args[i], imap_flag_desc_escaped[j])) {
					flaglist[j] = 1;
					flagcount++;
					break;
				}
			}
			if (j == IMAP_NFLAGS) {
				TRACE(TRACE_DEBUG,"[%p] found keyword [%s]", self, self->args[i]);
				keywords = g_list_append(keywords,g_strdup(self->args[i]));
				flagcount++;
			}

			i++;
		}

		i++;
		TRACE(TRACE_DEBUG, "[%p] )", self);
	}

	if (!self->args[i]) {
		TRACE(TRACE_INFO, "[%p] unexpected end of arguments", self);
		dbmail_imap_session_buff_printf(self, "%s BAD invalid arguments specified to APPEND\r\n", self->tag);
		D->status = 1;
		SESSION_RETURN;
	}

	/** check ACL's for STORE */
	if (flaglist[IMAP_FLAG_SEEN] == 1) {
		if ((result = mailbox_check_acl(self, M, ACL_RIGHT_SEEN))) {
			D->status = result;
			SESSION_RETURN;
		}
	}
	if (flaglist[IMAP_FLAG_DELETED] == 1) {
		if ((result = mailbox_check_acl(self, M, ACL_RIGHT_DELETED))) {
			D->status = result;
			SESSION_RETURN;
		}
	}
	if (flaglist[IMAP_FLAG_ANSWERED] == 1 ||
	    flaglist[IMAP_FLAG_FLAGGED] == 1 ||
	    flaglist[IMAP_FLAG_RECENT] == 1 ||
	    flaglist[IMAP_FLAG_DRAFT] == 1 ||
	    g_list_length(keywords) > 0) {
		if ((result = mailbox_check_acl(self, M, ACL_RIGHT_WRITE))) {
			D->status = result;
			SESSION_RETURN;
		}
	}


	/* there could be a literal date here, check if the next argument exists
	 * if so, assume this is the literal date.
	 */
	if (self->args[i + 1]) {
		struct tm tm;
		char *dt = self->args[i];

		memset(&tm, 0, sizeof(struct tm));

		dt = g_strstrip(dt);

		if (strptime(dt, "%d-%b-%Y %T", &tm) != NULL)
			strftime(sqldate, sizeof(sqldate), "%Y-%m-%d %H:%M:%S", &tm);
		else
			sqldate[0] = '\0';
		/* internal date specified */

		i++;
		TRACE(TRACE_DEBUG, "[%p] internal date [%s] found, next arg [%s]", self, sqldate, self->args[i]);
	} else {
		sqldate[0] = '\0';
	}

	message = self->args[i];

	D->status = db_append_msg(message, mboxid, self->userid, sqldate, &message_id);

	switch (D->status) {
	case -1:
		TRACE(TRACE_ERR, "[%p] error appending msg", self);
		dbmail_imap_session_buff_printf(self, "* BYE internal dbase error storing message\r\n");
		break;

	case -2:
		TRACE(TRACE_INFO, "[%p] quotum would exceed", self);
		dbmail_imap_session_buff_printf(self, "%s NO not enough quotum left\r\n", self->tag);
		break;

	case TRUE:
		TRACE(TRACE_ERR, "[%p] faulty msg", self);
		dbmail_imap_session_buff_printf(self, "%s NO invalid message specified\r\n", self->tag);
		break;
	case FALSE:
		if (flagcount) {
			if (db_set_msgflag(message_id, flaglist, keywords, IMAPFA_ADD, NULL) < 0)
				TRACE(TRACE_ERR, "[%p] error setting flags for message [%llu]", self, message_id);
			db_mailbox_seq_update(mboxid);
		}
		break;
	}

	if (message_id && self->state == CLIENTSTATE_SELECTED && self->mailbox->id == mboxid) {
		dbmail_imap_session_mailbox_status(self, TRUE);
	} else {
		g_list_destroy(keywords);
	}

	SESSION_OK;
	SESSION_RETURN;
}

int _ic_append(ImapSession *self)
{
	if (!check_state_and_args(self, 2, 0, CLIENTSTATE_AUTHENTICATED)) return 1;
	dm_thread_data_push((gpointer)self, _ic_append_enter, _ic_cb_leave, NULL);
	return 0;
}

/* 
 * SELECTED-STATE COMMANDS 
 * sort, check, close, expunge, search, fetch, store, copy, uid
 */

/* _ic_check()
 * 
 * request a checkpoint for the selected mailbox
 * (equivalent to NOOP)
 */
static void _ic_check_enter(dm_thread_data *D)
{
	SESSION_GET;
	dbmail_imap_session_mailbox_status(self, TRUE);
	SESSION_OK;
	SESSION_RETURN;
}

int _ic_check(ImapSession *self)
{
	if (!check_state_and_args(self, 0, 0, CLIENTSTATE_SELECTED)) return 1;
	dm_thread_data_push((gpointer)self, _ic_check_enter, _ic_cb_leave, NULL);
	return 0;
}


/* _ic_close()
 *
 * expunge deleted messages from selected mailbox & return to AUTH state
 * do not show expunge-output
 */
static void _ic_close_enter(dm_thread_data *D)
{
	SESSION_GET;
	int result = acl_has_right(self->mailbox->mbstate, self->userid, ACL_RIGHT_EXPUNGE);
	if (result < 0) {
		dbmail_imap_session_buff_printf(self, "* BYE Internal database error\r\n");
		D->status=result;
		SESSION_RETURN;
	}
	/* only perform the expunge if the user has the right to do it */
	if (result == 1)
		if (MailboxState_getPermission(self->mailbox->mbstate) == IMAPPERM_READWRITE)
			dbmail_imap_session_mailbox_expunge(self);

	dbmail_imap_session_set_state(self, CLIENTSTATE_AUTHENTICATED);

	SESSION_OK;
	SESSION_RETURN;
}
	
int _ic_close(ImapSession *self)
{
	if (!check_state_and_args(self, 0, 0, CLIENTSTATE_SELECTED)) return 1;
	dm_thread_data_push((gpointer)self, _ic_close_enter, _ic_cb_leave, NULL);
	return 0;
}

/* _ic_unselect
 *
 * non-expunging close for select mailbox and return to AUTH state
 */
static void _ic_unselect_enter(dm_thread_data *D)
{
	SESSION_GET;
	imap_session_mailbox_close(self);

	SESSION_OK;
	SESSION_RETURN;
}

int _ic_unselect(ImapSession *self)
{
	if (!check_state_and_args(self, 0, 0, CLIENTSTATE_SELECTED)) return 1;
	dm_thread_data_push((gpointer)self, _ic_unselect_enter, _ic_cb_leave, NULL);
	return 0;
}

/* _ic_expunge()
 *
 * expunge deleted messages from selected mailbox
 * show expunge output per message
 */
	
static void _ic_expunge_enter(dm_thread_data *D)
{
	int result;
	SESSION_GET;

	if ((result = mailbox_check_acl(self, self->mailbox->mbstate, ACL_RIGHT_EXPUNGE))) {
		D->status = result;
		SESSION_RETURN;
	}
	
	if (dbmail_imap_session_mailbox_expunge(self) != DM_SUCCESS) {
		dbmail_imap_session_buff_printf(self, "* BYE expunge failed\r\n");
		D->status = DM_EQUERY;
		SESSION_RETURN;
	}

	SESSION_OK;
	SESSION_RETURN;
}

int _ic_expunge(ImapSession *self)
{
	if (!check_state_and_args(self, 0, 0, CLIENTSTATE_SELECTED)) return 1;

	if (MailboxState_getPermission(self->mailbox->mbstate) != IMAPPERM_READWRITE) {
		dbmail_imap_session_buff_printf(self, "%s NO you do not have write permission on this folder\r\n", self->tag);
		return 1;
	}

	dm_thread_data_push((gpointer)self, _ic_expunge_enter, _ic_cb_leave, NULL);
	return 0;
}


/*
 * _ic_search()
 *
 * search the selected mailbox for messages
 *
 */
static void sorted_search_enter(dm_thread_data *D)
{
	SESSION_GET;
	DbmailMailbox *mb;
	int result = 0;
	gchar *s = NULL;
	const gchar *cmd;
	gboolean sorted;

	search_order_t order = *(search_order_t *)D->data;

	if (order == SEARCH_SORTED) sorted = 1;
	
	if ((result = mailbox_check_acl(self, self->mailbox->mbstate, ACL_RIGHT_READ))) {
		D->status = result;
		SESSION_RETURN;
	}

	mb = self->mailbox;
	switch(order) {
		case SEARCH_SORTED:
			cmd = "SORT";
			break;
		case SEARCH_UNORDERED:
			cmd = "SEARCH";
			break;
		case SEARCH_THREAD_REFERENCES:
		case SEARCH_THREAD_ORDEREDSUBJECT:
			cmd = "THREAD";
			break;
		default:// shouldn't happen
			cmd = "NO";
			break;
	}

	if (MailboxState_getExists(mb->mbstate) > 0) {
		dbmail_mailbox_set_uid(mb,self->use_uid);

		if (dbmail_mailbox_build_imap_search(mb, self->args, &(self->args_idx), order) < 0) {
			dbmail_imap_session_buff_printf(self, "%s BAD invalid arguments to %s\r\n",
				self->tag, cmd);
			D->status = 1;
			SESSION_RETURN;
		}
		dbmail_mailbox_search(mb);
		/* ok, display results */
		switch(order) {
			case SEARCH_SORTED:
				dbmail_mailbox_sort(mb);
				s = dbmail_mailbox_sorted_as_string(mb);
			break;
			case SEARCH_UNORDERED:
				s = dbmail_mailbox_ids_as_string(mb);
			break;
			case SEARCH_THREAD_ORDEREDSUBJECT:
				s = dbmail_mailbox_orderedsubject(mb);
			break;
			case SEARCH_THREAD_REFERENCES:
				s = NULL; // TODO: unsupported
			break;
		}
	} else {
		TRACE(TRACE_DEBUG, "empty mailbox?");
	}

	if (s) {
		dbmail_imap_session_buff_printf(self, "* %s %s\r\n", cmd, s);
		g_free(s);
	} else {
		dbmail_imap_session_buff_printf(self, "* %s\r\n", cmd);
	}

	SESSION_OK;
	SESSION_RETURN;
}

static int sorted_search(ImapSession *self, search_order_t order)
{
	if (!check_state_and_args(self, 1, 0, CLIENTSTATE_SELECTED)) return 1;
	search_order_t *data = g_new0(search_order_t,1);
	*data = order;
	dm_thread_data_push((gpointer)self, sorted_search_enter, _ic_cb_leave, (gpointer)data);
	return 0;
}

int _ic_search(ImapSession *self)
{
	return sorted_search(self,SEARCH_UNORDERED);
}

int _ic_sort(ImapSession *self)
{
	return sorted_search(self,SEARCH_SORTED);
}

int _ic_thread(ImapSession *self)
{
	if (MATCH(self->args[0],"ORDEREDSUBJECT"))
		return sorted_search(self,SEARCH_THREAD_ORDEREDSUBJECT);
	if (MATCH(self->args[0],"REFERENCES"))
		dbmail_imap_session_buff_printf(self, "%s BAD THREAD=REFERENCES not supported\r\n",self->tag);
		//return sorted_search(self,SEARCH_THREAD_REFERENCES);

	return 1;
}

int _dm_imapsession_get_ids(ImapSession *self, const char *set)
{
	dbmail_mailbox_set_uid(self->mailbox,self->use_uid);

	if (self->ids) {
		g_tree_destroy(self->ids);
		self->ids = NULL;
	}

	self->ids = dbmail_mailbox_get_set(self->mailbox, set, self->use_uid);

	if ( (!self->ids) || (g_tree_nnodes(self->ids)==0) )
		return DM_EGENERAL;

	return DM_SUCCESS;
}



/*
 * _ic_fetch()
 *
 * fetch message(s) from the selected mailbox
 */
	
static void _ic_fetch_enter(dm_thread_data *D)
{
	SESSION_GET;
	int result, state, setidx;

	if (self->fi) {
		dbmail_imap_session_bodyfetch_free(self);
		g_free(self->fi);
		self->fi = NULL;
	}
	self->fi = g_new0(fetch_items_t,1);
	self->fi->getUID = self->use_uid;

	setidx = self->args_idx;
	TRACE(TRACE_DEBUG, "id-set: [%s]", self->args[self->args_idx]);
	self->args_idx++; //skip on past this for the fetch_parse_args coming next...

	state = 1;
	do {
		if ( (state = dbmail_imap_session_fetch_parse_args(self)) == -2) {
			dbmail_imap_session_buff_printf(self, "%s BAD invalid argument list to fetch\r\n", self->tag);
			D->status = 1;
			SESSION_RETURN;
		}
		TRACE(TRACE_DEBUG,"[%p] dbmail_imap_session_fetch_parse_args loop idx %llu state %d ", self, self->args_idx, state);
		self->args_idx++;
	} while (state > 0);

	result = DM_SUCCESS;

  	if (g_tree_nnodes(MailboxState_getIds(self->mailbox->mbstate)) > 0) {
 		if (_dm_imapsession_get_ids(self, self->args[setidx]) == DM_SUCCESS) {
  			self->ids_list = g_tree_keys(self->ids);
  			result = dbmail_imap_session_fetch_get_items(self);
  		}
	}

	dbmail_imap_session_fetch_free(self);
	dbmail_imap_session_args_free(self, FALSE);
	dbmail_imap_session_mailbox_status(self, FALSE);

	if (result) {
		D->status = result;
		SESSION_RETURN;
	}

	SESSION_OK;
	SESSION_RETURN;
}

int _ic_fetch(ImapSession *self)
{
	if (!check_state_and_args (self, 2, 0, CLIENTSTATE_SELECTED)) return 1;
	dm_thread_data_push((gpointer)self, _ic_fetch_enter, _ic_cb_leave, NULL);
	return 0;
}

/*
 * _ic_store()
 *
 * alter message-associated data in selected mailbox
 */

static gboolean _do_store(u64_t *id, gpointer UNUSED value, dm_thread_data *D)
{
	ImapSession *self = D->session;
	cmd_t cmd = self->cmd;

	u64_t *msn;
	MessageInfo *msginfo = NULL;
	char *s;
	int i;

	if (self->mailbox && MailboxState_getMsginfo(self->mailbox->mbstate))
		msginfo = g_tree_lookup(MailboxState_getMsginfo(self->mailbox->mbstate), id);

	if (! msginfo) {
		TRACE(TRACE_WARNING, "[%p] unable to lookup msginfo struct for [%llu]", self, *id);
		return TRUE;
	}

	msn = g_tree_lookup(MailboxState_getIds(self->mailbox->mbstate), id);

	if (MailboxState_getPermission(self->mailbox->mbstate) == IMAPPERM_READWRITE) {
		if (db_set_msgflag(*id, cmd->flaglist, cmd->keywords, cmd->action, msginfo) < 0) {
			dbmail_imap_session_buff_printf(self, "\r\n* BYE internal dbase error\r\n");
			D->status = TRUE;
			return TRUE;
		}
	}

	// Set the system flags
	for (i = 0; i < IMAP_NFLAGS; i++) {
		
		if (i == IMAP_FLAG_RECENT) // Skip recent_flag because it is already part of the query.
			continue;

		switch (cmd->action) {
			case IMAPFA_ADD:
				if (cmd->flaglist[i])
					msginfo->flags[i] = 1;
			break;
			case IMAPFA_REMOVE:
				if (cmd->flaglist[i]) 
					msginfo->flags[i] = 0;
			break;
			case IMAPFA_REPLACE:
				if (cmd->flaglist[i]) 
					msginfo->flags[i] = 1;
				else
					msginfo->flags[i] = 0;
			break;
		}
	}

	// Set the user keywords as labels
	g_list_merge(&(msginfo->keywords), cmd->keywords, cmd->action, (GCompareFunc)g_ascii_strcasecmp);

	// reporting callback
	if (! cmd->silent) {
		char *uid = NULL;
		if (self->use_uid)
			uid = g_strdup_printf("UID %llu ", *id);
		s = imap_flags_as_string(self->mailbox->mbstate, msginfo);
		dbmail_imap_session_buff_printf(self,"* %llu FETCH (%sFLAGS %s)\r\n", *msn, uid?uid:"", s);
		if (uid) g_free(uid);
		g_free(s);
	}

	return FALSE;
}

static void _ic_store_enter(dm_thread_data *D)
{
	SESSION_GET;
	int result, i, j, k;
	cmd_t cmd;
	gboolean update = FALSE;

	k = self->args_idx;
	/* multiple flags should be parenthesed */
	if (self->args[k+3] && strcmp(self->args[k+2], "(") != 0) {
		dbmail_imap_session_buff_printf(self, "%s BAD invalid argument(s) to STORE\r\n", self->tag);
		D->status = 1;
		SESSION_RETURN;
	}

	cmd = g_malloc0(sizeof(*cmd));
	cmd->silent = FALSE;

	/* retrieve action type */
	if (MATCH(self->args[k+1], "flags"))
		cmd->action = IMAPFA_REPLACE;
	else if (MATCH(self->args[k+1], "flags.silent")) {
		cmd->action = IMAPFA_REPLACE;
		cmd->silent = TRUE;
	} else if (MATCH(self->args[k+1], "+flags"))
		cmd->action = IMAPFA_ADD;
	else if (MATCH(self->args[k+1], "+flags.silent")) {
		cmd->action = IMAPFA_ADD;
		cmd->silent = TRUE;
	} else if (MATCH(self->args[k+1], "-flags"))
		cmd->action = IMAPFA_REMOVE;
	else if (MATCH(self->args[k+1], "-flags.silent")) {
		cmd->action = IMAPFA_REMOVE;
		cmd->silent = TRUE;
	}

	if (cmd->action == IMAPFA_NONE) {
		dbmail_imap_session_buff_printf(self, "%s BAD invalid STORE action specified\r\n", self->tag);
		D->status = 1;
		g_free(cmd);
		SESSION_RETURN;
	}

	/* now fetch flag list */
	i = (strcmp(self->args[k+2], "(") == 0) ? 3 : 2;

	for (; self->args[k+i] && strcmp(self->args[k+i], ")") != 0; i++) {
		for (j = 0; j < IMAP_NFLAGS; j++) {
			/* storing the recent flag explicitely is not allowed */
			if (MATCH(self->args[k+i],"\\Recent")) {
				dbmail_imap_session_buff_printf(self, "%s BAD invalid flag list to STORE command\r\n", self->tag);
				D->status = 1;
				g_free(cmd);
				SESSION_RETURN;
			}
				
			if (MATCH(self->args[k+i], imap_flag_desc_escaped[j])) {
				cmd->flaglist[j] = 1;
				break;
			}
		}

		if (j == IMAP_NFLAGS) {
			char *kw = self->args[k+i];
			cmd->keywords = g_list_append(cmd->keywords,g_strdup(kw));
			if (! MailboxState_hasKeyword(self->mailbox->mbstate, kw)) {
				MailboxState_addKeyword(self->mailbox->mbstate, kw);
				update = TRUE;
			}
		}
	}

	/** check ACL's for STORE */
	if (cmd->flaglist[IMAP_FLAG_SEEN] == 1) {
		if ((result = mailbox_check_acl(self, self->mailbox->mbstate, ACL_RIGHT_SEEN))) {
			dbmail_imap_session_buff_printf(self, "%s NO access denied\r\n", self->tag);
			D->status = result;
			g_list_destroy(cmd->keywords);
			g_free(cmd);
			SESSION_RETURN;
		}
	}
	if (cmd->flaglist[IMAP_FLAG_DELETED] == 1) {
		if ((result = mailbox_check_acl(self, self->mailbox->mbstate, ACL_RIGHT_DELETED))) {
			dbmail_imap_session_buff_printf(self, "%s NO access denied\r\n", self->tag);
			D->status = result;
			g_list_destroy(cmd->keywords);
			g_free(cmd);
			SESSION_RETURN;
		}
	}
	if (cmd->flaglist[IMAP_FLAG_ANSWERED] == 1 ||
	    cmd->flaglist[IMAP_FLAG_FLAGGED] == 1 ||
	    cmd->flaglist[IMAP_FLAG_DRAFT] == 1 ||
	    g_list_length(cmd->keywords) > 0 ) {
		if ((result = mailbox_check_acl(self, self->mailbox->mbstate, ACL_RIGHT_WRITE))) {
			dbmail_imap_session_buff_printf(self, "%s NO access denied\r\n", self->tag);
			D->status = result;
			g_list_destroy(cmd->keywords);
			g_free(cmd);
			SESSION_RETURN;
		}
	}
	/* end of ACL checking. If we get here without returning, the user has
	   the right to store the flags */

	self->cmd = cmd;
	
	result = DM_SUCCESS;

	if ( update ) {
		char *flags = MailboxState_flags(self->mailbox->mbstate);
		dbmail_imap_session_buff_printf(self, "* FLAGS (%s)\r\n", flags);
		dbmail_imap_session_buff_printf(self, "* OK [PERMANENTFLAGS (%s \\*)] Flags allowed.\r\n", flags);
		g_free(flags);
	}

	if (g_tree_nnodes(MailboxState_getIds(self->mailbox->mbstate)) > 0) {
 		if ((result = _dm_imapsession_get_ids(self, self->args[k])) == DM_SUCCESS)
 			g_tree_foreach(self->ids, (GTraverseFunc) _do_store, D);
		else
			dbmail_imap_session_buff_printf(self, "%s NO STORE failed: Sequence invalid.\r\n", self->tag);
  	}	

	db_mailbox_seq_update(MailboxState_getId(self->mailbox->mbstate));

	g_list_destroy(cmd->keywords);
	g_free(cmd);

	if (result || D->status) {
		if (result) D->status = result;
		SESSION_RETURN;
	}

	SESSION_OK;
	SESSION_RETURN;
}

int _ic_store(ImapSession *self)
{
	if (!check_state_and_args (self, 2, 0, CLIENTSTATE_SELECTED)) return 1;
	dm_thread_data_push((gpointer)self, _ic_store_enter, _ic_cb_leave, NULL);
	return 0;
}

/*
 * _ic_copy()
 *
 * copy a message to another mailbox
 */

static gboolean _do_copy(u64_t *id, gpointer UNUSED value, ImapSession *self)
{
	cmd_t cmd = self->cmd;
	u64_t newid;
	int result;

	result = db_copymsg(*id, cmd->mailbox_id, self->userid, &newid);
	if (result == -1) {
		dbmail_imap_session_buff_printf(self, "* BYE internal dbase error\r\n");
		return TRUE;
	}
	if (result == -2) {
		dbmail_imap_session_buff_printf(self, "%s NO quotum would exceed\r\n", self->tag);
		return TRUE;
	}
	return FALSE;
}


static void _ic_copy_enter(dm_thread_data *D)
{
	SESSION_GET;
	u64_t destmboxid;
	int result;
	MailboxState_T S;
	cmd_t cmd;

	/* check if destination mailbox exists */
	if (! db_findmailbox(self->args[self->args_idx+1], self->userid, &destmboxid)) {
		dbmail_imap_session_buff_printf(self, "%s NO [TRYCREATE] specified mailbox does not exist\r\n", self->tag);
		D->status = 1;
		SESSION_RETURN;
	}
	// check if user has right to COPY from source mailbox
	if ((result = mailbox_check_acl(self, self->mailbox->mbstate, ACL_RIGHT_READ))) {
		D->status = result;
		SESSION_RETURN;
	}

	// check if user has right to COPY to destination mailbox
	S = dbmail_imap_session_mbxinfo_lookup(self, destmboxid, FALSE);
	if ((result = mailbox_check_acl(self, S, ACL_RIGHT_INSERT))) {
		D->status = result;
		SESSION_RETURN;
	}

	cmd = g_malloc0(sizeof(*cmd));
	cmd->mailbox_id = destmboxid;
	self->cmd = cmd;

	if (g_tree_nnodes(MailboxState_getIds(self->mailbox->mbstate)) > 0) {
 		if ((_dm_imapsession_get_ids(self, self->args[self->args_idx]) == DM_SUCCESS))
 			g_tree_foreach(self->ids, (GTraverseFunc) _do_copy, self);
  	}	
	g_free(self->cmd);
	self->cmd = NULL;

	db_mailbox_seq_update(destmboxid);

	if (MailboxState_getId(self->mailbox->mbstate) == destmboxid)
		dbmail_imap_session_mailbox_status(self, TRUE);

	SESSION_OK;
	SESSION_RETURN;
}

int _ic_copy(ImapSession *self) 
{
	if (!check_state_and_args(self, 2, 2, CLIENTSTATE_SELECTED)) return 1;
	dm_thread_data_push((gpointer)self, _ic_copy_enter, _ic_cb_leave, NULL);
	return 0;
}

/*
 * _ic_uid()
 *
 * fetch/store/copy/search message UID's
 */
int _ic_uid(ImapSession *self)
{
	int result;

	if (self->state != CLIENTSTATE_SELECTED) {
		dbmail_imap_session_buff_printf(self, "%s BAD UID command received in invalid state\r\n", self->tag);
		return 1;
	}

	if (! (self->args[0] && self->args[self->args_idx]) ) {
		dbmail_imap_session_buff_printf(self, "%s BAD missing argument(s) to UID\r\n", self->tag);
		return 1;
	}

	self->use_uid = 1;	/* set global var to make clear we will be using UID's */
	
	/* ACL rights for UID are handled by the other functions called below */
	if (MATCH(self->args[self->args_idx], "fetch")) {
		dbmail_imap_session_set_command(self, self->args[self->args_idx++]);
		result = _ic_fetch(self);
	} else if (MATCH(self->args[self->args_idx], "copy")) {
		dbmail_imap_session_set_command(self, self->args[self->args_idx++]);
		result = _ic_copy(self);
	} else if (MATCH(self->args[self->args_idx], "store")) {
		dbmail_imap_session_set_command(self, self->args[self->args_idx++]);
		result = _ic_store(self);
	} else if (MATCH(self->args[self->args_idx], "search")) {
		dbmail_imap_session_set_command(self, self->args[self->args_idx++]);
		result = _ic_search(self);
	} else if (MATCH(self->args[self->args_idx], "sort")) {
		dbmail_imap_session_set_command(self, self->args[self->args_idx++]);
		result = _ic_sort(self);
	} else if (MATCH(self->args[self->args_idx], "thread")) {
		dbmail_imap_session_set_command(self, self->args[self->args_idx++]);
		result = _ic_thread(self);
	} else {
		dbmail_imap_session_buff_printf(self, "%s BAD invalid UID command\r\n", self->tag);
		result = 1;
		self->use_uid = 0;
	}

	return result;
}


/* Helper function for _ic_getquotaroot() and _ic_getquota().
 * Send all resource limits in `quota'.
 */
void send_quota(ImapSession *self, quota_t * quota)
{
	int r;
	u64_t usage, limit;
	char *name;

	for (r = 0; r < quota->n_resources; r++) {
		if (quota->resource[r].limit > 0) {
			switch (quota->resource[r].type) {
			case RT_STORAGE:
				name = "STORAGE";
				usage = quota->resource[r].usage / 1024;
				limit = quota->resource[r].limit / 1024;
				break;
			default:
				continue;
			}
			dbmail_imap_session_buff_printf(self, "* QUOTA \"%s\" (%s %llu %llu)\r\n", quota->root, name, usage, limit);
		}
	}
}

/*
 * _ic_getquotaroot()
 *
 * get quota root and send quota
 */
static void _ic_getquotaroot_enter(dm_thread_data *D)
{
	quota_t *quota;
	char *root, *errormsg;
	SESSION_GET;

	if (! (root = quota_get_quotaroot(self->userid, self->args[self->args_idx], &errormsg))) {
		dbmail_imap_session_buff_printf(self, "%s NO %s\r\n", self->tag, errormsg);
		D->status=1;
		SESSION_RETURN;
	}

	if (! (quota = quota_get_quota(self->userid, root, &errormsg))) {
		dbmail_imap_session_buff_printf(self, "%s NO %s\r\n", self->tag, errormsg);
		D->status=1;
		SESSION_RETURN;
	}

	dbmail_imap_session_buff_printf(self, "* QUOTAROOT \"%s\" \"%s\"\r\n", self->args[self->args_idx], quota->root);

	send_quota(self, quota);
	quota_free(quota);

	SESSION_OK;
	SESSION_RETURN;
}

int _ic_getquotaroot(ImapSession *self)
{
	if (! check_state_and_args(self, 1, 1, CLIENTSTATE_AUTHENTICATED)) return 1;
	dm_thread_data_push((gpointer)self, _ic_getquotaroot_enter, _ic_cb_leave, NULL);
	return 0;
}

/*
 * _ic_getquot()
 *
 * get quota
 */
static void _ic_getquota_enter(dm_thread_data *D)
{
	quota_t *quota;
	char *errormsg;
	SESSION_GET;

	if (! (quota = quota_get_quota(self->userid, self->args[self->args_idx], &errormsg))) {
		dbmail_imap_session_buff_printf(self, "%s NO %s\r\n", self->tag, errormsg);
		D->status=1;
		SESSION_RETURN;
	}

	send_quota(self, quota);
	quota_free(quota);

	SESSION_OK;
	SESSION_RETURN;
}

int _ic_getquota(ImapSession *self)
{
	if (! check_state_and_args(self, 1, 1, CLIENTSTATE_AUTHENTICATED)) return 1;
	dm_thread_data_push((gpointer)self, _ic_getquota_enter, _ic_cb_leave, NULL);
	return 0;
}

/* returns -1 on error, 0 if user or mailbox not found and 1 otherwise */
static int imap_acl_pre_administer(const char *mailboxname,
				   const char *username,
				   u64_t executing_userid,
				   u64_t * mboxid, u64_t * target_userid)
{
	if (! db_findmailbox(mailboxname, executing_userid, mboxid))
		return FALSE;
	return auth_user_exists(username, target_userid);
}

static void _ic_setacl_enter(dm_thread_data *D)
{
	/* SETACL mailboxname identifier mod_rights */
	int result;
	u64_t mboxid;
	u64_t targetuserid;
	MailboxState_T S;
	SESSION_GET;

	result = imap_acl_pre_administer(self->args[self->args_idx], self->args[self->args_idx+1], self->userid, &mboxid, &targetuserid);
	if (result == -1) {
		dbmail_imap_session_buff_printf(self, "* BYE internal database error\r\n");
		D->status = -1;
		SESSION_RETURN;
	} else if (result == 0) {
		dbmail_imap_session_buff_printf(self, "%s NO SETACL failure: can't set acl\r\n", self->tag);
		D->status = 1;
		SESSION_RETURN;
	}
	// has the rights to 'administer' this mailbox? 
	S = dbmail_imap_session_mbxinfo_lookup(self, mboxid, FALSE);
	if ((result = mailbox_check_acl(self, S, ACL_RIGHT_ADMINISTER))) {
		D->status = result;
		SESSION_RETURN;
	}

	// set the new acl
	if (acl_set_rights(targetuserid, mboxid, self->args[self->args_idx+2]) < 0) {
		dbmail_imap_session_buff_printf(self, "* BYE internal database error\r\n");
		D->status = -1;
		SESSION_RETURN;
	}

	SESSION_OK;
	SESSION_RETURN;
}

int _ic_setacl(ImapSession *self)
{
	if (!check_state_and_args(self, 3, 3, CLIENTSTATE_AUTHENTICATED)) return 1;
	dm_thread_data_push((gpointer)self, _ic_setacl_enter, _ic_cb_leave, NULL);
	return 0;
}
	

static void _ic_deleteacl_enter(dm_thread_data *D)
{
	// DELETEACL mailboxname identifier
	u64_t mboxid, targetuserid;
	MailboxState_T S;
	int result;
	SESSION_GET;

	if (imap_acl_pre_administer(self->args[self->args_idx], 
				self->args[self->args_idx+1], self->userid, &mboxid, &targetuserid) == -1) {
		dbmail_imap_session_buff_printf(self, "* BYE internal dbase error\r\n");
		D->status = -1;
		SESSION_RETURN;
	}
	
	S = dbmail_imap_session_mbxinfo_lookup(self, mboxid, FALSE);
	if ((result = mailbox_check_acl(self, S, ACL_RIGHT_ADMINISTER))) {
		D->status = result;
		SESSION_RETURN;
	}

	// set the new acl
	if (acl_delete_acl(targetuserid, mboxid) < 0) {
		dbmail_imap_session_buff_printf(self, "* BYE internal database error\r\n");
		D->status = -1;
		SESSION_RETURN;
	}

	SESSION_OK;
	SESSION_RETURN;
}

int _ic_deleteacl(ImapSession *self)
{
	if (!check_state_and_args(self, 2, 2, CLIENTSTATE_AUTHENTICATED)) return 1;
	dm_thread_data_push((gpointer)self, _ic_deleteacl_enter, _ic_cb_leave, NULL);
	return 0;
}

static void _ic_getacl_enter(dm_thread_data *D)
{
	/* GETACL mailboxname */
	u64_t mboxid;
	char *acl_string;
	SESSION_GET;

	if (! db_findmailbox(self->args[self->args_idx], self->userid, &mboxid)) {
		dbmail_imap_session_buff_printf(self, "%s NO GETACL failure: can't get acl\r\n", self->tag);
		D->status = 1;
		SESSION_RETURN;
	}
	// get acl string (string of identifier-rights pairs)
	if (!(acl_string = acl_get_acl(mboxid))) {
		dbmail_imap_session_buff_printf(self, "* BYE internal database error\r\n");
		D->status = -1;
		SESSION_RETURN;
	}

	dbmail_imap_session_buff_printf(self, "* ACL \"%s\" %s\r\n", self->args[self->args_idx], acl_string);
	g_free(acl_string);

	SESSION_OK;
	SESSION_RETURN;
}

int _ic_getacl(ImapSession *self)
{
	if (!check_state_and_args(self, 1, 1, CLIENTSTATE_AUTHENTICATED)) return 1;
	dm_thread_data_push((gpointer)self, _ic_getacl_enter, _ic_cb_leave, NULL);
	return 0;
}

static void _ic_listrights_enter(dm_thread_data *D)
{
	/* LISTRIGHTS mailboxname identifier */
	int result;
	u64_t mboxid;
	u64_t targetuserid;
	char *listrights_string;
	MailboxState_T S;
	SESSION_GET;

	result = imap_acl_pre_administer(self->args[self->args_idx], self->args[self->args_idx+1], self->userid, &mboxid, &targetuserid);
	if (result == -1) {
		dbmail_imap_session_buff_printf(self, "* BYE internal database error\r\n");
		D->status = -1;
		SESSION_RETURN;
	} else if (result == 0) {
		dbmail_imap_session_buff_printf(self, "%s, NO LISTRIGHTS failure: can't set acl\r\n", self->tag);
		D->status = 1;
		SESSION_RETURN;
	}
	// has the rights to 'administer' this mailbox? 
	S = dbmail_imap_session_mbxinfo_lookup(self, mboxid, FALSE);
	if ((result = mailbox_check_acl(self, S, ACL_RIGHT_ADMINISTER))) {
		D->status=1;
		SESSION_RETURN;	
	}

	// set the new acl
	if (!(listrights_string = acl_listrights(targetuserid, mboxid))) {
		dbmail_imap_session_buff_printf(self, "* BYE internal database error\r\n");
		D->status=-1;
		SESSION_RETURN;
	}

	dbmail_imap_session_buff_printf(self, "* LISTRIGHTS \"%s\" %s %s\r\n",
		self->args[self->args_idx], self->args[self->args_idx+1], listrights_string);
	g_free(listrights_string);

	SESSION_OK;
	SESSION_RETURN;
}

int _ic_listrights(ImapSession *self)
{
	if (!check_state_and_args(self, 2, 2, CLIENTSTATE_AUTHENTICATED)) return 1;
	dm_thread_data_push((gpointer)self, _ic_listrights_enter, _ic_cb_leave, NULL);
	return 0;
}

static void _ic_myrights_enter(dm_thread_data *D)
{
	/* MYRIGHTS mailboxname */
	u64_t mboxid;
	char *myrights_string;
	SESSION_GET;

	if (! db_findmailbox(self->args[self->args_idx], self->userid, &mboxid)) {
		dbmail_imap_session_buff_printf(self, "%s NO MYRIGHTS failure: unknown mailbox\r\n", self->tag);
		D->status=1;
		SESSION_RETURN;
	}

	if (!(myrights_string = acl_myrights(self->userid, mboxid))) {
		dbmail_imap_session_buff_printf(self, "* BYE internal database error\r\n");
		D->status = -1;
		SESSION_RETURN;
	}

	dbmail_imap_session_buff_printf(self, "* MYRIGHTS \"%s\" %s\r\n", self->args[self->args_idx], myrights_string);
	g_free(myrights_string);

	SESSION_OK;
	SESSION_RETURN;
}

int _ic_myrights(ImapSession *self)
{
	if (!check_state_and_args(self, 1, 1, CLIENTSTATE_AUTHENTICATED)) return 1;
	dm_thread_data_push((gpointer)self, _ic_myrights_enter, _ic_cb_leave, NULL);
	return 0;
}

static void _ic_namespace_enter(dm_thread_data *D)
{
	SESSION_GET;
	dbmail_imap_session_buff_printf(self, "* NAMESPACE ((\"\" \"%s\")) ((\"%s\" \"%s\")) "
		"((\"%s\" \"%s\"))\r\n",
		MAILBOX_SEPARATOR, NAMESPACE_USER,
		MAILBOX_SEPARATOR, NAMESPACE_PUBLIC, MAILBOX_SEPARATOR);

	SESSION_OK;
	SESSION_RETURN;
}

int _ic_namespace(ImapSession *self)
{
	if (!check_state_and_args(self, 0, 0, CLIENTSTATE_AUTHENTICATED)) return 1;
	dm_thread_data_push((gpointer)self, _ic_namespace_enter, _ic_cb_leave, NULL);
	return 0;
}