fetch.c 45 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
/* GNU Mailutils -- a suite of utilities for electronic mail
   Copyright (C) 1999, 2001, 2005-2012, 2014-2016 Free Software
   Foundation, Inc.

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

   GNU Mailutils is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

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

#include "imap4d.h"
#include <ctype.h>
#include <mailutils/argcv.h>

/*  Taken from RFC2060
    fetch           ::= "FETCH" SPACE set SPACE ("ALL" / "FULL" /
    "FAST" / fetch_att / "(" 1#fetch_att ")")

    fetch_att       ::= "ENVELOPE" / "FLAGS" / "INTERNALDATE" /
    "RFC822" [".HEADER" / ".SIZE" / ".TEXT"] /
    "BODY" ["STRUCTURE"] / "UID" /
    "BODY" [".PEEK"] section
    ["<" number "." nz_number ">"]
*/

struct fetch_runtime_closure
{
  int eltno;           /* Serial number of the last output FETCH element */
  size_t msgno;        /* Sequence number of the message being processed */
  mu_message_t msg;    /* The message itself */
  mu_list_t msglist;   /* A list of referenced messages.  See KLUDGE below. */
  char *err_text;      /* On return: error description if failed. */

  mu_list_t fnlist;
};

struct fetch_function_closure;

typedef int (*fetch_function_t) (struct fetch_function_closure *,
				 struct fetch_runtime_closure *);

struct fetch_function_closure
{
  fetch_function_t fun;            /* Handler function */
  const char *name;                /* Response tag */
  const char *section_tag;          
  size_t *section_part;            /* Section-part */
  size_t nset;                     /* Number of elements in section_part */
  int peek;
  int not;                         /* Negate header set */  
  mu_list_t headers;               /* Headers */
  size_t start;                    /* Substring start */ 
  size_t size;                     /* Substring length */
};

struct fetch_parse_closure
{
  int isuid;
  mu_list_t fnlist;
  mu_msgset_t msgset;
};


static int
fetch_send_address (const char *addr)
{
  mu_address_t address;
  size_t i, count = 0;

  /* Short circuit.  */
  if (addr == NULL || *addr == '\0')
    {
      io_sendf ("NIL");
      return RESP_OK;
    }

  mu_address_create (&address, addr);
  mu_address_get_count (address, &count);

  /* We failed: can't parse.  */
  if (count == 0)
    {
      io_sendf ("NIL");
      return RESP_OK;
    }

  io_sendf ("(");
  for (i = 1; i <= count; i++)
    {
      const char *str;
      int is_group = 0;

      io_sendf ("(");

      mu_address_sget_personal (address, i, &str);
      io_send_qstring (str);
      io_sendf (" ");

      mu_address_sget_route (address, i, &str);
      io_send_qstring (str);

      io_sendf (" ");

      mu_address_is_group (address, i, &is_group);
      str = NULL;
      if (is_group)
	mu_address_sget_personal (address, i, &str);
      else
	mu_address_sget_local_part (address, i, &str);

      io_send_qstring (str);

      io_sendf (" ");

      mu_address_sget_domain (address, i, &str);
      io_send_qstring (str);

      io_sendf (")");
    }
  io_sendf (")");
  return RESP_OK;
}

static void
fetch_send_header_value (mu_header_t header, const char *name,
			 const char *defval, int space)
{
  char *buffer;
  
  if (space)
    io_sendf (" ");
  if (mu_header_aget_value (header, name, &buffer) == 0)
    {
      io_send_qstring (buffer);
      free (buffer);
    }
  else if (defval)
    io_send_qstring (defval);
  else
    io_sendf ("NIL");
}

static void
fetch_send_header_address (mu_header_t header, const char *name,
			   const char *defval, int space)
{
  char *buffer;
  
  if (space)
    io_sendf (" ");
  if (mu_header_aget_value (header, name, &buffer) == 0)
    {
      fetch_send_address (buffer);
      free (buffer);
    }
  else
    fetch_send_address (defval);
}

static void
imap4d_ws_alloc_die (struct mu_wordsplit *wsp)
{
  imap4d_bye (ERR_NO_MEM);
}

#define IMAP4D_WS_FLAGS \
  (MU_WRDSF_DEFFLAGS | MU_WRDSF_DELIM | \
   MU_WRDSF_ENOMEMABRT | MU_WRDSF_ALLOC_DIE)

/* Send parameter list for the bodystructure.  */
static void
send_parameter_list (const char *buffer)
{
  struct mu_wordsplit ws;
  
  if (!buffer)
    {
      io_sendf ("NIL");
      return;
    }

  ws.ws_delim = " \t\r\n;=";
  ws.ws_alloc_die = imap4d_ws_alloc_die;
  if (mu_wordsplit (buffer, &ws, IMAP4D_WS_FLAGS))
    {
      mu_error (_("%s failed: %s"), "mu_wordsplit",
		mu_wordsplit_strerror (&ws));
      return; /* FIXME: a better error handling, maybe? */
    }
  
  if (ws.ws_wordc == 0)
    io_sendf ("NIL");
  else
    {
      char *p;
      
      io_sendf ("(");
        
      p = ws.ws_wordv[0];
      io_send_qstring (p);

      if (ws.ws_wordc > 1)
	{
	  int i, space = 0;
	  char *lvalue = NULL;

	  io_sendf ("(");
	  for (i = 1; i < ws.ws_wordc; i++)
	    {
	      if (lvalue)
		{
		  if (space)
		    io_sendf (" ");
		  io_send_qstring (lvalue);
		  lvalue = NULL;
		  space = 1;
		}
	      
	      switch (ws.ws_wordv[i][0])
		{
		case ';':
		  continue;
		  
		case '=':
		  if (++i < ws.ws_wordc)
		    {
		      io_sendf (" ");
		      io_send_qstring (ws.ws_wordv[i]);
		    }
		  break;
		  
		default:
		  lvalue = ws.ws_wordv[i];
		}
	    }
	  if (lvalue)
	    {
	      if (space)
		io_sendf (" ");
	      io_send_qstring (lvalue);
	    }
	  io_sendf (")");
	}
      else
	io_sendf (" NIL");
      io_sendf (")");
    }
  mu_wordsplit_free (&ws);
}

static void
fetch_send_header_list (mu_header_t header, const char *name,
			const char *defval, int space)
{
  char *buffer;
  
  if (space)
    io_sendf (" ");
  if (mu_header_aget_value (header, name, &buffer) == 0)
    {
      send_parameter_list (buffer);
      free (buffer);
    }
  else if (defval)
    send_parameter_list (defval);
  else
    io_sendf ("NIL");
}

