mbox.c 63.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
/* GNU Mailutils -- a suite of utilities for electronic mail
   Copyright (C) 1999, 2000, 2001, 2003, 2004, 
   2005, 2006 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 2 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, write to the
   Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301 USA */

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

#ifdef ENABLE_IMAP

#include <errno.h>
#include <string.h>
#ifdef HAVE_STRINGS_H
#include <strings.h>
#endif
#include <stdlib.h>
#include <assert.h>
#include <time.h>

#include <mu_umaxtostr.h>
#include <mailutils/address.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/message.h>
#include <mailutils/mutil.h>
#include <mailutils/observer.h>
#include <mailutils/property.h>
#include <mailutils/stream.h>

#include <imap0.h>
#include <mailbox0.h>
#include <registrar0.h>
#include <url0.h>

#undef min
#define min(a,b) ((a) < (b) ? (a) : (b))

#define MU_IMAP_CACHE_HEADERS "Bcc Cc Content-Language Content-Transfer-Encoding Content-Type Date From In-Reply-To Message-ID Reference Reply-To Sender Subject To X-UIDL"

/* mu_mailbox_t API.  */
static void mailbox_imap_destroy  (mu_mailbox_t);
static int  mailbox_imap_open     (mu_mailbox_t, int);
static int  mailbox_imap_close    (mu_mailbox_t);
static int  imap_uidvalidity      (mu_mailbox_t, unsigned long *);
static int  imap_uidnext          (mu_mailbox_t, size_t *);
static int  imap_expunge          (mu_mailbox_t);
static int  imap_get_message      (mu_mailbox_t, size_t, mu_message_t *);
static int  imap_messages_count   (mu_mailbox_t, size_t *);
static int  imap_messages_recent  (mu_mailbox_t, size_t *);
static int  imap_message_unseen   (mu_mailbox_t, size_t *);
static int  imap_scan             (mu_mailbox_t, size_t, size_t *);
static int  imap_scan0            (mu_mailbox_t, size_t, size_t *, int);
static int  imap_is_updated       (mu_mailbox_t);
static int  imap_append_message   (mu_mailbox_t, mu_message_t);
static int  imap_append_message0  (mu_mailbox_t, mu_message_t);
static int  imap_copy_message     (mu_mailbox_t, mu_message_t);

/* mu_message_t API.  */
static int  imap_submessage_size  (msg_imap_t, size_t *);
static int  imap_message_size     (mu_message_t, size_t *);
static int  imap_message_lines    (mu_message_t, size_t *);
static int  imap_message_get_transport2  (mu_stream_t, mu_transport_t *pin, 
                                          mu_transport_t *pout);
static int  imap_message_read     (mu_stream_t , char *, size_t, mu_off_t, size_t *);
static int  imap_message_uid      (mu_message_t, size_t *);

/* mu_mime_t API.  */
static int  imap_is_multipart     (mu_message_t, int *);
static int  imap_get_num_parts    (mu_message_t, size_t *);
static int  imap_get_part         (mu_message_t, size_t, mu_message_t *);

/* mu_envelope_t API  */
static int  imap_envelope_sender  (mu_envelope_t, char *, size_t, size_t *);
static int  imap_envelope_date    (mu_envelope_t, char *, size_t, size_t *);

/* mu_attribute_t API  */
static int  imap_attr_get_flags   (mu_attribute_t, int *);
static int  imap_attr_set_flags   (mu_attribute_t, int);
static int  imap_attr_unset_flags (mu_attribute_t, int);

/* mu_header_t API.  */
static int  imap_header_read      (mu_header_t, char*, size_t, mu_off_t, size_t *);
static int  imap_header_get_value (mu_header_t, const char*, char *, size_t, size_t *);
static int  imap_header_get_fvalue (mu_header_t, const char*, char *, size_t, size_t *);

/* mu_body_t API.  */
static int  imap_body_read        (mu_stream_t, char *, size_t, mu_off_t, size_t *);
static int  imap_body_size        (mu_body_t, size_t *);
static int  imap_body_lines       (mu_body_t, size_t *);
static int  imap_body_get_transport2 (mu_stream_t, mu_transport_t *pin, mu_transport_t *pout);

/* Helpers.  */
static int  imap_get_transport2    (msg_imap_t msg_imap, 
                                    mu_transport_t *pin,
                                    mu_transport_t *pout);
static int  imap_get_message0     (msg_imap_t, mu_message_t *);
static int  fetch_operation       (f_imap_t, msg_imap_t, char *, size_t, size_t *);
static void free_subparts         (msg_imap_t);
static int  flags_to_string       (char **, int);
static int  delete_to_string      (m_imap_t, char **);
static int  is_same_folder        (mu_mailbox_t, mu_message_t);

#define MBX_WRITABLE(mbx) ((mbx)->flags & (MU_STREAM_WRITE|MU_STREAM_RDWR|MU_STREAM_CREAT))

/* Initialize the concrete object mu_mailbox_t by overloading the function of the
   structure.  */
int
_mailbox_imap_init (mu_mailbox_t mailbox)
{
  m_imap_t m_imap;
  size_t name_len = 0;
  mu_folder_t folder = NULL;

  assert(mailbox);

  folder = mailbox->folder;

  m_imap = mailbox->data = calloc (1, sizeof (*m_imap));
  if (m_imap == NULL)
    return ENOMEM;

  /* Retrieve the name of the mailbox from the URL.  */
  mu_url_get_path (mailbox->url, NULL, 0, &name_len);
  if (name_len == 0)
    {
      /* name "INBOX" is the default.  */
      m_imap->name = calloc (6, sizeof (char));
      strcpy (m_imap->name, "INBOX");
    }
  else
    {
      m_imap->name = calloc (name_len + 1, sizeof (char));
      mu_url_get_path (mailbox->url, m_imap->name, name_len + 1, NULL);
    }

  /* Overload the functions.  */
  mailbox->_destroy = mailbox_imap_destroy;

  mailbox->_open = mailbox_imap_open;
  mailbox->_close = mailbox_imap_close;

  /* Messages.  */
  mailbox->_get_message = imap_get_message;
  mailbox->_append_message = imap_append_message;
  mailbox->_messages_count = imap_messages_count;
  mailbox->_messages_recent = imap_messages_recent;
  mailbox->_message_unseen = imap_message_unseen;
  mailbox->_expunge = imap_expunge;
  mailbox->_uidvalidity = imap_uidvalidity;
  mailbox->_uidnext = imap_uidnext;

  mailbox->_scan = imap_scan;
  mailbox->_is_updated = imap_is_updated;

  /* Get the back pointer of the concrete folder. */
  if (mailbox->folder)
    m_imap->f_imap = mailbox->folder->data;
  /* maibox back pointer.  */
  m_imap->mailbox = mailbox;

  /* Set our properties.  */
  {
    mu_property_t property = NULL;
    mu_mailbox_get_property (mailbox, &property);
    mu_property_set_value (property, "TYPE", "IMAP4", 1);
  }

  return 0;
}

/* Recursive call to free all the subparts of a message.  */
static void
free_subparts (msg_imap_t msg_imap)
{
  size_t i;
  for (i = 0; i < msg_imap->num_parts; i++)
    {
      if (msg_imap->parts[i])
	free_subparts (msg_imap->parts[i]);
    }

  if (msg_imap->message)
    mu_message_destroy (&(msg_imap->message), msg_imap);
  if (msg_imap->parts)
    free (msg_imap->parts);
  if (msg_imap->fheader)
    mu_header_destroy (&msg_imap->fheader, NULL);
  if (msg_imap->internal_date)
    free (msg_imap->internal_date);
  free(msg_imap);
}

/* Give back all the resources. But it does not mean to shutdown the channel
   this is done on the folder.  */
static void
mailbox_imap_destroy (mu_mailbox_t mailbox)
{
  if (mailbox->data)
    {
      m_imap_t m_imap = mailbox->data;
      f_imap_t f_imap = m_imap->f_imap;
      size_t i;

      /* Deselect.  */
      if (m_imap != f_imap->selected)
	f_imap->selected = NULL;

      mu_monitor_wrlock (mailbox->monitor);
      /* Destroy the imap messages and ressources associated to them.  */
      for (i = 0; i < m_imap->imessages_count; i++)
	{
	  if (m_imap->imessages[i])
	    free_subparts (m_imap->imessages[i]);
	}
      if (m_imap->imessages)
	free (m_imap->imessages);
      if (m_imap->name)
	free (m_imap->name);
      free (m_imap);
      mailbox->data = NULL;
      mu_monitor_unlock (mailbox->monitor);
    }
}

/* If the connection was not up it is open by the folder since the stream
   socket is actually created by the folder.  It is not necessary
   to set select the mailbox right away, there are maybe on going operations.
   But on any operation by a particular mailbox, it will be selected first.  */
