File: maildir.c

package info (click to toggle)
mailutils 1%3A3.19-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 38,832 kB
  • sloc: ansic: 186,739; sh: 110,867; yacc: 7,463; cpp: 3,834; makefile: 3,161; lex: 1,972; python: 1,617; exp: 1,563; awk: 152; lisp: 132; sed: 31
file content (1900 lines) | stat: -rw-r--r-- 43,576 bytes parent folder | download
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
/* GNU Mailutils -- a suite of utilities for electronic mail
   Copyright (C) 1999-2025 Free Software Foundation, Inc.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 3 of the License, or (at your option) any later version.

   This library 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
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General
   Public License along with this library.  If not, see
   <http://www.gnu.org/licenses/>. */

/* First draft by Sergey Poznyakoff */

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <ctype.h>
#include <dirent.h>
#include <limits.h>

#ifdef WITH_PTHREAD
# ifdef HAVE_PTHREAD_H
#  ifndef _XOPEN_SOURCE
#   define _XOPEN_SOURCE  500
#  endif
#  include <pthread.h>
# endif
#endif

#include <string.h>
#ifdef HAVE_STRINGS_H
# include <strings.h>
#endif

#include <mailutils/attribute.h>
#include <mailutils/body.h>
#include <mailutils/debug.h>
#include <mailutils/envelope.h>
#include <mailutils/error.h>
#include <mailutils/header.h>
#include <mailutils/message.h>
#include <mailutils/util.h>
#include <mailutils/property.h>
#include <mailutils/stream.h>
#include <mailutils/url.h>
#include <mailutils/observer.h>
#include <mailutils/errno.h>
#include <mailutils/locker.h>
#include <mailutils/sys/mailbox.h>
#include <mailutils/sys/registrar.h>
#include <mailutils/sys/amd.h>
#include <mailutils/io.h>
#include <mailutils/cstr.h>
#include <maildir.h>

#ifndef PATH_MAX 
# define PATH_MAX _POSIX_PATH_MAX
#endif

/* The maildir mailbox */
struct _maildir_data
{
  struct _amd_data amd;
  int folder_fd;         /* Descriptor of the top-level maildir directory */
  /* Additional data used during scanning: */
  int needs_attribute_fixup; /* The mailbox is created by mailutils 3.10
				or earlier and needs the attribute fixup
				(see "Maildir attribute fixup"" below) */
  int needs_uid_fixup;       /* Messages in the mailbox need to be assigned
				new UIDS.  Consequently, the uidvalidity
				value must be updated too. */
  size_t next_uid;           /* Predicted next UID. */
};

struct _maildir_message
{
  struct _amd_message amd_message;
  int subdir;
  char *file_name;  /* File name */
  size_t uniq_len;  /* Length of the unique file name prefix. */
  size_t uid;
};

static char *subdir_name[] = { "cur", "new", "tmp" };

char const *
mu_maildir_subdir_name (int subdir)
{
  if (subdir < 0 || subdir >= MU_ARRAY_SIZE (subdir_name))
    {
      errno = EINVAL;
      return NULL;
    }
  return subdir_name[subdir];
}

int
mu_maildir_reserved_name (char const *name)
{
  return strcmp (name, subdir_name[SUB_TMP]) == 0
         || strcmp (name, subdir_name[SUB_CUR]) == 0
         || strcmp (name, subdir_name[SUB_NEW]) == 0
	 || (strlen (name) > 3
             && (memcmp (name, ".mh", 3) == 0 || memcmp (name, ".mu", 3) == 0));
}

static inline void
reset_uid (struct _maildir_data *md)
{
  md->next_uid = 1;
}
  
static inline size_t
alloc_uid (struct _maildir_data *md)
{
  return md->next_uid++;
}

static inline size_t
next_uid (struct _maildir_data *md)
{
  return md->next_uid;
}  

static inline void
update_uid (struct _maildir_data *md, size_t uid)
{
  md->next_uid = uid + 1;
}

/*
 * Attribute handling.
 */

static struct info_map {
  char letter;
  int flag;
} info_map[] = {
  /* Draft: the user considers this message a draft; toggled at user
     discretion.  */
  { 'D', MU_ATTRIBUTE_DRAFT },
  /* Flagged: user-defined flag; toggled at user discretion. */
  { 'F', MU_ATTRIBUTE_FLAGGED },
  /* Passed: the user has resent/forwarded/bounced this message to
     someone else. */
  { 'P', MU_ATTRIBUTE_FORWARDED }, 
  /* Replied: the user has replied to this message. */
  { 'R', MU_ATTRIBUTE_ANSWERED },
  /* Seen: the user has viewed this message, though perhaps he didn't
     read all the way through it.
     This corresponds to the MU_ATTRIBUTE_READ attribute. */
  { 'S', MU_ATTRIBUTE_READ },
  /* Trashed: the user has moved this message to the trash; the trash
     will be emptied by a later user action. */
  { 'T', MU_ATTRIBUTE_DELETED },
  
  /* Mailutils versions prior to 3.10.90 marked replied messages with the
     'a' flag.  The discrepancy with the de-facto standard was reported
     in http://savannah.gnu.org/bugs/?56428.

     This entry is preserved for a while, for backward compatibility.

     Keep it at the end, so the 'R' letter is used when converting
     attributes to maildir info letters.

     Info flags are fixed in maildir_scan_unlocked.
  */
  { 'a', MU_ATTRIBUTE_ANSWERED },
};
#define info_map_size (MU_ARRAY_SIZE (info_map))

/* NOTE: BUF must be at least info_map_size bytes long */
static int
flags_to_info (int flags, char *buf)
{
  struct info_map *p;
  
  for (p = info_map; p < info_map + info_map_size; p++)
    {
      if (p->flag & flags)
	*buf++ = p->letter;
      /* Avoid handling the same flag again.  See the description of
	 'a' in info_map above and "Maildir attribute fixup" below. */
      flags &= ~p->flag;
    }
  *buf = 0;
  return 0;
}

static int
info_to_flags (char const *buf)
{
  int flags = 0;
  struct info_map *p;

  for (p = info_map; p < info_map + info_map_size; p++)
    if (strchr (buf, p->letter))
      flags |= p->flag;
  return flags;
}

