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[256];
53 * Individual field functions for imap_do_fetch_msg() ...
58 void imap_fetch_uid(int seq) {
59 cprintf("UID %ld", IMAP->msgids[seq-1]);
62 void imap_fetch_flags(struct CtdlMessage *msg) {
63 cprintf("FLAGS ()"); /* FIXME do something here */
66 void imap_fetch_internaldate(struct CtdlMessage *msg) {
70 if (msg->cm_fields['T'] != NULL) {
71 msgdate = atol(msg->cm_fields['T']);
77 datestring(buf, msgdate, DATESTRING_IMAP);
78 cprintf("INTERNALDATE \"%s\"", buf);
83 * Fetch RFC822-formatted messages.
85 * 'whichfmt' should be set to one of:
86 * "RFC822" entire message
87 * "RFC822.HEADER" headers only (with trailing blank line)
88 * "RFC822.SIZE" size of translated message
89 * "RFC822.TEXT" body only (without leading blank line)
91 void imap_fetch_rfc822(int msgnum, char *whichfmt, struct CtdlMessage *msg) {
95 long headers_size, text_size, total_size;
96 long bytes_remaining = 0;
101 lprintf(1, "Cannot open temp file: %s\n", strerror(errno));
106 * Load the message into a temp file for translation and measurement
108 CtdlRedirectOutput(tmp, -1);
109 CtdlOutputPreLoadedMsg(msg, msgnum, MT_RFC822, 0, 0, 1);
110 CtdlRedirectOutput(NULL, -1);
113 * Now figure out where the headers/text break is. IMAP considers the
114 * intervening blank line to be part of the headers, not the text.
119 ptr = fgets(buf, sizeof buf, tmp);
122 if (strlen(buf) == 0) headers_size = ftell(tmp);
124 } while ( (headers_size == 0L) && (ptr != NULL) );
125 fseek(tmp, 0L, SEEK_END);
126 total_size = ftell(tmp);
127 text_size = total_size - headers_size;
129 if (!strcasecmp(whichfmt, "RFC822.SIZE")) {
130 cprintf("RFC822.SIZE %ld", total_size);
135 else if (!strcasecmp(whichfmt, "RFC822")) {
136 bytes_remaining = total_size;
140 else if (!strcasecmp(whichfmt, "RFC822.HEADER")) {
141 bytes_remaining = headers_size;
145 else if (!strcasecmp(whichfmt, "RFC822.TEXT")) {
146 bytes_remaining = text_size;
147 fseek(tmp, headers_size, SEEK_SET);
150 cprintf("%s {%ld}\r\n", whichfmt, bytes_remaining);
151 blocksize = sizeof(buf);
152 while (bytes_remaining > 0L) {
153 if (blocksize > bytes_remaining) blocksize = bytes_remaining;
154 fread(buf, blocksize, 1, tmp);
155 client_write(buf, blocksize);
156 bytes_remaining = bytes_remaining - blocksize;
165 * Load a specific part of a message into the temp file to be output to a
166 * client. FIXME we can handle parts like "2" and "2.1" and even "2.MIME"
167 * but we still can't handle "2.HEADER" (which might not be a problem, because
168 * we currently don't have the ability to break out nested RFC822's anyway).
170 * Note: mime_parser() was called with dont_decode set to 1, so we have the
171 * luxury of simply spewing without having to re-encode.
173 void imap_load_part(char *name, char *filename, char *partnum, char *disp,
174 void *content, char *cbtype, size_t length, char *encoding,
177 struct imap_fetch_part *imfp;
180 imfp = (struct imap_fetch_part *)cbuserdata;
182 if (!strcasecmp(partnum, imfp->desired_section)) {
183 fwrite(content, length, 1, imfp->output_fp);
186 sprintf(mbuf2, "%s.MIME", partnum);
188 if (!strcasecmp(imfp->desired_section, mbuf2)) {
189 fprintf(imfp->output_fp, "Content-type: %s", cbtype);
190 if (strlen(name) > 0)
191 fprintf(imfp->output_fp, "; name=\"%s\"", name);
192 fprintf(imfp->output_fp, "\r\n");
193 if (strlen(encoding) > 0)
194 fprintf(imfp->output_fp,
195 "Content-Transfer-Encoding: %s\r\n", encoding);
196 if (strlen(encoding) > 0) {
197 fprintf(imfp->output_fp, "Content-Disposition: %s",
199 if (strlen(filename) > 0) {
200 fprintf(imfp->output_fp, "; filename=\"%s\"",
203 fprintf(imfp->output_fp, "\r\n");
205 fprintf(imfp->output_fp, "Content-Length: %d\r\n", length);
206 fprintf(imfp->output_fp, "\r\n");
214 * Called by imap_fetch_envelope() to output the "From" field.
215 * This is in its own function because its logic is kind of complex. We
216 * really need to make this suck less.
218 void imap_output_envelope_from(struct CtdlMessage *msg) {
219 char user[1024], node[1024], name[1024];
221 cprintf("(("); /* open double-parens */
222 imap_strout(msg->cm_fields['A']); /* personal name */
223 cprintf(" NIL "); /* source route (not used) */
225 if (msg->cm_fields['F'] != NULL) {
226 process_rfc822_addr(msg->cm_fields['F'], user, node, name);
227 imap_strout(user); /* mailbox name (user id) */
229 if (!strcasecmp(node, config.c_nodename)) {
230 imap_strout(config.c_fqdn);
233 imap_strout(node); /* host name */
237 imap_strout(msg->cm_fields['A']); /* mailbox name (user id) */
239 imap_strout(msg->cm_fields['N']); /* host name */
242 cprintf(")) "); /* close double-parens */
247 * Implements the ENVELOPE fetch item
249 * FIXME ... we only output some of the fields right now. Definitely need
250 * to do all of them. Accurately, too.
252 * Note that the imap_strout() function can cleverly output NULL fields as NIL,
253 * so we don't have to check for that condition like we do elsewhere.
255 void imap_fetch_envelope(long msgnum, struct CtdlMessage *msg) {
256 char datestringbuf[256];
258 char *fieldptr = NULL;
260 /* Parse the message date into an IMAP-format date string */
261 if (msg->cm_fields['T'] != NULL) {
262 msgdate = atol(msg->cm_fields['T']);
265 msgdate = time(NULL);
267 datestring(datestringbuf, msgdate, DATESTRING_IMAP);
269 /* Now start spewing data fields. The order is important, as it is
270 * defined by the protocol specification. Nonexistent fields must
271 * be output as NIL, existent fields must be quoted or literalled.
272 * The imap_strout() function conveniently does all this for us.
274 cprintf("ENVELOPE (");
277 imap_strout(datestringbuf);
281 imap_strout(msg->cm_fields['U']);
285 imap_output_envelope_from(msg);
289 /* FIXME ... check for a *real* Sender: field */
292 imap_output_envelope_from(msg);
297 /* FIXME ... check for a *real* Reply-to: field */
300 imap_output_envelope_from(msg);
303 cprintf("NIL "); /* to */
305 cprintf("NIL "); /* cc */
307 cprintf("NIL "); /* bcc */
310 fieldptr = rfc822_fetch_field(msg->cm_fields['M'], "In-reply-to");
311 imap_strout(fieldptr);
313 if (fieldptr != NULL) phree(fieldptr);
316 imap_strout(msg->cm_fields['I']);
323 * Strip any non header information out of a chunk of RFC822 data on disk
325 void imap_strip_headers(FILE *fp) {
329 while (fgets(buf, sizeof buf, fp) != NULL) {
331 if (strlen(buf) == 0) {
333 ftruncate(fileno(fp), ftell(fp));
337 fprintf(fp, "\r\n"); /* add the trailing newline */
343 * Implements the BODY and BODY.PEEK fetch items
345 void imap_fetch_body(long msgnum, char *item, int is_peek,
346 struct CtdlMessage *msg) {
353 long bytes_remaining = 0;
356 struct imap_fetch_part imfp;
358 /* extract section */
359 strcpy(section, item);
360 for (i=0; i<strlen(section); ++i) {
361 if (section[i]=='[') strcpy(section, §ion[i+1]);
363 for (i=0; i<strlen(section); ++i) {
364 if (section[i]==']') section[i] = 0;
366 lprintf(9, "Section is %s\n", section);
368 /* extract partial */
369 strcpy(partial, item);
370 for (i=0; i<strlen(partial); ++i) {
371 if (partial[i]=='<') {
372 strcpy(partial, &partial[i+1]);
376 for (i=0; i<strlen(partial); ++i) {
377 if (partial[i]=='>') partial[i] = 0;
379 if (is_partial == 0) strcpy(partial, "");
380 lprintf(9, "Partial is %s\n", partial);
384 lprintf(1, "Cannot open temp file: %s\n", strerror(errno));
388 /* Now figure out what the client wants, and get it */
390 if (!strcmp(section, "")) { /* the whole thing */
391 CtdlRedirectOutput(tmp, -1);
392 CtdlOutputPreLoadedMsg(msg, msgnum, MT_RFC822, 0, 0, 1);
393 CtdlRedirectOutput(NULL, -1);
397 * Be obnoxious and send the entire header, even if the client only
398 * asks for certain fields. FIXME this shortcut later.
400 else if (!strncasecmp(section, "HEADER", 6)) {
401 CtdlRedirectOutput(tmp, -1);
402 CtdlOutputPreLoadedMsg(msg, msgnum, MT_RFC822, 1, 0, 1);
403 CtdlRedirectOutput(NULL, -1);
404 imap_strip_headers(tmp);
408 * Anything else must be a part specifier.
409 * (Note value of 1 passed as 'dont_decode' so client gets it encoded)
412 safestrncpy(imfp.desired_section, section,
413 sizeof(imfp.desired_section));
414 imfp.output_fp = tmp;
416 mime_parser(msg->cm_fields['M'], NULL,
423 fseek(tmp, 0L, SEEK_END);
424 bytes_remaining = ftell(tmp);
426 if (is_partial == 0) {
428 cprintf("BODY[%s] {%ld}\r\n", section, bytes_remaining);
431 sscanf(partial, "%ld.%ld", &pstart, &pbytes);
432 if ((bytes_remaining - pstart) < pbytes) {
433 pbytes = bytes_remaining - pstart;
435 fseek(tmp, pstart, SEEK_SET);
436 bytes_remaining = pbytes;
437 cprintf("BODY[%s] {%ld}<%ld>\r\n",
438 section, bytes_remaining, pstart);
441 blocksize = sizeof(buf);
442 while (bytes_remaining > 0L) {
443 if (blocksize > bytes_remaining) blocksize = bytes_remaining;
444 fread(buf, blocksize, 1, tmp);
445 client_write(buf, blocksize);
446 bytes_remaining = bytes_remaining - blocksize;
452 /* FIXME set the last read pointer or something */
458 * Spew the BODYSTRUCTURE data for a message. (Do you need a silencer if
459 * you're going to shoot a MIME? Do you need a reason to shoot Mark Crispin?
462 * FIXME finish the implementation
464 void imap_fetch_bodystructure (long msgnum, char *item,
465 struct CtdlMessage *msg) {
472 /* For non-RFC822 (ordinary Citadel) messages, this is short and
475 if (msg->cm_format_type != FMT_RFC822) {
477 /* *sigh* We have to RFC822-format the message just to be able
481 if (tmp == NULL) return;
482 CtdlRedirectOutput(tmp, -1);
483 CtdlOutputPreLoadedMsg(msg, msgnum, MT_RFC822, 0, 0, 1);
484 CtdlRedirectOutput(NULL, -1);
487 while (fgets(buf, sizeof buf, tmp) != NULL) ++lines;
491 cprintf("BODYSTRUCTURE (\"TEXT\" \"PLAIN\" "
492 "(\"CHARSET\" \"US-ASCII\") NIL NIL "
493 "\"7BIT\" %ld %ld) ", bytes, lines);
498 /* For messages already stored in RFC822 format, we have to parse. */
510 * imap_do_fetch() calls imap_do_fetch_msg() to output the deta of an
511 * individual message, once it has been successfully loaded from disk.
513 void imap_do_fetch_msg(int seq, struct CtdlMessage *msg,
514 int num_items, char **itemlist) {
517 cprintf("* %d FETCH (", seq);
519 for (i=0; i<num_items; ++i) {
521 if (!strncasecmp(itemlist[i], "BODY[", 5)) {
522 imap_fetch_body(IMAP->msgids[seq-1], itemlist[i],
525 else if (!strncasecmp(itemlist[i], "BODY.PEEK[", 10)) {
526 imap_fetch_body(IMAP->msgids[seq-1], itemlist[i],
529 else if (!strcasecmp(itemlist[i], "BODYSTRUCTURE")) {
530 imap_fetch_bodystructure(IMAP->msgids[seq-1],
533 else if (!strcasecmp(itemlist[i], "ENVELOPE")) {
534 imap_fetch_envelope(IMAP->msgids[seq-1], msg);
536 else if (!strcasecmp(itemlist[i], "FLAGS")) {
537 imap_fetch_flags(msg);
539 else if (!strcasecmp(itemlist[i], "INTERNALDATE")) {
540 imap_fetch_internaldate(msg);
542 else if (!strcasecmp(itemlist[i], "RFC822")) {
543 imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i], msg);
545 else if (!strcasecmp(itemlist[i], "RFC822.HEADER")) {
546 imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i], msg);
548 else if (!strcasecmp(itemlist[i], "RFC822.SIZE")) {
549 imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i], msg);
551 else if (!strcasecmp(itemlist[i], "RFC822.TEXT")) {
552 imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i], msg);
554 else if (!strcasecmp(itemlist[i], "UID")) {
558 if (i != num_items-1) cprintf(" ");
567 * imap_fetch() calls imap_do_fetch() to do its actual work, once it's
568 * validated and boiled down the request a bit.
570 void imap_do_fetch(int num_items, char **itemlist) {
572 struct CtdlMessage *msg;
574 if (IMAP->num_msgs > 0)
575 for (i = 0; i < IMAP->num_msgs; ++i)
576 if (IMAP->flags[i] && IMAP_FETCHED) {
577 msg = CtdlFetchMessage(IMAP->msgids[i]);
579 imap_do_fetch_msg(i+1, msg, num_items, itemlist);
580 CtdlFreeMessage(msg);
583 cprintf("* %d FETCH <internal error>\r\n", i+1);
591 * Back end for imap_handle_macros()
592 * Note that this function *only* looks at the beginning of the string. It
593 * is not a generic search-and-replace function.
595 void imap_macro_replace(char *str, char *find, char *replace) {
598 if (!strncasecmp(str, find, strlen(find))) {
599 if (str[strlen(find)]==' ') {
600 strcpy(holdbuf, &str[strlen(find)+1]);
601 strcpy(str, replace);
603 strcat(str, holdbuf);
605 if (str[strlen(find)]==0) {
606 strcpy(holdbuf, &str[strlen(find)+1]);
607 strcpy(str, replace);
615 * Handle macros embedded in FETCH data items.
616 * (What the heck are macros doing in a wire protocol? Are we trying to save
617 * the computer at the other end the trouble of typing a lot of characters?)
619 void imap_handle_macros(char *str) {
623 for (i=0; i<strlen(str); ++i) {
624 if (str[i]=='(') ++nest;
625 if (str[i]=='[') ++nest;
626 if (str[i]=='<') ++nest;
627 if (str[i]=='{') ++nest;
628 if (str[i]==')') --nest;
629 if (str[i]==']') --nest;
630 if (str[i]=='>') --nest;
631 if (str[i]=='}') --nest;
634 imap_macro_replace(&str[i],
636 "FLAGS INTERNALDATE RFC822.SIZE ENVELOPE"
638 imap_macro_replace(&str[i],
642 imap_macro_replace(&str[i],
644 "FLAGS INTERNALDATE RFC822.SIZE"
646 imap_macro_replace(&str[i],
648 "FLAGS INTERNALDATE RFC822.SIZE ENVELOPE BODY"
656 * Break out the data items requested, possibly a parenthesized list.
657 * Returns the number of data items, or -1 if the list is invalid.
658 * NOTE: this function alters the string it is fed, and uses it as a buffer
659 * to hold the data for the pointers it returns.
661 int imap_extract_data_items(char **argv, char *items) {
667 /* Convert all whitespace to ordinary space characters. */
668 for (i=0; i<strlen(items); ++i) {
669 if (isspace(items[i])) items[i]=' ';
672 /* Strip leading and trailing whitespace, then strip leading and
673 * trailing parentheses if it's a list
676 if ( (items[0]=='(') && (items[strlen(items)-1]==')') ) {
677 items[strlen(items)-1] = 0;
678 strcpy(items, &items[1]);
682 /* Parse any macro data items */
683 imap_handle_macros(items);
686 * Now break out the data items. We throw in one trailing space in
687 * order to avoid having to break out the last one manually.
691 initial_len = strlen(items);
692 for (i=0; i<initial_len; ++i) {
693 if (items[i]=='(') ++nest;
694 if (items[i]=='[') ++nest;
695 if (items[i]=='<') ++nest;
696 if (items[i]=='{') ++nest;
697 if (items[i]==')') --nest;
698 if (items[i]==']') --nest;
699 if (items[i]=='>') --nest;
700 if (items[i]=='}') --nest;
702 if (nest <= 0) if (items[i]==' ') {
704 argv[num_items++] = start;
715 * One particularly hideous aspect of IMAP is that we have to allow the client
716 * to specify arbitrary ranges and/or sets of messages to fetch. Citadel IMAP
717 * handles this by setting the IMAP_FETCHED flag for each message specified in
718 * the ranges/sets, then looping through the message array, outputting messages
719 * with the flag set. We don't bother returning an error if an out-of-range
720 * number is specified (we just return quietly) because any client braindead
721 * enough to request a bogus message number isn't going to notice the
724 * This function clears out the IMAP_FETCHED bits, then sets that bit for each
725 * message included in the specified range.
727 * Set is_uid to 1 to fetch by UID instead of sequence number.
729 void imap_pick_range(char *range, int is_uid) {
733 char setstr[1024], lostr[1024], histr[1024];
737 * Clear out the IMAP_FETCHED flags for all messages.
739 for (i = 1; i <= IMAP->num_msgs; ++i) {
740 IMAP->flags[i-1] = IMAP->flags[i-1] & ~IMAP_FETCHED;
744 * Now set it for all specified messages.
746 num_sets = num_tokens(range, ',');
747 for (s=0; s<num_sets; ++s) {
748 extract_token(setstr, range, s, ',');
750 extract_token(lostr, setstr, 0, ':');
751 if (num_tokens(setstr, ':') >= 2) {
752 extract_token(histr, setstr, 1, ':');
753 if (!strcmp(histr, "*")) sprintf(histr, "%d", INT_MAX);
756 strcpy(histr, lostr);
761 /* Loop through the array, flipping bits where appropriate */
762 for (i = 1; i <= IMAP->num_msgs; ++i) {
763 if (is_uid) { /* fetch by sequence number */
764 if ( (IMAP->msgids[i-1]>=lo)
765 && (IMAP->msgids[i-1]<=hi)) {
767 IMAP->flags[i-1] | IMAP_FETCHED;
770 else { /* fetch by uid */
771 if ( (i>=lo) && (i<=hi)) {
773 IMAP->flags[i-1] | IMAP_FETCHED;
783 * This function is called by the main command loop.
785 void imap_fetch(int num_parms, char *parms[]) {
792 cprintf("%s BAD invalid parameters\r\n", parms[0]);
796 imap_pick_range(parms[2], 0);
799 for (i=3; i<num_parms; ++i) {
800 strcat(items, parms[i]);
801 if (i < (num_parms-1)) strcat(items, " ");
804 num_items = imap_extract_data_items(itemlist, items);
806 cprintf("%s BAD invalid data item list\r\n", parms[0]);
810 imap_do_fetch(num_items, itemlist);
811 cprintf("%s OK FETCH completed\r\n", parms[0]);
815 * This function is called by the main command loop.
817 void imap_uidfetch(int num_parms, char *parms[]) {
822 int have_uid_item = 0;
825 cprintf("%s BAD invalid parameters\r\n", parms[0]);
829 imap_pick_range(parms[3], 1);
832 for (i=4; i<num_parms; ++i) {
833 strcat(items, parms[i]);
834 if (i < (num_parms-1)) strcat(items, " ");
837 num_items = imap_extract_data_items(itemlist, items);
839 cprintf("%s BAD invalid data item list\r\n", parms[0]);
843 /* If the "UID" item was not included, we include it implicitly
844 * because this is a UID FETCH command
846 for (i=0; i<num_items; ++i) {
847 if (!strcasecmp(itemlist[i], "UID")) ++have_uid_item;
849 if (have_uid_item == 0) itemlist[num_items++] = "UID";
851 imap_do_fetch(num_items, itemlist);
852 cprintf("%s OK UID FETCH completed\r\n", parms[0]);