static int
mailbox_imap_open (mu_mailbox_t mailbox, int flags)
{
  int status = 0;
  m_imap_t m_imap = mailbox->data;
  f_imap_t f_imap = m_imap->f_imap;
  mu_folder_t folder = f_imap->folder;
  mu_list_t folders = NULL;
  size_t count;
  
  /* m_imap must have been created during mailbox initialization. */
  assert (mailbox->data);
  assert (m_imap->name);

  mailbox->flags = flags;

  if ((status = mu_folder_open (mailbox->folder, flags)))
    return status;

  /* We might not have to SELECT the mailbox, but we need to know it
     exists, and CREATE it if it doesn't, and CREATE is specified in
     the flags.
   */

  switch (m_imap->state)
    {
    case IMAP_NO_STATE:
      m_imap->state = IMAP_LIST;

    case IMAP_LIST:
      status = mu_folder_list (folder, NULL, m_imap->name, 0, &folders);
      if (status != 0)
	{
	  if (status != EAGAIN && status != EINPROGRESS && status != EINTR)
	    m_imap->state = IMAP_NO_STATE;

	  return status;
	}
      m_imap->state = IMAP_NO_STATE;
      status = mu_list_count (folders, &count);
      mu_list_destroy (&folders);
      if (status || count)
	return 0;

      if ((flags & MU_STREAM_CREAT) == 0)
	return ENOENT;

      m_imap->state = IMAP_CREATE;

    case IMAP_CREATE:
      switch (f_imap->state)
	{
	case IMAP_NO_STATE:
	  {
	    char *path;
	    size_t len;
	    mu_url_get_path (folder->url, NULL, 0, &len);
	    if (len == 0)
	      return 0;
	    path = calloc (len + 1, sizeof (*path));
	    if (path == NULL)
	      return ENOMEM;
	    mu_url_get_path (folder->url, path, len + 1, NULL);
	    status = imap_writeline (f_imap, "g%u CREATE %s\r\n",
				     f_imap->seq, path);
	    MAILBOX_DEBUG2 (folder, MU_DEBUG_PROT, "g%u CREATE %s\n",
			    f_imap->seq, path);
	    f_imap->seq++;
	    free (path);
	    if (status != 0)
	      {
		m_imap->state = f_imap->state = IMAP_NO_STATE;
		return status;
	      }
	    f_imap->state = IMAP_CREATE;
	  }

	case IMAP_CREATE:
	  status = imap_send (f_imap);
	  if (status != 0)
	    {
	      if (status != EAGAIN && status != EINPROGRESS
		  && status != EINTR)
		m_imap->state = f_imap->state = IMAP_NO_STATE;

	      return status;
	    }
	  f_imap->state = IMAP_CREATE_ACK;

	case IMAP_CREATE_ACK:
	  status = imap_parse (f_imap);
	  if (status != 0)
	    {
	      if (status == EINVAL)
		status = EACCES;

	      if (status != EAGAIN && status != EINPROGRESS
		  && status != EINTR)
		m_imap->state = f_imap->state = IMAP_NO_STATE;

	      return status;
	    }
	  f_imap->state = IMAP_NO_STATE;
	  break;

	default:
	  status = EINVAL;
	  break;
	}
      m_imap->state = IMAP_NO_STATE;
      break;

    default:
      status = EINVAL;
      break;
    }

  return status;
}

/* We can not close the folder in term of shuting down the connection but if
   we were the selected mailbox we send the close and deselect ourself.
   The CLOSE is also use to expunge instead of sending expunge.  */
static int
mailbox_imap_close (mu_mailbox_t mailbox)
{
  m_imap_t m_imap = mailbox->data;
  f_imap_t f_imap = m_imap->f_imap;
  int status = 0;
  
  /* If we are not the selected mailbox, just close the stream.  */
  if (m_imap != f_imap->selected)
    return mu_folder_close (mailbox->folder);

  /* Select first.  */
  status = imap_messages_count (mailbox, NULL);
  if (status != 0)
    return status;

  switch (f_imap->state)
    {
    case IMAP_NO_STATE:
      status = imap_writeline (f_imap, "g%s CLOSE\r\n",
			       mu_umaxtostr (0, f_imap->seq++));
      CHECK_ERROR (f_imap, status);
      MAILBOX_DEBUG0 (mailbox, MU_DEBUG_PROT, f_imap->buffer);
      f_imap->state = IMAP_CLOSE;

    case IMAP_CLOSE:
      status = imap_send (f_imap);
      CHECK_EAGAIN (f_imap, status);
      f_imap->state = IMAP_CLOSE_ACK;

    case IMAP_CLOSE_ACK:
      {
	size_t i;
	status = imap_parse (f_imap);
	CHECK_EAGAIN (f_imap, status);
	MAILBOX_DEBUG0 (mailbox, MU_DEBUG_PROT, f_imap->buffer);

	mu_monitor_wrlock (mailbox->monitor);
	/* Destroy the imap messages and ressources associated to them.  */
	for (i = 0; i < m_imap->imessages_count; i++)
	  {
	    if (m_imap->imessages[i])
	      free_subparts (m_imap->imessages[i]);
	  }
	if (m_imap->imessages)
	  free (m_imap->imessages);
	m_imap->imessages = NULL;
	m_imap->imessages_count = 0;
	m_imap->messages_count = 0;
	m_imap->recent = 0;
	m_imap->unseen = 0;
	/* Clear the callback string structure.  */
	mu_stream_truncate (f_imap->string.stream, 0);
	f_imap->string.offset = 0;
	f_imap->string.nleft = 0;
	f_imap->string.type = IMAP_NO_STATE;
	f_imap->string.msg_imap = NULL;
	mu_monitor_unlock (mailbox->monitor);
      }
      break;

    default:
      /* mu_error ("imap_close unknown state: reconnect\n");*/
      break;
    }

  /* Deselect.  */
  f_imap->selected = NULL;

  f_imap->state = IMAP_NO_STATE;
  return mu_folder_close (mailbox->folder);
}

/* Construction of the mu_message_t, nothing else is done then this setup.  To
   clarify this is different from say mu_message_get_part().  This call is for the
   mailbox and we are setting up the mu_message_t structure.  */
static int
imap_get_message (mu_mailbox_t mailbox, size_t msgno, mu_message_t *pmsg)
{
  m_imap_t m_imap = mailbox->data;
  msg_imap_t msg_imap;
  int status = 0;

  if (pmsg == NULL)
    return MU_ERR_OUT_PTR_NULL;
  if (msgno == 0 || msgno > m_imap->messages_count)
    return EINVAL;

  /* Check to see if we have already this message.  */
  mu_monitor_rdlock (mailbox->monitor);
  {
    size_t i;
    for (i = 0; i < m_imap->imessages_count; i++)
      {
	if (m_imap->imessages[i])
	  {
	    if (m_imap->imessages[i]->num == msgno)
	      {
		*pmsg = m_imap->imessages[i]->message;
		mu_monitor_unlock (mailbox->monitor);
		return 0;
	      }
	  }
      }
  }
  mu_monitor_unlock (mailbox->monitor);

  /* Allocate a concrete imap message.  */
  msg_imap = calloc (1, sizeof *msg_imap);
  if (msg_imap == NULL)
    return ENOMEM;
  /* Back pointer.  */
  msg_imap->m_imap = m_imap;
  msg_imap->num = msgno;
  status = imap_get_message0 (msg_imap, pmsg);
  if (status == 0)
    {
      /* Add it to the list.  */
      mu_monitor_wrlock (mailbox->monitor);
      {
	msg_imap_t *m ;
	m = realloc (m_imap->imessages,
		     (m_imap->imessages_count + 1) * sizeof *m);
	if (m == NULL)
	  {
	    mu_message_destroy (pmsg, msg_imap);
	    mu_monitor_unlock (mailbox->monitor);
	    return ENOMEM;
	  }
	m_imap->imessages = m;
	m_imap->imessages[m_imap->imessages_count] = msg_imap;
	m_imap->imessages_count++;
      }
      mu_monitor_unlock (mailbox->monitor);

      msg_imap->message = *pmsg;
    }
  else
    free (msg_imap);
  return status;
}

/* Set all the mu_message_t functions and parts.  */
static int
imap_get_message0 (msg_imap_t msg_imap, mu_message_t *pmsg)
{
  int status = 0;
  mu_message_t msg = NULL;
  mu_mailbox_t mailbox = msg_imap->m_imap->mailbox;

  /* Create the message and its stream.  */
  {
    mu_stream_t stream = NULL;
    if ((status = mu_message_create (&msg, msg_imap)) != 0
        || (status = mu_stream_create (&stream, mailbox->flags, msg)) != 0)
      {
        mu_stream_destroy (&stream, msg);
        mu_message_destroy (&msg, msg_imap);
        return status;
      }
    mu_stream_setbufsiz (stream, 128);
    mu_stream_set_read (stream, imap_message_read, msg);
    mu_stream_set_get_transport2 (stream, imap_message_get_transport2, msg);
    mu_message_set_stream (msg, stream, msg_imap);
    mu_message_set_size (msg, imap_message_size, msg_imap);
    mu_message_set_lines (msg, imap_message_lines, msg_imap);
  }

  /* Create the header.  */
  {
    mu_header_t header = NULL;
    if ((status = mu_header_create (&header, NULL, 0,  msg)) != 0)
      {
        mu_message_destroy (&msg, msg_imap);
        return status;
      }
    mu_header_set_fill (header, imap_header_read, msg);
    mu_header_set_get_value (header, imap_header_get_value, msg);
    mu_header_set_get_fvalue (header, imap_header_get_fvalue, msg);
    mu_message_set_header (msg, header, msg_imap);
  }

  /* Create the attribute.  */
  {
    mu_attribute_t attribute;
    status = mu_attribute_create (&attribute, msg);
    if (status != 0)
      {
        mu_message_destroy (&msg, msg_imap);
        return status;
      }
    mu_attribute_set_get_flags (attribute, imap_attr_get_flags, msg);
    mu_attribute_set_set_flags (attribute, imap_attr_set_flags, msg);
    mu_attribute_set_unset_flags (attribute, imap_attr_unset_flags, msg);
    mu_message_set_attribute (msg, attribute, msg_imap);
  }

  /* Create the body and its stream.  */
  {
    mu_body_t body = NULL;
    mu_stream_t stream = NULL;
    if ((status = mu_body_create (&body, msg)) != 0
        || (status = mu_stream_create (&stream, mailbox->flags, body)) != 0)
      {
        mu_body_destroy (&body, msg);
        mu_stream_destroy (&stream, body);
        mu_message_destroy (&msg, msg_imap);
        return status;
      }
    mu_stream_setbufsiz (stream, 128);
    mu_stream_set_read (stream, imap_body_read, body);
    mu_stream_set_get_transport2 (stream, imap_body_get_transport2, body);
    mu_body_set_size (body, imap_body_size, msg);
    mu_body_set_lines (body, imap_body_lines, msg);
    mu_body_set_stream (body, stream, msg);
    mu_message_set_body (msg, body, msg_imap);
  }

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

  /* Set the mime handling.  */
  mu_message_set_is_multipart (msg, imap_is_multipart, msg_imap);
  mu_message_set_get_num_parts (msg, imap_get_num_parts, msg_imap);
  mu_message_set_get_part (msg, imap_get_part, msg_imap);

  /* Set the UID on the message. */
  mu_message_set_uid (msg, imap_message_uid, msg_imap);
  mu_message_set_mailbox (msg, mailbox, msg_imap);

  /* We are done here.  */
  *pmsg = msg;
  return 0;
}