/*
 * Maildir message file handling.
 * ==============================
 *
 * The format of the maildir message file name is described in:
 * http://cr.yp.to/proto/maildir.html.
 *
 * It consists of:
 *
 *   uniq [ ',' attrs ] ':2,' info
 *
 * where:
 *   uniq  - unique name prefix;
 *   info  - message flags in alphabetical order;
 *   attrs - implementation-defined attributes.
 *
 * The specification states that a "unique name can be anything that
 * doesn't contain a colon (or slash) and doesn't start with a dot."
 * This makes it possible to add to the unique prefix a list of comma-
 * separated attributes.  Each attribute consists of the attribute name,
 * immediately followed by '=' and attribute value.  Neither part can
 * contain '=' or ','.
 *
 * Mailutils implementation defines the following attributes:
 *
 *  u  -  UID of the message.
 *
 */

/*
 * Each attribute is represented by the following structure:
 */  
struct attrib
{
  char *name;             /* Attribute name */
  char *value;            /* Attribute value */
  struct attrib *next;    /* Pointer to the next attribute in list. */
};

/*
 * Both name and value point to the memory allocated in one block with
 * the attrib structure.  Attributes form a singly-linked list with the
 * list head pointing to the first attribute defined in the file name.
 *
 * Functions for accessing attribute lists:
 */

/* Push new attribute at the head of the existing attribute list.

   head - Pointer to the current list head;
   name - Attribute name;
   nlen - Length of the name;
   val  - Value;
   vlen - Length of the value.

   On success, updates head and returns the new head attribute.
   On memory allocation error, return NULL and does not modify head.
*/
static inline struct attrib *
attrib_push (struct attrib **head, char const *name, size_t nlen,
	     char const *val, size_t vlen)
{
  struct attrib *attr;

  attr = malloc (sizeof (*attr) + nlen + vlen + 2);
  attr->next = *head;
  attr->name = (char*)(attr + 1);
  memcpy(attr->name, name, nlen);
  attr->name[nlen] = 0;
  attr->value = attr->name + nlen + 1;
  memcpy(attr->value, val, vlen);
  attr->value[vlen] = 0;
  *head = attr;
  return attr;
}

/* Free the attribute list */
static void
attrib_free (struct attrib *alist)
{
  while (alist)
    {
      struct attrib *next = alist->next;
      free (alist);
      alist = next;
    }
}

/* If the attribute name is present in the list alist, return its value.
   Otherwise, return NULL. */
static char const *
attrib_lookup (struct attrib *alist, char const *name)
{
  while (alist)
    {
      if (strcmp (alist->name, name) == 0)
	return alist->value;
      alist = alist->next;
    }
  return NULL;
}

/* Auxiliary function.  Returns 1 if the string STR of length LEN is
   encountered in the NULL-terminated string list STRLIST, and 0 otherwise.
*/
static inline int
is_member_of (char const *str, size_t len, char **strlist)
{
  char const *p;
  
  if (!strlist)
    return 1;
  while ((p = *strlist) != NULL)
    {
      if (strlen (p) == len && memcmp (p, str, len) == 0)
	return 1;
      strlist++;
    }
  return 0;
}

/*
 * Message name parser.
 *
 * Alphabet:
 *      0   ANY
 *      1   ','
 *      2   '1'
 *      3   '2'
 *      4   ':'
 *      5   '='
 *
 * Transitions:
 *
 *      \      input
 *      state
 *      
 *      \  0 1 2 3 4 5
 *      -+ -----------
 *      0| 0 1 0 0 0 0
 *      1| 0 0 2 3 0 0
 *      2| 0 0 0 0 4 0 
 *      3| 0 0 0 0 5 0
 *      4| 6 8 6 6 6 8   experimental semantics: any except ,=
 *      5| 6 8 6 6 6 8   flags : any except ,=
 *      6| 6 8 6 6 6 7   consume value; ends at =
 *      7| 7 6 7 7 7 8   consume keyword; ends at ,
 *      8|<stop>
 */

/* Convert input character to alphabet symbol code. */
static inline int
alpha (int input)
{
  switch (input)
    {
    case ',':
      return 1;

    case '1':
      return 2;

    case '2':
      return 3;

    case ':':
      return 4;

    case '=':
      return 5;
    }

  return 0;
}

/* Extract information from the maildir message name NAME.
   
   Input:
     name      - Message file name.
     attrnames - Pointer to the array of attribute names we are interested in.
                 NULL means all attributes, if attrs is not NULL.

   Output:
     flags     - Parsed out flags.  Can be NULL.
     attrs     - Linked list of extracted attributes.  

   If attrs is NULL, no attributes are returned and attrnames is not referenced.
     
   Returns length of the unique name prefix, or (size_t)-1 if memory
   allocation fails.
*/
static size_t
maildir_message_name_parse (char const *name, char **attrnames,
			    int *flags, struct attrib **attrs)
{
  char const *p = name + strlen (name);
  static int transition[][6] = {
    { 0, 1, 0, 0, 0, 0 },
    { 0, 0, 2, 3, 0, 0 },
    { 0, 0, 0, 0, 4, 0 }, 
    { 0, 0, 0, 0, 5, 0 },
    { 6, 8, 6, 6, 6, 8 },
    { 6, 8, 6, 6, 6, 8 },
    { 6, 8, 6, 6, 6, 7 },
    { 7, 6, 7, 7, 7, 8 },
  };
  int state = 0, oldstate;
  char const *endp = p;
  char const *startval;
  char const *endval = NULL;
  struct attrib *athead = NULL;
  size_t len;
  int f = 0;
  
  while (p > name)
    {
      p--;
      oldstate = state;
      state = transition[state][alpha(*p)];
      switch (state)
	{
	case 4:
	  endp = p;
	  endval = p;
	  f = 0;
	  break;

	case 5:
	  endp = p;
	  endval = p;
	  f = info_to_flags (p + 3);
	  break;

	case 6:
	  if (oldstate == 7)
	    {
	      len = startval - p - 2;
	      if (attrs && is_member_of (p + 1, len, attrnames))
		{
		  if (!attrib_push (&athead, p + 1, len,
				    startval, endval - startval))
		    {
		      attrib_free (athead);
		      return (size_t)-1;
		    }
		}
	      endp = p;
	      endval = p;
	    }
	  else if (oldstate != state)
	    endval = p + 1;
	  break;

	case 7:
	  if (oldstate != state)
	    startval = p + 1;
	  break;

	case 8:
	  /* error */
	  if (endval)
	    endp = endval;
	  else
	    endp = p + 2;
	  goto end;
	}
    }
 end:
  if (flags)
    *flags = f;
  if (attrs)
    *attrs = athead;
  return endp - name;
}

static int
maildir_open (struct _maildir_data *md)
{
  if (md->folder_fd == -1)
    {
      int fd = open (md->amd.name, O_RDONLY | O_NONBLOCK | O_DIRECTORY);
      if (fd == -1)
	{
	  int rc = errno;
	  mu_debug (MU_DEBCAT_MAILBOX, MU_DEBUG_ERROR,
		    ("can't open directory %s: %s",
		     md->amd.name, mu_strerror (rc)));
	  return rc;
	}
      else
	md->folder_fd = fd;
    }
  return 0;
}

