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

/* Mailutils Abstract Mail Directory Layer 
   First draft by Sergey Poznyakoff.
   Thanks Tang Yong Ping <yongping.tang@radixs.com> for initial
   patch (although not used here).

   This module provides basic support for "MH" and "Maildir" formats. */

#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 <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <dirent.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/cctype.h>
#include <mailutils/cstr.h>
#include <mailutils/attribute.h>
#include <mailutils/body.h>
#include <mailutils/debug.h>
#include <mailutils/envelope.h>
#include <mailutils/error.h>
#include <mailutils/errno.h>
#include <mailutils/header.h>
#include <mailutils/locker.h>
#include <mailutils/message.h>
#include <mailutils/util.h>
#include <mailutils/datetime.h>
#include <mailutils/property.h>
#include <mailutils/stream.h>
#include <mailutils/url.h>
#include <mailutils/observer.h>
#include <mailutils/sys/stream.h>
#include <mailutils/sys/mailbox.h>
#include <mailutils/sys/registrar.h>
#include <mailutils/sys/url.h>
#include <mailutils/sys/amd.h>

static void amd_destroy (mu_mailbox_t mailbox);
static int amd_open (mu_mailbox_t, int);
static int amd_close (mu_mailbox_t);
static int amd_get_message (mu_mailbox_t, size_t, mu_message_t *);
static int amd_quick_get_message (mu_mailbox_t mailbox, mu_message_qid_t qid,
				  mu_message_t *pmsg);
static int amd_append_message (mu_mailbox_t, mu_message_t);
static int amd_messages_count (mu_mailbox_t, size_t *);
static int amd_messages_recent (mu_mailbox_t, size_t *);
static int amd_message_unseen (mu_mailbox_t, size_t *);
static int amd_expunge (mu_mailbox_t);
static int amd_sync (mu_mailbox_t);
static int amd_uidnext (mu_mailbox_t mailbox, size_t *puidnext);
static int amd_uidvalidity (mu_mailbox_t, unsigned long *);
static int amd_scan (mu_mailbox_t, size_t, size_t *);
static int amd_is_updated (mu_mailbox_t);
static int amd_get_size (mu_mailbox_t, mu_off_t *);

static int amd_body_size (mu_body_t body, size_t *psize);
static int amd_body_lines (mu_body_t body, size_t *plines);

static int amd_header_fill (void *data, char **pbuf, size_t *plen);

static int amd_get_attr_flags (mu_attribute_t attr, int *pflags);
static int amd_set_attr_flags (mu_attribute_t attr, int flags);
static int amd_unset_attr_flags (mu_attribute_t attr, int flags);

static int amd_pool_open (struct _amd_message *mhm);
static int amd_pool_open_count (struct _amd_data *amd);
static void amd_pool_flush (struct _amd_data *amd);
static struct _amd_message **amd_pool_lookup (struct _amd_message *mhm);

static int amd_envelope_date (mu_envelope_t envelope, char *buf, size_t len,
			      size_t *psize);
static int amd_envelope_sender (mu_envelope_t envelope, char *buf, size_t len,
			        size_t *psize);
static int amd_remove_mbox (mu_mailbox_t mailbox);


static int amd_body_stream_read (mu_stream_t str, char *buffer,
				 size_t buflen,
				 size_t *pnread);
static int amd_body_stream_readdelim (mu_stream_t is,
				      char *buffer, size_t buflen,
				      int delim,
				      size_t *pnread);
static int amd_body_stream_size (mu_stream_t str, mu_off_t *psize);
static int amd_body_stream_seek (mu_stream_t str, mu_off_t off, 
				 mu_off_t *presult);

struct _amd_body_stream
{
  struct _mu_stream stream;
  mu_body_t body;
  mu_off_t off;
};

/* AMD Properties */
int
_amd_prop_fetch_off (struct _amd_data *amd, const char *name, mu_off_t *pval)
{
  const char *p;
  mu_off_t n = 0;
  
  if (!amd->prop || mu_property_sget_value (amd->prop, name, &p))
    return MU_ERR_NOENT;
  if (!pval)
    return 0;
  for (; *p; p++)
    {
      if (!mu_isdigit (*p))
	return EINVAL;
      n = n * 10 + *p - '0';
    }
  *pval = n;
  return 0;
}

int
_amd_prop_fetch_size (struct _amd_data *amd, const char *name, size_t *pval)
{
  mu_off_t n;
  int rc = _amd_prop_fetch_off (amd, name, &n);
  if (rc == 0)
    {
      size_t s = n;
      if (s != n)
	return ERANGE;
      if (pval)
	*pval = s;
    }
  return rc;
}

int
_amd_prop_fetch_ulong (struct _amd_data *amd, const char *name,
		       unsigned long *pval)
{
  mu_off_t n;
  int rc = _amd_prop_fetch_off (amd, name, &n);
  if (rc == 0)
    {
      unsigned long s = n;
      if (s != n)
	return ERANGE;
      if (pval)
	*pval = s;
    }
  return rc;
}

int
_amd_prop_store_off (struct _amd_data *amd, const char *name, mu_off_t val)
{
  char nbuf[128];
  char *p;
  int sign = 0;
  
  p = nbuf + sizeof nbuf;
  *--p = 0;
  if (val < 0)
    {
      sign = 1;
      val = - val;
    }
  do
    {
      unsigned d = val % 10;
      if (p == nbuf)
	return ERANGE;
      *--p = d + '0';
      val /= 10;
    }
  while (val);
  if (sign)
    {
      if (p == nbuf)
	return ERANGE;
      *--p = '-';
    }
  return mu_property_set_value (amd->prop, name, p, 1);
}

/* Backward-compatible size file support */
static int
read_size_file (struct _amd_data *amd)
{
  FILE *fp;
  int rc;
  char *name = mu_make_file_name (amd->name, _MU_AMD_SIZE_FILE_NAME);
  if (!name)
    return 1;
  fp = fopen (name, "r");
  if (fp)
    {
      unsigned long size;
      if (fscanf (fp, "%lu", &size) == 1)
	{
	  rc = _amd_prop_store_off (amd, _MU_AMD_PROP_SIZE, size);
	}
      else
	rc = 1;
      fclose (fp);
      unlink (name);
    }
  else
    rc = 1;
  free (name);
  return rc;
}

static int
_amd_prop_create (struct _amd_data *amd)
{
  int rc;
  struct mu_mh_prop *mhprop;
  mhprop = calloc (1, sizeof (mhprop[0]));
  if (!mhprop)
    return ENOMEM;
  mhprop->filename = mu_make_file_name (amd->name, _MU_AMD_PROP_FILE_NAME);
  if (!mhprop->filename)
    {
      free (mhprop);
      return errno;
    }
  rc = mu_property_create_init (&amd->prop, mu_mh_property_init, mhprop);
  if (rc)
    {
      mu_debug (MU_DEBCAT_MAILBOX, MU_DEBUG_ERROR,
		("mu_property_create_init: %s",
		 mu_strerror (rc)));
      free (mhprop->filename);
      free (mhprop);
    }
  else
    read_size_file (amd);
  return rc;
}

/* Operations on message array */

/* Perform binary search for message MSG on a segment of message array
   of AMD between the indexes FIRST and LAST inclusively.
   If found, return 0 and store index of the located entry in the
   variable PRET. Otherwise, return 1 and place into PRET index of
   the nearest array element that is less than MSG (in the sense of
   amd->msg_cmp)
   Indexes are zero-based. */
   
static int
amd_msg_bsearch (struct _amd_data *amd, mu_off_t first, mu_off_t last,
		 struct _amd_message *msg,
		 mu_off_t *pret)
{
  mu_off_t mid;
  int rc;

  if (last < first)
    return 1;
  
  mid = (first + last) / 2;
  rc = amd->msg_cmp (amd->msg_array[mid], msg);
  if (rc > 0)
    return amd_msg_bsearch (amd, first, mid-1, msg, pret);
  *pret = mid;
  if (rc < 0)
    return amd_msg_bsearch (amd, mid+1, last, msg, pret);
  /* else */
  return 0;
}