static int
imap_message_unseen (mu_mailbox_t mailbox, size_t *punseen)
{
  m_imap_t m_imap = mailbox->data;
  *punseen = m_imap->unseen;
  return 0;
}

static int
imap_messages_recent (mu_mailbox_t mailbox, size_t *precent)
{
  m_imap_t m_imap = mailbox->data;
  *precent = m_imap->recent;
  return 0;
}

static int
imap_uidvalidity (mu_mailbox_t mailbox, unsigned long *puidvalidity)
{
  m_imap_t m_imap = mailbox->data;
  *puidvalidity = m_imap->uidvalidity;
  return 0;
}

static int
imap_uidnext (mu_mailbox_t mailbox, size_t *puidnext)
{
  m_imap_t m_imap = mailbox->data;
  *puidnext = m_imap->uidnext;
  return 0;
}

/* There is no explicit call to get the message count.  The count is send on
   a SELECT/EXAMINE command it is also sent async, meaning it will be piggy
   back on other server response as an untag "EXIST" response.  The
   function is also use as a way to select mailbox by other functions.  */
static int
imap_messages_count (mu_mailbox_t mailbox, size_t *pnum)
{
  m_imap_t m_imap = mailbox->data;
  f_imap_t f_imap = m_imap->f_imap;
  int status = 0;

  /* FIXME: It is debatable if we should reconnect when the connection
     timeout or die.  Probably for timeout client should ping i.e. send
     a NOOP via imap_is_updated() function to keep the connection alive.  */
  status = mu_folder_open (mailbox->folder, mailbox->flags);
  if (status != 0)
    return status;

  /* Are we already selected ? */
  if (m_imap == (f_imap->selected))
    {
      if (pnum)
	*pnum = m_imap->messages_count;
      return 0;
    }

  /*  Put the mailbox as selected.  */
  f_imap->selected = m_imap;

  switch (f_imap->state)
    {
    case IMAP_NO_STATE:
      status = imap_writeline (f_imap, "g%s %s %s\r\n",
			       mu_umaxtostr (0, f_imap->seq++), 
                               MBX_WRITABLE(mailbox) ? "SELECT" : "EXAMINE",
                               m_imap->name);
      CHECK_ERROR (f_imap, status);
      MAILBOX_DEBUG0 (mailbox, MU_DEBUG_PROT, f_imap->buffer);
      f_imap->state = IMAP_SELECT;

    case IMAP_SELECT:
      status = imap_send (f_imap);
      CHECK_EAGAIN (f_imap, status);
      f_imap->state = IMAP_SELECT_ACK;

    case IMAP_SELECT_ACK:
      status = imap_parse (f_imap);
      CHECK_EAGAIN (f_imap, status);
      MAILBOX_DEBUG0 (mailbox, MU_DEBUG_PROT, f_imap->buffer);
      break;

    default:
      /*mu_error ("imap_message_count unknown state: reconnect\n");*/
      break;
    }

  if (pnum)
    *pnum = m_imap->messages_count;

  f_imap->state = IMAP_NO_STATE;
  return status;
}

static int
imap_scan (mu_mailbox_t mailbox, size_t msgno, size_t *pcount)
{
  return imap_scan0 (mailbox, msgno, pcount , 1);
}

/* Usually when this function is call it is because there is an oberver
   attach an the client is try to build some sort of list/tree header
   as the scanning progress.  But doing this for each message can be
   time consuming and inefficient.  So we bundle all the request
   into one and ask the server for everything "FETCH 1:*".  The good
   side is that everything will be faster and we do not do lot of small
   transcation but rather a big one.  The bad thing is that every thing
   will be cache in the structure using a lot of memory.  */
static int
imap_scan0 (mu_mailbox_t mailbox, size_t msgno, size_t *pcount, int notif)
{
  int status;
  size_t i;
  size_t count = 0;
  m_imap_t m_imap = mailbox->data;
  f_imap_t f_imap = m_imap->f_imap;

  /* Selected.  */
  status = imap_messages_count (mailbox, &count);
  if (pcount)
    *pcount = count;
  if (status != 0)
    return status;

  /* No need to scan, there is no messages. */
  if (count == 0)
    return 0;

  switch (f_imap->state)
    {
    case IMAP_NO_STATE:
      status = imap_writeline (f_imap,
			       "g%s FETCH 1:* (FLAGS RFC822.SIZE BODY.PEEK[HEADER.FIELDS (%s)])\r\n",
			       mu_umaxtostr (0, f_imap->seq++),
			       MU_IMAP_CACHE_HEADERS);
      CHECK_ERROR (f_imap, status);
      MAILBOX_DEBUG0 (mailbox, MU_DEBUG_PROT, f_imap->buffer);
      f_imap->state = IMAP_SCAN;

    case IMAP_SCAN:
      status = imap_send (f_imap);
      CHECK_EAGAIN (f_imap, status);
      f_imap->state = IMAP_SCAN_ACK;
      /* Clear the callback string structure.  */
      mu_stream_truncate (f_imap->string.stream, 0);
      f_imap->string.offset = 0;
      f_imap->string.nleft = 0;
      f_imap->string.type = IMAP_NO_STATE;
      f_imap->string.msg_imap = NULL;

    case IMAP_SCAN_ACK:
      status = imap_parse (f_imap);
      CHECK_EAGAIN (f_imap, status);
      MAILBOX_DEBUG0 (mailbox, MU_DEBUG_PROT, f_imap->buffer);
      /* Clear the callback string structure.  */
      mu_stream_truncate (f_imap->string.stream, 0);
      f_imap->string.offset = 0;
      f_imap->string.nleft = 0;
      f_imap->string.type = IMAP_NO_STATE;
      f_imap->string.msg_imap = NULL;
      break;

    default:
      /*mu_error ("imap_scan unknown state: reconnect\n");*/
      return EINVAL;
    }

  f_imap->state = IMAP_NO_STATE;

  /* Do not send notifications.  */
  if (!notif)
    return 0;

  /* If no callbacks bail out early.  */
  if (mailbox->observable == NULL)
    return 0;

  for (i = msgno; i <= count; i++)
    {
      if (mu_observable_notify (mailbox->observable, MU_EVT_MESSAGE_ADD) != 0)
	break;
      if (((i + 1) % 100) == 0)
	{
	  mu_observable_notify (mailbox->observable, MU_EVT_MAILBOX_PROGRESS);
	}
    }
  return 0;
}

/* Send a NOOP and see if the count has changed.  */
static int
imap_is_updated (mu_mailbox_t mailbox)
{
  m_imap_t m_imap = mailbox->data;
  size_t oldcount = m_imap->messages_count;
  f_imap_t f_imap = m_imap->f_imap;
  int status = 0;

  /* Selected.  */
  status = imap_messages_count (mailbox, &oldcount);
  if (status != 0)
    return status;

  /* Send a noop, and let imap piggy pack the information.  */
  switch (f_imap->state)
    {
    case IMAP_NO_STATE:
      status = imap_writeline (f_imap, "g%s NOOP\r\n",
			       mu_umaxtostr (0, f_imap->seq++));
      CHECK_ERROR (f_imap, status);
      MAILBOX_DEBUG0 (mailbox, MU_DEBUG_PROT, f_imap->buffer);
      f_imap->state = IMAP_NOOP;

    case IMAP_NOOP:
      status = imap_send (f_imap);
      CHECK_EAGAIN (f_imap, status);
      f_imap->state = IMAP_NOOP_ACK;

    case IMAP_NOOP_ACK:
      status = imap_parse (f_imap);
      CHECK_EAGAIN (f_imap, status);
      MAILBOX_DEBUG0 (mailbox, MU_DEBUG_PROT, f_imap->buffer);
      break;

    default:
      /*mu_error ("imap_noop unknown state: reconnect\n"); */
      break;
    }
  f_imap->state = IMAP_NO_STATE;
  return (oldcount == m_imap->messages_count);
}


