4 * Implements the FETCH command in IMAP.
5 * This is a good example of the protocol's gratuitous complexity.
7 * Copyright (c) 2001-2009 by the citadel.org team
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.
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.
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
33 #include <sys/types.h>
35 #if TIME_WITH_SYS_TIME
36 # include <sys/time.h>
40 # include <sys/time.h>
50 #include <libcitadel.h>
53 #include "sysdep_decls.h"
54 #include "citserver.h"
61 #include "internet_addressing.h"
62 #include "serv_imap.h"
63 #include "imap_tools.h"
64 #include "imap_fetch.h"
66 #include "ctdl_module.h"
71 * Individual field functions for imap_do_fetch_msg() ...
74 void imap_fetch_uid(int seq) {
75 cprintf("UID %ld", IMAP->msgids[seq-1]);
78 void imap_fetch_flags(int seq) {
79 int num_flags_printed = 0;
81 if (IMAP->flags[seq] & IMAP_DELETED) {
82 if (num_flags_printed > 0) cprintf(" ");
86 if (IMAP->flags[seq] & IMAP_SEEN) {
87 if (num_flags_printed > 0) cprintf(" ");
91 if (IMAP->flags[seq] & IMAP_ANSWERED) {
92 if (num_flags_printed > 0) cprintf(" ");
93 cprintf("\\Answered");
96 if (IMAP->flags[seq] & IMAP_RECENT) {
97 if (num_flags_printed > 0) cprintf(" ");
104 void imap_fetch_internaldate(struct CtdlMessage *msg) {
109 if (msg->cm_fields['T'] != NULL) {
110 msgdate = atol(msg->cm_fields['T']);
113 msgdate = time(NULL);
116 datestring(buf, sizeof buf, msgdate, DATESTRING_IMAP);
117 cprintf("INTERNALDATE \"%s\"", buf);
122 * Fetch RFC822-formatted messages.
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)
130 void imap_fetch_rfc822(long msgnum, char *whichfmt) {
133 size_t headers_size, text_size, total_size;
134 size_t bytes_to_send = 0;
136 int need_to_rewrite_metadata = 0;
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...
143 if ( (!strcasecmp(whichfmt, "RFC822"))
144 || (!strcasecmp(whichfmt, "RFC822.TEXT")) ) {
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.
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);
157 need_to_rewrite_metadata = 1;
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.
167 if ((IMAP->cached_rfc822_data != NULL)
168 && (IMAP->cached_rfc822_msgnum == msgnum)
169 && (IMAP->cached_rfc822_withbody || (!need_body)) ) {
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;
180 /* At this point, we now can fetch and convert the message iff it's not
181 * the one we had cached.
183 if (IMAP->cached_rfc822_data == NULL) {
185 * Load the message into memory for translation & measurement
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
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;
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.
217 ptr = IMAP->cached_rfc822_data;
219 ptr = memreadline(ptr, buf, sizeof buf);
222 if (IsEmptyStr(buf)) {
223 headers_size = ptr - IMAP->cached_rfc822_data;
226 } while ( (headers_size == 0) && (*ptr != 0) );
228 total_size = IMAP->cached_rfc822_len;
229 text_size = total_size - headers_size;
232 headers_size = IMAP->cached_rfc822_len;
233 total_size = IMAP->cached_rfc822_len;
237 CtdlLogPrintf(CTDL_DEBUG,
238 "RFC822: headers=" SIZE_T_FMT
240 ", total=" SIZE_T_FMT "\n",
241 headers_size, text_size, total_size);
243 if (!strcasecmp(whichfmt, "RFC822.SIZE")) {
244 cprintf("RFC822.SIZE " SIZE_T_FMT, total_size);
248 else if (!strcasecmp(whichfmt, "RFC822")) {
249 ptr = IMAP->cached_rfc822_data;
250 bytes_to_send = total_size;
253 else if (!strcasecmp(whichfmt, "RFC822.HEADER")) {
254 ptr = IMAP->cached_rfc822_data;
255 bytes_to_send = headers_size;
258 else if (!strcasecmp(whichfmt, "RFC822.TEXT")) {
259 ptr = &IMAP->cached_rfc822_data[headers_size];
260 bytes_to_send = text_size;
263 cprintf("%s {" SIZE_T_FMT "}\r\n", whichfmt, bytes_to_send);
264 client_write(ptr, bytes_to_send);
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).
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.
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)
282 char *desired_section;
284 desired_section = (char *)cbuserdata;
286 if (!strcasecmp(partnum, desired_section)) {
287 client_write(content, length);
290 snprintf(mbuf2, sizeof mbuf2, "%s.MIME", partnum);
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);
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);
308 cprintf("Content-Length: %ld\r\n", (long)length);
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.
321 void imap_output_envelope_from(struct CtdlMessage *msg) {
322 char user[SIZ], node[SIZ], name[SIZ];
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\")) ");
331 if (!is_room_aide() && (msg->cm_anon_type == MES_ANONOPT)) {
332 cprintf("((\"anonymous\" NIL \"x\" \"x.org\")) ");
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) */
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) */
346 if (!strcasecmp(node, config.c_nodename)) {
347 imap_strout(config.c_fqdn);
350 imap_strout(node); /* host name */
354 imap_strout(msg->cm_fields['A']); /* mailbox name (user id) */
356 imap_strout(msg->cm_fields['N']); /* host name */
359 cprintf(")) "); /* close double-parens */
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.
370 void imap_output_envelope_addr(char *addr) {
371 char individual_addr[256];
383 if (IsEmptyStr(addr)) {
390 /* How many addresses are listed here? */
391 num_addrs = num_tokens(addr, ',');
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);
405 if (i < (num_addrs-1)) cprintf(" ");
413 * Implements the ENVELOPE fetch item
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.
418 void imap_fetch_envelope(struct CtdlMessage *msg) {
419 char datestringbuf[SIZ];
421 char *fieldptr = NULL;
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']);
430 msgdate = time(NULL);
432 datestring(datestringbuf, sizeof datestringbuf,
433 msgdate, DATESTRING_IMAP);
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.
440 cprintf("ENVELOPE (");
443 imap_strout(datestringbuf);
447 imap_strout(msg->cm_fields['U']);
451 imap_output_envelope_from(msg);
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);
460 imap_output_envelope_from(msg);
464 fieldptr = rfc822_fetch_field(msg->cm_fields['M'], "Reply-to");
465 if (fieldptr != NULL) {
466 imap_output_envelope_addr(fieldptr);
470 imap_output_envelope_from(msg);
474 imap_output_envelope_addr(msg->cm_fields['R']);
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);
482 fieldptr = rfc822_fetch_field(msg->cm_fields['M'], "Cc");
483 imap_output_envelope_addr(fieldptr);
484 if (fieldptr != NULL) free(fieldptr);
488 fieldptr = rfc822_fetch_field(msg->cm_fields['M'], "Bcc");
489 imap_output_envelope_addr(fieldptr);
490 if (fieldptr != NULL) free(fieldptr);
493 fieldptr = rfc822_fetch_field(msg->cm_fields['M'], "In-reply-to");
494 imap_strout(fieldptr);
496 if (fieldptr != NULL) free(fieldptr);
499 imap_strout(msg->cm_fields['I']);
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.
509 void imap_strip_headers(char *section) {
511 char *which_fields = NULL;
512 int doing_headers = 0;
517 char *boiled_headers = NULL;
519 int done_headers = 0;
522 if (CC->redirect_buffer == NULL) return;
524 which_fields = strdup(section);
526 if (!strncasecmp(which_fields, "HEADER.FIELDS", 13))
528 if (!strncasecmp(which_fields, "HEADER.FIELDS.NOT", 17))
531 for (i=0; which_fields[i]; ++i) {
532 if (which_fields[i]=='(')
533 strcpy(which_fields, &which_fields[i+1]);
535 for (i=0; which_fields[i]; ++i) {
536 if (which_fields[i]==')') {
541 num_parms = imap_parameterize(parms, which_fields);
543 boiled_headers = malloc(CC->redirect_alloc);
544 strcpy(boiled_headers, "");
546 ptr = CC->redirect_buffer;
549 ptr = memreadline(ptr, buf, sizeof buf);
550 if (!isspace(buf[0])) {
552 if (doing_headers == 0) ok = 1;
554 if (headers_not) ok = 1;
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;
568 strcat(boiled_headers, buf);
569 strcat(boiled_headers, "\r\n");
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);
578 strcat(boiled_headers, "\r\n");
580 /* Now save it back (it'll always be smaller) */
581 strcpy(CC->redirect_buffer, boiled_headers);
582 CC->redirect_len = strlen(boiled_headers);
585 free(boiled_headers);
590 * Implements the BODY and BODY.PEEK fetch items
592 void imap_fetch_body(long msgnum, char *item, int is_peek) {
593 struct CtdlMessage *msg = NULL;
597 size_t pstart, pbytes;
598 int loading_body_now = 0;
600 int burn_the_cache = 0;
602 /* extract section */
603 safestrncpy(section, item, sizeof section);
604 if (strchr(section, '[') != NULL) {
605 stripallbut(section, '[', ']');
607 CtdlLogPrintf(CTDL_DEBUG, "Section is: %s%s\n",
609 IsEmptyStr(section) ? "(empty)" : "");
611 /* Burn the cache if we don't have the same section of the
612 * same message again.
614 if (IMAP->cached_body != NULL) {
615 if (IMAP->cached_bodymsgnum != msgnum) {
618 else if ( (!IMAP->cached_body_withbody) && (need_body) ) {
621 else if (strcasecmp(IMAP->cached_bodypart, section)) {
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, "");
634 /* extract partial */
635 safestrncpy(partial, item, sizeof partial);
636 if (strchr(partial, '<') != NULL) {
637 stripallbut(partial, '<', '>');
640 if (is_partial == 0) strcpy(partial, "");
641 /* if (!IsEmptyStr(partial)) CtdlLogPrintf(CTDL_DEBUG, "Partial is %s\n", partial); */
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));
651 /* Now figure out what the client wants, and get it */
653 if (!loading_body_now) {
654 /* What we want is already in memory */
657 else if ( (!strcmp(section, "1")) && (msg->cm_format_type != 4) ) {
658 CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_NONE, 0, 1, SUPPRESS_ENV_TO);
661 else if (!strcmp(section, "")) {
662 CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_ALL, 0, 1, SUPPRESS_ENV_TO);
666 * If the client asked for just headers, or just particular header
667 * fields, strip it down.
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.
674 CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_ONLY, 0, 1, SUPPRESS_ENV_TO);
675 imap_strip_headers(section);
679 * Strip it down if the client asked for everything _except_ headers.
681 else if (!strncasecmp(section, "TEXT", 4)) {
682 CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_NONE, 0, 1, SUPPRESS_ENV_TO);
686 * Anything else must be a part specifier.
687 * (Note value of 1 passed as 'dont_decode' so client gets it encoded)
690 mime_parser(msg->cm_fields['M'], NULL,
691 *imap_load_part, NULL, NULL,
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;
707 if (is_partial == 0) {
708 cprintf("BODY[%s] {" SIZE_T_FMT "}\r\n", section, IMAP->cached_body_len);
710 pbytes = IMAP->cached_body_len;
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;
717 cprintf("BODY[%s]<" SIZE_T_FMT "> {" SIZE_T_FMT "}\r\n", section, pstart, pbytes);
720 /* Here we go -- output it */
721 client_write(&IMAP->cached_body[pstart], pbytes);
724 CtdlFreeMessage(msg);
727 /* Mark this message as "seen" *unless* this is a "peek" operation */
729 CtdlSetSeen(&msgnum, 1, 1, ctdlsetseen_seen, NULL, NULL);
734 * Called immediately before outputting a multipart bodystructure
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
748 * Called immediately after outputting a multipart bodystructure
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
761 extract_token(subtype, cbtype, 1, '/', sizeof subtype);
762 imap_strout(subtype);
765 /* cprintf(" NIL"); We thought we needed this at one point, but maybe we don't... */
773 * Output the info for a MIME part in the format required by BODYSTRUCTURE.
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
783 int have_encoding = 0;
786 char cbmaintype[128];
789 if (cbtype != NULL) if (!IsEmptyStr(cbtype)) have_cbtype = 1;
791 extract_token(cbmaintype, cbtype, 0, '/', sizeof cbmaintype);
792 extract_token(cbsubtype, cbtype, 1, '/', sizeof cbsubtype);
795 strcpy(cbmaintype, "TEXT");
796 strcpy(cbsubtype, "PLAIN");
800 imap_strout(cbmaintype); /* body type */
802 imap_strout(cbsubtype); /* body subtype */
805 cprintf("("); /* begin body parameter list */
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.
811 if (name != NULL) if (!IsEmptyStr(name)) {
812 cprintf("\"NAME\" ");
817 cprintf("\"CHARSET\" ");
818 if (cbcharset == NULL) {
819 imap_strout("US-ASCII");
821 else if (cbcharset[0] == 0) {
822 imap_strout("US-ASCII");
825 imap_strout(cbcharset);
827 cprintf(") "); /* end body parameter list */
829 cprintf("NIL "); /* Body ID */
830 cprintf("NIL "); /* Body description */
832 if (encoding != NULL) if (encoding[0] != 0) have_encoding = 1;
834 imap_strout(encoding);
841 /* The next field is the size of the part in bytes. */
842 cprintf("%ld ", (long)length); /* bytes */
844 /* The next field is the number of lines in the part, if and only
845 * if the part is TEXT. More gratuitous complexity.
847 if (!strcasecmp(cbmaintype, "TEXT")) {
848 if (length) for (i=0; i<length; ++i) {
849 if (((char *)content)[i] == '\n') ++lines;
851 cprintf("%d ", lines);
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.
864 /* MD5 value of body part; we can get away with NIL'ing this */
871 else if (IsEmptyStr(disp)) {
877 if (filename != NULL) if (!IsEmptyStr(filename)) {
878 cprintf(" (\"FILENAME\" ");
879 imap_strout(filename);
885 /* Body language (not defined yet) */
892 * Spew the BODYSTRUCTURE data for a message.
895 void imap_fetch_bodystructure (long msgnum, char *item,
896 struct CtdlMessage *msg) {
898 char *rfc822_body = NULL;
900 size_t rfc822_headers_len;
901 size_t rfc822_body_len;
906 /* Handle NULL message gracefully */
908 cprintf("BODYSTRUCTURE (\"TEXT\" \"PLAIN\" "
909 "(\"CHARSET\" \"US-ASCII\") NIL NIL "
914 /* For non-RFC822 (ordinary Citadel) messages, this is short and
917 if (msg->cm_format_type != FMT_RFC822) {
919 /* *sigh* We have to RFC822-format the message just to be able
920 * to measure it. FIXME use smi cached fields if possible
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;
935 ptr = memreadline(ptr, buf, sizeof buf);
937 if ((IsEmptyStr(buf)) && (rfc822_body == NULL)) {
942 rfc822_headers_len = rfc822_body - rfc822;
943 rfc822_body_len = rfc822_len - rfc822_headers_len;
946 cprintf("BODYSTRUCTURE (\"TEXT\" \"PLAIN\" "
947 "(\"CHARSET\" \"US-ASCII\") NIL NIL "
948 "\"7BIT\" " SIZE_T_FMT " %d)", rfc822_body_len, lines);
953 /* For messages already stored in RFC822 format, we have to parse. */
954 cprintf("BODYSTRUCTURE ");
955 mime_parser(msg->cm_fields['M'],
957 *imap_fetch_bodystructure_part, /* part */
958 *imap_fetch_bodystructure_pre, /* pre-multi */
959 *imap_fetch_bodystructure_post, /* post-multi */
961 1); /* don't decode -- we want it as-is */
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.
969 void imap_do_fetch_msg(int seq, int num_items, char **itemlist) {
971 struct CtdlMessage *msg = NULL;
974 /* Don't attempt to fetch bogus messages or UID's */
976 if (IMAP->msgids[seq-1] < 1L) return;
979 cprintf("* %d FETCH (", seq);
981 for (i=0; i<num_items; ++i) {
983 /* Fetchable without going to the message store at all */
984 if (!strcasecmp(itemlist[i], "UID")) {
987 else if (!strcasecmp(itemlist[i], "FLAGS")) {
988 imap_fetch_flags(seq-1);
991 /* Potentially fetchable from cache, if the client requests
992 * stuff from the same message several times in a row.
994 else if (!strcasecmp(itemlist[i], "RFC822")) {
995 imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i]);
997 else if (!strcasecmp(itemlist[i], "RFC822.HEADER")) {
998 imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i]);
1000 else if (!strcasecmp(itemlist[i], "RFC822.SIZE")) {
1001 imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i]);
1003 else if (!strcasecmp(itemlist[i], "RFC822.TEXT")) {
1004 imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i]);
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);
1011 else if (!strncasecmp(itemlist[i], "BODY.PEEK[", 10)) {
1012 imap_fetch_body(IMAP->msgids[seq-1], itemlist[i], 1);
1015 /* Otherwise, load the message into memory.
1017 else if (!strcasecmp(itemlist[i], "BODYSTRUCTURE")) {
1018 if ((msg != NULL) && (!body_loaded)) {
1019 CtdlFreeMessage(msg); /* need the whole thing */
1023 msg = CtdlFetchMessage(IMAP->msgids[seq-1], 1);
1026 imap_fetch_bodystructure(IMAP->msgids[seq-1],
1029 else if (!strcasecmp(itemlist[i], "ENVELOPE")) {
1031 msg = CtdlFetchMessage(IMAP->msgids[seq-1], 0);
1034 imap_fetch_envelope(msg);
1036 else if (!strcasecmp(itemlist[i], "INTERNALDATE")) {
1038 msg = CtdlFetchMessage(IMAP->msgids[seq-1], 0);
1041 imap_fetch_internaldate(msg);
1044 if (i != num_items-1) cprintf(" ");
1050 CtdlFreeMessage(msg);
1057 * imap_fetch() calls imap_do_fetch() to do its actual work, once it's
1058 * validated and boiled down the request a bit.
1060 void imap_do_fetch(int num_items, char **itemlist) {
1063 if (IMAP->num_msgs > 0) {
1064 for (i = 0; i < IMAP->num_msgs; ++i) {
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. :)
1071 if (CC->kill_me) return;
1073 /* Get any message marked for fetch. */
1074 if (IMAP->flags[i] & IMAP_SELECTED) {
1075 imap_do_fetch_msg(i+1, num_items, itemlist);
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.
1088 void imap_macro_replace(char *str, char *find, char *replace) {
1092 findlen = strlen(find);
1094 if (!strncasecmp(str, find, findlen)) {
1095 if (str[findlen]==' ') {
1096 strcpy(holdbuf, &str[findlen+1]);
1097 strcpy(str, replace);
1099 strcat(str, holdbuf);
1101 if (str[findlen]==0) {
1102 strcpy(holdbuf, &str[findlen+1]);
1103 strcpy(str, replace);
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?)
1115 void imap_handle_macros(char *str) {
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;
1130 imap_macro_replace(&str[i],
1132 "FLAGS INTERNALDATE RFC822.SIZE ENVELOPE"
1134 imap_macro_replace(&str[i],
1138 imap_macro_replace(&str[i],
1140 "FLAGS INTERNALDATE RFC822.SIZE"
1142 imap_macro_replace(&str[i],
1144 "FLAGS INTERNALDATE RFC822.SIZE ENVELOPE BODY"
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.
1157 int imap_extract_data_items(char **argv, char *items) {
1164 /* Convert all whitespace to ordinary space characters. */
1165 for (i=0; items[i]; ++i) {
1166 if (isspace(items[i])) items[i]=' ';
1169 /* Strip leading and trailing whitespace, then strip leading and
1170 * trailing parentheses if it's a list
1173 if ( (items[0]=='(') && (items[strlen(items)-1]==')') ) {
1174 items[strlen(items)-1] = 0;
1175 strcpy(items, &items[1]);
1179 /* Parse any macro data items */
1180 imap_handle_macros(items);
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.
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;
1199 if (nest <= 0) if (items[i]==' ') {
1201 argv[num_items++] = start;
1202 start = &items[i+1];
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.
1221 * This function clears out the IMAP_SELECTED bits, then sets that bit for each
1222 * message included in the specified range.
1224 * Set is_uid to 1 to fetch by UID instead of sequence number.
1226 void imap_pick_range(char *supplied_range, int is_uid) {
1230 char setstr[SIZ], lostr[SIZ], histr[SIZ];
1232 char actual_range[SIZ];
1233 struct citimap *Imap;
1236 * Handle the "ALL" macro
1238 if (!strcasecmp(supplied_range, "ALL")) {
1239 safestrncpy(actual_range, "1:*", sizeof actual_range);
1242 safestrncpy(actual_range, supplied_range, sizeof actual_range);
1247 * Clear out the IMAP_SELECTED flags for all messages.
1249 for (i = 0; i < Imap->num_msgs; ++i) {
1250 Imap->flags[i] = Imap->flags[i] & ~IMAP_SELECTED;
1254 * Now set it for all specified messages.
1256 num_sets = num_tokens(actual_range, ',');
1257 for (s=0; s<num_sets; ++s) {
1258 extract_token(setstr, actual_range, s, ',', sizeof setstr);
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);
1266 safestrncpy(histr, lostr, sizeof histr);
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;
1279 else { /* fetch by uid */
1280 if ( (i>=lo) && (i<=hi)) {
1281 Imap->flags[i-1] |= IMAP_SELECTED;
1292 * This function is called by the main command loop.
1294 void imap_fetch(int num_parms, char *parms[]) {
1296 char *itemlist[512];
1300 if (num_parms < 4) {
1301 cprintf("%s BAD invalid parameters\r\n", parms[0]);
1305 imap_pick_range(parms[2], 0);
1308 for (i=3; i<num_parms; ++i) {
1309 strcat(items, parms[i]);
1310 if (i < (num_parms-1)) strcat(items, " ");
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]);
1319 imap_do_fetch(num_items, itemlist);
1320 cprintf("%s OK FETCH completed\r\n", parms[0]);
1324 * This function is called by the main command loop.
1326 void imap_uidfetch(int num_parms, char *parms[]) {
1328 char *itemlist[512];
1331 int have_uid_item = 0;
1333 if (num_parms < 5) {
1334 cprintf("%s BAD invalid parameters\r\n", parms[0]);
1338 imap_pick_range(parms[3], 1);
1341 for (i=4; i<num_parms; ++i) {
1342 strcat(items, parms[i]);
1343 if (i < (num_parms-1)) strcat(items, " ");
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]);
1352 /* If the "UID" item was not included, we include it implicitly
1353 * (at the beginning) because this is a UID FETCH command
1355 for (i=0; i<num_items; ++i) {
1356 if (!strcasecmp(itemlist[i], "UID")) ++have_uid_item;
1358 if (have_uid_item == 0) {
1359 memmove(&itemlist[1], &itemlist[0], (sizeof(itemlist[0]) * num_items));
1361 itemlist[0] = "UID";
1364 imap_do_fetch(num_items, itemlist);
1365 cprintf("%s OK UID FETCH completed\r\n", parms[0]);