/* ENVELOPE:
   The envelope structure of the message.  This is computed by the server by
   parsing the [RFC-822] header into the component parts, defaulting various
   fields as necessary.  The fields are presented in the order:
   Date, Subject, From, Sender, Reply-To, To, Cc, Bcc, In-Reply-To, Message-ID.
   Any field of an envelope or address structure that is not applicable is
   presented as NIL.  Note that the server MUST default the reply-to and sender
   fields from the from field.  The date, subject, in-reply-to, and message-id
   fields are strings.  The from, sender, reply-to, to, cc, and bcc fields
   are parenthesized lists of address structures.  */
static int
fetch_envelope0 (mu_message_t msg)
{
  char *from = NULL;
  mu_header_t header = NULL;

  mu_message_get_header (msg, &header);

  fetch_send_header_value (header, "Date", NULL, 0);
  fetch_send_header_value (header, "Subject", NULL, 1);

  /* From:  */
  mu_header_aget_value (header, "From", &from);
  io_sendf (" ");
  fetch_send_address (from);

  fetch_send_header_address (header, "Sender", from, 1);
  fetch_send_header_address (header, "Reply-to", from, 1);
  fetch_send_header_address (header, "To", NULL, 1);
  fetch_send_header_address (header, "Cc", NULL, 1);
  fetch_send_header_address (header, "Bcc", NULL, 1);
  fetch_send_header_value (header, "In-Reply-To", NULL, 1);
  fetch_send_header_value (header, "Message-ID", NULL, 1);

  free (from);
  return RESP_OK;
}

static int fetch_bodystructure0 (mu_message_t message, int extension);

/* The basic fields of a non-multipart body part are in the following order:
   body type:
   A string giving the content media type name as defined in [MIME-IMB].

   body subtype:
   A string giving the content subtype name as defined in [MIME-IMB].

   body parameter parenthesized list:
   A parenthesized list of attribute/value pairs [e.g. ("foo" "bar" "baz"
   "rag") where "bar" is the value of "foo" and "rag" is the value of "baz"]
   as defined in [MIME-IMB].

   body id:
   A string giving the content id as defined in [MIME-IMB].

   body description:
   A string giving the content description as defined in [MIME-IMB].

   body encoding:
   A string giving the content transfer encoding as defined in [MIME-IMB].

   body size:
   A number giving the size of the body in octets. Note that this size is the
   size in its transfer encoding and not the resulting size after any decoding.

   A body type of type TEXT contains, immediately after the basic fields, the
   size of the body in text lines.

   A body type of type MESSAGE and subtype RFC822 contains, immediately after
   the basic fields, the envelope structure, body structure, and size in text
   lines of the encapsulated message.

   The extension data of a non-multipart body part are in the following order:
   body MD5:
   A string giving the body MD5 value as defined in [MD5].

   body disposition:
   A parenthesized list with the same content and function as the body
   disposition for a multipart body part.

   body language:\
   A string or parenthesized list giving the body language value as defined
   in [LANGUAGE-TAGS].
 */
static int
bodystructure (mu_message_t msg, int extension)
{
  mu_header_t header = NULL;
  char *buffer = NULL;
  size_t blines = 0;
  int message_rfc822 = 0;
  int text_plain = 0;

  mu_message_get_header (msg, &header);

  if (mu_header_aget_value (header, MU_HEADER_CONTENT_TYPE, &buffer) == 0)
    {
      struct mu_wordsplit ws;
      char *p;
      size_t len;
      
      ws.ws_delim = " \t\r\n;=";
      ws.ws_alloc_die = imap4d_ws_alloc_die;
      if (mu_wordsplit (buffer, &ws, IMAP4D_WS_FLAGS))
	{
	  mu_error (_("%s failed: %s"), "mu_wordsplit",
		    mu_wordsplit_strerror (&ws));
	  return RESP_BAD; /* FIXME: a better error handling, maybe? */
	}

      len = strcspn (ws.ws_wordv[0], "/");
      if (mu_c_strcasecmp (ws.ws_wordv[0], "MESSAGE/RFC822") == 0)
        message_rfc822 = 1;
      else if (mu_c_strncasecmp (ws.ws_wordv[0], "TEXT", len) == 0)
        text_plain = 1;

      ws.ws_wordv[0][len++] = 0;
      p = ws.ws_wordv[0];
      io_send_qstring (p);
      io_sendf (" ");
      io_send_qstring (ws.ws_wordv[0] + len);

      /* body parameter parenthesized list: Content-type attributes */
      if (ws.ws_wordc > 1)
	{
	  int space = 0;
	  char *lvalue = NULL;
	  int i;
	  
	  io_sendf (" (");
	  for (i = 1; i < ws.ws_wordc; i++)
	    {
	      /* body parameter parenthesized list:
		 Content-type parameter list. */
	      if (lvalue)
		{
		  if (space)
		    io_sendf (" ");
		  io_send_qstring (lvalue);
		  lvalue = NULL;
		  space = 1;
		}
	      
	      switch (ws.ws_wordv[i][0])
		{
		case ';':
		  continue;
		  
		case '=':
		  if (++i < ws.ws_wordc)
		    {
		      io_sendf (" ");
		      io_send_qstring (ws.ws_wordv[i]);
		    }
		  break;
		  
		default:
		  lvalue = ws.ws_wordv[i];
		}
	    }
	  
	  if (lvalue)
	    {
	      if (space)
		io_sendf (" ");
	      io_send_qstring (lvalue);
	    }

	  io_sendf (")");
	}
      else
	io_sendf (" NIL");
      mu_wordsplit_free (&ws);
      free (buffer);
    }
  else
    {
      /* Default? If Content-Type is not present consider as text/plain.  */
      io_sendf ("\"TEXT\" \"PLAIN\" (\"CHARSET\" \"US-ASCII\")");
      text_plain = 1;
    }
  
  /* body id: Content-ID. */
  fetch_send_header_value (header, MU_HEADER_CONTENT_ID, NULL, 1);
  /* body description: Content-Description. */
  fetch_send_header_value (header, MU_HEADER_CONTENT_DESCRIPTION, NULL, 1);

  /* body encoding: Content-Transfer-Encoding. */
  fetch_send_header_value (header, MU_HEADER_CONTENT_TRANSFER_ENCODING,
			   "7BIT", 1);

  /* body size RFC822 format.  */
  {
    size_t size = 0;
    mu_body_t body = NULL;
    mu_message_get_body (msg, &body);
    mu_body_size (body, &size);
    mu_body_lines (body, &blines);
    io_sendf (" %s", mu_umaxtostr (0, size + blines));
  }

  /* If the mime type was text.  */
  if (text_plain)
    {
      /* Add the line number of the body.  */
      io_sendf (" %s", mu_umaxtostr (0, blines));
    }
  else if (message_rfc822)
    {
      size_t lines = 0;
      mu_message_t emsg = NULL;
      mu_message_unencapsulate  (msg, &emsg, NULL);
      /* Add envelope structure of the encapsulated message.  */
      io_sendf (" (");
      fetch_envelope0 (emsg);
      io_sendf (")");
      /* Add body structure of the encapsulated message.  */
      io_sendf ("(");
      fetch_bodystructure0 (emsg, extension);
      io_sendf (")");
      /* Size in text lines of the encapsulated message.  */
      mu_message_lines (emsg, &lines);
      io_sendf (" %s", mu_umaxtostr (0, lines));
      mu_message_destroy (&emsg, NULL);
    }

  if (extension)
    {
      /* body MD5: Content-MD5.  */
      fetch_send_header_value (header, MU_HEADER_CONTENT_MD5, NULL, 1);

      /* body disposition: Content-Disposition.  */
      fetch_send_header_list (header, MU_HEADER_CONTENT_DISPOSITION, NULL, 1);

      /* body language: Content-Language.  */
      fetch_send_header_value (header, MU_HEADER_CONTENT_LANGUAGE, NULL, 1);
    }
  return RESP_OK;
}