static int
imap_expunge (mu_mailbox_t mailbox)
{
  int status;
  m_imap_t m_imap = mailbox->data;
  f_imap_t f_imap = m_imap->f_imap;

  if (!MBX_WRITABLE(mailbox))
    return EACCES;
       
  /* Select first.  */
  status = imap_messages_count (mailbox, NULL);
  if (status != 0)
    return status;

  switch (f_imap->state)
    {
    case IMAP_NO_STATE:
      {
	char *set = NULL;
	status = delete_to_string (m_imap, &set);
	CHECK_ERROR (f_imap, status);
	if (set == NULL || *set == '\0')
	  {
	    if (set)
	      free (set);
	    return 0;
	  }
	status = imap_writeline (f_imap,
				 "g%s STORE %s +FLAGS.SILENT (\\Deleted)\r\n",
				 mu_umaxtostr (0, f_imap->seq++),
				 set);
	free (set);
	CHECK_ERROR (f_imap, status);
	MAILBOX_DEBUG0 (m_imap->mailbox, MU_DEBUG_PROT, f_imap->buffer);
	f_imap->state = IMAP_STORE;
      }

      /* Send DELETE.  */
    case IMAP_STORE:
      status = imap_send (f_imap);
      CHECK_EAGAIN (f_imap, status);
      f_imap->state = IMAP_STORE_ACK;

    case IMAP_STORE_ACK:
      status = imap_parse (f_imap);
      CHECK_EAGAIN (f_imap, status);
      MAILBOX_DEBUG0 (m_imap->mailbox, MU_DEBUG_PROT, f_imap->buffer);
      f_imap->state = IMAP_NO_STATE;

    case IMAP_EXPUNGE:
    case IMAP_EXPUNGE_ACK:
      status = imap_writeline (f_imap, "g%s EXPUNGE\r\n",
			       mu_umaxtostr (0, f_imap->seq++));
      CHECK_ERROR (f_imap, status);
      status = imap_send (f_imap);
      CHECK_EAGAIN (f_imap, status);

      /* Rescan after expunging but do not trigger the observers.  */
    case IMAP_SCAN:
    case IMAP_SCAN_ACK:
      status = imap_scan0 (mailbox, 1, NULL, 0);
      CHECK_EAGAIN (f_imap, status);

    default:
      /* mu_error ("imap_expunge: unknown state\n"); */
      break;
    }

  return status;
}

/* FIXME: Not ___Nonblocking___ safe.  */
/* DANGER:  The mu_message_t object makes no guaranty about the size and the lines
   that it returns, if its pointing to non-local file messages, so we
   make a local copy.  */
static int
imap_append_message (mu_mailbox_t mailbox, mu_message_t msg)
{
  int status = 0;
  m_imap_t m_imap = mailbox->data;
  f_imap_t f_imap = m_imap->f_imap;

  /* FIXME: It is debatable if we should reconnect when the connection
   timeout or die.  For timeout client should ping i.e. send
   a NOOP via imap_is_updated() function to keep the connection alive.  */
  status = mu_folder_open (mailbox->folder, mailbox->flags);
  if (status != 0)
    return status;

  /* FIXME: Can we append to self.  */

  /* Check to see if we are selected. If the message was not modified
     and came from the same imap folder. use COPY.*/
  if (f_imap->selected != m_imap && !mu_message_is_modified (msg)
      && is_same_folder (mailbox, msg))
    return imap_copy_message (mailbox, msg);

  /* copy the message to local disk by createing a floating message.  */
  {
    mu_message_t message = NULL;

    status = mu_message_create_copy(&message, msg);

    if (status == 0)
      status = imap_append_message0 (mailbox, message);
    mu_message_destroy (&message, NULL);
  }
  return status;
}

/* Ok this mean that the message is coming from somewhere else.  IMAP
   is very susceptible on the size, example:
   A003 APPEND saved-messages (\Seen) {310}
   if the server does not get the right size advertise in the string literal
   it will misbehave.  Sine we are assuming that the message will be
   in native file system format meaning ending with NEWLINE, we will have
   to do the calculation.  But what is worse; the value return
   by mu_message_size () and mu_message_lines () are no mean exact but rather
   a gross approximation for certain type of mailbox.  So the sane
   thing to do is to save the message in temporary file, this we say
   we guarantee the size of the message.  */
static int
imap_append_message0 (mu_mailbox_t mailbox, mu_message_t msg)
{
  size_t total;
  int status = 0;
  m_imap_t m_imap = mailbox->data;
  f_imap_t f_imap = m_imap->f_imap;

  switch (f_imap->state)
    {
    case IMAP_NO_STATE:
      {
	size_t lines, size;
	char *path;
	char *abuf = malloc (1);
	/* Get the desired flags attribute.  */
	if (abuf == NULL)
	  return ENOMEM;
	*abuf = '\0';
	{
	  mu_attribute_t attribute = NULL;
	  int flags = 0;
	  mu_message_get_attribute (msg, &attribute);
	  mu_attribute_get_flags (attribute, &flags);
	  status = flags_to_string (&abuf, flags);
	  if (status != 0)
	    return status;
	  /* Put the surrounding parenthesis, wu-IMAP is sensible to this.  */
	  {
	    char *tmp = calloc (strlen (abuf) + 3, 1);
	    if (tmp == NULL)
	      {
		free (abuf);
		return ENOMEM;
	      }
	    sprintf (tmp, "(%s)", abuf);
	    free (abuf);
	    abuf = tmp;
	  }
	}

	/* Get the mailbox filepath.  */
	{
	  size_t n = 0;
	  mu_url_get_path (mailbox->url, NULL, 0, &n);
	  if (n == 0)
	    {
	      if (!(path = strdup ("INBOX")))
		{
		  free (abuf);
		  return ENOMEM;
		}
	    }
	  else
	    {
	      path = calloc (n + 1, sizeof (*path));
	      if (path == NULL)
		{
		  free (abuf);
		  return ENOMEM;
		}
	      mu_url_get_path (mailbox->url, path, n + 1, NULL);
	    }
	}

	/* FIXME: we need to get the mu_envelope_date and use it.
	   currently it is ignored.  */

	/* Get the total size, assuming that it is in UNIX format.  */
	lines = size = 0;
	mu_message_size (msg, &size);
	mu_message_lines (msg, &lines);
	total = size + lines;
	status = imap_writeline (f_imap, "g%s APPEND %s %s {%s}\r\n",
				 mu_umaxtostr (0, f_imap->seq++),
				 path,
				 abuf,
				 mu_umaxtostr (1, size + lines));
	free (abuf);
	free (path);
	CHECK_ERROR (f_imap, status);
	MAILBOX_DEBUG0 (mailbox, MU_DEBUG_PROT, f_imap->buffer);
	f_imap->state = IMAP_APPEND;
      }

    case IMAP_APPEND:
      status = imap_send (f_imap);
      CHECK_EAGAIN (f_imap, status);
      f_imap->state = IMAP_APPEND_CONT;

    case IMAP_APPEND_CONT:
      status = imap_parse (f_imap);
      CHECK_EAGAIN (f_imap, status);
      MAILBOX_DEBUG0 (mailbox, MU_DEBUG_PROT, f_imap->buffer);
      /* If we did not receive the continuation token, it is an error
         bail out.  */
      if (f_imap->buffer[0] != '+')
	{
	  status = EACCES;
	  break;
	}
      f_imap->state = IMAP_APPEND_SEND;

    case IMAP_APPEND_SEND:
      {
	mu_stream_t stream = NULL;
	mu_off_t off = 0;
	size_t n = 0;
	char buffer[255];
	mu_message_get_stream (msg, &stream);
	while (mu_stream_readline (stream, buffer, sizeof buffer, off, &n) == 0
	       && n > 0)
	  {
	    if (buffer[n - 1] == '\n')
	      {
		buffer[n - 1] = '\0';
		status = imap_writeline (f_imap, "%s\r\n", buffer);
	      }
	    else
	      imap_writeline (f_imap, "%s", buffer);
	    off += n;
	    status = imap_send (f_imap);
	    CHECK_EAGAIN (f_imap, status);
	  }
	f_imap->state = IMAP_APPEND_ACK;
      }
      /* !@#%$ UW-IMAP server hack: insists on the last line.  */
      imap_writeline (f_imap, "\n");
      status = imap_send (f_imap);
      CHECK_EAGAIN (f_imap, status);

    case IMAP_APPEND_ACK:
      status = imap_parse (f_imap);
      CHECK_EAGAIN (f_imap, status);
      MAILBOX_DEBUG0 (m_imap->mailbox, MU_DEBUG_PROT, f_imap->buffer);

    default:
      /* mu_error ("imap_append: unknown state\n"); */
      break;
    }
  f_imap->state = IMAP_NO_STATE;
  return status;
}

/* If the message is on the same server.  Use the COPY command much more
   efficient.  */
