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