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

#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;
  size_t msgno;
  mu_message_t msg;
  char *err_text;
};

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 */
  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 */
};

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

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

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

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

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

      util_send ("(");

      mu_address_sget_personal (address, i, &str);
      util_send_qstring (str);
      util_send (" ");

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

      util_send (" ");

      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);

      util_send_qstring (str);

      util_send (" ");

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

      util_send (")");
    }
  util_send (")");
  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)
    util_send (" ");
  if (mu_header_aget_value (header, name, &buffer) == 0)
    {
      util_send_qstring (buffer);
      free (buffer);
    }
  else if (defval)
    util_send_qstring (defval);
  else
    util_send ("NIL");
}

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

/* Send parameter list for the bodystructure.  */
static void
send_parameter_list (const char *buffer)
{
  int argc = 0;
  char **argv;
  
  if (!buffer)
    {
      util_send ("NIL");
      return;
    }

  mu_argcv_get (buffer, " \t\r\n;=", NULL, &argc, &argv);
  
  if (argc == 0)
    util_send ("NIL");
  else
    {
      char *p;
      
      util_send ("(");
        
      p = argv[0];
      util_send_qstring (p);

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

	  util_send ("(");
	  for (i = 1; i < argc; i++)
	    {
	      if (lvalue)
		{
		  if (space)
		    util_send (" ");
		  util_send_qstring (lvalue);
		  lvalue = NULL;
		  space = 1;
		}
	      
	      switch (argv[i][0])
		{
		case ';':
		  continue;
		  
		case '=':
		  if (++i < argc)
		    {
		      char *p = argv[i];
		      util_send (" ");
		      util_send_qstring (p);
		    }
		  break;
		  
		default:
		  lvalue = argv[i];
		}
	    }
	  if (lvalue)
	    {
	      if (space)
		util_send (" ");
	      util_send_qstring (lvalue);
	    }
	  util_send (")");
	}
      else
	util_send (" NIL");
      util_send (")");
    }
  mu_argcv_free (argc, argv);
}