static void
maildir_close (struct _maildir_data *md)
{
  if (md->folder_fd != -1)
    {
      close (md->folder_fd);
      md->folder_fd = -1;
    }
}

/* Open subdirectory SUBDIR in MD.
   Note: maildir must be open.
 */
static int
maildir_subdir_open (struct _maildir_data *md, int subdir,
		     DIR **pdir, int *pfd)
{
  int rc;
  int fd;
  DIR *dir;
  
  fd = openat (md->folder_fd, subdir_name[subdir],
	       O_RDONLY | O_NONBLOCK | O_DIRECTORY);
  if (fd == -1)
    {
      if (errno == ENOENT)
	{
	  int perms = PERMS | mu_stream_flags_to_mode (md->amd.mailbox->flags, 1);
	  if (mkdirat (md->folder_fd, subdir_name[subdir], perms) == 0)
	    {
	      fd = openat (md->folder_fd, subdir_name[subdir],
			   O_RDONLY | O_NONBLOCK | O_DIRECTORY);
	    }
	  else
	    {
	      rc = errno;
	      mu_debug (MU_DEBCAT_MAILBOX, MU_DEBUG_ERROR,
			("can't create directory %s/%s: %s",
			 md->amd.name, subdir_name[subdir], mu_strerror (rc)));
	      return rc;
	      
	    }
	}

      if (fd == -1)
	{
	  rc = errno;
	  mu_debug (MU_DEBCAT_MAILBOX, MU_DEBUG_ERROR,
		    ("can't open directory %s/%s: %s",
		     md->amd.name, subdir_name[subdir], mu_strerror (rc)));
	  return rc;
	}
    }

  if (pdir)
    {
      dir = fdopendir (fd);
      if (!dir)
	{
	  rc = errno;
	  mu_debug (MU_DEBCAT_MAILBOX, MU_DEBUG_ERROR,
		    ("can't fdopen directory %s/%s: %s",
		     md->amd.name, subdir_name[subdir], mu_strerror (rc)));
	  close (fd);
	  return rc;
	}

      *pdir = dir;
    }
  *pfd = fd;
  
  return 0;
}

static int
maildir_message_alloc (struct _maildir_data *md, int subdir, char const *name,
		       struct _maildir_message **pmsg)
{
  struct _maildir_message *msg;
  size_t n;
  static char *attrnames[] = { "a", "u", NULL };
  struct attrib *attrs;
  char const *p;
  
  msg = calloc (1, sizeof (*msg));
  if (!msg)
    return errno;
  msg->subdir = subdir;
  msg->file_name = strdup (name);
  if (!msg->file_name)
    {
      free (msg);
      return ENOMEM;
    }
  
  n = maildir_message_name_parse (name, attrnames,
				  &msg->amd_message.attr_flags,
				  &attrs);
  if (n == (size_t)-1)
    {
      free (msg->file_name);
      free (msg);
      return ENOMEM;
    }
  msg->uniq_len = n;
  
  if ((p = attrib_lookup (attrs, "a")) != NULL)
    {
      /* NOTICE: mu_attribute_string_to_flags preserves existing bits
	 in its second argument. */
      mu_attribute_string_to_flags (p, &msg->amd_message.attr_flags);
    }
  
  if ((p = attrib_lookup (attrs, "u")) != NULL)
    {
      char *endp;
      unsigned long n = strtoul (p, &endp, 10);
      if ((n == ULONG_MAX && errno == ERANGE) || *endp)
	/* The uid remains set to 0 and will be fixed up later */;
      else
	msg->uid = n;
    }

  attrib_free (attrs);
  *pmsg = msg;
  return 0;
}

static void
maildir_message_free (struct _amd_message *amsg)
{
  struct _maildir_message *mp = (struct _maildir_message *) amsg;
  if (mp)
    free (mp->file_name);
}

/*
 * Maildir scanning
 */
int
maildir_tmp_flush (struct _maildir_data *md)
{
  int rc;
  int fd;
  DIR *dir;
  struct dirent *entry;
    
  if (!(md->amd.mailbox->flags & MU_STREAM_WRITE))
    return 0; /* Do nothing in read-only mode */

  rc = maildir_subdir_open (md, SUB_TMP, &dir, &fd);
  if (rc)
    return rc;

  while ((entry = readdir (dir)))
    {
      switch (entry->d_name[0])
	{
	case '.':
	  break;

	default:
	  unlinkat (fd, entry->d_name, 0);
	  break;
	}
    }

  closedir (dir);
  return 0;
}

static int
maildir_subdir_scan (struct _maildir_data *md, int subdir)
{
  int rc;
  int fd;
  DIR *dir;
  struct dirent *entry;

  rc = maildir_subdir_open (md, subdir, &dir, &fd);
  if (rc)
    return rc;

  while ((entry = readdir (dir)))
    {
      struct stat st;
      struct _maildir_message *msg;
      size_t index;
      
      if (entry->d_name[0] == '.')
	continue;

      if (fstatat (fd, entry->d_name, &st, 0))
	{
	  if (errno != ENOENT)
	    {
	      mu_debug (MU_DEBCAT_MAILBOX, MU_DEBUG_ERROR,
			("can't stat %s/%s/%s: %s",
			 md->amd.name, subdir_name[subdir], entry->d_name,
			 mu_strerror (errno)));
	    }
	  continue;
	}

      if (!S_ISREG (st.st_mode))
	continue;

      msg = calloc (1, sizeof (*msg));
      if (!msg)
	{
	  rc = ENOMEM;
	  break;
	}

      rc = maildir_message_alloc (md, subdir, entry->d_name, &msg);

      if (!amd_msg_lookup (&md->amd, (struct _amd_message *) msg, &index))
	{
	  /* should not happen */
	  maildir_message_free ((struct _amd_message *) msg);
	  continue;
	}

      rc = _amd_message_append (&md->amd, (struct _amd_message *) msg);
      if (rc)
	{
	  maildir_message_free ((struct _amd_message *) msg);
	  break;
	}
    }
  
  closedir (dir);
  return 0;
}