/* Search for message MSG in the message array of AMD.
   If found, return 0 and store index of the located entry in the
   variable PRET. Otherwise, return 1 and store in PRET the index of
   the array element that is less than MSG (in the sense of
   amd->msg_cmp)
   Index returned in PRET is 1-based, so *PRET == 0 means that MSG
   is less than the very first element of the message array.

   In other words, when amd_msg_lookup() returns 1, the value in *PRET
   can be regarded as a 0-based index of the array slot where MSG can
   be inserted */

int
amd_msg_lookup (struct _amd_data *amd, struct _amd_message *msg,
		 size_t *pret)
{
  int rc;
  mu_off_t i;
  
  if (amd->msg_count == 0)
    {
      *pret = 0;
      return 1;
    }
  
  rc = amd->msg_cmp (msg, amd->msg_array[0]);
  if (rc < 0)
    {
      *pret = 0;
      return 1;
    }
  else if (rc == 0)
    {
      *pret = 1;
      return 0;
    }
  
  rc = amd->msg_cmp (msg, amd->msg_array[amd->msg_count - 1]);
  if (rc > 0)
    {
      *pret = amd->msg_count;
      return 1;
    }
  else if (rc == 0)
    {
      *pret = amd->msg_count;
      return 0;
    }
  
  rc = amd_msg_bsearch (amd, 0, amd->msg_count - 1, msg, &i);
  *pret = i + 1;
  return rc;
}

#define AMD_MSG_INC 64

/* Prepare the message array for insertion of a new message
   at position INDEX (zero based), by moving its contents
   one slot to the right. If necessary, expand the array by
   AMD_MSG_INC */
int
amd_array_expand (struct _amd_data *amd, size_t index)
{
  if (amd->msg_count == amd->msg_max)
    {
      struct _amd_message **p;
      
      amd->msg_max += AMD_MSG_INC; /* FIXME: configurable? */
      p = realloc (amd->msg_array, amd->msg_max * sizeof (amd->msg_array[0]));
      if (!p)
	{
	  amd->msg_max -= AMD_MSG_INC;
	  return ENOMEM;
	}
      amd->msg_array = p;
    }
  if (amd->msg_count > index)
    memmove (&amd->msg_array[index+1], &amd->msg_array[index],
	     (amd->msg_count-index) * sizeof (amd->msg_array[0]));
  amd->msg_count++;
  return 0;
}

/* Shrink the message array by removing the element at INDEX-COUNT and
   shifting left by COUNT positions all the elements to the right of
   it. */
int
amd_array_shrink (struct _amd_data *amd, size_t index, size_t count)
{
  if (amd->msg_count-index-1 && index < amd->msg_count)
    memmove (&amd->msg_array[index-count+1], &amd->msg_array[index + 1],
	     (amd->msg_count-index-1) * sizeof (amd->msg_array[0]));
  amd->msg_count -= count;
  return 0;
}


int
amd_init_mailbox (mu_mailbox_t mailbox, size_t amd_size,
		  struct _amd_data **pamd) 
{
  int status;
  struct _amd_data *amd;

  if (mailbox == NULL)
    return EINVAL;
  if (amd_size < sizeof (*amd))
    return EINVAL;

  amd = mailbox->data = calloc (1, amd_size);
  if (amd == NULL)
    return ENOMEM;

  /* Back pointer.  */
  amd->mailbox = mailbox;

  status = mu_url_aget_path (mailbox->url, &amd->name);
  if (status)
    {
      free (amd);
      mailbox->data = NULL;
      return status;
    }

  /* Overloading the defaults.  */
  mailbox->_destroy = amd_destroy;

  mailbox->_open = amd_open;
  mailbox->_close = amd_close;

  /* Overloading of the entire mailbox object methods.  */
  mailbox->_get_message = amd_get_message;
  mailbox->_quick_get_message = amd_quick_get_message;
  mailbox->_append_message = amd_append_message;
  mailbox->_messages_count = amd_messages_count;
  mailbox->_messages_recent = amd_messages_recent;
  mailbox->_message_unseen = amd_message_unseen;
  mailbox->_expunge = amd_expunge;
  mailbox->_sync = amd_sync;
  mailbox->_uidvalidity = amd_uidvalidity;
  mailbox->_uidnext = amd_uidnext;

  mailbox->_scan = amd_scan;
  mailbox->_is_updated = amd_is_updated;

  mailbox->_get_size = amd_get_size;
  mailbox->_remove = amd_remove_mbox;
  
  mu_debug (MU_DEBCAT_MAILBOX, MU_DEBUG_TRACE1, ("amd_init(%s)", amd->name));
  *pamd = amd;
  return 0;
}

static void
amd_destroy (mu_mailbox_t mailbox)
{
  struct _amd_data *amd = mailbox->data;
  size_t i;
  
  if (!amd)
    return;

  amd_pool_flush (amd);
  mu_monitor_wrlock (mailbox->monitor);
  for (i = 0; i < amd->msg_count; i++)
    {
      mu_message_destroy (&amd->msg_array[i]->message, amd->msg_array[i]);
      free (amd->msg_array[i]);
    }
  free (amd->msg_array);

  mu_property_destroy (&amd->prop);
  
  if (amd->name)
    free (amd->name);

  free (amd);
  mailbox->data = NULL;
  mu_monitor_unlock (mailbox->monitor);
}

static int
amd_open (mu_mailbox_t mailbox, int flags)
{
  struct _amd_data *amd = mailbox->data;
  struct stat st;

  mailbox->flags = flags;
  if (stat (amd->name, &st) < 0)
    {
      if ((flags & MU_STREAM_CREAT) && errno == ENOENT)
	{
	  int rc;
	  int perms = mu_stream_flags_to_mode (flags, 1);
	  if (mkdir (amd->name, S_IRUSR|S_IWUSR|S_IXUSR|perms))
	    return errno;
	  if (stat (amd->name, &st) < 0)
	    return errno;
	  if (amd->create && (rc = amd->create (amd, flags)))
	    return rc;
	}
      else
	return errno;
    }
    
  if (!S_ISDIR (st.st_mode))
    return EINVAL;

  if (access (amd->name,
	      (flags & (MU_STREAM_WRITE|MU_STREAM_APPEND)) ?
	       W_OK : R_OK | X_OK))
    return errno;

  /* Create/read properties.  It is not an error if this fails. */
  _amd_prop_create (amd);
  
  if (mailbox->locker == NULL)
    mu_locker_create (&mailbox->locker, "/dev/null", 0);
  
  return 0;
}

static int
amd_close (mu_mailbox_t mailbox)
{
  struct _amd_data *amd;
  int i;
    
  if (!mailbox)
    return EINVAL;

  amd = mailbox->data;
  
  /* Destroy all cached data */
  amd_pool_flush (amd);
  mu_monitor_wrlock (mailbox->monitor);
  for (i = 0; i < amd->msg_count; i++)
    {
      mu_message_destroy (&amd->msg_array[i]->message, amd->msg_array[i]);
      free (amd->msg_array[i]);
    }
  free (amd->msg_array);
  amd->msg_array = NULL;

  amd->msg_count = 0; /* number of messages in the list */
  amd->msg_max = 0;   /* maximum message buffer capacity */

  mu_monitor_unlock (mailbox->monitor);
  
  return 0;
}

static int
amd_message_qid (mu_message_t msg, mu_message_qid_t *pqid)
{
  struct _amd_message *mhm = mu_message_get_owner (msg);
  
  return mhm->amd->cur_msg_file_name (mhm, pqid);
}

struct _amd_message *
_amd_get_message (struct _amd_data *amd, size_t msgno)
{
  msgno--;
  if (msgno >= amd->msg_count)
    return NULL;
  return amd->msg_array[msgno];
}

