2 * Implements the FETCH command in IMAP.
3 * This is a good example of the protocol's gratuitous complexity.
5 * Copyright (c) 2001-2020 by the citadel.org team
7 * This program is open source software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
19 #include "../../sysdep.h"
27 #include <sys/types.h>
33 #include <libcitadel.h>
34 #include "../../citadel_defs.h"
35 #include "../../server.h"
36 #include "../../sysdep_decls.h"
37 #include "../../citserver.h"
38 #include "../../support.h"
39 #include "../../config.h"
40 #include "../../user_ops.h"
41 #include "../../database.h"
42 #include "../../msgbase.h"
43 #include "../../internet_addressing.h"
44 #include "serv_imap.h"
45 #include "imap_tools.h"
46 #include "imap_fetch.h"
47 #include "../../genstamp.h"
48 #include "../../ctdl_module.h"
53 * Individual field functions for imap_do_fetch_msg() ...
56 void imap_fetch_uid(int seq) {
57 IAPrintf("UID %ld", IMAP->msgids[seq-1]);
60 void imap_fetch_flags(int seq)
63 int num_flags_printed = 0;
65 if (Imap->flags[seq] & IMAP_DELETED) {
66 if (num_flags_printed > 0)
71 if (Imap->flags[seq] & IMAP_SEEN) {
72 if (num_flags_printed > 0)
77 if (Imap->flags[seq] & IMAP_ANSWERED) {
78 if (num_flags_printed > 0)
83 if (Imap->flags[seq] & IMAP_RECENT) {
84 if (num_flags_printed > 0)
93 void imap_fetch_internaldate(struct CtdlMessage *msg) {
98 if (!CM_IsEmpty(msg, eTimestamp)) {
99 msgdate = atol(msg->cm_fields[eTimestamp]);
102 msgdate = time(NULL);
105 datestring(datebuf, sizeof datebuf, msgdate, DATESTRING_IMAP);
106 IAPrintf( "INTERNALDATE \"%s\"", datebuf);
111 * Fetch RFC822-formatted messages.
113 * 'whichfmt' should be set to one of:
114 * "RFC822" entire message
115 * "RFC822.HEADER" headers only (with trailing blank line)
116 * "RFC822.SIZE" size of translated message
117 * "RFC822.TEXT" body only (without leading blank line)
119 void imap_fetch_rfc822(long msgnum, const char *whichfmt) {
120 citimap *Imap = IMAP;
121 const char *ptr = NULL;
122 size_t headers_size, text_size, total_size;
123 size_t bytes_to_send = 0;
125 int need_to_rewrite_metadata = 0;
128 /* Determine whether this particular fetch operation requires
129 * us to fetch the message body from disk. If not, we can save
130 * on some disk operations...
132 if ( (!strcasecmp(whichfmt, "RFC822")) || (!strcasecmp(whichfmt, "RFC822.TEXT")) ) {
136 /* If this is an RFC822.SIZE fetch, first look in the message's
137 * metadata record to see if we've saved that information.
139 if (!strcasecmp(whichfmt, "RFC822.SIZE")) {
140 GetMetaData(&smi, msgnum);
141 if (smi.meta_rfc822_length > 0L) {
142 IAPrintf("RFC822.SIZE %ld", smi.meta_rfc822_length);
145 need_to_rewrite_metadata = 1;
149 /* Cache the most recent RFC822 FETCH because some clients like to
150 * fetch in pieces, and we don't want to have to go back to the
151 * message store for each piece. We also burn the cache if the
152 * client requests something that involves reading the message
153 * body, but we haven't fetched the body yet.
155 if ((Imap->cached_rfc822 != NULL)
156 && (Imap->cached_rfc822_msgnum == msgnum)
157 && (Imap->cached_rfc822_withbody || (!need_body)) ) {
160 else if (Imap->cached_rfc822 != NULL) {
161 /* Some other message is cached -- free it */
162 FreeStrBuf(&Imap->cached_rfc822);
163 Imap->cached_rfc822_msgnum = (-1);
166 /* At this point, we now can fetch and convert the message iff it's not
167 * the one we had cached.
169 if (Imap->cached_rfc822 == NULL) {
171 * Load the message into memory for translation & measurement
173 CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
174 CtdlOutputMsg(msgnum, MT_RFC822,
175 (need_body ? HEADERS_ALL : HEADERS_FAST),
176 0, 1, NULL, SUPPRESS_ENV_TO, NULL, NULL, NULL
179 client_write(HKEY("\r\n")); // extra trailing newline -- to the redirect_buffer, *not* to the client
181 Imap->cached_rfc822 = CC->redirect_buffer;
182 CC->redirect_buffer = NULL;
183 Imap->cached_rfc822_msgnum = msgnum;
184 Imap->cached_rfc822_withbody = need_body;
185 if ( (need_to_rewrite_metadata) &&
186 (StrLength(Imap->cached_rfc822) > 0) ) {
187 smi.meta_rfc822_length = StrLength(Imap->cached_rfc822);
193 * Now figure out where the headers/text break is. IMAP considers the
194 * intervening blank line to be part of the headers, not the text.
199 StrBuf *Line = NewStrBuf();
202 StrBufSipLine(Line, Imap->cached_rfc822, &ptr);
204 if ((StrLength(Line) != 0) && (ptr != StrBufNOTNULL))
207 if ((StrLength(Line) != 0) &&
208 (ptr != StrBufNOTNULL) )
210 headers_size = ptr - ChrPtr(Imap->cached_rfc822);
213 } while ( (headers_size == 0) &&
214 (ptr != StrBufNOTNULL) );
216 total_size = StrLength(Imap->cached_rfc822);
217 text_size = total_size - headers_size;
221 headers_size = total_size = StrLength(Imap->cached_rfc822);
225 syslog(LOG_DEBUG, "imap: RFC822 headers=" SIZE_T_FMT ", text=" SIZE_T_FMT ", total=" SIZE_T_FMT, headers_size, text_size, total_size);
227 if (!strcasecmp(whichfmt, "RFC822.SIZE")) {
228 IAPrintf("RFC822.SIZE " SIZE_T_FMT, total_size);
232 else if (!strcasecmp(whichfmt, "RFC822")) {
233 ptr = ChrPtr(Imap->cached_rfc822);
234 bytes_to_send = total_size;
237 else if (!strcasecmp(whichfmt, "RFC822.HEADER")) {
238 ptr = ChrPtr(Imap->cached_rfc822);
239 bytes_to_send = headers_size;
242 else if (!strcasecmp(whichfmt, "RFC822.TEXT")) {
243 ptr = &ChrPtr(Imap->cached_rfc822)[headers_size];
244 bytes_to_send = text_size;
247 IAPrintf("%s {" SIZE_T_FMT "}\r\n", whichfmt, bytes_to_send);
248 iaputs(ptr, bytes_to_send);
253 * Load a specific part of a message into the temp file to be output to a
254 * client. FIXME we can handle parts like "2" and "2.1" and even "2.MIME"
255 * but we still can't handle "2.HEADER" (which might not be a problem).
257 * Note: mime_parser() was called with dont_decode set to 1, so we have the
258 * luxury of simply spewing without having to re-encode.
260 void imap_load_part(char *name, char *filename, char *partnum, char *disp,
261 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
262 char *cbid, void *cbuserdata)
265 StrBuf *desired_section;
267 desired_section = (StrBuf *)cbuserdata;
268 syslog(LOG_DEBUG, "imap: imap_load_part() looking for %s, found %s", ChrPtr(desired_section), partnum);
270 if (!strcasecmp(partnum, ChrPtr(desired_section))) {
271 client_write(content, length);
274 snprintf(mimebuf2, sizeof mimebuf2, "%s.MIME", partnum);
276 if (!strcasecmp(ChrPtr(desired_section), mimebuf2)) {
277 client_write(HKEY("Content-type: "));
278 client_write(cbtype, strlen(cbtype));
279 if (!IsEmptyStr(cbcharset)) {
280 client_write(HKEY("; charset=\""));
281 client_write(cbcharset, strlen(cbcharset));
282 client_write(HKEY("\""));
284 if (!IsEmptyStr(name)) {
285 client_write(HKEY("; name=\""));
286 client_write(name, strlen(name));
287 client_write(HKEY("\""));
289 client_write(HKEY("\r\n"));
290 if (!IsEmptyStr(encoding)) {
291 client_write(HKEY("Content-Transfer-Encoding: "));
292 client_write(encoding, strlen(encoding));
293 client_write(HKEY("\r\n"));
295 if (!IsEmptyStr(encoding)) {
296 client_write(HKEY("Content-Disposition: "));
297 client_write(disp, strlen(disp));
299 if (!IsEmptyStr(filename)) {
300 client_write(HKEY("; filename=\""));
301 client_write(filename, strlen(filename));
302 client_write(HKEY("\""));
304 client_write(HKEY("\r\n"));
306 cprintf("Content-Length: %ld\r\n\r\n", (long)length);
312 * Called by imap_fetch_envelope() to output the "From" field.
313 * This is in its own function because its logic is kind of complex. We
314 * really need to make this suck less.
316 void imap_output_envelope_from(struct CtdlMessage *msg) {
317 char user[SIZ], node[SIZ], name[SIZ];
321 /* For anonymous messages, it's so easy! */
322 if (!is_room_aide() && (msg->cm_anon_type == MES_ANONONLY)) {
323 IAPuts("((\"----\" NIL \"x\" \"x.org\")) ");
326 if (!is_room_aide() && (msg->cm_anon_type == MES_ANONOPT)) {
327 IAPuts("((\"anonymous\" NIL \"x\" \"x.org\")) ");
331 /* For everything else, we do stuff. */
332 IAPuts("(("); // open double-parens
333 IPutMsgField(eAuthor); // display name
334 IAPuts(" NIL "); // source route (not used)
336 if (!CM_IsEmpty(msg, erFc822Addr)) {
337 process_rfc822_addr(msg->cm_fields[erFc822Addr], user, node, name);
338 IPutStr(user, strlen(user)); /* mailbox name (user id) */
340 IPutStr(node, strlen(node)); /* host name */
343 IPutMsgField(eAuthor); /* Make up a synthetic address */
345 IPutStr(CtdlGetConfigStr("c_fqdn"), strlen(CtdlGetConfigStr("c_fqdn")));
348 IAPuts(")) "); /* close double-parens */
353 * Output an envelope address (or set of addresses) in the official,
354 * convoluted, braindead format. (Note that we can't use this for
355 * the "From" address because its data may come from a number of different
356 * fields. But we can use it for "To" and possibly others.
358 void imap_output_envelope_addr(char *addr) {
359 char individual_addr[256];
371 if (IsEmptyStr(addr)) {
378 /* How many addresses are listed here? */
379 num_addrs = num_tokens(addr, ',');
381 /* Output them one by one. */
382 for (i=0; i<num_addrs; ++i) {
383 extract_token(individual_addr, addr, i, ',', sizeof individual_addr);
384 string_trim(individual_addr);
385 process_rfc822_addr(individual_addr, user, node, name);
387 IPutStr(name, strlen(name));
389 IPutStr(user, strlen(user));
391 IPutStr(node, strlen(node));
393 if (i < (num_addrs-1))
402 * Implements the ENVELOPE fetch item
404 * Note that the imap_strout() function can cleverly output NULL fields as NIL,
405 * so we don't have to check for that condition like we do elsewhere.
407 void imap_fetch_envelope(struct CtdlMessage *msg) {
408 char datestringbuf[SIZ];
410 char *fieldptr = NULL;
415 /* Parse the message date into an IMAP-format date string */
416 if (!CM_IsEmpty(msg, eTimestamp)) {
417 msgdate = atol(msg->cm_fields[eTimestamp]);
420 msgdate = time(NULL);
422 len = datestring(datestringbuf, sizeof datestringbuf, msgdate, DATESTRING_IMAP);
424 /* Now start spewing data fields. The order is important, as it is
425 * defined by the protocol specification. Nonexistent fields must
426 * be output as NIL, existent fields must be quoted or literalled.
427 * The imap_strout() function conveniently does all this for us.
429 IAPuts("ENVELOPE (");
432 IPutStr(datestringbuf, len);
436 IPutMsgField(eMsgSubject);
440 imap_output_envelope_from(msg);
442 /* Sender (default to same as 'From' if not present) */
443 fieldptr = rfc822_fetch_field(msg->cm_fields[eMessageText], "Sender");
444 if (fieldptr != NULL) {
445 imap_output_envelope_addr(fieldptr);
449 imap_output_envelope_from(msg);
453 fieldptr = rfc822_fetch_field(msg->cm_fields[eMessageText], "Reply-to");
454 if (fieldptr != NULL) {
455 imap_output_envelope_addr(fieldptr);
459 imap_output_envelope_from(msg);
463 imap_output_envelope_addr(msg->cm_fields[eRecipient]);
465 /* Cc (we do it this way because there might be a legacy non-Citadel Cc: field present) */
466 fieldptr = msg->cm_fields[eCarbonCopY];
467 if (fieldptr != NULL) {
468 imap_output_envelope_addr(fieldptr);
471 fieldptr = rfc822_fetch_field(msg->cm_fields[eMessageText], "Cc");
472 imap_output_envelope_addr(fieldptr);
473 if (fieldptr != NULL) free(fieldptr);
477 fieldptr = rfc822_fetch_field(msg->cm_fields[eMessageText], "Bcc");
478 imap_output_envelope_addr(fieldptr);
479 if (fieldptr != NULL) free(fieldptr);
482 fieldptr = rfc822_fetch_field(msg->cm_fields[eMessageText], "In-reply-to");
483 IPutStr(fieldptr, (fieldptr)?strlen(fieldptr):0);
485 if (fieldptr != NULL) free(fieldptr);
488 len = msg->cm_lengths[emessageId];
491 (msg->cm_fields[emessageId][0] == '<') &&
492 (msg->cm_fields[emessageId][len - 1] == '>'))
494 IPutMsgField(emessageId);
498 char *Buf = malloc(len + 3);
501 if (msg->cm_fields[emessageId][0] != '<')
506 memcpy(&Buf[pos], msg->cm_fields[emessageId], len);
508 if (msg->cm_fields[emessageId][len] != '>')
522 * This function is called only when CC->redirect_buffer contains a set of
523 * RFC822 headers with no body attached. Its job is to strip that set of
524 * headers down to *only* the ones we're interested in.
526 void imap_strip_headers(StrBuf *section) {
528 StrBuf *which_fields = NULL;
529 int doing_headers = 0;
533 StrBuf *boiled_headers = NULL;
536 int done_headers = 0;
537 const char *Ptr = NULL;
539 if (CC->redirect_buffer == NULL) return;
541 which_fields = NewStrBufDup(section);
543 if (!strncasecmp(ChrPtr(which_fields), "HEADER.FIELDS", 13))
546 !strncasecmp(ChrPtr(which_fields), "HEADER.FIELDS.NOT", 17))
549 for (i=0; i < StrLength(which_fields); ++i) {
550 if (ChrPtr(which_fields)[i]=='(')
551 StrBufReplaceToken(which_fields, i, 1, HKEY(""));
553 for (i=0; i < StrLength(which_fields); ++i) {
554 if (ChrPtr(which_fields)[i]==')') {
555 StrBufCutAt(which_fields, i, NULL);
559 memset(&Cmd, 0, sizeof(citimap_command));
560 Cmd.CmdBuf = which_fields;
561 num_parms = imap_parameterize(&Cmd);
563 boiled_headers = NewStrBufPlain(NULL, StrLength(CC->redirect_buffer));
564 Line = NewStrBufPlain(NULL, SIZ);
568 StrBufSipLine(Line, CC->redirect_buffer, &Ptr);
570 if (!isspace(ChrPtr(Line)[0])) {
572 if (doing_headers == 0) ok = 1;
574 /* we're supposed to print all headers that are not matching the filter list */
575 if (headers_not) for (i=0, ok = 1; (i < num_parms) && (ok == 1); ++i) {
576 if ( (!strncasecmp(ChrPtr(Line),
578 Cmd.Params[i].len)) &&
579 (ChrPtr(Line)[Cmd.Params[i].len]==':') ) {
583 /* we're supposed to print all headers matching the filterlist */
584 else for (i=0, ok = 0; ((i < num_parms) && (ok == 0)); ++i) {
585 if ( (!strncasecmp(ChrPtr(Line),
587 Cmd.Params[i].len)) &&
588 (ChrPtr(Line)[Cmd.Params[i].len]==':') ) {
596 StrBufAppendBuf(boiled_headers, Line, 0);
597 StrBufAppendBufPlain(boiled_headers, HKEY("\r\n"), 0);
600 if ((Ptr == StrBufNOTNULL) ||
601 (StrLength(Line) == 0) ||
602 (ChrPtr(Line)[0]=='\r') ||
603 (ChrPtr(Line)[0]=='\n') ) done_headers = 1;
604 } while (!done_headers);
606 StrBufAppendBufPlain(boiled_headers, HKEY("\r\n"), 0);
608 /* Now save it back (it'll always be smaller) */
609 FreeStrBuf(&CC->redirect_buffer);
610 CC->redirect_buffer = boiled_headers;
613 FreeStrBuf(&which_fields);
619 * Implements the BODY and BODY.PEEK fetch items
621 void imap_fetch_body(long msgnum, ConstStr item, int is_peek) {
622 struct CtdlMessage *msg = NULL;
626 size_t pstart, pbytes;
627 int loading_body_now = 0;
629 int burn_the_cache = 0;
630 citimap *Imap = IMAP;
632 /* extract section */
633 section = NewStrBufPlain(CKEY(item));
635 if (strchr(ChrPtr(section), '[') != NULL) {
636 StrBufStripAllBut(section, '[', ']');
638 syslog(LOG_DEBUG, "imap: selected section is [%s]", (StrLength(section) == 0) ? "(empty)" : ChrPtr(section));
640 /* Burn the cache if we don't have the same section of the
641 * same message again.
643 if (Imap->cached_body != NULL) {
644 if (Imap->cached_bodymsgnum != msgnum) {
647 else if ( (!Imap->cached_body_withbody) && (need_body) ) {
650 else if (strcasecmp(Imap->cached_bodypart, ChrPtr(section))) {
653 if (burn_the_cache) {
654 /* Yup, go ahead and burn the cache. */
655 free(Imap->cached_body);
656 Imap->cached_body_len = 0;
657 Imap->cached_body = NULL;
658 Imap->cached_bodymsgnum = (-1);
659 strcpy(Imap->cached_bodypart, "");
663 /* extract partial */
664 partial = NewStrBufPlain(CKEY(item));
665 if (strchr(ChrPtr(partial), '<') != NULL) {
666 StrBufStripAllBut(partial, '<', '>');
669 if ( (is_partial == 1) && (StrLength(partial) > 0) ) {
670 syslog(LOG_DEBUG, "imap: selected partial is <%s>", ChrPtr(partial));
673 if (Imap->cached_body == NULL) {
674 CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
675 loading_body_now = 1;
676 msg = CtdlFetchMessage(msgnum, (need_body ? 1 : 0));
679 /* Now figure out what the client wants, and get it */
681 if (!loading_body_now) {
682 /* What we want is already in memory */
685 else if ( (!strcmp(ChrPtr(section), "1")) && (msg->cm_format_type != 4) ) {
686 CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_NONE, 0, 1, SUPPRESS_ENV_TO);
689 else if (StrLength(section) == 0) {
690 CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_ALL, 0, 1, SUPPRESS_ENV_TO);
694 * If the client asked for just headers, or just particular header
695 * fields, strip it down.
697 else if (!strncasecmp(ChrPtr(section), "HEADER", 6)) {
698 /* This used to work with HEADERS_FAST, but then Apple got stupid with their
699 * IMAP library and this broke Mail.App and iPhone Mail, so we had to change it
700 * to HEADERS_ONLY so the trendy hipsters with their iPhones can read mail.
702 CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_ONLY, 0, 1, SUPPRESS_ENV_TO);
703 imap_strip_headers(section);
707 * Strip it down if the client asked for everything _except_ headers.
709 else if (!strncasecmp(ChrPtr(section), "TEXT", 4)) {
710 CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_NONE, 0, 1, SUPPRESS_ENV_TO);
714 * Anything else must be a part specifier.
715 * (Note value of 1 passed as 'dont_decode' so client gets it encoded)
718 mime_parser(CM_RANGE(msg, eMessageText),
719 *imap_load_part, NULL, NULL,
725 if (loading_body_now) {
726 Imap->cached_body_len = StrLength(CC->redirect_buffer);
727 Imap->cached_body = SmashStrBuf(&CC->redirect_buffer);
728 Imap->cached_bodymsgnum = msgnum;
729 Imap->cached_body_withbody = need_body;
730 strcpy(Imap->cached_bodypart, ChrPtr(section));
733 if (is_partial == 0) {
735 iaputs(SKEY(section));
736 IAPrintf("] {" SIZE_T_FMT "}\r\n", Imap->cached_body_len);
738 pbytes = Imap->cached_body_len;
741 sscanf(ChrPtr(partial), SIZE_T_FMT "." SIZE_T_FMT, &pstart, &pbytes);
742 if (pbytes > (Imap->cached_body_len - pstart)) {
743 pbytes = Imap->cached_body_len - pstart;
746 iaputs(SKEY(section));
747 IAPrintf("]<" SIZE_T_FMT "> {" SIZE_T_FMT "}\r\n", pstart, pbytes);
750 FreeStrBuf(&partial);
752 /* Here we go -- output it */
753 iaputs(&Imap->cached_body[pstart], pbytes);
759 /* Mark this message as "seen" *unless* this is a "peek" operation */
761 CtdlSetSeen(&msgnum, 1, 1, ctdlsetseen_seen, NULL, NULL);
763 FreeStrBuf(§ion);
767 * Called immediately before outputting a multipart bodystructure
769 void imap_fetch_bodystructure_pre(
770 char *name, char *filename, char *partnum, char *disp,
771 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
772 char *cbid, void *cbuserdata
781 * Called immediately after outputting a multipart bodystructure
783 void imap_fetch_bodystructure_post(
784 char *name, char *filename, char *partnum, char *disp,
785 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
786 char *cbid, void *cbuserdata
794 len = extract_token(subtype, cbtype, 1, '/', sizeof subtype);
795 IPutStr(subtype, len);
798 /* IAPuts(" NIL"); We thought we needed this at one point, but maybe we don't... */
806 * Output the info for a MIME part in the format required by BODYSTRUCTURE.
809 void imap_fetch_bodystructure_part(
810 char *name, char *filename, char *partnum, char *disp,
811 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
812 char *cbid, void *cbuserdata
816 int have_encoding = 0;
819 char cbmaintype[128];
824 if (cbtype != NULL) if (!IsEmptyStr(cbtype)) have_cbtype = 1;
826 cbmaintype_len = extract_token(cbmaintype, cbtype, 0, '/', sizeof cbmaintype);
827 cbsubtype_len = extract_token(cbsubtype, cbtype, 1, '/', sizeof cbsubtype);
830 strcpy(cbmaintype, "TEXT");
832 strcpy(cbsubtype, "PLAIN");
837 IPutStr(cbmaintype, cbmaintype_len); /* body type */
839 IPutStr(cbsubtype, cbsubtype_len); /* body subtype */
842 IAPuts("("); /* begin body parameter list */
844 /* "NAME" must appear as the first parameter. This is not required by IMAP,
845 * but the Asterisk voicemail application blindly assumes that NAME will be in
846 * the first position. If it isn't, it rejects the message.
848 if ((name != NULL) && (!IsEmptyStr(name))) {
850 IPutStr(name, strlen(name));
854 IAPuts("\"CHARSET\" ");
855 if ((cbcharset == NULL) || (cbcharset[0] == 0)){
856 IPutStr(HKEY("US-ASCII"));
859 IPutStr(cbcharset, strlen(cbcharset));
861 IAPuts(") "); /* end body parameter list */
863 IAPuts("NIL "); /* Body ID */
864 IAPuts("NIL "); /* Body description */
866 if ((encoding != NULL) && (encoding[0] != 0)) have_encoding = 1;
868 IPutStr(encoding, strlen(encoding));
871 IPutStr(HKEY("7BIT"));
875 /* The next field is the size of the part in bytes. */
876 IAPrintf("%ld ", (long)length); /* bytes */
878 /* The next field is the number of lines in the part, if and only
879 * if the part is TEXT. More gratuitous complexity.
881 if (!strcasecmp(cbmaintype, "TEXT")) {
882 if (length) for (i=0; i<length; ++i) {
883 if (((char *)content)[i] == '\n') ++lines;
885 IAPrintf("%d ", lines);
888 /* More gratuitous complexity */
889 if ((!strcasecmp(cbmaintype, "MESSAGE"))
890 && (!strcasecmp(cbsubtype, "RFC822"))) {
891 /* FIXME: message/rfc822 also needs to output the envelope structure,
892 * body structure, and line count of the encapsulated message. Fortunately
893 * there are not yet any clients depending on this, so we can get away
894 * with not implementing it for now.
898 /* MD5 value of body part; we can get away with NIL'ing this */
902 if ((disp == NULL) || IsEmptyStr(disp)) {
907 IPutStr(disp, strlen(disp));
908 if ((filename != NULL) && (!IsEmptyStr(filename))) {
909 IAPuts(" (\"FILENAME\" ");
910 IPutStr(filename, strlen(filename));
916 /* Body language (not defined yet) */
923 * Spew the BODYSTRUCTURE data for a message.
926 void imap_fetch_bodystructure (long msgnum, const char *item,
927 struct CtdlMessage *msg) {
928 const char *rfc822 = NULL;
929 const char *rfc822_body = NULL;
931 size_t rfc822_headers_len;
932 size_t rfc822_body_len;
933 const char *ptr = NULL;
938 /* Handle NULL message gracefully */
940 IAPuts("BODYSTRUCTURE (\"TEXT\" \"PLAIN\" "
941 "(\"CHARSET\" \"US-ASCII\") NIL NIL "
946 /* For non-RFC822 (ordinary Citadel) messages, this is short and
949 if (msg->cm_format_type != FMT_RFC822) {
951 /* *sigh* We have to RFC822-format the message just to be able
952 * to measure it. FIXME use smi cached fields if possible
955 CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
956 CtdlOutputPreLoadedMsg(msg, MT_RFC822, 0, 0, 1, SUPPRESS_ENV_TO);
957 rfc822_len = StrLength(CC->redirect_buffer);
958 rfc822 = pch = SmashStrBuf(&CC->redirect_buffer);
962 ptr = cmemreadline(ptr, buf, sizeof buf);
964 if ((IsEmptyStr(buf)) && (rfc822_body == NULL)) {
969 rfc822_headers_len = rfc822_body - rfc822;
970 rfc822_body_len = rfc822_len - rfc822_headers_len;
973 IAPuts("BODYSTRUCTURE (\"TEXT\" \"PLAIN\" "
974 "(\"CHARSET\" \"US-ASCII\") NIL NIL "
976 IAPrintf(SIZE_T_FMT " %d)", rfc822_body_len, lines);
981 /* For messages already stored in RFC822 format, we have to parse. */
982 IAPuts("BODYSTRUCTURE ");
983 mime_parser(CM_RANGE(msg, eMessageText),
984 *imap_fetch_bodystructure_part, /* part */
985 *imap_fetch_bodystructure_pre, /* pre-multi */
986 *imap_fetch_bodystructure_post, /* post-multi */
988 1); /* don't decode -- we want it as-is */
993 * imap_do_fetch() calls imap_do_fetch_msg() to output the data of an
994 * individual message, once it has been selected for output.
996 void imap_do_fetch_msg(int seq, citimap_command *Cmd) {
998 citimap *Imap = IMAP;
999 struct CtdlMessage *msg = NULL;
1000 int body_loaded = 0;
1002 /* Don't attempt to fetch bogus messages or UID's */
1003 if (seq < 1) return;
1004 if (Imap->msgids[seq-1] < 1L) return;
1007 IAPrintf("* %d FETCH (", seq);
1009 for (i=0; i<Cmd->num_parms; ++i) {
1011 /* Fetchable without going to the message store at all */
1012 if (!strcasecmp(Cmd->Params[i].Key, "UID")) {
1013 imap_fetch_uid(seq);
1015 else if (!strcasecmp(Cmd->Params[i].Key, "FLAGS")) {
1016 imap_fetch_flags(seq-1);
1019 /* Potentially fetchable from cache, if the client requests
1020 * stuff from the same message several times in a row.
1022 else if (!strcasecmp(Cmd->Params[i].Key, "RFC822")) {
1023 imap_fetch_rfc822(Imap->msgids[seq-1], Cmd->Params[i].Key);
1025 else if (!strcasecmp(Cmd->Params[i].Key, "RFC822.HEADER")) {
1026 imap_fetch_rfc822(Imap->msgids[seq-1], Cmd->Params[i].Key);
1028 else if (!strcasecmp(Cmd->Params[i].Key, "RFC822.SIZE")) {
1029 imap_fetch_rfc822(Imap->msgids[seq-1], Cmd->Params[i].Key);
1031 else if (!strcasecmp(Cmd->Params[i].Key, "RFC822.TEXT")) {
1032 imap_fetch_rfc822(Imap->msgids[seq-1], Cmd->Params[i].Key);
1035 /* BODY fetches do their own fetching and caching too. */
1036 else if (!strncasecmp(Cmd->Params[i].Key, "BODY[", 5)) {
1037 imap_fetch_body(Imap->msgids[seq-1], Cmd->Params[i], 0);
1039 else if (!strncasecmp(Cmd->Params[i].Key, "BODY.PEEK[", 10)) {
1040 imap_fetch_body(Imap->msgids[seq-1], Cmd->Params[i], 1);
1043 /* Otherwise, load the message into memory.
1045 else if (!strcasecmp(Cmd->Params[i].Key, "BODYSTRUCTURE")) {
1046 if ((msg != NULL) && (!body_loaded)) {
1047 CM_Free(msg); /* need the whole thing */
1051 msg = CtdlFetchMessage(Imap->msgids[seq-1], 1);
1054 imap_fetch_bodystructure(Imap->msgids[seq-1],
1055 Cmd->Params[i].Key, msg);
1057 else if (!strcasecmp(Cmd->Params[i].Key, "ENVELOPE")) {
1059 msg = CtdlFetchMessage(Imap->msgids[seq-1], 0);
1062 imap_fetch_envelope(msg);
1064 else if (!strcasecmp(Cmd->Params[i].Key, "INTERNALDATE")) {
1066 msg = CtdlFetchMessage(Imap->msgids[seq-1], 0);
1069 imap_fetch_internaldate(msg);
1072 if (i != Cmd->num_parms-1) IAPuts(" ");
1085 * imap_fetch() calls imap_do_fetch() to do its actual work, once it's
1086 * validated and boiled down the request a bit.
1088 void imap_do_fetch(citimap_command *Cmd) {
1089 citimap *Imap = IMAP;
1092 /* debug output the parsed vector */
1095 syslog(LOG_DEBUG, "imap: ----- %ld params", Cmd->num_parms);
1097 for (i=0; i < Cmd->num_parms; i++) {
1098 if (Cmd->Params[i].len != strlen(Cmd->Params[i].Key))
1099 syslog(LOG_DEBUG, "imap: *********** %ld != %ld : %s",
1101 strlen(Cmd->Params[i].Key),
1102 Cmd->Params[i].Key);
1104 syslog(LOG_DEBUG, "imap: %ld : %s",
1106 Cmd->Params[i].Key);
1111 if (Imap->num_msgs > 0) {
1112 for (i = 0; i < Imap->num_msgs; ++i) {
1114 /* Abort the fetch loop if the session breaks.
1115 * This is important for users who keep mailboxes
1116 * that are too big *and* are too impatient to
1117 * let them finish loading. :)
1119 if (CC->kill_me) return;
1121 /* Get any message marked for fetch. */
1122 if (Imap->flags[i] & IMAP_SELECTED) {
1123 imap_do_fetch_msg(i+1, Cmd);
1132 * Back end for imap_handle_macros()
1133 * Note that this function *only* looks at the beginning of the string. It
1134 * is not a generic search-and-replace function.
1136 void imap_macro_replace(StrBuf *Buf, long where,
1138 char *find, long findlen,
1139 char *replace, long replacelen)
1142 if (StrLength(Buf) - where > findlen)
1145 if (!strncasecmp(ChrPtr(Buf) + where, find, findlen)) {
1146 if (ChrPtr(Buf)[where + findlen] == ' ') {
1147 StrBufPlain(TmpBuf, replace, replacelen);
1148 StrBufAppendBufPlain(TmpBuf, HKEY(" "), 0);
1149 StrBufReplaceToken(Buf, where, findlen,
1152 if (where + findlen == StrLength(Buf)) {
1153 StrBufReplaceToken(Buf, where, findlen,
1154 replace, replacelen);
1162 * Handle macros embedded in FETCH data items.
1163 * (What the heck are macros doing in a wire protocol? Are we trying to save
1164 * the computer at the other end the trouble of typing a lot of characters?)
1166 void imap_handle_macros(citimap_command *Cmd) {
1169 StrBuf *Tmp = NewStrBuf();
1171 for (i=0; i < StrLength(Cmd->CmdBuf); ++i) {
1172 char ch = ChrPtr(Cmd->CmdBuf)[i];
1177 else if ((ch==')') ||
1183 imap_macro_replace(Cmd->CmdBuf, i,
1186 HKEY("FLAGS INTERNALDATE RFC822.SIZE ENVELOPE")
1188 imap_macro_replace(Cmd->CmdBuf, i,
1191 HKEY("BODYSTRUCTURE")
1193 imap_macro_replace(Cmd->CmdBuf, i,
1196 HKEY("FLAGS INTERNALDATE RFC822.SIZE")
1198 imap_macro_replace(Cmd->CmdBuf, i,
1201 HKEY("FLAGS INTERNALDATE RFC822.SIZE ENVELOPE BODY")
1210 * Break out the data items requested, possibly a parenthesized list.
1211 * Returns the number of data items, or -1 if the list is invalid.
1212 * NOTE: this function alters the string it is fed, and uses it as a buffer
1213 * to hold the data for the pointers it returns.
1215 int imap_extract_data_items(citimap_command *Cmd)
1219 const char *pch, *end;
1221 /* Convert all whitespace to ordinary space characters. */
1222 pch = ChrPtr(Cmd->CmdBuf);
1223 end = pch + StrLength(Cmd->CmdBuf);
1228 StrBufPeek(Cmd->CmdBuf, pch, 0, ' ');
1232 /* Strip leading and trailing whitespace, then strip leading and
1233 * trailing parentheses if it's a list
1235 StrBufTrim(Cmd->CmdBuf);
1236 pch = ChrPtr(Cmd->CmdBuf);
1237 if ( (pch[0]=='(') &&
1238 (pch[StrLength(Cmd->CmdBuf)-1]==')') )
1240 StrBufCutRight(Cmd->CmdBuf, 1);
1241 StrBufCutLeft(Cmd->CmdBuf, 1);
1242 StrBufTrim(Cmd->CmdBuf);
1245 /* Parse any macro data items */
1246 imap_handle_macros(Cmd);
1249 * Now break out the data items. We throw in one trailing space in
1250 * order to avoid having to break out the last one manually.
1252 nArgs = StrLength(Cmd->CmdBuf) / 10 + 10;
1253 nArgs = CmdAdjust(Cmd, nArgs, 0);
1255 Cmd->Params[Cmd->num_parms].Key = pch = ChrPtr(Cmd->CmdBuf);
1256 end = Cmd->Params[Cmd->num_parms].Key + StrLength(Cmd->CmdBuf);
1266 else if ((*pch==')') ||
1272 if ((nest <= 0) && (*pch==' ')) {
1273 StrBufPeek(Cmd->CmdBuf, pch, 0, '\0');
1274 Cmd->Params[Cmd->num_parms].len =
1275 pch - Cmd->Params[Cmd->num_parms].Key;
1277 if (Cmd->num_parms + 1 >= Cmd->avail_parms) {
1278 nArgs = CmdAdjust(Cmd, nArgs * 2, 1);
1281 Cmd->Params[Cmd->num_parms].Key = ++pch;
1283 else if (pch + 1 == end) {
1284 Cmd->Params[Cmd->num_parms].len =
1285 pch - Cmd->Params[Cmd->num_parms].Key + 1;
1291 return Cmd->num_parms;
1297 * One particularly hideous aspect of IMAP is that we have to allow the client
1298 * to specify arbitrary ranges and/or sets of messages to fetch. Citadel IMAP
1299 * handles this by setting the IMAP_SELECTED flag for each message specified in
1300 * the ranges/sets, then looping through the message array, outputting messages
1301 * with the flag set. We don't bother returning an error if an out-of-range
1302 * number is specified (we just return quietly) because any client braindead
1303 * enough to request a bogus message number isn't going to notice the
1304 * difference anyway.
1306 * This function clears out the IMAP_SELECTED bits, then sets that bit for each
1307 * message included in the specified range.
1309 * Set is_uid to 1 to fetch by UID instead of sequence number.
1311 void imap_pick_range(const char *supplied_range, int is_uid) {
1312 citimap *Imap = IMAP;
1316 char setstr[SIZ], lostr[SIZ], histr[SIZ];
1318 char actual_range[SIZ];
1321 * Handle the "ALL" macro
1323 if (!strcasecmp(supplied_range, "ALL")) {
1324 safestrncpy(actual_range, "1:*", sizeof actual_range);
1327 safestrncpy(actual_range, supplied_range, sizeof actual_range);
1331 * Clear out the IMAP_SELECTED flags for all messages.
1333 for (i = 0; i < Imap->num_msgs; ++i) {
1334 Imap->flags[i] = Imap->flags[i] & ~IMAP_SELECTED;
1338 * Now set it for all specified messages.
1340 num_sets = num_tokens(actual_range, ',');
1341 for (s=0; s<num_sets; ++s) {
1342 extract_token(setstr, actual_range, s, ',', sizeof setstr);
1344 extract_token(lostr, setstr, 0, ':', sizeof lostr);
1345 if (num_tokens(setstr, ':') >= 2) {
1346 extract_token(histr, setstr, 1, ':', sizeof histr);
1347 if (!strcmp(histr, "*")) snprintf(histr, sizeof histr, "%ld", LONG_MAX);
1350 safestrncpy(histr, lostr, sizeof histr);
1355 /* Loop through the array, flipping bits where appropriate */
1356 for (i = 1; i <= Imap->num_msgs; ++i) {
1357 if (is_uid) { /* fetch by sequence number */
1358 if ( (Imap->msgids[i-1]>=lo)
1359 && (Imap->msgids[i-1]<=hi)) {
1360 Imap->flags[i-1] |= IMAP_SELECTED;
1363 else { /* fetch by uid */
1364 if ( (i>=lo) && (i<=hi)) {
1365 Imap->flags[i-1] |= IMAP_SELECTED;
1375 * This function is called by the main command loop.
1377 void imap_fetch(int num_parms, ConstStr *Params) {
1378 citimap_command Cmd;
1381 if (num_parms < 4) {
1382 IReply("BAD invalid parameters");
1386 imap_pick_range(Params[2].Key, 0);
1388 memset(&Cmd, 0, sizeof(citimap_command));
1389 Cmd.CmdBuf = NewStrBufPlain(NULL, StrLength(IMAP->Cmd.CmdBuf));
1390 MakeStringOf(Cmd.CmdBuf, 3);
1392 num_items = imap_extract_data_items(&Cmd);
1393 if (num_items < 1) {
1394 IReply("BAD invalid data item list");
1395 FreeStrBuf(&Cmd.CmdBuf);
1400 imap_do_fetch(&Cmd);
1401 IReply("OK FETCH completed");
1402 FreeStrBuf(&Cmd.CmdBuf);
1407 * This function is called by the main command loop.
1409 void imap_uidfetch(int num_parms, ConstStr *Params) {
1410 citimap_command Cmd;
1413 int have_uid_item = 0;
1415 if (num_parms < 5) {
1416 IReply("BAD invalid parameters");
1420 imap_pick_range(Params[3].Key, 1);
1422 memset(&Cmd, 0, sizeof(citimap_command));
1423 Cmd.CmdBuf = NewStrBufPlain(NULL, StrLength(IMAP->Cmd.CmdBuf));
1425 MakeStringOf(Cmd.CmdBuf, 4);
1427 syslog(LOG_DEBUG, "imap: -------%s--------", ChrPtr(Cmd.CmdBuf));
1429 num_items = imap_extract_data_items(&Cmd);
1430 if (num_items < 1) {
1431 IReply("BAD invalid data item list");
1432 FreeStrBuf(&Cmd.CmdBuf);
1437 /* If the "UID" item was not included, we include it implicitly
1438 * (at the beginning) because this is a UID FETCH command
1440 for (i=0; i<num_items; ++i) {
1441 if (!strcasecmp(Cmd.Params[i].Key, "UID")) ++have_uid_item;
1443 if (have_uid_item == 0) {
1444 if (Cmd.num_parms + 1 >= Cmd.avail_parms)
1445 CmdAdjust(&Cmd, Cmd.avail_parms + 1, 1);
1446 memmove(&Cmd.Params[1],
1448 sizeof(ConstStr) * Cmd.num_parms);
1451 Cmd.Params[0] = (ConstStr){HKEY("UID")};
1454 imap_do_fetch(&Cmd);
1455 IReply("OK UID FETCH completed");
1456 FreeStrBuf(&Cmd.CmdBuf);