/* The beef BODYSTRUCTURE.
   A parenthesized list that describes the [MIME-IMB] body structure of a
   message. Multiple parts are indicated by parenthesis nesting.  Instead of
   a body type as the first element of the parenthesized list there is a nested
   body.  The second element of the parenthesized list is the multipart
   subtype (mixed, digest, parallel, alternative, etc.).

   The extension data of a multipart body part are in the following order:
   body parameter parenthesized list:
   A parenthesized list of attribute/value pairs [e.g. ("foo" "bar" "baz"
   "rag") where "bar" is the value of "foo" and "rag" is the value of
   "baz"] as defined in [MIME-IMB].

   body disposition:
   A parenthesized list, consisting of a disposition type string followed by a
   parenthesized list of disposition attribute/value pairs.  The disposition
   type and attribute names will be defined in a future standards-track
   revision to [DISPOSITION].

   body language:
   A string or parenthesized list giving the body language value as defined
   in [LANGUAGE-TAGS].  */
static int
fetch_bodystructure0 (mu_message_t message, int extension)
{
  size_t nparts = 1;
  size_t i;
  int is_multipart = 0;

  mu_message_is_multipart (message, &is_multipart);
  if (is_multipart)
    {
      char *buffer = NULL;
      mu_header_t header = NULL;

      mu_message_get_num_parts (message, &nparts);

      /* Get all the sub messages.  */
      for (i = 1; i <= nparts; i++)
        {
          mu_message_t msg = NULL;
          mu_message_get_part (message, i, &msg);
          io_sendf ("(");
          fetch_bodystructure0 (msg, extension);
          io_sendf (")");
        } /* for () */

      mu_message_get_header (message, &header);

      /* The subtype.  */
      if (mu_header_aget_value (header, MU_HEADER_CONTENT_TYPE, &buffer) == 0)
	{
	  struct mu_wordsplit ws;
	  char *s;

	  ws.ws_delim = " \t\r\n;=";
	  ws.ws_alloc_die = imap4d_ws_alloc_die;
	  if (mu_wordsplit (buffer, &ws, IMAP4D_WS_FLAGS))
	    {
	      mu_error (_("%s failed: %s"), "mu_wordsplit",
			mu_wordsplit_strerror (&ws));
	      return RESP_BAD; /* FIXME: a better error handling, maybe? */
	    }

	  s = strchr (ws.ws_wordv[0], '/');
	  if (s)
	    s++;
	  io_sendf (" ");
	  io_send_qstring (s);

	  /* The extension data for multipart. */
	  if (extension)
	    {
	      int space = 0;
	      char *lvalue = NULL;
	      
	      io_sendf (" (");
	      for (i = 1; i < ws.ws_wordc; i++)
		{
		  /* body parameter parenthesized list:
		     Content-type parameter list. */
		  if (lvalue)
		    {
		      if (space)
			io_sendf (" ");
		      io_send_qstring (lvalue);
		      lvalue = NULL;
		      space = 1;
		    }

		  switch (ws.ws_wordv[i][0])
		    {
		    case ';':
		      continue;
		      
		    case '=':
		      if (++i < ws.ws_wordc)
			{
			  io_sendf (" ");
			  io_send_qstring (ws.ws_wordv[i]);
			}
		      break;
		      
		    default:
		      lvalue = ws.ws_wordv[i];
		    }
		}
	      if (lvalue)
		{
		  if (space)
		    io_sendf (" ");
		  io_send_qstring (lvalue);
		}
	      io_sendf (")");
	    }
	  else
	    io_sendf (" NIL");
	  mu_wordsplit_free (&ws);
          free (buffer);
	}
      else
	/* No content-type header */
	io_sendf (" NIL");

      /* body disposition: Content-Disposition.  */
      fetch_send_header_list (header, MU_HEADER_CONTENT_DISPOSITION,
			      NULL, 1);
      /* body language: Content-Language.  */
      fetch_send_header_list (header, MU_HEADER_CONTENT_LANGUAGE,
			      NULL, 1);
    }
  else
    bodystructure (message, extension);
  return RESP_OK;
}

static void
set_seen (struct fetch_function_closure *ffc,
	  struct fetch_runtime_closure *frt)
{
  if (!ffc->peek)
    {
      mu_attribute_t attr = NULL;
      mu_message_get_attribute (frt->msg, &attr);
      if (!mu_attribute_is_read (attr))
	{
	  io_sendf ("FLAGS (\\Seen) ");
	  mu_attribute_set_read (attr);
	}
    }
}

static mu_message_t 
fetch_get_part (struct fetch_function_closure *ffc,
		struct fetch_runtime_closure *frt)
{
  mu_message_t msg = frt->msg;
  size_t i;

  for (i = 0; i < ffc->nset; i++)
    if (mu_message_get_part (msg, ffc->section_part[i], &msg))
      return NULL;
  return msg;
}

/* FIXME: This is a KLUDGE.

   There is so far no way to unref the MU elements being used to construct
   a certain entity when this entity itself is being destroyed.  In particular,
   retrieving a nested message/rfc822 part involves creating several messages
   while unencapsulating, which messages should be unreferenced when the
   topmost one is destroyed.

   A temporary solution used here is to keep a list of such messages and
   unreference them together with the topmost one when no longer needed.
   A message is added to the list by frt_register_message().  All messages
   in the list are unreferenced by calling frt_unregister_messages().

   The proper solution is of course providing a way for mu_message_t (and
   other MU objects) to unreference its parent elements.  This should be fixed
   in later releases.
 */

static void
_unref_message_item (void *data)
{
  mu_message_unref ((mu_message_t)data);
}

static int
frt_register_message (struct fetch_runtime_closure *frt, mu_message_t msg)
{
  if (!frt->msglist)
    {
      int rc = mu_list_create (&frt->msglist);
      if (rc)
	return rc;
      mu_list_set_destroy_item (frt->msglist, _unref_message_item);
    }
  return mu_list_append (frt->msglist, msg);
}

static void
frt_unregister_messages (struct fetch_runtime_closure *frt)
{
  mu_list_clear (frt->msglist);
}