static int
_amd_attach_message (mu_mailbox_t mailbox, struct _amd_message *mhm,
		     mu_message_t *pmsg)
{
  int status;
  mu_message_t msg;

  /* Check if we already have it.  */
  if (mhm->message)
    {
      if (pmsg)
	*pmsg = mhm->message;
      return 0;
    }

  /* Get an empty message struct.  */
  status = mu_message_create (&msg, mhm);
  if (status != 0)
    return status;

  /* Set the header.  */
  {
    mu_header_t header = NULL;
    status = mu_header_create (&header, NULL, 0);
    if (status != 0)
      {
	mu_message_destroy (&msg, mhm);
	return status;
      }
    mu_header_set_fill (header, amd_header_fill, msg);
    /*FIXME:
    mu_header_set_get_fvalue (header, amd_header_get_fvalue, msg);
    */
    mu_message_set_header (msg, header, mhm);
  }

  /* Set the attribute.  */
  {
    mu_attribute_t attribute;
    status = mu_attribute_create (&attribute, msg);
    if (status != 0)
      {
	mu_message_destroy (&msg, mhm);
	return status;
      }
    mu_attribute_set_get_flags (attribute, amd_get_attr_flags, msg);
    mu_attribute_set_set_flags (attribute, amd_set_attr_flags, msg);
    mu_attribute_set_unset_flags (attribute, amd_unset_attr_flags, msg);
    mu_message_set_attribute (msg, attribute, mhm);
  }

  /* Prepare the body.  */
  {
    mu_body_t body = NULL;
    struct _amd_body_stream *str;
    
    if ((status = mu_body_create (&body, msg)) != 0)
      return status;

    str = (struct _amd_body_stream *)
              _mu_stream_create (sizeof (*str),
				 mailbox->flags | MU_STREAM_SEEK | 
				 _MU_STR_OPEN);
    if (!str)
      {
	mu_body_destroy (&body, msg);
	mu_message_destroy (&msg, mhm);
	return ENOMEM;
      }
    str->stream.read = amd_body_stream_read;
    str->stream.readdelim = amd_body_stream_readdelim;
    str->stream.size = amd_body_stream_size;
    str->stream.seek = amd_body_stream_seek;
    mu_body_set_stream (body, (mu_stream_t) str, msg);
    mu_body_clear_modified (body);
    mu_body_set_size (body, amd_body_size, msg);
    mu_body_set_lines (body, amd_body_lines, msg);
    mu_message_set_body (msg, body, mhm);
    str->body = body;
  }

  /* Set the envelope.  */
  {
    mu_envelope_t envelope = NULL;
    status = mu_envelope_create (&envelope, msg);
    if (status != 0)
      {
	mu_message_destroy (&msg, mhm);
	return status;
      }
    mu_envelope_set_sender (envelope, amd_envelope_sender, msg);
    mu_envelope_set_date (envelope, amd_envelope_date, msg);
    mu_message_set_envelope (msg, envelope, mhm);
  }

  /* Set the UID.  */
  if (mhm->amd->message_uid)
    mu_message_set_uid (msg, mhm->amd->message_uid, mhm);
  mu_message_set_qid (msg, amd_message_qid, mhm);
  
  /* Attach the message to the mailbox mbox data.  */
  mhm->message = msg;
  mu_message_set_mailbox (msg, mailbox, mhm);

  /* Some of mu_message_set_ functions above mark message as modified.
     Undo it now.

     FIXME: Marking message as modified is not always appropriate. Find
     a better way. */
     
  mu_message_clear_modified (msg);

  if (pmsg)
    *pmsg = msg;

  return 0;
}

static int
_amd_scan0 (struct _amd_data *amd, size_t msgno, size_t *pcount,
	    int do_notify)
{
  unsigned long uidval;
  int status = amd->scan0 (amd->mailbox, msgno, pcount, do_notify);
  if (status != 0)
    return status;
  /* Reset the uidvalidity.  */
  if (amd->msg_count == 0 ||
      _amd_prop_fetch_ulong (amd, _MU_AMD_PROP_UIDVALIDITY, &uidval) ||
      !uidval)
    {
      uidval = (unsigned long)time (NULL);
      _amd_prop_store_off (amd, _MU_AMD_PROP_UIDVALIDITY, uidval);
    }
  return 0;
}

static int
amd_get_message (mu_mailbox_t mailbox, size_t msgno, mu_message_t *pmsg)
{
  int status;
  struct _amd_data *amd = mailbox->data;
  struct _amd_message *mhm;

  /* Sanity checks.  */
  if (pmsg == NULL)
    return MU_ERR_OUT_PTR_NULL;
  if (amd == NULL || msgno < 1)
    return EINVAL;

  /* If we did not start a scanning yet do it now.  */
  if (amd->msg_count == 0)
    {
      status = _amd_scan0 (amd, 1, NULL, 0);
      if (status != 0)
	return status;
    }

  if ((mhm = _amd_get_message (amd, msgno)) == NULL)
    return MU_ERR_NOENT;
  return _amd_attach_message (mailbox, mhm, pmsg);
}

static int
amd_quick_get_message (mu_mailbox_t mailbox, mu_message_qid_t qid,
		       mu_message_t *pmsg)
{
  int status;
  struct _amd_data *amd = mailbox->data;
  if (amd->msg_count)
    {
      mu_message_qid_t vqid;
      mu_message_t msg = amd->msg_array[0]->message;
      status = mu_message_get_qid (msg, &vqid);
      if (status)
	return status;
      status = strcmp (qid, vqid);
      free (vqid);
      if (status)
	return MU_ERR_EXISTS;
      *pmsg = msg;
    }
  else if (amd->qfetch)
    {
      status = amd->qfetch (amd, qid);
      if (status)
	return status;
      return _amd_attach_message (mailbox, amd->msg_array[0], pmsg);
    }
  
  return ENOSYS;
}

static int
_amd_tempfile (struct _amd_data *amd, FILE **pfile, char **namep)
{
  struct mu_tempfile_hints hints;
  int fd, rc;

  hints.tmpdir = amd->name;
  rc = mu_tempfile (&hints, MU_TEMPFILE_TMPDIR, &fd, namep);
  if (rc == 0)
    if ((*pfile = fdopen (fd, "w")) == NULL)
      rc = errno;
  return rc;
}

static int
_amd_delim (char *str)
{
  if (str[0] == '-')
    {
      for (; *str == '-'; str++)
	;
      for (; *str == ' ' || *str == '\t'; str++)
	;
    }
  return str[0] == '\n';
}