static int
imap_copy_message (mu_mailbox_t mailbox, mu_message_t msg)
{
  m_imap_t m_imap = mailbox->data;
  f_imap_t f_imap = m_imap->f_imap;
  msg_imap_t msg_imap = mu_message_get_owner (msg);
  int status = 0;

  /* FIXME: It is debatable if we should reconnect when the connection
   timeout or die.  For timeout client should ping i.e. send
   a NOOP via imap_is_updated() function to keep the connection alive.  */
  status = mu_folder_open (mailbox->folder, mailbox->flags);
  if (status != 0)
    return status;

  switch (f_imap->state)
    {
    case IMAP_NO_STATE:
      {
	char *path;
	size_t n = 0;
	/* Check for a valid mailbox name.  */
	mu_url_get_path (mailbox->url, NULL, 0, &n);
	if (n == 0)
	  return EINVAL;
	path = calloc (n + 1, sizeof (*path));
	if (path == NULL)
	  return ENOMEM;
	mu_url_get_path (mailbox->url, path, n + 1, NULL);
	status = imap_writeline (f_imap, "g%s COPY %s %s\r\n",
				 mu_umaxtostr (0, f_imap->seq++),
				 mu_umaxtostr (1, msg_imap->num),
				 path);
	free (path);
	CHECK_ERROR (f_imap, status);
	MAILBOX_DEBUG0 (mailbox, MU_DEBUG_PROT, f_imap->buffer);
	f_imap->state = IMAP_COPY;
      }

    case IMAP_COPY:
      status = imap_send (f_imap);
      CHECK_EAGAIN (f_imap, status);
      f_imap->state = IMAP_COPY_ACK;

    case IMAP_COPY_ACK:
      status = imap_parse (f_imap);
      CHECK_EAGAIN (f_imap, status);
      MAILBOX_DEBUG0 (mailbox, MU_DEBUG_PROT, f_imap->buffer);

    default:
      break;
    }
  f_imap->state = IMAP_NO_STATE;
  return status;
}

/* Message read overload  */
static int
imap_message_read (mu_stream_t stream, char *buffer, size_t buflen,
		   mu_off_t offset, size_t *plen)
{
  mu_message_t msg = mu_stream_get_owner (stream);
  msg_imap_t msg_imap = mu_message_get_owner (msg);
  m_imap_t m_imap = msg_imap->m_imap;
  f_imap_t f_imap = m_imap->f_imap;
  char *oldbuf = NULL;
  char newbuf[2];
  int status;

  /* This is so annoying, a buffer len of 1 is a killer. If you have for
     example "\n" to retrieve from the server, IMAP will transform this to
     "\r\n" and since you ask for only 1, the server will send '\r' only.
     And ... '\r' will be stripped by (imap_readline()) the number of char
     read will be 0 which means we're done .... sigh ...  So we guard by at
     least ask for 2 chars.  */
  if (buflen == 1)
    {
      oldbuf = buffer;
      buffer = newbuf;
      buflen = 2;
    }

  /* Start over.  */
  if (offset == 0)
    msg_imap->mu_message_lines = 0;

  status = imap_messages_count (m_imap->mailbox, NULL);
  if (status != 0)
    return status;

  /* Select first.  */
  if (f_imap->state == IMAP_NO_STATE)
    {
      char *section = NULL;

      if (msg_imap->part)
	section = section_name (msg_imap);

      /* We have strip the \r, but the offset on the imap server is with that
	 octet(CFLF) so add it in the offset, it's the number of lines.  */
      status = imap_writeline (f_imap,
			       "g%s FETCH %s BODY.PEEK[%s]<%s.%s>\r\n",
			       mu_umaxtostr (0, f_imap->seq++),
			       mu_umaxtostr (1, msg_imap->num),
			       (section) ? section : "",
			       mu_umaxtostr (2, offset +
					     msg_imap->mu_message_lines),
			       mu_umaxtostr (3, buflen));
      if (section)
	free (section);
      CHECK_ERROR (f_imap, status);
      MAILBOX_DEBUG0 (m_imap->mailbox, MU_DEBUG_PROT, f_imap->buffer);
      f_imap->state = IMAP_FETCH;
    }
  status = fetch_operation (f_imap, msg_imap, buffer, buflen, plen);

  if (oldbuf)
    oldbuf[0] = buffer[0];
  return status;
}

static int
imap_message_lines (mu_message_t msg, size_t *plines)
{
  msg_imap_t msg_imap = mu_message_get_owner (msg);
  if (plines && msg_imap)
    {
      if (msg_imap->mu_message_lines == 0)
	*plines = msg_imap->body_lines + msg_imap->header_lines;
      else
	*plines = msg_imap->mu_message_lines;
    }
  return 0;
}

/* Sometimes a message is just a place container for other sub parts.
   In those cases imap bodystructure does not set the mu_message_size aka
   the mu_body_size.  But we can calculate it since the mu_message_size
   is the sum of its subparts.  */
static int
imap_submessage_size (msg_imap_t msg_imap, size_t *psize)
{
  if (psize)
    {
      *psize = 0;
      if (msg_imap->mu_message_size == 0)
	{
	  size_t i, size;
	  for (size = i = 0; i < msg_imap->num_parts; i++, size = 0)
	    {
	      if (msg_imap->parts[i])
		imap_submessage_size (msg_imap->parts[i], &size);
	      *psize += size;
	    }
	}
      else
	*psize = (msg_imap->mu_message_size + msg_imap->header_size)
	  - msg_imap->mu_message_lines;
    }
  return 0;
}

static int
imap_message_size (mu_message_t msg, size_t *psize)
{
  msg_imap_t msg_imap = mu_message_get_owner (msg);
  m_imap_t m_imap = msg_imap->m_imap;
  f_imap_t f_imap = m_imap->f_imap;
  int status = 0;;

  status = imap_messages_count (m_imap->mailbox, NULL);
  if (status != 0)
    return status;

  /* If there is a parent it means it is a sub message, IMAP does not give
     the full size of mime messages, so the mu_message_size retrieved from
     doing a bodystructure represents rather the mu_body_size.  */
  if (msg_imap->parent)
    return imap_submessage_size (msg_imap, psize);

  if (msg_imap->mu_message_size == 0)
    {
      /* Select first.  */
      if (f_imap->state == IMAP_NO_STATE)
	{
	  /* We strip the \r, but the offset/size on the imap server is with
	     that octet so add it in the offset, since it's the number of
	     lines.  */
	  status = imap_writeline (f_imap,
				   "g%s FETCH %s RFC822.SIZE\r\n",
				   mu_umaxtostr (0, f_imap->seq++),
				   mu_umaxtostr (1, msg_imap->num));
	  CHECK_ERROR (f_imap, status);
	  MAILBOX_DEBUG0 (m_imap->mailbox, MU_DEBUG_PROT, f_imap->buffer);
	  f_imap->state = IMAP_FETCH;
	}
      status = fetch_operation (f_imap, msg_imap, 0, 0, 0);
    }

  if (status == 0)
    {
      if (psize)
	*psize = msg_imap->mu_message_size - msg_imap->mu_message_lines;
    }
  return status;
}

static int
imap_message_uid (mu_message_t msg, size_t *puid)
{
  msg_imap_t msg_imap = mu_message_get_owner (msg);
  m_imap_t m_imap = msg_imap->m_imap;
  f_imap_t f_imap = m_imap->f_imap;
  int status;

  if (puid)
    return 0;

  /* Select first.  */
  status = imap_messages_count (m_imap->mailbox, NULL);
  if (status != 0)
    return status;

  if (f_imap->state == IMAP_NO_STATE)
    {
      if (msg_imap->uid)
	{
	  *puid = msg_imap->uid;
	  return 0;
	}
      status = imap_writeline (f_imap, "g%s FETCH %s UID\r\n",
			       mu_umaxtostr (0, f_imap->seq++),
			       mu_umaxtostr (1, msg_imap->num));
      CHECK_ERROR (f_imap, status);
      MAILBOX_DEBUG0 (m_imap->mailbox, MU_DEBUG_PROT, f_imap->buffer);
      f_imap->state = IMAP_FETCH;
    }
  status = fetch_operation (f_imap, msg_imap, 0, 0, 0);
  if (status != 0)
    return status;
  *puid = msg_imap->uid;
  return 0;
}

static int
imap_message_get_transport2 (mu_stream_t stream, mu_transport_t *pin, mu_transport_t *pout)
{
  mu_message_t msg = mu_stream_get_owner (stream);
  msg_imap_t msg_imap = mu_message_get_owner (msg);
  return imap_get_transport2 (msg_imap, pin, pout);
}

/* Mime.  */
static int
imap_is_multipart (mu_message_t msg, int *ismulti)
{
  msg_imap_t msg_imap = mu_message_get_owner (msg);
  m_imap_t m_imap = msg_imap->m_imap;
  f_imap_t f_imap = m_imap->f_imap;
  int status;

  /* Select first.  */
  status = imap_messages_count (m_imap->mailbox, NULL);
  if (status != 0)
    return status;

  if (f_imap->state == IMAP_NO_STATE)
    {
      if (msg_imap->num_parts || msg_imap->part)
	{
	  if (ismulti)
	    *ismulti = (msg_imap->num_parts > 1);
	  return 0;
	}
      status = imap_writeline (f_imap,
			       "g%s FETCH %s BODYSTRUCTURE\r\n",
			       mu_umaxtostr (0, f_imap->seq++),
			       mu_umaxtostr (1, msg_imap->num));
      CHECK_ERROR (f_imap, status);
      MAILBOX_DEBUG0 (m_imap->mailbox, MU_DEBUG_PROT, f_imap->buffer);
      f_imap->state = IMAP_FETCH;
    }
  status = fetch_operation (f_imap, msg_imap, 0, 0, 0);
  if (status != 0)
    return status;
  if (ismulti)
    *ismulti = (msg_imap->num_parts > 1);
  return 0;
}

static int
imap_get_num_parts (mu_message_t msg, size_t *nparts)
{
  msg_imap_t msg_imap = mu_message_get_owner (msg);
  if (msg_imap)
    {
      if (msg_imap->num_parts == 0)
	{
	  int status = imap_is_multipart (msg, NULL);
	  if (status != 0)
	    return status;
	}
      if (nparts)
	*nparts = (msg_imap->num_parts == 0) ? 1 : msg_imap->num_parts;
    }
  return 0;
}

