2 * Implements the FETCH command in IMAP.
3 * This is a good example of the protocol's gratuitous complexity.
5 * Copyright (c) 2001-2017 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.
27 #include <sys/types.h>
29 #if TIME_WITH_SYS_TIME
30 # include <sys/time.h>
34 # include <sys/time.h>
44 #include <libcitadel.h>
47 #include "sysdep_decls.h"
48 #include "citserver.h"
54 #include "internet_addressing.h"
55 #include "serv_imap.h"
56 #include "imap_tools.h"
57 #include "imap_fetch.h"
59 #include "ctdl_module.h"
64 * Individual field functions for imap_do_fetch_msg() ...
67 void imap_fetch_uid(int seq) {
68 IAPrintf("UID %ld", IMAP->msgids[seq-1]);
71 void imap_fetch_flags(int seq)
74 int num_flags_printed = 0;
76 if (Imap->flags[seq] & IMAP_DELETED) {
77 if (num_flags_printed > 0)
82 if (Imap->flags[seq] & IMAP_SEEN) {
83 if (num_flags_printed > 0)
88 if (Imap->flags[seq] & IMAP_ANSWERED) {
89 if (num_flags_printed > 0)
94 if (Imap->flags[seq] & IMAP_RECENT) {
95 if (num_flags_printed > 0)
104 void imap_fetch_internaldate(struct CtdlMessage *msg) {
109 if (!CM_IsEmpty(msg, eTimestamp)) {
110 msgdate = atol(msg->cm_fields[eTimestamp]);
113 msgdate = time(NULL);
116 datestring(datebuf, sizeof datebuf, msgdate, DATESTRING_IMAP);
117 IAPrintf( "INTERNALDATE \"%s\"", datebuf);
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, const char *whichfmt) {
131 CitContext *CCC = CC;
132 citimap *Imap = CCCIMAP;
133 const char *ptr = NULL;
134 size_t headers_size, text_size, total_size;
135 size_t bytes_to_send = 0;
137 int need_to_rewrite_metadata = 0;
140 /* Determine whether this particular fetch operation requires
141 * us to fetch the message body from disk. If not, we can save
142 * on some disk operations...
144 if ( (!strcasecmp(whichfmt, "RFC822"))
145 || (!strcasecmp(whichfmt, "RFC822.TEXT")) ) {
149 /* If this is an RFC822.SIZE fetch, first look in the message's
150 * metadata record to see if we've saved that information.
152 if (!strcasecmp(whichfmt, "RFC822.SIZE")) {
153 GetMetaData(&smi, msgnum);
154 if (smi.meta_rfc822_length > 0L) {
155 IAPrintf("RFC822.SIZE %ld", smi.meta_rfc822_length);
158 need_to_rewrite_metadata = 1;
162 /* Cache the most recent RFC822 FETCH because some clients like to
163 * fetch in pieces, and we don't want to have to go back to the
164 * message store for each piece. We also burn the cache if the
165 * client requests something that involves reading the message
166 * body, but we haven't fetched the body yet.
168 if ((Imap->cached_rfc822 != NULL)
169 && (Imap->cached_rfc822_msgnum == msgnum)
170 && (Imap->cached_rfc822_withbody || (!need_body)) ) {
173 else if (Imap->cached_rfc822 != NULL) {
174 /* Some other message is cached -- free it */
175 FreeStrBuf(&Imap->cached_rfc822);
176 Imap->cached_rfc822_msgnum = (-1);
179 /* At this point, we now can fetch and convert the message iff it's not
180 * the one we had cached.
182 if (Imap->cached_rfc822 == NULL) {
184 * Load the message into memory for translation & measurement
186 CCC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
187 CtdlOutputMsg(msgnum, MT_RFC822,
188 (need_body ? HEADERS_ALL : HEADERS_FAST),
189 0, 1, NULL, SUPPRESS_ENV_TO, NULL, NULL, NULL
191 if (!need_body) IAPuts("\r\n"); /* extra trailing newline */
192 Imap->cached_rfc822 = CCC->redirect_buffer;
193 CCC->redirect_buffer = NULL;
194 Imap->cached_rfc822_msgnum = msgnum;
195 Imap->cached_rfc822_withbody = need_body;
196 if ( (need_to_rewrite_metadata) &&
197 (StrLength(Imap->cached_rfc822) > 0) ) {
198 smi.meta_rfc822_length = StrLength(Imap->cached_rfc822);
204 * Now figure out where the headers/text break is. IMAP considers the
205 * intervening blank line to be part of the headers, not the text.
210 StrBuf *Line = NewStrBuf();
213 StrBufSipLine(Line, Imap->cached_rfc822, &ptr);
215 if ((StrLength(Line) != 0) && (ptr != StrBufNOTNULL))
218 if ((StrLength(Line) != 0) &&
219 (ptr != StrBufNOTNULL) )
221 headers_size = ptr - ChrPtr(Imap->cached_rfc822);
224 } while ( (headers_size == 0) &&
225 (ptr != StrBufNOTNULL) );
227 total_size = StrLength(Imap->cached_rfc822);
228 text_size = total_size - headers_size;
233 total_size = StrLength(Imap->cached_rfc822);
238 "RFC822: headers=" SIZE_T_FMT
240 ", total=" SIZE_T_FMT,
241 headers_size, text_size, total_size);
243 if (!strcasecmp(whichfmt, "RFC822.SIZE")) {
244 IAPrintf("RFC822.SIZE " SIZE_T_FMT, total_size);
248 else if (!strcasecmp(whichfmt, "RFC822")) {
249 ptr = ChrPtr(Imap->cached_rfc822);
250 bytes_to_send = total_size;
253 else if (!strcasecmp(whichfmt, "RFC822.HEADER")) {
254 ptr = ChrPtr(Imap->cached_rfc822);
255 bytes_to_send = headers_size;
258 else if (!strcasecmp(whichfmt, "RFC822.TEXT")) {
259 ptr = &ChrPtr(Imap->cached_rfc822)[headers_size];
260 bytes_to_send = text_size;
263 IAPrintf("%s {" SIZE_T_FMT "}\r\n", whichfmt, bytes_to_send);
264 iaputs(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 StrBuf *desired_section;
284 desired_section = (StrBuf *)cbuserdata;
285 syslog(LOG_DEBUG, "imap_load_part() looking for %s, found %s",
286 ChrPtr(desired_section),
290 if (!strcasecmp(partnum, ChrPtr(desired_section))) {
291 client_write(content, length);
294 snprintf(mimebuf2, sizeof mimebuf2, "%s.MIME", partnum);
296 if (!strcasecmp(ChrPtr(desired_section), mimebuf2)) {
297 client_write(HKEY("Content-type: "));
298 client_write(cbtype, strlen(cbtype));
299 if (!IsEmptyStr(cbcharset)) {
300 client_write(HKEY("; charset=\""));
301 client_write(cbcharset, strlen(cbcharset));
302 client_write(HKEY("\""));
304 if (!IsEmptyStr(name)) {
305 client_write(HKEY("; name=\""));
306 client_write(name, strlen(name));
307 client_write(HKEY("\""));
309 client_write(HKEY("\r\n"));
310 if (!IsEmptyStr(encoding)) {
311 client_write(HKEY("Content-Transfer-Encoding: "));
312 client_write(encoding, strlen(encoding));
313 client_write(HKEY("\r\n"));
315 if (!IsEmptyStr(encoding)) {
316 client_write(HKEY("Content-Disposition: "));
317 client_write(disp, strlen(disp));
319 if (!IsEmptyStr(filename)) {
320 client_write(HKEY("; filename=\""));
321 client_write(filename, strlen(filename));
322 client_write(HKEY("\""));
324 client_write(HKEY("\r\n"));
326 cprintf("Content-Length: %ld\r\n\r\n", (long)length);
332 * Called by imap_fetch_envelope() to output the "From" field.
333 * This is in its own function because its logic is kind of complex. We
334 * really need to make this suck less.
336 void imap_output_envelope_from(struct CtdlMessage *msg) {
337 char user[SIZ], node[SIZ], name[SIZ];
341 /* For anonymous messages, it's so easy! */
342 if (!is_room_aide() && (msg->cm_anon_type == MES_ANONONLY)) {
343 IAPuts("((\"----\" NIL \"x\" \"x.org\")) ");
346 if (!is_room_aide() && (msg->cm_anon_type == MES_ANONOPT)) {
347 IAPuts("((\"anonymous\" NIL \"x\" \"x.org\")) ");
351 /* For everything else, we do stuff. */
352 IAPuts("(("); /* open double-parens */
353 IPutMsgField(eAuthor); /* personal name */
354 IAPuts(" NIL "); /* source route (not used) */
357 if (!CM_IsEmpty(msg, erFc822Addr)) {
358 process_rfc822_addr(msg->cm_fields[erFc822Addr], user, node, name);
359 IPutStr(user, strlen(user)); /* mailbox name (user id) */
361 if (!strcasecmp(node, CtdlGetConfigStr("c_nodename"))) {
362 IPutStr(CtdlGetConfigStr("c_fqdn"), strlen(CtdlGetConfigStr("c_fqdn")));
365 IPutStr(node, strlen(node)); /* host name */
369 IPutMsgField(eAuthor); /* mailbox name (user id) */
371 IPutMsgField(eNodeName); /* host name */
374 IAPuts(")) "); /* close double-parens */
380 * Output an envelope address (or set of addresses) in the official,
381 * convoluted, braindead format. (Note that we can't use this for
382 * the "From" address because its data may come from a number of different
383 * fields. But we can use it for "To" and possibly others.
385 void imap_output_envelope_addr(char *addr) {
386 char individual_addr[256];
398 if (IsEmptyStr(addr)) {
405 /* How many addresses are listed here? */
406 num_addrs = num_tokens(addr, ',');
408 /* Output them one by one. */
409 for (i=0; i<num_addrs; ++i) {
410 extract_token(individual_addr, addr, i, ',', sizeof individual_addr);
411 striplt(individual_addr);
412 process_rfc822_addr(individual_addr, user, node, name);
414 IPutStr(name, strlen(name));
416 IPutStr(user, strlen(user));
418 IPutStr(node, strlen(node));
420 if (i < (num_addrs-1))
429 * Implements the ENVELOPE fetch item
431 * Note that the imap_strout() function can cleverly output NULL fields as NIL,
432 * so we don't have to check for that condition like we do elsewhere.
434 void imap_fetch_envelope(struct CtdlMessage *msg) {
435 char datestringbuf[SIZ];
437 char *fieldptr = NULL;
442 /* Parse the message date into an IMAP-format date string */
443 if (!CM_IsEmpty(msg, eTimestamp)) {
444 msgdate = atol(msg->cm_fields[eTimestamp]);
447 msgdate = time(NULL);
449 len = datestring(datestringbuf, sizeof datestringbuf,
450 msgdate, DATESTRING_IMAP);
452 /* Now start spewing data fields. The order is important, as it is
453 * defined by the protocol specification. Nonexistent fields must
454 * be output as NIL, existent fields must be quoted or literalled.
455 * The imap_strout() function conveniently does all this for us.
457 IAPuts("ENVELOPE (");
460 IPutStr(datestringbuf, len);
464 IPutMsgField(eMsgSubject);
468 imap_output_envelope_from(msg);
470 /* Sender (default to same as 'From' if not present) */
471 fieldptr = rfc822_fetch_field(msg->cm_fields[eMesageText], "Sender");
472 if (fieldptr != NULL) {
473 imap_output_envelope_addr(fieldptr);
477 imap_output_envelope_from(msg);
481 fieldptr = rfc822_fetch_field(msg->cm_fields[eMesageText], "Reply-to");
482 if (fieldptr != NULL) {
483 imap_output_envelope_addr(fieldptr);
487 imap_output_envelope_from(msg);
491 imap_output_envelope_addr(msg->cm_fields[eRecipient]);
493 /* Cc (we do it this way because there might be a legacy non-Citadel Cc: field present) */
494 fieldptr = msg->cm_fields[eCarbonCopY];
495 if (fieldptr != NULL) {
496 imap_output_envelope_addr(fieldptr);
499 fieldptr = rfc822_fetch_field(msg->cm_fields[eMesageText], "Cc");
500 imap_output_envelope_addr(fieldptr);
501 if (fieldptr != NULL) free(fieldptr);
505 fieldptr = rfc822_fetch_field(msg->cm_fields[eMesageText], "Bcc");
506 imap_output_envelope_addr(fieldptr);
507 if (fieldptr != NULL) free(fieldptr);
510 fieldptr = rfc822_fetch_field(msg->cm_fields[eMesageText], "In-reply-to");
511 IPutStr(fieldptr, (fieldptr)?strlen(fieldptr):0);
513 if (fieldptr != NULL) free(fieldptr);
516 len = msg->cm_lengths[emessageId];
519 (msg->cm_fields[emessageId][0] == '<') &&
520 (msg->cm_fields[emessageId][len - 1] == '>'))
523 IPutMsgField(emessageId);
527 char *Buf = malloc(len + 3);
530 if (msg->cm_fields[emessageId][0] != '<')
535 memcpy(&Buf[pos], msg->cm_fields[emessageId], len);
537 if (msg->cm_fields[emessageId][len] != '>')
550 * This function is called only when CC->redirect_buffer contains a set of
551 * RFC822 headers with no body attached. Its job is to strip that set of
552 * headers down to *only* the ones we're interested in.
554 void imap_strip_headers(StrBuf *section) {
556 StrBuf *which_fields = NULL;
557 int doing_headers = 0;
561 StrBuf *boiled_headers = NULL;
564 int done_headers = 0;
565 const char *Ptr = NULL;
566 CitContext *CCC = CC;
568 if (CCC->redirect_buffer == NULL) return;
570 which_fields = NewStrBufDup(section);
572 if (!strncasecmp(ChrPtr(which_fields), "HEADER.FIELDS", 13))
575 !strncasecmp(ChrPtr(which_fields), "HEADER.FIELDS.NOT", 17))
578 for (i=0; i < StrLength(which_fields); ++i) {
579 if (ChrPtr(which_fields)[i]=='(')
580 StrBufReplaceToken(which_fields, i, 1, HKEY(""));
582 for (i=0; i < StrLength(which_fields); ++i) {
583 if (ChrPtr(which_fields)[i]==')') {
584 StrBufCutAt(which_fields, i, NULL);
588 memset(&Cmd, 0, sizeof(citimap_command));
589 Cmd.CmdBuf = which_fields;
590 num_parms = imap_parameterize(&Cmd);
592 boiled_headers = NewStrBufPlain(NULL, StrLength(CCC->redirect_buffer));
593 Line = NewStrBufPlain(NULL, SIZ);
597 StrBufSipLine(Line, CCC->redirect_buffer, &Ptr);
599 if (!isspace(ChrPtr(Line)[0])) {
601 if (doing_headers == 0) ok = 1;
603 /* we're supposed to print all headers that are not matching the filter list */
604 if (headers_not) for (i=0, ok = 1; (i < num_parms) && (ok == 1); ++i) {
605 if ( (!strncasecmp(ChrPtr(Line),
607 Cmd.Params[i].len)) &&
608 (ChrPtr(Line)[Cmd.Params[i].len]==':') ) {
612 /* we're supposed to print all headers matching the filterlist */
613 else for (i=0, ok = 0; ((i < num_parms) && (ok == 0)); ++i) {
614 if ( (!strncasecmp(ChrPtr(Line),
616 Cmd.Params[i].len)) &&
617 (ChrPtr(Line)[Cmd.Params[i].len]==':') ) {
625 StrBufAppendBuf(boiled_headers, Line, 0);
626 StrBufAppendBufPlain(boiled_headers, HKEY("\r\n"), 0);
629 if ((Ptr == StrBufNOTNULL) ||
630 (StrLength(Line) == 0) ||
631 (ChrPtr(Line)[0]=='\r') ||
632 (ChrPtr(Line)[0]=='\n') ) done_headers = 1;
633 } while (!done_headers);
635 StrBufAppendBufPlain(boiled_headers, HKEY("\r\n"), 0);
637 /* Now save it back (it'll always be smaller) */
638 FreeStrBuf(&CCC->redirect_buffer);
639 CCC->redirect_buffer = boiled_headers;
642 FreeStrBuf(&which_fields);
648 * Implements the BODY and BODY.PEEK fetch items
650 void imap_fetch_body(long msgnum, ConstStr item, int is_peek) {
651 struct CtdlMessage *msg = NULL;
655 size_t pstart, pbytes;
656 int loading_body_now = 0;
658 int burn_the_cache = 0;
659 CitContext *CCC = CC;
660 citimap *Imap = CCCIMAP;
662 /* extract section */
663 section = NewStrBufPlain(CKEY(item));
665 if (strchr(ChrPtr(section), '[') != NULL) {
666 StrBufStripAllBut(section, '[', ']');
668 syslog(LOG_DEBUG, "Section is: [%s]", (StrLength(section) == 0) ? "(empty)" : ChrPtr(section));
670 /* Burn the cache if we don't have the same section of the
671 * same message again.
673 if (Imap->cached_body != NULL) {
674 if (Imap->cached_bodymsgnum != msgnum) {
677 else if ( (!Imap->cached_body_withbody) && (need_body) ) {
680 else if (strcasecmp(Imap->cached_bodypart, ChrPtr(section))) {
683 if (burn_the_cache) {
684 /* Yup, go ahead and burn the cache. */
685 free(Imap->cached_body);
686 Imap->cached_body_len = 0;
687 Imap->cached_body = NULL;
688 Imap->cached_bodymsgnum = (-1);
689 strcpy(Imap->cached_bodypart, "");
693 /* extract partial */
694 partial = NewStrBufPlain(CKEY(item));
695 if (strchr(ChrPtr(partial), '<') != NULL) {
696 StrBufStripAllBut(partial, '<', '>');
699 if ( (is_partial == 1) && (StrLength(partial) > 0) ) {
700 syslog(LOG_DEBUG, "Partial is <%s>", ChrPtr(partial));
703 if (Imap->cached_body == NULL) {
704 CCC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
705 loading_body_now = 1;
706 msg = CtdlFetchMessage(msgnum, (need_body ? 1 : 0), 1);
709 /* Now figure out what the client wants, and get it */
711 if (!loading_body_now) {
712 /* What we want is already in memory */
715 else if ( (!strcmp(ChrPtr(section), "1")) && (msg->cm_format_type != 4) ) {
716 CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_NONE, 0, 1, SUPPRESS_ENV_TO);
719 else if (StrLength(section) == 0) {
720 CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_ALL, 0, 1, SUPPRESS_ENV_TO);
724 * If the client asked for just headers, or just particular header
725 * fields, strip it down.
727 else if (!strncasecmp(ChrPtr(section), "HEADER", 6)) {
728 /* This used to work with HEADERS_FAST, but then Apple got stupid with their
729 * IMAP library and this broke Mail.App and iPhone Mail, so we had to change it
730 * to HEADERS_ONLY so the trendy hipsters with their iPhones can read mail.
732 CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_ONLY, 0, 1, SUPPRESS_ENV_TO);
733 imap_strip_headers(section);
737 * Strip it down if the client asked for everything _except_ headers.
739 else if (!strncasecmp(ChrPtr(section), "TEXT", 4)) {
740 CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_NONE, 0, 1, SUPPRESS_ENV_TO);
744 * Anything else must be a part specifier.
745 * (Note value of 1 passed as 'dont_decode' so client gets it encoded)
748 mime_parser(CM_RANGE(msg, eMesageText),
749 *imap_load_part, NULL, NULL,
755 if (loading_body_now) {
756 Imap->cached_body_len = StrLength(CCC->redirect_buffer);
757 Imap->cached_body = SmashStrBuf(&CCC->redirect_buffer);
758 Imap->cached_bodymsgnum = msgnum;
759 Imap->cached_body_withbody = need_body;
760 strcpy(Imap->cached_bodypart, ChrPtr(section));
763 if (is_partial == 0) {
765 iaputs(SKEY(section));
766 IAPrintf("] {" SIZE_T_FMT "}\r\n", Imap->cached_body_len);
768 pbytes = Imap->cached_body_len;
771 sscanf(ChrPtr(partial), SIZE_T_FMT "." SIZE_T_FMT, &pstart, &pbytes);
772 if (pbytes > (Imap->cached_body_len - pstart)) {
773 pbytes = Imap->cached_body_len - pstart;
776 iaputs(SKEY(section));
777 IAPrintf("]<" SIZE_T_FMT "> {" SIZE_T_FMT "}\r\n", pstart, pbytes);
780 FreeStrBuf(&partial);
782 /* Here we go -- output it */
783 iaputs(&Imap->cached_body[pstart], pbytes);
789 /* Mark this message as "seen" *unless* this is a "peek" operation */
791 CtdlSetSeen(&msgnum, 1, 1, ctdlsetseen_seen, NULL, NULL);
793 FreeStrBuf(§ion);
797 * Called immediately before outputting a multipart bodystructure
799 void imap_fetch_bodystructure_pre(
800 char *name, char *filename, char *partnum, char *disp,
801 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
802 char *cbid, void *cbuserdata
811 * Called immediately after outputting a multipart bodystructure
813 void imap_fetch_bodystructure_post(
814 char *name, char *filename, char *partnum, char *disp,
815 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
816 char *cbid, void *cbuserdata
824 len = extract_token(subtype, cbtype, 1, '/', sizeof subtype);
825 IPutStr(subtype, len);
828 /* IAPuts(" NIL"); We thought we needed this at one point, but maybe we don't... */
836 * Output the info for a MIME part in the format required by BODYSTRUCTURE.
839 void imap_fetch_bodystructure_part(
840 char *name, char *filename, char *partnum, char *disp,
841 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
842 char *cbid, void *cbuserdata
846 int have_encoding = 0;
849 char cbmaintype[128];
854 if (cbtype != NULL) if (!IsEmptyStr(cbtype)) have_cbtype = 1;
856 cbmaintype_len = extract_token(cbmaintype, cbtype, 0, '/', sizeof cbmaintype);
857 cbsubtype_len = extract_token(cbsubtype, cbtype, 1, '/', sizeof cbsubtype);
860 strcpy(cbmaintype, "TEXT");
862 strcpy(cbsubtype, "PLAIN");
867 IPutStr(cbmaintype, cbmaintype_len); /* body type */
869 IPutStr(cbsubtype, cbsubtype_len); /* body subtype */
872 IAPuts("("); /* begin body parameter list */
874 /* "NAME" must appear as the first parameter. This is not required by IMAP,
875 * but the Asterisk voicemail application blindly assumes that NAME will be in
876 * the first position. If it isn't, it rejects the message.
878 if ((name != NULL) && (!IsEmptyStr(name))) {
880 IPutStr(name, strlen(name));
884 IAPuts("\"CHARSET\" ");
885 if ((cbcharset == NULL) || (cbcharset[0] == 0)){
886 IPutStr(HKEY("US-ASCII"));
889 IPutStr(cbcharset, strlen(cbcharset));
891 IAPuts(") "); /* end body parameter list */
893 IAPuts("NIL "); /* Body ID */
894 IAPuts("NIL "); /* Body description */
896 if ((encoding != NULL) && (encoding[0] != 0)) have_encoding = 1;
898 IPutStr(encoding, strlen(encoding));
901 IPutStr(HKEY("7BIT"));
905 /* The next field is the size of the part in bytes. */
906 IAPrintf("%ld ", (long)length); /* bytes */
908 /* The next field is the number of lines in the part, if and only
909 * if the part is TEXT. More gratuitous complexity.
911 if (!strcasecmp(cbmaintype, "TEXT")) {
912 if (length) for (i=0; i<length; ++i) {
913 if (((char *)content)[i] == '\n') ++lines;
915 IAPrintf("%d ", lines);
918 /* More gratuitous complexity */
919 if ((!strcasecmp(cbmaintype, "MESSAGE"))
920 && (!strcasecmp(cbsubtype, "RFC822"))) {
921 /* FIXME: message/rfc822 also needs to output the envelope structure,
922 * body structure, and line count of the encapsulated message. Fortunately
923 * there are not yet any clients depending on this, so we can get away
924 * with not implementing it for now.
928 /* MD5 value of body part; we can get away with NIL'ing this */
932 if ((disp == NULL) || IsEmptyStr(disp)) {
937 IPutStr(disp, strlen(disp));
938 if ((filename != NULL) && (!IsEmptyStr(filename))) {
939 IAPuts(" (\"FILENAME\" ");
940 IPutStr(filename, strlen(filename));
946 /* Body language (not defined yet) */
953 * Spew the BODYSTRUCTURE data for a message.
956 void imap_fetch_bodystructure (long msgnum, const char *item,
957 struct CtdlMessage *msg) {
958 const char *rfc822 = NULL;
959 const char *rfc822_body = NULL;
961 size_t rfc822_headers_len;
962 size_t rfc822_body_len;
963 const char *ptr = NULL;
968 /* Handle NULL message gracefully */
970 IAPuts("BODYSTRUCTURE (\"TEXT\" \"PLAIN\" "
971 "(\"CHARSET\" \"US-ASCII\") NIL NIL "
976 /* For non-RFC822 (ordinary Citadel) messages, this is short and
979 if (msg->cm_format_type != FMT_RFC822) {
981 /* *sigh* We have to RFC822-format the message just to be able
982 * to measure it. FIXME use smi cached fields if possible
985 CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
986 CtdlOutputPreLoadedMsg(msg, MT_RFC822, 0, 0, 1, SUPPRESS_ENV_TO);
987 rfc822_len = StrLength(CC->redirect_buffer);
988 rfc822 = pch = SmashStrBuf(&CC->redirect_buffer);
992 ptr = cmemreadline(ptr, buf, sizeof buf);
994 if ((IsEmptyStr(buf)) && (rfc822_body == NULL)) {
999 rfc822_headers_len = rfc822_body - rfc822;
1000 rfc822_body_len = rfc822_len - rfc822_headers_len;
1003 IAPuts("BODYSTRUCTURE (\"TEXT\" \"PLAIN\" "
1004 "(\"CHARSET\" \"US-ASCII\") NIL NIL "
1006 IAPrintf(SIZE_T_FMT " %d)", rfc822_body_len, lines);
1011 /* For messages already stored in RFC822 format, we have to parse. */
1012 IAPuts("BODYSTRUCTURE ");
1013 mime_parser(CM_RANGE(msg, eMesageText),
1014 *imap_fetch_bodystructure_part, /* part */
1015 *imap_fetch_bodystructure_pre, /* pre-multi */
1016 *imap_fetch_bodystructure_post, /* post-multi */
1018 1); /* don't decode -- we want it as-is */
1023 * imap_do_fetch() calls imap_do_fetch_msg() to output the data of an
1024 * individual message, once it has been selected for output.
1026 void imap_do_fetch_msg(int seq, citimap_command *Cmd) {
1028 citimap *Imap = IMAP;
1029 struct CtdlMessage *msg = NULL;
1030 int body_loaded = 0;
1032 /* Don't attempt to fetch bogus messages or UID's */
1033 if (seq < 1) return;
1034 if (Imap->msgids[seq-1] < 1L) return;
1037 IAPrintf("* %d FETCH (", seq);
1039 for (i=0; i<Cmd->num_parms; ++i) {
1041 /* Fetchable without going to the message store at all */
1042 if (!strcasecmp(Cmd->Params[i].Key, "UID")) {
1043 imap_fetch_uid(seq);
1045 else if (!strcasecmp(Cmd->Params[i].Key, "FLAGS")) {
1046 imap_fetch_flags(seq-1);
1049 /* Potentially fetchable from cache, if the client requests
1050 * stuff from the same message several times in a row.
1052 else if (!strcasecmp(Cmd->Params[i].Key, "RFC822")) {
1053 imap_fetch_rfc822(Imap->msgids[seq-1], Cmd->Params[i].Key);
1055 else if (!strcasecmp(Cmd->Params[i].Key, "RFC822.HEADER")) {
1056 imap_fetch_rfc822(Imap->msgids[seq-1], Cmd->Params[i].Key);
1058 else if (!strcasecmp(Cmd->Params[i].Key, "RFC822.SIZE")) {
1059 imap_fetch_rfc822(Imap->msgids[seq-1], Cmd->Params[i].Key);
1061 else if (!strcasecmp(Cmd->Params[i].Key, "RFC822.TEXT")) {
1062 imap_fetch_rfc822(Imap->msgids[seq-1], Cmd->Params[i].Key);
1065 /* BODY fetches do their own fetching and caching too. */
1066 else if (!strncasecmp(Cmd->Params[i].Key, "BODY[", 5)) {
1067 imap_fetch_body(Imap->msgids[seq-1], Cmd->Params[i], 0);
1069 else if (!strncasecmp(Cmd->Params[i].Key, "BODY.PEEK[", 10)) {
1070 imap_fetch_body(Imap->msgids[seq-1], Cmd->Params[i], 1);
1073 /* Otherwise, load the message into memory.
1075 else if (!strcasecmp(Cmd->Params[i].Key, "BODYSTRUCTURE")) {
1076 if ((msg != NULL) && (!body_loaded)) {
1077 CM_Free(msg); /* need the whole thing */
1081 msg = CtdlFetchMessage(Imap->msgids[seq-1], 1, 1);
1084 imap_fetch_bodystructure(Imap->msgids[seq-1],
1085 Cmd->Params[i].Key, msg);
1087 else if (!strcasecmp(Cmd->Params[i].Key, "ENVELOPE")) {
1089 msg = CtdlFetchMessage(Imap->msgids[seq-1], 0, 1);
1092 imap_fetch_envelope(msg);
1094 else if (!strcasecmp(Cmd->Params[i].Key, "INTERNALDATE")) {
1096 msg = CtdlFetchMessage(Imap->msgids[seq-1], 0, 1);
1099 imap_fetch_internaldate(msg);
1102 if (i != Cmd->num_parms-1) IAPuts(" ");
1115 * imap_fetch() calls imap_do_fetch() to do its actual work, once it's
1116 * validated and boiled down the request a bit.
1118 void imap_do_fetch(citimap_command *Cmd) {
1119 citimap *Imap = IMAP;
1122 /* debug output the parsed vector */
1125 syslog(LOG_DEBUG, "----- %ld params", Cmd->num_parms);
1127 for (i=0; i < Cmd->num_parms; i++) {
1128 if (Cmd->Params[i].len != strlen(Cmd->Params[i].Key))
1129 syslog(LOG_DEBUG, "*********** %ld != %ld : %s",
1131 strlen(Cmd->Params[i].Key),
1132 Cmd->Params[i].Key);
1134 syslog(LOG_DEBUG, "%ld : %s",
1136 Cmd->Params[i].Key);
1141 if (Imap->num_msgs > 0) {
1142 for (i = 0; i < Imap->num_msgs; ++i) {
1144 /* Abort the fetch loop if the session breaks.
1145 * This is important for users who keep mailboxes
1146 * that are too big *and* are too impatient to
1147 * let them finish loading. :)
1149 if (CC->kill_me) return;
1151 /* Get any message marked for fetch. */
1152 if (Imap->flags[i] & IMAP_SELECTED) {
1153 imap_do_fetch_msg(i+1, Cmd);
1162 * Back end for imap_handle_macros()
1163 * Note that this function *only* looks at the beginning of the string. It
1164 * is not a generic search-and-replace function.
1166 void imap_macro_replace(StrBuf *Buf, long where,
1168 char *find, long findlen,
1169 char *replace, long replacelen)
1172 if (StrLength(Buf) - where > findlen)
1175 if (!strncasecmp(ChrPtr(Buf) + where, find, findlen)) {
1176 if (ChrPtr(Buf)[where + findlen] == ' ') {
1177 StrBufPlain(TmpBuf, replace, replacelen);
1178 StrBufAppendBufPlain(TmpBuf, HKEY(" "), 0);
1179 StrBufReplaceToken(Buf, where, findlen,
1182 if (where + findlen == StrLength(Buf)) {
1183 StrBufReplaceToken(Buf, where, findlen,
1184 replace, replacelen);
1192 * Handle macros embedded in FETCH data items.
1193 * (What the heck are macros doing in a wire protocol? Are we trying to save
1194 * the computer at the other end the trouble of typing a lot of characters?)
1196 void imap_handle_macros(citimap_command *Cmd) {
1199 StrBuf *Tmp = NewStrBuf();
1201 for (i=0; i < StrLength(Cmd->CmdBuf); ++i) {
1202 char ch = ChrPtr(Cmd->CmdBuf)[i];
1207 else if ((ch==')') ||
1213 imap_macro_replace(Cmd->CmdBuf, i,
1216 HKEY("FLAGS INTERNALDATE RFC822.SIZE ENVELOPE")
1218 imap_macro_replace(Cmd->CmdBuf, i,
1221 HKEY("BODYSTRUCTURE")
1223 imap_macro_replace(Cmd->CmdBuf, i,
1226 HKEY("FLAGS INTERNALDATE RFC822.SIZE")
1228 imap_macro_replace(Cmd->CmdBuf, i,
1231 HKEY("FLAGS INTERNALDATE RFC822.SIZE ENVELOPE BODY")
1240 * Break out the data items requested, possibly a parenthesized list.
1241 * Returns the number of data items, or -1 if the list is invalid.
1242 * NOTE: this function alters the string it is fed, and uses it as a buffer
1243 * to hold the data for the pointers it returns.
1245 int imap_extract_data_items(citimap_command *Cmd)
1249 const char *pch, *end;
1251 /* Convert all whitespace to ordinary space characters. */
1252 pch = ChrPtr(Cmd->CmdBuf);
1253 end = pch + StrLength(Cmd->CmdBuf);
1258 StrBufPeek(Cmd->CmdBuf, pch, 0, ' ');
1262 /* Strip leading and trailing whitespace, then strip leading and
1263 * trailing parentheses if it's a list
1265 StrBufTrim(Cmd->CmdBuf);
1266 pch = ChrPtr(Cmd->CmdBuf);
1267 if ( (pch[0]=='(') &&
1268 (pch[StrLength(Cmd->CmdBuf)-1]==')') )
1270 StrBufCutRight(Cmd->CmdBuf, 1);
1271 StrBufCutLeft(Cmd->CmdBuf, 1);
1272 StrBufTrim(Cmd->CmdBuf);
1275 /* Parse any macro data items */
1276 imap_handle_macros(Cmd);
1279 * Now break out the data items. We throw in one trailing space in
1280 * order to avoid having to break out the last one manually.
1282 nArgs = StrLength(Cmd->CmdBuf) / 10 + 10;
1283 nArgs = CmdAdjust(Cmd, nArgs, 0);
1285 Cmd->Params[Cmd->num_parms].Key = pch = ChrPtr(Cmd->CmdBuf);
1286 end = Cmd->Params[Cmd->num_parms].Key + StrLength(Cmd->CmdBuf);
1296 else if ((*pch==')') ||
1302 if ((nest <= 0) && (*pch==' ')) {
1303 StrBufPeek(Cmd->CmdBuf, pch, 0, '\0');
1304 Cmd->Params[Cmd->num_parms].len =
1305 pch - Cmd->Params[Cmd->num_parms].Key;
1307 if (Cmd->num_parms + 1 >= Cmd->avail_parms) {
1308 nArgs = CmdAdjust(Cmd, nArgs * 2, 1);
1311 Cmd->Params[Cmd->num_parms].Key = ++pch;
1313 else if (pch + 1 == end) {
1314 Cmd->Params[Cmd->num_parms].len =
1315 pch - Cmd->Params[Cmd->num_parms].Key + 1;
1321 return Cmd->num_parms;
1327 * One particularly hideous aspect of IMAP is that we have to allow the client
1328 * to specify arbitrary ranges and/or sets of messages to fetch. Citadel IMAP
1329 * handles this by setting the IMAP_SELECTED flag for each message specified in
1330 * the ranges/sets, then looping through the message array, outputting messages
1331 * with the flag set. We don't bother returning an error if an out-of-range
1332 * number is specified (we just return quietly) because any client braindead
1333 * enough to request a bogus message number isn't going to notice the
1334 * difference anyway.
1336 * This function clears out the IMAP_SELECTED bits, then sets that bit for each
1337 * message included in the specified range.
1339 * Set is_uid to 1 to fetch by UID instead of sequence number.
1341 void imap_pick_range(const char *supplied_range, int is_uid) {
1342 citimap *Imap = IMAP;
1346 char setstr[SIZ], lostr[SIZ], histr[SIZ];
1348 char actual_range[SIZ];
1351 * Handle the "ALL" macro
1353 if (!strcasecmp(supplied_range, "ALL")) {
1354 safestrncpy(actual_range, "1:*", sizeof actual_range);
1357 safestrncpy(actual_range, supplied_range, sizeof actual_range);
1361 * Clear out the IMAP_SELECTED flags for all messages.
1363 for (i = 0; i < Imap->num_msgs; ++i) {
1364 Imap->flags[i] = Imap->flags[i] & ~IMAP_SELECTED;
1368 * Now set it for all specified messages.
1370 num_sets = num_tokens(actual_range, ',');
1371 for (s=0; s<num_sets; ++s) {
1372 extract_token(setstr, actual_range, s, ',', sizeof setstr);
1374 extract_token(lostr, setstr, 0, ':', sizeof lostr);
1375 if (num_tokens(setstr, ':') >= 2) {
1376 extract_token(histr, setstr, 1, ':', sizeof histr);
1377 if (!strcmp(histr, "*")) snprintf(histr, sizeof histr, "%ld", LONG_MAX);
1380 safestrncpy(histr, lostr, sizeof histr);
1385 /* Loop through the array, flipping bits where appropriate */
1386 for (i = 1; i <= Imap->num_msgs; ++i) {
1387 if (is_uid) { /* fetch by sequence number */
1388 if ( (Imap->msgids[i-1]>=lo)
1389 && (Imap->msgids[i-1]<=hi)) {
1390 Imap->flags[i-1] |= IMAP_SELECTED;
1393 else { /* fetch by uid */
1394 if ( (i>=lo) && (i<=hi)) {
1395 Imap->flags[i-1] |= IMAP_SELECTED;
1405 * This function is called by the main command loop.
1407 void imap_fetch(int num_parms, ConstStr *Params) {
1408 citimap_command Cmd;
1411 if (num_parms < 4) {
1412 IReply("BAD invalid parameters");
1416 imap_pick_range(Params[2].Key, 0);
1418 memset(&Cmd, 0, sizeof(citimap_command));
1419 Cmd.CmdBuf = NewStrBufPlain(NULL, StrLength(IMAP->Cmd.CmdBuf));
1420 MakeStringOf(Cmd.CmdBuf, 3);
1422 num_items = imap_extract_data_items(&Cmd);
1423 if (num_items < 1) {
1424 IReply("BAD invalid data item list");
1425 FreeStrBuf(&Cmd.CmdBuf);
1430 imap_do_fetch(&Cmd);
1431 IReply("OK FETCH completed");
1432 FreeStrBuf(&Cmd.CmdBuf);
1437 * This function is called by the main command loop.
1439 void imap_uidfetch(int num_parms, ConstStr *Params) {
1440 citimap_command Cmd;
1443 int have_uid_item = 0;
1445 if (num_parms < 5) {
1446 IReply("BAD invalid parameters");
1450 imap_pick_range(Params[3].Key, 1);
1452 memset(&Cmd, 0, sizeof(citimap_command));
1453 Cmd.CmdBuf = NewStrBufPlain(NULL, StrLength(IMAP->Cmd.CmdBuf));
1455 MakeStringOf(Cmd.CmdBuf, 4);
1457 syslog(LOG_DEBUG, "-------%s--------", ChrPtr(Cmd.CmdBuf));
1459 num_items = imap_extract_data_items(&Cmd);
1460 if (num_items < 1) {
1461 IReply("BAD invalid data item list");
1462 FreeStrBuf(&Cmd.CmdBuf);
1467 /* If the "UID" item was not included, we include it implicitly
1468 * (at the beginning) because this is a UID FETCH command
1470 for (i=0; i<num_items; ++i) {
1471 if (!strcasecmp(Cmd.Params[i].Key, "UID")) ++have_uid_item;
1473 if (have_uid_item == 0) {
1474 if (Cmd.num_parms + 1 >= Cmd.avail_parms)
1475 CmdAdjust(&Cmd, Cmd.avail_parms + 1, 1);
1476 memmove(&Cmd.Params[1],
1478 sizeof(ConstStr) * Cmd.num_parms);
1481 Cmd.Params[0] = (ConstStr){HKEY("UID")};
1484 imap_do_fetch(&Cmd);
1485 IReply("OK UID FETCH completed");
1486 FreeStrBuf(&Cmd.CmdBuf);