static int
_amd_message_save (struct _amd_data *amd, struct _amd_message *mhm,
		   int expunge)
{
  mu_stream_t stream = NULL;
  char *name = NULL, *buf = NULL, *msg_name, *old_name;
  size_t n;
  size_t bsize;
  size_t nlines, nbytes;
  size_t new_body_start, new_header_lines;
  FILE *fp;
  mu_message_t msg = mhm->message;
  mu_header_t hdr;
  int status;
  mu_attribute_t attr;
  mu_body_t body;
  const char *sbuf;
  mu_envelope_t env = NULL;

  status = mu_message_size (msg, &bsize);
  if (status)
    return status;

  status = amd->new_msg_file_name (mhm, mhm->attr_flags, expunge, &msg_name);
  if (status)
    return status;
  if (!msg_name)
    {
      /* Unlink the original file */
      char *old_name;
      status = amd->cur_msg_file_name (mhm, &old_name);
      free (msg_name);
      if (status == 0 && unlink (old_name))
	status = errno;
      free (old_name);
      return status;
    }      
    
  status = _amd_tempfile (mhm->amd, &fp, &name);
  if (status)
    {
      free (msg_name);
      return status;
    }

  /* Try to allocate large buffer */
  for (; bsize > 1; bsize /= 2)
    if ((buf = malloc (bsize)))
      break;

  if (!bsize)
    {
      unlink (name);
      free (name);
      free (msg_name);
      return ENOMEM;
    }

  /* Copy flags */
  mu_message_get_header (msg, &hdr);
  mu_header_get_streamref (hdr, &stream);
  status = mu_stream_seek (stream, 0, MU_SEEK_SET, NULL);
  if (status)
    {
      /* FIXME: Provide a common exit point for all error
	 cases */
      unlink (name);
      free (name);
      free (msg_name);
      mu_stream_destroy (&stream);
      return status;
    }
      
  nlines = nbytes = 0;
  while ((status = mu_stream_readline (stream, buf, bsize, &n)) == 0
	 && n != 0)
    {
      if (_amd_delim (buf))
	break;

      if (!(mu_c_strncasecmp (buf, "status:", 7) == 0
	    || mu_c_strncasecmp (buf, "x-imapbase:", 11) == 0
	    || mu_c_strncasecmp (buf, "x-uid:", 6) == 0
	    || mu_c_strncasecmp (buf, 
                MU_HEADER_ENV_DATE ":", sizeof (MU_HEADER_ENV_DATE)) == 0
	    || mu_c_strncasecmp (buf, 
                MU_HEADER_ENV_SENDER ":", sizeof (MU_HEADER_ENV_SENDER)) == 0))
	{
	  nlines++;
	  nbytes += fprintf (fp, "%s", buf);
	}
    }
  mu_stream_destroy (&stream);
  
  mu_message_get_envelope (msg, &env);
  if (mu_envelope_sget_date (env, &sbuf) == 0)
    {
      /* NOTE: buffer might be terminated with \n */
      while (*sbuf && mu_isspace (*sbuf))
	sbuf++;
      nbytes += fprintf (fp, "%s: %s", MU_HEADER_ENV_DATE, sbuf);

      if (*sbuf && sbuf[strlen (sbuf) - 1] != '\n')
	nbytes += fprintf (fp, "\n");
      
      nlines++;
    }
	  
  if (mu_envelope_sget_sender (env, &sbuf) == 0)
    {
      fprintf (fp, "%s: %s\n", MU_HEADER_ENV_SENDER, sbuf);
      nlines++;
    }

  if (!(amd->capabilities & MU_AMD_STATUS))
    {
      /* Add status */
      char statbuf[MU_STATUS_BUF_SIZE];
      
      mu_message_get_attribute (msg, &attr);
      mu_attribute_to_string (attr, statbuf, sizeof (statbuf), &n);
      if (n)
	{
	  nbytes += fprintf (fp, "Status: %s\n", statbuf);
	  nlines++;
	}
    }

  nbytes += fprintf (fp, "\n");
  nlines++;
  
  new_header_lines = nlines;
  new_body_start = nbytes;

  /* Copy message body */

  mu_message_get_body (msg, &body);
  mu_body_get_streamref (body, &stream);
  status = mu_stream_seek (stream, 0, MU_SEEK_SET, NULL);
  if (status)
    {
      unlink (name);
      free (name);
      free (msg_name);
      mu_stream_destroy (&stream);
      return status;
    }
    
  nlines = 0;
  while (mu_stream_read (stream, buf, bsize, &n) == 0 && n != 0)
    {
      char *p;
      for (p = buf; p < buf + n; p++)
	if (*p == '\n')
	  nlines++;
      fwrite (buf, 1, n, fp);
      nbytes += n;
    }
  mu_stream_destroy (&stream);
  
  mhm->header_lines = new_header_lines;
  mhm->body_start = new_body_start;
  mhm->body_lines = nlines;
  mhm->body_end = nbytes;

  free (buf);
  fclose (fp);

  status = amd->cur_msg_file_name (mhm, &old_name);
  if (status == 0)
    {
      if (rename (name, msg_name))
	{
	  if (errno == ENOENT)
	    mu_observable_notify (amd->mailbox->observable,
				  MU_EVT_MAILBOX_CORRUPT,
				  amd->mailbox);
	  else
	    {
	      status = errno;
	      mu_debug (MU_DEBCAT_MAILBOX, MU_DEBUG_ERROR,
			("renaming %s to %s failed: %s",
			 name, msg_name, mu_strerror (status)));
	    }
	}
      else
	{
	  mode_t perms;
	  
	  perms = mu_stream_flags_to_mode (amd->mailbox->flags, 0);
	  if (perms != 0)
	    {
	      /* It is documented that the mailbox permissions are
		 affected by the current umask, so take it into account
		 here.
		 FIXME: I'm still not sure we should honor umask, though.
		 --gray
	      */
	      mode_t mask = umask (0);
	      chmod (msg_name, (0600 | perms) & ~mask);
	      umask (mask);
	    }
	  if (strcmp (old_name, msg_name))
	    /* Unlink original message */
	    unlink (old_name);
	}
      free (old_name);
      
      mhm->orig_flags = mhm->attr_flags;
    }
  free (msg_name);
  free (name);

  return status;
}

static int
amd_append_message (mu_mailbox_t mailbox, mu_message_t msg)
{
  int status;
  struct _amd_data *amd = mailbox->data;
  struct _amd_message *mhm;

  if (!mailbox || !msg)
    return EINVAL;

  mhm = calloc (1, amd->msg_size);
  if (!mhm)
    return ENOMEM;
    
  /* If we did not start a scanning yet do it now.  */
  if (amd->msg_count == 0)
    {
      status = _amd_scan0 (amd, 1, NULL, 0);
      if (status != 0)
	{
	  free (mhm);
	  return status;
	}
    }

  amd->has_new_msg = 1;
  
  mhm->amd = amd;
  if (amd->msg_init_delivery)
    {
      status = amd->msg_init_delivery (amd, mhm);
      if (status)
	{
	  free (mhm);
	  return status;
	}
    }
  
  mhm->message = msg;
  status = _amd_message_save (amd, mhm, 0);
  if (status)
    {
      free (mhm);
      return status;
    }

  mhm->message = NULL;
  /* Insert and re-scan the message */
  status = _amd_message_insert (amd, mhm);
  if (status)
    {
      free (mhm);
      return status;
    }

  if (amd->msg_finish_delivery)
    status = amd->msg_finish_delivery (amd, mhm, msg);
  
  if (status == 0 && mailbox->observable)
    {
      char *qid;
      if (amd->cur_msg_file_name (mhm, &qid) == 0)
	{
	  mu_observable_notify (mailbox->observable, 
	                        MU_EVT_MAILBOX_MESSAGE_APPEND,
				qid);
	  free (qid);
	}
    }
  
  return status;
}

static int
amd_messages_count (mu_mailbox_t mailbox, size_t *pcount)
{
  struct _amd_data *amd = mailbox->data;

  if (amd == NULL)
    return EINVAL;

  if (!amd_is_updated (mailbox))
    return _amd_scan0 (amd,  amd->msg_count, pcount, 0);

  if (pcount)
    *pcount = amd->msg_count;

  return 0;
}

/* A "recent" message is the one not marked with MU_ATTRIBUTE_SEEN
   ('O' in the Status header), i.e. a message that is first seen
   by the current session (see attributes.h) */
static int
amd_messages_recent (mu_mailbox_t mailbox, size_t *pcount)
{
  struct _amd_data *amd = mailbox->data;
  size_t count, i;

  /* If we did not start a scanning yet do it now.  */
  if (amd->msg_count == 0)
    {
      int status = _amd_scan0 (amd, 1, NULL, 0);
      if (status != 0)
	return status;
    }
  count = 0;
  for (i = 0; i < amd->msg_count; i++)
    {
      if (MU_ATTRIBUTE_IS_UNSEEN(amd->msg_array[i]->attr_flags))
	count++;
    }
  *pcount = count;
  return 0;
}

/* An "unseen" message is the one that has not been read yet */
static int
amd_message_unseen (mu_mailbox_t mailbox, size_t *pmsgno)
{
  struct _amd_data *amd = mailbox->data;
  size_t i;

  /* If we did not start a scanning yet do it now.  */
  if (amd->msg_count == 0)
    {
      int status = _amd_scan0 (amd, 1, NULL, 0);
      if (status != 0)
	return status;
    }

  for (i = 0; i < amd->msg_count; i++)
    {
      if (MU_ATTRIBUTE_IS_UNREAD(amd->msg_array[0]->attr_flags))
	{
	  *pmsgno = i + 1;
	  break;
	}
    }
  return 0;
}