/*
 * Maildir attribute fixup
 * =======================
 *
 * Message info flags used by Mailutils versions prior to 3.10.90 differ
 * from those described in the reference maildir implementation
 * (http://cr.yp.to/proto/maildir.html)
 * This was reported in http://savannah.gnu.org/bugs/?56428.
 *
 * The difference is summarized in the table below:
 *
 *  Attribute              Reference  MU-3.10
 *  ---------------------  ---------  -------
 *  MU_ATTRIBUTE_READ          S         R
 *  MU_ATTRIBUTE_ANSWERED      R         a
 *  MU_ATTRIBUTE_SEEN          -         S
 *
 * The "Attribute" column lists the mailutils attribute flag, the
 * "Reference" column contains the letter that corresponds to that flag
 * in the reference implementation and the "MU-3.10" column shows the
 * letter in mailutils 3.10 and earlier.
 *
 * Starting from version 3.10.90 this discrepancy is fixed.  To make sure
 * both old and new message attributes are correctly recognized, we try 
 * to detect whether the mailbox was created by mailutils versions prior to
 * 3.10.90 and fix up the attributes if so.  This is done after the initial
 * mailbox scan.
 *
 * To detect whether attributes need to be fixed, the .mu-prop file is
 * examined.  If it does not exist, it is assumed that the mailbox was
 * not created by mailutils and no fixup is needed.  If it exists and
 * does not contain the "version" property, or if the value of that
 * property is less than or equal to 3.10, then the fixup is needed.
 * Otherwise, fixup is not needed.  This is done by the needs_fixup
 * function.
 *
 * To assist in diagnostics, new AMD flag MU_AMD_F_PROP has been
 * added.  It is set if the .mu-prop file existed when the mailbox
 * was opened.
 *
 * During fixup, the internal attribute flags are changed according to
 * the table above.  If the mailbox is writable, each message file is
 * renamed if its attributes changed.  Otherwise, changes remain
 * in memory.  This is done by the maildir_attribute_fixup function.
 *
 * After successfully opening the (writable) mailbox, the "version"
 * property in its .mu-prop file is updated so that subsequent accesses
 * avoid performing the fixup again.
 *
 * The code below (up to the form feed character) will live for a couple
 * of releases after 3.11 to make sure all existing mailboxes have been
 * fixed up.
 */

static int
needs_fixup (struct _amd_data *amd)
{
  char const *amd_version;
  int rc;

  if (!(amd->flags & MU_AMD_F_PROP))
    {
      /* Absence of the mu-prop file indicates that this mailbox was
	 not created by mailutils (unless the file has been deleted,
	 of course).  Let's assume the former.  This means that no
	 attribute fixup is needed. */
      return 0;
    }

  if (amd->prop)
    {
      switch (mu_property_sget_value (amd->prop, "version", &amd_version))
	{
	case 0:
	  break;
	  
	case MU_ERR_NOENT:
	  return 1;

	default:
	  return 0;
	}
      if (mu_version_string_cmp (amd_version, "3.10", 0, &rc) == 0)
	return rc <= 0;
    }
  return 0;
}

static void
maildir_message_fixup (struct _maildir_data *md, struct _maildir_message *msg)
{
  int update = 0;
  
  if (md->needs_attribute_fixup)
    {
      int flags = msg->amd_message.attr_flags;

      if (flags & MU_ATTRIBUTE_READ)
	{
	  flags &= ~MU_ATTRIBUTE_READ;
	  flags |= MU_ATTRIBUTE_SEEN;
	}
      
      if (flags & MU_ATTRIBUTE_ANSWERED)
	{
	  flags &= ~MU_ATTRIBUTE_ANSWERED;
	  flags |= MU_ATTRIBUTE_READ;
	}
	  
      if (msg->amd_message.attr_flags != flags)
	{
	  msg->amd_message.attr_flags = flags;
	  update = 1;
	}
    }

  if (msg->uid == 0 || msg->uid < next_uid (md))
    md->needs_uid_fixup = 1;

  if (md->needs_uid_fixup)
    {
      msg->uid = alloc_uid (md);
      update = 1;
    }
  else
    update_uid (md, msg->uid);

  if (update && (md->amd.mailbox->flags & MU_STREAM_WRITE))
    {  
      md->amd.chattr_msg (&msg->amd_message, 0);
    }
}

static int
maildir_scan_unlocked (mu_mailbox_t mailbox, size_t *pcount, int do_notify)
{
  struct _maildir_data *md = mailbox->data;
  int rc;
  char const *s;
  struct stat st;
  size_t i;
  int has_new = 0;
  
  rc = maildir_open (md);
  if (rc)
    return rc;
  md->needs_attribute_fixup = needs_fixup (&md->amd);
  md->needs_uid_fixup = 0;
  reset_uid (md);
  
  /* Flush tmp/ */
  rc = maildir_tmp_flush (md);
  if (rc)
    goto err;

  /* Scan cur/ */
  rc = maildir_subdir_scan (md, SUB_CUR);
  if (rc)
    goto err;

  /* Scan new/ */
  rc = maildir_subdir_scan (md, SUB_NEW);
  if (rc)
    goto err;
  
  /* Sort messages */
  amd_sort (&md->amd);

  /* Fix up messages and send out dispatch notifications, if necessary. */
  for (i = 1; i <= md->amd.msg_count; i++)
    {
      struct _maildir_message *msg = (struct _maildir_message *)
	_amd_get_message (&md->amd, i);

      if (msg->subdir == SUB_NEW && !has_new)
	{
	  /* Update predicted next UID for allocation */
 	  amd_update_uidnext (&md->amd, &md->next_uid);
  	}
      
      if (msg->subdir == SUB_NEW && (md->amd.mailbox->flags & MU_STREAM_WRITE))
	{
	  msg->uid = alloc_uid (md);
	  if (md->amd.chattr_msg (&msg->amd_message, 0) == 0)
	    has_new = 1;
	}
      else
	{
	  if (has_new) /* should not happen */
	    md->needs_uid_fixup = 1;
	  maildir_message_fixup (md, msg);
	}
      if (do_notify)
	DISPATCH_ADD_MSG (mailbox, &md->amd, i);
    }

  /* Update predicted next UID either way */
  amd_update_uidnext (&md->amd, &md->next_uid);
  
  /* Reset uidvalidity if any of the UIDs changed */
  if (md->needs_uid_fixup)
    amd_reset_uidvalidity (&md->amd);
  
  /* Update version marker in the property file */
  if ((md->amd.mailbox->flags & MU_STREAM_WRITE) &&
      (mu_property_sget_value (md->amd.prop, "version", &s) ||
       strcmp (s, PACKAGE_VERSION)))
    {
      rc = mu_property_set_value (md->amd.prop, "version", PACKAGE_VERSION, 1);
      if (rc)
	{
	  mu_debug (MU_DEBCAT_MAILBOX, MU_DEBUG_ERROR,
		    ("maildir_scan_dir: mu_property_set_value failed during attribute fixup: %s",
		     mu_strerror (rc)));
	}
    }

  if (md->amd.mailbox->flags & MU_STREAM_WRITE)
    {
      rc = mu_property_save (md->amd.prop);
      if (rc)
	{
	  mu_debug (MU_DEBCAT_MAILBOX, MU_DEBUG_ERROR,
		    ("maildir_scan_dir: mu_property_save failed during attribute fixup: %s",
		     mu_strerror (rc)));
	}
      rc = 0;
    }

  if (stat (md->amd.name, &st) == 0)
    md->amd.mtime = st.st_mtime;
  else
    md->amd.mtime = time (NULL);
  if (rc == 0 && pcount)
    *pcount = md->amd.msg_count;

 err:
  maildir_close (md);

  return rc;
}

