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.
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")) || (!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 IAPrintf("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 != NULL)
168 && (Imap->cached_rfc822_msgnum == msgnum)
169 && (Imap->cached_rfc822_withbody || (!need_body)) ) {
172 else if (Imap->cached_rfc822 != NULL) {
173 /* Some other message is cached -- free it */
174 FreeStrBuf(&Imap->cached_rfc822);
175 Imap->cached_rfc822_msgnum = (-1);
178 /* At this point, we now can fetch and convert the message iff it's not
179 * the one we had cached.
181 if (Imap->cached_rfc822 == NULL) {
183 * Load the message into memory for translation & measurement
185 CCC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
186 CtdlOutputMsg(msgnum, MT_RFC822,
187 (need_body ? HEADERS_ALL : HEADERS_FAST),
188 0, 1, NULL, SUPPRESS_ENV_TO, NULL, NULL, NULL
191 client_write(HKEY("\r\n")); // extra trailing newline -- to the redirect_buffer, *not* to the client
193 Imap->cached_rfc822 = CCC->redirect_buffer;
194 CCC->redirect_buffer = NULL;
195 Imap->cached_rfc822_msgnum = msgnum;
196 Imap->cached_rfc822_withbody = need_body;
197 if ( (need_to_rewrite_metadata) &&
198 (StrLength(Imap->cached_rfc822) > 0) ) {
199 smi.meta_rfc822_length = StrLength(Imap->cached_rfc822);
205 * Now figure out where the headers/text break is. IMAP considers the
206 * intervening blank line to be part of the headers, not the text.
211 StrBuf *Line = NewStrBuf();
214 StrBufSipLine(Line, Imap->cached_rfc822, &ptr);
216 if ((StrLength(Line) != 0) && (ptr != StrBufNOTNULL))
219 if ((StrLength(Line) != 0) &&
220 (ptr != StrBufNOTNULL) )
222 headers_size = ptr - ChrPtr(Imap->cached_rfc822);
225 } while ( (headers_size == 0) &&
226 (ptr != StrBufNOTNULL) );
228 total_size = StrLength(Imap->cached_rfc822);
229 text_size = total_size - headers_size;
233 headers_size = total_size = StrLength(Imap->cached_rfc822);
237 syslog(LOG_DEBUG, "imap: RFC822 headers=" SIZE_T_FMT ", text=" SIZE_T_FMT ", total=" SIZE_T_FMT, headers_size, text_size, total_size);
239 if (!strcasecmp(whichfmt, "RFC822.SIZE")) {
240 IAPrintf("RFC822.SIZE " SIZE_T_FMT, total_size);
244 else if (!strcasecmp(whichfmt, "RFC822")) {
245 ptr = ChrPtr(Imap->cached_rfc822);
246 bytes_to_send = total_size;
249 else if (!strcasecmp(whichfmt, "RFC822.HEADER")) {
250 ptr = ChrPtr(Imap->cached_rfc822);
251 bytes_to_send = headers_size;
254 else if (!strcasecmp(whichfmt, "RFC822.TEXT")) {
255 ptr = &ChrPtr(Imap->cached_rfc822)[headers_size];
256 bytes_to_send = text_size;
259 IAPrintf("%s {" SIZE_T_FMT "}\r\n", whichfmt, bytes_to_send);
260 iaputs(ptr, bytes_to_send);
265 * Load a specific part of a message into the temp file to be output to a
266 * client. FIXME we can handle parts like "2" and "2.1" and even "2.MIME"
267 * but we still can't handle "2.HEADER" (which might not be a problem).
269 * Note: mime_parser() was called with dont_decode set to 1, so we have the
270 * luxury of simply spewing without having to re-encode.
272 void imap_load_part(char *name, char *filename, char *partnum, char *disp,
273 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
274 char *cbid, void *cbuserdata)
277 StrBuf *desired_section;
279 desired_section = (StrBuf *)cbuserdata;
280 syslog(LOG_DEBUG, "imap: imap_load_part() looking for %s, found %s", ChrPtr(desired_section), partnum);
282 if (!strcasecmp(partnum, ChrPtr(desired_section))) {
283 client_write(content, length);
286 snprintf(mimebuf2, sizeof mimebuf2, "%s.MIME", partnum);
288 if (!strcasecmp(ChrPtr(desired_section), mimebuf2)) {
289 client_write(HKEY("Content-type: "));
290 client_write(cbtype, strlen(cbtype));
291 if (!IsEmptyStr(cbcharset)) {
292 client_write(HKEY("; charset=\""));
293 client_write(cbcharset, strlen(cbcharset));
294 client_write(HKEY("\""));
296 if (!IsEmptyStr(name)) {
297 client_write(HKEY("; name=\""));
298 client_write(name, strlen(name));
299 client_write(HKEY("\""));
301 client_write(HKEY("\r\n"));
302 if (!IsEmptyStr(encoding)) {
303 client_write(HKEY("Content-Transfer-Encoding: "));
304 client_write(encoding, strlen(encoding));
305 client_write(HKEY("\r\n"));
307 if (!IsEmptyStr(encoding)) {
308 client_write(HKEY("Content-Disposition: "));
309 client_write(disp, strlen(disp));
311 if (!IsEmptyStr(filename)) {
312 client_write(HKEY("; filename=\""));
313 client_write(filename, strlen(filename));
314 client_write(HKEY("\""));
316 client_write(HKEY("\r\n"));
318 cprintf("Content-Length: %ld\r\n\r\n", (long)length);
324 * Called by imap_fetch_envelope() to output the "From" field.
325 * This is in its own function because its logic is kind of complex. We
326 * really need to make this suck less.
328 void imap_output_envelope_from(struct CtdlMessage *msg) {
329 char user[SIZ], node[SIZ], name[SIZ];
333 /* For anonymous messages, it's so easy! */
334 if (!is_room_aide() && (msg->cm_anon_type == MES_ANONONLY)) {
335 IAPuts("((\"----\" NIL \"x\" \"x.org\")) ");
338 if (!is_room_aide() && (msg->cm_anon_type == MES_ANONOPT)) {
339 IAPuts("((\"anonymous\" NIL \"x\" \"x.org\")) ");
343 /* For everything else, we do stuff. */
344 IAPuts("(("); // open double-parens
345 IPutMsgField(eAuthor); // display name
346 IAPuts(" NIL "); // source route (not used)
348 if (!CM_IsEmpty(msg, erFc822Addr)) {
349 process_rfc822_addr(msg->cm_fields[erFc822Addr], user, node, name);
350 IPutStr(user, strlen(user)); /* mailbox name (user id) */
352 IPutStr(node, strlen(node)); /* host name */
355 IPutMsgField(eAuthor); /* Make up a synthetic address */
357 IPutStr(CtdlGetConfigStr("c_fqdn"), strlen(CtdlGetConfigStr("c_fqdn")));
360 IAPuts(")) "); /* 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);
399 IPutStr(name, strlen(name));
401 IPutStr(user, strlen(user));
403 IPutStr(node, strlen(node));
405 if (i < (num_addrs-1))
414 * Implements the ENVELOPE fetch item
416 * Note that the imap_strout() function can cleverly output NULL fields as NIL,
417 * so we don't have to check for that condition like we do elsewhere.
419 void imap_fetch_envelope(struct CtdlMessage *msg) {
420 char datestringbuf[SIZ];
422 char *fieldptr = NULL;
427 /* Parse the message date into an IMAP-format date string */
428 if (!CM_IsEmpty(msg, eTimestamp)) {
429 msgdate = atol(msg->cm_fields[eTimestamp]);
432 msgdate = time(NULL);
434 len = datestring(datestringbuf, sizeof datestringbuf, msgdate, DATESTRING_IMAP);
436 /* Now start spewing data fields. The order is important, as it is
437 * defined by the protocol specification. Nonexistent fields must
438 * be output as NIL, existent fields must be quoted or literalled.
439 * The imap_strout() function conveniently does all this for us.
441 IAPuts("ENVELOPE (");
444 IPutStr(datestringbuf, len);
448 IPutMsgField(eMsgSubject);
452 imap_output_envelope_from(msg);
454 /* Sender (default to same as 'From' if not present) */
455 fieldptr = rfc822_fetch_field(msg->cm_fields[eMesageText], "Sender");
456 if (fieldptr != NULL) {
457 imap_output_envelope_addr(fieldptr);
461 imap_output_envelope_from(msg);
465 fieldptr = rfc822_fetch_field(msg->cm_fields[eMesageText], "Reply-to");
466 if (fieldptr != NULL) {
467 imap_output_envelope_addr(fieldptr);
471 imap_output_envelope_from(msg);
475 imap_output_envelope_addr(msg->cm_fields[eRecipient]);
477 /* Cc (we do it this way because there might be a legacy non-Citadel Cc: field present) */
478 fieldptr = msg->cm_fields[eCarbonCopY];
479 if (fieldptr != NULL) {
480 imap_output_envelope_addr(fieldptr);
483 fieldptr = rfc822_fetch_field(msg->cm_fields[eMesageText], "Cc");
484 imap_output_envelope_addr(fieldptr);
485 if (fieldptr != NULL) free(fieldptr);
489 fieldptr = rfc822_fetch_field(msg->cm_fields[eMesageText], "Bcc");
490 imap_output_envelope_addr(fieldptr);
491 if (fieldptr != NULL) free(fieldptr);
494 fieldptr = rfc822_fetch_field(msg->cm_fields[eMesageText], "In-reply-to");
495 IPutStr(fieldptr, (fieldptr)?strlen(fieldptr):0);
497 if (fieldptr != NULL) free(fieldptr);
500 len = msg->cm_lengths[emessageId];
503 (msg->cm_fields[emessageId][0] == '<') &&
504 (msg->cm_fields[emessageId][len - 1] == '>'))
506 IPutMsgField(emessageId);
510 char *Buf = malloc(len + 3);
513 if (msg->cm_fields[emessageId][0] != '<')
518 memcpy(&Buf[pos], msg->cm_fields[emessageId], len);
520 if (msg->cm_fields[emessageId][len] != '>')
534 * This function is called only when CC->redirect_buffer contains a set of
535 * RFC822 headers with no body attached. Its job is to strip that set of
536 * headers down to *only* the ones we're interested in.
538 void imap_strip_headers(StrBuf *section) {
540 StrBuf *which_fields = NULL;
541 int doing_headers = 0;
545 StrBuf *boiled_headers = NULL;
548 int done_headers = 0;
549 const char *Ptr = NULL;
550 CitContext *CCC = CC;
552 if (CCC->redirect_buffer == NULL) return;
554 which_fields = NewStrBufDup(section);
556 if (!strncasecmp(ChrPtr(which_fields), "HEADER.FIELDS", 13))
559 !strncasecmp(ChrPtr(which_fields), "HEADER.FIELDS.NOT", 17))
562 for (i=0; i < StrLength(which_fields); ++i) {
563 if (ChrPtr(which_fields)[i]=='(')
564 StrBufReplaceToken(which_fields, i, 1, HKEY(""));
566 for (i=0; i < StrLength(which_fields); ++i) {
567 if (ChrPtr(which_fields)[i]==')') {
568 StrBufCutAt(which_fields, i, NULL);
572 memset(&Cmd, 0, sizeof(citimap_command));
573 Cmd.CmdBuf = which_fields;
574 num_parms = imap_parameterize(&Cmd);
576 boiled_headers = NewStrBufPlain(NULL, StrLength(CCC->redirect_buffer));
577 Line = NewStrBufPlain(NULL, SIZ);
581 StrBufSipLine(Line, CCC->redirect_buffer, &Ptr);
583 if (!isspace(ChrPtr(Line)[0])) {
585 if (doing_headers == 0) ok = 1;
587 /* we're supposed to print all headers that are not matching the filter list */
588 if (headers_not) for (i=0, ok = 1; (i < num_parms) && (ok == 1); ++i) {
589 if ( (!strncasecmp(ChrPtr(Line),
591 Cmd.Params[i].len)) &&
592 (ChrPtr(Line)[Cmd.Params[i].len]==':') ) {
596 /* we're supposed to print all headers matching the filterlist */
597 else for (i=0, ok = 0; ((i < num_parms) && (ok == 0)); ++i) {
598 if ( (!strncasecmp(ChrPtr(Line),
600 Cmd.Params[i].len)) &&
601 (ChrPtr(Line)[Cmd.Params[i].len]==':') ) {
609 StrBufAppendBuf(boiled_headers, Line, 0);
610 StrBufAppendBufPlain(boiled_headers, HKEY("\r\n"), 0);
613 if ((Ptr == StrBufNOTNULL) ||
614 (StrLength(Line) == 0) ||
615 (ChrPtr(Line)[0]=='\r') ||
616 (ChrPtr(Line)[0]=='\n') ) done_headers = 1;
617 } while (!done_headers);
619 StrBufAppendBufPlain(boiled_headers, HKEY("\r\n"), 0);
621 /* Now save it back (it'll always be smaller) */
622 FreeStrBuf(&CCC->redirect_buffer);
623 CCC->redirect_buffer = boiled_headers;
626 FreeStrBuf(&which_fields);
632 * Implements the BODY and BODY.PEEK fetch items
634 void imap_fetch_body(long msgnum, ConstStr item, int is_peek) {
635 struct CtdlMessage *msg = NULL;
639 size_t pstart, pbytes;
640 int loading_body_now = 0;
642 int burn_the_cache = 0;
643 CitContext *CCC = CC;
644 citimap *Imap = CCCIMAP;
646 /* extract section */
647 section = NewStrBufPlain(CKEY(item));
649 if (strchr(ChrPtr(section), '[') != NULL) {
650 StrBufStripAllBut(section, '[', ']');
652 syslog(LOG_DEBUG, "imap: selected section is [%s]", (StrLength(section) == 0) ? "(empty)" : ChrPtr(section));
654 /* Burn the cache if we don't have the same section of the
655 * same message again.
657 if (Imap->cached_body != NULL) {
658 if (Imap->cached_bodymsgnum != msgnum) {
661 else if ( (!Imap->cached_body_withbody) && (need_body) ) {
664 else if (strcasecmp(Imap->cached_bodypart, ChrPtr(section))) {
667 if (burn_the_cache) {
668 /* Yup, go ahead and burn the cache. */
669 free(Imap->cached_body);
670 Imap->cached_body_len = 0;
671 Imap->cached_body = NULL;
672 Imap->cached_bodymsgnum = (-1);
673 strcpy(Imap->cached_bodypart, "");
677 /* extract partial */
678 partial = NewStrBufPlain(CKEY(item));
679 if (strchr(ChrPtr(partial), '<') != NULL) {
680 StrBufStripAllBut(partial, '<', '>');
683 if ( (is_partial == 1) && (StrLength(partial) > 0) ) {
684 syslog(LOG_DEBUG, "imap: selected partial is <%s>", ChrPtr(partial));
687 if (Imap->cached_body == NULL) {
688 CCC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
689 loading_body_now = 1;
690 msg = CtdlFetchMessage(msgnum, (need_body ? 1 : 0));
693 /* Now figure out what the client wants, and get it */
695 if (!loading_body_now) {
696 /* What we want is already in memory */
699 else if ( (!strcmp(ChrPtr(section), "1")) && (msg->cm_format_type != 4) ) {
700 CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_NONE, 0, 1, SUPPRESS_ENV_TO);
703 else if (StrLength(section) == 0) {
704 CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_ALL, 0, 1, SUPPRESS_ENV_TO);
708 * If the client asked for just headers, or just particular header
709 * fields, strip it down.
711 else if (!strncasecmp(ChrPtr(section), "HEADER", 6)) {
712 /* This used to work with HEADERS_FAST, but then Apple got stupid with their
713 * IMAP library and this broke Mail.App and iPhone Mail, so we had to change it
714 * to HEADERS_ONLY so the trendy hipsters with their iPhones can read mail.
716 CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_ONLY, 0, 1, SUPPRESS_ENV_TO);
717 imap_strip_headers(section);
721 * Strip it down if the client asked for everything _except_ headers.
723 else if (!strncasecmp(ChrPtr(section), "TEXT", 4)) {
724 CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_NONE, 0, 1, SUPPRESS_ENV_TO);
728 * Anything else must be a part specifier.
729 * (Note value of 1 passed as 'dont_decode' so client gets it encoded)
732 mime_parser(CM_RANGE(msg, eMesageText),
733 *imap_load_part, NULL, NULL,
739 if (loading_body_now) {
740 Imap->cached_body_len = StrLength(CCC->redirect_buffer);
741 Imap->cached_body = SmashStrBuf(&CCC->redirect_buffer);
742 Imap->cached_bodymsgnum = msgnum;
743 Imap->cached_body_withbody = need_body;
744 strcpy(Imap->cached_bodypart, ChrPtr(section));
747 if (is_partial == 0) {
749 iaputs(SKEY(section));
750 IAPrintf("] {" SIZE_T_FMT "}\r\n", Imap->cached_body_len);
752 pbytes = Imap->cached_body_len;
755 sscanf(ChrPtr(partial), SIZE_T_FMT "." SIZE_T_FMT, &pstart, &pbytes);
756 if (pbytes > (Imap->cached_body_len - pstart)) {
757 pbytes = Imap->cached_body_len - pstart;
760 iaputs(SKEY(section));
761 IAPrintf("]<" SIZE_T_FMT "> {" SIZE_T_FMT "}\r\n", pstart, pbytes);
764 FreeStrBuf(&partial);
766 /* Here we go -- output it */
767 iaputs(&Imap->cached_body[pstart], pbytes);
773 /* Mark this message as "seen" *unless* this is a "peek" operation */
775 CtdlSetSeen(&msgnum, 1, 1, ctdlsetseen_seen, NULL, NULL);
777 FreeStrBuf(§ion);
781 * Called immediately before outputting a multipart bodystructure
783 void imap_fetch_bodystructure_pre(
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
795 * Called immediately after outputting a multipart bodystructure
797 void imap_fetch_bodystructure_post(
798 char *name, char *filename, char *partnum, char *disp,
799 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
800 char *cbid, void *cbuserdata
808 len = extract_token(subtype, cbtype, 1, '/', sizeof subtype);
809 IPutStr(subtype, len);
812 /* IAPuts(" NIL"); We thought we needed this at one point, but maybe we don't... */
820 * Output the info for a MIME part in the format required by BODYSTRUCTURE.
823 void imap_fetch_bodystructure_part(
824 char *name, char *filename, char *partnum, char *disp,
825 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
826 char *cbid, void *cbuserdata
830 int have_encoding = 0;
833 char cbmaintype[128];
838 if (cbtype != NULL) if (!IsEmptyStr(cbtype)) have_cbtype = 1;
840 cbmaintype_len = extract_token(cbmaintype, cbtype, 0, '/', sizeof cbmaintype);
841 cbsubtype_len = extract_token(cbsubtype, cbtype, 1, '/', sizeof cbsubtype);
844 strcpy(cbmaintype, "TEXT");
846 strcpy(cbsubtype, "PLAIN");
851 IPutStr(cbmaintype, cbmaintype_len); /* body type */
853 IPutStr(cbsubtype, cbsubtype_len); /* body subtype */
856 IAPuts("("); /* begin body parameter list */
858 /* "NAME" must appear as the first parameter. This is not required by IMAP,
859 * but the Asterisk voicemail application blindly assumes that NAME will be in
860 * the first position. If it isn't, it rejects the message.
862 if ((name != NULL) && (!IsEmptyStr(name))) {
864 IPutStr(name, strlen(name));
868 IAPuts("\"CHARSET\" ");
869 if ((cbcharset == NULL) || (cbcharset[0] == 0)){
870 IPutStr(HKEY("US-ASCII"));
873 IPutStr(cbcharset, strlen(cbcharset));
875 IAPuts(") "); /* end body parameter list */
877 IAPuts("NIL "); /* Body ID */
878 IAPuts("NIL "); /* Body description */
880 if ((encoding != NULL) && (encoding[0] != 0)) have_encoding = 1;
882 IPutStr(encoding, strlen(encoding));
885 IPutStr(HKEY("7BIT"));
889 /* The next field is the size of the part in bytes. */
890 IAPrintf("%ld ", (long)length); /* bytes */
892 /* The next field is the number of lines in the part, if and only
893 * if the part is TEXT. More gratuitous complexity.
895 if (!strcasecmp(cbmaintype, "TEXT")) {
896 if (length) for (i=0; i<length; ++i) {
897 if (((char *)content)[i] == '\n') ++lines;
899 IAPrintf("%d ", lines);
902 /* More gratuitous complexity */
903 if ((!strcasecmp(cbmaintype, "MESSAGE"))
904 && (!strcasecmp(cbsubtype, "RFC822"))) {
905 /* FIXME: message/rfc822 also needs to output the envelope structure,
906 * body structure, and line count of the encapsulated message. Fortunately
907 * there are not yet any clients depending on this, so we can get away
908 * with not implementing it for now.
912 /* MD5 value of body part; we can get away with NIL'ing this */
916 if ((disp == NULL) || IsEmptyStr(disp)) {
921 IPutStr(disp, strlen(disp));
922 if ((filename != NULL) && (!IsEmptyStr(filename))) {
923 IAPuts(" (\"FILENAME\" ");
924 IPutStr(filename, strlen(filename));
930 /* Body language (not defined yet) */
937 * Spew the BODYSTRUCTURE data for a message.
940 void imap_fetch_bodystructure (long msgnum, const char *item,
941 struct CtdlMessage *msg) {
942 const char *rfc822 = NULL;
943 const char *rfc822_body = NULL;
945 size_t rfc822_headers_len;
946 size_t rfc822_body_len;
947 const char *ptr = NULL;
952 /* Handle NULL message gracefully */
954 IAPuts("BODYSTRUCTURE (\"TEXT\" \"PLAIN\" "
955 "(\"CHARSET\" \"US-ASCII\") NIL NIL "
960 /* For non-RFC822 (ordinary Citadel) messages, this is short and
963 if (msg->cm_format_type != FMT_RFC822) {
965 /* *sigh* We have to RFC822-format the message just to be able
966 * to measure it. FIXME use smi cached fields if possible
969 CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
970 CtdlOutputPreLoadedMsg(msg, MT_RFC822, 0, 0, 1, SUPPRESS_ENV_TO);
971 rfc822_len = StrLength(CC->redirect_buffer);
972 rfc822 = pch = SmashStrBuf(&CC->redirect_buffer);
976 ptr = cmemreadline(ptr, buf, sizeof buf);
978 if ((IsEmptyStr(buf)) && (rfc822_body == NULL)) {
983 rfc822_headers_len = rfc822_body - rfc822;
984 rfc822_body_len = rfc822_len - rfc822_headers_len;
987 IAPuts("BODYSTRUCTURE (\"TEXT\" \"PLAIN\" "
988 "(\"CHARSET\" \"US-ASCII\") NIL NIL "
990 IAPrintf(SIZE_T_FMT " %d)", rfc822_body_len, lines);
995 /* For messages already stored in RFC822 format, we have to parse. */
996 IAPuts("BODYSTRUCTURE ");
997 mime_parser(CM_RANGE(msg, eMesageText),
998 *imap_fetch_bodystructure_part, /* part */
999 *imap_fetch_bodystructure_pre, /* pre-multi */
1000 *imap_fetch_bodystructure_post, /* post-multi */
1002 1); /* don't decode -- we want it as-is */
1007 * imap_do_fetch() calls imap_do_fetch_msg() to output the data of an
1008 * individual message, once it has been selected for output.
1010 void imap_do_fetch_msg(int seq, citimap_command *Cmd) {
1012 citimap *Imap = IMAP;
1013 struct CtdlMessage *msg = NULL;
1014 int body_loaded = 0;
1016 /* Don't attempt to fetch bogus messages or UID's */
1017 if (seq < 1) return;
1018 if (Imap->msgids[seq-1] < 1L) return;
1021 IAPrintf("* %d FETCH (", seq);
1023 for (i=0; i<Cmd->num_parms; ++i) {
1025 /* Fetchable without going to the message store at all */
1026 if (!strcasecmp(Cmd->Params[i].Key, "UID")) {
1027 imap_fetch_uid(seq);
1029 else if (!strcasecmp(Cmd->Params[i].Key, "FLAGS")) {
1030 imap_fetch_flags(seq-1);
1033 /* Potentially fetchable from cache, if the client requests
1034 * stuff from the same message several times in a row.
1036 else if (!strcasecmp(Cmd->Params[i].Key, "RFC822")) {
1037 imap_fetch_rfc822(Imap->msgids[seq-1], Cmd->Params[i].Key);
1039 else if (!strcasecmp(Cmd->Params[i].Key, "RFC822.HEADER")) {
1040 imap_fetch_rfc822(Imap->msgids[seq-1], Cmd->Params[i].Key);
1042 else if (!strcasecmp(Cmd->Params[i].Key, "RFC822.SIZE")) {
1043 imap_fetch_rfc822(Imap->msgids[seq-1], Cmd->Params[i].Key);
1045 else if (!strcasecmp(Cmd->Params[i].Key, "RFC822.TEXT")) {
1046 imap_fetch_rfc822(Imap->msgids[seq-1], Cmd->Params[i].Key);
1049 /* BODY fetches do their own fetching and caching too. */
1050 else if (!strncasecmp(Cmd->Params[i].Key, "BODY[", 5)) {
1051 imap_fetch_body(Imap->msgids[seq-1], Cmd->Params[i], 0);
1053 else if (!strncasecmp(Cmd->Params[i].Key, "BODY.PEEK[", 10)) {
1054 imap_fetch_body(Imap->msgids[seq-1], Cmd->Params[i], 1);
1057 /* Otherwise, load the message into memory.
1059 else if (!strcasecmp(Cmd->Params[i].Key, "BODYSTRUCTURE")) {
1060 if ((msg != NULL) && (!body_loaded)) {
1061 CM_Free(msg); /* need the whole thing */
1065 msg = CtdlFetchMessage(Imap->msgids[seq-1], 1);
1068 imap_fetch_bodystructure(Imap->msgids[seq-1],
1069 Cmd->Params[i].Key, msg);
1071 else if (!strcasecmp(Cmd->Params[i].Key, "ENVELOPE")) {
1073 msg = CtdlFetchMessage(Imap->msgids[seq-1], 0);
1076 imap_fetch_envelope(msg);
1078 else if (!strcasecmp(Cmd->Params[i].Key, "INTERNALDATE")) {
1080 msg = CtdlFetchMessage(Imap->msgids[seq-1], 0);
1083 imap_fetch_internaldate(msg);
1086 if (i != Cmd->num_parms-1) IAPuts(" ");
1099 * imap_fetch() calls imap_do_fetch() to do its actual work, once it's
1100 * validated and boiled down the request a bit.
1102 void imap_do_fetch(citimap_command *Cmd) {
1103 citimap *Imap = IMAP;
1106 /* debug output the parsed vector */
1109 syslog(LOG_DEBUG, "imap: ----- %ld params", Cmd->num_parms);
1111 for (i=0; i < Cmd->num_parms; i++) {
1112 if (Cmd->Params[i].len != strlen(Cmd->Params[i].Key))
1113 syslog(LOG_DEBUG, "imap: *********** %ld != %ld : %s",
1115 strlen(Cmd->Params[i].Key),
1116 Cmd->Params[i].Key);
1118 syslog(LOG_DEBUG, "imap: %ld : %s",
1120 Cmd->Params[i].Key);
1125 if (Imap->num_msgs > 0) {
1126 for (i = 0; i < Imap->num_msgs; ++i) {
1128 /* Abort the fetch loop if the session breaks.
1129 * This is important for users who keep mailboxes
1130 * that are too big *and* are too impatient to
1131 * let them finish loading. :)
1133 if (CC->kill_me) return;
1135 /* Get any message marked for fetch. */
1136 if (Imap->flags[i] & IMAP_SELECTED) {
1137 imap_do_fetch_msg(i+1, Cmd);
1146 * Back end for imap_handle_macros()
1147 * Note that this function *only* looks at the beginning of the string. It
1148 * is not a generic search-and-replace function.
1150 void imap_macro_replace(StrBuf *Buf, long where,
1152 char *find, long findlen,
1153 char *replace, long replacelen)
1156 if (StrLength(Buf) - where > findlen)
1159 if (!strncasecmp(ChrPtr(Buf) + where, find, findlen)) {
1160 if (ChrPtr(Buf)[where + findlen] == ' ') {
1161 StrBufPlain(TmpBuf, replace, replacelen);
1162 StrBufAppendBufPlain(TmpBuf, HKEY(" "), 0);
1163 StrBufReplaceToken(Buf, where, findlen,
1166 if (where + findlen == StrLength(Buf)) {
1167 StrBufReplaceToken(Buf, where, findlen,
1168 replace, replacelen);
1176 * Handle macros embedded in FETCH data items.
1177 * (What the heck are macros doing in a wire protocol? Are we trying to save
1178 * the computer at the other end the trouble of typing a lot of characters?)
1180 void imap_handle_macros(citimap_command *Cmd) {
1183 StrBuf *Tmp = NewStrBuf();
1185 for (i=0; i < StrLength(Cmd->CmdBuf); ++i) {
1186 char ch = ChrPtr(Cmd->CmdBuf)[i];
1191 else if ((ch==')') ||
1197 imap_macro_replace(Cmd->CmdBuf, i,
1200 HKEY("FLAGS INTERNALDATE RFC822.SIZE ENVELOPE")
1202 imap_macro_replace(Cmd->CmdBuf, i,
1205 HKEY("BODYSTRUCTURE")
1207 imap_macro_replace(Cmd->CmdBuf, i,
1210 HKEY("FLAGS INTERNALDATE RFC822.SIZE")
1212 imap_macro_replace(Cmd->CmdBuf, i,
1215 HKEY("FLAGS INTERNALDATE RFC822.SIZE ENVELOPE BODY")
1224 * Break out the data items requested, possibly a parenthesized list.
1225 * Returns the number of data items, or -1 if the list is invalid.
1226 * NOTE: this function alters the string it is fed, and uses it as a buffer
1227 * to hold the data for the pointers it returns.
1229 int imap_extract_data_items(citimap_command *Cmd)
1233 const char *pch, *end;
1235 /* Convert all whitespace to ordinary space characters. */
1236 pch = ChrPtr(Cmd->CmdBuf);
1237 end = pch + StrLength(Cmd->CmdBuf);
1242 StrBufPeek(Cmd->CmdBuf, pch, 0, ' ');
1246 /* Strip leading and trailing whitespace, then strip leading and
1247 * trailing parentheses if it's a list
1249 StrBufTrim(Cmd->CmdBuf);
1250 pch = ChrPtr(Cmd->CmdBuf);
1251 if ( (pch[0]=='(') &&
1252 (pch[StrLength(Cmd->CmdBuf)-1]==')') )
1254 StrBufCutRight(Cmd->CmdBuf, 1);
1255 StrBufCutLeft(Cmd->CmdBuf, 1);
1256 StrBufTrim(Cmd->CmdBuf);
1259 /* Parse any macro data items */
1260 imap_handle_macros(Cmd);
1263 * Now break out the data items. We throw in one trailing space in
1264 * order to avoid having to break out the last one manually.
1266 nArgs = StrLength(Cmd->CmdBuf) / 10 + 10;
1267 nArgs = CmdAdjust(Cmd, nArgs, 0);
1269 Cmd->Params[Cmd->num_parms].Key = pch = ChrPtr(Cmd->CmdBuf);
1270 end = Cmd->Params[Cmd->num_parms].Key + StrLength(Cmd->CmdBuf);
1280 else if ((*pch==')') ||
1286 if ((nest <= 0) && (*pch==' ')) {
1287 StrBufPeek(Cmd->CmdBuf, pch, 0, '\0');
1288 Cmd->Params[Cmd->num_parms].len =
1289 pch - Cmd->Params[Cmd->num_parms].Key;
1291 if (Cmd->num_parms + 1 >= Cmd->avail_parms) {
1292 nArgs = CmdAdjust(Cmd, nArgs * 2, 1);
1295 Cmd->Params[Cmd->num_parms].Key = ++pch;
1297 else if (pch + 1 == end) {
1298 Cmd->Params[Cmd->num_parms].len =
1299 pch - Cmd->Params[Cmd->num_parms].Key + 1;
1305 return Cmd->num_parms;
1311 * One particularly hideous aspect of IMAP is that we have to allow the client
1312 * to specify arbitrary ranges and/or sets of messages to fetch. Citadel IMAP
1313 * handles this by setting the IMAP_SELECTED flag for each message specified in
1314 * the ranges/sets, then looping through the message array, outputting messages
1315 * with the flag set. We don't bother returning an error if an out-of-range
1316 * number is specified (we just return quietly) because any client braindead
1317 * enough to request a bogus message number isn't going to notice the
1318 * difference anyway.
1320 * This function clears out the IMAP_SELECTED bits, then sets that bit for each
1321 * message included in the specified range.
1323 * Set is_uid to 1 to fetch by UID instead of sequence number.
1325 void imap_pick_range(const char *supplied_range, int is_uid) {
1326 citimap *Imap = IMAP;
1330 char setstr[SIZ], lostr[SIZ], histr[SIZ];
1332 char actual_range[SIZ];
1335 * Handle the "ALL" macro
1337 if (!strcasecmp(supplied_range, "ALL")) {
1338 safestrncpy(actual_range, "1:*", sizeof actual_range);
1341 safestrncpy(actual_range, supplied_range, sizeof actual_range);
1345 * Clear out the IMAP_SELECTED flags for all messages.
1347 for (i = 0; i < Imap->num_msgs; ++i) {
1348 Imap->flags[i] = Imap->flags[i] & ~IMAP_SELECTED;
1352 * Now set it for all specified messages.
1354 num_sets = num_tokens(actual_range, ',');
1355 for (s=0; s<num_sets; ++s) {
1356 extract_token(setstr, actual_range, s, ',', sizeof setstr);
1358 extract_token(lostr, setstr, 0, ':', sizeof lostr);
1359 if (num_tokens(setstr, ':') >= 2) {
1360 extract_token(histr, setstr, 1, ':', sizeof histr);
1361 if (!strcmp(histr, "*")) snprintf(histr, sizeof histr, "%ld", LONG_MAX);
1364 safestrncpy(histr, lostr, sizeof histr);
1369 /* Loop through the array, flipping bits where appropriate */
1370 for (i = 1; i <= Imap->num_msgs; ++i) {
1371 if (is_uid) { /* fetch by sequence number */
1372 if ( (Imap->msgids[i-1]>=lo)
1373 && (Imap->msgids[i-1]<=hi)) {
1374 Imap->flags[i-1] |= IMAP_SELECTED;
1377 else { /* fetch by uid */
1378 if ( (i>=lo) && (i<=hi)) {
1379 Imap->flags[i-1] |= IMAP_SELECTED;
1389 * This function is called by the main command loop.
1391 void imap_fetch(int num_parms, ConstStr *Params) {
1392 citimap_command Cmd;
1395 if (num_parms < 4) {
1396 IReply("BAD invalid parameters");
1400 imap_pick_range(Params[2].Key, 0);
1402 memset(&Cmd, 0, sizeof(citimap_command));
1403 Cmd.CmdBuf = NewStrBufPlain(NULL, StrLength(IMAP->Cmd.CmdBuf));
1404 MakeStringOf(Cmd.CmdBuf, 3);
1406 num_items = imap_extract_data_items(&Cmd);
1407 if (num_items < 1) {
1408 IReply("BAD invalid data item list");
1409 FreeStrBuf(&Cmd.CmdBuf);
1414 imap_do_fetch(&Cmd);
1415 IReply("OK FETCH completed");
1416 FreeStrBuf(&Cmd.CmdBuf);
1421 * This function is called by the main command loop.
1423 void imap_uidfetch(int num_parms, ConstStr *Params) {
1424 citimap_command Cmd;
1427 int have_uid_item = 0;
1429 if (num_parms < 5) {
1430 IReply("BAD invalid parameters");
1434 imap_pick_range(Params[3].Key, 1);
1436 memset(&Cmd, 0, sizeof(citimap_command));
1437 Cmd.CmdBuf = NewStrBufPlain(NULL, StrLength(IMAP->Cmd.CmdBuf));
1439 MakeStringOf(Cmd.CmdBuf, 4);
1441 syslog(LOG_DEBUG, "imap: -------%s--------", ChrPtr(Cmd.CmdBuf));
1443 num_items = imap_extract_data_items(&Cmd);
1444 if (num_items < 1) {
1445 IReply("BAD invalid data item list");
1446 FreeStrBuf(&Cmd.CmdBuf);
1451 /* If the "UID" item was not included, we include it implicitly
1452 * (at the beginning) because this is a UID FETCH command
1454 for (i=0; i<num_items; ++i) {
1455 if (!strcasecmp(Cmd.Params[i].Key, "UID")) ++have_uid_item;
1457 if (have_uid_item == 0) {
1458 if (Cmd.num_parms + 1 >= Cmd.avail_parms)
1459 CmdAdjust(&Cmd, Cmd.avail_parms + 1, 1);
1460 memmove(&Cmd.Params[1],
1462 sizeof(ConstStr) * Cmd.num_parms);
1465 Cmd.Params[0] = (ConstStr){HKEY("UID")};
1468 imap_do_fetch(&Cmd);
1469 IReply("OK UID FETCH completed");
1470 FreeStrBuf(&Cmd.CmdBuf);