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