static int
imap_get_part (mu_message_t msg, size_t partno, mu_message_t *pmsg)
{
  msg_imap_t msg_imap = mu_message_get_owner (msg);
  int status = 0;

  if (msg_imap->num_parts == 0)
    {
      status = imap_get_num_parts (msg, NULL);
      if (status != 0)
	return status;
    }

  if (partno <= msg_imap->num_parts)
    {
      if (msg_imap->parts[partno - 1]->message)
	{
	  if (pmsg)
	    *pmsg = msg_imap->parts[partno - 1]->message;
	}
      else
	{
	  mu_message_t message;
	  status = imap_get_message0 (msg_imap->parts[partno - 1], &message);
	  if (status == 0)
	    {
	      mu_header_t header;
	      mu_message_get_header (message, &header);
	      mu_header_set_get_value (header, NULL, message);
	      mu_message_set_stream (message, NULL, msg_imap->parts[partno - 1]);
	      /* mu_message_set_size (message, NULL, msg_imap->parts[partno - 1]); */
	      msg_imap->parts[partno - 1]->message = message;
	      if (pmsg)
		*pmsg = message;
	    }
	}
    }
  else
    {
      if (pmsg)
	*pmsg = msg_imap->message;
    }
  return status;
}

/* Envelope.  */
static int
imap_envelope_sender (mu_envelope_t envelope, char *buffer, size_t buflen,
		      size_t *plen)
{
  mu_message_t msg = mu_envelope_get_owner (envelope);
  mu_header_t header;
  int status;

  if (buflen == 0)
    return 0;

  mu_message_get_header (msg, &header);
  status = mu_header_get_value (header, MU_HEADER_SENDER, buffer, buflen, plen);
  if (status == EAGAIN)
    return status;
  else if (status != 0)
    status = mu_header_get_value (header, MU_HEADER_FROM, buffer, buflen, plen);
  if (status == 0)
    {
      mu_address_t address;
      if (mu_address_create (&address, buffer) == 0)
	{
	  mu_address_get_email (address, 1, buffer, buflen, plen);
	  mu_address_destroy (&address);
	}
    }
  else if (status != EAGAIN)
    {
      strncpy (buffer, "Unknown", buflen)[buflen - 1] = '0';
      if (plen)
	*plen = strlen (buffer);
    }
  return status;
}

static int
imap_envelope_date (mu_envelope_t envelope, char *buffer, size_t buflen,
		    size_t *plen)
{
  mu_message_t msg = mu_envelope_get_owner (envelope);
  msg_imap_t msg_imap = mu_message_get_owner (msg);
  m_imap_t m_imap = msg_imap->m_imap;
  f_imap_t f_imap = m_imap->f_imap;
  struct tm tm;
  mu_timezone tz;
  time_t now;
  char datebuf[] = "mm-dd-yyyy hh:mm:ss +0000";
  const char* date = datebuf;
  const char** datep = &date;
  /* reserve as much space as we need for internal-date */
  int status;

  /* Select first.  */
  status = imap_messages_count (m_imap->mailbox, NULL);
  if (status != 0)
    return status;
  if (msg_imap->internal_date == NULL)
    {
      if (f_imap->state == IMAP_NO_STATE)
	{
	  status = imap_writeline (f_imap,
				   "g%s FETCH %s INTERNALDATE\r\n",
				   mu_umaxtostr (0, f_imap->seq++),
				   mu_umaxtostr (1, msg_imap->num));
	  CHECK_ERROR (f_imap, status);
	  MAILBOX_DEBUG0 (m_imap->mailbox, MU_DEBUG_PROT, f_imap->buffer);
	  f_imap->state = IMAP_FETCH;
	}
      status = fetch_operation (f_imap, msg_imap, datebuf,
				sizeof datebuf, NULL);
      if (status != 0)
	return status;
      msg_imap->internal_date = strdup (datebuf);
    }
  else
    {
      date = msg_imap->internal_date;
      datep = &date;
    }

  if (mu_parse_imap_date_time(datep, &tm, &tz) != 0)
    now = (time_t)-1;
  else
    now = mu_tm2time (&tm, &tz);

  /* if the time was unparseable, or mktime() didn't like what we
     parsed, use the calendar time. */
  if (now == (time_t)-1)
    {
      struct tm *gmt;

      time (&now);
      gmt = gmtime (&now);
      tm = *gmt;
    }

  {
    char tmpbuf[MU_ENVELOPE_DATE_LENGTH+1];
    size_t n = mu_strftime (tmpbuf, sizeof tmpbuf,
                            MU_ENVELOPE_DATE_FORMAT, localtime (&tm));
    n = mu_cpystr (buffer, tmpbuf, buflen);
    if (plen)
      *plen = n;
  }
  return 0;
}

/* Attributes.  */
static int
imap_attr_get_flags (mu_attribute_t attribute, int *pflags)
{
  mu_message_t msg = mu_attribute_get_owner (attribute);
  msg_imap_t msg_imap = mu_message_get_owner (msg);
  m_imap_t m_imap = msg_imap->m_imap;
  f_imap_t f_imap = m_imap->f_imap;
  int status = 0;

  /* Select first.  */
  status = imap_messages_count (m_imap->mailbox, NULL);
  if (status != 0)
    return status;

  /* Did we retrieve it alread ?  */
  if (msg_imap->flags != 0)
    {
      if (pflags)
	*pflags = msg_imap->flags;
      return 0;
    }

  if (f_imap->state == IMAP_NO_STATE)
    {
      status = imap_writeline (f_imap, "g%s FETCH %s FLAGS\r\n",
			       mu_umaxtostr (0, f_imap->seq++),
			       mu_umaxtostr (1, msg_imap->num));
      CHECK_ERROR (f_imap, status);
      MAILBOX_DEBUG0 (m_imap->mailbox, MU_DEBUG_PROT, f_imap->buffer);
      f_imap->state = IMAP_FETCH;
    }
  status = fetch_operation (f_imap, msg_imap, NULL, 0, NULL);
  if (status == 0)
    {
      if (pflags)
	*pflags = msg_imap->flags;
    }
  return status;
}

static int
imap_attr_set_flags (mu_attribute_t attribute, int flag)
{
  mu_message_t msg = mu_attribute_get_owner (attribute);
  msg_imap_t msg_imap = mu_message_get_owner (msg);
  m_imap_t m_imap = msg_imap->m_imap;
  f_imap_t f_imap = m_imap->f_imap;
  int status = 0;

  /* Select first.  */
  status = imap_messages_count (m_imap->mailbox, NULL);
  if (status != 0)
    return status;

  /* If already set don't bother.  */
  if (msg_imap->flags & flag)
    return 0;

  /* The delete FLAG is not pass yet but only on the expunge.  */
  if (flag & MU_ATTRIBUTE_DELETED)
    {
      msg_imap->flags |= MU_ATTRIBUTE_DELETED;
      flag &= ~MU_ATTRIBUTE_DELETED;
    }

  if (f_imap->state == IMAP_NO_STATE)
    {
      char *abuf = malloc (1);
      if (abuf == NULL)
	return ENOMEM;
      *abuf = '\0';
      status = flags_to_string (&abuf, flag);
      if (status != 0)
	return status;
      /* No flags to send??  */
      if (*abuf == '\0')
	{
	  free (abuf);
	  return 0;
	}
      status = imap_writeline (f_imap, "g%s STORE %s +FLAGS.SILENT (%s)\r\n",
			       mu_umaxtostr (0, f_imap->seq++),
			       mu_umaxtostr (1, msg_imap->num),
			       abuf);
      free (abuf);
      CHECK_ERROR (f_imap, status);
      MAILBOX_DEBUG0 (m_imap->mailbox, MU_DEBUG_PROT, f_imap->buffer);
      msg_imap->flags |= flag;
      f_imap->state = IMAP_FETCH;
    }
  return fetch_operation (f_imap, msg_imap, NULL, 0, NULL);
}

static int
imap_attr_unset_flags (mu_attribute_t attribute, int flag)
{
  mu_message_t msg = mu_attribute_get_owner (attribute);
  msg_imap_t msg_imap = mu_message_get_owner (msg);
  m_imap_t m_imap = msg_imap->m_imap;
  f_imap_t f_imap = m_imap->f_imap;
  int status = 0;

  /* Select first.  */
  status = imap_messages_count (m_imap->mailbox, NULL);
  if (status != 0)
    return status;

  /* The delete FLAG is not pass yet but only on the expunge.  */
  if (flag & MU_ATTRIBUTE_DELETED)
    {
      msg_imap->flags &= ~MU_ATTRIBUTE_DELETED;
      flag &= ~MU_ATTRIBUTE_DELETED;
    }

  if (f_imap->state == IMAP_NO_STATE)
    {
      char *abuf = malloc (1);
      if (abuf == NULL)
	return ENOMEM;
      *abuf = '\0';
      status = flags_to_string (&abuf, flag);
      if (status != 0)
	return status;
      /* No flags to send??  */
      if (*abuf == '\0')
	{
	  free (abuf);
	  return 0;
	}
      status = imap_writeline (f_imap, "g%s STORE %s -FLAGS.SILENT (%s)\r\n",
			       mu_umaxtostr (0, f_imap->seq++),
			       mu_umaxtostr (1, msg_imap->num),
			       abuf);
      free (abuf);
      CHECK_ERROR (f_imap, status);
      MAILBOX_DEBUG0 (m_imap->mailbox, MU_DEBUG_PROT, f_imap->buffer);
      msg_imap->flags &= ~flag;
      f_imap->state = IMAP_FETCH;
    }
  return fetch_operation (f_imap, msg_imap, NULL, 0, NULL);
}