static void
fetch_send_header_list (mu_header_t header, const char *name,
			const char *defval, int space)
{
  char *buffer;
  
  if (space)
    util_send (" ");
  if (mu_header_aget_value (header, name, &buffer) == 0)
    {
      send_parameter_list (buffer);
      free (buffer);
    }
  else if (defval)
    send_parameter_list (defval);
  else
    util_send ("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);
  util_send (" ");
  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;
}

/* 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)
    {
      int argc = 0;
      char **argv;
      char *s, *p;
	  
      mu_argcv_get (buffer, " \t\r\n;=", NULL, &argc, &argv);

      if (strcasecmp (argv[0], "MESSAGE/RFC822") == 0)
        message_rfc822 = 1;
      else if (strcasecmp (argv[0], "TEXT/PLAIN") == 0)
        text_plain = 1;

      s = strchr (argv[0], '/');
      if (s)
	*s++ = 0;
      p = argv[0];
      util_send_qstring (p);
      util_send (" ");
      util_send_qstring (s);

      /* body parameter parenthesized list: Content-type attributes */
      if (argc > 1 || text_plain)
	{
	  int space = 0;
	  char *lvalue = NULL;
	  int have_charset = 0;
	  int i;
	  
	  util_send (" (");
	  for (i = 1; i < argc; i++)
	    {
	      /* body parameter parenthesized list:
		 Content-type parameter list. */
	      if (lvalue)
		{
		  if (space)
		    util_send (" ");
		  util_send_qstring (lvalue);
		  lvalue = NULL;
		  space = 1;
		}
	      
	      switch (argv[i][0])
		{
		case ';':
		  continue;
		  
		case '=':
		  if (++i < argc)
		    {
		      char *p = argv[i];
		      util_send (" ");
		      util_send_qstring (p);
		    }
		  break;
		  
		default:
		  lvalue = argv[i];
		  if (strcasecmp (lvalue, "charset") == 0)
		    have_charset = 1;

		}
	    }
	  
	  if (lvalue)
	    {
	      if (space)
		util_send (" ");
	      util_send_qstring (lvalue);
	    }
	  
	  if (!have_charset && text_plain)
	    {
	      if (space)
		util_send (" ");
	      util_send ("\"CHARSET\" \"US-ASCII\"");
	    }
	  util_send (")");
	}
      else
	util_send (" NIL");
      mu_argcv_free (argc, argv);
      free (buffer);
    }
  else
    {
      /* Default? If Content-Type is not present consider as text/plain.  */
      util_send ("\"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);
    util_send (" %s", mu_umaxtostr (0, size + blines));
  }

  /* If the mime type was text.  */
  if (text_plain)
    {
      /* Add the line number of the body.  */
      util_send (" %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.  */
      util_send (" (");
      fetch_envelope0 (emsg);
      util_send (")");
      /* Add body structure of the encapsulated message.  */
      util_send ("(");
      bodystructure (emsg, extension);
      util_send (")");
      /* Size in text lines of the encapsulated message.  */
      mu_message_lines (emsg, &lines);
      util_send (" %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);
          util_send ("(");
          fetch_bodystructure0 (msg, extension);
          util_send (")");
        } /* for () */

      mu_message_get_header (message, &header);


      /* The subtype.  */
      if (mu_header_aget_value (header, MU_HEADER_CONTENT_TYPE, &buffer) == 0)
	{
	  int argc = 0;
	  char **argv;
	  char *s;
	  
	  mu_argcv_get (buffer, " \t\r\n;=", NULL, &argc, &argv);

	  s = strchr (argv[0], '/');
	  if (s)
	    s++;
	  util_send (" ");
	  util_send_qstring (s);

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

		  switch (argv[i][0])
		    {
		    case ';':
		      continue;
		      
		    case '=':
		      if (++i < argc)
			{
			  char *p = argv[i];
			  util_send (" ");
			  util_send_qstring (p);
			}
		      break;
		      
		    default:
		      lvalue = argv[i];
		    }
		}
	      if (lvalue)
		{
		  if (space)
		    util_send (" ");
		  util_send_qstring (lvalue);
		}
	      util_send (")");
	    }
	  else
	    util_send (" NIL");
	  mu_argcv_free (argc, argv);
          free (buffer);
	}
      else
	/* No content-type header */
	util_send (" 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))
	{
	  util_send ("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;
}

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

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_off_t offset;

  mu_filter_create (&rfc, stream, "rfc822", MU_FILTER_ENCODE, MU_STREAM_READ);

  if (start == 0 && size == (size_t) -1)
    {
      char buffer[512];
      offset = 0;
      if (max)
	{
	  util_send (" {%lu}\r\n", (unsigned long) max);
	  while (mu_stream_read (rfc, buffer, sizeof (buffer) - 1, offset,
				 &n) == 0 && n > 0)
	    {
	      buffer[n] = '\0';
	      util_send ("%s", buffer);
	      offset += n;
	    }
	  /* FIXME: Make sure exactly max bytes were sent */
	}
      else
	util_send (" \"\"");
    }
  else if (size + 2 < size) /* Check for integer overflow */
    {
      return RESP_BAD;
    }
  else
    {
      char *buffer, *p;
      size_t total = 0;
      offset = start;
      p = buffer = malloc (size + 1);
      if (!p)
	imap4d_bye (ERR_NO_MEM);
      
      while (total < size
	     && mu_stream_read (rfc, p, size - total + 1, offset, &n) == 0
	     && n > 0)
	{
	  offset += n;
	  total += n;
	  p += n;
	}
      *p = 0;
      util_send ("<%lu>", (unsigned long) start);
      if (total)
	{
	  util_send (" {%lu}\r\n", (unsigned long) total);
	  util_send ("%s", buffer);
	}
      else
	util_send (" \"\"");
      free (buffer);
    }
  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);
  util_send ("%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)
{
  util_send ("%s (", ffc->name);
  fetch_envelope0 (frt->msg);
  util_send (")");
  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);
  util_send ("%s (", ffc->name);
  util_print_flags (attr);
  util_send (")");
  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;
  mu_timezone tz;
  char datebuf[sizeof ("13-Jul-2002 00:00:00")];

  mu_message_get_envelope (frt->msg, &env);
  if (mu_envelope_sget_date (env, &date) == 0
      && mu_parse_ctime_date_time (&date, &tm, &tz) == 0)
    tmp = &tm;
  else
    {
      time_t t = time (NULL);
      tmp = localtime (&t);
    }
  mu_strftime (datebuf, sizeof (datebuf), "%d-%b-%Y %H:%M:%S", tmp);
  util_send ("%s", ffc->name);
  util_send (" \"%s +0000\"", datebuf);
  return 0;
}

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

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

/* BODY[] */
static int
_frt_body (struct fetch_function_closure *ffc,
	   struct fetch_runtime_closure *frt)
{
  mu_message_t msg;
  mu_stream_t stream = NULL;
  size_t size = 0, lines = 0;

  set_seen (ffc, frt);
  if (ffc->name)
    util_send ("%s", ffc->name);
  else
    fetch_send_section_part (ffc, "BODY[", "]");
  msg = fetch_get_part (ffc, frt);
  if (!msg)
    {
      util_send (" \"\"");
      return RESP_OK;
    }
  mu_message_get_stream (msg, &stream);
  mu_message_size (msg, &size);
  mu_message_lines (msg, &lines);
  return fetch_io (stream, ffc->start, ffc->size, size + lines);
}

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;

  set_seen (ffc, frt);
  if (ffc->name)
    util_send ("%s",  ffc->name);
  else
    fetch_send_section_part (ffc, "BODY[", "TEXT]");
  msg = fetch_get_part (ffc, frt);
  if (!msg)
    {
      util_send (" \"\"");
      return RESP_OK;
    }

  mu_message_get_body (msg, &body);
  mu_body_size (body, &size);
  mu_body_lines (body, &lines);
  mu_body_get_stream (body, &stream);
  return fetch_io (stream, ffc->start, ffc->size, size + lines);
}

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);
  util_send ("%s %u", ffc->name, size + lines);
  return RESP_OK;
}

