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