static int
_compute_mailbox_size_recursive (struct _amd_data *amd, const char *name,
				 mu_off_t *psize)
{
  DIR *dir;
  struct dirent *entry;
  char *buf;
  size_t bufsize;
  size_t dirlen;
  size_t flen;
  int status = 0;
  struct stat sb;

  dir = opendir (name);
  if (!dir)
    return errno;

  dirlen = strlen (name);
  bufsize = dirlen + 32;
  buf = malloc (bufsize);
  if (!buf)
    {
      closedir (dir);
      return ENOMEM;
    }
  
  strcpy (buf, name);
  if (buf[dirlen-1] != '/')
    buf[++dirlen - 1] = '/';
	  
  while ((entry = readdir (dir)))
    {
      switch (entry->d_name[0])
	{
	case '.':
	  break;

	default:
	  flen = strlen (entry->d_name);
	  if (dirlen + flen + 1 > bufsize)
	    {
	      bufsize = dirlen + flen + 1;
	      buf = realloc (buf, bufsize);
	      if (!buf)
		{
		  status = ENOMEM;
		  break;
		}
	    }
	  strcpy (buf + dirlen, entry->d_name);
	  if (stat (buf, &sb) == 0)
	    {
	      if (S_ISREG (sb.st_mode))
		*psize += sb.st_size;
	      else if (S_ISDIR (sb.st_mode))
		_compute_mailbox_size_recursive (amd, buf, psize);
	    }
	  /* FIXME: else? */
	  break;
	}
    }

  free (buf);
  
  closedir (dir);
  return 0;
}

static int
compute_mailbox_size (struct _amd_data *amd, mu_off_t *psize)
{
  mu_off_t size = 0;
  int rc = _compute_mailbox_size_recursive (amd, amd->name, &size);
  if (rc == 0)
    {
      rc = _amd_prop_store_off (amd, _MU_AMD_PROP_SIZE, size);
      if (rc == 0 && psize)
	*psize = size;
    }
  return rc;
}

static int
amd_remove_mbox (mu_mailbox_t mailbox)
{
  int rc;
  struct _amd_data *amd = mailbox->data;
  
  if (!amd->remove)
    return ENOSYS;
  rc = amd->remove (amd);
  if (rc == 0)
    {
      char *name;

      name = mu_make_file_name (amd->name, _MU_AMD_SIZE_FILE_NAME);
      if (!name)
	return ENOMEM;
      if (unlink (name) && errno != ENOENT)
	rc = errno;
      else
	{
	  free (name);
	  name = mu_make_file_name (amd->name, _MU_AMD_PROP_FILE_NAME);
	  if (!name)
	    return ENOMEM;
	  if (unlink (name) && errno != ENOENT)
	    rc = errno;
	}
      free (name);
    }

  if (rc == 0)
    {
      if (rmdir (amd->name) && errno != ENOENT)
	{
	  rc = errno;
	  /* POSIX.1-2001 allows EEXIST to be returned if the directory
	     contained entries other than . and .. */
	  if (rc == EEXIST)
	    rc = ENOTEMPTY;
	}
    }
  
  return rc;
}

static int
_amd_update_message (struct _amd_data *amd, struct _amd_message *mhm,
		     int expunge, int *upd)
{
  int flg, rc;
      
  if (mhm->message)
    flg = mu_message_is_modified (mhm->message);
  else if (mhm->attr_flags & MU_ATTRIBUTE_MODIFIED)
    flg = MU_MSG_ATTRIBUTE_MODIFIED;

  if (!flg)
    return 0;

  if (flg == MU_MSG_ATTRIBUTE_MODIFIED && amd->chattr_msg)
    {
      rc = amd->chattr_msg (mhm, expunge);
      if (rc)
	{
	  mu_debug (MU_DEBCAT_MAILBOX, MU_DEBUG_ERROR,
		    ("_amd_update_message: chattr_msg failed: %s",
		     mu_strerror (rc)));
	  return rc;
	}
    }
  else
    {
      rc = _amd_attach_message (amd->mailbox, mhm, NULL);
      if (rc)
	{
	  mu_debug (MU_DEBCAT_MAILBOX, MU_DEBUG_ERROR,
		    ("_amd_update_message: _amd_attach_message failed: %s",
		     mu_strerror (rc)));
	  return rc;
	}
	  
      rc = _amd_message_save (amd, mhm, expunge);
      if (rc)
	{
	  mu_debug (MU_DEBCAT_MAILBOX, MU_DEBUG_ERROR,
		    ("_amd_update_message: _amd_message_save failed: %s",
		     mu_strerror (rc)));
	  return rc;
	}
    }
  *upd = 1;
  return rc;
}

static int
amd_expunge (mu_mailbox_t mailbox)
{
  struct _amd_data *amd = mailbox->data;
  struct _amd_message *mhm;
  size_t i;
  int updated = amd->has_new_msg;
  size_t expcount = 0;
  size_t last_expunged = 0;
  
  if (amd == NULL)
    return EINVAL;

  if (amd->msg_count == 0)
    return 0;

  for (i = 0; i < amd->msg_count; i++)
    {
      mhm = amd->msg_array[i];
      
      if (mhm->attr_flags & MU_ATTRIBUTE_DELETED)
	{
	  int rc;
	  struct _amd_message **pp;

	  if (amd->delete_msg)
	    {
	      rc = amd->delete_msg (amd, mhm);
	      if (rc)
		return rc;
	    }
	  else
	    {
	      char *old_name;
	      char *new_name;

	      rc = amd->cur_msg_file_name (mhm, &old_name);
	      if (rc)
		return rc;
	      rc = amd->new_msg_file_name (mhm, mhm->attr_flags, 1,
					   &new_name);
	      if (rc)
		{
		  free (old_name);
		  return rc;
		}

	      if (new_name)
		{
		  /* FIXME: It may be a good idea to have a capability flag
		     in struct _amd_data indicating that no actual removal
		     is needed (e.g. for traditional MH). It will allow to
		     bypass lots of no-op code here. */
		  if (strcmp (old_name, new_name) &&
		      /* Rename original message */
		      rename (old_name, new_name))
		    {
		      if (errno == ENOENT)
			mu_observable_notify (mailbox->observable,
					      MU_EVT_MAILBOX_CORRUPT,
					      mailbox);
		      else
			{
			  rc = errno;
			  mu_debug (MU_DEBCAT_MAILBOX, MU_DEBUG_ERROR,
				    ("renaming %s to %s failed: %s",
				     old_name, new_name, mu_strerror (rc)));
			}
		    }
		}
	      else
		/* Unlink original file */
		unlink (old_name);
	      
	      free (old_name);
	      free (new_name);
	    }

	  pp = amd_pool_lookup (mhm);
	  if (pp)
	    *pp = NULL;
	  mu_message_destroy (&mhm->message, mhm);
	  if (amd->msg_free)
	    amd->msg_free (mhm);
	  free (mhm);
	  amd->msg_array[i] = NULL;
	  last_expunged = i;
	  updated = 1;

	  {
	    size_t expevt[2] = { i + 1, expcount };
	    mu_observable_notify (mailbox->observable,
				  MU_EVT_MAILBOX_MESSAGE_EXPUNGE,
				  expevt);
	    ++expcount;
	  }
	}
      else
	{
	  _amd_update_message (amd, mhm, 1, &updated);/*FIXME: Error checking*/
	}
    }

  if (expcount)
    {
      last_expunged++;
      do
	{
	  size_t j;
	  
	  for (j = 1; j < last_expunged && !amd->msg_array[last_expunged-j-1];
	       j++)
	    ;
	  amd_array_shrink (amd, last_expunged - 1, j);
	  for (last_expunged -= j;
	       last_expunged > 0 && amd->msg_array[last_expunged - 1];
	       last_expunged--)
	    ;
	}
      while (last_expunged);
    }
  
  if (updated && !amd->mailbox_size)
    {
      compute_mailbox_size (amd, NULL);
    }
  return 0;
}