static mu_message_t 
fetch_get_part_rfc822 (struct fetch_function_closure *ffc,
		       struct fetch_runtime_closure *frt)
{
  mu_message_t msg = frt->msg, retmsg = NULL;
  size_t i;
  mu_header_t header;
  const char *hval;
  
  if (ffc->nset == 0)
    {
      mu_message_ref (msg);
      return msg;
    }
  
  for (i = 0; i < ffc->nset; i++)
    {
      if (mu_message_get_part (msg, ffc->section_part[i], &msg))
	return NULL;

      if (mu_message_get_header (msg, &header))
	return NULL;
  
      if (mu_header_sget_value (header, MU_HEADER_CONTENT_TYPE, &hval) == 0)
	{
	  struct mu_wordsplit ws;
	  int rc;
      
	  ws.ws_delim = " \t\r\n;=";
	  ws.ws_alloc_die = imap4d_ws_alloc_die;
	  if (mu_wordsplit (hval, &ws, IMAP4D_WS_FLAGS))
	    {
	      mu_error (_("%s failed: %s"), "mu_wordsplit",
			mu_wordsplit_strerror (&ws));
	      return NULL;
	    }

	  rc = mu_c_strcasecmp (ws.ws_wordv[0], "MESSAGE/RFC822");
	  mu_wordsplit_free (&ws);

	  if (rc == 0)
	    {
	      rc = mu_message_unencapsulate  (msg, &retmsg, NULL);
	      if (rc)
		{
		  mu_error (_("%s failed: %s"), "mu_message_unencapsulate",
			    mu_strerror (rc));
		  return NULL;
		}
	      if (frt_register_message (frt, retmsg))
		{
		  frt_unregister_messages (frt);
		  return NULL;
		}
	      msg = retmsg;
	    }
	}
    }
  
  return retmsg;
}

static void
fetch_send_section_part (struct fetch_function_closure *ffc,
                         const char *suffix, int close_bracket)
{
  int i;
  
  io_sendf ("BODY[");
  for (i = 0; i < ffc->nset; i++)
    {
      if (i)
	io_sendf (".");
      io_sendf ("%lu",  (unsigned long) ffc->section_part[i]);
    }
  if (suffix)
    {
      if (i)
	io_sendf (".");
      io_sendf ("%s", suffix);
    }
  if (close_bracket)
    io_sendf ("]");
}

static int
fetch_io (mu_stream_t stream, size_t start, size_t size, size_t max)
{
  mu_stream_t rfc = NULL;
  
  size_t n = 0;

  mu_filter_create (&rfc, stream, "CRLF", MU_FILTER_ENCODE,
		    MU_STREAM_READ|MU_STREAM_SEEK);
  
  if (start == 0 && size == (size_t) -1)
    {
      int rc;
      
      rc = mu_stream_seek (rfc, 0, MU_SEEK_SET, NULL);
      if (rc)
	{
	  mu_error ("seek error: %s", mu_stream_strerror (stream, rc));
	  return RESP_BAD;
	}
      if (max)
	{
	  io_sendf (" {%lu}\n", (unsigned long) max);
	  io_copy_out (rfc, max);
	  /* FIXME: Make sure exactly max bytes were sent */
	}
      else
	io_sendf (" \"\"");
    }
  else if (start > max)
    {
      io_sendf ("<%lu>", (unsigned long) start);
      io_sendf (" \"\"");
    }
  else
    {
      int rc;
      char *buffer, *p;
      size_t total = 0;

      if (size > max)
	size = max;
      if (size + 2 < size) /* Check for integer overflow */
	{
	  mu_stream_destroy (&rfc);
	  return RESP_BAD;
	}
      
      p = buffer = mu_alloc (size + 1);

      rc = mu_stream_seek (rfc, start, MU_SEEK_SET, NULL);
      if (rc)
	{
	  mu_error ("seek error: %s", mu_stream_strerror (rfc, rc));
	  free (buffer);
	  mu_stream_destroy (&rfc);
	  return RESP_BAD;
	}

      while (total < size
	     && mu_stream_read (rfc, p, size - total, &n) == 0
	     && n > 0)
	{
	  total += n;
	  p += n;
	}
      *p = 0;
      io_sendf ("<%lu>", (unsigned long) start);
      if (total)
	{
	  io_sendf (" {%lu}\n", (unsigned long) total);
	  io_send_bytes (buffer, total);
	}
      else
	io_sendf (" \"\"");
      free (buffer);
    }
  mu_stream_destroy (&rfc);
  return RESP_OK;
}


/* Runtime functions */
static int
_frt_uid (struct fetch_function_closure *ffc,
	  struct fetch_runtime_closure *frt)
{
  size_t uid = 0;

  mu_message_get_uid (frt->msg, &uid);
  io_sendf ("%s %s", ffc->name, mu_umaxtostr (0, uid));
  return RESP_OK;
}

static int
_frt_envelope (struct fetch_function_closure *ffc,
	       struct fetch_runtime_closure *frt)
{
  io_sendf ("%s (", ffc->name);
  fetch_envelope0 (frt->msg);
  io_sendf (")");
  return RESP_OK;
}

static int
_frt_flags (struct fetch_function_closure *ffc,
	    struct fetch_runtime_closure *frt)
{
  mu_attribute_t attr = NULL;

  mu_message_get_attribute (frt->msg, &attr);
  io_sendf ("%s (", ffc->name);
  util_print_flags (attr);
  io_sendf (")");
  return 0;
}

/* INTERNALDATE   The internal date of the message.
   Format:

   date_time       ::= <"> date_day_fixed "-" date_month "-" date_year
   SPACE time SPACE zone <">

   date_day        ::= 1*2digit
   ;; Day of month

   date_day_fixed  ::= (SPACE digit) / 2digit
   ;; Fixed-format version of date_day

   date_month      ::= "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" /
   "Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec"

   date_text       ::= date_day "-" date_month "-" date_year

   date_year       ::= 4digit

   time            ::= 2digit ":" 2digit ":" 2digit
   ;; Hours minutes seconds

   zone            ::= ("+" / "-") 4digit
   ;; Signed four-digit value of hhmm representing
   ;; hours and minutes west of Greenwich (that is,
   ;; (the amount that the given time differs from
   ;; Universal Time).  Subtracting the timezone
   ;; from the given time will give the UT form.
   ;; The Universal Time zone is "+0000".  */
static int
_frt_internaldate (struct fetch_function_closure *ffc,
		   struct fetch_runtime_closure *frt)
{
  const char *date;
  mu_envelope_t env = NULL;
  struct tm tm, *tmp = NULL;
  struct mu_timezone tz;
  