/*
 * Functions for generating the unique part of the filename.
 */

/* Auxiliary functions operate on a buffer of the following structure: */
struct string_buffer
{
  char *base;   /* Buffer pointer. */
  size_t size;  /* Number of bytes allocated for base. */
  size_t off;   /* Offset of the first uninitialized byte. */
};

#define STRING_BUFFER_INITIALIZER { NULL, 0, 0 }

static void
string_buffer_free (struct string_buffer *buf)
{
  free (buf->base);
}

/* Expand the buffer to approx. 3/2 of its current size. */
static int
string_buffer_expand (struct string_buffer *buf)
{
  size_t n;
  char *p;
  
  if (!buf->base)
    {
      n = 64;
    }
  else
    {
      n = buf->size;
      
      if ((size_t) -1 / 3 * 2 <= n)
	return ENOMEM;

      n += (n + 1) / 2;
    }
  p = realloc (buf->base, n);
  if (!p)
    return ENOMEM;
  buf->base = p;
  buf->size = n;
  return 0;
}

/* Append LEN bytes from S to the buffer. */
static int
string_buffer_append (struct string_buffer *buf, char const *s, size_t len)
{
  while (buf->off + len > buf->size)
    {
      if (string_buffer_expand (buf))
	return ENOMEM;
    }
  memcpy (buf->base + buf->off, s, len);
  buf->off += len;
  return 0;
}

/* Append nul-terminated string S. */
static inline int
string_buffer_appendz (struct string_buffer *buf, char const *s)
{
  return string_buffer_append (buf, s, strlen (s));
}

static char const digits[] = "0123456789ABCDEF";

/* Format the number N to the buffer.  BASE must be 10 or 16, no other
   value is allowed. */
static int
string_buffer_format_long (struct string_buffer *buf, unsigned long n,
			   int base)
{
  size_t start = buf->off;
  char *p, *q;
  do
    {
      if (string_buffer_append (buf, &digits[n % base], 1))
	return ENOMEM;
      n /= base;
    }
  while (n > 0);
  p = buf->base + start;
  q = buf->base + buf->off - 1;
  while (p < q)
    {
      int t = *q;
      *q = *p;
      *p = t;
      p++;
      q--;
    }
  return 0;
}

/* Format this host name to the buffer. */
static int
string_buffer_format_hostname (struct string_buffer *buf)
{
  size_t start = buf->off;
  size_t len, i;
  
  while (gethostname (buf->base + buf->off, buf->size - buf->off) != 0)
    {
      if (errno != 0 && errno != ENAMETOOLONG && errno != EINVAL
	  && errno != ENOMEM)
	return errno;
      if (string_buffer_expand (buf))
	return ENOMEM;
    }

  len = strlen (buf->base + buf->off);
  buf->off += len;
  
  /* encode '/', ':', '.', and ',' */
  for (i = start; i < buf->off; i++)
    {
      switch (buf->base[i])
	{
	case '/':
	case ':':
	case ',':
	  break;

	default:
	  continue;
	}

      while (buf->off + 3 > buf->size)
	{
	  if (string_buffer_expand (buf))
	    return ENOMEM;
	}
      memmove (buf->base + i + 4, buf->base + i + 1, buf->off - i - 1);
      buf->base[i+1] = digits[(buf->base[i] >> 6) & 7];
      buf->base[i+2] = digits[(buf->base[i] >> 3) & 7];
      buf->base[i+3] = digits[buf->base[i] & 7];
      buf->base[i] = '\\';
      i += 3;
      buf->off += 3;
    }

  return 0;
}

/* Format message flags to buffer. */
static int
string_buffer_format_flags (struct string_buffer *buf, int flags)
{
  int rc;
  char fbuf[info_map_size + 1];

  flags_to_info (flags, fbuf);
  if ((rc = string_buffer_append (buf, ":2,", 3)) != 0)
    return rc;
  return string_buffer_appendz (buf, fbuf);
}

/* Format mailutils-specific attribute flags to the string buffer.
   Mailutils-specific flags are the flags that have no corresponding
   info letter in the maildir memo.  These flags are encoded in the
   'a' attribute setting.
*/
static int
string_buffer_format_mu_flags (struct string_buffer *buf, int flags)
{
  int rc = 0;
  char fb[MU_STATUS_BUF_SIZE];
  size_t len;
  
  mu_attribute_flags_to_string (flags & (MU_ATTRIBUTE_FLAGGED|MU_ATTRIBUTE_SEEN),
				fb, sizeof (fb), &len);
  if (len > 0)
    {
      if ((rc = string_buffer_append (buf, ",a=", 3)) == 0)
	rc = string_buffer_append (buf, fb, len);
    }
  return rc;
}

static int
string_buffer_format_message_name (struct string_buffer *buf,
				   struct _maildir_message *msg,
				   int flags)
{
  int rc;
  
  if ((rc = string_buffer_append (buf, msg->file_name, msg->uniq_len)) == 0 &&
      (rc = string_buffer_format_mu_flags (buf, flags)) == 0 &&
      (rc = string_buffer_append (buf, ",u=", 3)) == 0 &&
      (rc = string_buffer_format_long (buf, msg->uid, 10)) == 0 &&
      (rc = string_buffer_format_flags (buf, flags)) == 0)
    ;
  return rc;
}

static int
read_random (void *buf, size_t size)
{
  int rc;
  int fd = open ("/dev/urandom", O_RDONLY);
  if (fd == -1)
    return -1;
  rc = read (fd, buf, size);
  close (fd);
  return rc != size;
}

/* Create unique part.  If FD is supplied, use its inode and dev numbers
   as part of the created string.  Return the allocated string or NULL on
   memory shortage.
 */