static int
amd_sync (mu_mailbox_t mailbox)
{
  struct _amd_data *amd = mailbox->data;
  struct _amd_message *mhm;
  size_t i;
  int updated = amd->has_new_msg;
  
  if (amd == NULL)
    return EINVAL;

  if (amd->msg_count == 0)
    return 0;

  /* Find the first dirty(modified) message.  */
  for (i = 0; i < amd->msg_count; i++)
    {
      mhm = amd->msg_array[i];
      if ((mhm->attr_flags & MU_ATTRIBUTE_MODIFIED)
	  || (mhm->message && mu_message_is_modified (mhm->message)))
	break;
    }

  for ( ; i < amd->msg_count; i++)
    {
      mhm = amd->msg_array[i];
      _amd_update_message (amd, mhm, 0, &updated); 
    }

  if (updated && !amd->mailbox_size)
    {
      compute_mailbox_size (amd, NULL);
    }

  return 0;
}

static int
amd_uidvalidity (mu_mailbox_t mailbox, unsigned long *puidvalidity)
{
  struct _amd_data *amd = mailbox->data;
  int status = amd_messages_count (mailbox, NULL);
  if (status != 0)
    return status;
  /* If we did not start scanning yet do it now.  */
  if (amd->msg_count == 0)
    {
      status = _amd_scan0 (amd, 1, NULL, 0);
      if (status != 0)
	return status;
    }

  return _amd_prop_fetch_ulong (amd, _MU_AMD_PROP_UIDVALIDITY, puidvalidity);
}

static int
amd_uidnext (mu_mailbox_t mailbox, size_t *puidnext)
{
  struct _amd_data *amd = mailbox->data;
  int status;
  
  if (!amd->next_uid)
    return ENOSYS;
  status = mu_mailbox_messages_count (mailbox, NULL);
  if (status != 0)
    return status;
  /* If we did not start a scanning yet do it now.  */
  if (amd->msg_count == 0)
    {
      status = _amd_scan0 (amd, 1, NULL, 0);
      if (status != 0)
	return status;
    }
   if (puidnext)
     *puidnext = amd->next_uid (amd);
  return 0;
}

/* FIXME: effectively the same as mbox_cleanup */
void
amd_cleanup (void *arg)
{
  mu_mailbox_t mailbox = arg;
  mu_monitor_unlock (mailbox->monitor);
}

int
_amd_message_lookup_or_insert (struct _amd_data *amd,
			       struct _amd_message *key,
			       size_t *pindex)
{
  int result = 0;
  size_t index;
  if (amd_msg_lookup (amd, key, &index))
    {
      /* Not found. Index points to the array cell where msg would
	 be placed */
      result = amd_array_expand (amd, index);
      if (result)
	return result;
      else
	result = MU_ERR_NOENT;
    }
  else
    result = 0;
  *pindex = index;
  return result;
}

/* Insert message msg into the message list on the appropriate position */
int
_amd_message_insert (struct _amd_data *amd, struct _amd_message *msg)
{
  size_t index;
  int rc = _amd_message_lookup_or_insert (amd, msg, &index);

  if (rc == MU_ERR_NOENT)
    {
      amd->msg_array[index] = msg;
      msg->amd = amd;
    }
  else if (rc == 0)
    {
      /*FIXME: Found? Shouldn't happen */
      return EEXIST;
    }
  else
    return rc;
  return 0;
}

/* Append message to the end of the array, expanding it if necessary */
int
_amd_message_append (struct _amd_data *amd, struct _amd_message *msg)
{
  size_t index = amd->msg_count;
  int rc = amd_array_expand (amd, index);
  if (rc)
    return rc;
  amd->msg_array[index] = msg;
  msg->amd = amd;
  return 0;
}

static int
msg_array_comp (const void *a, const void *b)
{
  struct _amd_message **ma = (struct _amd_message **) a;
  struct _amd_message **mb = (struct _amd_message **) b;
  struct _amd_data *amd = (*ma)->amd;
  return amd->msg_cmp (*ma, *mb);
}

void
amd_sort (struct _amd_data *amd)
{
  qsort (amd->msg_array, amd->msg_count, sizeof (amd->msg_array[0]),
	 msg_array_comp);
}

/* Scan given message and fill amd_message_t fields.
   NOTE: the function assumes mhm->stream != NULL. */
static int
amd_scan_message (struct _amd_message *mhm)
{
  mu_stream_t stream = mhm->stream;
  char buf[1024];
  size_t off;
  size_t n;
  int status;
  int in_header = 1;
  size_t hlines = 0;
  size_t blines = 0;
  size_t body_start = 0;
  struct stat st;
  char *msg_name;
  struct _amd_data *amd = mhm->amd;
  int amd_capa = amd->capabilities;
  
  /* Check if the message was modified after the last scan */
  status = mhm->amd->cur_msg_file_name (mhm, &msg_name);
  if (status)
    {
      mu_debug (MU_DEBCAT_MAILBOX, MU_DEBUG_ERROR,
		("amd_scan_message: cur_msg_file_name=%s",
		 mu_strerror (status)));      
      return status;
    }
  
  if (stat (msg_name, &st) == 0 && st.st_mtime == mhm->mtime)
    {
      /* Nothing to do */
      free (msg_name);
      return 0;
    }

  off = 0;
  status = mu_stream_seek (stream, 0, MU_SEEK_SET, NULL);
  if (status)
    mu_debug (MU_DEBCAT_MAILBOX, MU_DEBUG_ERROR,
	      ("amd_scan_message(%s): mu_stream_seek=%s",
	       msg_name, mu_strerror (status)));      
  else
    {
      while ((status = mu_stream_readline (stream, buf, sizeof (buf), &n)) == 0
	     && n != 0)
	{
	  if (in_header)
	    {
	      if (buf[0] == '\n')
		{
		  in_header = 0;
		  body_start = off + 1;
		}
	      if (buf[n - 1] == '\n')
		hlines++;
	      
	      /* Process particular attributes */
	      if (!(amd_capa & MU_AMD_STATUS) &&
		  mu_c_strncasecmp (buf, "status:", 7) == 0)
		{
		  int deleted = mhm->attr_flags & MU_ATTRIBUTE_DELETED;
		  mu_string_to_flags (buf, &mhm->attr_flags);
		  mhm->attr_flags |= deleted;
		}
	      else if (!(amd_capa & MU_AMD_IMAPBASE) &&
		       mu_c_strncasecmp (buf, "x-imapbase:", 11) == 0)
		{
		  if (_amd_prop_fetch_ulong (amd, _MU_AMD_PROP_UIDVALIDITY,
					     NULL))
		    {
		      char *p;
		      unsigned long uidval = strtoul (buf + 11, &p, 10);
		      /* The next number is next uid. Ignored */
		      _amd_prop_store_off (amd, _MU_AMD_PROP_UIDVALIDITY,
					   uidval);
		    }
		}
	    }
	  else
	    {
	      if (buf[n - 1] == '\n')
		blines++;
	    }
	  off += n;
	}
      if (status)
	mu_debug (MU_DEBCAT_MAILBOX, MU_DEBUG_ERROR,
		  ("amd_scan_message(%s): %s",
		   msg_name, mu_strerror (status)));     
    }

  free (msg_name);

  if (status == 0)
    {
      mhm->mtime = st.st_mtime;
      if (!body_start)
	body_start = off;
      mhm->header_lines = hlines;
      mhm->body_lines = blines;
      mhm->body_start = body_start;
      mhm->body_end = off;
    }
  return status;
}

static int
amd_scan (mu_mailbox_t mailbox, size_t msgno, size_t *pcount)
{
  struct _amd_data *amd = mailbox->data;

  if (! amd_is_updated (mailbox))
    return _amd_scan0 (amd, msgno, pcount, 1);

  if (pcount)
    *pcount = amd->msg_count;

  return 0;
}

/* Is the internal representation of the mailbox up to date.
   Return 1 if so, 0 otherwise. */
static int
amd_is_updated (mu_mailbox_t mailbox)
{
  struct stat st;
  struct _amd_data *amd = mailbox->data;

  if (stat (amd->name, &st) < 0)
    return 1;

  return amd->mtime == st.st_mtime;
}