  mu_message_get_envelope (frt->msg, &env);
  if (mu_envelope_sget_date (env, &date) == 0
      && mu_scan_datetime (date, MU_DATETIME_FROM, &tm, &tz, NULL) == 0)
    {
      tmp = &tm;
    }
  else
    {
      time_t t;
      struct timeval stv;
      struct timezone stz;
      
      gettimeofday (&stv, &stz);
      t = stv.tv_sec;
      tz.utc_offset = - stz.tz_minuteswest;
      tmp = localtime (&t);
    }
  io_sendf ("%s", ffc->name);
  mu_c_streamftime (iostream, " \"%d-%b-%Y %H:%M:%S %z\"", tmp, &tz);
  return 0;
}

static int
_frt_bodystructure (struct fetch_function_closure *ffc,
		    struct fetch_runtime_closure *frt)
{
  io_sendf ("%s (", ffc->name);
  fetch_bodystructure0 (frt->msg, 1); /* 1 means with extension data.  */
  io_sendf (")");
  return RESP_OK;
}

static int
_frt_bodystructure0 (struct fetch_function_closure *ffc,
		     struct fetch_runtime_closure *frt)
{
  io_sendf ("%s (", ffc->name);
  fetch_bodystructure0 (frt->msg, 0);
  io_sendf (")");
  return RESP_OK;
}

/* BODY[] */
static int
_frt_body (struct fetch_function_closure *ffc,
	   struct fetch_runtime_closure *frt)
{
  mu_message_t msg = frt->msg;
  mu_stream_t stream = NULL;
  size_t size = 0, lines = 0;
  int rc;
  
  set_seen (ffc, frt);
  if (ffc->name)
    io_sendf ("%s", ffc->name);
  else
    fetch_send_section_part (ffc, NULL, 1);
  mu_message_get_streamref (msg, &stream);
  mu_message_size (msg, &size);
  mu_message_lines (msg, &lines);
  rc = fetch_io (stream, ffc->start, ffc->size, size + lines);
  mu_stream_destroy (&stream);
  return rc;
}

/* BODY[N] */
static int
_frt_body_n (struct fetch_function_closure *ffc,
	     struct fetch_runtime_closure *frt)
{
  mu_message_t msg;
  mu_body_t body = NULL;
  mu_stream_t stream = NULL;
  size_t size = 0, lines = 0;
  int rc;
  
  set_seen (ffc, frt);
  if (ffc->name)
    io_sendf ("%s",  ffc->name);
  else
    fetch_send_section_part (ffc, ffc->section_tag, 1);
  msg = fetch_get_part (ffc, frt);
  if (!msg)
    {
      io_sendf (" NIL");
      return RESP_OK;
    }

  mu_message_get_body (msg, &body);
  mu_body_size (body, &size);
  mu_body_lines (body, &lines);
  mu_body_get_streamref (body, &stream);
  rc = fetch_io (stream, ffc->start, ffc->size, size + lines);
  mu_stream_destroy (&stream);

  return rc;
}

static int
_frt_body_text (struct fetch_function_closure *ffc,
		struct fetch_runtime_closure *frt)
{
  mu_message_t msg;
  mu_body_t body = NULL;
  mu_stream_t stream = NULL;
  size_t size = 0, lines = 0;
  int rc;
  
  set_seen (ffc, frt);
  if (ffc->name)
    io_sendf ("%s",  ffc->name);
  else
    fetch_send_section_part (ffc, ffc->section_tag, 1);
  msg = fetch_get_part_rfc822 (ffc, frt);
  if (!msg)
    {
      io_sendf (" NIL");
      return RESP_OK;
    }

  mu_message_get_body (msg, &body);
  mu_body_size (body, &size);
  mu_body_lines (body, &lines);
  mu_body_get_streamref (body, &stream);
  rc = fetch_io (stream, ffc->start, ffc->size, size + lines);
  mu_stream_destroy (&stream);
  frt_unregister_messages (frt);
  return rc;
}

static int
_frt_size (struct fetch_function_closure *ffc,
	   struct fetch_runtime_closure *frt)
{
  size_t size = 0;
  size_t lines = 0;
  
  mu_message_size (frt->msg, &size);
  mu_message_lines (frt->msg, &lines);
  io_sendf ("%s %lu", ffc->name, (unsigned long) (size + lines));
  return RESP_OK;
}

static int
_frt_header (struct fetch_function_closure *ffc,
	     struct fetch_runtime_closure *frt)
{
  mu_message_t msg;
  mu_header_t header = NULL;
  mu_stream_t stream = NULL;
  size_t size = 0, lines = 0;
  int rc;
  
  set_seen (ffc, frt);
  if (ffc->name)
    io_sendf ("%s",  ffc->name);
  else
    fetch_send_section_part (ffc, ffc->section_tag, 1);

  msg = fetch_get_part_rfc822 (ffc, frt);
  if (!msg)
    {
      io_sendf (" NIL");
      return RESP_OK;
    }
  mu_message_get_header (msg, &header);
  mu_header_size (header, &size);
  mu_header_lines (header, &lines);
  mu_header_get_streamref (header, &stream);
  rc = fetch_io (stream, ffc->start, ffc->size, size + lines);
  mu_stream_destroy (&stream);
  frt_unregister_messages (frt);
  return rc;
}

static int
_frt_mime (struct fetch_function_closure *ffc,
	     struct fetch_runtime_closure *frt)
{
  mu_message_t msg;
  mu_header_t header = NULL;
  mu_stream_t stream = NULL;
  size_t size = 0, lines = 0;
  int rc;
  
  set_seen (ffc, frt);
  if (ffc->name)
    io_sendf ("%s",  ffc->name);
  else
    fetch_send_section_part (ffc, ffc->section_tag, 1);

  msg = fetch_get_part (ffc, frt);
  if (!msg)
    {
      io_sendf (" NIL");
      return RESP_OK;
    }
  mu_message_get_header (msg, &header);
  mu_header_size (header, &size);
  mu_header_lines (header, &lines);
  mu_header_get_streamref (header, &stream);
  rc = fetch_io (stream, ffc->start, ffc->size, size + lines);
  mu_stream_destroy (&stream);

  return rc;
}

static int
_send_header_name (void *item, void *data)
{
  int *pf = data;
  if (*pf)
    io_sendf (" ");
  else
    *pf = 1;
  io_sendf ("%s", (char*) item);
  return 0;
}

static int
count_nl (const char *str)
{
  int n = 0;
  for (;(str = strchr (str, '\n')); str++)
    n++;
  return n;
}

static int
_frt_header_fields (struct fetch_function_closure *ffc,
		    struct fetch_runtime_closure *frt)
{
  int status;
  mu_message_t msg;
  mu_off_t size = 0;
  size_t lines = 0;
  mu_stream_t stream;
  mu_header_t header;
  mu_iterator_t itr;
  
  set_seen (ffc, frt);

  fetch_send_section_part (ffc, "HEADER.FIELDS", 0);
  if (ffc->not)
    io_sendf (".NOT");
  io_sendf (" (");
  status = 0;
  mu_list_foreach (ffc->headers, _send_header_name, &status);
  io_sendf (")]");
  
  msg = fetch_get_part_rfc822 (ffc, frt);
  if (!msg)
    {
      io_sendf (" NIL");
      return RESP_OK;
    }

