]> code.citadel.org Git - citadel.git/blob - citadel/imap_fetch.c
* Started working on part fetches
[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 /*
48  * Individual field functions for imap_do_fetch_msg() ...
49  */
50
51
52
53 void imap_fetch_uid(int seq) {
54         cprintf("UID %ld", IMAP->msgids[seq-1]);
55 }
56
57 void imap_fetch_flags(struct CtdlMessage *msg) {
58         cprintf("FLAGS ()");    /* FIXME do something here */
59 }
60
61 void imap_fetch_internaldate(struct CtdlMessage *msg) {
62         char buf[256];
63         time_t msgdate;
64
65         if (msg->cm_fields['T'] != NULL) {
66                 msgdate = atol(msg->cm_fields['T']);
67         }
68         else {
69                 msgdate = time(NULL);
70         }
71
72         datestring(buf, msgdate, DATESTRING_IMAP);
73         cprintf("INTERNALDATE \"%s\"", buf);
74 }
75
76
77 /*
78  * Fetch RFC822-formatted messages.
79  *
80  * 'whichfmt' should be set to one of:
81  *      "RFC822"        entire message
82  *      "RFC822.HEADER" headers only (with trailing blank line)
83  *      "RFC822.SIZE"   size of translated message
84  *      "RFC822.TEXT"   body only (without leading blank line)
85  */
86 void imap_fetch_rfc822(int msgnum, char *whichfmt) {
87         FILE *tmp;
88         char buf[1024];
89         char *ptr;
90         long headers_size, text_size, total_size;
91         long bytes_remaining = 0;
92         long blocksize;
93
94         tmp = tmpfile();
95         if (tmp == NULL) {
96                 lprintf(1, "Cannot open temp file: %s\n", strerror(errno));
97                 return;
98         }
99
100         /*
101          * Load the message into a temp file for translation and measurement
102          */ 
103         CtdlRedirectOutput(tmp, -1);
104         CtdlOutputMsg(msgnum, MT_RFC822, 0, 0, 1);
105         CtdlRedirectOutput(NULL, -1);
106
107         /*
108          * Now figure out where the headers/text break is.  IMAP considers the
109          * intervening blank line to be part of the headers, not the text.
110          */
111         rewind(tmp);
112         headers_size = 0L;
113         do {
114                 ptr = fgets(buf, sizeof buf, tmp);
115                 if (ptr != NULL) {
116                         striplt(buf);
117                         if (strlen(buf) == 0) headers_size = ftell(tmp);
118                 }
119         } while ( (headers_size == 0L) && (ptr != NULL) );
120         fseek(tmp, 0L, SEEK_END);
121         total_size = ftell(tmp);
122         text_size = total_size - headers_size;
123
124         if (!strcasecmp(whichfmt, "RFC822.SIZE")) {
125                 cprintf("RFC822.SIZE %ld", total_size);
126                 fclose(tmp);
127                 return;
128         }
129
130         else if (!strcasecmp(whichfmt, "RFC822")) {
131                 bytes_remaining = total_size;
132                 rewind(tmp);
133         }
134
135         else if (!strcasecmp(whichfmt, "RFC822.HEADER")) {
136                 bytes_remaining = headers_size;
137                 rewind(tmp);
138         }
139
140         else if (!strcasecmp(whichfmt, "RFC822.TEXT")) {
141                 bytes_remaining = text_size;
142                 fseek(tmp, headers_size, SEEK_SET);
143         }
144
145         cprintf("%s {%ld}\r\n", whichfmt, bytes_remaining);
146         blocksize = sizeof(buf);
147         while (bytes_remaining > 0L) {
148                 if (blocksize > bytes_remaining) blocksize = bytes_remaining;
149                 fread(buf, blocksize, 1, tmp);
150                 client_write(buf, blocksize);
151                 bytes_remaining = bytes_remaining - blocksize;
152         }
153
154         fclose(tmp);
155 }
156
157
158
159 /*
160  * FIXME this is TOTALLY BROKEN!!!
161  */
162 void imap_fetch_part(char *name, char *filename, char *partnum, char *disp,
163                     void *content, char *cbtype, size_t length)
164 {
165
166         if (!strcasecmp(partnum, IMAP->desired_part)) {
167                 cprintf("part=%s|%s|%s|%s|%s|%d\r\n",
168                         name, filename, partnum, disp, cbtype, length);
169         }
170 }
171
172
173
174
175
176 /*
177  * Implements the BODY and BODY.PEEK fetch items
178  */
179 void imap_fetch_body(long msgnum, char *item, int is_peek,
180                 struct CtdlMessage *msg) {
181         char section[1024];
182         char partial[1024];
183         int is_partial = 0;
184         char buf[1024];
185         int i;
186         FILE *tmp;
187         long bytes_remaining = 0;
188         long blocksize;
189         long pstart, pbytes;
190
191         /* extract section */
192         strcpy(section, item);
193         for (i=0; i<strlen(section); ++i) {
194                 if (section[i]=='[') strcpy(section, &section[i+1]);
195         }
196         for (i=0; i<strlen(section); ++i) {
197                 if (section[i]==']') section[i] = 0;
198         }
199         lprintf(9, "Section is %s\n", section);
200
201         /* extract partial */
202         strcpy(partial, item);
203         for (i=0; i<strlen(partial); ++i) {
204                 if (partial[i]=='<') {
205                         strcpy(partial, &partial[i+1]);
206                         is_partial = 1;
207                 }
208         }
209         for (i=0; i<strlen(partial); ++i) {
210                 if (partial[i]=='>') partial[i] = 0;
211         }
212         lprintf(9, "Partial is %s\n", partial);
213
214         tmp = tmpfile();
215         if (tmp == NULL) {
216                 lprintf(1, "Cannot open temp file: %s\n", strerror(errno));
217                 return;
218         }
219
220         /* Now figure out what the client wants, and get it */
221
222         if (!strcmp(section, "")) {             /* the whole thing */
223                 CtdlRedirectOutput(tmp, -1);
224                 CtdlOutputMsg(msgnum, MT_RFC822, 0, 0, 1);
225                 CtdlRedirectOutput(NULL, -1);
226         }
227
228         /*
229          * Be obnoxious and send the entire header, even if the client only
230          * asks for certain fields.  FIXME this shortcut later.
231          */
232         else if (!strncasecmp(section, "HEADER", 6)) {
233                 CtdlRedirectOutput(tmp, -1);
234                 CtdlOutputMsg(msgnum, MT_RFC822, 1, 0, 1);
235                 CtdlRedirectOutput(NULL, -1);
236                 fprintf(tmp, "\r\n");   /* add the trailing newline */
237         }
238
239         /*
240          * Anything else must be a part specifier.
241          */
242         else {
243                 safestrncpy(IMAP->desired_part, section,
244                                 sizeof(IMAP->desired_part));
245                 mime_parser(msg->cm_fields['M'], NULL, *imap_fetch_part);
246         }
247
248
249         fseek(tmp, 0L, SEEK_END);
250         bytes_remaining = ftell(tmp);
251
252         if (is_partial == 0) {
253                 rewind(tmp);
254                 cprintf("BODY[%s] {%ld}\r\n", section, bytes_remaining);
255         }
256         else {
257                 sscanf(partial, "%ld.%ld", &pstart, &pbytes);
258                 if ((bytes_remaining - pstart) < pbytes) {
259                         pbytes = bytes_remaining - pstart;
260                 }
261                 fseek(tmp, pstart, SEEK_SET);
262                 bytes_remaining = pbytes;
263                 cprintf("BODY[%s] {%ld}<%ld>\r\n",
264                         section, bytes_remaining, pstart);
265         }
266
267         blocksize = sizeof(buf);
268         while (bytes_remaining > 0L) {
269                 if (blocksize > bytes_remaining) blocksize = bytes_remaining;
270                 fread(buf, blocksize, 1, tmp);
271                 client_write(buf, blocksize);
272                 bytes_remaining = bytes_remaining - blocksize;
273         }
274
275         fclose(tmp);
276
277         if (is_peek) {
278                 /* FIXME set the last read pointer or something */
279         }
280 }
281
282
283
284 /*
285  * imap_do_fetch() calls imap_do_fetch_msg() to output the deta of an
286  * individual message, once it has been successfully loaded from disk.
287  */
288 void imap_do_fetch_msg(int seq, struct CtdlMessage *msg,
289                         int num_items, char **itemlist) {
290         int i;
291
292         cprintf("* %d FETCH (", seq);
293
294         for (i=0; i<num_items; ++i) {
295
296                 if (!strncasecmp(itemlist[i], "BODY[", 5)) {
297                         imap_fetch_body(IMAP->msgids[seq-1], itemlist[i], 0, msg);
298                 }
299                 else if (!strncasecmp(itemlist[i], "BODY.PEEK[", 10)) {
300                         imap_fetch_body(IMAP->msgids[seq-1], itemlist[i], 1, msg);
301                 }
302                 else if (!strcasecmp(itemlist[i], "BODYSTRUCTURE")) {
303                         /* FIXME do something here */
304                 }
305                 else if (!strcasecmp(itemlist[i], "ENVELOPE")) {
306                         /* FIXME do something here */
307                 }
308                 else if (!strcasecmp(itemlist[i], "FLAGS")) {
309                         imap_fetch_flags(msg);
310                 }
311                 else if (!strcasecmp(itemlist[i], "INTERNALDATE")) {
312                         imap_fetch_internaldate(msg);
313                 }
314                 else if (!strcasecmp(itemlist[i], "RFC822")) {
315                         imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i]);
316                 }
317                 else if (!strcasecmp(itemlist[i], "RFC822.HEADER")) {
318                         imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i]);
319                 }
320                 else if (!strcasecmp(itemlist[i], "RFC822.SIZE")) {
321                         imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i]);
322                 }
323                 else if (!strcasecmp(itemlist[i], "RFC822.TEXT")) {
324                         imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i]);
325                 }
326                 else if (!strcasecmp(itemlist[i], "UID")) {
327                         imap_fetch_uid(seq);
328                 }
329
330                 if (i != num_items-1) cprintf(" ");
331         }
332
333         cprintf(")\r\n");
334 }
335
336
337
338 /*
339  * imap_fetch() calls imap_do_fetch() to do its actual work, once it's
340  * validated and boiled down the request a bit.
341  */
342 void imap_do_fetch(int num_items, char **itemlist) {
343         int i;
344         struct CtdlMessage *msg;
345
346         if (IMAP->num_msgs > 0)
347          for (i = 0; i < IMAP->num_msgs; ++i)
348           if (IMAP->flags[i] && IMAP_FETCHED) {
349                 msg = CtdlFetchMessage(IMAP->msgids[i]);
350                 if (msg != NULL) {
351                         imap_do_fetch_msg(i+1, msg, num_items, itemlist);
352                         CtdlFreeMessage(msg);
353                 }
354                 else {
355                         cprintf("* %d FETCH <internal error>\r\n", i+1);
356                 }
357         }
358 }
359
360
361
362 /*
363  * Back end for imap_handle_macros()
364  * Note that this function *only* looks at the beginning of the string.  It
365  * is not a generic search-and-replace function.
366  */
367 void imap_macro_replace(char *str, char *find, char *replace) {
368         char holdbuf[1024];
369
370         if (!strncasecmp(str, find, strlen(find))) {
371                 if (str[strlen(find)]==' ') {
372                         strcpy(holdbuf, &str[strlen(find)+1]);
373                         strcpy(str, replace);
374                         strcat(str, " ");
375                         strcat(str, holdbuf);
376                 }
377                 if (str[strlen(find)]==0) {
378                         strcpy(holdbuf, &str[strlen(find)+1]);
379                         strcpy(str, replace);
380                 }
381         }
382 }
383
384
385
386 /*
387  * Handle macros embedded in FETCH data items.
388  * (What the heck are macros doing in a wire protocol?  Are we trying to save
389  * the computer at the other end the trouble of typing a lot of characters?)
390  */
391 void imap_handle_macros(char *str) {
392         int i;
393         int nest = 0;
394
395         for (i=0; i<strlen(str); ++i) {
396                 if (str[i]=='(') ++nest;
397                 if (str[i]=='[') ++nest;
398                 if (str[i]=='<') ++nest;
399                 if (str[i]=='{') ++nest;
400                 if (str[i]==')') --nest;
401                 if (str[i]==']') --nest;
402                 if (str[i]=='>') --nest;
403                 if (str[i]=='}') --nest;
404
405                 if (nest <= 0) {
406                         imap_macro_replace(&str[i],
407                                 "ALL",
408                                 "FLAGS INTERNALDATE RFC822.SIZE ENVELOPE"
409                         );
410                         imap_macro_replace(&str[i],
411                                 "BODY",
412                                 "BODYSTRUCTURE"
413                         );
414                         imap_macro_replace(&str[i],
415                                 "FAST",
416                                 "FLAGS INTERNALDATE RFC822.SIZE"
417                         );
418                         imap_macro_replace(&str[i],
419                                 "FULL",
420                                 "FLAGS INTERNALDATE RFC822.SIZE ENVELOPE BODY"
421                         );
422                 }
423         }
424 }
425
426
427 /*
428  * Break out the data items requested, possibly a parenthesized list.
429  * Returns the number of data items, or -1 if the list is invalid.
430  * NOTE: this function alters the string it is fed, and uses it as a buffer
431  * to hold the data for the pointers it returns.
432  */
433 int imap_extract_data_items(char **argv, char *items) {
434         int num_items = 0;
435         int nest = 0;
436         int i, initial_len;
437         char *start;
438
439         /* Convert all whitespace to ordinary space characters. */
440         for (i=0; i<strlen(items); ++i) {
441                 if (isspace(items[i])) items[i]=' ';
442         }
443
444         /* Strip leading and trailing whitespace, then strip leading and
445          * trailing parentheses if it's a list
446          */
447         striplt(items);
448         if ( (items[0]=='(') && (items[strlen(items)-1]==')') ) {
449                 items[strlen(items)-1] = 0;
450                 strcpy(items, &items[1]);
451                 striplt(items);
452         }
453
454         /* Parse any macro data items */
455         imap_handle_macros(items);
456
457         /*
458          * Now break out the data items.  We throw in one trailing space in
459          * order to avoid having to break out the last one manually.
460          */
461         strcat(items, " ");
462         start = items;
463         initial_len = strlen(items);
464         for (i=0; i<initial_len; ++i) {
465                 if (items[i]=='(') ++nest;
466                 if (items[i]=='[') ++nest;
467                 if (items[i]=='<') ++nest;
468                 if (items[i]=='{') ++nest;
469                 if (items[i]==')') --nest;
470                 if (items[i]==']') --nest;
471                 if (items[i]=='>') --nest;
472                 if (items[i]=='}') --nest;
473
474                 if (nest <= 0) if (items[i]==' ') {
475                         items[i] = 0;
476                         argv[num_items++] = start;
477                         start = &items[i+1];
478                 }
479         }
480
481         return(num_items);
482
483 }
484
485
486 /*
487  * One particularly hideous aspect of IMAP is that we have to allow the client
488  * to specify arbitrary ranges and/or sets of messages to fetch.  Citadel IMAP
489  * handles this by setting the IMAP_FETCHED flag for each message specified in
490  * the ranges/sets, then looping through the message array, outputting messages
491  * with the flag set.  We don't bother returning an error if an out-of-range
492  * number is specified (we just return quietly) because any client braindead
493  * enough to request a bogus message number isn't going to notice the
494  * difference anyway.
495  *
496  * This function clears out the IMAP_FETCHED bits, then sets that bit for each
497  * message included in the specified range.
498  *
499  * Set is_uid to 1 to fetch by UID instead of sequence number.
500  */
501 void imap_pick_range(char *range, int is_uid) {
502         int i;
503         int num_sets;
504         int s;
505         char setstr[1024], lostr[1024], histr[1024];
506         int lo, hi;
507
508         /*
509          * Clear out the IMAP_FETCHED flags for all messages.
510          */
511         for (i = 1; i <= IMAP->num_msgs; ++i) {
512                 IMAP->flags[i-1] = IMAP->flags[i-1] & ~IMAP_FETCHED;
513         }
514
515         /*
516          * Now set it for all specified messages.
517          */
518         num_sets = num_tokens(range, ',');
519         for (s=0; s<num_sets; ++s) {
520                 extract_token(setstr, range, s, ',');
521
522                 extract_token(lostr, setstr, 0, ':');
523                 if (num_tokens(setstr, ':') >= 2) {
524                         extract_token(histr, setstr, 1, ':');
525                         if (!strcmp(histr, "*")) sprintf(histr, "%d", INT_MAX);
526                 } 
527                 else {
528                         strcpy(histr, lostr);
529                 }
530                 lo = atoi(lostr);
531                 hi = atoi(histr);
532
533                 /* Loop through the array, flipping bits where appropriate */
534                 for (i = 1; i <= IMAP->num_msgs; ++i) {
535                         if (is_uid) {   /* fetch by sequence number */
536                                 if ( (IMAP->msgids[i-1]>=lo)
537                                    && (IMAP->msgids[i-1]<=hi)) {
538                                         IMAP->flags[i-1] =
539                                                 IMAP->flags[i-1] | IMAP_FETCHED;
540                                 }
541                         }
542                         else {          /* fetch by uid */
543                                 if ( (i>=lo) && (i<=hi)) {
544                                         IMAP->flags[i-1] =
545                                                 IMAP->flags[i-1] | IMAP_FETCHED;
546                                 }
547                         }
548                 }
549         }
550 }
551
552
553
554 /*
555  * This function is called by the main command loop.
556  */
557 void imap_fetch(int num_parms, char *parms[]) {
558         char items[1024];
559         char *itemlist[256];
560         int num_items;
561         int i;
562
563         if (num_parms < 4) {
564                 cprintf("%s BAD invalid parameters\r\n", parms[0]);
565                 return;
566         }
567
568         imap_pick_range(parms[2], 0);
569
570         strcpy(items, "");
571         for (i=3; i<num_parms; ++i) {
572                 strcat(items, parms[i]);
573                 if (i < (num_parms-1)) strcat(items, " ");
574         }
575
576         num_items = imap_extract_data_items(itemlist, items);
577         if (num_items < 1) {
578                 cprintf("%s BAD invalid data item list\r\n", parms[0]);
579                 return;
580         }
581
582         imap_do_fetch(num_items, itemlist);
583         cprintf("%s OK FETCH completed\r\n", parms[0]);
584 }
585
586 /*
587  * This function is called by the main command loop.
588  */
589 void imap_uidfetch(int num_parms, char *parms[]) {
590         char items[1024];
591         char *itemlist[256];
592         int num_items;
593         int i;
594         int have_uid_item = 0;
595
596         if (num_parms < 5) {
597                 cprintf("%s BAD invalid parameters\r\n", parms[0]);
598                 return;
599         }
600
601         imap_pick_range(parms[3], 1);
602
603         strcpy(items, "");
604         for (i=4; i<num_parms; ++i) {
605                 strcat(items, parms[i]);
606                 if (i < (num_parms-1)) strcat(items, " ");
607         }
608
609         num_items = imap_extract_data_items(itemlist, items);
610         if (num_items < 1) {
611                 cprintf("%s BAD invalid data item list\r\n", parms[0]);
612                 return;
613         }
614
615         /* If the "UID" item was not included, we include it implicitly
616          * because this is a UID FETCH command
617          */
618         for (i=0; i<num_items; ++i) {
619                 if (!strcasecmp(itemlist[i], "UID")) ++have_uid_item;
620         }
621         if (have_uid_item == 0) itemlist[num_items++] = "UID";
622
623         imap_do_fetch(num_items, itemlist);
624         cprintf("%s OK UID FETCH completed\r\n", parms[0]);
625 }
626
627