895a03feed44b704c792fba51fd1be2b0b3c0c83
[citadel.git] / citadel / imap_fetch.c
1 /*
2  * $Id$
3  *
4  * Implements the FETCH command in IMAP.
5  * This command is way too convoluted.  Marc Crispin is a fscking idiot.
6  *
7  */
8
9
10 #include "sysdep.h"
11 #include <stdlib.h>
12 #include <unistd.h>
13 #include <stdio.h>
14 #include <fcntl.h>
15 #include <signal.h>
16 #include <pwd.h>
17 #include <errno.h>
18 #include <sys/types.h>
19 #include <sys/time.h>
20 #include <sys/wait.h>
21 #include <ctype.h>
22 #include <string.h>
23 #include <limits.h>
24 #include "citadel.h"
25 #include "server.h"
26 #include <time.h>
27 #include "sysdep_decls.h"
28 #include "citserver.h"
29 #include "support.h"
30 #include "config.h"
31 #include "dynloader.h"
32 #include "room_ops.h"
33 #include "user_ops.h"
34 #include "policy.h"
35 #include "database.h"
36 #include "msgbase.h"
37 #include "tools.h"
38 #include "internet_addressing.h"
39 #include "mime_parser.h"
40 #include "serv_imap.h"
41 #include "imap_tools.h"
42 #include "imap_fetch.h"
43 #include "genstamp.h"
44
45
46
47 struct imap_fetch_part {
48         char desired_section[256];
49         FILE *output_fp;
50 };
51
52 /*
53  * Individual field functions for imap_do_fetch_msg() ...
54  */
55
56
57
58 void imap_fetch_uid(int seq) {
59         cprintf("UID %ld", IMAP->msgids[seq-1]);
60 }
61
62 void imap_fetch_flags(struct CtdlMessage *msg) {
63         cprintf("FLAGS ()");    /* FIXME do something here */
64 }
65
66 void imap_fetch_internaldate(struct CtdlMessage *msg) {
67         char buf[256];
68         time_t msgdate;
69
70         if (msg->cm_fields['T'] != NULL) {
71                 msgdate = atol(msg->cm_fields['T']);
72         }
73         else {
74                 msgdate = time(NULL);
75         }
76
77         datestring(buf, msgdate, DATESTRING_IMAP);
78         cprintf("INTERNALDATE \"%s\"", buf);
79 }
80
81
82 /*
83  * Fetch RFC822-formatted messages.
84  *
85  * 'whichfmt' should be set to one of:
86  *      "RFC822"        entire message
87  *      "RFC822.HEADER" headers only (with trailing blank line)
88  *      "RFC822.SIZE"   size of translated message
89  *      "RFC822.TEXT"   body only (without leading blank line)
90  */
91 void imap_fetch_rfc822(int msgnum, char *whichfmt, struct CtdlMessage *msg) {
92         FILE *tmp;
93         char buf[1024];
94         char *ptr;
95         long headers_size, text_size, total_size;
96         long bytes_remaining = 0;
97         long blocksize;
98
99         tmp = tmpfile();
100         if (tmp == NULL) {
101                 lprintf(1, "Cannot open temp file: %s\n", strerror(errno));
102                 return;
103         }
104
105         /*
106          * Load the message into a temp file for translation and measurement
107          */ 
108         CtdlRedirectOutput(tmp, -1);
109         CtdlOutputPreLoadedMsg(msg, msgnum, MT_RFC822, 0, 0, 1);
110         CtdlRedirectOutput(NULL, -1);
111
112         /*
113          * Now figure out where the headers/text break is.  IMAP considers the
114          * intervening blank line to be part of the headers, not the text.
115          */
116         rewind(tmp);
117         headers_size = 0L;
118         do {
119                 ptr = fgets(buf, sizeof buf, tmp);
120                 if (ptr != NULL) {
121                         striplt(buf);
122                         if (strlen(buf) == 0) headers_size = ftell(tmp);
123                 }
124         } while ( (headers_size == 0L) && (ptr != NULL) );
125         fseek(tmp, 0L, SEEK_END);
126         total_size = ftell(tmp);
127         text_size = total_size - headers_size;
128
129         if (!strcasecmp(whichfmt, "RFC822.SIZE")) {
130                 cprintf("RFC822.SIZE %ld", total_size);
131                 fclose(tmp);
132                 return;
133         }
134
135         else if (!strcasecmp(whichfmt, "RFC822")) {
136                 bytes_remaining = total_size;
137                 rewind(tmp);
138         }
139
140         else if (!strcasecmp(whichfmt, "RFC822.HEADER")) {
141                 bytes_remaining = headers_size;
142                 rewind(tmp);
143         }
144
145         else if (!strcasecmp(whichfmt, "RFC822.TEXT")) {
146                 bytes_remaining = text_size;
147                 fseek(tmp, headers_size, SEEK_SET);
148         }
149
150         cprintf("%s {%ld}\r\n", whichfmt, bytes_remaining);
151         blocksize = sizeof(buf);
152         while (bytes_remaining > 0L) {
153                 if (blocksize > bytes_remaining) blocksize = bytes_remaining;
154                 fread(buf, blocksize, 1, tmp);
155                 client_write(buf, blocksize);
156                 bytes_remaining = bytes_remaining - blocksize;
157         }
158
159         fclose(tmp);
160 }
161
162
163
164 /*
165  * Load a specific part of a message into the temp file to be output to a
166  * client.  FIXME we can handle parts like "2" and "2.1" and even "2.MIME"
167  * but we still can't handle "2.HEADER" (which might not be a problem, because
168  * we currently don't have the ability to break out nested RFC822's anyway).
169  *
170  * Note: mime_parser() was called with dont_decode set to 1, so we have the
171  * luxury of simply spewing without having to re-encode.
172  */
173 void imap_load_part(char *name, char *filename, char *partnum, char *disp,
174                     void *content, char *cbtype, size_t length, char *encoding,
175                     void *cbuserdata)
176 {
177         struct imap_fetch_part *imfp;
178         char mbuf2[1024];
179
180         imfp = (struct imap_fetch_part *)cbuserdata;
181
182         if (!strcasecmp(partnum, imfp->desired_section)) {
183                 fwrite(content, length, 1, imfp->output_fp);
184         }
185
186         sprintf(mbuf2, "%s.MIME", partnum);
187
188         if (!strcasecmp(imfp->desired_section, mbuf2)) {
189                 fprintf(imfp->output_fp, "Content-type: %s", cbtype);
190                 if (strlen(name) > 0)
191                         fprintf(imfp->output_fp, "; name=\"%s\"", name);
192                 fprintf(imfp->output_fp, "\r\n");
193                 if (strlen(encoding) > 0)
194                         fprintf(imfp->output_fp,
195                                 "Content-Transfer-Encoding: %s\r\n", encoding);
196                 if (strlen(encoding) > 0) {
197                         fprintf(imfp->output_fp, "Content-Disposition: %s",
198                                         disp);
199                         if (strlen(filename) > 0) {
200                                 fprintf(imfp->output_fp, "; filename=\"%s\"",
201                                         filename);
202                         }
203                         fprintf(imfp->output_fp, "\r\n");
204                 }
205                 fprintf(imfp->output_fp, "Content-Length: %d\r\n", length);
206                 fprintf(imfp->output_fp, "\r\n");
207         }
208                         
209
210 }
211
212
213 /* 
214  * Called by imap_fetch_envelope() to output the "From" field.
215  * This is in its own function because its logic is kind of complex.  We
216  * really need to make this suck less.
217  */
218 void imap_output_envelope_from(struct CtdlMessage *msg) {
219         char user[1024], node[1024], name[1024];
220
221         cprintf("((");                          /* open double-parens */
222         imap_strout(msg->cm_fields['A']);       /* personal name */
223         cprintf(" NIL ");                       /* source route (not used) */
224
225         if (msg->cm_fields['F'] != NULL) {
226                 process_rfc822_addr(msg->cm_fields['F'], user, node, name);
227                 imap_strout(user);              /* mailbox name (user id) */
228                 cprintf(" ");
229                 if (!strcasecmp(node, config.c_nodename)) {
230                         imap_strout(config.c_fqdn);
231                 }
232                 else {
233                         imap_strout(node);              /* host name */
234                 }
235         }
236         else {
237                 imap_strout(msg->cm_fields['A']); /* mailbox name (user id) */
238                 cprintf(" ");
239                 imap_strout(msg->cm_fields['N']);       /* host name */
240         }
241         
242         cprintf(")) ");                         /* close double-parens */
243 }
244
245
246 /*
247  * Implements the ENVELOPE fetch item
248  * 
249  * FIXME ... we only output some of the fields right now.  Definitely need
250  *           to do all of them.  Accurately, too.
251  *
252  * Note that the imap_strout() function can cleverly output NULL fields as NIL,
253  * so we don't have to check for that condition like we do elsewhere.
254  */
255 void imap_fetch_envelope(long msgnum, struct CtdlMessage *msg) {
256         char datestringbuf[256];
257         time_t msgdate;
258
259
260         /* Parse the message date into an IMAP-format date string */
261         if (msg->cm_fields['T'] != NULL) {
262                 msgdate = atol(msg->cm_fields['T']);
263         }
264         else {
265                 msgdate = time(NULL);
266         }
267         datestring(datestringbuf, msgdate, DATESTRING_IMAP);
268
269         /* Now start spewing data fields.  The order is important, as it is
270          * defined by the protocol specification.  Nonexistent fields must
271          * be output as NIL, existent fields must be quoted or literalled.
272          * The imap_strout() function conveniently does all this for us.
273          */
274         cprintf("ENVELOPE (");
275
276         /* date */
277         imap_strout(datestringbuf);
278         cprintf(" ");
279
280         /* subject */
281         imap_strout(msg->cm_fields['U']);
282         cprintf(" ");
283
284         /* from */
285         imap_output_envelope_from(msg);
286
287         /* Sender (always in the RFC822 header) */
288         cprintf("NIL ");
289
290         cprintf("NIL ");        /* reply-to */
291
292         cprintf("NIL ");        /* to */
293
294         cprintf("NIL ");        /* cc */
295
296         cprintf("NIL ");        /* bcc */
297
298         cprintf("NIL ");        /* in-reply-to */
299
300
301         /* message ID */
302         imap_strout(msg->cm_fields['I']);
303
304         cprintf(") ");
305 }
306
307
308 /*
309  * Strip any non header information out of a chunk of RFC822 data on disk
310  */
311 void imap_strip_headers(FILE *fp) {
312         char buf[1024];
313
314         rewind(fp);
315         while (fgets(buf, sizeof buf, fp) != NULL) {
316                 striplt(buf);
317                 if (strlen(buf) == 0) {
318                         fflush(fp);
319                         ftruncate(fileno(fp), ftell(fp));
320                 }
321         }
322         fflush(fp);
323         fprintf(fp, "\r\n");    /* add the trailing newline */
324         rewind(fp);
325 }
326
327
328 /*
329  * Implements the BODY and BODY.PEEK fetch items
330  */
331 void imap_fetch_body(long msgnum, char *item, int is_peek,
332                 struct CtdlMessage *msg) {
333         char section[1024];
334         char partial[1024];
335         int is_partial = 0;
336         char buf[1024];
337         int i;
338         FILE *tmp;
339         long bytes_remaining = 0;
340         long blocksize;
341         long pstart, pbytes;
342         struct imap_fetch_part imfp;
343
344         /* extract section */
345         strcpy(section, item);
346         for (i=0; i<strlen(section); ++i) {
347                 if (section[i]=='[') strcpy(section, &section[i+1]);
348         }
349         for (i=0; i<strlen(section); ++i) {
350                 if (section[i]==']') section[i] = 0;
351         }
352         lprintf(9, "Section is %s\n", section);
353
354         /* extract partial */
355         strcpy(partial, item);
356         for (i=0; i<strlen(partial); ++i) {
357                 if (partial[i]=='<') {
358                         strcpy(partial, &partial[i+1]);
359                         is_partial = 1;
360                 }
361         }
362         for (i=0; i<strlen(partial); ++i) {
363                 if (partial[i]=='>') partial[i] = 0;
364         }
365         if (is_partial == 0) strcpy(partial, "");
366         lprintf(9, "Partial is %s\n", partial);
367
368         tmp = tmpfile();
369         if (tmp == NULL) {
370                 lprintf(1, "Cannot open temp file: %s\n", strerror(errno));
371                 return;
372         }
373
374         /* Now figure out what the client wants, and get it */
375
376         if (!strcmp(section, "")) {             /* the whole thing */
377                 CtdlRedirectOutput(tmp, -1);
378                 CtdlOutputPreLoadedMsg(msg, msgnum, MT_RFC822, 0, 0, 1);
379                 CtdlRedirectOutput(NULL, -1);
380         }
381
382         /*
383          * Be obnoxious and send the entire header, even if the client only
384          * asks for certain fields.  FIXME this shortcut later.
385          */
386         else if (!strncasecmp(section, "HEADER", 6)) {
387                 CtdlRedirectOutput(tmp, -1);
388                 CtdlOutputPreLoadedMsg(msg, msgnum, MT_RFC822, 1, 0, 1);
389                 CtdlRedirectOutput(NULL, -1);
390                 imap_strip_headers(tmp);
391         }
392
393         /*
394          * Anything else must be a part specifier.
395          * (Note value of 1 passed as 'dont_decode' so client gets it encoded)
396          */
397         else {
398                 safestrncpy(imfp.desired_section, section,
399                                 sizeof(imfp.desired_section));
400                 imfp.output_fp = tmp;
401
402                 mime_parser(msg->cm_fields['M'], NULL,
403                                 *imap_load_part,
404                                 (void *)&imfp,
405                                 1);
406         }
407
408
409         fseek(tmp, 0L, SEEK_END);
410         bytes_remaining = ftell(tmp);
411
412         if (is_partial == 0) {
413                 rewind(tmp);
414                 cprintf("BODY[%s] {%ld}\r\n", section, bytes_remaining);
415         }
416         else {
417                 sscanf(partial, "%ld.%ld", &pstart, &pbytes);
418                 if ((bytes_remaining - pstart) < pbytes) {
419                         pbytes = bytes_remaining - pstart;
420                 }
421                 fseek(tmp, pstart, SEEK_SET);
422                 bytes_remaining = pbytes;
423                 cprintf("BODY[%s] {%ld}<%ld>\r\n",
424                         section, bytes_remaining, pstart);
425         }
426
427         blocksize = sizeof(buf);
428         while (bytes_remaining > 0L) {
429                 if (blocksize > bytes_remaining) blocksize = bytes_remaining;
430                 fread(buf, blocksize, 1, tmp);
431                 client_write(buf, blocksize);
432                 bytes_remaining = bytes_remaining - blocksize;
433         }
434
435         fclose(tmp);
436
437         if (is_peek) {
438                 /* FIXME set the last read pointer or something */
439         }
440 }
441
442
443 /*
444  * Spew the BODYSTRUCTURE data for a message.  (Do you need a silencer if
445  * you're going to shoot a MIME?  Do you need a reason to shoot Mark Crispin?
446  * No, and no.)
447  *
448  * FIXME finish the implementation
449  */
450 void imap_fetch_bodystructure (long msgnum, char *item,
451                 struct CtdlMessage *msg) {
452         FILE *tmp;
453         char buf[1024];
454         long lines = 0L;
455         long bytes = 0L;
456
457
458         /* For non-RFC822 (ordinary Citadel) messages, this is short and
459          * sweet...
460          */
461         if (msg->cm_format_type != FMT_RFC822) {
462
463                 /* *sigh* We have to RFC822-format the message just to be able
464                  * to measure it.
465                  */
466                 tmp = tmpfile();
467                 if (tmp == NULL) return;
468                 CtdlRedirectOutput(tmp, -1);
469                 CtdlOutputPreLoadedMsg(msg, msgnum, MT_RFC822, 0, 0, 1);
470                 CtdlRedirectOutput(NULL, -1);
471
472                 rewind(tmp);
473                 while (fgets(buf, sizeof buf, tmp) != NULL) ++lines;
474                 bytes = ftell(tmp);
475                 fclose(tmp);
476
477                 cprintf("BODYSTRUCTURE (\"TEXT\" \"PLAIN\" "
478                         "(\"CHARSET\" \"US-ASCII\") NIL NIL "
479                         "\"7BIT\" %ld %ld) ", bytes, lines);
480
481                 return;
482         }
483
484         /* For messages already stored in RFC822 format, we have to parse. */
485         /* FIXME do this! */
486
487
488 }
489
490
491
492
493
494
495 /*
496  * imap_do_fetch() calls imap_do_fetch_msg() to output the deta of an
497  * individual message, once it has been successfully loaded from disk.
498  */
499 void imap_do_fetch_msg(int seq, struct CtdlMessage *msg,
500                         int num_items, char **itemlist) {
501         int i;
502
503         cprintf("* %d FETCH (", seq);
504
505         for (i=0; i<num_items; ++i) {
506
507                 if (!strncasecmp(itemlist[i], "BODY[", 5)) {
508                         imap_fetch_body(IMAP->msgids[seq-1], itemlist[i],
509                                         0, msg);
510                 }
511                 else if (!strncasecmp(itemlist[i], "BODY.PEEK[", 10)) {
512                         imap_fetch_body(IMAP->msgids[seq-1], itemlist[i],
513                                         1, msg);
514                 }
515                 else if (!strcasecmp(itemlist[i], "BODYSTRUCTURE")) {
516                         imap_fetch_bodystructure(IMAP->msgids[seq-1],
517                                         itemlist[i], msg);
518                 }
519                 else if (!strcasecmp(itemlist[i], "ENVELOPE")) {
520                         imap_fetch_envelope(IMAP->msgids[seq-1], msg);
521                 }
522                 else if (!strcasecmp(itemlist[i], "FLAGS")) {
523                         imap_fetch_flags(msg);
524                 }
525                 else if (!strcasecmp(itemlist[i], "INTERNALDATE")) {
526                         imap_fetch_internaldate(msg);
527                 }
528                 else if (!strcasecmp(itemlist[i], "RFC822")) {
529                         imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i], msg);
530                 }
531                 else if (!strcasecmp(itemlist[i], "RFC822.HEADER")) {
532                         imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i], msg);
533                 }
534                 else if (!strcasecmp(itemlist[i], "RFC822.SIZE")) {
535                         imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i], msg);
536                 }
537                 else if (!strcasecmp(itemlist[i], "RFC822.TEXT")) {
538                         imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i], msg);
539                 }
540                 else if (!strcasecmp(itemlist[i], "UID")) {
541                         imap_fetch_uid(seq);
542                 }
543
544                 if (i != num_items-1) cprintf(" ");
545         }
546
547         cprintf(")\r\n");
548 }
549
550
551
552 /*
553  * imap_fetch() calls imap_do_fetch() to do its actual work, once it's
554  * validated and boiled down the request a bit.
555  */
556 void imap_do_fetch(int num_items, char **itemlist) {
557         int i;
558         struct CtdlMessage *msg;
559
560         if (IMAP->num_msgs > 0)
561          for (i = 0; i < IMAP->num_msgs; ++i)
562           if (IMAP->flags[i] && IMAP_FETCHED) {
563                 msg = CtdlFetchMessage(IMAP->msgids[i]);
564                 if (msg != NULL) {
565                         imap_do_fetch_msg(i+1, msg, num_items, itemlist);
566                         CtdlFreeMessage(msg);
567                 }
568                 else {
569                         cprintf("* %d FETCH <internal error>\r\n", i+1);
570                 }
571         }
572 }
573
574
575
576 /*
577  * Back end for imap_handle_macros()
578  * Note that this function *only* looks at the beginning of the string.  It
579  * is not a generic search-and-replace function.
580  */
581 void imap_macro_replace(char *str, char *find, char *replace) {
582         char holdbuf[1024];
583
584         if (!strncasecmp(str, find, strlen(find))) {
585                 if (str[strlen(find)]==' ') {
586                         strcpy(holdbuf, &str[strlen(find)+1]);
587                         strcpy(str, replace);
588                         strcat(str, " ");
589                         strcat(str, holdbuf);
590                 }
591                 if (str[strlen(find)]==0) {
592                         strcpy(holdbuf, &str[strlen(find)+1]);
593                         strcpy(str, replace);
594                 }
595         }
596 }
597
598
599
600 /*
601  * Handle macros embedded in FETCH data items.
602  * (What the heck are macros doing in a wire protocol?  Are we trying to save
603  * the computer at the other end the trouble of typing a lot of characters?)
604  */
605 void imap_handle_macros(char *str) {
606         int i;
607         int nest = 0;
608
609         for (i=0; i<strlen(str); ++i) {
610                 if (str[i]=='(') ++nest;
611                 if (str[i]=='[') ++nest;
612                 if (str[i]=='<') ++nest;
613                 if (str[i]=='{') ++nest;
614                 if (str[i]==')') --nest;
615                 if (str[i]==']') --nest;
616                 if (str[i]=='>') --nest;
617                 if (str[i]=='}') --nest;
618
619                 if (nest <= 0) {
620                         imap_macro_replace(&str[i],
621                                 "ALL",
622                                 "FLAGS INTERNALDATE RFC822.SIZE ENVELOPE"
623                         );
624                         imap_macro_replace(&str[i],
625                                 "BODY",
626                                 "BODYSTRUCTURE"
627                         );
628                         imap_macro_replace(&str[i],
629                                 "FAST",
630                                 "FLAGS INTERNALDATE RFC822.SIZE"
631                         );
632                         imap_macro_replace(&str[i],
633                                 "FULL",
634                                 "FLAGS INTERNALDATE RFC822.SIZE ENVELOPE BODY"
635                         );
636                 }
637         }
638 }
639
640
641 /*
642  * Break out the data items requested, possibly a parenthesized list.
643  * Returns the number of data items, or -1 if the list is invalid.
644  * NOTE: this function alters the string it is fed, and uses it as a buffer
645  * to hold the data for the pointers it returns.
646  */
647 int imap_extract_data_items(char **argv, char *items) {
648         int num_items = 0;
649         int nest = 0;
650         int i, initial_len;
651         char *start;
652
653         /* Convert all whitespace to ordinary space characters. */
654         for (i=0; i<strlen(items); ++i) {
655                 if (isspace(items[i])) items[i]=' ';
656         }
657
658         /* Strip leading and trailing whitespace, then strip leading and
659          * trailing parentheses if it's a list
660          */
661         striplt(items);
662         if ( (items[0]=='(') && (items[strlen(items)-1]==')') ) {
663                 items[strlen(items)-1] = 0;
664                 strcpy(items, &items[1]);
665                 striplt(items);
666         }
667
668         /* Parse any macro data items */
669         imap_handle_macros(items);
670
671         /*
672          * Now break out the data items.  We throw in one trailing space in
673          * order to avoid having to break out the last one manually.
674          */
675         strcat(items, " ");
676         start = items;
677         initial_len = strlen(items);
678         for (i=0; i<initial_len; ++i) {
679                 if (items[i]=='(') ++nest;
680                 if (items[i]=='[') ++nest;
681                 if (items[i]=='<') ++nest;
682                 if (items[i]=='{') ++nest;
683                 if (items[i]==')') --nest;
684                 if (items[i]==']') --nest;
685                 if (items[i]=='>') --nest;
686                 if (items[i]=='}') --nest;
687
688                 if (nest <= 0) if (items[i]==' ') {
689                         items[i] = 0;
690                         argv[num_items++] = start;
691                         start = &items[i+1];
692                 }
693         }
694
695         return(num_items);
696
697 }
698
699
700 /*
701  * One particularly hideous aspect of IMAP is that we have to allow the client
702  * to specify arbitrary ranges and/or sets of messages to fetch.  Citadel IMAP
703  * handles this by setting the IMAP_FETCHED flag for each message specified in
704  * the ranges/sets, then looping through the message array, outputting messages
705  * with the flag set.  We don't bother returning an error if an out-of-range
706  * number is specified (we just return quietly) because any client braindead
707  * enough to request a bogus message number isn't going to notice the
708  * difference anyway.
709  *
710  * This function clears out the IMAP_FETCHED bits, then sets that bit for each
711  * message included in the specified range.
712  *
713  * Set is_uid to 1 to fetch by UID instead of sequence number.
714  */
715 void imap_pick_range(char *range, int is_uid) {
716         int i;
717         int num_sets;
718         int s;
719         char setstr[1024], lostr[1024], histr[1024];
720         int lo, hi;
721
722         /*
723          * Clear out the IMAP_FETCHED flags for all messages.
724          */
725         for (i = 1; i <= IMAP->num_msgs; ++i) {
726                 IMAP->flags[i-1] = IMAP->flags[i-1] & ~IMAP_FETCHED;
727         }
728
729         /*
730          * Now set it for all specified messages.
731          */
732         num_sets = num_tokens(range, ',');
733         for (s=0; s<num_sets; ++s) {
734                 extract_token(setstr, range, s, ',');
735
736                 extract_token(lostr, setstr, 0, ':');
737                 if (num_tokens(setstr, ':') >= 2) {
738                         extract_token(histr, setstr, 1, ':');
739                         if (!strcmp(histr, "*")) sprintf(histr, "%d", INT_MAX);
740                 } 
741                 else {
742                         strcpy(histr, lostr);
743                 }
744                 lo = atoi(lostr);
745                 hi = atoi(histr);
746
747                 /* Loop through the array, flipping bits where appropriate */
748                 for (i = 1; i <= IMAP->num_msgs; ++i) {
749                         if (is_uid) {   /* fetch by sequence number */
750                                 if ( (IMAP->msgids[i-1]>=lo)
751                                    && (IMAP->msgids[i-1]<=hi)) {
752                                         IMAP->flags[i-1] =
753                                                 IMAP->flags[i-1] | IMAP_FETCHED;
754                                 }
755                         }
756                         else {          /* fetch by uid */
757                                 if ( (i>=lo) && (i<=hi)) {
758                                         IMAP->flags[i-1] =
759                                                 IMAP->flags[i-1] | IMAP_FETCHED;
760                                 }
761                         }
762                 }
763         }
764 }
765
766
767
768 /*
769  * This function is called by the main command loop.
770  */
771 void imap_fetch(int num_parms, char *parms[]) {
772         char items[1024];
773         char *itemlist[256];
774         int num_items;
775         int i;
776
777         if (num_parms < 4) {
778                 cprintf("%s BAD invalid parameters\r\n", parms[0]);
779                 return;
780         }
781
782         imap_pick_range(parms[2], 0);
783
784         strcpy(items, "");
785         for (i=3; i<num_parms; ++i) {
786                 strcat(items, parms[i]);
787                 if (i < (num_parms-1)) strcat(items, " ");
788         }
789
790         num_items = imap_extract_data_items(itemlist, items);
791         if (num_items < 1) {
792                 cprintf("%s BAD invalid data item list\r\n", parms[0]);
793                 return;
794         }
795
796         imap_do_fetch(num_items, itemlist);
797         cprintf("%s OK FETCH completed\r\n", parms[0]);
798 }
799
800 /*
801  * This function is called by the main command loop.
802  */
803 void imap_uidfetch(int num_parms, char *parms[]) {
804         char items[1024];
805         char *itemlist[256];
806         int num_items;
807         int i;
808         int have_uid_item = 0;
809
810         if (num_parms < 5) {
811                 cprintf("%s BAD invalid parameters\r\n", parms[0]);
812                 return;
813         }
814
815         imap_pick_range(parms[3], 1);
816
817         strcpy(items, "");
818         for (i=4; i<num_parms; ++i) {
819                 strcat(items, parms[i]);
820                 if (i < (num_parms-1)) strcat(items, " ");
821         }
822
823         num_items = imap_extract_data_items(itemlist, items);
824         if (num_items < 1) {
825                 cprintf("%s BAD invalid data item list\r\n", parms[0]);
826                 return;
827         }
828
829         /* If the "UID" item was not included, we include it implicitly
830          * because this is a UID FETCH command
831          */
832         for (i=0; i<num_items; ++i) {
833                 if (!strcasecmp(itemlist[i], "UID")) ++have_uid_item;
834         }
835         if (have_uid_item == 0) itemlist[num_items++] = "UID";
836
837         imap_do_fetch(num_items, itemlist);
838         cprintf("%s OK UID FETCH completed\r\n", parms[0]);
839 }
840
841