static char *
maildir_uniq_create (struct _amd_data *amd, int fd)
{
  struct string_buffer sb = STRING_BUFFER_INITIALIZER;
  struct timeval tv;
  unsigned long n;
  char *ret;
  int rc;
  struct stat st;
  
  gettimeofday (&tv, NULL);
  rc = string_buffer_format_long (&sb, (unsigned long) tv.tv_sec, 10);
  if (rc)
    goto err;

  rc = string_buffer_append (&sb, ".", 1);
  if (rc)
    goto err;
  
  if (read_random (&n, sizeof (unsigned long))) /* FIXME: 32 bits */
    {
      rc = string_buffer_append (&sb, "R", 1);
      if (rc)
	goto err;
      rc = string_buffer_format_long (&sb, n, 16);
      if (rc)
	goto err;
    }

  if (fd > 0 && fstat (fd, &st) == 0)
    {
      rc = string_buffer_append (&sb, "I", 1);
      if (rc)
	goto err;
      rc = string_buffer_format_long (&sb, st.st_ino, 16);
      if (rc)
	goto err;

      rc = string_buffer_append (&sb, "V", 1);
      if (rc)
	goto err;
      rc = string_buffer_format_long (&sb, st.st_dev, 16);
      if (rc)
	goto err;
    }
  
  rc = string_buffer_append (&sb, "M", 1);
  if (rc)
    goto err;
  rc = string_buffer_format_long (&sb, tv.tv_usec, 10);
  if (rc)
    goto err;
  
  rc = string_buffer_append (&sb, "P", 1);
  if (rc)
    goto err;
  rc = string_buffer_format_long (&sb, getpid (), 10);
  if (rc)
    goto err;

  rc = string_buffer_append (&sb, "Q", 1);
  if (rc)
    goto err;
  rc = string_buffer_format_long (&sb, amd->msg_count, 10);
  if (rc)
    goto err;

  rc = string_buffer_append (&sb, ".", 1);
  if (rc)
    goto err;
  rc = string_buffer_format_hostname (&sb);
  if (rc)
    goto err;
  
  rc = string_buffer_append (&sb, "", 1);
  
 err:
  if (rc == 0)
    {
      ret = sb.base;
      sb.base = NULL;
    }
  else
    ret = NULL;
  string_buffer_free (&sb);
  return ret;
}

/*
 * AMD interface functions.
 */
static int
maildir_cur_message_name (struct _amd_message *amsg, int abs, char **pname)
{
  struct _maildir_message *msg = (struct _maildir_message *) amsg;
  struct string_buffer sb = STRING_BUFFER_INITIALIZER;
  int rc;

  if (abs)
    {
      if ((rc = string_buffer_appendz (&sb, amsg->amd->name)) == 0)
	rc = string_buffer_append (&sb, "/", 1);
    }
  else
    rc = 0;

  if (rc == 0 &&
      (rc = string_buffer_appendz (&sb, subdir_name[msg->subdir])) == 0 &&
      (rc = string_buffer_append (&sb, "/", 1)) == 0 &&
      (rc = string_buffer_appendz (&sb, msg->file_name)) == 0 &&
      (rc = string_buffer_append (&sb, "", 1)) == 0)
    {
      *pname = sb.base;
      sb.base = NULL;
    }
  string_buffer_free (&sb);
  return rc;
}

static int
maildir_new_message_name (struct _amd_message *amsg, int flags, int expunge,
			  char **pname)
{
  struct _maildir_message *msg = (struct _maildir_message *) amsg;
  int rc = 0;
  
  if (expunge && (flags & MU_ATTRIBUTE_DELETED))
    {
      /* Force amd.c to unlink the file. */
      *pname = NULL;
    }
  else
    {
      struct string_buffer sb = STRING_BUFFER_INITIALIZER;
      if ((rc = string_buffer_appendz (&sb, amsg->amd->name)) == 0 &&
	  (rc = string_buffer_append (&sb, "/", 1)) == 0 &&
	  (rc = string_buffer_appendz (&sb, subdir_name[msg->subdir])) == 0 &&
	  (rc = string_buffer_append (&sb, "/", 1)) == 0)
	{
	  if (msg->subdir == SUB_CUR)
	    rc = string_buffer_format_message_name (&sb, msg, flags);
	  else
	    rc = string_buffer_appendz (&sb, msg->file_name);

	  if (rc == 0)
	    rc = string_buffer_append (&sb, "", 1);
	}

      if (rc == 0)
	{
	  *pname = sb.base;
	}
      else
	string_buffer_free (&sb);
    }
  return rc;
}

static int
maildir_create (struct _amd_data *amd, int flags)
{
  int rc;
  struct _maildir_data *md = (struct _maildir_data *)amd;
  
  rc = maildir_open (md);
  if (rc == 0) 
    {
      int i;
      
      for (i = 0; i < MU_ARRAY_SIZE (subdir_name); i++)
	{
	  int fd;
	  rc = maildir_subdir_open (md, i, NULL, &fd);
	  if (rc)
	    break;
	  close (fd);
	}
      maildir_close (md);
    }

  return rc;
}

static int
maildir_msg_finish_delivery (struct _amd_data *amd, struct _amd_message *amm,
			     const mu_message_t orig_msg,
			     mu_attribute_t atr)
{
  struct _maildir_data *md = (struct _maildir_data *)amd;
  struct _maildir_message *msg = (struct _maildir_message *) amm;
  int flags;
  int rc;
  int src_fd = -1, dst_fd = -1;
  struct string_buffer sb = STRING_BUFFER_INITIALIZER;
  char const *newname;
  
  if ((atr || mu_message_get_attribute (orig_msg, &atr) == 0)
      && mu_attribute_get_flags (atr, &flags) == 0
      && flags)
    {
      msg->subdir = SUB_CUR;
      rc = string_buffer_format_message_name (&sb, msg, flags);
      if (rc == 0)
	rc = string_buffer_append (&sb, "", 1);
      if (rc)
	{
	  string_buffer_free (&sb);
	  return rc;
	}
      newname = sb.base;
    }
  else
    {
      msg->subdir = SUB_NEW;
      newname = msg->file_name;
    }

  rc = maildir_open (md);
  if (rc)
    goto err;
    
  rc = maildir_subdir_open (md, SUB_TMP, NULL, &src_fd);
  if (rc)
    goto err;
  
  rc = maildir_subdir_open (md, msg->subdir, NULL, &dst_fd);
  if (rc)
    goto err;

  if (unlinkat (dst_fd, newname, 0) && errno != ENOENT)
    {
      rc = errno;
      mu_debug (MU_DEBCAT_MAILBOX, MU_DEBUG_ERROR,
		("can't unlink %s/%s/%s: %s",
		 amd->name, subdir_name[msg->subdir],
		 newname, mu_strerror (rc)));
    }
  else if (linkat (src_fd, msg->file_name, dst_fd, newname, 0) == 0)
    {
      if (unlinkat (src_fd, msg->file_name, 0))
	{
	  mu_debug (MU_DEBCAT_MAILBOX, MU_DEBUG_ERROR,
		    ("can't unlink %s/%s/%s: %s",
		     amd->name, subdir_name[SUB_TMP], msg->file_name,
		     mu_strerror (errno)));
	}
      
      if (strcmp (msg->file_name, newname))
	{
	  char *p = strdup (newname);
	  if (!p)
	    rc = errno;
	  else
	    {
	      free (msg->file_name);
	      msg->file_name = p;
	      /* uniq_len remains the same */
	    }
	}
    }
  else
    {
      rc = errno;
      
      mu_debug (MU_DEBCAT_MAILBOX, MU_DEBUG_ERROR,
		("renaming %s/%s to %s/%s in %s failed: %s",
		 subdir_name[SUB_TMP], msg->file_name,
		 subdir_name[msg->subdir], newname, 
		 amd->name, mu_strerror (rc)));
    }

 err:
  string_buffer_free (&sb);
  close (src_fd);
  close (dst_fd);
  maildir_close (md);
  
  return rc;
}
    
