Citadel API clean up.
[citadel.git] / citadel / modules / imap / imap_fetch.c
1 /*
2  * $Id$
3  *
4  * Implements the FETCH command in IMAP.
5  * This is a good example of the protocol's gratuitous complexity.
6  *
7  * Copyright (c) 2001-2009 by the citadel.org team
8  *
9  *  This program is free software; you can redistribute it and/or modify
10  *  it under the terms of the GNU General Public License as published by
11  *  the Free Software Foundation; either version 3 of the License, or
12  *  (at your option) any later version.
13  *
14  *  This program is distributed in the hope that it will be useful,
15  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  *  GNU General Public License for more details.
18  *
19  *  You should have received a copy of the GNU General Public License
20  *  along with this program; if not, write to the Free Software
21  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  */
23
24
25 #include "sysdep.h"
26 #include <stdlib.h>
27 #include <unistd.h>
28 #include <stdio.h>
29 #include <fcntl.h>
30 #include <signal.h>
31 #include <pwd.h>
32 #include <errno.h>
33 #include <sys/types.h>
34
35 #if TIME_WITH_SYS_TIME
36 # include <sys/time.h>
37 # include <time.h>
38 #else
39 # if HAVE_SYS_TIME_H
40 #  include <sys/time.h>
41 # else
42 #  include <time.h>
43 # endif
44 #endif
45
46 #include <sys/wait.h>
47 #include <ctype.h>
48 #include <string.h>
49 #include <limits.h>
50 #include <libcitadel.h>
51 #include "citadel.h"
52 #include "server.h"
53 #include "sysdep_decls.h"
54 #include "citserver.h"
55 #include "support.h"
56 #include "config.h"
57 #include "user_ops.h"
58 #include "policy.h"
59 #include "database.h"
60 #include "msgbase.h"
61 #include "internet_addressing.h"
62 #include "serv_imap.h"
63 #include "imap_tools.h"
64 #include "imap_fetch.h"
65 #include "genstamp.h"
66 #include "ctdl_module.h"
67
68
69
70 /*
71  * Individual field functions for imap_do_fetch_msg() ...
72  */
73
74 void imap_fetch_uid(int seq) {
75         cprintf("UID %ld", IMAP->msgids[seq-1]);
76 }
77
78 void imap_fetch_flags(int seq) {
79         int num_flags_printed = 0;
80         cprintf("FLAGS (");
81         if (IMAP->flags[seq] & IMAP_DELETED) {
82                 if (num_flags_printed > 0) cprintf(" ");
83                 cprintf("\\Deleted");
84                 ++num_flags_printed;
85         }
86         if (IMAP->flags[seq] & IMAP_SEEN) {
87                 if (num_flags_printed > 0) cprintf(" ");
88                 cprintf("\\Seen");
89                 ++num_flags_printed;
90         }
91         if (IMAP->flags[seq] & IMAP_ANSWERED) {
92                 if (num_flags_printed > 0) cprintf(" ");
93                 cprintf("\\Answered");
94                 ++num_flags_printed;
95         }
96         if (IMAP->flags[seq] & IMAP_RECENT) {
97                 if (num_flags_printed > 0) cprintf(" ");
98                 cprintf("\\Recent");
99                 ++num_flags_printed;
100         }
101         cprintf(")");
102 }
103
104 void imap_fetch_internaldate(struct CtdlMessage *msg) {
105         char buf[SIZ];
106         time_t msgdate;
107
108         if (!msg) return;
109         if (msg->cm_fields['T'] != NULL) {
110                 msgdate = atol(msg->cm_fields['T']);
111         }
112         else {
113                 msgdate = time(NULL);
114         }
115
116         datestring(buf, sizeof buf, msgdate, DATESTRING_IMAP);
117         cprintf("INTERNALDATE \"%s\"", buf);
118 }
119
120
121 /*
122  * Fetch RFC822-formatted messages.
123  *
124  * 'whichfmt' should be set to one of:
125  *      "RFC822"        entire message
126  *      "RFC822.HEADER" headers only (with trailing blank line)
127  *      "RFC822.SIZE"   size of translated message
128  *      "RFC822.TEXT"   body only (without leading blank line)
129  */
130 void imap_fetch_rfc822(long msgnum, char *whichfmt) {
131         char buf[SIZ];
132         char *ptr = NULL;
133         size_t headers_size, text_size, total_size;
134         size_t bytes_to_send = 0;
135         struct MetaData smi;
136         int need_to_rewrite_metadata = 0;
137         int need_body = 0;
138
139         /* Determine whether this particular fetch operation requires
140          * us to fetch the message body from disk.  If not, we can save
141          * on some disk operations...
142          */
143         if ( (!strcasecmp(whichfmt, "RFC822"))
144            || (!strcasecmp(whichfmt, "RFC822.TEXT")) ) {
145                 need_body = 1;
146         }
147
148         /* If this is an RFC822.SIZE fetch, first look in the message's
149          * metadata record to see if we've saved that information.
150          */
151         if (!strcasecmp(whichfmt, "RFC822.SIZE")) {
152                 GetMetaData(&smi, msgnum);
153                 if (smi.meta_rfc822_length > 0L) {
154                         cprintf("RFC822.SIZE %ld", smi.meta_rfc822_length);
155                         return;
156                 }
157                 need_to_rewrite_metadata = 1;
158                 need_body = 1;
159         }
160         
161         /* Cache the most recent RFC822 FETCH because some clients like to
162          * fetch in pieces, and we don't want to have to go back to the
163          * message store for each piece.  We also burn the cache if the
164          * client requests something that involves reading the message
165          * body, but we haven't fetched the body yet.
166          */
167         if ((IMAP->cached_rfc822_data != NULL)
168            && (IMAP->cached_rfc822_msgnum == msgnum)
169            && (IMAP->cached_rfc822_withbody || (!need_body)) ) {
170                 /* Good to go! */
171         }
172         else if (IMAP->cached_rfc822_data != NULL) {
173                 /* Some other message is cached -- free it */
174                 free(IMAP->cached_rfc822_data);
175                 IMAP->cached_rfc822_data = NULL;
176                 IMAP->cached_rfc822_msgnum = (-1);
177                 IMAP->cached_rfc822_len = 0;
178         }
179
180         /* At this point, we now can fetch and convert the message iff it's not
181          * the one we had cached.
182          */
183         if (IMAP->cached_rfc822_data == NULL) {
184                 /*
185                  * Load the message into memory for translation & measurement
186                  */
187                 CC->redirect_buffer = malloc(SIZ);
188                 CC->redirect_len = 0;
189                 CC->redirect_alloc = SIZ;
190                 CtdlOutputMsg(msgnum, MT_RFC822,
191                         (need_body ? HEADERS_ALL : HEADERS_FAST),
192                         0, 1, NULL, SUPPRESS_ENV_TO
193                 );
194                 if (!need_body) cprintf("\r\n");        /* extra trailing newline */
195                 IMAP->cached_rfc822_data = CC->redirect_buffer;
196                 IMAP->cached_rfc822_len = CC->redirect_len;
197                 IMAP->cached_rfc822_msgnum = msgnum;
198                 IMAP->cached_rfc822_withbody = need_body;
199                 CC->redirect_buffer = NULL;
200                 CC->redirect_len = 0;
201                 CC->redirect_alloc = 0;
202                 if ( (need_to_rewrite_metadata) && (IMAP->cached_rfc822_len > 0) ) {
203                         smi.meta_rfc822_length = (long)IMAP->cached_rfc822_len;
204                         PutMetaData(&smi);
205                 }
206         }
207
208         /*
209          * Now figure out where the headers/text break is.  IMAP considers the
210          * intervening blank line to be part of the headers, not the text.
211          */
212         headers_size = 0;
213         text_size = 0;
214         total_size = 0;
215
216         if (need_body) {
217                 ptr = IMAP->cached_rfc822_data;
218                 do {
219                         ptr = memreadline(ptr, buf, sizeof buf);
220                         if (*ptr != 0) {
221                                 striplt(buf);
222                                 if (IsEmptyStr(buf)) {
223                                         headers_size = ptr - IMAP->cached_rfc822_data;
224                                 }
225                         }
226                 } while ( (headers_size == 0) && (*ptr != 0) );
227
228                 total_size = IMAP->cached_rfc822_len;
229                 text_size = total_size - headers_size;
230         }
231         else {
232                 headers_size = IMAP->cached_rfc822_len;
233                 total_size = IMAP->cached_rfc822_len;
234                 text_size = 0;
235         }
236
237         CtdlLogPrintf(CTDL_DEBUG, 
238                 "RFC822: headers=" SIZE_T_FMT 
239                 ", text=" SIZE_T_FMT
240                 ", total=" SIZE_T_FMT "\n",
241                 headers_size, text_size, total_size);
242
243         if (!strcasecmp(whichfmt, "RFC822.SIZE")) {
244                 cprintf("RFC822.SIZE " SIZE_T_FMT, total_size);
245                 return;
246         }
247
248         else if (!strcasecmp(whichfmt, "RFC822")) {
249                 ptr = IMAP->cached_rfc822_data;
250                 bytes_to_send = total_size;
251         }
252
253         else if (!strcasecmp(whichfmt, "RFC822.HEADER")) {
254                 ptr = IMAP->cached_rfc822_data;
255                 bytes_to_send = headers_size;
256         }
257
258         else if (!strcasecmp(whichfmt, "RFC822.TEXT")) {
259                 ptr = &IMAP->cached_rfc822_data[headers_size];
260                 bytes_to_send = text_size;
261         }
262
263         cprintf("%s {" SIZE_T_FMT "}\r\n", whichfmt, bytes_to_send);
264         client_write(ptr, bytes_to_send);
265 }
266
267
268
269 /*
270  * Load a specific part of a message into the temp file to be output to a
271  * client.  FIXME we can handle parts like "2" and "2.1" and even "2.MIME"
272  * but we still can't handle "2.HEADER" (which might not be a problem).
273  *
274  * Note: mime_parser() was called with dont_decode set to 1, so we have the
275  * luxury of simply spewing without having to re-encode.
276  */
277 void imap_load_part(char *name, char *filename, char *partnum, char *disp,
278                     void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
279                     char *cbid, void *cbuserdata)
280 {
281         char mbuf2[SIZ];
282         char *desired_section;
283
284         desired_section = (char *)cbuserdata;
285
286         if (!strcasecmp(partnum, desired_section)) {
287                 client_write(content, length);
288         }
289
290         snprintf(mbuf2, sizeof mbuf2, "%s.MIME", partnum);
291
292         if (!strcasecmp(desired_section, mbuf2)) {
293                 cprintf("Content-type: %s", cbtype);
294                 if (!IsEmptyStr(cbcharset))
295                         cprintf("; charset=\"%s\"", cbcharset);
296                 if (!IsEmptyStr(name))
297                         cprintf("; name=\"%s\"", name);
298                 cprintf("\r\n");
299                 if (!IsEmptyStr(encoding))
300                         cprintf("Content-Transfer-Encoding: %s\r\n", encoding);
301                 if (!IsEmptyStr(encoding)) {
302                         cprintf("Content-Disposition: %s", disp);
303                         if (!IsEmptyStr(filename)) {
304                                 cprintf("; filename=\"%s\"", filename);
305                         }
306                         cprintf("\r\n");
307                 }
308                 cprintf("Content-Length: %ld\r\n", (long)length);
309                 cprintf("\r\n");
310         }
311                         
312
313 }
314
315
316 /* 
317  * Called by imap_fetch_envelope() to output the "From" field.
318  * This is in its own function because its logic is kind of complex.  We
319  * really need to make this suck less.
320  */
321 void imap_output_envelope_from(struct CtdlMessage *msg) {
322         char user[SIZ], node[SIZ], name[SIZ];
323
324         if (!msg) return;
325
326         /* For anonymous messages, it's so easy! */
327         if (!is_room_aide() && (msg->cm_anon_type == MES_ANONONLY)) {
328                 cprintf("((\"----\" NIL \"x\" \"x.org\")) ");
329                 return;
330         }
331         if (!is_room_aide() && (msg->cm_anon_type == MES_ANONOPT)) {
332                 cprintf("((\"anonymous\" NIL \"x\" \"x.org\")) ");
333                 return;
334         }
335
336         /* For everything else, we do stuff. */
337         cprintf("((");                          /* open double-parens */
338         imap_strout(msg->cm_fields['A']);       /* personal name */
339         cprintf(" NIL ");                       /* source route (not used) */
340
341
342         if (msg->cm_fields['F'] != NULL) {
343                 process_rfc822_addr(msg->cm_fields['F'], user, node, name);
344                 imap_strout(user);              /* mailbox name (user id) */
345                 cprintf(" ");
346                 if (!strcasecmp(node, config.c_nodename)) {
347                         imap_strout(config.c_fqdn);
348                 }
349                 else {
350                         imap_strout(node);              /* host name */
351                 }
352         }
353         else {
354                 imap_strout(msg->cm_fields['A']); /* mailbox name (user id) */
355                 cprintf(" ");
356                 imap_strout(msg->cm_fields['N']);       /* host name */
357         }
358         
359         cprintf(")) ");                         /* close double-parens */
360 }
361
362
363
364 /*
365  * Output an envelope address (or set of addresses) in the official,
366  * convoluted, braindead format.  (Note that we can't use this for
367  * the "From" address because its data may come from a number of different
368  * fields.  But we can use it for "To" and possibly others.
369  */
370 void imap_output_envelope_addr(char *addr) {
371         char individual_addr[256];
372         int num_addrs;
373         int i;
374         char user[256];
375         char node[256];
376         char name[256];
377
378         if (addr == NULL) {
379                 cprintf("NIL ");
380                 return;
381         }
382
383         if (IsEmptyStr(addr)) {
384                 cprintf("NIL ");
385                 return;
386         }
387
388         cprintf("(");
389
390         /* How many addresses are listed here? */
391         num_addrs = num_tokens(addr, ',');
392
393         /* Output them one by one. */
394         for (i=0; i<num_addrs; ++i) {
395                 extract_token(individual_addr, addr, i, ',', sizeof individual_addr);
396                 striplt(individual_addr);
397                 process_rfc822_addr(individual_addr, user, node, name);
398                 cprintf("(");
399                 imap_strout(name);
400                 cprintf(" NIL ");
401                 imap_strout(user);
402                 cprintf(" ");
403                 imap_strout(node);
404                 cprintf(")");
405                 if (i < (num_addrs-1)) cprintf(" ");
406         }
407
408         cprintf(") ");
409 }
410
411
412 /*
413  * Implements the ENVELOPE fetch item
414  * 
415  * Note that the imap_strout() function can cleverly output NULL fields as NIL,
416  * so we don't have to check for that condition like we do elsewhere.
417  */
418 void imap_fetch_envelope(struct CtdlMessage *msg) {
419         char datestringbuf[SIZ];
420         time_t msgdate;
421         char *fieldptr = NULL;
422
423         if (!msg) return;
424
425         /* Parse the message date into an IMAP-format date string */
426         if (msg->cm_fields['T'] != NULL) {
427                 msgdate = atol(msg->cm_fields['T']);
428         }
429         else {
430                 msgdate = time(NULL);
431         }
432         datestring(datestringbuf, sizeof datestringbuf,
433                 msgdate, DATESTRING_IMAP);
434
435         /* Now start spewing data fields.  The order is important, as it is
436          * defined by the protocol specification.  Nonexistent fields must
437          * be output as NIL, existent fields must be quoted or literalled.
438          * The imap_strout() function conveniently does all this for us.
439          */
440         cprintf("ENVELOPE (");
441
442         /* Date */
443         imap_strout(datestringbuf);
444         cprintf(" ");
445
446         /* Subject */
447         imap_strout(msg->cm_fields['U']);
448         cprintf(" ");
449
450         /* From */
451         imap_output_envelope_from(msg);
452
453         /* Sender (default to same as 'From' if not present) */
454         fieldptr = rfc822_fetch_field(msg->cm_fields['M'], "Sender");
455         if (fieldptr != NULL) {
456                 imap_output_envelope_addr(fieldptr);
457                 free(fieldptr);
458         }
459         else {
460                 imap_output_envelope_from(msg);
461         }
462
463         /* Reply-to */
464         fieldptr = rfc822_fetch_field(msg->cm_fields['M'], "Reply-to");
465         if (fieldptr != NULL) {
466                 imap_output_envelope_addr(fieldptr);
467                 free(fieldptr);
468         }
469         else {
470                 imap_output_envelope_from(msg);
471         }
472
473         /* To */
474         imap_output_envelope_addr(msg->cm_fields['R']);
475
476         /* Cc (we do it this way because there might be a legacy non-Citadel Cc: field present) */
477         fieldptr = msg->cm_fields['Y'];
478         if (fieldptr != NULL) {
479                 imap_output_envelope_addr(fieldptr);
480         }
481         else {
482                 fieldptr = rfc822_fetch_field(msg->cm_fields['M'], "Cc");
483                 imap_output_envelope_addr(fieldptr);
484                 if (fieldptr != NULL) free(fieldptr);
485         }
486
487         /* Bcc */
488         fieldptr = rfc822_fetch_field(msg->cm_fields['M'], "Bcc");
489         imap_output_envelope_addr(fieldptr);
490         if (fieldptr != NULL) free(fieldptr);
491
492         /* In-reply-to */
493         fieldptr = rfc822_fetch_field(msg->cm_fields['M'], "In-reply-to");
494         imap_strout(fieldptr);
495         cprintf(" ");
496         if (fieldptr != NULL) free(fieldptr);
497
498         /* message ID */
499         imap_strout(msg->cm_fields['I']);
500
501         cprintf(")");
502 }
503
504 /*
505  * This function is called only when CC->redirect_buffer contains a set of
506  * RFC822 headers with no body attached.  Its job is to strip that set of
507  * headers down to *only* the ones we're interested in.
508  */
509 void imap_strip_headers(char *section) {
510         char buf[SIZ];
511         char *which_fields = NULL;
512         int doing_headers = 0;
513         int headers_not = 0;
514         char *parms[SIZ];
515         int num_parms = 0;
516         int i;
517         char *boiled_headers = NULL;
518         int ok = 0;
519         int done_headers = 0;
520         char *ptr = NULL;
521
522         if (CC->redirect_buffer == NULL) return;
523
524         which_fields = strdup(section);
525
526         if (!strncasecmp(which_fields, "HEADER.FIELDS", 13))
527                 doing_headers = 1;
528         if (!strncasecmp(which_fields, "HEADER.FIELDS.NOT", 17))
529                 headers_not = 1;
530
531         for (i=0; which_fields[i]; ++i) {
532                 if (which_fields[i]=='(')
533                         strcpy(which_fields, &which_fields[i+1]);
534         }
535         for (i=0; which_fields[i]; ++i) {
536                 if (which_fields[i]==')') {
537                         which_fields[i] = 0;
538                         break;
539                 }
540         }
541         num_parms = imap_parameterize(parms, which_fields);
542
543         boiled_headers = malloc(CC->redirect_alloc);
544         strcpy(boiled_headers, "");
545
546         ptr = CC->redirect_buffer;
547         ok = 0;
548         do {
549                 ptr = memreadline(ptr, buf, sizeof buf);
550                 if (!isspace(buf[0])) {
551                         ok = 0;
552                         if (doing_headers == 0) ok = 1;
553                         else {
554                                 if (headers_not) ok = 1;
555                                 else ok = 0;
556                                 for (i=0; i<num_parms; ++i) {
557                                         if ( (!strncasecmp(buf, parms[i],
558                                            strlen(parms[i]))) &&
559                                            (buf[strlen(parms[i])]==':') ) {
560                                                 if (headers_not) ok = 0;
561                                                 else ok = 1;
562                                         }
563                                 }
564                         }
565                 }
566
567                 if (ok) {
568                         strcat(boiled_headers, buf);
569                         strcat(boiled_headers, "\r\n");
570                 }
571
572                 if (IsEmptyStr(buf)) done_headers = 1;
573                 if (buf[0]=='\r') done_headers = 1;
574                 if (buf[0]=='\n') done_headers = 1;
575                 if (*ptr == 0) done_headers = 1;
576         } while (!done_headers);
577
578         strcat(boiled_headers, "\r\n");
579
580         /* Now save it back (it'll always be smaller) */
581         strcpy(CC->redirect_buffer, boiled_headers);
582         CC->redirect_len = strlen(boiled_headers);
583
584         free(which_fields);
585         free(boiled_headers);
586 }
587
588
589 /*
590  * Implements the BODY and BODY.PEEK fetch items
591  */
592 void imap_fetch_body(long msgnum, char *item, int is_peek) {
593         struct CtdlMessage *msg = NULL;
594         char section[SIZ];
595         char partial[SIZ];
596         int is_partial = 0;
597         size_t pstart, pbytes;
598         int loading_body_now = 0;
599         int need_body = 1;
600         int burn_the_cache = 0;
601
602         /* extract section */
603         safestrncpy(section, item, sizeof section);
604         if (strchr(section, '[') != NULL) {
605                 stripallbut(section, '[', ']');
606         }
607         CtdlLogPrintf(CTDL_DEBUG, "Section is: %s%s\n", 
608                 section, 
609                 IsEmptyStr(section) ? "(empty)" : "");
610
611         /* Burn the cache if we don't have the same section of the 
612          * same message again.
613          */
614         if (IMAP->cached_body != NULL) {
615                 if (IMAP->cached_bodymsgnum != msgnum) {
616                         burn_the_cache = 1;
617                 }
618                 else if ( (!IMAP->cached_body_withbody) && (need_body) ) {
619                         burn_the_cache = 1;
620                 }
621                 else if (strcasecmp(IMAP->cached_bodypart, section)) {
622                         burn_the_cache = 1;
623                 }
624                 if (burn_the_cache) {
625                         /* Yup, go ahead and burn the cache. */
626                         free(IMAP->cached_body);
627                         IMAP->cached_body_len = 0;
628                         IMAP->cached_body = NULL;
629                         IMAP->cached_bodymsgnum = (-1);
630                         strcpy(IMAP->cached_bodypart, "");
631                 }
632         }
633
634         /* extract partial */
635         safestrncpy(partial, item, sizeof partial);
636         if (strchr(partial, '<') != NULL) {
637                 stripallbut(partial, '<', '>');
638                 is_partial = 1;
639         }
640         if (is_partial == 0) strcpy(partial, "");
641         /* if (!IsEmptyStr(partial)) CtdlLogPrintf(CTDL_DEBUG, "Partial is %s\n", partial); */
642
643         if (IMAP->cached_body == NULL) {
644                 CC->redirect_buffer = malloc(SIZ);
645                 CC->redirect_len = 0;
646                 CC->redirect_alloc = SIZ;
647                 loading_body_now = 1;
648                 msg = CtdlFetchMessage(msgnum, (need_body ? 1 : 0));
649         }
650
651         /* Now figure out what the client wants, and get it */
652
653         if (!loading_body_now) {
654                 /* What we want is already in memory */
655         }
656
657         else if ( (!strcmp(section, "1")) && (msg->cm_format_type != 4) ) {
658                 CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_NONE, 0, 1, SUPPRESS_ENV_TO);
659         }
660
661         else if (!strcmp(section, "")) {
662                 CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_ALL, 0, 1, SUPPRESS_ENV_TO);
663         }
664
665         /*
666          * If the client asked for just headers, or just particular header
667          * fields, strip it down.
668          */
669         else if (!strncasecmp(section, "HEADER", 6)) {
670                 /* This used to work with HEADERS_FAST, but then Apple got stupid with their
671                  * IMAP library and this broke Mail.App and iPhone Mail, so we had to change it
672                  * to HEADERS_ONLY so the trendy hipsters with their iPhones can read mail.
673                  */
674                 CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_ONLY, 0, 1, SUPPRESS_ENV_TO);
675                 imap_strip_headers(section);
676         }
677
678         /*
679          * Strip it down if the client asked for everything _except_ headers.
680          */
681         else if (!strncasecmp(section, "TEXT", 4)) {
682                 CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_NONE, 0, 1, SUPPRESS_ENV_TO);
683         }
684
685         /*
686          * Anything else must be a part specifier.
687          * (Note value of 1 passed as 'dont_decode' so client gets it encoded)
688          */
689         else {
690                 mime_parser(msg->cm_fields['M'], NULL,
691                                 *imap_load_part, NULL, NULL,
692                                 section,
693                                 1);
694         }
695
696         if (loading_body_now) {
697                 IMAP->cached_body = CC->redirect_buffer;
698                 IMAP->cached_body_len = CC->redirect_len;
699                 IMAP->cached_bodymsgnum = msgnum;
700                 IMAP->cached_body_withbody = need_body;
701                 strcpy(IMAP->cached_bodypart, section);
702                 CC->redirect_buffer = NULL;
703                 CC->redirect_len = 0;
704                 CC->redirect_alloc = 0;
705         }
706
707         if (is_partial == 0) {
708                 cprintf("BODY[%s] {" SIZE_T_FMT "}\r\n", section, IMAP->cached_body_len);
709                 pstart = 0;
710                 pbytes = IMAP->cached_body_len;
711         }
712         else {
713                 sscanf(partial, SIZE_T_FMT "." SIZE_T_FMT, &pstart, &pbytes);
714                 if (pbytes > (IMAP->cached_body_len - pstart)) {
715                         pbytes = IMAP->cached_body_len - pstart;
716                 }
717                 cprintf("BODY[%s]<" SIZE_T_FMT "> {" SIZE_T_FMT "}\r\n", section, pstart, pbytes);
718         }
719
720         /* Here we go -- output it */
721         client_write(&IMAP->cached_body[pstart], pbytes);
722
723         if (msg != NULL) {
724                 CtdlFreeMessage(msg);
725         }
726
727         /* Mark this message as "seen" *unless* this is a "peek" operation */
728         if (is_peek == 0) {
729                 CtdlSetSeen(&msgnum, 1, 1, ctdlsetseen_seen, NULL, NULL);
730         }
731 }
732
733 /*
734  * Called immediately before outputting a multipart bodystructure
735  */
736 void imap_fetch_bodystructure_pre(
737                 char *name, char *filename, char *partnum, char *disp,
738                 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
739                 char *cbid, void *cbuserdata
740                 ) {
741
742         cprintf("(");
743 }
744
745
746
747 /*
748  * Called immediately after outputting a multipart bodystructure
749  */
750 void imap_fetch_bodystructure_post(
751                 char *name, char *filename, char *partnum, char *disp,
752                 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
753                 char *cbid, void *cbuserdata
754                 ) {
755
756         char subtype[128];
757
758         cprintf(" ");
759
760         /* disposition */
761         extract_token(subtype, cbtype, 1, '/', sizeof subtype);
762         imap_strout(subtype);
763
764         /* body language */
765         /* cprintf(" NIL"); We thought we needed this at one point, but maybe we don't... */
766
767         cprintf(")");
768 }
769
770
771
772 /*
773  * Output the info for a MIME part in the format required by BODYSTRUCTURE.
774  *
775  */
776 void imap_fetch_bodystructure_part(
777                 char *name, char *filename, char *partnum, char *disp,
778                 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
779                 char *cbid, void *cbuserdata
780                 ) {
781
782         int have_cbtype = 0;
783         int have_encoding = 0;
784         int lines = 0;
785         size_t i;
786         char cbmaintype[128];
787         char cbsubtype[128];
788
789         if (cbtype != NULL) if (!IsEmptyStr(cbtype)) have_cbtype = 1;
790         if (have_cbtype) {
791                 extract_token(cbmaintype, cbtype, 0, '/', sizeof cbmaintype);
792                 extract_token(cbsubtype, cbtype, 1, '/', sizeof cbsubtype);
793         }
794         else {
795                 strcpy(cbmaintype, "TEXT");
796                 strcpy(cbsubtype, "PLAIN");
797         }
798
799         cprintf("(");
800         imap_strout(cbmaintype);                                        /* body type */
801         cprintf(" ");
802         imap_strout(cbsubtype);                                         /* body subtype */
803         cprintf(" ");
804
805         cprintf("(");                                                   /* begin body parameter list */
806
807         /* "NAME" must appear as the first parameter.  This is not required by IMAP,
808          * but the Asterisk voicemail application blindly assumes that NAME will be in
809          * the first position.  If it isn't, it rejects the message.
810          */
811         if (name != NULL) if (!IsEmptyStr(name)) {
812                 cprintf("\"NAME\" ");
813                 imap_strout(name);
814                 cprintf(" ");
815         }
816
817         cprintf("\"CHARSET\" ");
818         if (cbcharset == NULL) {
819                 imap_strout("US-ASCII");
820         }
821         else if (cbcharset[0] == 0) {
822                 imap_strout("US-ASCII");
823         }
824         else {
825                 imap_strout(cbcharset);
826         }
827         cprintf(") ");                                                  /* end body parameter list */
828
829         cprintf("NIL ");                                                /* Body ID */
830         cprintf("NIL ");                                                /* Body description */
831
832         if (encoding != NULL) if (encoding[0] != 0)  have_encoding = 1;
833         if (have_encoding) {
834                 imap_strout(encoding);
835         }
836         else {
837                 imap_strout("7BIT");
838         }
839         cprintf(" ");
840
841         /* The next field is the size of the part in bytes. */
842         cprintf("%ld ", (long)length);  /* bytes */
843
844         /* The next field is the number of lines in the part, if and only
845          * if the part is TEXT.  More gratuitous complexity.
846          */
847         if (!strcasecmp(cbmaintype, "TEXT")) {
848                 if (length) for (i=0; i<length; ++i) {
849                         if (((char *)content)[i] == '\n') ++lines;
850                 }
851                 cprintf("%d ", lines);
852         }
853
854         /* More gratuitous complexity */
855         if ((!strcasecmp(cbmaintype, "MESSAGE"))
856            && (!strcasecmp(cbsubtype, "RFC822"))) {
857                 /* FIXME: message/rfc822 also needs to output the envelope structure,
858                  * body structure, and line count of the encapsulated message.  Fortunately
859                  * there are not yet any clients depending on this, so we can get away
860                  * with not implementing it for now.
861                  */
862         }
863
864         /* MD5 value of body part; we can get away with NIL'ing this */
865         cprintf("NIL ");
866
867         /* Disposition */
868         if (disp == NULL) {
869                 cprintf("NIL");
870         }
871         else if (IsEmptyStr(disp)) {
872                 cprintf("NIL");
873         }
874         else {
875                 cprintf("(");
876                 imap_strout(disp);
877                 if (filename != NULL) if (!IsEmptyStr(filename)) {
878                         cprintf(" (\"FILENAME\" ");
879                         imap_strout(filename);
880                         cprintf(")");
881                 }
882                 cprintf(")");
883         }
884
885         /* Body language (not defined yet) */
886         cprintf(" NIL)");
887 }
888
889
890
891 /*
892  * Spew the BODYSTRUCTURE data for a message.
893  *
894  */
895 void imap_fetch_bodystructure (long msgnum, char *item,
896                 struct CtdlMessage *msg) {
897         char *rfc822 = NULL;
898         char *rfc822_body = NULL;
899         size_t rfc822_len;
900         size_t rfc822_headers_len;
901         size_t rfc822_body_len;
902         char *ptr = NULL;
903         char buf[SIZ];
904         int lines = 0;
905
906         /* Handle NULL message gracefully */
907         if (msg == NULL) {
908                 cprintf("BODYSTRUCTURE (\"TEXT\" \"PLAIN\" "
909                         "(\"CHARSET\" \"US-ASCII\") NIL NIL "
910                         "\"7BIT\" 0 0)");
911                 return;
912         }
913
914         /* For non-RFC822 (ordinary Citadel) messages, this is short and
915          * sweet...
916          */
917         if (msg->cm_format_type != FMT_RFC822) {
918
919                 /* *sigh* We have to RFC822-format the message just to be able
920                  * to measure it.  FIXME use smi cached fields if possible
921                  */
922
923                 CC->redirect_buffer = malloc(SIZ);
924                 CC->redirect_len = 0;
925                 CC->redirect_alloc = SIZ;
926                 CtdlOutputPreLoadedMsg(msg, MT_RFC822, 0, 0, 1, SUPPRESS_ENV_TO);
927                 rfc822 = CC->redirect_buffer;
928                 rfc822_len = CC->redirect_len;
929                 CC->redirect_buffer = NULL;
930                 CC->redirect_len = 0;
931                 CC->redirect_alloc = 0;
932
933                 ptr = rfc822;
934                 do {
935                         ptr = memreadline(ptr, buf, sizeof buf);
936                         ++lines;
937                         if ((IsEmptyStr(buf)) && (rfc822_body == NULL)) {
938                                 rfc822_body = ptr;
939                         }
940                 } while (*ptr != 0);
941
942                 rfc822_headers_len = rfc822_body - rfc822;
943                 rfc822_body_len = rfc822_len - rfc822_headers_len;
944                 free(rfc822);
945
946                 cprintf("BODYSTRUCTURE (\"TEXT\" \"PLAIN\" "
947                         "(\"CHARSET\" \"US-ASCII\") NIL NIL "
948                         "\"7BIT\" " SIZE_T_FMT " %d)", rfc822_body_len, lines);
949
950                 return;
951         }
952
953         /* For messages already stored in RFC822 format, we have to parse. */
954         cprintf("BODYSTRUCTURE ");
955         mime_parser(msg->cm_fields['M'],
956                         NULL,
957                         *imap_fetch_bodystructure_part, /* part */
958                         *imap_fetch_bodystructure_pre,  /* pre-multi */
959                         *imap_fetch_bodystructure_post, /* post-multi */
960                         NULL,
961                         1);     /* don't decode -- we want it as-is */
962 }
963
964
965 /*
966  * imap_do_fetch() calls imap_do_fetch_msg() to output the data of an
967  * individual message, once it has been selected for output.
968  */
969 void imap_do_fetch_msg(int seq, int num_items, char **itemlist) {
970         int i;
971         struct CtdlMessage *msg = NULL;
972         int body_loaded = 0;
973
974         /* Don't attempt to fetch bogus messages or UID's */
975         if (seq < 1) return;
976         if (IMAP->msgids[seq-1] < 1L) return;
977
978         buffer_output();
979         cprintf("* %d FETCH (", seq);
980
981         for (i=0; i<num_items; ++i) {
982
983                 /* Fetchable without going to the message store at all */
984                 if (!strcasecmp(itemlist[i], "UID")) {
985                         imap_fetch_uid(seq);
986                 }
987                 else if (!strcasecmp(itemlist[i], "FLAGS")) {
988                         imap_fetch_flags(seq-1);
989                 }
990
991                 /* Potentially fetchable from cache, if the client requests
992                  * stuff from the same message several times in a row.
993                  */
994                 else if (!strcasecmp(itemlist[i], "RFC822")) {
995                         imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i]);
996                 }
997                 else if (!strcasecmp(itemlist[i], "RFC822.HEADER")) {
998                         imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i]);
999                 }
1000                 else if (!strcasecmp(itemlist[i], "RFC822.SIZE")) {
1001                         imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i]);
1002                 }
1003                 else if (!strcasecmp(itemlist[i], "RFC822.TEXT")) {
1004                         imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i]);
1005                 }
1006
1007                 /* BODY fetches do their own fetching and caching too. */
1008                 else if (!strncasecmp(itemlist[i], "BODY[", 5)) {
1009                         imap_fetch_body(IMAP->msgids[seq-1], itemlist[i], 0);
1010                 }
1011                 else if (!strncasecmp(itemlist[i], "BODY.PEEK[", 10)) {
1012                         imap_fetch_body(IMAP->msgids[seq-1], itemlist[i], 1);
1013                 }
1014
1015                 /* Otherwise, load the message into memory.
1016                  */
1017                 else if (!strcasecmp(itemlist[i], "BODYSTRUCTURE")) {
1018                         if ((msg != NULL) && (!body_loaded)) {
1019                                 CtdlFreeMessage(msg);   /* need the whole thing */
1020                                 msg = NULL;
1021                         }
1022                         if (msg == NULL) {
1023                                 msg = CtdlFetchMessage(IMAP->msgids[seq-1], 1);
1024                                 body_loaded = 1;
1025                         }
1026                         imap_fetch_bodystructure(IMAP->msgids[seq-1],
1027                                         itemlist[i], msg);
1028                 }
1029                 else if (!strcasecmp(itemlist[i], "ENVELOPE")) {
1030                         if (msg == NULL) {
1031                                 msg = CtdlFetchMessage(IMAP->msgids[seq-1], 0);
1032                                 body_loaded = 0;
1033                         }
1034                         imap_fetch_envelope(msg);
1035                 }
1036                 else if (!strcasecmp(itemlist[i], "INTERNALDATE")) {
1037                         if (msg == NULL) {
1038                                 msg = CtdlFetchMessage(IMAP->msgids[seq-1], 0);
1039                                 body_loaded = 0;
1040                         }
1041                         imap_fetch_internaldate(msg);
1042                 }
1043
1044                 if (i != num_items-1) cprintf(" ");
1045         }
1046
1047         cprintf(")\r\n");
1048         unbuffer_output();
1049         if (msg != NULL) {
1050                 CtdlFreeMessage(msg);
1051         }
1052 }
1053
1054
1055
1056 /*
1057  * imap_fetch() calls imap_do_fetch() to do its actual work, once it's
1058  * validated and boiled down the request a bit.
1059  */
1060 void imap_do_fetch(int num_items, char **itemlist) {
1061         int i;
1062
1063         if (IMAP->num_msgs > 0) {
1064                 for (i = 0; i < IMAP->num_msgs; ++i) {
1065
1066                         /* Abort the fetch loop if the session breaks.
1067                          * This is important for users who keep mailboxes
1068                          * that are too big *and* are too impatient to
1069                          * let them finish loading.  :)
1070                          */
1071                         if (CC->kill_me) return;
1072
1073                         /* Get any message marked for fetch. */
1074                         if (IMAP->flags[i] & IMAP_SELECTED) {
1075                                 imap_do_fetch_msg(i+1, num_items, itemlist);
1076                         }
1077                 }
1078         }
1079 }
1080
1081
1082
1083 /*
1084  * Back end for imap_handle_macros()
1085  * Note that this function *only* looks at the beginning of the string.  It
1086  * is not a generic search-and-replace function.
1087  */
1088 void imap_macro_replace(char *str, char *find, char *replace) {
1089         char holdbuf[SIZ];
1090         int findlen;
1091
1092         findlen = strlen(find);
1093
1094         if (!strncasecmp(str, find, findlen)) {
1095                 if (str[findlen]==' ') {
1096                         strcpy(holdbuf, &str[findlen+1]);
1097                         strcpy(str, replace);
1098                         strcat(str, " ");
1099                         strcat(str, holdbuf);
1100                 }
1101                 if (str[findlen]==0) {
1102                         strcpy(holdbuf, &str[findlen+1]);
1103                         strcpy(str, replace);
1104                 }
1105         }
1106 }
1107
1108
1109
1110 /*
1111  * Handle macros embedded in FETCH data items.
1112  * (What the heck are macros doing in a wire protocol?  Are we trying to save
1113  * the computer at the other end the trouble of typing a lot of characters?)
1114  */
1115 void imap_handle_macros(char *str) {
1116         int i;
1117         int nest = 0;
1118
1119         for (i=0; str[i]; ++i) {
1120                 if (str[i]=='(') ++nest;
1121                 if (str[i]=='[') ++nest;
1122                 if (str[i]=='<') ++nest;
1123                 if (str[i]=='{') ++nest;
1124                 if (str[i]==')') --nest;
1125                 if (str[i]==']') --nest;
1126                 if (str[i]=='>') --nest;
1127                 if (str[i]=='}') --nest;
1128
1129                 if (nest <= 0) {
1130                         imap_macro_replace(&str[i],
1131                                 "ALL",
1132                                 "FLAGS INTERNALDATE RFC822.SIZE ENVELOPE"
1133                         );
1134                         imap_macro_replace(&str[i],
1135                                 "BODY",
1136                                 "BODYSTRUCTURE"
1137                         );
1138                         imap_macro_replace(&str[i],
1139                                 "FAST",
1140                                 "FLAGS INTERNALDATE RFC822.SIZE"
1141                         );
1142                         imap_macro_replace(&str[i],
1143                                 "FULL",
1144                                 "FLAGS INTERNALDATE RFC822.SIZE ENVELOPE BODY"
1145                         );
1146                 }
1147         }
1148 }
1149
1150
1151 /*
1152  * Break out the data items requested, possibly a parenthesized list.
1153  * Returns the number of data items, or -1 if the list is invalid.
1154  * NOTE: this function alters the string it is fed, and uses it as a buffer
1155  * to hold the data for the pointers it returns.
1156  */
1157 int imap_extract_data_items(char **argv, char *items) {
1158         int num_items = 0;
1159         int nest = 0;
1160         int i;
1161         char *start;
1162         long initial_len;
1163
1164         /* Convert all whitespace to ordinary space characters. */
1165         for (i=0; items[i]; ++i) {
1166                 if (isspace(items[i])) items[i]=' ';
1167         }
1168
1169         /* Strip leading and trailing whitespace, then strip leading and
1170          * trailing parentheses if it's a list
1171          */
1172         striplt(items);
1173         if ( (items[0]=='(') && (items[strlen(items)-1]==')') ) {
1174                 items[strlen(items)-1] = 0;
1175                 strcpy(items, &items[1]);
1176                 striplt(items);
1177         }
1178
1179         /* Parse any macro data items */
1180         imap_handle_macros(items);
1181
1182         /*
1183          * Now break out the data items.  We throw in one trailing space in
1184          * order to avoid having to break out the last one manually.
1185          */
1186         strcat(items, " ");
1187         start = items;
1188         initial_len = strlen(items);
1189         for (i=0; i<initial_len; ++i) {
1190                 if (items[i]=='(') ++nest;
1191                 if (items[i]=='[') ++nest;
1192                 if (items[i]=='<') ++nest;
1193                 if (items[i]=='{') ++nest;
1194                 if (items[i]==')') --nest;
1195                 if (items[i]==']') --nest;
1196                 if (items[i]=='>') --nest;
1197                 if (items[i]=='}') --nest;
1198
1199                 if (nest <= 0) if (items[i]==' ') {
1200                         items[i] = 0;
1201                         argv[num_items++] = start;
1202                         start = &items[i+1];
1203                 }
1204         }
1205
1206         return(num_items);
1207
1208 }
1209
1210
1211 /*
1212  * One particularly hideous aspect of IMAP is that we have to allow the client
1213  * to specify arbitrary ranges and/or sets of messages to fetch.  Citadel IMAP
1214  * handles this by setting the IMAP_SELECTED flag for each message specified in
1215  * the ranges/sets, then looping through the message array, outputting messages
1216  * with the flag set.  We don't bother returning an error if an out-of-range
1217  * number is specified (we just return quietly) because any client braindead
1218  * enough to request a bogus message number isn't going to notice the
1219  * difference anyway.
1220  *
1221  * This function clears out the IMAP_SELECTED bits, then sets that bit for each
1222  * message included in the specified range.
1223  *
1224  * Set is_uid to 1 to fetch by UID instead of sequence number.
1225  */
1226 void imap_pick_range(char *supplied_range, int is_uid) {
1227         int i;
1228         int num_sets;
1229         int s;
1230         char setstr[SIZ], lostr[SIZ], histr[SIZ];
1231         long lo, hi;
1232         char actual_range[SIZ];
1233         struct citimap *Imap;
1234
1235         /* 
1236          * Handle the "ALL" macro
1237          */
1238         if (!strcasecmp(supplied_range, "ALL")) {
1239                 safestrncpy(actual_range, "1:*", sizeof actual_range);
1240         }
1241         else {
1242                 safestrncpy(actual_range, supplied_range, sizeof actual_range);
1243         }
1244
1245         Imap = IMAP;
1246         /*
1247          * Clear out the IMAP_SELECTED flags for all messages.
1248          */
1249         for (i = 0; i < Imap->num_msgs; ++i) {
1250                 Imap->flags[i] = Imap->flags[i] & ~IMAP_SELECTED;
1251         }
1252
1253         /*
1254          * Now set it for all specified messages.
1255          */
1256         num_sets = num_tokens(actual_range, ',');
1257         for (s=0; s<num_sets; ++s) {
1258                 extract_token(setstr, actual_range, s, ',', sizeof setstr);
1259
1260                 extract_token(lostr, setstr, 0, ':', sizeof lostr);
1261                 if (num_tokens(setstr, ':') >= 2) {
1262                         extract_token(histr, setstr, 1, ':', sizeof histr);
1263                         if (!strcmp(histr, "*")) snprintf(histr, sizeof histr, "%ld", LONG_MAX);
1264                 } 
1265                 else {
1266                         safestrncpy(histr, lostr, sizeof histr);
1267                 }
1268                 lo = atol(lostr);
1269                 hi = atol(histr);
1270
1271                 /* Loop through the array, flipping bits where appropriate */
1272                 for (i = 1; i <= Imap->num_msgs; ++i) {
1273                         if (is_uid) {   /* fetch by sequence number */
1274                                 if ( (Imap->msgids[i-1]>=lo)
1275                                    && (Imap->msgids[i-1]<=hi)) {
1276                                         Imap->flags[i-1] |= IMAP_SELECTED;
1277                                 }
1278                         }
1279                         else {          /* fetch by uid */
1280                                 if ( (i>=lo) && (i<=hi)) {
1281                                         Imap->flags[i-1] |= IMAP_SELECTED;
1282                                 }
1283                         }
1284                 }
1285         }
1286
1287 }
1288
1289
1290
1291 /*
1292  * This function is called by the main command loop.
1293  */
1294 void imap_fetch(int num_parms, char *parms[]) {
1295         char items[SIZ];
1296         char *itemlist[512];
1297         int num_items;
1298         int i;
1299
1300         if (num_parms < 4) {
1301                 cprintf("%s BAD invalid parameters\r\n", parms[0]);
1302                 return;
1303         }
1304
1305         imap_pick_range(parms[2], 0);
1306
1307         strcpy(items, "");
1308         for (i=3; i<num_parms; ++i) {
1309                 strcat(items, parms[i]);
1310                 if (i < (num_parms-1)) strcat(items, " ");
1311         }
1312
1313         num_items = imap_extract_data_items(itemlist, items);
1314         if (num_items < 1) {
1315                 cprintf("%s BAD invalid data item list\r\n", parms[0]);
1316                 return;
1317         }
1318
1319         imap_do_fetch(num_items, itemlist);
1320         cprintf("%s OK FETCH completed\r\n", parms[0]);
1321 }
1322
1323 /*
1324  * This function is called by the main command loop.
1325  */
1326 void imap_uidfetch(int num_parms, char *parms[]) {
1327         char items[SIZ];
1328         char *itemlist[512];
1329         int num_items;
1330         int i;
1331         int have_uid_item = 0;
1332
1333         if (num_parms < 5) {
1334                 cprintf("%s BAD invalid parameters\r\n", parms[0]);
1335                 return;
1336         }
1337
1338         imap_pick_range(parms[3], 1);
1339
1340         strcpy(items, "");
1341         for (i=4; i<num_parms; ++i) {
1342                 strcat(items, parms[i]);
1343                 if (i < (num_parms-1)) strcat(items, " ");
1344         }
1345
1346         num_items = imap_extract_data_items(itemlist, items);
1347         if (num_items < 1) {
1348                 cprintf("%s BAD invalid data item list\r\n", parms[0]);
1349                 return;
1350         }
1351
1352         /* If the "UID" item was not included, we include it implicitly
1353          * (at the beginning) because this is a UID FETCH command
1354          */
1355         for (i=0; i<num_items; ++i) {
1356                 if (!strcasecmp(itemlist[i], "UID")) ++have_uid_item;
1357         }
1358         if (have_uid_item == 0) {
1359                 memmove(&itemlist[1], &itemlist[0], (sizeof(itemlist[0]) * num_items));
1360                 ++num_items;
1361                 itemlist[0] = "UID";
1362         }
1363
1364         imap_do_fetch(num_items, itemlist);
1365         cprintf("%s OK UID FETCH completed\r\n", parms[0]);
1366 }
1367
1368