]> code.citadel.org Git - citadel.git/blob - citadel/imap_fetch.c
* Changed the mime_parser() API (again) to allow "don't decode" mode
[citadel.git] / citadel / imap_fetch.c
1 /*
2  * $Id$
3  *
4  * Implements the FETCH command in IMAP.
5  * This command is way too convoluted.  Marc Crispin is a fscking idiot.
6  *
7  */
8
9
10 #include "sysdep.h"
11 #include <stdlib.h>
12 #include <unistd.h>
13 #include <stdio.h>
14 #include <fcntl.h>
15 #include <signal.h>
16 #include <pwd.h>
17 #include <errno.h>
18 #include <sys/types.h>
19 #include <sys/time.h>
20 #include <sys/wait.h>
21 #include <ctype.h>
22 #include <string.h>
23 #include <limits.h>
24 #include "citadel.h"
25 #include "server.h"
26 #include <time.h>
27 #include "sysdep_decls.h"
28 #include "citserver.h"
29 #include "support.h"
30 #include "config.h"
31 #include "dynloader.h"
32 #include "room_ops.h"
33 #include "user_ops.h"
34 #include "policy.h"
35 #include "database.h"
36 #include "msgbase.h"
37 #include "tools.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"
43 #include "genstamp.h"
44
45
46
47 struct imap_fetch_part {
48         char desired_section[256];
49         FILE *output_fp;
50 };
51
52 /*
53  * Individual field functions for imap_do_fetch_msg() ...
54  */
55
56
57
58 void imap_fetch_uid(int seq) {
59         cprintf("UID %ld", IMAP->msgids[seq-1]);
60 }
61
62 void imap_fetch_flags(struct CtdlMessage *msg) {
63         cprintf("FLAGS ()");    /* FIXME do something here */
64 }
65
66 void imap_fetch_internaldate(struct CtdlMessage *msg) {
67         char buf[256];
68         time_t msgdate;
69
70         if (msg->cm_fields['T'] != NULL) {
71                 msgdate = atol(msg->cm_fields['T']);
72         }
73         else {
74                 msgdate = time(NULL);
75         }
76
77         datestring(buf, msgdate, DATESTRING_IMAP);
78         cprintf("INTERNALDATE \"%s\"", buf);
79 }
80
81
82 /*
83  * Fetch RFC822-formatted messages.
84  *
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)
90  */
91 void imap_fetch_rfc822(int msgnum, char *whichfmt) {
92         FILE *tmp;
93         char buf[1024];
94         char *ptr;
95         long headers_size, text_size, total_size;
96         long bytes_remaining = 0;
97         long blocksize;
98
99         tmp = tmpfile();
100         if (tmp == NULL) {
101                 lprintf(1, "Cannot open temp file: %s\n", strerror(errno));
102                 return;
103         }
104
105         /*
106          * Load the message into a temp file for translation and measurement
107          */ 
108         CtdlRedirectOutput(tmp, -1);
109         CtdlOutputMsg(msgnum, MT_RFC822, 0, 0, 1);
110         CtdlRedirectOutput(NULL, -1);
111
112         /*
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.
115          */
116         rewind(tmp);
117         headers_size = 0L;
118         do {
119                 ptr = fgets(buf, sizeof buf, tmp);
120                 if (ptr != NULL) {
121                         striplt(buf);
122                         if (strlen(buf) == 0) headers_size = ftell(tmp);
123                 }
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;
128
129         if (!strcasecmp(whichfmt, "RFC822.SIZE")) {
130                 cprintf("RFC822.SIZE %ld", total_size);
131                 fclose(tmp);
132                 return;
133         }
134
135         else if (!strcasecmp(whichfmt, "RFC822")) {
136                 bytes_remaining = total_size;
137                 rewind(tmp);
138         }
139
140         else if (!strcasecmp(whichfmt, "RFC822.HEADER")) {
141                 bytes_remaining = headers_size;
142                 rewind(tmp);
143         }
144
145         else if (!strcasecmp(whichfmt, "RFC822.TEXT")) {
146                 bytes_remaining = text_size;
147                 fseek(tmp, headers_size, SEEK_SET);
148         }
149
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;
157         }
158
159         fclose(tmp);
160 }
161
162
163
164 /*
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)
169  *
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.
172  */
173 void imap_load_part(char *name, char *filename, char *partnum, char *disp,
174                     void *content, char *cbtype, size_t length, char *encoding,
175                     void *cbuserdata)
176 {
177         struct imap_fetch_part *imfp;
178
179         imfp = (struct imap_fetch_part *)cbuserdata;
180
181         if (!strcasecmp(partnum, imfp->desired_section)) {
182                 fwrite(content, length, 1, imfp->output_fp);
183         }
184
185 }
186
187
188
189
190
191 /*
192  * Implements the BODY and BODY.PEEK fetch items
193  */
194 void imap_fetch_body(long msgnum, char *item, int is_peek,
195                 struct CtdlMessage *msg) {
196         char section[1024];
197         char partial[1024];
198         int is_partial = 0;
199         char buf[1024];
200         int i;
201         FILE *tmp;
202         long bytes_remaining = 0;
203         long blocksize;
204         long pstart, pbytes;
205         struct imap_fetch_part imfp;
206
207         /* extract section */
208         strcpy(section, item);
209         for (i=0; i<strlen(section); ++i) {
210                 if (section[i]=='[') strcpy(section, &section[i+1]);
211         }
212         for (i=0; i<strlen(section); ++i) {
213                 if (section[i]==']') section[i] = 0;
214         }
215         lprintf(9, "Section is %s\n", section);
216
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]);
222                         is_partial = 1;
223                 }
224         }
225         for (i=0; i<strlen(partial); ++i) {
226                 if (partial[i]=='>') partial[i] = 0;
227         }
228         lprintf(9, "Partial is %s\n", partial);
229
230         tmp = tmpfile();
231         if (tmp == NULL) {
232                 lprintf(1, "Cannot open temp file: %s\n", strerror(errno));
233                 return;
234         }
235
236         /* Now figure out what the client wants, and get it */
237
238         if (!strcmp(section, "")) {             /* the whole thing */
239                 CtdlRedirectOutput(tmp, -1);
240                 CtdlOutputMsg(msgnum, MT_RFC822, 0, 0, 1);
241                 CtdlRedirectOutput(NULL, -1);
242         }
243
244         /*
245          * Be obnoxious and send the entire header, even if the client only
246          * asks for certain fields.  FIXME this shortcut later.
247          */
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 */
253         }
254
255         /*
256          * Anything else must be a part specifier.
257          * (Note value of 1 passed as 'dont_decode' so client gets it encoded)
258          */
259         else {
260                 safestrncpy(imfp.desired_section, section,
261                                 sizeof(imfp.desired_section));
262                 imfp.output_fp = tmp;
263
264                 mime_parser(msg->cm_fields['M'], NULL,
265                                 *imap_load_part,
266                                 (void *)&imfp,
267                                 1);
268         }
269
270
271         fseek(tmp, 0L, SEEK_END);
272         bytes_remaining = ftell(tmp);
273
274         if (is_partial == 0) {
275                 rewind(tmp);
276                 cprintf("BODY[%s] {%ld}\r\n", section, bytes_remaining);
277         }
278         else {
279                 sscanf(partial, "%ld.%ld", &pstart, &pbytes);
280                 if ((bytes_remaining - pstart) < pbytes) {
281                         pbytes = bytes_remaining - pstart;
282                 }
283                 fseek(tmp, pstart, SEEK_SET);
284                 bytes_remaining = pbytes;
285                 cprintf("BODY[%s] {%ld}<%ld>\r\n",
286                         section, bytes_remaining, pstart);
287         }
288
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;
295         }
296
297         fclose(tmp);
298
299         if (is_peek) {
300                 /* FIXME set the last read pointer or something */
301         }
302 }
303
304
305
306 /*
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.
309  */
310 void imap_do_fetch_msg(int seq, struct CtdlMessage *msg,
311                         int num_items, char **itemlist) {
312         int i;
313
314         cprintf("* %d FETCH (", seq);
315
316         for (i=0; i<num_items; ++i) {
317
318                 if (!strncasecmp(itemlist[i], "BODY[", 5)) {
319                         imap_fetch_body(IMAP->msgids[seq-1], itemlist[i], 0, msg);
320                 }
321                 else if (!strncasecmp(itemlist[i], "BODY.PEEK[", 10)) {
322                         imap_fetch_body(IMAP->msgids[seq-1], itemlist[i], 1, msg);
323                 }
324                 else if (!strcasecmp(itemlist[i], "BODYSTRUCTURE")) {
325                         /* FIXME do something here */
326                 }
327                 else if (!strcasecmp(itemlist[i], "ENVELOPE")) {
328                         /* FIXME do something here */
329                 }
330                 else if (!strcasecmp(itemlist[i], "FLAGS")) {
331                         imap_fetch_flags(msg);
332                 }
333                 else if (!strcasecmp(itemlist[i], "INTERNALDATE")) {
334                         imap_fetch_internaldate(msg);
335                 }
336                 else if (!strcasecmp(itemlist[i], "RFC822")) {
337                         imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i]);
338                 }
339                 else if (!strcasecmp(itemlist[i], "RFC822.HEADER")) {
340                         imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i]);
341                 }
342                 else if (!strcasecmp(itemlist[i], "RFC822.SIZE")) {
343                         imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i]);
344                 }
345                 else if (!strcasecmp(itemlist[i], "RFC822.TEXT")) {
346                         imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i]);
347                 }
348                 else if (!strcasecmp(itemlist[i], "UID")) {
349                         imap_fetch_uid(seq);
350                 }
351
352                 if (i != num_items-1) cprintf(" ");
353         }
354
355         cprintf(")\r\n");
356 }
357
358
359
360 /*
361  * imap_fetch() calls imap_do_fetch() to do its actual work, once it's
362  * validated and boiled down the request a bit.
363  */
364 void imap_do_fetch(int num_items, char **itemlist) {
365         int i;
366         struct CtdlMessage *msg;
367
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]);
372                 if (msg != NULL) {
373                         imap_do_fetch_msg(i+1, msg, num_items, itemlist);
374                         CtdlFreeMessage(msg);
375                 }
376                 else {
377                         cprintf("* %d FETCH <internal error>\r\n", i+1);
378                 }
379         }
380 }
381
382
383
384 /*
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.
388  */
389 void imap_macro_replace(char *str, char *find, char *replace) {
390         char holdbuf[1024];
391
392         if (!strncasecmp(str, find, strlen(find))) {
393                 if (str[strlen(find)]==' ') {
394                         strcpy(holdbuf, &str[strlen(find)+1]);
395                         strcpy(str, replace);
396                         strcat(str, " ");
397                         strcat(str, holdbuf);
398                 }
399                 if (str[strlen(find)]==0) {
400                         strcpy(holdbuf, &str[strlen(find)+1]);
401                         strcpy(str, replace);
402                 }
403         }
404 }
405
406
407
408 /*
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?)
412  */
413 void imap_handle_macros(char *str) {
414         int i;
415         int nest = 0;
416
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;
426
427                 if (nest <= 0) {
428                         imap_macro_replace(&str[i],
429                                 "ALL",
430                                 "FLAGS INTERNALDATE RFC822.SIZE ENVELOPE"
431                         );
432                         imap_macro_replace(&str[i],
433                                 "BODY",
434                                 "BODYSTRUCTURE"
435                         );
436                         imap_macro_replace(&str[i],
437                                 "FAST",
438                                 "FLAGS INTERNALDATE RFC822.SIZE"
439                         );
440                         imap_macro_replace(&str[i],
441                                 "FULL",
442                                 "FLAGS INTERNALDATE RFC822.SIZE ENVELOPE BODY"
443                         );
444                 }
445         }
446 }
447
448
449 /*
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.
454  */
455 int imap_extract_data_items(char **argv, char *items) {
456         int num_items = 0;
457         int nest = 0;
458         int i, initial_len;
459         char *start;
460
461         /* Convert all whitespace to ordinary space characters. */
462         for (i=0; i<strlen(items); ++i) {
463                 if (isspace(items[i])) items[i]=' ';
464         }
465
466         /* Strip leading and trailing whitespace, then strip leading and
467          * trailing parentheses if it's a list
468          */
469         striplt(items);
470         if ( (items[0]=='(') && (items[strlen(items)-1]==')') ) {
471                 items[strlen(items)-1] = 0;
472                 strcpy(items, &items[1]);
473                 striplt(items);
474         }
475
476         /* Parse any macro data items */
477         imap_handle_macros(items);
478
479         /*
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.
482          */
483         strcat(items, " ");
484         start = items;
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;
495
496                 if (nest <= 0) if (items[i]==' ') {
497                         items[i] = 0;
498                         argv[num_items++] = start;
499                         start = &items[i+1];
500                 }
501         }
502
503         return(num_items);
504
505 }
506
507
508 /*
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
516  * difference anyway.
517  *
518  * This function clears out the IMAP_FETCHED bits, then sets that bit for each
519  * message included in the specified range.
520  *
521  * Set is_uid to 1 to fetch by UID instead of sequence number.
522  */
523 void imap_pick_range(char *range, int is_uid) {
524         int i;
525         int num_sets;
526         int s;
527         char setstr[1024], lostr[1024], histr[1024];
528         int lo, hi;
529
530         /*
531          * Clear out the IMAP_FETCHED flags for all messages.
532          */
533         for (i = 1; i <= IMAP->num_msgs; ++i) {
534                 IMAP->flags[i-1] = IMAP->flags[i-1] & ~IMAP_FETCHED;
535         }
536
537         /*
538          * Now set it for all specified messages.
539          */
540         num_sets = num_tokens(range, ',');
541         for (s=0; s<num_sets; ++s) {
542                 extract_token(setstr, range, s, ',');
543
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);
548                 } 
549                 else {
550                         strcpy(histr, lostr);
551                 }
552                 lo = atoi(lostr);
553                 hi = atoi(histr);
554
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)) {
560                                         IMAP->flags[i-1] =
561                                                 IMAP->flags[i-1] | IMAP_FETCHED;
562                                 }
563                         }
564                         else {          /* fetch by uid */
565                                 if ( (i>=lo) && (i<=hi)) {
566                                         IMAP->flags[i-1] =
567                                                 IMAP->flags[i-1] | IMAP_FETCHED;
568                                 }
569                         }
570                 }
571         }
572 }
573
574
575
576 /*
577  * This function is called by the main command loop.
578  */
579 void imap_fetch(int num_parms, char *parms[]) {
580         char items[1024];
581         char *itemlist[256];
582         int num_items;
583         int i;
584
585         if (num_parms < 4) {
586                 cprintf("%s BAD invalid parameters\r\n", parms[0]);
587                 return;
588         }
589
590         imap_pick_range(parms[2], 0);
591
592         strcpy(items, "");
593         for (i=3; i<num_parms; ++i) {
594                 strcat(items, parms[i]);
595                 if (i < (num_parms-1)) strcat(items, " ");
596         }
597
598         num_items = imap_extract_data_items(itemlist, items);
599         if (num_items < 1) {
600                 cprintf("%s BAD invalid data item list\r\n", parms[0]);
601                 return;
602         }
603
604         imap_do_fetch(num_items, itemlist);
605         cprintf("%s OK FETCH completed\r\n", parms[0]);
606 }
607
608 /*
609  * This function is called by the main command loop.
610  */
611 void imap_uidfetch(int num_parms, char *parms[]) {
612         char items[1024];
613         char *itemlist[256];
614         int num_items;
615         int i;
616         int have_uid_item = 0;
617
618         if (num_parms < 5) {
619                 cprintf("%s BAD invalid parameters\r\n", parms[0]);
620                 return;
621         }
622
623         imap_pick_range(parms[3], 1);
624
625         strcpy(items, "");
626         for (i=4; i<num_parms; ++i) {
627                 strcat(items, parms[i]);
628                 if (i < (num_parms-1)) strcat(items, " ");
629         }
630
631         num_items = imap_extract_data_items(itemlist, items);
632         if (num_items < 1) {
633                 cprintf("%s BAD invalid data item list\r\n", parms[0]);
634                 return;
635         }
636
637         /* If the "UID" item was not included, we include it implicitly
638          * because this is a UID FETCH command
639          */
640         for (i=0; i<num_items; ++i) {
641                 if (!strcasecmp(itemlist[i], "UID")) ++have_uid_item;
642         }
643         if (have_uid_item == 0) itemlist[num_items++] = "UID";
644
645         imap_do_fetch(num_items, itemlist);
646         cprintf("%s OK UID FETCH completed\r\n", parms[0]);
647 }
648
649