static int
maildir_scan0 (mu_mailbox_t mailbox, size_t msgno MU_ARG_UNUSED,
	       size_t *pcount, int do_notify)
{
  struct _amd_data *amd = mailbox->data;
  int rc;
  
  if (amd == NULL)
    return EINVAL;
  if (mailbox->flags & MU_STREAM_APPEND)
    return 0;
  mu_monitor_wrlock (mailbox->monitor);
  rc = maildir_scan_unlocked (mailbox, pcount, do_notify);
  mu_monitor_unlock (mailbox->monitor);
  return rc;
}

static int
maildir_qfetch (struct _amd_data *amd, mu_message_qid_t qid)
{
  struct _maildir_data *md = (struct _maildir_data *)amd;
  struct _maildir_message *msg;
  char *name = (char*)qid;
  char *p;
  int rc;
  int subdir;
  struct stat st;
  
  p = strrchr (name, '/');
  if (!p || p - qid != 3)
    return EINVAL;
  
  if (memcmp (name, subdir_name[SUB_CUR], strlen (subdir_name[SUB_CUR])) == 0)
    subdir = SUB_CUR;
  else if (memcmp (name, subdir_name[SUB_NEW], strlen (subdir_name[SUB_NEW])) == 0)
    subdir = SUB_NEW;
  else
    return EINVAL;
  
  rc = maildir_open (md);
  if (fstatat (md->folder_fd, name, &st, 0) == 0)
    {
      name = p + 1;
  
      rc = maildir_message_alloc (md, subdir, name, &msg);
      if (rc == 0)
	{
	  rc = _amd_message_insert (amd, (struct _amd_message*) msg);
	  if (rc)
	    maildir_message_free ((struct _amd_message*) msg);
	}
    }
  else
    rc = errno;

  maildir_close (md);
  
  return rc;
}

/*
 * Compare two maildir messages A and B.  The purpose is to determine
 * which one was delivered prior to another.
 *
 * Compare seconds, microseconds and number of deliveries, in that
 * order.  If all match (shouldn't happen), resort to lexicographical
 * comparison.
 *
 * FIXME: Use uid, if it is present in both message names?
 */
static int
maildir_message_cmp (struct _amd_message *a, struct _amd_message *b)
{
  char *name_a = ((struct _maildir_message *) a)->file_name;
  char *name_b = ((struct _maildir_message *) b)->file_name;
  char *pa, *pb;
  unsigned long la, lb;
  int d;
  
  la = strtoul (name_a, &name_a, 10);
  lb = strtoul (name_b, &name_b, 10);

  if (la > lb)
    return 1;
  if (la < lb)
    return -1;

  if ((d = (*name_a - *name_b)) != 0)
    return d;
  
  name_a++;
  name_b++;

  if ((pa = strchr (name_a, 'M')) != 0 && (pb = strchr (name_b, 'M')) != 0)
    {
      la = strtoul (pa + 1, &name_a, 10);
      lb = strtoul (pb + 1, &name_b, 10);

      if (la > lb)
	return 1;
      if (la < lb)
	return -1;
    }

  if ((pa = strchr (name_a, 'Q')) != 0 && (pb = strchr (name_b, 'Q')) != 0)
    {
      la = strtoul (pa + 1, &name_a, 10);
      lb = strtoul (pb + 1, &name_b, 10);

      if (la > lb)
	return 1;
      if (la < lb)
	return -1;
    }

  for (; *name_a && *name_a != ':' && *name_b && *name_b != ':';
       name_a++, name_b++)
    {
      if ((d = (*name_a - *name_b)) != 0)
	return d;
    }
  
  if ((*name_a == ':' || *name_a == 0) && (*name_b == ':' || *name_b == 0))
    return 0;

  return *name_a - *name_b;
}

static int
maildir_message_uid (mu_message_t msg, size_t *puid)
{
  struct _maildir_message *mp = mu_message_get_owner (msg);
  if (puid)
    *puid = mp->uid;
  return 0;
}

static int
maildir_remove (struct _amd_data *amd)
{
  int i;
  int rc = 0;
  struct string_buffer sb = STRING_BUFFER_INITIALIZER;
  size_t off;

  /* FIXME: amd_remove_dir requires absolute file names */
  if ((rc = string_buffer_appendz (&sb, amd->name)) == 0 &&
      (rc = string_buffer_append (&sb, "/", 1)) == 0)
    {
      off = sb.off;
      for (i = 0; i < MU_ARRAY_SIZE (subdir_name); i++)
	{
	  string_buffer_appendz (&sb, subdir_name[i]);
	  string_buffer_append (&sb, "", 1);
	  
	  rc = amd_remove_dir (sb.base);
	  if (rc)
	    {
	      mu_diag_output (MU_DIAG_WARNING,
			      "removing contents of %s failed: %s", sb.base,
			      mu_strerror (rc));
	      break;
	    }
	  sb.off = off;
	}
    }
  string_buffer_free (&sb);
  return rc;
}