  /* Collect headers: */
  if (mu_message_get_header (msg, &header)
      || mu_header_get_iterator (header, &itr))
    {
      frt_unregister_messages (frt);
      io_sendf (" NIL");
      return RESP_OK;
    }

  status = mu_memory_stream_create (&stream, 0);
  if (status != 0)
    imap4d_bye (ERR_NO_MEM);

  for (mu_iterator_first (itr);
       !mu_iterator_is_done (itr); mu_iterator_next (itr))
    {
      const char *hf;
      char *hv;
      const char *item;
      
      mu_iterator_current_kv (itr, (const void **)&hf, (void **)&hv);
      status = mu_list_locate (ffc->headers, (void *)hf, (void**) &item) == 0;
      if (ffc->not)
	{
	  status = !status;
	  item = hf;
	}
      
      if (status)
	{
	  mu_stream_printf (stream, "%s: %s\n", item, hv);
	  lines += 1 + count_nl (hv);
	}
    }
  mu_iterator_destroy (&itr);
  mu_stream_write (stream, "\n", 1, NULL);
  lines++;
  
  /* Output collected data */
  mu_stream_size (stream, &size);
  mu_stream_seek (stream, 0, MU_SEEK_SET, NULL);
  status = fetch_io (stream, ffc->start, ffc->size, size + lines);
  mu_stream_destroy (&stream);
  frt_unregister_messages (frt);
  
  return status;
}


static void
ffc_init (struct fetch_function_closure *ffc)
{
  memset(ffc, 0, sizeof *ffc);
  ffc->start = 0;
  ffc->size = (size_t) -1;
}

static void
_free_ffc (void *item)
{
  struct fetch_function_closure *ffc = item;
  mu_list_destroy (&ffc->headers);
  free (ffc);
}

static int
_do_fetch (void *item, void *data)
{
  struct fetch_function_closure *ffc = item;
  struct fetch_runtime_closure *frt = data;
  if (frt->eltno++)
    io_sendf (" ");
  return ffc->fun (ffc, frt);
}

static void
append_ffc (struct fetch_parse_closure *p, struct fetch_function_closure *ffc)
{
  struct fetch_function_closure *new_ffc = mu_alloc (sizeof (*new_ffc));
  *new_ffc = *ffc;
  mu_list_append (p->fnlist, new_ffc);
}

static void
append_simple_function (struct fetch_parse_closure *p, const char *name,
			fetch_function_t fun)
{
  struct fetch_function_closure ffc;
  ffc_init (&ffc);
  ffc.fun = fun;
  ffc.name = name;
  append_ffc (p, &ffc);
}


static struct fetch_macro
{
  char *macro;
  char *exp;
} fetch_macro_tab[] = {
  { "ALL",  "FLAGS INTERNALDATE RFC822.SIZE ENVELOPE" },
  { "FULL", "FLAGS INTERNALDATE RFC822.SIZE ENVELOPE BODY" },
  { "FAST", "FLAGS INTERNALDATE RFC822.SIZE" },
  { NULL }
};

static char *
find_macro (const char *name)
{
  int i;
  for (i = 0; fetch_macro_tab[i].macro; i++)
    if (mu_c_strcasecmp (fetch_macro_tab[i].macro, name) == 0)
      return fetch_macro_tab[i].exp;
  return NULL;
}


struct fetch_att_tab
{
  char *name;
  fetch_function_t fun;
};

static struct fetch_att_tab fetch_att_tab[] = {
  { "ENVELOPE", _frt_envelope },
  { "FLAGS", _frt_flags },
  { "INTERNALDATE", _frt_internaldate },
  { "UID", _frt_uid },
  { NULL }
};

static struct fetch_att_tab *
find_fetch_att_tab (char *name)
{
  struct fetch_att_tab *p;
  for (p = fetch_att_tab; p->name; p++)
    if (mu_c_strcasecmp (p->name, name) == 0)
      return p;
  return NULL;
}

/*
fetch-att       = "ENVELOPE" / "FLAGS" / "INTERNALDATE" /
                  "RFC822" [".HEADER" / ".SIZE" / ".TEXT"] /
                  "BODY" ["STRUCTURE"] / "UID" /
                  "BODY" section ["<" number "." nz-number ">"] /
                  "BODY.PEEK" section ["<" number "." nz-number ">"]

*/

/*  "RFC822" [".HEADER" / ".SIZE" / ".TEXT"]  */
static void
parse_fetch_rfc822 (imap4d_parsebuf_t p)
{
  struct fetch_function_closure ffc;
  ffc_init (&ffc);
  ffc.name = "RFC822";
  imap4d_parsebuf_next (p, 0);
  if (p->token == NULL || p->token[0] == ')') 
    {
      /* Equivalent to BODY[]. */
      ffc.fun = _frt_body;
    }
  else if (p->token[0] == '.')
    {
      imap4d_parsebuf_next (p, 1);
      if (mu_c_strcasecmp (p->token, "HEADER") == 0)
	{
	  /* RFC822.HEADER
	     Equivalent to BODY[HEADER].  Note that this did not result in
	     \Seen being set, because RFC822.HEADER response data occurs as
	     a result of a FETCH of RFC822.HEADER.  BODY[HEADER] response
	     data occurs as a result of a FETCH of BODY[HEADER] (which sets
	     \Seen) or BODY.PEEK[HEADER] (which does not set \Seen). */

	  ffc.name = "RFC822.HEADER";
	  ffc.fun = _frt_header;
	  ffc.peek = 1;
	  imap4d_parsebuf_next (p, 0);
	}
      else if (mu_c_strcasecmp (p->token, "SIZE") == 0)
	{
	  /* A number expressing the [RFC-2822] size of the message. */
	  ffc.name = "RFC822.SIZE";
	  ffc.fun = _frt_size;
	  imap4d_parsebuf_next (p, 0);
	}
      else if (mu_c_strcasecmp (p->token, "TEXT") == 0)
	{
	  /* RFC822.TEXT
	     Equivalent to BODY[TEXT]. */
	  ffc.name = "RFC822.TEXT";
	  ffc.fun = _frt_body_text;
	  imap4d_parsebuf_next (p, 0);
	}
      else
	imap4d_parsebuf_exit (p, "Syntax error after RFC822.");
    }
  else
    imap4d_parsebuf_exit (p, "Syntax error after RFC822");
  append_ffc (imap4d_parsebuf_data (p), &ffc);
}

static int
_header_cmp (const void *a, const void *b)
{
  return mu_c_strcasecmp ((char*)a, (char*)b);
}

