4 * Implements the FETCH command in IMAP.
5 * This command is way too convoluted. Marc Crispin is a fscking idiot.
18 #include <sys/types.h>
27 #include "sysdep_decls.h"
28 #include "citserver.h"
31 #include "dynloader.h"
38 #include "internet_addressing.h"
39 #include "mime_parser.h"
40 #include "serv_imap.h"
41 #include "imap_tools.h"
42 #include "imap_fetch.h"
47 struct imap_fetch_part {
48 char desired_section[SIZ];
55 * Output the flags associated with a message. Note that this function
56 * expects an index number in the array, *not* a sequence or uid number.
58 void imap_output_flags(int num) {
60 if (IMAP->flags[num] & IMAP_DELETED) cprintf("\\Deleted ");
67 * Individual field functions for imap_do_fetch_msg() ...
72 void imap_fetch_uid(int seq) {
73 cprintf("UID %ld", IMAP->msgids[seq-1]);
76 void imap_fetch_internaldate(struct CtdlMessage *msg) {
80 if (msg->cm_fields['T'] != NULL) {
81 msgdate = atol(msg->cm_fields['T']);
87 datestring(buf, msgdate, DATESTRING_IMAP);
88 cprintf("INTERNALDATE \"%s\"", buf);
93 * Fetch RFC822-formatted messages.
95 * 'whichfmt' should be set to one of:
96 * "RFC822" entire message
97 * "RFC822.HEADER" headers only (with trailing blank line)
98 * "RFC822.SIZE" size of translated message
99 * "RFC822.TEXT" body only (without leading blank line)
101 void imap_fetch_rfc822(int msgnum, char *whichfmt, struct CtdlMessage *msg) {
105 long headers_size, text_size, total_size;
106 long bytes_remaining = 0;
111 lprintf(1, "Cannot open temp file: %s\n", strerror(errno));
116 * Load the message into a temp file for translation and measurement
118 CtdlRedirectOutput(tmp, -1);
119 CtdlOutputPreLoadedMsg(msg, msgnum, MT_RFC822, 0, 0, 1);
120 CtdlRedirectOutput(NULL, -1);
121 if (!is_valid_message(msg)) {
122 lprintf(1, "WARNING: output clobbered the message!\n");
126 * Now figure out where the headers/text break is. IMAP considers the
127 * intervening blank line to be part of the headers, not the text.
132 ptr = fgets(buf, sizeof buf, tmp);
135 if (strlen(buf) == 0) headers_size = ftell(tmp);
137 } while ( (headers_size == 0L) && (ptr != NULL) );
138 fseek(tmp, 0L, SEEK_END);
139 total_size = ftell(tmp);
140 text_size = total_size - headers_size;
142 if (!strcasecmp(whichfmt, "RFC822.SIZE")) {
143 cprintf("RFC822.SIZE %ld", total_size);
148 else if (!strcasecmp(whichfmt, "RFC822")) {
149 bytes_remaining = total_size;
153 else if (!strcasecmp(whichfmt, "RFC822.HEADER")) {
154 bytes_remaining = headers_size;
158 else if (!strcasecmp(whichfmt, "RFC822.TEXT")) {
159 bytes_remaining = text_size;
160 fseek(tmp, headers_size, SEEK_SET);
163 cprintf("%s {%ld}\r\n", whichfmt, bytes_remaining);
164 blocksize = sizeof(buf);
165 while (bytes_remaining > 0L) {
166 if (blocksize > bytes_remaining) blocksize = bytes_remaining;
167 fread(buf, blocksize, 1, tmp);
168 client_write(buf, blocksize);
169 bytes_remaining = bytes_remaining - blocksize;
178 * Load a specific part of a message into the temp file to be output to a
179 * client. FIXME we can handle parts like "2" and "2.1" and even "2.MIME"
180 * but we still can't handle "2.HEADER" (which might not be a problem, because
181 * we currently don't have the ability to break out nested RFC822's anyway).
183 * Note: mime_parser() was called with dont_decode set to 1, so we have the
184 * luxury of simply spewing without having to re-encode.
186 void imap_load_part(char *name, char *filename, char *partnum, char *disp,
187 void *content, char *cbtype, size_t length, char *encoding,
190 struct imap_fetch_part *imfp;
193 imfp = (struct imap_fetch_part *)cbuserdata;
195 if (!strcasecmp(partnum, imfp->desired_section)) {
196 fwrite(content, length, 1, imfp->output_fp);
199 sprintf(mbuf2, "%s.MIME", partnum);
201 if (!strcasecmp(imfp->desired_section, mbuf2)) {
202 fprintf(imfp->output_fp, "Content-type: %s", cbtype);
203 if (strlen(name) > 0)
204 fprintf(imfp->output_fp, "; name=\"%s\"", name);
205 fprintf(imfp->output_fp, "\r\n");
206 if (strlen(encoding) > 0)
207 fprintf(imfp->output_fp,
208 "Content-Transfer-Encoding: %s\r\n", encoding);
209 if (strlen(encoding) > 0) {
210 fprintf(imfp->output_fp, "Content-Disposition: %s",
212 if (strlen(filename) > 0) {
213 fprintf(imfp->output_fp, "; filename=\"%s\"",
216 fprintf(imfp->output_fp, "\r\n");
218 fprintf(imfp->output_fp, "Content-Length: %d\r\n", length);
219 fprintf(imfp->output_fp, "\r\n");
227 * Called by imap_fetch_envelope() to output the "From" field.
228 * This is in its own function because its logic is kind of complex. We
229 * really need to make this suck less.
231 void imap_output_envelope_from(struct CtdlMessage *msg) {
232 char user[1024], node[1024], name[1024];
234 cprintf("(("); /* open double-parens */
235 imap_strout(msg->cm_fields['A']); /* personal name */
236 cprintf(" NIL "); /* source route (not used) */
238 if (msg->cm_fields['F'] != NULL) {
239 process_rfc822_addr(msg->cm_fields['F'], user, node, name);
240 imap_strout(user); /* mailbox name (user id) */
242 if (!strcasecmp(node, config.c_nodename)) {
243 imap_strout(config.c_fqdn);
246 imap_strout(node); /* host name */
250 imap_strout(msg->cm_fields['A']); /* mailbox name (user id) */
252 imap_strout(msg->cm_fields['N']); /* host name */
255 cprintf(")) "); /* close double-parens */
260 * Implements the ENVELOPE fetch item
262 * FIXME ... we only output some of the fields right now. Definitely need
263 * to do all of them. Accurately, too.
265 * Note that the imap_strout() function can cleverly output NULL fields as NIL,
266 * so we don't have to check for that condition like we do elsewhere.
268 void imap_fetch_envelope(long msgnum, struct CtdlMessage *msg) {
269 char datestringbuf[SIZ];
271 char *fieldptr = NULL;
273 /* Parse the message date into an IMAP-format date string */
274 if (msg->cm_fields['T'] != NULL) {
275 msgdate = atol(msg->cm_fields['T']);
278 msgdate = time(NULL);
280 datestring(datestringbuf, msgdate, DATESTRING_IMAP);
282 /* Now start spewing data fields. The order is important, as it is
283 * defined by the protocol specification. Nonexistent fields must
284 * be output as NIL, existent fields must be quoted or literalled.
285 * The imap_strout() function conveniently does all this for us.
287 cprintf("ENVELOPE (");
290 imap_strout(datestringbuf);
294 imap_strout(msg->cm_fields['U']);
298 imap_output_envelope_from(msg);
302 /* FIXME ... check for a *real* Sender: field */
305 imap_output_envelope_from(msg);
310 /* FIXME ... check for a *real* Reply-to: field */
313 imap_output_envelope_from(msg);
316 cprintf("NIL "); /* to */
318 cprintf("NIL "); /* cc */
320 cprintf("NIL "); /* bcc */
323 fieldptr = rfc822_fetch_field(msg->cm_fields['M'], "In-reply-to");
324 imap_strout(fieldptr);
326 if (fieldptr != NULL) phree(fieldptr);
329 imap_strout(msg->cm_fields['I']);
336 * Strip any non header information out of a chunk of RFC822 data on disk
338 void imap_strip_headers(FILE *fp) {
342 while (fgets(buf, sizeof buf, fp) != NULL) {
344 if (strlen(buf) == 0) {
346 ftruncate(fileno(fp), ftell(fp));
350 fprintf(fp, "\r\n"); /* add the trailing newline */
356 * Implements the BODY and BODY.PEEK fetch items
358 void imap_fetch_body(long msgnum, char *item, int is_peek,
359 struct CtdlMessage *msg) {
366 long bytes_remaining = 0;
369 struct imap_fetch_part imfp;
371 /* extract section */
372 strcpy(section, item);
373 for (i=0; i<strlen(section); ++i) {
374 if (section[i]=='[') strcpy(section, §ion[i+1]);
376 for (i=0; i<strlen(section); ++i) {
377 if (section[i]==']') section[i] = 0;
379 lprintf(9, "Section is %s\n", section);
381 /* extract partial */
382 strcpy(partial, item);
383 for (i=0; i<strlen(partial); ++i) {
384 if (partial[i]=='<') {
385 strcpy(partial, &partial[i+1]);
389 for (i=0; i<strlen(partial); ++i) {
390 if (partial[i]=='>') partial[i] = 0;
392 if (is_partial == 0) strcpy(partial, "");
393 if (strlen(partial) > 0) lprintf(9, "Partial is %s\n", partial);
397 lprintf(1, "Cannot open temp file: %s\n", strerror(errno));
401 /* Now figure out what the client wants, and get it */
403 if (!strcmp(section, "")) { /* the whole thing */
404 CtdlRedirectOutput(tmp, -1);
405 CtdlOutputPreLoadedMsg(msg, msgnum, MT_RFC822, 0, 0, 1);
406 CtdlRedirectOutput(NULL, -1);
410 * Be obnoxious and send the entire header, even if the client only
411 * asks for certain fields. FIXME this shortcut later.
413 else if (!strncasecmp(section, "HEADER", 6)) {
414 CtdlRedirectOutput(tmp, -1);
415 CtdlOutputPreLoadedMsg(msg, msgnum, MT_RFC822, 1, 0, 1);
416 CtdlRedirectOutput(NULL, -1);
417 imap_strip_headers(tmp);
421 * Anything else must be a part specifier.
422 * (Note value of 1 passed as 'dont_decode' so client gets it encoded)
425 safestrncpy(imfp.desired_section, section,
426 sizeof(imfp.desired_section));
427 imfp.output_fp = tmp;
429 mime_parser(msg->cm_fields['M'], NULL,
430 *imap_load_part, NULL, NULL,
436 fseek(tmp, 0L, SEEK_END);
437 bytes_remaining = ftell(tmp);
439 if (is_partial == 0) {
441 cprintf("BODY[%s] {%ld}\r\n", section, bytes_remaining);
444 sscanf(partial, "%ld.%ld", &pstart, &pbytes);
445 if ((bytes_remaining - pstart) < pbytes) {
446 pbytes = bytes_remaining - pstart;
448 fseek(tmp, pstart, SEEK_SET);
449 bytes_remaining = pbytes;
450 cprintf("BODY[%s] {%ld}<%ld>\r\n",
451 section, bytes_remaining, pstart);
454 blocksize = sizeof(buf);
455 while (bytes_remaining > 0L) {
456 if (blocksize > bytes_remaining) blocksize = bytes_remaining;
457 fread(buf, blocksize, 1, tmp);
458 client_write(buf, blocksize);
459 bytes_remaining = bytes_remaining - blocksize;
465 /* FIXME set the last read pointer or something */
470 * Called immediately before outputting a multipart bodystructure
472 void imap_fetch_bodystructure_pre(
473 char *name, char *filename, char *partnum, char *disp,
474 void *content, char *cbtype, size_t length, char *encoding,
484 * Called immediately after outputting a multipart bodystructure
486 void imap_fetch_bodystructure_post(
487 char *name, char *filename, char *partnum, char *disp,
488 void *content, char *cbtype, size_t length, char *encoding,
494 extract_token(subtype, cbtype, 1, '/');
495 imap_strout(subtype);
502 * Output the info for a MIME part in the format required by BODYSTRUCTURE.
505 void imap_fetch_bodystructure_part(
506 char *name, char *filename, char *partnum, char *disp,
507 void *content, char *cbtype, size_t length, char *encoding,
513 int have_encoding = 0;
517 if (cbtype != NULL) if (strlen(cbtype)>0) have_cbtype = 1;
520 extract_token(buf, cbtype, 0, '/');
523 extract_token(buf, cbtype, 1, '/');
528 cprintf("\"TEXT\" \"PLAIN\" ");
531 cprintf("(\"CHARSET\" \"US-ASCII\"");
533 if (name != NULL) if (strlen(name)>0) {
534 cprintf(" \"NAME\" ");
538 if (filename != NULL) if (strlen(filename)>0) {
539 cprintf(" \"FILENAME\" ");
547 if (encoding != NULL) if (strlen(encoding) > 0) have_encoding = 1;
550 imap_strout(encoding);
557 cprintf("%ld ", length); /* bytes */
558 cprintf("NIL) "); /* lines */
564 * Spew the BODYSTRUCTURE data for a message. (Do you need a silencer if
565 * you're going to shoot a MIME? Do you need a reason to shoot Mark Crispin?
569 void imap_fetch_bodystructure (long msgnum, char *item,
570 struct CtdlMessage *msg) {
576 /* For non-RFC822 (ordinary Citadel) messages, this is short and
579 if (msg->cm_format_type != FMT_RFC822) {
581 /* *sigh* We have to RFC822-format the message just to be able
585 if (tmp == NULL) return;
586 CtdlRedirectOutput(tmp, -1);
587 CtdlOutputPreLoadedMsg(msg, msgnum, MT_RFC822, 0, 0, 1);
588 CtdlRedirectOutput(NULL, -1);
591 while (fgets(buf, sizeof buf, tmp) != NULL) ++lines;
595 cprintf("BODYSTRUCTURE (\"TEXT\" \"PLAIN\" "
596 "(\"CHARSET\" \"US-ASCII\") NIL NIL "
597 "\"7BIT\" %ld %ld)", bytes, lines);
602 /* For messages already stored in RFC822 format, we have to parse. */
603 cprintf("BODYSTRUCTURE ");
604 mime_parser(msg->cm_fields['M'],
606 *imap_fetch_bodystructure_part, /* part */
607 *imap_fetch_bodystructure_pre, /* pre-multi */
608 *imap_fetch_bodystructure_post, /* post-multi */
619 * imap_do_fetch() calls imap_do_fetch_msg() to output the deta of an
620 * individual message, once it has been successfully loaded from disk.
622 void imap_do_fetch_msg(int seq, struct CtdlMessage *msg,
623 int num_items, char **itemlist) {
626 cprintf("* %d FETCH (", seq);
628 for (i=0; i<num_items; ++i) {
630 if (!strncasecmp(itemlist[i], "BODY[", 5)) {
631 imap_fetch_body(IMAP->msgids[seq-1], itemlist[i],
634 else if (!strncasecmp(itemlist[i], "BODY.PEEK[", 10)) {
635 imap_fetch_body(IMAP->msgids[seq-1], itemlist[i],
638 else if (!strcasecmp(itemlist[i], "BODYSTRUCTURE")) {
639 imap_fetch_bodystructure(IMAP->msgids[seq-1],
642 else if (!strcasecmp(itemlist[i], "ENVELOPE")) {
643 imap_fetch_envelope(IMAP->msgids[seq-1], msg);
645 else if (!strcasecmp(itemlist[i], "FLAGS")) {
646 imap_output_flags(seq-1);
648 else if (!strcasecmp(itemlist[i], "INTERNALDATE")) {
649 imap_fetch_internaldate(msg);
651 else if (!strcasecmp(itemlist[i], "RFC822")) {
652 imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i], msg);
654 else if (!strcasecmp(itemlist[i], "RFC822.HEADER")) {
655 imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i], msg);
657 else if (!strcasecmp(itemlist[i], "RFC822.SIZE")) {
658 imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i], msg);
660 else if (!strcasecmp(itemlist[i], "RFC822.TEXT")) {
661 imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i], msg);
663 else if (!strcasecmp(itemlist[i], "UID")) {
667 if (i != num_items-1) cprintf(" ");
676 * imap_fetch() calls imap_do_fetch() to do its actual work, once it's
677 * validated and boiled down the request a bit.
679 void imap_do_fetch(int num_items, char **itemlist) {
681 struct CtdlMessage *msg;
683 if (IMAP->num_msgs > 0)
684 for (i = 0; i < IMAP->num_msgs; ++i)
685 if (IMAP->flags[i] & IMAP_SELECTED) {
686 msg = CtdlFetchMessage(IMAP->msgids[i]);
688 imap_do_fetch_msg(i+1, msg, num_items, itemlist);
689 CtdlFreeMessage(msg);
692 cprintf("* %d FETCH <internal error>\r\n", i+1);
700 * Back end for imap_handle_macros()
701 * Note that this function *only* looks at the beginning of the string. It
702 * is not a generic search-and-replace function.
704 void imap_macro_replace(char *str, char *find, char *replace) {
707 if (!strncasecmp(str, find, strlen(find))) {
708 if (str[strlen(find)]==' ') {
709 strcpy(holdbuf, &str[strlen(find)+1]);
710 strcpy(str, replace);
712 strcat(str, holdbuf);
714 if (str[strlen(find)]==0) {
715 strcpy(holdbuf, &str[strlen(find)+1]);
716 strcpy(str, replace);
724 * Handle macros embedded in FETCH data items.
725 * (What the heck are macros doing in a wire protocol? Are we trying to save
726 * the computer at the other end the trouble of typing a lot of characters?)
728 void imap_handle_macros(char *str) {
732 for (i=0; i<strlen(str); ++i) {
733 if (str[i]=='(') ++nest;
734 if (str[i]=='[') ++nest;
735 if (str[i]=='<') ++nest;
736 if (str[i]=='{') ++nest;
737 if (str[i]==')') --nest;
738 if (str[i]==']') --nest;
739 if (str[i]=='>') --nest;
740 if (str[i]=='}') --nest;
743 imap_macro_replace(&str[i],
745 "FLAGS INTERNALDATE RFC822.SIZE ENVELOPE"
747 imap_macro_replace(&str[i],
751 imap_macro_replace(&str[i],
753 "FLAGS INTERNALDATE RFC822.SIZE"
755 imap_macro_replace(&str[i],
757 "FLAGS INTERNALDATE RFC822.SIZE ENVELOPE BODY"
765 * Break out the data items requested, possibly a parenthesized list.
766 * Returns the number of data items, or -1 if the list is invalid.
767 * NOTE: this function alters the string it is fed, and uses it as a buffer
768 * to hold the data for the pointers it returns.
770 int imap_extract_data_items(char **argv, char *items) {
776 /* Convert all whitespace to ordinary space characters. */
777 for (i=0; i<strlen(items); ++i) {
778 if (isspace(items[i])) items[i]=' ';
781 /* Strip leading and trailing whitespace, then strip leading and
782 * trailing parentheses if it's a list
785 if ( (items[0]=='(') && (items[strlen(items)-1]==')') ) {
786 items[strlen(items)-1] = 0;
787 strcpy(items, &items[1]);
791 /* Parse any macro data items */
792 imap_handle_macros(items);
795 * Now break out the data items. We throw in one trailing space in
796 * order to avoid having to break out the last one manually.
800 initial_len = strlen(items);
801 for (i=0; i<initial_len; ++i) {
802 if (items[i]=='(') ++nest;
803 if (items[i]=='[') ++nest;
804 if (items[i]=='<') ++nest;
805 if (items[i]=='{') ++nest;
806 if (items[i]==')') --nest;
807 if (items[i]==']') --nest;
808 if (items[i]=='>') --nest;
809 if (items[i]=='}') --nest;
811 if (nest <= 0) if (items[i]==' ') {
813 argv[num_items++] = start;
824 * One particularly hideous aspect of IMAP is that we have to allow the client
825 * to specify arbitrary ranges and/or sets of messages to fetch. Citadel IMAP
826 * handles this by setting the IMAP_SELECTED flag for each message specified in
827 * the ranges/sets, then looping through the message array, outputting messages
828 * with the flag set. We don't bother returning an error if an out-of-range
829 * number is specified (we just return quietly) because any client braindead
830 * enough to request a bogus message number isn't going to notice the
833 * This function clears out the IMAP_SELECTED bits, then sets that bit for each
834 * message included in the specified range.
836 * Set is_uid to 1 to fetch by UID instead of sequence number.
838 void imap_pick_range(char *supplied_range, int is_uid) {
842 char setstr[SIZ], lostr[SIZ], histr[SIZ]; /* was 1024 */
844 char actual_range[SIZ];
847 * Handle the "ALL" macro
849 if (!strcasecmp(supplied_range, "ALL")) {
850 safestrncpy(actual_range, "1:*", sizeof actual_range);
853 safestrncpy(actual_range, supplied_range, sizeof actual_range);
857 * Clear out the IMAP_SELECTED flags for all messages.
859 for (i = 0; i < IMAP->num_msgs; ++i) {
860 IMAP->flags[i] = IMAP->flags[i] & ~IMAP_SELECTED;
864 * Now set it for all specified messages.
866 num_sets = num_tokens(actual_range, ',');
867 for (s=0; s<num_sets; ++s) {
868 extract_token(setstr, actual_range, s, ',');
870 extract_token(lostr, setstr, 0, ':');
871 if (num_tokens(setstr, ':') >= 2) {
872 extract_token(histr, setstr, 1, ':');
873 if (!strcmp(histr, "*")) sprintf(histr, "%d", INT_MAX);
876 strcpy(histr, lostr);
881 /* Loop through the array, flipping bits where appropriate */
882 for (i = 1; i <= IMAP->num_msgs; ++i) {
883 if (is_uid) { /* fetch by sequence number */
884 if ( (IMAP->msgids[i-1]>=lo)
885 && (IMAP->msgids[i-1]<=hi)) {
887 IMAP->flags[i-1] | IMAP_SELECTED;
890 else { /* fetch by uid */
891 if ( (i>=lo) && (i<=hi)) {
893 IMAP->flags[i-1] | IMAP_SELECTED;
900 * Make sure we didn't select any expunged messages.
902 for (i = 0; i < IMAP->num_msgs; ++i) {
903 if (IMAP->flags[i] & IMAP_EXPUNGED) {
904 lprintf(9, "eliminating %d because expunged\n", i);
905 IMAP->flags[i] = IMAP->flags[i] & ~IMAP_SELECTED;
914 * This function is called by the main command loop.
916 void imap_fetch(int num_parms, char *parms[]) {
917 char items[SIZ]; /* was 1024 */
923 cprintf("%s BAD invalid parameters\r\n", parms[0]);
927 imap_pick_range(parms[2], 0);
930 for (i=3; i<num_parms; ++i) {
931 strcat(items, parms[i]);
932 if (i < (num_parms-1)) strcat(items, " ");
935 num_items = imap_extract_data_items(itemlist, items);
937 cprintf("%s BAD invalid data item list\r\n", parms[0]);
941 imap_do_fetch(num_items, itemlist);
942 cprintf("%s OK FETCH completed\r\n", parms[0]);
946 * This function is called by the main command loop.
948 void imap_uidfetch(int num_parms, char *parms[]) {
949 char items[SIZ]; /* was 1024 */
953 int have_uid_item = 0;
956 cprintf("%s BAD invalid parameters\r\n", parms[0]);
960 imap_pick_range(parms[3], 1);
963 for (i=4; i<num_parms; ++i) {
964 strcat(items, parms[i]);
965 if (i < (num_parms-1)) strcat(items, " ");
968 num_items = imap_extract_data_items(itemlist, items);
970 cprintf("%s BAD invalid data item list\r\n", parms[0]);
974 /* If the "UID" item was not included, we include it implicitly
975 * because this is a UID FETCH command
977 for (i=0; i<num_items; ++i) {
978 if (!strcasecmp(itemlist[i], "UID")) ++have_uid_item;
980 if (have_uid_item == 0) itemlist[num_items++] = "UID";
982 imap_do_fetch(num_items, itemlist);
983 cprintf("%s OK UID FETCH completed\r\n", parms[0]);