011119d3aca25d5e0b6b4e0cf7cc27ee2a306178
[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         /* Mark this message as "seen" *unless* this is a "peek" operation */
517         if (is_peek == 0) {
518                 CtdlSetSeen(msgnum, 1);
519         }
520 }
521
522 /*
523  * Called immediately before outputting a multipart bodystructure
524  */
525 void imap_fetch_bodystructure_pre(
526                 char *name, char *filename, char *partnum, char *disp,
527                 void *content, char *cbtype, size_t length, char *encoding,
528                 void *cbuserdata
529                 ) {
530
531         cprintf("(");
532 }
533
534
535
536 /*
537  * Called immediately after outputting a multipart bodystructure
538  */
539 void imap_fetch_bodystructure_post(
540                 char *name, char *filename, char *partnum, char *disp,
541                 void *content, char *cbtype, size_t length, char *encoding,
542                 void *cbuserdata
543                 ) {
544
545         char subtype[SIZ];
546
547         extract_token(subtype, cbtype, 1, '/');
548         imap_strout(subtype);
549         cprintf(")");
550 }
551
552
553
554 /*
555  * Output the info for a MIME part in the format required by BODYSTRUCTURE.
556  *
557  */
558 void imap_fetch_bodystructure_part(
559                 char *name, char *filename, char *partnum, char *disp,
560                 void *content, char *cbtype, size_t length, char *encoding,
561                 void *cbuserdata
562                 ) {
563
564         char buf[SIZ];
565         int have_cbtype = 0;
566         int have_encoding = 0;
567
568         cprintf("(");
569
570         if (cbtype != NULL) if (strlen(cbtype)>0) have_cbtype = 1;
571
572         if (have_cbtype) {
573                 extract_token(buf, cbtype, 0, '/');
574                 imap_strout(buf);
575                 cprintf(" ");
576                 extract_token(buf, cbtype, 1, '/');
577                 imap_strout(buf);
578                 cprintf(" ");
579         }
580         else {
581                 cprintf("\"TEXT\" \"PLAIN\" ");
582         }
583
584         cprintf("(\"CHARSET\" \"US-ASCII\"");
585
586         if (name != NULL) if (strlen(name)>0) {
587                 cprintf(" \"NAME\" ");
588                 imap_strout(name);
589         }
590
591         if (filename != NULL) if (strlen(filename)>0) {
592                 cprintf(" \"FILENAME\" ");
593                 imap_strout(name);
594         }
595
596         cprintf(") ");
597
598         cprintf("NIL NIL ");
599
600         if (encoding != NULL) if (strlen(encoding) > 0)  have_encoding = 1;
601
602         if (have_encoding) {
603                 imap_strout(encoding);
604         }
605         else {
606                 imap_strout("7BIT");
607         }
608         cprintf(" ");
609
610         cprintf("%ld ", length);        /* bytes */
611         cprintf("NIL) ");               /* lines */
612 }
613
614
615
616 /*
617  * Spew the BODYSTRUCTURE data for a message.  (Do you need a silencer if
618  * you're going to shoot a MIME?  Do you need a reason to shoot Mark Crispin?
619  * No, and no.)
620  *
621  */
622 void imap_fetch_bodystructure (long msgnum, char *item,
623                 struct CtdlMessage *msg) {
624         FILE *tmp;
625         char buf[1024];
626         long lines = 0L;
627         long bytes = 0L;
628
629         /* For non-RFC822 (ordinary Citadel) messages, this is short and
630          * sweet...
631          */
632         if (msg->cm_format_type != FMT_RFC822) {
633
634                 /* *sigh* We have to RFC822-format the message just to be able
635                  * to measure it.
636                  */
637                 tmp = tmpfile();
638                 if (tmp == NULL) return;
639                 CtdlRedirectOutput(tmp, -1);
640                 CtdlOutputPreLoadedMsg(msg, msgnum, MT_RFC822, 0, 0, 1);
641                 CtdlRedirectOutput(NULL, -1);
642
643                 rewind(tmp);
644                 while (fgets(buf, sizeof buf, tmp) != NULL) ++lines;
645                 bytes = ftell(tmp);
646                 fclose(tmp);
647
648                 cprintf("BODYSTRUCTURE (\"TEXT\" \"PLAIN\" "
649                         "(\"CHARSET\" \"US-ASCII\") NIL NIL "
650                         "\"7BIT\" %ld %ld)", bytes, lines);
651
652                 return;
653         }
654
655         /* For messages already stored in RFC822 format, we have to parse. */
656         cprintf("BODYSTRUCTURE ");
657         mime_parser(msg->cm_fields['M'],
658                         NULL,
659                         *imap_fetch_bodystructure_part, /* part */
660                         *imap_fetch_bodystructure_pre,  /* pre-multi */
661                         *imap_fetch_bodystructure_post, /* post-multi */
662                         NULL,
663                         0);
664 }
665
666
667
668
669
670
671 /*
672  * imap_do_fetch() calls imap_do_fetch_msg() to output the deta of an
673  * individual message, once it has been successfully loaded from disk.
674  */
675 void imap_do_fetch_msg(int seq, struct CtdlMessage *msg,
676                         int num_items, char **itemlist) {
677         int i;
678
679         cprintf("* %d FETCH (", seq);
680
681         for (i=0; i<num_items; ++i) {
682
683                 if (!strncasecmp(itemlist[i], "BODY[", 5)) {
684                         imap_fetch_body(IMAP->msgids[seq-1], itemlist[i],
685                                         0, msg);
686                 }
687                 else if (!strncasecmp(itemlist[i], "BODY.PEEK[", 10)) {
688                         imap_fetch_body(IMAP->msgids[seq-1], itemlist[i],
689                                         1, msg);
690                 }
691                 else if (!strcasecmp(itemlist[i], "BODYSTRUCTURE")) {
692                         imap_fetch_bodystructure(IMAP->msgids[seq-1],
693                                         itemlist[i], msg);
694                 }
695                 else if (!strcasecmp(itemlist[i], "ENVELOPE")) {
696                         imap_fetch_envelope(IMAP->msgids[seq-1], msg);
697                 }
698                 else if (!strcasecmp(itemlist[i], "FLAGS")) {
699                         imap_fetch_flags(seq-1);
700                 }
701                 else if (!strcasecmp(itemlist[i], "INTERNALDATE")) {
702                         imap_fetch_internaldate(msg);
703                 }
704                 else if (!strcasecmp(itemlist[i], "RFC822")) {
705                         imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i], msg);
706                 }
707                 else if (!strcasecmp(itemlist[i], "RFC822.HEADER")) {
708                         imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i], msg);
709                 }
710                 else if (!strcasecmp(itemlist[i], "RFC822.SIZE")) {
711                         imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i], msg);
712                 }
713                 else if (!strcasecmp(itemlist[i], "RFC822.TEXT")) {
714                         imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i], msg);
715                 }
716                 else if (!strcasecmp(itemlist[i], "UID")) {
717                         imap_fetch_uid(seq);
718                 }
719
720                 if (i != num_items-1) cprintf(" ");
721         }
722
723         cprintf(")\r\n");
724 }
725
726
727
728 /*
729  * imap_fetch() calls imap_do_fetch() to do its actual work, once it's
730  * validated and boiled down the request a bit.
731  */
732 void imap_do_fetch(int num_items, char **itemlist) {
733         int i;
734         struct CtdlMessage *msg;
735
736         if (IMAP->num_msgs > 0)
737          for (i = 0; i < IMAP->num_msgs; ++i)
738           if (IMAP->flags[i] & IMAP_SELECTED) {
739                 msg = CtdlFetchMessage(IMAP->msgids[i]);
740                 if (msg != NULL) {
741                         imap_do_fetch_msg(i+1, msg, num_items, itemlist);
742                         CtdlFreeMessage(msg);
743                 }
744                 else {
745                         cprintf("* %d FETCH <internal error>\r\n", i+1);
746                 }
747         }
748 }
749
750
751
752 /*
753  * Back end for imap_handle_macros()
754  * Note that this function *only* looks at the beginning of the string.  It
755  * is not a generic search-and-replace function.
756  */
757 void imap_macro_replace(char *str, char *find, char *replace) {
758         char holdbuf[1024];
759
760         if (!strncasecmp(str, find, strlen(find))) {
761                 if (str[strlen(find)]==' ') {
762                         strcpy(holdbuf, &str[strlen(find)+1]);
763                         strcpy(str, replace);
764                         strcat(str, " ");
765                         strcat(str, holdbuf);
766                 }
767                 if (str[strlen(find)]==0) {
768                         strcpy(holdbuf, &str[strlen(find)+1]);
769                         strcpy(str, replace);
770                 }
771         }
772 }
773
774
775
776 /*
777  * Handle macros embedded in FETCH data items.
778  * (What the heck are macros doing in a wire protocol?  Are we trying to save
779  * the computer at the other end the trouble of typing a lot of characters?)
780  */
781 void imap_handle_macros(char *str) {
782         int i;
783         int nest = 0;
784
785         for (i=0; i<strlen(str); ++i) {
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                 if (str[i]=='}') --nest;
794
795                 if (nest <= 0) {
796                         imap_macro_replace(&str[i],
797                                 "ALL",
798                                 "FLAGS INTERNALDATE RFC822.SIZE ENVELOPE"
799                         );
800                         imap_macro_replace(&str[i],
801                                 "BODY",
802                                 "BODYSTRUCTURE"
803                         );
804                         imap_macro_replace(&str[i],
805                                 "FAST",
806                                 "FLAGS INTERNALDATE RFC822.SIZE"
807                         );
808                         imap_macro_replace(&str[i],
809                                 "FULL",
810                                 "FLAGS INTERNALDATE RFC822.SIZE ENVELOPE BODY"
811                         );
812                 }
813         }
814 }
815
816
817 /*
818  * Break out the data items requested, possibly a parenthesized list.
819  * Returns the number of data items, or -1 if the list is invalid.
820  * NOTE: this function alters the string it is fed, and uses it as a buffer
821  * to hold the data for the pointers it returns.
822  */
823 int imap_extract_data_items(char **argv, char *items) {
824         int num_items = 0;
825         int nest = 0;
826         int i, initial_len;
827         char *start;
828
829         /* Convert all whitespace to ordinary space characters. */
830         for (i=0; i<strlen(items); ++i) {
831                 if (isspace(items[i])) items[i]=' ';
832         }
833
834         /* Strip leading and trailing whitespace, then strip leading and
835          * trailing parentheses if it's a list
836          */
837         striplt(items);
838         if ( (items[0]=='(') && (items[strlen(items)-1]==')') ) {
839                 items[strlen(items)-1] = 0;
840                 strcpy(items, &items[1]);
841                 striplt(items);
842         }
843
844         /* Parse any macro data items */
845         imap_handle_macros(items);
846
847         /*
848          * Now break out the data items.  We throw in one trailing space in
849          * order to avoid having to break out the last one manually.
850          */
851         strcat(items, " ");
852         start = items;
853         initial_len = strlen(items);
854         for (i=0; i<initial_len; ++i) {
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                 if (items[i]=='}') --nest;
863
864                 if (nest <= 0) if (items[i]==' ') {
865                         items[i] = 0;
866                         argv[num_items++] = start;
867                         start = &items[i+1];
868                 }
869         }
870
871         return(num_items);
872
873 }
874
875
876 /*
877  * One particularly hideous aspect of IMAP is that we have to allow the client
878  * to specify arbitrary ranges and/or sets of messages to fetch.  Citadel IMAP
879  * handles this by setting the IMAP_SELECTED flag for each message specified in
880  * the ranges/sets, then looping through the message array, outputting messages
881  * with the flag set.  We don't bother returning an error if an out-of-range
882  * number is specified (we just return quietly) because any client braindead
883  * enough to request a bogus message number isn't going to notice the
884  * difference anyway.
885  *
886  * This function clears out the IMAP_SELECTED bits, then sets that bit for each
887  * message included in the specified range.
888  *
889  * Set is_uid to 1 to fetch by UID instead of sequence number.
890  */
891 void imap_pick_range(char *supplied_range, int is_uid) {
892         int i;
893         int num_sets;
894         int s;
895         char setstr[SIZ], lostr[SIZ], histr[SIZ];       /* was 1024 */
896         int lo, hi;
897         char actual_range[SIZ];
898
899         /* 
900          * Handle the "ALL" macro
901          */
902         if (!strcasecmp(supplied_range, "ALL")) {
903                 safestrncpy(actual_range, "1:*", sizeof actual_range);
904         }
905         else {
906                 safestrncpy(actual_range, supplied_range, sizeof actual_range);
907         }
908
909         /*
910          * Clear out the IMAP_SELECTED flags for all messages.
911          */
912         for (i = 0; i < IMAP->num_msgs; ++i) {
913                 IMAP->flags[i] = IMAP->flags[i] & ~IMAP_SELECTED;
914         }
915
916         /*
917          * Now set it for all specified messages.
918          */
919         num_sets = num_tokens(actual_range, ',');
920         for (s=0; s<num_sets; ++s) {
921                 extract_token(setstr, actual_range, s, ',');
922
923                 extract_token(lostr, setstr, 0, ':');
924                 if (num_tokens(setstr, ':') >= 2) {
925                         extract_token(histr, setstr, 1, ':');
926                         if (!strcmp(histr, "*")) sprintf(histr, "%d", INT_MAX);
927                 } 
928                 else {
929                         strcpy(histr, lostr);
930                 }
931                 lo = atoi(lostr);
932                 hi = atoi(histr);
933
934                 /* Loop through the array, flipping bits where appropriate */
935                 for (i = 1; i <= IMAP->num_msgs; ++i) {
936                         if (is_uid) {   /* fetch by sequence number */
937                                 if ( (IMAP->msgids[i-1]>=lo)
938                                    && (IMAP->msgids[i-1]<=hi)) {
939                                         IMAP->flags[i-1] =
940                                                 IMAP->flags[i-1] | IMAP_SELECTED;
941                                 }
942                         }
943                         else {          /* fetch by uid */
944                                 if ( (i>=lo) && (i<=hi)) {
945                                         IMAP->flags[i-1] =
946                                                 IMAP->flags[i-1] | IMAP_SELECTED;
947                                 }
948                         }
949                 }
950         }
951
952 }
953
954
955
956 /*
957  * This function is called by the main command loop.
958  */
959 void imap_fetch(int num_parms, char *parms[]) {
960         char items[SIZ];        /* was 1024 */
961         char *itemlist[SIZ];
962         int num_items;
963         int i;
964
965         if (num_parms < 4) {
966                 cprintf("%s BAD invalid parameters\r\n", parms[0]);
967                 return;
968         }
969
970         imap_pick_range(parms[2], 0);
971
972         strcpy(items, "");
973         for (i=3; i<num_parms; ++i) {
974                 strcat(items, parms[i]);
975                 if (i < (num_parms-1)) strcat(items, " ");
976         }
977
978         num_items = imap_extract_data_items(itemlist, items);
979         if (num_items < 1) {
980                 cprintf("%s BAD invalid data item list\r\n", parms[0]);
981                 return;
982         }
983
984         imap_do_fetch(num_items, itemlist);
985         cprintf("%s OK FETCH completed\r\n", parms[0]);
986 }
987
988 /*
989  * This function is called by the main command loop.
990  */
991 void imap_uidfetch(int num_parms, char *parms[]) {
992         char items[SIZ];        /* was 1024 */
993         char *itemlist[SIZ];
994         int num_items;
995         int i;
996         int have_uid_item = 0;
997
998         if (num_parms < 5) {
999                 cprintf("%s BAD invalid parameters\r\n", parms[0]);
1000                 return;
1001         }
1002
1003         imap_pick_range(parms[3], 1);
1004
1005         strcpy(items, "");
1006         for (i=4; i<num_parms; ++i) {
1007                 strcat(items, parms[i]);
1008                 if (i < (num_parms-1)) strcat(items, " ");
1009         }
1010
1011         num_items = imap_extract_data_items(itemlist, items);
1012         if (num_items < 1) {
1013                 cprintf("%s BAD invalid data item list\r\n", parms[0]);
1014                 return;
1015         }
1016
1017         /* If the "UID" item was not included, we include it implicitly
1018          * because this is a UID FETCH command
1019          */
1020         for (i=0; i<num_items; ++i) {
1021                 if (!strcasecmp(itemlist[i], "UID")) ++have_uid_item;
1022         }
1023         if (have_uid_item == 0) itemlist[num_items++] = "UID";
1024
1025         imap_do_fetch(num_items, itemlist);
1026         cprintf("%s OK UID FETCH completed\r\n", parms[0]);
1027 }
1028
1029