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) {
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 CtdlOutputMsg(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" but we still have
167 * to handle parts like "2.MIME" and "2.HEADER" (the latter maybe not ...
168 * Mark Crispy's server doesn't seem to)
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;
179 imfp = (struct imap_fetch_part *)cbuserdata;
181 if (!strcasecmp(partnum, imfp->desired_section)) {
182 fwrite(content, length, 1, imfp->output_fp);
192 * Implements the BODY and BODY.PEEK fetch items
194 void imap_fetch_body(long msgnum, char *item, int is_peek,
195 struct CtdlMessage *msg) {
202 long bytes_remaining = 0;
205 struct imap_fetch_part imfp;
207 /* extract section */
208 strcpy(section, item);
209 for (i=0; i<strlen(section); ++i) {
210 if (section[i]=='[') strcpy(section, §ion[i+1]);
212 for (i=0; i<strlen(section); ++i) {
213 if (section[i]==']') section[i] = 0;
215 lprintf(9, "Section is %s\n", section);
217 /* extract partial */
218 strcpy(partial, item);
219 for (i=0; i<strlen(partial); ++i) {
220 if (partial[i]=='<') {
221 strcpy(partial, &partial[i+1]);
225 for (i=0; i<strlen(partial); ++i) {
226 if (partial[i]=='>') partial[i] = 0;
228 lprintf(9, "Partial is %s\n", partial);
232 lprintf(1, "Cannot open temp file: %s\n", strerror(errno));
236 /* Now figure out what the client wants, and get it */
238 if (!strcmp(section, "")) { /* the whole thing */
239 CtdlRedirectOutput(tmp, -1);
240 CtdlOutputMsg(msgnum, MT_RFC822, 0, 0, 1);
241 CtdlRedirectOutput(NULL, -1);
245 * Be obnoxious and send the entire header, even if the client only
246 * asks for certain fields. FIXME this shortcut later.
248 else if (!strncasecmp(section, "HEADER", 6)) {
249 CtdlRedirectOutput(tmp, -1);
250 CtdlOutputMsg(msgnum, MT_RFC822, 1, 0, 1);
251 CtdlRedirectOutput(NULL, -1);
252 fprintf(tmp, "\r\n"); /* add the trailing newline */
256 * Anything else must be a part specifier.
257 * (Note value of 1 passed as 'dont_decode' so client gets it encoded)
260 safestrncpy(imfp.desired_section, section,
261 sizeof(imfp.desired_section));
262 imfp.output_fp = tmp;
264 mime_parser(msg->cm_fields['M'], NULL,
271 fseek(tmp, 0L, SEEK_END);
272 bytes_remaining = ftell(tmp);
274 if (is_partial == 0) {
276 cprintf("BODY[%s] {%ld}\r\n", section, bytes_remaining);
279 sscanf(partial, "%ld.%ld", &pstart, &pbytes);
280 if ((bytes_remaining - pstart) < pbytes) {
281 pbytes = bytes_remaining - pstart;
283 fseek(tmp, pstart, SEEK_SET);
284 bytes_remaining = pbytes;
285 cprintf("BODY[%s] {%ld}<%ld>\r\n",
286 section, bytes_remaining, pstart);
289 blocksize = sizeof(buf);
290 while (bytes_remaining > 0L) {
291 if (blocksize > bytes_remaining) blocksize = bytes_remaining;
292 fread(buf, blocksize, 1, tmp);
293 client_write(buf, blocksize);
294 bytes_remaining = bytes_remaining - blocksize;
300 /* FIXME set the last read pointer or something */
307 * imap_do_fetch() calls imap_do_fetch_msg() to output the deta of an
308 * individual message, once it has been successfully loaded from disk.
310 void imap_do_fetch_msg(int seq, struct CtdlMessage *msg,
311 int num_items, char **itemlist) {
314 cprintf("* %d FETCH (", seq);
316 for (i=0; i<num_items; ++i) {
318 if (!strncasecmp(itemlist[i], "BODY[", 5)) {
319 imap_fetch_body(IMAP->msgids[seq-1], itemlist[i], 0, msg);
321 else if (!strncasecmp(itemlist[i], "BODY.PEEK[", 10)) {
322 imap_fetch_body(IMAP->msgids[seq-1], itemlist[i], 1, msg);
324 else if (!strcasecmp(itemlist[i], "BODYSTRUCTURE")) {
325 /* FIXME do something here */
327 else if (!strcasecmp(itemlist[i], "ENVELOPE")) {
328 /* FIXME do something here */
330 else if (!strcasecmp(itemlist[i], "FLAGS")) {
331 imap_fetch_flags(msg);
333 else if (!strcasecmp(itemlist[i], "INTERNALDATE")) {
334 imap_fetch_internaldate(msg);
336 else if (!strcasecmp(itemlist[i], "RFC822")) {
337 imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i]);
339 else if (!strcasecmp(itemlist[i], "RFC822.HEADER")) {
340 imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i]);
342 else if (!strcasecmp(itemlist[i], "RFC822.SIZE")) {
343 imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i]);
345 else if (!strcasecmp(itemlist[i], "RFC822.TEXT")) {
346 imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i]);
348 else if (!strcasecmp(itemlist[i], "UID")) {
352 if (i != num_items-1) cprintf(" ");
361 * imap_fetch() calls imap_do_fetch() to do its actual work, once it's
362 * validated and boiled down the request a bit.
364 void imap_do_fetch(int num_items, char **itemlist) {
366 struct CtdlMessage *msg;
368 if (IMAP->num_msgs > 0)
369 for (i = 0; i < IMAP->num_msgs; ++i)
370 if (IMAP->flags[i] && IMAP_FETCHED) {
371 msg = CtdlFetchMessage(IMAP->msgids[i]);
373 imap_do_fetch_msg(i+1, msg, num_items, itemlist);
374 CtdlFreeMessage(msg);
377 cprintf("* %d FETCH <internal error>\r\n", i+1);
385 * Back end for imap_handle_macros()
386 * Note that this function *only* looks at the beginning of the string. It
387 * is not a generic search-and-replace function.
389 void imap_macro_replace(char *str, char *find, char *replace) {
392 if (!strncasecmp(str, find, strlen(find))) {
393 if (str[strlen(find)]==' ') {
394 strcpy(holdbuf, &str[strlen(find)+1]);
395 strcpy(str, replace);
397 strcat(str, holdbuf);
399 if (str[strlen(find)]==0) {
400 strcpy(holdbuf, &str[strlen(find)+1]);
401 strcpy(str, replace);
409 * Handle macros embedded in FETCH data items.
410 * (What the heck are macros doing in a wire protocol? Are we trying to save
411 * the computer at the other end the trouble of typing a lot of characters?)
413 void imap_handle_macros(char *str) {
417 for (i=0; i<strlen(str); ++i) {
418 if (str[i]=='(') ++nest;
419 if (str[i]=='[') ++nest;
420 if (str[i]=='<') ++nest;
421 if (str[i]=='{') ++nest;
422 if (str[i]==')') --nest;
423 if (str[i]==']') --nest;
424 if (str[i]=='>') --nest;
425 if (str[i]=='}') --nest;
428 imap_macro_replace(&str[i],
430 "FLAGS INTERNALDATE RFC822.SIZE ENVELOPE"
432 imap_macro_replace(&str[i],
436 imap_macro_replace(&str[i],
438 "FLAGS INTERNALDATE RFC822.SIZE"
440 imap_macro_replace(&str[i],
442 "FLAGS INTERNALDATE RFC822.SIZE ENVELOPE BODY"
450 * Break out the data items requested, possibly a parenthesized list.
451 * Returns the number of data items, or -1 if the list is invalid.
452 * NOTE: this function alters the string it is fed, and uses it as a buffer
453 * to hold the data for the pointers it returns.
455 int imap_extract_data_items(char **argv, char *items) {
461 /* Convert all whitespace to ordinary space characters. */
462 for (i=0; i<strlen(items); ++i) {
463 if (isspace(items[i])) items[i]=' ';
466 /* Strip leading and trailing whitespace, then strip leading and
467 * trailing parentheses if it's a list
470 if ( (items[0]=='(') && (items[strlen(items)-1]==')') ) {
471 items[strlen(items)-1] = 0;
472 strcpy(items, &items[1]);
476 /* Parse any macro data items */
477 imap_handle_macros(items);
480 * Now break out the data items. We throw in one trailing space in
481 * order to avoid having to break out the last one manually.
485 initial_len = strlen(items);
486 for (i=0; i<initial_len; ++i) {
487 if (items[i]=='(') ++nest;
488 if (items[i]=='[') ++nest;
489 if (items[i]=='<') ++nest;
490 if (items[i]=='{') ++nest;
491 if (items[i]==')') --nest;
492 if (items[i]==']') --nest;
493 if (items[i]=='>') --nest;
494 if (items[i]=='}') --nest;
496 if (nest <= 0) if (items[i]==' ') {
498 argv[num_items++] = start;
509 * One particularly hideous aspect of IMAP is that we have to allow the client
510 * to specify arbitrary ranges and/or sets of messages to fetch. Citadel IMAP
511 * handles this by setting the IMAP_FETCHED flag for each message specified in
512 * the ranges/sets, then looping through the message array, outputting messages
513 * with the flag set. We don't bother returning an error if an out-of-range
514 * number is specified (we just return quietly) because any client braindead
515 * enough to request a bogus message number isn't going to notice the
518 * This function clears out the IMAP_FETCHED bits, then sets that bit for each
519 * message included in the specified range.
521 * Set is_uid to 1 to fetch by UID instead of sequence number.
523 void imap_pick_range(char *range, int is_uid) {
527 char setstr[1024], lostr[1024], histr[1024];
531 * Clear out the IMAP_FETCHED flags for all messages.
533 for (i = 1; i <= IMAP->num_msgs; ++i) {
534 IMAP->flags[i-1] = IMAP->flags[i-1] & ~IMAP_FETCHED;
538 * Now set it for all specified messages.
540 num_sets = num_tokens(range, ',');
541 for (s=0; s<num_sets; ++s) {
542 extract_token(setstr, range, s, ',');
544 extract_token(lostr, setstr, 0, ':');
545 if (num_tokens(setstr, ':') >= 2) {
546 extract_token(histr, setstr, 1, ':');
547 if (!strcmp(histr, "*")) sprintf(histr, "%d", INT_MAX);
550 strcpy(histr, lostr);
555 /* Loop through the array, flipping bits where appropriate */
556 for (i = 1; i <= IMAP->num_msgs; ++i) {
557 if (is_uid) { /* fetch by sequence number */
558 if ( (IMAP->msgids[i-1]>=lo)
559 && (IMAP->msgids[i-1]<=hi)) {
561 IMAP->flags[i-1] | IMAP_FETCHED;
564 else { /* fetch by uid */
565 if ( (i>=lo) && (i<=hi)) {
567 IMAP->flags[i-1] | IMAP_FETCHED;
577 * This function is called by the main command loop.
579 void imap_fetch(int num_parms, char *parms[]) {
586 cprintf("%s BAD invalid parameters\r\n", parms[0]);
590 imap_pick_range(parms[2], 0);
593 for (i=3; i<num_parms; ++i) {
594 strcat(items, parms[i]);
595 if (i < (num_parms-1)) strcat(items, " ");
598 num_items = imap_extract_data_items(itemlist, items);
600 cprintf("%s BAD invalid data item list\r\n", parms[0]);
604 imap_do_fetch(num_items, itemlist);
605 cprintf("%s OK FETCH completed\r\n", parms[0]);
609 * This function is called by the main command loop.
611 void imap_uidfetch(int num_parms, char *parms[]) {
616 int have_uid_item = 0;
619 cprintf("%s BAD invalid parameters\r\n", parms[0]);
623 imap_pick_range(parms[3], 1);
626 for (i=4; i<num_parms; ++i) {
627 strcat(items, parms[i]);
628 if (i < (num_parms-1)) strcat(items, " ");
631 num_items = imap_extract_data_items(itemlist, items);
633 cprintf("%s BAD invalid data item list\r\n", parms[0]);
637 /* If the "UID" item was not included, we include it implicitly
638 * because this is a UID FETCH command
640 for (i=0; i<num_items; ++i) {
641 if (!strcasecmp(itemlist[i], "UID")) ++have_uid_item;
643 if (have_uid_item == 0) itemlist[num_items++] = "UID";
645 imap_do_fetch(num_items, itemlist);
646 cprintf("%s OK UID FETCH completed\r\n", parms[0]);