]> code.citadel.org Git - citadel.git/blob - citadel/imap_fetch.c
* tools.c: striplt() strips all whitespace, not just spaces
[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" 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).
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         char mbuf2[1024];
179
180         imfp = (struct imap_fetch_part *)cbuserdata;
181
182         if (!strcasecmp(partnum, imfp->desired_section)) {
183                 fwrite(content, length, 1, imfp->output_fp);
184         }
185
186         sprintf(mbuf2, "%s.MIME", partnum);
187
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",
198                                         disp);
199                         if (strlen(filename) > 0) {
200                                 fprintf(imfp->output_fp, "; filename=\"%s\"",
201                                         filename);
202                         }
203                         fprintf(imfp->output_fp, "\r\n");
204                 }
205                 fprintf(imfp->output_fp, "Content-Length: %d\r\n", length);
206                 fprintf(imfp->output_fp, "\r\n");
207         }
208                         
209
210 }
211
212
213 /*
214  * Implements the ENVELOPE fetch item
215  * 
216  * FIXME ... we have to actually do something useful here.
217  */
218 void imap_fetch_envelope(long msgnum, struct CtdlMessage *msg) {
219         cprintf("ENVELOPE (");
220         cprintf("NIL ");        /* date */
221         cprintf("NIL ");        /* subject */
222         cprintf("NIL ");        /* from */
223         cprintf("NIL ");        /* sender */
224         cprintf("NIL ");        /* reply-to */
225         cprintf("NIL ");        /* to */
226         cprintf("NIL ");        /* cc */
227         cprintf("NIL ");        /* bcc */
228         cprintf("NIL ");        /* in-reply-to */
229         cprintf("NIL");         /* message-id */
230         cprintf(")\r\n");
231 }
232
233
234 /*
235  * Strip any non header information out of a chunk of RFC822 data on disk
236  */
237 void imap_strip_headers(FILE *fp) {
238         char buf[1024];
239
240         rewind(fp);
241         while (fgets(buf, sizeof buf, fp) != NULL) {
242                 striplt(buf);
243                 if (strlen(buf) == 0) {
244                         ftruncate(fileno(fp), ftell(fp));
245                 }
246         }
247         fflush(fp);
248         fprintf(fp, "\r\n");    /* add the trailing newline */
249         rewind(fp);
250 }
251
252
253 /*
254  * Implements the BODY and BODY.PEEK fetch items
255  */
256 void imap_fetch_body(long msgnum, char *item, int is_peek,
257                 struct CtdlMessage *msg) {
258         char section[1024];
259         char partial[1024];
260         int is_partial = 0;
261         char buf[1024];
262         int i;
263         FILE *tmp;
264         long bytes_remaining = 0;
265         long blocksize;
266         long pstart, pbytes;
267         struct imap_fetch_part imfp;
268
269         /* extract section */
270         strcpy(section, item);
271         for (i=0; i<strlen(section); ++i) {
272                 if (section[i]=='[') strcpy(section, &section[i+1]);
273         }
274         for (i=0; i<strlen(section); ++i) {
275                 if (section[i]==']') section[i] = 0;
276         }
277         lprintf(9, "Section is %s\n", section);
278
279         /* extract partial */
280         strcpy(partial, item);
281         for (i=0; i<strlen(partial); ++i) {
282                 if (partial[i]=='<') {
283                         strcpy(partial, &partial[i+1]);
284                         is_partial = 1;
285                 }
286         }
287         for (i=0; i<strlen(partial); ++i) {
288                 if (partial[i]=='>') partial[i] = 0;
289         }
290         lprintf(9, "Partial is %s\n", partial);
291
292         tmp = tmpfile();
293         if (tmp == NULL) {
294                 lprintf(1, "Cannot open temp file: %s\n", strerror(errno));
295                 return;
296         }
297
298         /* Now figure out what the client wants, and get it */
299
300         if (!strcmp(section, "")) {             /* the whole thing */
301                 CtdlRedirectOutput(tmp, -1);
302                 CtdlOutputMsg(msgnum, MT_RFC822, 0, 0, 1);
303                 CtdlRedirectOutput(NULL, -1);
304         }
305
306         /*
307          * Be obnoxious and send the entire header, even if the client only
308          * asks for certain fields.  FIXME this shortcut later.
309          */
310         else if (!strncasecmp(section, "HEADER", 6)) {
311                 CtdlRedirectOutput(tmp, -1);
312                 CtdlOutputMsg(msgnum, MT_RFC822, 1, 0, 1);
313                 CtdlRedirectOutput(NULL, -1);
314                 imap_strip_headers(tmp);
315         }
316
317         /*
318          * Anything else must be a part specifier.
319          * (Note value of 1 passed as 'dont_decode' so client gets it encoded)
320          */
321         else {
322                 safestrncpy(imfp.desired_section, section,
323                                 sizeof(imfp.desired_section));
324                 imfp.output_fp = tmp;
325
326                 mime_parser(msg->cm_fields['M'], NULL,
327                                 *imap_load_part,
328                                 (void *)&imfp,
329                                 1);
330         }
331
332
333         fseek(tmp, 0L, SEEK_END);
334         bytes_remaining = ftell(tmp);
335
336         if (is_partial == 0) {
337                 rewind(tmp);
338                 cprintf("BODY[%s] {%ld}\r\n", section, bytes_remaining);
339         }
340         else {
341                 sscanf(partial, "%ld.%ld", &pstart, &pbytes);
342                 if ((bytes_remaining - pstart) < pbytes) {
343                         pbytes = bytes_remaining - pstart;
344                 }
345                 fseek(tmp, pstart, SEEK_SET);
346                 bytes_remaining = pbytes;
347                 cprintf("BODY[%s] {%ld}<%ld>\r\n",
348                         section, bytes_remaining, pstart);
349         }
350
351         blocksize = sizeof(buf);
352         while (bytes_remaining > 0L) {
353                 if (blocksize > bytes_remaining) blocksize = bytes_remaining;
354                 fread(buf, blocksize, 1, tmp);
355                 client_write(buf, blocksize);
356                 bytes_remaining = bytes_remaining - blocksize;
357         }
358
359         fclose(tmp);
360
361         if (is_peek) {
362                 /* FIXME set the last read pointer or something */
363         }
364 }
365
366
367
368 /*
369  * imap_do_fetch() calls imap_do_fetch_msg() to output the deta of an
370  * individual message, once it has been successfully loaded from disk.
371  */
372 void imap_do_fetch_msg(int seq, struct CtdlMessage *msg,
373                         int num_items, char **itemlist) {
374         int i;
375
376         cprintf("* %d FETCH (", seq);
377
378         for (i=0; i<num_items; ++i) {
379
380                 if (!strncasecmp(itemlist[i], "BODY[", 5)) {
381                         imap_fetch_body(IMAP->msgids[seq-1], itemlist[i],
382                                         0, msg);
383                 }
384                 else if (!strncasecmp(itemlist[i], "BODY.PEEK[", 10)) {
385                         imap_fetch_body(IMAP->msgids[seq-1], itemlist[i],
386                                         1, msg);
387                 }
388                 else if (!strcasecmp(itemlist[i], "BODYSTRUCTURE")) {
389                         /* FIXME do something here */
390                 }
391                 else if (!strcasecmp(itemlist[i], "ENVELOPE")) {
392                         imap_fetch_envelope(IMAP->msgids[seq-1], msg);
393                 }
394                 else if (!strcasecmp(itemlist[i], "FLAGS")) {
395                         imap_fetch_flags(msg);
396                 }
397                 else if (!strcasecmp(itemlist[i], "INTERNALDATE")) {
398                         imap_fetch_internaldate(msg);
399                 }
400                 else if (!strcasecmp(itemlist[i], "RFC822")) {
401                         imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i]);
402                 }
403                 else if (!strcasecmp(itemlist[i], "RFC822.HEADER")) {
404                         imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i]);
405                 }
406                 else if (!strcasecmp(itemlist[i], "RFC822.SIZE")) {
407                         imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i]);
408                 }
409                 else if (!strcasecmp(itemlist[i], "RFC822.TEXT")) {
410                         imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i]);
411                 }
412                 else if (!strcasecmp(itemlist[i], "UID")) {
413                         imap_fetch_uid(seq);
414                 }
415
416                 if (i != num_items-1) cprintf(" ");
417         }
418
419         cprintf(")\r\n");
420 }
421
422
423
424 /*
425  * imap_fetch() calls imap_do_fetch() to do its actual work, once it's
426  * validated and boiled down the request a bit.
427  */
428 void imap_do_fetch(int num_items, char **itemlist) {
429         int i;
430         struct CtdlMessage *msg;
431
432         if (IMAP->num_msgs > 0)
433          for (i = 0; i < IMAP->num_msgs; ++i)
434           if (IMAP->flags[i] && IMAP_FETCHED) {
435                 msg = CtdlFetchMessage(IMAP->msgids[i]);
436                 if (msg != NULL) {
437                         imap_do_fetch_msg(i+1, msg, num_items, itemlist);
438                         CtdlFreeMessage(msg);
439                 }
440                 else {
441                         cprintf("* %d FETCH <internal error>\r\n", i+1);
442                 }
443         }
444 }
445
446
447
448 /*
449  * Back end for imap_handle_macros()
450  * Note that this function *only* looks at the beginning of the string.  It
451  * is not a generic search-and-replace function.
452  */
453 void imap_macro_replace(char *str, char *find, char *replace) {
454         char holdbuf[1024];
455
456         if (!strncasecmp(str, find, strlen(find))) {
457                 if (str[strlen(find)]==' ') {
458                         strcpy(holdbuf, &str[strlen(find)+1]);
459                         strcpy(str, replace);
460                         strcat(str, " ");
461                         strcat(str, holdbuf);
462                 }
463                 if (str[strlen(find)]==0) {
464                         strcpy(holdbuf, &str[strlen(find)+1]);
465                         strcpy(str, replace);
466                 }
467         }
468 }
469
470
471
472 /*
473  * Handle macros embedded in FETCH data items.
474  * (What the heck are macros doing in a wire protocol?  Are we trying to save
475  * the computer at the other end the trouble of typing a lot of characters?)
476  */
477 void imap_handle_macros(char *str) {
478         int i;
479         int nest = 0;
480
481         for (i=0; i<strlen(str); ++i) {
482                 if (str[i]=='(') ++nest;
483                 if (str[i]=='[') ++nest;
484                 if (str[i]=='<') ++nest;
485                 if (str[i]=='{') ++nest;
486                 if (str[i]==')') --nest;
487                 if (str[i]==']') --nest;
488                 if (str[i]=='>') --nest;
489                 if (str[i]=='}') --nest;
490
491                 if (nest <= 0) {
492                         imap_macro_replace(&str[i],
493                                 "ALL",
494                                 "FLAGS INTERNALDATE RFC822.SIZE ENVELOPE"
495                         );
496                         imap_macro_replace(&str[i],
497                                 "BODY",
498                                 "BODYSTRUCTURE"
499                         );
500                         imap_macro_replace(&str[i],
501                                 "FAST",
502                                 "FLAGS INTERNALDATE RFC822.SIZE"
503                         );
504                         imap_macro_replace(&str[i],
505                                 "FULL",
506                                 "FLAGS INTERNALDATE RFC822.SIZE ENVELOPE BODY"
507                         );
508                 }
509         }
510 }
511
512
513 /*
514  * Break out the data items requested, possibly a parenthesized list.
515  * Returns the number of data items, or -1 if the list is invalid.
516  * NOTE: this function alters the string it is fed, and uses it as a buffer
517  * to hold the data for the pointers it returns.
518  */
519 int imap_extract_data_items(char **argv, char *items) {
520         int num_items = 0;
521         int nest = 0;
522         int i, initial_len;
523         char *start;
524
525         /* Convert all whitespace to ordinary space characters. */
526         for (i=0; i<strlen(items); ++i) {
527                 if (isspace(items[i])) items[i]=' ';
528         }
529
530         /* Strip leading and trailing whitespace, then strip leading and
531          * trailing parentheses if it's a list
532          */
533         striplt(items);
534         if ( (items[0]=='(') && (items[strlen(items)-1]==')') ) {
535                 items[strlen(items)-1] = 0;
536                 strcpy(items, &items[1]);
537                 striplt(items);
538         }
539
540         /* Parse any macro data items */
541         imap_handle_macros(items);
542
543         /*
544          * Now break out the data items.  We throw in one trailing space in
545          * order to avoid having to break out the last one manually.
546          */
547         strcat(items, " ");
548         start = items;
549         initial_len = strlen(items);
550         for (i=0; i<initial_len; ++i) {
551                 if (items[i]=='(') ++nest;
552                 if (items[i]=='[') ++nest;
553                 if (items[i]=='<') ++nest;
554                 if (items[i]=='{') ++nest;
555                 if (items[i]==')') --nest;
556                 if (items[i]==']') --nest;
557                 if (items[i]=='>') --nest;
558                 if (items[i]=='}') --nest;
559
560                 if (nest <= 0) if (items[i]==' ') {
561                         items[i] = 0;
562                         argv[num_items++] = start;
563                         start = &items[i+1];
564                 }
565         }
566
567         return(num_items);
568
569 }
570
571
572 /*
573  * One particularly hideous aspect of IMAP is that we have to allow the client
574  * to specify arbitrary ranges and/or sets of messages to fetch.  Citadel IMAP
575  * handles this by setting the IMAP_FETCHED flag for each message specified in
576  * the ranges/sets, then looping through the message array, outputting messages
577  * with the flag set.  We don't bother returning an error if an out-of-range
578  * number is specified (we just return quietly) because any client braindead
579  * enough to request a bogus message number isn't going to notice the
580  * difference anyway.
581  *
582  * This function clears out the IMAP_FETCHED bits, then sets that bit for each
583  * message included in the specified range.
584  *
585  * Set is_uid to 1 to fetch by UID instead of sequence number.
586  */
587 void imap_pick_range(char *range, int is_uid) {
588         int i;
589         int num_sets;
590         int s;
591         char setstr[1024], lostr[1024], histr[1024];
592         int lo, hi;
593
594         /*
595          * Clear out the IMAP_FETCHED flags for all messages.
596          */
597         for (i = 1; i <= IMAP->num_msgs; ++i) {
598                 IMAP->flags[i-1] = IMAP->flags[i-1] & ~IMAP_FETCHED;
599         }
600
601         /*
602          * Now set it for all specified messages.
603          */
604         num_sets = num_tokens(range, ',');
605         for (s=0; s<num_sets; ++s) {
606                 extract_token(setstr, range, s, ',');
607
608                 extract_token(lostr, setstr, 0, ':');
609                 if (num_tokens(setstr, ':') >= 2) {
610                         extract_token(histr, setstr, 1, ':');
611                         if (!strcmp(histr, "*")) sprintf(histr, "%d", INT_MAX);
612                 } 
613                 else {
614                         strcpy(histr, lostr);
615                 }
616                 lo = atoi(lostr);
617                 hi = atoi(histr);
618
619                 /* Loop through the array, flipping bits where appropriate */
620                 for (i = 1; i <= IMAP->num_msgs; ++i) {
621                         if (is_uid) {   /* fetch by sequence number */
622                                 if ( (IMAP->msgids[i-1]>=lo)
623                                    && (IMAP->msgids[i-1]<=hi)) {
624                                         IMAP->flags[i-1] =
625                                                 IMAP->flags[i-1] | IMAP_FETCHED;
626                                 }
627                         }
628                         else {          /* fetch by uid */
629                                 if ( (i>=lo) && (i<=hi)) {
630                                         IMAP->flags[i-1] =
631                                                 IMAP->flags[i-1] | IMAP_FETCHED;
632                                 }
633                         }
634                 }
635         }
636 }
637
638
639
640 /*
641  * This function is called by the main command loop.
642  */
643 void imap_fetch(int num_parms, char *parms[]) {
644         char items[1024];
645         char *itemlist[256];
646         int num_items;
647         int i;
648
649         if (num_parms < 4) {
650                 cprintf("%s BAD invalid parameters\r\n", parms[0]);
651                 return;
652         }
653
654         imap_pick_range(parms[2], 0);
655
656         strcpy(items, "");
657         for (i=3; i<num_parms; ++i) {
658                 strcat(items, parms[i]);
659                 if (i < (num_parms-1)) strcat(items, " ");
660         }
661
662         num_items = imap_extract_data_items(itemlist, items);
663         if (num_items < 1) {
664                 cprintf("%s BAD invalid data item list\r\n", parms[0]);
665                 return;
666         }
667
668         imap_do_fetch(num_items, itemlist);
669         cprintf("%s OK FETCH completed\r\n", parms[0]);
670 }
671
672 /*
673  * This function is called by the main command loop.
674  */
675 void imap_uidfetch(int num_parms, char *parms[]) {
676         char items[1024];
677         char *itemlist[256];
678         int num_items;
679         int i;
680         int have_uid_item = 0;
681
682         if (num_parms < 5) {
683                 cprintf("%s BAD invalid parameters\r\n", parms[0]);
684                 return;
685         }
686
687         imap_pick_range(parms[3], 1);
688
689         strcpy(items, "");
690         for (i=4; i<num_parms; ++i) {
691                 strcat(items, parms[i]);
692                 if (i < (num_parms-1)) strcat(items, " ");
693         }
694
695         num_items = imap_extract_data_items(itemlist, items);
696         if (num_items < 1) {
697                 cprintf("%s BAD invalid data item list\r\n", parms[0]);
698                 return;
699         }
700
701         /* If the "UID" item was not included, we include it implicitly
702          * because this is a UID FETCH command
703          */
704         for (i=0; i<num_items; ++i) {
705                 if (!strcasecmp(itemlist[i], "UID")) ++have_uid_item;
706         }
707         if (have_uid_item == 0) itemlist[num_items++] = "UID";
708
709         imap_do_fetch(num_items, itemlist);
710         cprintf("%s OK UID FETCH completed\r\n", parms[0]);
711 }
712
713