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