static int
amd_get_size (mu_mailbox_t mailbox, mu_off_t *psize)
{
  struct _amd_data *amd = mailbox->data;
  if (amd->mailbox_size)
    return amd->mailbox_size (mailbox, psize);
  if (_amd_prop_fetch_off (amd, _MU_AMD_PROP_SIZE, psize))
    return compute_mailbox_size (amd, psize);
  return 0;
}

/* Return number of open streams residing in a message pool */
static int
amd_pool_open_count (struct _amd_data *amd)
{
  int cnt = amd->pool_last - amd->pool_first;
  if (cnt < 0)
    cnt += MAX_OPEN_STREAMS;
  return cnt;
}

/* Look up a _amd_message in the pool of open messages.
   If the message is found in the pool, returns the address of
   the pool slot occupied by it. Otherwise returns NULL. */
static struct _amd_message **
amd_pool_lookup (struct _amd_message *mhm)
{
  struct _amd_data *amd = mhm->amd;
  int i;

  for (i = amd->pool_first; i != amd->pool_last; )
    {
      if (amd->msg_pool[i] == mhm)
	return &amd->msg_pool[i];
      if (++i == MAX_OPEN_STREAMS)
	i = 0;
    }
  return NULL;
}

/* Open a stream associated with the message mhm. If the stream is
   already open, do nothing.
   NOTE: We could have reused the NULL holes in the msg_pool, but
   that hardly is worth the effort, since the holes appear only when
   expunging. On the other hand this may be useful when MAX_OPEN_STREAMS
   size is very big. "Premature optimization is the root of all evil" */
static int
amd_pool_open (struct _amd_message *mhm)
{
  int status;
  struct _amd_data *amd = mhm->amd;
  if (amd_pool_lookup (mhm))
    return 0;
  if (amd_pool_open_count (amd) == MAX_OPEN_STREAMS-1)
    {
      amd_message_stream_close (amd->msg_pool[amd->pool_first++]);
      amd->pool_first %= MAX_OPEN_STREAMS;
    }
  status = amd_message_stream_open (mhm);
  if (status)
    {
      mu_debug (MU_DEBCAT_MAILBOX, MU_DEBUG_ERROR,
		("amd_pool_open: amd_message_stream_open=%s",
		 mu_strerror (status)));
      return status;
    }
  amd->msg_pool[amd->pool_last++] = mhm;
  amd->pool_last %= MAX_OPEN_STREAMS;
  return 0;
}

static void
amd_pool_flush (struct _amd_data *amd)
{
  int i;
  
  for (i = amd->pool_first; i != amd->pool_last; )
    {
      if (amd->msg_pool[i])
	amd_message_stream_close (amd->msg_pool[i]);
      if (++i == MAX_OPEN_STREAMS)
	i = 0;
    }
  amd->pool_first = amd->pool_last = 0;
}

/* Attach a stream to a given message structure. The latter is supposed
   to be already added to the open message pool. */
int
amd_message_stream_open (struct _amd_message *mhm)
{
  struct _amd_data *amd = mhm->amd;
  char *filename;
  int status;
  int flags = 0;

  status = amd->cur_msg_file_name (mhm, &filename);
  if (status)
    {
      mu_debug (MU_DEBCAT_MAILBOX, MU_DEBUG_ERROR,
		("amd_message_stream_open: cur_msg_file_name=%s",
		 mu_strerror (status)));
      return status;
    }
  
  /* The message should be at least readable */
  if (amd->mailbox->flags & (MU_STREAM_WRITE|MU_STREAM_APPEND))
    flags |= MU_STREAM_RDWR;
  else 
    flags |= MU_STREAM_READ;
  status = mu_file_stream_create (&mhm->stream, filename, flags);
  if (status)
    mu_debug (MU_DEBCAT_MAILBOX, MU_DEBUG_ERROR,
	      ("amd_message_stream_open: mu_file_stream_create(%s)=%s",
	       filename, mu_strerror (status)));      

  free (filename);

  if (status != 0)
    return status;

  /* FIXME: Select buffer size dynamically */
  mu_stream_set_buffer (mhm->stream, mu_buffer_full, 16384);
  
  status = amd_scan_message (mhm);
  if (status)
    mu_debug (MU_DEBCAT_MAILBOX, MU_DEBUG_ERROR,
	      ("amd_message_stream_open: amd_scan_message=%s",
	       mu_strerror (status)));
  
  return status;
}

/* Close the stream associated with the given message. */
void
amd_message_stream_close (struct _amd_message *mhm)
{
  if (mhm)
    {
      mu_stream_close (mhm->stream);
      mhm->stream = NULL;
    }
}

int
amd_check_message (struct _amd_message *mhm)
{
  if (mhm->body_end == 0)
    return amd_pool_open (mhm);
  return 0;
}

/* Reading functions */
static int
amd_body_stream_read (mu_stream_t is, char *buffer, size_t buflen,
		      size_t *pnread)
{
  struct _amd_body_stream *amdstr = (struct _amd_body_stream *)is;
  mu_body_t body = amdstr->body;
  mu_message_t msg = mu_body_get_owner (body);
  struct _amd_message *mhm = mu_message_get_owner (msg);
  size_t nread = 0;
  int status = 0;
  mu_off_t ln;

  status = amd_pool_open (mhm);
  if (status)
    return status;

  if (buffer == NULL || buflen == 0)
    {
      *pnread = nread;
      return 0;
    }

  mu_monitor_rdlock (mhm->amd->mailbox->monitor);
#ifdef WITH_PTHREAD
  /* read() is cancellation point since we're doing a potentially
     long operation.  Lets make sure we clean the state.  */
  pthread_cleanup_push (amd_cleanup, (void *)mhm->amd->mailbox);
#endif

  ln = mhm->body_end - (mhm->body_start + amdstr->off);
  if (ln > 0)
    {
      nread = ((size_t)ln < buflen) ? (size_t)ln : buflen;
      status = mu_stream_seek (mhm->stream, mhm->body_start + amdstr->off,
			       MU_SEEK_SET, NULL);
      if (status == 0)
	{
	  status = mu_stream_read (mhm->stream, buffer, nread, &nread);
	  amdstr->off += nread;
	}
    }

  *pnread = nread;

  mu_monitor_unlock (mhm->amd->mailbox->monitor);
#ifdef WITH_PTHREAD
  pthread_cleanup_pop (0);
#endif

  return status;
}

static int
amd_body_stream_readdelim (mu_stream_t is, char *buffer, size_t buflen,
			   int delim,
			   size_t *pnread)
{
  struct _amd_body_stream *amdstr = (struct _amd_body_stream *)is;
  mu_body_t body = amdstr->body;
  mu_message_t msg = mu_body_get_owner (body);
  struct _amd_message *mhm = mu_message_get_owner (msg);
  int status = 0;

  status = amd_pool_open (mhm);
  if (status)
    return status;

  if (buffer == NULL || buflen == 0)
    {
      if (pnread)
	*pnread = 0;
      return 0;
    }

  mu_monitor_rdlock (mhm->amd->mailbox->monitor);
#ifdef WITH_PTHREAD
  /* read() is cancellation point since we're doing a potentially
     long operation.  Lets make sure we clean the state.  */
  pthread_cleanup_push (amd_cleanup, (void *)mhm->amd->mailbox);
#endif

  status = mu_stream_seek (mhm->stream, mhm->body_start + amdstr->off,
			   MU_SEEK_SET, NULL);
  if (status == 0)
    {
      size_t nread = 0;
      size_t ln;
	  
      ln = mhm->body_end - (mhm->body_start + amdstr->off) + 1;
      if (ln > 0)
	{
	  size_t rdsize = ((size_t)ln < buflen) ? (size_t)ln : buflen;
	  status = mu_stream_readdelim (mhm->stream, buffer, rdsize,
					delim, &nread);
	  amdstr->off += nread;
	}

      if (pnread)
	*pnread = nread;
    }

  mu_monitor_unlock (mhm->amd->mailbox->monitor);
#ifdef WITH_PTHREAD
  pthread_cleanup_pop (0);
#endif

  return status;
}

