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