/* Header.  */
static int
imap_header_get_value (mu_header_t header, const char *field, char * buffer,
		       size_t buflen, size_t *plen)
{
  mu_message_t msg = mu_header_get_owner (header);
  msg_imap_t msg_imap = mu_message_get_owner (msg);
  m_imap_t m_imap = msg_imap->m_imap;
  f_imap_t f_imap = m_imap->f_imap;
  int status;
  size_t len = 0;
  char *value;

  /* Select first.  */
  status = imap_messages_count (m_imap->mailbox, NULL);
  if (status != 0)
    return status;

  /* Hack, if buffer == NULL they want to know how big is the field value,
     Unfortunately IMAP does not say, so we take a guess hoping that the
     value will not be over 1024.  */
  if (buffer == NULL || buflen == 0)
    len = 1024;
  else
    len = strlen (field) + buflen + 4;

  if (f_imap->state == IMAP_NO_STATE)
    {
      /* Select first.  */
      status = imap_messages_count (m_imap->mailbox, NULL);
      if (status != 0)
	return status;
      status = imap_writeline (f_imap,
			       "g%s FETCH %s BODY.PEEK[HEADER.FIELDS (%s)]<0.%s>\r\n",
			       mu_umaxtostr (0, f_imap->seq++),
			       mu_umaxtostr (1, msg_imap->num),
			       field,
			       mu_umaxtostr (2, len));
      CHECK_ERROR (f_imap, status);
      MAILBOX_DEBUG0 (m_imap->mailbox, MU_DEBUG_PROT, f_imap->buffer);
      f_imap->state = IMAP_FETCH;

    }

  value = calloc (len, sizeof (*value));
  status = fetch_operation (f_imap, msg_imap, value, len, &len);
  if (status == 0)
    {
      char *colon;
      /* The field-matching is case-insensitive.  In all cases, the
	 delimiting newline between the header and the body is always
	 included. Nuke it  */
      if (len)
	value[len - 1] = '\0';

      /* Move pass the field-name.  */
      colon = strchr (value, ':');
      if (colon)
	{
	  colon++;
	  if (*colon == ' ')
	    colon++;
	}
      else
	colon = value;

      while (*colon && colon[strlen (colon) - 1] == '\n')
	colon[strlen (colon) - 1] = '\0';

      if (buffer && buflen)
	{
	  strncpy (buffer, colon, buflen);
	  buffer[buflen - 1] = '\0';
	}
      len = strlen (buffer);
      if (plen)
	*plen = len;
      if (len == 0)
	status = MU_ERR_NOENT;
    }
  free (value);
  return status;
}

static int
imap_header_get_fvalue (mu_header_t header, const char *field, char * buffer,
			size_t buflen, size_t *plen)
{
  mu_message_t msg = mu_header_get_owner (header);
  msg_imap_t msg_imap = mu_message_get_owner (msg);
  m_imap_t m_imap = msg_imap->m_imap;
  f_imap_t f_imap = m_imap->f_imap;
  int status;
  size_t len = 0;
  char *value;

  /* Select first.  */
  status = imap_messages_count (m_imap->mailbox, NULL);
  if (status != 0)
    return status;

  /* Do we all ready have the headers.  */
  if (msg_imap->fheader)
    return mu_header_get_value (msg_imap->fheader, field, buffer, buflen, plen);

  /* We are caching the must use headers.  */
  if (f_imap->state == IMAP_NO_STATE)
    {
      /* Select first.  */
      status = imap_messages_count (m_imap->mailbox, NULL);
      if (status != 0)
        return status;
      status = imap_writeline (f_imap,
                               "g%s FETCH %s (FLAGS RFC822.SIZE BODY.PEEK[HEADER.FIELDS (%s)])\r\n",
                               mu_umaxtostr (0, f_imap->seq++),
			       mu_umaxtostr (1, msg_imap->num),
			       MU_IMAP_CACHE_HEADERS);
      CHECK_ERROR (f_imap, status);
      MAILBOX_DEBUG0 (m_imap->mailbox, MU_DEBUG_PROT, f_imap->buffer);
      f_imap->state = IMAP_FETCH;

    }

  /* Should be enough for our needs.  */
  len = 2048;
  value = calloc (len, sizeof *value);
  status = fetch_operation (f_imap, msg_imap, value, len, &len);
  if (status == 0)
    {
      status = mu_header_create (&msg_imap->fheader, value, len, NULL);
      if (status == 0)
	status =  mu_header_get_value (msg_imap->fheader, field, buffer,
				    buflen, plen);
    }
  free (value);
  return status;
}

static int
imap_header_read (mu_header_t header, char *buffer, size_t buflen, mu_off_t offset,
		  size_t *plen)
{
  mu_message_t msg = mu_header_get_owner (header);
  msg_imap_t msg_imap = mu_message_get_owner (msg);
  m_imap_t m_imap = msg_imap->m_imap;
  f_imap_t f_imap = m_imap->f_imap;
  char *oldbuf = NULL;
  char newbuf[2];
  int status;

  /* This is so annoying, a buffer len of 1 is a killer. If you have for
     example "\n" to retrieve from the server, IMAP will transform this to
     "\r\n" and since you ask for only 1, the server will send '\r' only.
     And ... '\r' will be stripped by (imap_readline()) the number of char
     read will be 0 which means we're done .... sigh ...  So we guard by at
     least ask for 2 chars.  */
  if (buflen == 1)
    {
      oldbuf = buffer;
      buffer = newbuf;
      buflen = 2;
    }

  /* Start over.  */
  if (offset == 0)
    msg_imap->header_lines = 0;

  /* Select first.  */
  status = imap_messages_count (m_imap->mailbox, NULL);
  if (status != 0)
    return status;

  if (f_imap->state == IMAP_NO_STATE)
    {
      /* We strip the \r, but the offset/size on the imap server is with that
         octet so add it in the offset, since it's the number of lines.  */
      if (msg_imap->part)
        {
          char *section = section_name (msg_imap);
          status = imap_writeline (f_imap,
                                   "g%s FETCH %s BODY.PEEK[%s.MIME]<%s.%s>\r\n",
                                   mu_umaxtostr (0, f_imap->seq++),
				   mu_umaxtostr (1, msg_imap->num),
                                   (section) ? section : "",
                                   mu_umaxtostr (2, offset +
						 msg_imap->header_lines),
				   mu_umaxtostr (3, buflen));
          if (section)
            free (section);
        }
      else
        status = imap_writeline (f_imap,
                                 "g%s FETCH %s BODY.PEEK[HEADER]<%s.%s>\r\n",
                                 mu_umaxtostr (0, f_imap->seq++),
				 mu_umaxtostr (1, msg_imap->num),
                                 mu_umaxtostr (2, offset +
					       msg_imap->header_lines),
				 mu_umaxtostr (3, buflen));
      CHECK_ERROR (f_imap, status);
      MAILBOX_DEBUG0 (m_imap->mailbox, MU_DEBUG_PROT, f_imap->buffer);
      f_imap->state = IMAP_FETCH;

    }
  status = fetch_operation (f_imap, msg_imap, buffer, buflen, plen);
  if (oldbuf)
    oldbuf[0] = buffer[0];
  return status;
}

/* Body.  */
static int
imap_body_size (mu_body_t body, size_t *psize)
{
  mu_message_t msg = mu_body_get_owner (body);
  msg_imap_t msg_imap = mu_message_get_owner (msg);
  if (psize && msg_imap)
    {
      /* If there is a parent it means it is a sub message, IMAP does not give
	 the full size of mime messages, so the mu_message_size was retrieve from
	 doing a bodystructure and represents rather the mu_body_size.  */
      if (msg_imap->parent)
	{
	  *psize = msg_imap->mu_message_size - msg_imap->mu_message_lines;
	}
      else
	{
	  if (msg_imap->body_size)
	    *psize = msg_imap->body_size;
	  else if (msg_imap->mu_message_size)
	    *psize = msg_imap->mu_message_size
	      - (msg_imap->header_size + msg_imap->header_lines);
	  else
	    *psize = 0;
	}
    }
  return 0;
}

static int
imap_body_lines (mu_body_t body, size_t *plines)
{
  mu_message_t msg = mu_body_get_owner (body);
  msg_imap_t msg_imap = mu_message_get_owner (msg);
  if (plines && msg_imap)
    *plines = msg_imap->body_lines;
  return 0;
}