static int
_frt_header0 (struct fetch_function_closure *ffc,
	      struct fetch_runtime_closure *frt,
	      const char *suffix)
{
  mu_message_t msg;
  mu_header_t header = NULL;
  mu_stream_t stream = NULL;
  size_t size = 0, lines = 0;
  
  set_seen (ffc, frt);
  if (ffc->name)
    util_send ("%s",  ffc->name);
  else
    fetch_send_section_part (ffc, "BODY[", suffix);

  msg = fetch_get_part (ffc, frt);
  if (!msg)
    {
      util_send (" \"\"");
      return RESP_OK;
    }
  mu_message_get_header (msg, &header);
  mu_header_size (header, &size);
  mu_header_lines (header, &lines);
  mu_header_get_stream (header, &stream);
  return fetch_io (stream, ffc->start, ffc->size, size + lines);
}

static int
_frt_header (struct fetch_function_closure *ffc,
	     struct fetch_runtime_closure *frt)
{
  return _frt_header0 (ffc, frt, "HEADER]");
}

static int
_frt_mime (struct fetch_function_closure *ffc,
	   struct fetch_runtime_closure *frt)
{
  return _frt_header0 (ffc, frt, "MIME]");
}

static int
_send_header_name (void *item, void *data)
{
  int *pf = data;
  if (*pf)
    util_send (" ");
  else
    *pf = 1;
  util_send ("\"%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, "BODY[", "HEADER.FIELDS");
  if (ffc->not)
    util_send (".NOT");
  util_send (" (");
  status = 0;
  mu_list_do (ffc->headers, _send_header_name, &status);
  util_send (")]");
  
  msg = fetch_get_part (ffc, frt);
  if (!msg)
    {
      util_send (" \"\"");
      return RESP_OK;
    }

  /* Collect headers: */
  if (mu_message_get_header (msg, &header)
      || mu_header_get_iterator (header, &itr))
    {
      util_send (" \"\"");
      return RESP_OK;
    }

  status = mu_memory_stream_create (&stream, NULL, MU_STREAM_NO_CHECK);
  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_sequential_printf (stream, "%s: %s\n", item, hv);
	  lines += 1 + count_nl (hv);
	}
    }
  mu_stream_sequential_write (stream, "\n", 1);
  lines++;
  
  /* Output collected data */
  mu_stream_size (stream, &size);
  status = fetch_io (stream, ffc->start, ffc->size, size + lines);
  mu_stream_destroy (&stream, NULL);
  
  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++)
    util_send (" ");
  return ffc->fun (ffc, frt);
}
    