/*
header-fld-name = astring

header-list     = "(" header-fld-name *(SP header-fld-name) ")"
*/
static void
parse_header_list (imap4d_parsebuf_t p, struct fetch_function_closure *ffc)
{
  if (!(p->token && p->token[0] == '('))
    imap4d_parsebuf_exit (p, "Syntax error: expected (");
  mu_list_create (&ffc->headers);
  mu_list_set_comparator (ffc->headers, _header_cmp);
  for (imap4d_parsebuf_next (p, 1); p->token[0] != ')'; imap4d_parsebuf_next (p, 1))
    {
      if (p->token[1] == 0 && strchr ("()[]<>.", p->token[0]))
	imap4d_parsebuf_exit (p, "Syntax error: unexpected delimiter");
      mu_list_append (ffc->headers, p->token);
    }
  imap4d_parsebuf_next (p, 1);
}

/*
section-msgtext = "HEADER" / "HEADER.FIELDS" [".NOT"] SP header-list /
                  "TEXT"
                    ; top-level or MESSAGE/RFC822 part
section-text    = section-msgtext / "MIME"
                    ; text other than actual body part (headers, etc.)
*/  
static int
parse_section_text (imap4d_parsebuf_t p, struct fetch_function_closure *ffc,
		    int allow_mime)
{
  if (mu_c_strcasecmp (p->token, "HEADER") == 0)
    {
      /* "HEADER" / "HEADER.FIELDS" [".NOT"] SP header-list  */
      imap4d_parsebuf_next (p, 1);
      if (p->token[0] == '.')
	{
	  imap4d_parsebuf_next (p, 1);
	  if (mu_c_strcasecmp (p->token, "FIELDS"))
	    imap4d_parsebuf_exit (p, "Expected FIELDS");
	  ffc->fun = _frt_header_fields;
	  imap4d_parsebuf_next (p, 1);
	  if (p->token[0] == '.')
	    {
	      imap4d_parsebuf_next (p, 1);
	      if (mu_c_strcasecmp (p->token, "NOT") == 0)
		{
		  ffc->not = 1;
		  imap4d_parsebuf_next (p, 1);
		}
	      else
		imap4d_parsebuf_exit (p, "Expected NOT");
	    }
	  parse_header_list (p, ffc);
	}
      else
	{
	  ffc->fun = _frt_header;
	  ffc->section_tag = "HEADER";
	}
    }
  else if (mu_c_strcasecmp (p->token, "TEXT") == 0)
    {
      imap4d_parsebuf_next (p, 1);
      ffc->fun = _frt_body_text;
      ffc->section_tag = "TEXT";
    }
  else if (allow_mime && mu_c_strcasecmp (p->token, "MIME") == 0)
    {
      imap4d_parsebuf_next (p, 1);
      ffc->fun = _frt_mime;
      ffc->section_tag = "MIME";
    }
  else
    return 1;
 return 0;
}

static size_t
parsebuf_get_number (imap4d_parsebuf_t p)
{
  char *cp;
  unsigned long n = strtoul (p->token, &cp, 10);

  if (*cp)
    imap4d_parsebuf_exit (p, "Syntax error: expected number");
  return n;
}
    
/*
section-part    = nz-number *("." nz-number)
                    ; body part nesting
*/  
static void
parse_section_part (imap4d_parsebuf_t p, struct fetch_function_closure *ffc)
{
  size_t *parts;
  size_t nmax = 0;
  size_t ncur = 0;

  for (;;)
    {
      char *cp;
      size_t n = parsebuf_get_number (p);
      if (ncur == nmax)
	{
	  if (nmax == 0)
	    {
	      nmax = 16;
	      parts = calloc (nmax, sizeof (parts[0]));
	    }
	  else
	    {
	      nmax *= 2;
	      parts = realloc (parts, nmax * sizeof (parts[0]));
	    }
	  if (!parts)
	    imap4d_bye (ERR_NO_MEM);
	}
      parts[ncur++] = n;

      imap4d_parsebuf_next (p, 1);
      
      if (p->token[0] == '.'
	  && (cp = imap4d_parsebuf_peek (p))
	  && mu_isdigit (*cp))
	imap4d_parsebuf_next (p, 1);
      else
	break;
    }
  ffc->section_part = parts;
  ffc->nset = ncur;
}
  
/*
section         = "[" [section-spec] "]"
section-spec    = section-msgtext / (section-part ["." section-text])
*/  
static int
parse_section (imap4d_parsebuf_t p, struct fetch_function_closure *ffc)
{
  if (p->token[0] != '[')
    return 1;
  ffc_init (ffc);
  ffc->name = NULL;
  ffc->fun = _frt_body_text;
  imap4d_parsebuf_next (p, 1);
  if (parse_section_text (p, ffc, 0))
    {
      if (p->token[0] == ']')
	ffc->fun = _frt_body;
      else if (mu_isdigit (p->token[0]))
	{
	  parse_section_part (p, ffc);
	  if (p->token[0] == '.')
	    {
	      imap4d_parsebuf_next (p, 1);
	      parse_section_text (p, ffc, 1);
	    }
	  else
	    ffc->fun = _frt_body_n;
	}
      else
	imap4d_parsebuf_exit (p, "Syntax error");
    }
  if (p->token[0] != ']')
    imap4d_parsebuf_exit (p, "Syntax error: missing ]");
  imap4d_parsebuf_next (p, 0);
  return 0;
}

static void
parse_substring (imap4d_parsebuf_t p, struct fetch_function_closure *ffc)
{
  if (p->token && p->token[0] == '<')
    {
      imap4d_parsebuf_next (p, 1);
      ffc->start = parsebuf_get_number (p);
      imap4d_parsebuf_next (p, 1);
      if (p->token[0] != '.')
	imap4d_parsebuf_exit (p, "Syntax error: expected .");
      imap4d_parsebuf_next (p, 1);
      ffc->size = parsebuf_get_number (p);
      imap4d_parsebuf_next (p, 1);
      if (p->token[0] != '>')
	imap4d_parsebuf_exit (p, "Syntax error: expected >");
      imap4d_parsebuf_next (p, 0);
    }
}
	
/* section ["<" number "." nz-number ">"]  */
static int
parse_body_args (imap4d_parsebuf_t p, int peek)
{
  struct fetch_function_closure ffc;
  if (parse_section (p, &ffc) == 0)
    {
      parse_substring (p, &ffc);
      ffc.peek = peek;
      append_ffc (imap4d_parsebuf_data (p), &ffc);
      return 0;
    }
  return 1;
}

static void
parse_body_peek (imap4d_parsebuf_t p)
{
  imap4d_parsebuf_next (p, 1);
  if (mu_c_strcasecmp (p->token, "PEEK") == 0)
    {
      imap4d_parsebuf_next (p, 1);
      if (parse_body_args (p, 1))
	imap4d_parsebuf_exit (p, "Syntax error");
    }
  else
    imap4d_parsebuf_exit (p, "Syntax error: expected PEEK");
}

/*  "BODY" ["STRUCTURE"] / 
    "BODY" section ["<" number "." nz-number ">"] /
    "BODY.PEEK" section ["<" number "." nz-number ">"] */