static int
maildir_chattr_msg (struct _amd_message *amsg, int expunge)
{
  struct _maildir_message *mp = (struct _maildir_message *) amsg;
  struct _amd_data *amd = amsg->amd;
  int rc;
  int old_subdir;
  char *cur_name, *new_name;

  rc = maildir_cur_message_name (amsg, 1, &cur_name);
  if (rc)
    return rc;

  old_subdir = mp->subdir; 
  mp->subdir = SUB_CUR;
  rc = amd->new_msg_file_name (amsg, amsg->attr_flags, expunge, &new_name);
  if (rc == 0)
    {
      if (!new_name)
	{
	  if (unlink (mp->file_name))
	    {
	      rc = errno;
	      mu_debug (MU_DEBCAT_MAILBOX, MU_DEBUG_ERROR,
			("can't unlink %s: %s",
			 mp->file_name, mu_strerror (rc)));
	    }
	}
      else
	{
	  if (rename (cur_name, new_name))
	    {
	      rc = errno;
	      if (rc == ENOENT)
		mu_observable_notify (amd->mailbox->observable,
				      MU_EVT_MAILBOX_CORRUPT,
				      amd->mailbox);
	      else
		{
		  mu_debug (MU_DEBCAT_MAILBOX, MU_DEBUG_ERROR,
			    ("renaming %s to %s failed: %s",
			     cur_name, new_name, mu_strerror (rc)));
		}
	    }
	}
      if (rc)
	mp->subdir = old_subdir;
      else
	{
	  free (mp->file_name);
	  mp->file_name = strdup (strrchr (new_name, '/') + 1);
	  if (!mp->file_name)
	    rc = errno;
	  else
	    mp->uniq_len = maildir_message_name_parse (mp->file_name,
						       NULL, NULL, NULL);
	}
      free (new_name);
    }
  
  free (cur_name);

  return rc;
}

/* Compute size of the subdirectory SUBDIR.  Add the computed value to
   *PSIZE.
   Note: Maildir must be open. */
static int
maildir_subdir_size (struct _maildir_data *md, int subdir, mu_off_t *psize)
{
  int fd;
  DIR *dir;
  struct dirent *entry;
  int rc = 0;
  struct stat st;
  mu_off_t size = 0;
  
  rc = maildir_subdir_open (md, subdir, &dir, &fd);
  if (rc)
    return rc;

  while ((entry = readdir (dir)))
    {
      switch (entry->d_name[0])
	{
	case '.':
	  break;

	default:
	  if (fstatat (fd, entry->d_name, &st, 0))
	    {
	      mu_debug (MU_DEBCAT_MAILBOX, MU_DEBUG_ERROR,
			("can't stat %s/%s/%s: %s",
			 md->amd.name, subdir_name[subdir], entry->d_name,
			 mu_strerror (errno)));
	      continue;
	    }
	  if (S_ISREG (st.st_mode))
	    size += st.st_size;
	}
    }

  closedir (dir);
  *psize += size;

  return 0;
}

static int
maildir_size_unlocked (struct _amd_data *amd, mu_off_t *psize)
{
  struct _maildir_data *md = (struct _maildir_data *) amd;
  mu_off_t size = 0;
  int rc;

  rc = maildir_open (md);
  if (rc == 0)
    {
      rc = maildir_subdir_size (md, SUB_NEW, &size);
      if (rc == 0)
	{
	  rc = maildir_subdir_size (md, SUB_CUR, &size);
	  if (rc == 0)
	    *psize = size;
	}
      maildir_close (md);
    }
  return rc;
}

static int
maildir_size (mu_mailbox_t mailbox, mu_off_t *psize)
{
  struct _amd_data *amd = mailbox->data;
  int rc;
  
  if (amd == NULL)
    return EINVAL;

  mu_monitor_wrlock (mailbox->monitor);
  rc = maildir_size_unlocked (amd, psize);
  mu_monitor_unlock (mailbox->monitor);

  return rc;
}

/* Delivery to "dir/new" */
#define NTRIES 30

static int
maildir_msg_init (struct _amd_data *amd, struct _amd_message *amm)
{
  struct _maildir_data *md = (struct _maildir_data *)amd;
  struct _maildir_message *msg = (struct _maildir_message *) amm;
  struct stat st;
  int i;
  int rc;
  char *name = NULL;
  int fd;
  
  rc = maildir_open (md);
  if (rc == 0)
    {
      rc = maildir_subdir_open (md, SUB_TMP, NULL, &fd);
      if (rc == 0)
	{
	  name = maildir_uniq_create (amd, -1);
	  rc = EAGAIN;
	  for (i = NTRIES; i > 0; i--)
	    {
	      if (fstatat (fd, name, &st, 0) == 0)
		{
		  mu_diag_output (MU_DIAG_WARNING,
				  "%s/%s/%s exists during delivery",
				  md->amd.name, subdir_name[SUB_TMP], name);
		  if (i > 1)
		    sleep (2);
		}
	      else if (errno == ENOENT)
		{
		  msg->subdir = SUB_TMP;
		  msg->uid = alloc_uid (md);
		  msg->file_name = name;
		  msg->uniq_len = strlen (name);
		  name = NULL;
		  rc = 0;
		  break;
		}
	      else
		{
		  mu_diag_output (MU_DIAG_WARNING, "cannot stat %s/%s/%s: %s",
				  md->amd.name, subdir_name[SUB_TMP], name,
				  mu_strerror (errno));
		  break;
		}
	    }
	  close (fd);
	}
      maildir_close (md);
    }
  free (name);
  return rc;
}

int
_mailbox_maildir_init (mu_mailbox_t mailbox)
{
  int rc;
  struct _amd_data *amd;
  struct _maildir_data *md;

  rc = amd_init_mailbox (mailbox, sizeof (struct _maildir_data), &amd);
  if (rc)
    return rc;

  amd->msg_size = sizeof (struct _maildir_message);
  amd->msg_free = maildir_message_free;
  amd->create = maildir_create;
  amd->msg_init_delivery = maildir_msg_init;
  amd->msg_finish_delivery = maildir_msg_finish_delivery;
  amd->cur_msg_file_name = maildir_cur_message_name;
  amd->new_msg_file_name = maildir_new_message_name;
  amd->scan0 = maildir_scan0;
  amd->qfetch = maildir_qfetch;
  amd->msg_cmp = maildir_message_cmp;
  amd->message_uid = maildir_message_uid;
  amd->remove = maildir_remove;
  amd->chattr_msg = maildir_chattr_msg;
  amd->capabilities = MU_AMD_STATUS;
  amd->mailbox_size = maildir_size;
  
  /* Set our properties.  */
  {
    mu_property_t property = NULL;
    mu_mailbox_get_property (mailbox, &property);
    mu_property_set_value (property, "TYPE", "MAILDIR", 1);
  }

  md = (struct _maildir_data *) amd;
  md->folder_fd = -1;
  
  return 0;
}