struct parsebuf
{
  imap4d_tokbuf_t tok;
  int arg;
  char *token;
  int isuid;
  mu_list_t fnlist;
  jmp_buf errjmp;
  char *err_text;
};

static void
parsebuf_exit (struct parsebuf *p, char *text)
{
  p->err_text = text;
  longjmp (p->errjmp, 1);
}

static char *
parsebuf_peek (struct parsebuf *p)
{
  return imap4d_tokbuf_getarg (p->tok, p->arg);
}

static char *
parsebuf_next (struct parsebuf *p, int req)
{
  p->token = imap4d_tokbuf_getarg (p->tok, p->arg++);
  if (!p->token && req)
    parsebuf_exit (p, "Too few arguments");
  return p->token;
}

static void
append_ffc (struct parsebuf *p, struct fetch_function_closure *ffc)
{
  struct fetch_function_closure *new_ffc = malloc (sizeof (*new_ffc));
  if (!new_ffc)
    imap4d_bye (ERR_NO_MEM);
  *new_ffc = *ffc;
  mu_list_append (p->fnlist, new_ffc);
}

static void
append_simple_function (struct parsebuf *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 (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 (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 (struct parsebuf *p)
{
  struct fetch_function_closure ffc;
  ffc_init (&ffc);
  ffc.name = "RFC822";
  parsebuf_next (p, 0);
  if (p->token == NULL || p->token[0] == ')') 
    {
      /* Equivalent to BODY[]. */
      ffc.fun = _frt_body;
    }
  else if (p->token[0] == '.')
    {
      parsebuf_next (p, 1);
      if (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;
	  parsebuf_next (p, 0);
	}
      else if (strcasecmp (p->token, "SIZE") == 0)
	{
	  /* A number expressing the [RFC-2822] size of the message. */
	  ffc.name = "RFC822.SIZE";
	  ffc.fun = _frt_size;
	  parsebuf_next (p, 0);
	}
      else if (strcasecmp (p->token, "TEXT") == 0)
	{
	  /* RFC822.TEXT
	     Equivalent to BODY[TEXT]. */
	  ffc.name = "RFC822.TEXT";
	  ffc.fun = _frt_body_text;
	  parsebuf_next (p, 0);
	}
      else
	parsebuf_exit (p, "Syntax error after RFC822.");
    }
  else
    parsebuf_exit (p, "Syntax error after RFC822");
  append_ffc (p, &ffc);
}

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

/*
header-fld-name = astring

header-list     = "(" header-fld-name *(SP header-fld-name) ")"
*/
static void
parse_header_list (struct parsebuf *p, struct fetch_function_closure *ffc)
{
  if (p->token[0] != '(')
    parsebuf_exit (p, "Syntax error: expected (");
  mu_list_create (&ffc->headers);
  mu_list_set_comparator (ffc->headers, _header_cmp);
  for (parsebuf_next (p, 1); p->token[0] != ')'; parsebuf_next (p, 1))
    {
      if (util_isdelim (p->token))
	parsebuf_exit (p, "Syntax error: unexpected delimiter");
      mu_list_append (ffc->headers, p->token);
    }
  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 (struct parsebuf *p, struct fetch_function_closure *ffc,
		    int allow_mime)
{
  if (strcasecmp (p->token, "HEADER") == 0)
    {
      /* "HEADER" / "HEADER.FIELDS" [".NOT"] SP header-list  */
      parsebuf_next (p, 1);
      if (p->token[0] == '.')
	{
	  parsebuf_next (p, 1);
	  if (strcasecmp (p->token, "FIELDS"))
	    parsebuf_exit (p, "Expected FIELDS");
	  ffc->fun = _frt_header_fields;
	  parsebuf_next (p, 1);
	  if (p->token[0] == '.')
	    {
	      parsebuf_next (p, 1);
	      if (strcasecmp (p->token, "NOT") == 0)
		{
		  ffc->not = 1;
		  parsebuf_next (p, 1);
		}
	      else
		parsebuf_exit (p, "Expected NOT");
	    }
	  parse_header_list (p, ffc);
	}
      else
	ffc->fun = _frt_header;
    }
  else if (strcasecmp (p->token, "TEXT") == 0)
    {
      parsebuf_next (p, 1);
      ffc->fun = _frt_body_text;
    }
  else if (allow_mime && strcasecmp (p->token, "MIME") == 0)
    {
      parsebuf_next (p, 1);
      ffc->fun = _frt_mime;
    }
  else
    return 1;
 return 0;
}

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

  if (*cp)
    parsebuf_exit (p, "Syntax error: expected number");
  return n;
}
    
/*
section-part    = nz-number *("." nz-number)
                    ; body part nesting
*/  
static void
parse_section_part (struct parsebuf *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;

      parsebuf_next (p, 1);
      if (p->token[0] == '.'
	  && (cp = parsebuf_peek (p)) && isascii (*cp) && isdigit (cp[0]))
	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 (struct parsebuf *p, struct fetch_function_closure *ffc)
{
  if (p->token[0] != '[')
    return 1;
  ffc_init (ffc);
  ffc->name = NULL;
  ffc->fun = _frt_body;
  parsebuf_next (p, 1);
  if (parse_section_text (p, ffc, 0))
    {
      if (p->token[0] == ']')
	/* OK */;
      else if (isascii (p->token[0]) && isdigit (p->token[0]))
	{
	  parse_section_part (p, ffc);
	  if (p->token[0] == '.')
	    {
	      parsebuf_next (p, 1);
	      parse_section_text (p, ffc, 1);
	    }
	}
      else
	parsebuf_exit (p, "Syntax error");
    }
  if (p->token[0] != ']')
    parsebuf_exit (p, "Syntax error: missing ]");
  parsebuf_next (p, 0);
  return 0;
}

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

static void
parse_body_peek (struct parsebuf *p)
{
  parsebuf_next (p, 1);
  if (strcasecmp (p->token, "PEEK") == 0)
    {
      parsebuf_next (p, 1);
      if (parse_body_args (p, 1))
	parsebuf_exit (p, "Syntax error");
    }
  else
    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 (struct parsebuf *p)
{
  if (parsebuf_next (p, 0) == NULL || p->token[0] == ')')
    append_simple_function (p, "BODY", _frt_bodystructure0);
  else if (p->token[0] == '.')
    parse_body_peek (p);
  else if (strcasecmp (p->token, "STRUCTURE") == 0)
    {
      /* For compatibility with previous versions */
      append_simple_function (p, "BODYSTRUCTURE", _frt_bodystructure);
      parsebuf_next (p, 0);
    }
  else if (parse_body_args (p, 0))
    parsebuf_exit (p, "Syntax error");
}

static int
parse_fetch_att (struct parsebuf *p)
{
  struct fetch_att_tab *ent;

  ent = find_fetch_att_tab (p->token);
  if (ent)
    {
      if (!(ent->fun == _frt_uid && p->isuid))
	append_simple_function (p, ent->name, ent->fun);
      parsebuf_next (p, 0);
    }
  else if (strcasecmp (p->token, "RFC822") == 0)
    parse_fetch_rfc822 (p);
  else if (strcasecmp (p->token, "BODY") == 0)
    parse_fetch_body (p);
  else if (strcasecmp (p->token, "BODYSTRUCTURE") == 0)
    {
      append_simple_function (p, "BODYSTRUCTURE", _frt_bodystructure);
      parsebuf_next (p, 0);
    }
  else
    return 1;
  return 0;
}

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

/* "ALL" / "FULL" / "FAST" / fetch-att / "(" */
static void
parse_macro (struct parsebuf *p)
{  
  char *exp;
  
  parsebuf_next (p, 1);
  if (p->token[0] == '(')
    {
      parsebuf_next (p, 1);
      parse_fetch_att_list (p);
      if (p->token[0] != ')')
	parsebuf_exit (p, "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;
      parsebuf_next (p, 1);
      parse_fetch_att_list (p);
      imap4d_tokbuf_destroy (&p->tok);
  
      p->arg = save_arg;
      p->tok = save_tok;

      if (parsebuf_peek (p))
	parsebuf_exit (p, "Too many arguments");
    }     
  else
    {
      parse_fetch_att (p);
      if (p->token)
	parsebuf_exit (p, "Too many arguments");
    }
}
    
/* 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 = RESP_OK;
  char *msgset;
  size_t *set = NULL;
  int n = 0;
  int i;
  int status;
  struct fetch_runtime_closure frc;
  struct parsebuf pb;

  if (imap4d_tokbuf_argc (tok) - (IMAP4_ARG_1 + isuid) < 2)
    {
      *err_text = "Invalid arguments";
      return 1;
    }
  
  pb.tok = tok;
  pb.arg = IMAP4_ARG_1 + isuid;
  pb.isuid = isuid;
  pb.err_text = "Syntax error";
  mu_list_create (&pb.fnlist);
  mu_list_set_destroy_item (pb.fnlist, _free_ffc);
  if (setjmp (pb.errjmp))
    {
      *err_text = pb.err_text;
      mu_list_destroy (&pb.fnlist);
      return RESP_BAD;
    }
  
  msgset = parsebuf_next (&pb, 1);

  /* Get the message numbers in set[].  */
  status = util_msgset (msgset, &set, &n, isuid);
  if (status != 0)
    {
      *err_text = "Bogus number set";
      return RESP_BAD;
    }

  /* 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 (isuid)
    append_simple_function (&pb, "UID", _frt_uid);

  parse_macro (&pb);
  
  /* Prepare status code. It will be replaced if an error occurs in the
     loop below */
  frc.err_text = "Completed";
  
  for (i = 0; i < n && rc == RESP_OK; i++)
    {
      frc.msgno = (isuid) ? uid_to_msgno (set[i]) : set[i];

      if (frc.msgno && mu_mailbox_get_message (mbox, frc.msgno, &frc.msg) == 0)
	{
	  util_send ("* %lu FETCH (", (unsigned long) frc.msgno);
	  frc.eltno = 0;
	  rc = mu_list_do (pb.fnlist, _do_fetch, &frc);
	  util_send (")\r\n");
	}
    }
  
  mu_list_destroy (&pb.fnlist);
  free (set);
  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_command *command, imap4d_tokbuf_t tok)
{
  int rc;
  char *err_text = "Completed";

  rc = imap4d_fetch0 (tok, 0, &err_text);
  return util_finish (command, rc, "%s", err_text);
}