static void
parse_fetch_body (imap4d_parsebuf_t p)
{
  if (imap4d_parsebuf_next (p, 0) == NULL || p->token[0] == ')')
    append_simple_function (imap4d_parsebuf_data (p),
			    "BODY", _frt_bodystructure0);
  else if (p->token[0] == '.')
    parse_body_peek (p);
  else if (mu_c_strcasecmp (p->token, "STRUCTURE") == 0)
    {
      /* For compatibility with previous versions */
      append_simple_function (imap4d_parsebuf_data (p),
			      "BODYSTRUCTURE", _frt_bodystructure);
      imap4d_parsebuf_next (p, 0);
    }
  else if (parse_body_args (p, 0))
    append_simple_function (imap4d_parsebuf_data (p),
			    "BODY", _frt_bodystructure0);
}

static int
parse_fetch_att (imap4d_parsebuf_t p)
{
  struct fetch_att_tab *ent;
  struct fetch_parse_closure *pclos = imap4d_parsebuf_data (p);
  
  ent = find_fetch_att_tab (p->token);
  if (ent)
    {
      if (!(ent->fun == _frt_uid && pclos->isuid))
	append_simple_function (pclos, ent->name, ent->fun);
      imap4d_parsebuf_next (p, 0);
    }
  else if (mu_c_strcasecmp (p->token, "RFC822") == 0)
    parse_fetch_rfc822 (p);
  else if (mu_c_strcasecmp (p->token, "BODY") == 0)
    parse_fetch_body (p);
  else if (mu_c_strcasecmp (p->token, "BODYSTRUCTURE") == 0)
    {
      append_simple_function (pclos, "BODYSTRUCTURE", _frt_bodystructure);
      imap4d_parsebuf_next (p, 0);
    }
  else
    return 1;
  return 0;
}

/* fetch-att *(SP fetch-att) */
static void
parse_fetch_att_list (imap4d_parsebuf_t p)
{
  while (p->token && parse_fetch_att (p) == 0)
    ;
}

/* "ALL" / "FULL" / "FAST" / fetch-att / "(" */
static void
parse_macro (imap4d_parsebuf_t p)
{  
  char *exp;
  
  imap4d_parsebuf_next (p, 1);
  if (p->token[0] == '(')
    {
      imap4d_parsebuf_next (p, 1);
      parse_fetch_att_list (p);
      if (!(p->token && p->token[0] == ')'))
	imap4d_parsebuf_exit (p, "Unknown token or missing closing parenthesis");
    }
  else if ((exp = find_macro (p->token))) 
    {
      imap4d_tokbuf_t save_tok = p->tok;
      int save_arg = p->arg;
      p->tok = imap4d_tokbuf_from_string (exp);
      p->arg = 0;
      imap4d_parsebuf_next (p, 1);
      parse_fetch_att_list (p);
      imap4d_tokbuf_destroy (&p->tok);
  
      p->arg = save_arg;
      p->tok = save_tok;

      if (imap4d_parsebuf_peek (p))
	imap4d_parsebuf_exit (p, "Too many arguments");
    }     
  else
    {
      parse_fetch_att (p);
      if (p->token)
	imap4d_parsebuf_exit (p, "Too many arguments");
    }
}
    

static int
fetch_thunk (imap4d_parsebuf_t pb)
{
  int status;
  char *mstr;
  char *end;
  struct fetch_parse_closure *pclos = imap4d_parsebuf_data (pb);
  
  mstr = imap4d_parsebuf_next (pb, 1);

  status = mu_msgset_create (&pclos->msgset, mbox, MU_MSGSET_NUM);
  if (status)
    imap4d_parsebuf_exit (pb, "Software error");
  
  /* Parse sequence numbers. */
  status = mu_msgset_parse_imap (pclos->msgset,
				 pclos->isuid ? MU_MSGSET_UID : MU_MSGSET_NUM,
				 mstr, &end);
  if (status)
    imap4d_parsebuf_exit (pb, "Failed to parse message set");
  
  /* Compile the expression */

  /* Server implementations MUST implicitly
     include the UID message data item as part of any FETCH
     response caused by a UID command, regardless of whether
     a UID was specified as a message data item to the FETCH. */
  if (pclos->isuid)
    append_simple_function (pclos, "UID", _frt_uid);

  parse_macro (pb);
  return RESP_OK;
}

int
_fetch_from_message (size_t msgno, mu_message_t msg, void *data)
{
  int rc = 0;
  struct fetch_runtime_closure *frc = data;

  frc->msgno = msgno;
  frc->msg = msg;

  io_sendf ("* %lu FETCH (", (unsigned long) msgno);
  frc->eltno = 0;
  rc = mu_list_foreach (frc->fnlist, _do_fetch, frc);
  io_sendf (")\n");

  return rc;
}

/* Where the real implementation is.  It is here since UID command also
   calls FETCH.  */
int
imap4d_fetch0 (imap4d_tokbuf_t tok, int isuid, char **err_text)
{
  int rc;
  struct fetch_parse_closure pclos;
  
  if (imap4d_tokbuf_argc (tok) - (IMAP4_ARG_1 + isuid) < 2)
    {
      *err_text = "Invalid arguments";
      return 1;
    }

  memset (&pclos, 0, sizeof (pclos));
  pclos.isuid = isuid;
  mu_list_create (&pclos.fnlist);
  mu_list_set_destroy_item (pclos.fnlist, _free_ffc);
  
  rc = imap4d_with_parsebuf (tok, IMAP4_ARG_1 + isuid,
			     ".[]<>",
			     fetch_thunk, &pclos,
			     err_text);

  if (rc == RESP_OK)
    {
      struct fetch_runtime_closure frc;

      memset (&frc, 0, sizeof (frc));
      frc.fnlist = pclos.fnlist;
      /* Prepare status code. It will be replaced if an error occurs in the
	 loop below */
      frc.err_text = "Completed";

      mu_msgset_foreach_message (pclos.msgset, _fetch_from_message, &frc);
      mu_list_destroy (&frc.msglist);
    }
  
  mu_list_destroy (&pclos.fnlist);
  mu_msgset_free (pclos.msgset);
  return rc;
}


/*
6.4.5.  FETCH Command

   Arguments:  message set
               message data item names

   Responses:  untagged responses: FETCH

   Result:     OK - fetch completed
               NO - fetch error: can't fetch that data
               BAD - command unknown or arguments invalid
*/

/* The FETCH command retrieves data associated with a message in the
   mailbox.  The data items to be fetched can be either a single atom
   or a parenthesized list.  */
int
imap4d_fetch (struct imap4d_session *session,
              struct imap4d_command *command, imap4d_tokbuf_t tok)
{
  int rc;
  char *err_text = "Completed";
  int xlev = set_xscript_level (MU_XSCRIPT_PAYLOAD);
  rc = imap4d_fetch0 (tok, 0, &err_text);
  set_xscript_level (xlev);
  return io_completion_response (command, rc, "%s", err_text);
}