]> code.citadel.org Git - citadel.git/blob - citadel/imap_fetch.c
* fetch
[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         }
217
218
219         fseek(tmp, 0L, SEEK_END);
220         bytes_remaining = ftell(tmp);
221
222         if (is_partial == 0) {
223                 rewind(tmp);
224                 cprintf("BODY[%s] {%ld}\r\n", section, bytes_remaining);
225         }
226         else {
227                 sscanf(partial, "%ld.%ld", &pstart, &pbytes);
228                 if ((bytes_remaining - pstart) < pbytes) {
229                         pbytes = bytes_remaining - pstart;
230                 }
231                 fseek(tmp, pstart, SEEK_SET);
232                 bytes_remaining = pbytes;
233                 cprintf("BODY[%s] {%ld}<%ld>\r\n",
234                         section, bytes_remaining, pstart);
235         }
236
237         blocksize = sizeof(buf);
238         while (bytes_remaining > 0L) {
239                 if (blocksize > bytes_remaining) blocksize = bytes_remaining;
240                 fread(buf, blocksize, 1, tmp);
241                 client_write(buf, blocksize);
242                 bytes_remaining = bytes_remaining - blocksize;
243         }
244
245         fclose(tmp);
246
247         if (is_peek) {
248                 /* FIXME set the last read pointer or something */
249         }
250 }
251
252
253
254 /*
255  * imap_do_fetch() calls imap_do_fetch_msg() to output the deta of an
256  * individual message, once it has been successfully loaded from disk.
257  */
258 void imap_do_fetch_msg(int seq, struct CtdlMessage *msg,
259                         int num_items, char **itemlist) {
260         int i;
261
262         cprintf("* %d FETCH (", seq);
263
264         for (i=0; i<num_items; ++i) {
265
266                 if (!strncasecmp(itemlist[i], "BODY[", 5)) {
267                         imap_fetch_body(IMAP->msgids[seq-1], itemlist[i], 0);
268                 }
269                 else if (!strncasecmp(itemlist[i], "BODY.PEEK[", 10)) {
270                         imap_fetch_body(IMAP->msgids[seq-1], itemlist[i], 1);
271                 }
272                 else if (!strcasecmp(itemlist[i], "BODYSTRUCTURE")) {
273                         /* FIXME do something here */
274                 }
275                 else if (!strcasecmp(itemlist[i], "ENVELOPE")) {
276                         /* FIXME do something here */
277                 }
278                 else if (!strcasecmp(itemlist[i], "FLAGS")) {
279                         imap_fetch_flags(msg);
280                 }
281                 else if (!strcasecmp(itemlist[i], "INTERNALDATE")) {
282                         imap_fetch_internaldate(msg);
283                 }
284                 else if (!strcasecmp(itemlist[i], "RFC822")) {
285                         imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i]);
286                 }
287                 else if (!strcasecmp(itemlist[i], "RFC822.HEADER")) {
288                         imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i]);
289                 }
290                 else if (!strcasecmp(itemlist[i], "RFC822.SIZE")) {
291                         imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i]);
292                 }
293                 else if (!strcasecmp(itemlist[i], "RFC822.TEXT")) {
294                         imap_fetch_rfc822(IMAP->msgids[seq-1], itemlist[i]);
295                 }
296                 else if (!strcasecmp(itemlist[i], "UID")) {
297                         imap_fetch_uid(seq);
298                 }
299
300                 if (i != num_items-1) cprintf(" ");
301         }
302
303         cprintf(")\r\n");
304 }
305
306
307
308 /*
309  * imap_fetch() calls imap_do_fetch() to do its actual work, once it's
310  * validated and boiled down the request a bit.
311  */
312 void imap_do_fetch(int num_items, char **itemlist) {
313         int i;
314         struct CtdlMessage *msg;
315
316         if (IMAP->num_msgs > 0)
317          for (i = 0; i < IMAP->num_msgs; ++i)
318           if (IMAP->flags[i] && IMAP_FETCHED) {
319                 msg = CtdlFetchMessage(IMAP->msgids[i]);
320                 if (msg != NULL) {
321                         imap_do_fetch_msg(i+1, msg, num_items, itemlist);
322                         CtdlFreeMessage(msg);
323                 }
324                 else {
325                         cprintf("* %d FETCH <internal error>\r\n", i+1);
326                 }
327         }
328 }
329
330
331
332 /*
333  * Back end for imap_handle_macros()
334  * Note that this function *only* looks at the beginning of the string.  It
335  * is not a generic search-and-replace function.
336  */
337 void imap_macro_replace(char *str, char *find, char *replace) {
338         char holdbuf[1024];
339
340         if (!strncasecmp(str, find, strlen(find))) {
341                 if (str[strlen(find)]==' ') {
342                         strcpy(holdbuf, &str[strlen(find)+1]);
343                         strcpy(str, replace);
344                         strcat(str, " ");
345                         strcat(str, holdbuf);
346                 }
347                 if (str[strlen(find)]==0) {
348                         strcpy(holdbuf, &str[strlen(find)+1]);
349                         strcpy(str, replace);
350                 }
351         }
352 }
353
354
355
356 /*
357  * Handle macros embedded in FETCH data items.
358  * (What the heck are macros doing in a wire protocol?  Are we trying to save
359  * the computer at the other end the trouble of typing a lot of characters?)
360  */
361 void imap_handle_macros(char *str) {
362         int i;
363         int nest = 0;
364
365         for (i=0; i<strlen(str); ++i) {
366                 if (str[i]=='(') ++nest;
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
375                 if (nest <= 0) {
376                         imap_macro_replace(&str[i],
377                                 "ALL",
378                                 "FLAGS INTERNALDATE RFC822.SIZE ENVELOPE"
379                         );
380                         imap_macro_replace(&str[i],
381                                 "BODY",
382                                 "BODYSTRUCTURE"
383                         );
384                         imap_macro_replace(&str[i],
385                                 "FAST",
386                                 "FLAGS INTERNALDATE RFC822.SIZE"
387                         );
388                         imap_macro_replace(&str[i],
389                                 "FULL",
390                                 "FLAGS INTERNALDATE RFC822.SIZE ENVELOPE BODY"
391                         );
392                 }
393         }
394 }
395
396
397 /*
398  * Break out the data items requested, possibly a parenthesized list.
399  * Returns the number of data items, or -1 if the list is invalid.
400  * NOTE: this function alters the string it is fed, and uses it as a buffer
401  * to hold the data for the pointers it returns.
402  */
403 int imap_extract_data_items(char **argv, char *items) {
404         int num_items = 0;
405         int nest = 0;
406         int i, initial_len;
407         char *start;
408
409         /* Convert all whitespace to ordinary space characters. */
410         for (i=0; i<strlen(items); ++i) {
411                 if (isspace(items[i])) items[i]=' ';
412         }
413
414         /* Strip leading and trailing whitespace, then strip leading and
415          * trailing parentheses if it's a list
416          */
417         striplt(items);
418         if ( (items[0]=='(') && (items[strlen(items)-1]==')') ) {
419                 items[strlen(items)-1] = 0;
420                 strcpy(items, &items[1]);
421                 striplt(items);
422         }
423
424         /* Parse any macro data items */
425         imap_handle_macros(items);
426
427         /*
428          * Now break out the data items.  We throw in one trailing space in
429          * order to avoid having to break out the last one manually.
430          */
431         strcat(items, " ");
432         start = items;
433         initial_len = strlen(items);
434         for (i=0; i<initial_len; ++i) {
435                 if (items[i]=='(') ++nest;
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
444                 if (nest <= 0) if (items[i]==' ') {
445                         items[i] = 0;
446                         argv[num_items++] = start;
447                         start = &items[i+1];
448                 }
449         }
450
451         return(num_items);
452
453 }
454
455
456 /*
457  * One particularly hideous aspect of IMAP is that we have to allow the client
458  * to specify arbitrary ranges and/or sets of messages to fetch.  Citadel IMAP
459  * handles this by setting the IMAP_FETCHED flag for each message specified in
460  * the ranges/sets, then looping through the message array, outputting messages
461  * with the flag set.  We don't bother returning an error if an out-of-range
462  * number is specified (we just return quietly) because any client braindead
463  * enough to request a bogus message number isn't going to notice the
464  * difference anyway.
465  *
466  * This function clears out the IMAP_FETCHED bits, then sets that bit for each
467  * message included in the specified range.
468  *
469  * Set is_uid to 1 to fetch by UID instead of sequence number.
470  */
471 void imap_pick_range(char *range, int is_uid) {
472         int i;
473         int num_sets;
474         int s;
475         char setstr[1024], lostr[1024], histr[1024];
476         int lo, hi;
477
478         /*
479          * Clear out the IMAP_FETCHED flags for all messages.
480          */
481         for (i = 1; i <= IMAP->num_msgs; ++i) {
482                 IMAP->flags[i-1] = IMAP->flags[i-1] & ~IMAP_FETCHED;
483         }
484
485         /*
486          * Now set it for all specified messages.
487          */
488         num_sets = num_tokens(range, ',');
489         for (s=0; s<num_sets; ++s) {
490                 extract_token(setstr, range, s, ',');
491
492                 extract_token(lostr, setstr, 0, ':');
493                 if (num_tokens(setstr, ':') >= 2) {
494                         extract_token(histr, setstr, 1, ':');
495                         if (!strcmp(histr, "*")) sprintf(histr, "%d", INT_MAX);
496                 } 
497                 else {
498                         strcpy(histr, lostr);
499                 }
500                 lo = atoi(lostr);
501                 hi = atoi(histr);
502
503                 /* Loop through the array, flipping bits where appropriate */
504                 for (i = 1; i <= IMAP->num_msgs; ++i) {
505                         if (is_uid) {   /* fetch by sequence number */
506                                 if ( (IMAP->msgids[i-1]>=lo)
507                                    && (IMAP->msgids[i-1]<=hi)) {
508                                         IMAP->flags[i-1] =
509                                                 IMAP->flags[i-1] | IMAP_FETCHED;
510                                 }
511                         }
512                         else {          /* fetch by uid */
513                                 if ( (i>=lo) && (i<=hi)) {
514                                         IMAP->flags[i-1] =
515                                                 IMAP->flags[i-1] | IMAP_FETCHED;
516                                 }
517                         }
518                 }
519         }
520 }
521
522
523
524 /*
525  * This function is called by the main command loop.
526  */
527 void imap_fetch(int num_parms, char *parms[]) {
528         char items[1024];
529         char *itemlist[256];
530         int num_items;
531         int i;
532
533         if (num_parms < 4) {
534                 cprintf("%s BAD invalid parameters\r\n", parms[0]);
535                 return;
536         }
537
538         imap_pick_range(parms[2], 0);
539
540         strcpy(items, "");
541         for (i=3; i<num_parms; ++i) {
542                 strcat(items, parms[i]);
543                 if (i < (num_parms-1)) strcat(items, " ");
544         }
545
546         num_items = imap_extract_data_items(itemlist, items);
547         if (num_items < 1) {
548                 cprintf("%s BAD invalid data item list\r\n", parms[0]);
549                 return;
550         }
551
552         imap_do_fetch(num_items, itemlist);
553         cprintf("%s OK FETCH completed\r\n", parms[0]);
554 }
555
556 /*
557  * This function is called by the main command loop.
558  */
559 void imap_uidfetch(int num_parms, char *parms[]) {
560         char items[1024];
561         char *itemlist[256];
562         int num_items;
563         int i;
564         int have_uid_item = 0;
565
566         if (num_parms < 5) {
567                 cprintf("%s BAD invalid parameters\r\n", parms[0]);
568                 return;
569         }
570
571         imap_pick_range(parms[3], 1);
572
573         strcpy(items, "");
574         for (i=4; i<num_parms; ++i) {
575                 strcat(items, parms[i]);
576                 if (i < (num_parms-1)) strcat(items, " ");
577         }
578
579         num_items = imap_extract_data_items(itemlist, items);
580         if (num_items < 1) {
581                 cprintf("%s BAD invalid data item list\r\n", parms[0]);
582                 return;
583         }
584
585         /* If the "UID" item was not included, we include it implicitly
586          * because this is a UID FETCH command
587          */
588         for (i=0; i<num_items; ++i) {
589                 if (!strcasecmp(itemlist[i], "UID")) ++have_uid_item;
590         }
591         if (have_uid_item == 0) itemlist[num_items++] = "UID";
592
593         imap_do_fetch(num_items, itemlist);
594         cprintf("%s OK UID FETCH completed\r\n", parms[0]);
595 }
596
597