static int
amd_body_stream_seek (mu_stream_t str, mu_off_t off, mu_off_t *presult)
{
  size_t size;
  struct _amd_body_stream *amdstr = (struct _amd_body_stream *)str;
  
  amd_body_size (amdstr->body, &size);

  if (off < 0 || off > size)
    return ESPIPE;

  amdstr->off = off;
  if (presult)
    *presult = off;
  return 0;
}

/* Return corresponding sizes */

static int
amd_body_stream_size (mu_stream_t stream, mu_off_t *psize)
{
  mu_body_t body = ((struct _amd_body_stream *)stream)->body;
  size_t size;
  int rc = amd_body_size (body, &size);
  if (rc == 0)
    *psize = size;
  return rc;
}

static int
amd_body_size (mu_body_t body, size_t *psize)
{
  int status;
  mu_message_t msg = mu_body_get_owner (body);
  struct _amd_message *mhm = mu_message_get_owner (msg);
  if (mhm == NULL)
    return EINVAL;
  status = amd_check_message (mhm);
  if (status)
    return status;
  if (psize)
    *psize = mhm->body_end - mhm->body_start;
  return 0;
}

static int
amd_body_lines (mu_body_t body, size_t *plines)
{
  int status;
  mu_message_t msg = mu_body_get_owner (body);
  struct _amd_message *mhm = mu_message_get_owner (msg);
  if (mhm == NULL)
    return EINVAL;
  status = amd_check_message (mhm);
  if (status)
    return status;
  if (plines)
    *plines = mhm->body_lines;
  return 0;
}

/* Headers */
static int
amd_header_fill (void *data, char **pbuf, size_t *plen)
{
  char *buffer;
  size_t len;
  mu_message_t msg = data;
  struct _amd_message *mhm = mu_message_get_owner (msg);
  int status, rc;
  mu_off_t pos;
  
  status = amd_pool_open (mhm);
  if (status)
    return status;

  len = mhm->body_start;
  buffer = malloc (len);
  if (!buffer)
    return ENOMEM;
  
  status = mu_stream_seek (mhm->stream, 0, MU_SEEK_CUR, &pos);
  if (status)
    return status;
  status = mu_stream_seek (mhm->stream, 0, MU_SEEK_SET, NULL);
  if (status)
    return status;

  status = mu_stream_read (mhm->stream, buffer, len, NULL);
  rc = mu_stream_seek (mhm->stream, pos, MU_SEEK_SET, NULL);

  if (!status)
    status = rc;
  
  if (status)
    {
      free (buffer);
      return status;
    }

  *plen = len;
  *pbuf = buffer;
  return 0;
}

/* Attributes */
static int
amd_get_attr_flags (mu_attribute_t attr, int *pflags)
{
  mu_message_t msg = mu_attribute_get_owner (attr);
  struct _amd_message *mhm = mu_message_get_owner (msg);

  if (mhm == NULL)
    return EINVAL;
  if (pflags)
    *pflags = mhm->attr_flags;
  return 0;
}

static int
amd_set_attr_flags (mu_attribute_t attr, int flags)
{
  mu_message_t msg = mu_attribute_get_owner (attr);
  struct _amd_message *mhm = mu_message_get_owner (msg);

  if (mhm == NULL)
    return EINVAL;
  mhm->attr_flags |= flags;
  return 0;
}

static int
amd_unset_attr_flags (mu_attribute_t attr, int flags)
{
  mu_message_t msg = mu_attribute_get_owner (attr);
  struct _amd_message *mhm = mu_message_get_owner (msg);

  if (mhm == NULL)
    return EINVAL;
  mhm->attr_flags &= ~flags;
  return 0;
}

/* Envelope */
static int
amd_envelope_date (mu_envelope_t envelope, char *buf, size_t len,
		   size_t *psize)
{
  mu_message_t msg = mu_envelope_get_owner (envelope);
  struct _amd_message *mhm = mu_message_get_owner (msg);
  mu_header_t hdr = NULL;
  const char *date;
  char datebuf[25]; /* Buffer for the output of ctime (terminating nl being
		       replaced by 0) */
  int status;
  
  if (mhm == NULL)
    return EINVAL;

  if ((status = mu_message_get_header (msg, &hdr)) != 0)
    return status;
  if (mu_header_sget_value (hdr, MU_HEADER_ENV_DATE, &date)
      && mu_header_sget_value (hdr, MU_HEADER_DELIVERY_DATE, &date))
    return MU_ERR_NOENT;
  else
    {
      time_t t;
      int rc;
      
      /* Convert to ctime format */
      rc = mu_parse_date (date, &t, NULL); /* FIXME: TZ info is lost */
      if (rc)
	return MU_ERR_NOENT;
      memcpy (datebuf, ctime (&t), sizeof (datebuf) - 1);
      datebuf[sizeof (datebuf) - 1] = 0; /* Kill the terminating newline */
      date = datebuf;
    }

  /* Format:  "sender date" */
  if (buf && len > 0)
    {
      len--; /* Leave space for the null.  */
      strncpy (buf, date, len);
      if (strlen (date) < len)
	{
	  len = strlen (buf);
	  if (buf[len-1] != '\n')
	    buf[len++] = '\n';
	}
      buf[len] = '\0';
    }
  else
    len = strlen (date);
  
  if (psize)
    *psize = len;
  return 0;
}

static int
amd_envelope_sender (mu_envelope_t envelope, char *buf, size_t len, size_t *psize)
{
  mu_message_t msg = mu_envelope_get_owner (envelope);
  struct _amd_message *mhm = mu_message_get_owner (msg);
  mu_header_t hdr = NULL;
  char *from;
  int status;

  if (mhm == NULL)
    return EINVAL;

  if ((status = mu_message_get_header (msg, &hdr)))
    return status;
  if ((status = mu_header_aget_value (hdr, MU_HEADER_ENV_SENDER, &from)))
    return status;

  if (buf && len > 0)
    {
      int slen = strlen (from);

      if (len < slen + 1)
	slen = len - 1;
      memcpy (buf, from, slen);
      buf[slen] = 0;
    }
  else
    len = strlen (from);

  if (psize)
    *psize = len;
  return 0;
}


int
amd_remove_dir (const char *name)
{
  DIR *dir;
  struct dirent *ent;
  char *namebuf;
  size_t namelen, namesize;
  int rc = 0;
  int has_subdirs = 0;
  
  namelen = strlen (name);
  namesize = namelen + 128;
  namebuf = malloc (namesize);
  if (!namebuf)
    return ENOMEM;
  memcpy (namebuf, name, namelen);
  if (namebuf[namelen - 1] != '/')
    namebuf[namelen++] = '/';
  
  dir = opendir (name);
  if (!dir)
    return errno;
  while ((ent = readdir (dir)))
    {
      struct stat st;
      size_t len;

      if (strcmp (ent->d_name, ".") == 0 ||
	  strcmp (ent->d_name, "..") == 0)
	continue;
      len = strlen (ent->d_name);
      if (namelen + len >= namesize)
	{
	  char *p;

	  namesize += len + 1;
	  p = realloc (namebuf, namesize);
	  if (!p)
	    {
	      rc = ENOMEM;
	      break;
	    }
	}
      strcpy (namebuf + namelen, ent->d_name);
      if (stat (namebuf, &st) == 0 && S_ISDIR (st.st_mode))
	{
	  has_subdirs = 1;
	  continue;
	}
      
      if (unlink (namebuf))
	{
	  rc = errno;
	  mu_diag_output (MU_DIAG_WARNING,
			  "failed to remove %s: %s",
			  namebuf, mu_strerror (rc));
	  break;
	}
    }
  closedir (dir);
  free (namebuf);

  if (rc == 0 && !has_subdirs)
    {
      if (rmdir (name))
	{
	  rc = errno;
	  /* POSIX.1-2001 allows EEXIST to be returned if the directory
	     contained entries other than . and .. */
	  if (rc == EEXIST)
	    rc = ENOTEMPTY;
	}
    }
  return rc;
}