/* FIXME: Send EISPIPE if trying to seek back.  */
static int
imap_body_read (mu_stream_t stream, char *buffer, size_t buflen,
		mu_off_t offset, size_t *plen)
{
  mu_body_t body = mu_stream_get_owner (stream);
  mu_message_t msg = mu_body_get_owner (body);
  msg_imap_t msg_imap = mu_message_get_owner (msg);
  m_imap_t m_imap = msg_imap->m_imap;
  f_imap_t f_imap = m_imap->f_imap;
  char *oldbuf = NULL;
  char newbuf[2];
  int status;

  /* This is so annoying, a buffer len of 1 is a killer. If you have for
     example "\n" to retrieve from the server, IMAP will transform this to
     "\r\n" and since you ask for only 1, the server will send '\r' only.
     And ... '\r' will be stripped by (imap_readline()) the number of char
     read will be 0 which means we're done .... sigh ...  So we guard by at
     least ask for 2 chars.  */
  if (buflen == 1)
    {
      oldbuf = buffer;
      buffer = newbuf;
      buflen = 2;
    }

  /* Start over.  */
  if (offset == 0)
    {
      msg_imap->body_lines = 0;
      msg_imap->body_size = 0;
    }

  /* Select first.  */
  status = imap_messages_count (m_imap->mailbox, NULL);
  if (status != 0)
    return status;

  if (f_imap->state == IMAP_NO_STATE)
    {
      /* We strip the \r, but the offset/size on the imap server is with the
         octet, so add it since it's the number of lines.  */
      if (msg_imap->part)
        {
          char *section = section_name (msg_imap);
          status = imap_writeline (f_imap,
                                   "g%s FETCH %s BODY.PEEK[%s]<%s.%s>\r\n",
                                   mu_umaxtostr (0, f_imap->seq++),
				   mu_umaxtostr (1, msg_imap->num),
                                   (section) ? section: "",
                                   mu_umaxtostr (2, offset +
						 msg_imap->body_lines),
				   mu_umaxtostr (3, buflen));
          if (section)
            free (section);
        }
      else
        status = imap_writeline (f_imap,
                                 "g%s FETCH %s BODY.PEEK[TEXT]<%s.%s>\r\n",
                                 mu_umaxtostr (0, f_imap->seq++),
				 mu_umaxtostr (1, msg_imap->num),
                                 mu_umaxtostr (2, offset +
					       msg_imap->body_lines),
				 mu_umaxtostr (3, buflen));
      CHECK_ERROR (f_imap, status);
      MAILBOX_DEBUG0 (m_imap->mailbox, MU_DEBUG_PROT, f_imap->buffer);
      f_imap->state = IMAP_FETCH;

    }
  status = fetch_operation (f_imap, msg_imap, buffer, buflen, plen);
  if (oldbuf)
    oldbuf[0] = buffer[0];
  return status;
}

static int
imap_body_get_transport2 (mu_stream_t stream, mu_transport_t *pin, 
                         mu_transport_t *pout)
{
  mu_body_t body = mu_stream_get_owner (stream);
  mu_message_t msg = mu_body_get_owner (body);
  msg_imap_t msg_imap = mu_message_get_owner (msg);
  return imap_get_transport2 (msg_imap, pin, pout);
}


static int
imap_get_transport2 (msg_imap_t msg_imap, mu_transport_t *pin, mu_transport_t *pout)
{
  if (   msg_imap
      && msg_imap->m_imap
      && msg_imap->m_imap->f_imap
      && msg_imap->m_imap->f_imap->folder)
    return mu_stream_get_transport2 (msg_imap->m_imap->f_imap->folder->stream,
			         pin, pout);
  return EINVAL;
}

/* Since so many operations are fetch, we regoup this into one function.  */
static int
fetch_operation (f_imap_t f_imap, msg_imap_t msg_imap, char *buffer,
		 size_t buflen, size_t *plen)
{
  int status = 0;

  switch (f_imap->state)
    {
    case IMAP_FETCH:
      status = imap_send (f_imap);
      CHECK_EAGAIN (f_imap, status);
      mu_stream_truncate (f_imap->string.stream, 0);
      f_imap->string.offset = 0;
      f_imap->string.nleft = 0;
      f_imap->string.type = IMAP_NO_STATE;
      f_imap->string.msg_imap = msg_imap;
      f_imap->state = IMAP_FETCH_ACK;

    case IMAP_FETCH_ACK:
      status = imap_parse (f_imap);
      CHECK_EAGAIN (f_imap, status);
      if (f_imap->selected)
	MAILBOX_DEBUG0 (f_imap->selected->mailbox, MU_DEBUG_PROT,
			f_imap->buffer);

    default:
      break;
    }

  f_imap->state = IMAP_NO_STATE;

  /* The server may have timeout any case connection is gone away.  */
  if (status == 0 && f_imap->isopen == 0 && f_imap->string.offset == 0)
    status = MU_ERR_CONN_CLOSED;

  if (buffer)
    mu_stream_read (f_imap->string.stream, buffer, buflen, 0, plen);
  else if (plen)
    *plen = 0;
  mu_stream_truncate (f_imap->string.stream, 0);
  f_imap->string.offset = 0;
  f_imap->string.nleft = 0;
  f_imap->string.type = IMAP_NO_STATE;
  f_imap->string.msg_imap = NULL;
  return status;
}

/* Decide whether the message came from the same folder as the mailbox.  */
static int
is_same_folder (mu_mailbox_t mailbox, mu_message_t msg)
{
  mu_mailbox_t mbox = NULL;
  mu_message_get_mailbox (msg, &mbox);
  return (mbox != NULL && mbox->url != NULL
          && mu_url_is_same_scheme (mbox->url, mailbox->url)
          && mu_url_is_same_host (mbox->url, mailbox->url)
          && mu_url_is_same_port (mbox->url, mailbox->url));
}

/* Convert flag attribute to IMAP String attributes.  */
static int
flags_to_string (char **pbuf, int flag)
{
  char *abuf = *pbuf;
  if (flag & MU_ATTRIBUTE_DELETED)
    {
      char *tmp = realloc (abuf, strlen (abuf) + strlen ("\\Deleted") + 2);
      if (tmp == NULL)
        {
          free (abuf);
          return ENOMEM;
        }
      abuf = tmp;
      if (*abuf)
        strcat (abuf, " ");
      strcat (abuf, "\\Deleted");
    }
  if (flag & MU_ATTRIBUTE_READ)
    {
      char *tmp = realloc (abuf, strlen (abuf) + strlen ("\\Seen") + 2);
      if (tmp == NULL)
        {
          free (abuf);
          return ENOMEM;
        }
      abuf = tmp;
      if (*abuf)
        strcat (abuf, " ");
      strcat (abuf, "\\Seen");
    }
  if (flag & MU_ATTRIBUTE_ANSWERED)
    {
      char *tmp = realloc (abuf, strlen (abuf) + strlen ("\\Answered") + 2);
      if (tmp == NULL)
        {
          free (abuf);
          return ENOMEM;
        }
      abuf = tmp;
      if (*abuf)
        strcat (abuf, " ");
      strcat (abuf, "\\Answered");
    }
  if (flag & MU_ATTRIBUTE_DRAFT)
    {
      char *tmp = realloc (abuf, strlen (abuf) + strlen ("\\Draft") + 2);
      if (tmp == NULL)
        {
          free (abuf);
          return ENOMEM;
        }
      abuf = tmp;
      if (*abuf)
        strcat (abuf, " ");
      strcat (abuf, "\\Draft");
    }
  if (flag & MU_ATTRIBUTE_FLAGGED)
    {
      char *tmp = realloc (abuf, strlen (abuf) + strlen ("\\Flagged") + 2);
      if (tmp == NULL)
        {
          free (abuf);
          return ENOMEM;
        }
      abuf = tmp;
      if (*abuf)
        strcat (abuf, " ");
      strcat (abuf, "\\Flagged");
    }
  *pbuf = abuf;
  return 0;
}

/* Convert a suite of number to IMAP message number.  */
static int
add_number (char **pset, size_t start, size_t end)
{
  char buf[2*UINTMAX_STRSIZE_BOUND+2];
  char *set;
  char *tmp;
  size_t set_len = 0;

  if (pset == NULL)
    return 0;

  set = *pset;

  if (set)
    set_len = strlen (set);

  /* We had a previous seqence.  */
  if (start == 0)
    *buf = '\0';
  else if (start != end)
    snprintf (buf, sizeof buf, "%s:%s",
	      mu_umaxtostr (0, start),
	      mu_umaxtostr (1, end));
  else
    snprintf (buf, sizeof buf, "%s", mu_umaxtostr (0, start));

  if (set_len)
    tmp = realloc (set, set_len + strlen (buf) + 2 /* null and comma */);
  else
    tmp = calloc (strlen (buf) + 1, 1);

  if (tmp == NULL)
    {
      free (set);
      return ENOMEM;
    }
  set = tmp;

  /* If we had something add a comma separator.  */
  if (set_len)
    strcat (set, ",");
  strcat (set, buf);

  *pset = set;
  return 0;
}

static int
delete_to_string (m_imap_t m_imap, char **pset)
{
  int status;
  size_t i, prev = 0, is_range = 0;
  size_t start = 0, cur = 0;
  char *set = NULL;

  /* Reformat the number for IMAP.  */
  for (i = 0; i < m_imap->imessages_count; ++i)
    {
      if (m_imap->imessages[i]
	  && (m_imap->imessages[i]->flags & MU_ATTRIBUTE_DELETED))
	{
	  cur = m_imap->imessages[i]->num;
	  /* The first number.  */
	  if (start == 0)
	    {
	      start = prev = cur;
	    }
	  /* Is it a sequence?  */
	  else if ((prev + 1) == cur)
	    {
	      prev = cur;
	      is_range = 1;
	    }
	  continue;
	}

      if (start)
	{
	  status = add_number (&set, start, cur);
	  if (status != 0)
	    return status;
	  start = 0;
	  prev = 0;
	  cur = 0;
	  is_range = 0;
	}
    } /* for () */

  if (start)
    {
      status = add_number (&set, start, cur);
      if (status != 0)
	return status;
    }
  *pset = set;
  return 0;
}

#endif