* fix imap uid fetching:
[citadel.git] / citadel / modules / imap / imap_fetch.c
1 /*
2  * $Id$
3  *
4  * Implements the FETCH command in IMAP.
5  * This is a good example of the protocol's gratuitous complexity.
6  *
7  * Copyright (c) 2001-2009 by the citadel.org team
8  *
9  *  This program is free software; you can redistribute it and/or modify
10  *  it under the terms of the GNU General Public License as published by
11  *  the Free Software Foundation; either version 3 of the License, or
12  *  (at your option) any later version.
13  *
14  *  This program is distributed in the hope that it will be useful,
15  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  *  GNU General Public License for more details.
18  *
19  *  You should have received a copy of the GNU General Public License
20  *  along with this program; if not, write to the Free Software
21  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  */
23
24
25 #include "sysdep.h"
26 #include <stdlib.h>
27 #include <unistd.h>
28 #include <stdio.h>
29 #include <fcntl.h>
30 #include <signal.h>
31 #include <pwd.h>
32 #include <errno.h>
33 #include <sys/types.h>
34
35 #if TIME_WITH_SYS_TIME
36 # include <sys/time.h>
37 # include <time.h>
38 #else
39 # if HAVE_SYS_TIME_H
40 #  include <sys/time.h>
41 # else
42 #  include <time.h>
43 # endif
44 #endif
45
46 #include <sys/wait.h>
47 #include <ctype.h>
48 #include <string.h>
49 #include <limits.h>
50 #include <libcitadel.h>
51 #include "citadel.h"
52 #include "server.h"
53 #include "sysdep_decls.h"
54 #include "citserver.h"
55 #include "support.h"
56 #include "config.h"
57 #include "user_ops.h"
58 #include "policy.h"
59 #include "database.h"
60 #include "msgbase.h"
61 #include "internet_addressing.h"
62 #include "imap_tools.h"
63 #include "serv_imap.h"
64 #include "imap_fetch.h"
65 #include "genstamp.h"
66 #include "ctdl_module.h"
67
68
69
70 /*
71  * Individual field functions for imap_do_fetch_msg() ...
72  */
73
74 void imap_fetch_uid(int seq) {
75         cprintf("UID %ld", IMAP->msgids[seq-1]);
76 }
77
78 void imap_fetch_flags(int seq) {
79         int num_flags_printed = 0;
80         cprintf("FLAGS (");
81         if (IMAP->flags[seq] & IMAP_DELETED) {
82                 if (num_flags_printed > 0) cprintf(" ");
83                 cprintf("\\Deleted");
84                 ++num_flags_printed;
85         }
86         if (IMAP->flags[seq] & IMAP_SEEN) {
87                 if (num_flags_printed > 0) cprintf(" ");
88                 cprintf("\\Seen");
89                 ++num_flags_printed;
90         }
91         if (IMAP->flags[seq] & IMAP_ANSWERED) {
92                 if (num_flags_printed > 0) cprintf(" ");
93                 cprintf("\\Answered");
94                 ++num_flags_printed;
95         }
96         if (IMAP->flags[seq] & IMAP_RECENT) {
97                 if (num_flags_printed > 0) cprintf(" ");
98                 cprintf("\\Recent");
99                 ++num_flags_printed;
100         }
101         cprintf(")");
102 }
103
104
105 void imap_fetch_internaldate(struct CtdlMessage *msg) {
106         char buf[SIZ];
107         time_t msgdate;
108
109         if (!msg) return;
110         if (msg->cm_fields['T'] != NULL) {
111                 msgdate = atol(msg->cm_fields['T']);
112         }
113         else {
114                 msgdate = time(NULL);
115         }
116
117         datestring(buf, sizeof buf, msgdate, DATESTRING_IMAP);
118         cprintf("INTERNALDATE \"%s\"", buf);
119 }
120
121
122 /*
123  * Fetch RFC822-formatted messages.
124  *
125  * 'whichfmt' should be set to one of:
126  *      "RFC822"        entire message
127  *      "RFC822.HEADER" headers only (with trailing blank line)
128  *      "RFC822.SIZE"   size of translated message
129  *      "RFC822.TEXT"   body only (without leading blank line)
130  */
131 void imap_fetch_rfc822(long msgnum, const char *whichfmt) {
132         char buf[SIZ];
133         const char *ptr = NULL;
134         size_t headers_size, text_size, total_size;
135         size_t bytes_to_send = 0;
136         struct MetaData smi;
137         int need_to_rewrite_metadata = 0;
138         int need_body = 0;
139
140         /* Determine whether this particular fetch operation requires
141          * us to fetch the message body from disk.  If not, we can save
142          * on some disk operations...
143          */
144         if ( (!strcasecmp(whichfmt, "RFC822"))
145            || (!strcasecmp(whichfmt, "RFC822.TEXT")) ) {
146                 need_body = 1;
147         }
148
149         /* If this is an RFC822.SIZE fetch, first look in the message's
150          * metadata record to see if we've saved that information.
151          */
152         if (!strcasecmp(whichfmt, "RFC822.SIZE")) {
153                 GetMetaData(&smi, msgnum);
154                 if (smi.meta_rfc822_length > 0L) {
155                         cprintf("RFC822.SIZE %ld", smi.meta_rfc822_length);
156                         return;
157                 }
158                 need_to_rewrite_metadata = 1;
159                 need_body = 1;
160         }
161         
162         /* Cache the most recent RFC822 FETCH because some clients like to
163          * fetch in pieces, and we don't want to have to go back to the
164          * message store for each piece.  We also burn the cache if the
165          * client requests something that involves reading the message
166          * body, but we haven't fetched the body yet.
167          */
168         if ((IMAP->cached_rfc822_data != NULL)
169            && (IMAP->cached_rfc822_msgnum == msgnum)
170            && (IMAP->cached_rfc822_withbody || (!need_body)) ) {
171                 /* Good to go! */
172         }
173         else if (IMAP->cached_rfc822_data != NULL) {
174                 /* Some other message is cached -- free it */
175                 free(IMAP->cached_rfc822_data);
176                 IMAP->cached_rfc822_data = NULL;
177                 IMAP->cached_rfc822_msgnum = (-1);
178                 IMAP->cached_rfc822_len = 0;
179         }
180
181         /* At this point, we now can fetch and convert the message iff it's not
182          * the one we had cached.
183          */
184         if (IMAP->cached_rfc822_data == NULL) {
185                 /*
186                  * Load the message into memory for translation & measurement
187                  */
188                 CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
189                 CtdlOutputMsg(msgnum, MT_RFC822,
190                         (need_body ? HEADERS_ALL : HEADERS_FAST),
191                         0, 1, NULL, SUPPRESS_ENV_TO
192                 );
193                 if (!need_body) cprintf("\r\n");        /* extra trailing newline */
194                 IMAP->cached_rfc822_len = StrLength(CC->redirect_buffer);
195                 IMAP->cached_rfc822_data = SmashStrBuf(&CC->redirect_buffer);
196                 IMAP->cached_rfc822_msgnum = msgnum;
197                 IMAP->cached_rfc822_withbody = need_body;
198                 if ( (need_to_rewrite_metadata) && (IMAP->cached_rfc822_len > 0) ) {
199                         smi.meta_rfc822_length = (long)IMAP->cached_rfc822_len;
200                         PutMetaData(&smi);
201                 }
202         }
203
204         /*
205          * Now figure out where the headers/text break is.  IMAP considers the
206          * intervening blank line to be part of the headers, not the text.
207          */
208         headers_size = 0;
209         text_size = 0;
210         total_size = 0;
211
212         if (need_body) {
213                 ptr = IMAP->cached_rfc822_data;
214                 do {
215                         ptr = memreadline(ptr, buf, sizeof buf);
216                         if (*ptr != 0) {
217                                 striplt(buf);
218                                 if (IsEmptyStr(buf)) {
219                                         headers_size = ptr - IMAP->cached_rfc822_data;
220                                 }
221                         }
222                 } while ( (headers_size == 0) && (*ptr != 0) );
223
224                 total_size = IMAP->cached_rfc822_len;
225                 text_size = total_size - headers_size;
226         }
227         else {
228                 headers_size = IMAP->cached_rfc822_len;
229                 total_size = IMAP->cached_rfc822_len;
230                 text_size = 0;
231         }
232
233         CtdlLogPrintf(CTDL_DEBUG, 
234                 "RFC822: headers=" SIZE_T_FMT 
235                 ", text=" SIZE_T_FMT
236                 ", total=" SIZE_T_FMT "\n",
237                 headers_size, text_size, total_size);
238
239         if (!strcasecmp(whichfmt, "RFC822.SIZE")) {
240                 cprintf("RFC822.SIZE " SIZE_T_FMT, total_size);
241                 return;
242         }
243
244         else if (!strcasecmp(whichfmt, "RFC822")) {
245                 ptr = IMAP->cached_rfc822_data;
246                 bytes_to_send = total_size;
247         }
248
249         else if (!strcasecmp(whichfmt, "RFC822.HEADER")) {
250                 ptr = IMAP->cached_rfc822_data;
251                 bytes_to_send = headers_size;
252         }
253
254         else if (!strcasecmp(whichfmt, "RFC822.TEXT")) {
255                 ptr = &IMAP->cached_rfc822_data[headers_size];
256                 bytes_to_send = text_size;
257         }
258
259         cprintf("%s {" SIZE_T_FMT "}\r\n", whichfmt, bytes_to_send);
260         client_write(ptr, bytes_to_send);
261 }
262
263
264
265 /*
266  * Load a specific part of a message into the temp file to be output to a
267  * client.  FIXME we can handle parts like "2" and "2.1" and even "2.MIME"
268  * but we still can't handle "2.HEADER" (which might not be a problem).
269  *
270  * Note: mime_parser() was called with dont_decode set to 1, so we have the
271  * luxury of simply spewing without having to re-encode.
272  */
273 void imap_load_part(char *name, char *filename, char *partnum, char *disp,
274                     void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
275                     char *cbid, void *cbuserdata)
276 {
277         char mbuf2[SIZ];
278         char *desired_section;
279
280         desired_section = (char *)cbuserdata;
281
282         if (!strcasecmp(partnum, desired_section)) {
283                 client_write(content, length);
284         }
285
286         snprintf(mbuf2, sizeof mbuf2, "%s.MIME", partnum);
287
288         if (!strcasecmp(desired_section, mbuf2)) {
289                 cprintf("Content-type: %s", cbtype);
290                 if (!IsEmptyStr(cbcharset))
291                         cprintf("; charset=\"%s\"", cbcharset);
292                 if (!IsEmptyStr(name))
293                         cprintf("; name=\"%s\"", name);
294                 cprintf("\r\n");
295                 if (!IsEmptyStr(encoding))
296                         cprintf("Content-Transfer-Encoding: %s\r\n", encoding);
297                 if (!IsEmptyStr(encoding)) {
298                         cprintf("Content-Disposition: %s", disp);
299                         if (!IsEmptyStr(filename)) {
300                                 cprintf("; filename=\"%s\"", filename);
301                         }
302                         cprintf("\r\n");
303                 }
304                 cprintf("Content-Length: %ld\r\n", (long)length);
305                 cprintf("\r\n");
306         }
307                         
308
309 }
310
311
312 /* 
313  * Called by imap_fetch_envelope() to output the "From" field.
314  * This is in its own function because its logic is kind of complex.  We
315  * really need to make this suck less.
316  */
317 void imap_output_envelope_from(struct CtdlMessage *msg) {
318         char user[SIZ], node[SIZ], name[SIZ];
319
320         if (!msg) return;
321
322         /* For anonymous messages, it's so easy! */
323         if (!is_room_aide() && (msg->cm_anon_type == MES_ANONONLY)) {
324                 cprintf("((\"----\" NIL \"x\" \"x.org\")) ");
325                 return;
326         }
327         if (!is_room_aide() && (msg->cm_anon_type == MES_ANONOPT)) {
328                 cprintf("((\"anonymous\" NIL \"x\" \"x.org\")) ");
329                 return;
330         }
331
332         /* For everything else, we do stuff. */
333         cprintf("((");                          /* open double-parens */
334         plain_imap_strout(msg->cm_fields['A']); /* personal name */
335         cprintf(" NIL ");                       /* source route (not used) */
336
337
338         if (msg->cm_fields['F'] != NULL) {
339                 process_rfc822_addr(msg->cm_fields['F'], user, node, name);
340                 plain_imap_strout(user);                /* mailbox name (user id) */
341                 cprintf(" ");
342                 if (!strcasecmp(node, config.c_nodename)) {
343                         plain_imap_strout(config.c_fqdn);
344                 }
345                 else {
346                         plain_imap_strout(node);                /* host name */
347                 }
348         }
349         else {
350                 plain_imap_strout(msg->cm_fields['A']); /* mailbox name (user id) */
351                 cprintf(" ");
352                 plain_imap_strout(msg->cm_fields['N']); /* host name */
353         }
354         
355         cprintf(")) ");                         /* close double-parens */
356 }
357
358
359
360 /*
361  * Output an envelope address (or set of addresses) in the official,
362  * convoluted, braindead format.  (Note that we can't use this for
363  * the "From" address because its data may come from a number of different
364  * fields.  But we can use it for "To" and possibly others.
365  */
366 void imap_output_envelope_addr(char *addr) {
367         char individual_addr[256];
368         int num_addrs;
369         int i;
370         char user[256];
371         char node[256];
372         char name[256];
373
374         if (addr == NULL) {
375                 cprintf("NIL ");
376                 return;
377         }
378
379         if (IsEmptyStr(addr)) {
380                 cprintf("NIL ");
381                 return;
382         }
383
384         cprintf("(");
385
386         /* How many addresses are listed here? */
387         num_addrs = num_tokens(addr, ',');
388
389         /* Output them one by one. */
390         for (i=0; i<num_addrs; ++i) {
391                 extract_token(individual_addr, addr, i, ',', sizeof individual_addr);
392                 striplt(individual_addr);
393                 process_rfc822_addr(individual_addr, user, node, name);
394                 cprintf("(");
395                 plain_imap_strout(name);
396                 cprintf(" NIL ");
397                 plain_imap_strout(user);
398                 cprintf(" ");
399                 plain_imap_strout(node);
400                 cprintf(")");
401                 if (i < (num_addrs-1)) cprintf(" ");
402         }
403
404         cprintf(") ");
405 }
406
407
408 /*
409  * Implements the ENVELOPE fetch item
410  * 
411  * Note that the imap_strout() function can cleverly output NULL fields as NIL,
412  * so we don't have to check for that condition like we do elsewhere.
413  */
414 void imap_fetch_envelope(struct CtdlMessage *msg) {
415         char datestringbuf[SIZ];
416         time_t msgdate;
417         char *fieldptr = NULL;
418
419         if (!msg) return;
420
421         /* Parse the message date into an IMAP-format date string */
422         if (msg->cm_fields['T'] != NULL) {
423                 msgdate = atol(msg->cm_fields['T']);
424         }
425         else {
426                 msgdate = time(NULL);
427         }
428         datestring(datestringbuf, sizeof datestringbuf,
429                 msgdate, DATESTRING_IMAP);
430
431         /* Now start spewing data fields.  The order is important, as it is
432          * defined by the protocol specification.  Nonexistent fields must
433          * be output as NIL, existent fields must be quoted or literalled.
434          * The imap_strout() function conveniently does all this for us.
435          */
436         cprintf("ENVELOPE (");
437
438         /* Date */
439         plain_imap_strout(datestringbuf);
440         cprintf(" ");
441
442         /* Subject */
443         plain_imap_strout(msg->cm_fields['U']);
444         cprintf(" ");
445
446         /* From */
447         imap_output_envelope_from(msg);
448
449         /* Sender (default to same as 'From' if not present) */
450         fieldptr = rfc822_fetch_field(msg->cm_fields['M'], "Sender");
451         if (fieldptr != NULL) {
452                 imap_output_envelope_addr(fieldptr);
453                 free(fieldptr);
454         }
455         else {
456                 imap_output_envelope_from(msg);
457         }
458
459         /* Reply-to */
460         fieldptr = rfc822_fetch_field(msg->cm_fields['M'], "Reply-to");
461         if (fieldptr != NULL) {
462                 imap_output_envelope_addr(fieldptr);
463                 free(fieldptr);
464         }
465         else {
466                 imap_output_envelope_from(msg);
467         }
468
469         /* To */
470         imap_output_envelope_addr(msg->cm_fields['R']);
471
472         /* Cc (we do it this way because there might be a legacy non-Citadel Cc: field present) */
473         fieldptr = msg->cm_fields['Y'];
474         if (fieldptr != NULL) {
475                 imap_output_envelope_addr(fieldptr);
476         }
477         else {
478                 fieldptr = rfc822_fetch_field(msg->cm_fields['M'], "Cc");
479                 imap_output_envelope_addr(fieldptr);
480                 if (fieldptr != NULL) free(fieldptr);
481         }
482
483         /* Bcc */
484         fieldptr = rfc822_fetch_field(msg->cm_fields['M'], "Bcc");
485         imap_output_envelope_addr(fieldptr);
486         if (fieldptr != NULL) free(fieldptr);
487
488         /* In-reply-to */
489         fieldptr = rfc822_fetch_field(msg->cm_fields['M'], "In-reply-to");
490         plain_imap_strout(fieldptr);
491         cprintf(" ");
492         if (fieldptr != NULL) free(fieldptr);
493
494         /* message ID */
495         plain_imap_strout(msg->cm_fields['I']);
496
497         cprintf(")");
498 }
499
500 /*
501  * This function is called only when CC->redirect_buffer contains a set of
502  * RFC822 headers with no body attached.  Its job is to strip that set of
503  * headers down to *only* the ones we're interested in.
504  */
505 void imap_strip_headers(StrBuf *section) {
506         citimap_command Cmd;
507         StrBuf *which_fields = NULL;
508         int doing_headers = 0;
509         int headers_not = 0;
510         int num_parms = 0;
511         int i;
512         StrBuf *boiled_headers = NULL;
513         StrBuf *Line;
514         int ok = 0;
515         int done_headers = 0;
516         const char *Ptr = NULL;
517         CitContext *CCC = CC;
518
519         if (CCC->redirect_buffer == NULL) return;
520
521         which_fields = NewStrBufDup(section);
522
523         if (!strncasecmp(ChrPtr(which_fields), "HEADER.FIELDS", 13))
524                 doing_headers = 1;
525         if (doing_headers && 
526             !strncasecmp(ChrPtr(which_fields), "HEADER.FIELDS.NOT", 17))
527                 headers_not = 1;
528
529         for (i=0; i < StrLength(which_fields); ++i) {
530                 if (ChrPtr(which_fields)[i]=='(')
531                         StrBufReplaceToken(which_fields, i, 1, HKEY(""));
532         }
533         for (i=0; i < StrLength(which_fields); ++i) {
534                 if (ChrPtr(which_fields)[i]==')') {
535                         StrBufCutAt(which_fields, i, NULL);
536                         break;
537                 }
538         }
539         memset(&Cmd, 0, sizeof(citimap_command));
540         Cmd.CmdBuf = which_fields;
541         num_parms = imap_parameterize(&Cmd);
542
543         boiled_headers = NewStrBufPlain(NULL, StrLength(CCC->redirect_buffer));
544         Line = NewStrBufPlain(NULL, SIZ);
545         Ptr = NULL;
546         ok = 0;
547         do {
548                 StrBufSipLine(Line, CCC->redirect_buffer, &Ptr);
549
550                 if (!isspace(ChrPtr(Line)[0])) {
551                         ok = 0;
552                         if (doing_headers == 0) ok = 1;
553                         else {
554                                 /* we're supposed to print all headers that are not matching the filter list */
555                                 if (headers_not) for (i=0, ok = 1; (i < num_parms) && (ok == 1); ++i) {
556                                                 if ( (!strncasecmp(ChrPtr(Line), 
557                                                                    Cmd.Params[i].Key,
558                                                                    Cmd.Params[i].len)) &&
559                                                      (ChrPtr(Line)[Cmd.Params[i].len]==':') ) {
560                                                         ok = 0;
561                                                 }
562                                 }
563                                 /* we're supposed to print all headers matching the filterlist */
564                                 else for (i=0, ok = 0; ((i < num_parms) && (ok == 0)); ++i) {
565                                                 if ( (!strncasecmp(ChrPtr(Line), 
566                                                                    Cmd.Params[i].Key,
567                                                                    Cmd.Params[i].len)) &&
568                                                      (ChrPtr(Line)[Cmd.Params[i].len]==':') ) {
569                                                         ok = 1;
570                                         }
571                                 }
572                         }
573                 }
574
575                 if (ok) {
576                         StrBufAppendBuf(boiled_headers, Line, 0);
577                         StrBufAppendBufPlain(boiled_headers, HKEY("\r\n"), 0);
578                 }
579
580                 if ((Ptr == StrBufNOTNULL)  ||
581                     (StrLength(Line) == 0)  ||
582                     (ChrPtr(Line)[0]=='\r') ||
583                     (ChrPtr(Line)[0]=='\n')   ) done_headers = 1;
584         } while (!done_headers);
585
586         StrBufAppendBufPlain(boiled_headers, HKEY("\r\n"), 0);
587
588         /* Now save it back (it'll always be smaller) */
589         FreeStrBuf(&CCC->redirect_buffer);
590         CCC->redirect_buffer = boiled_headers;
591
592         FreeStrBuf(&which_fields);
593         FreeStrBuf(&Line);
594 }
595
596
597 /*
598  * Implements the BODY and BODY.PEEK fetch items
599  */
600 void imap_fetch_body(long msgnum, ConstStr item, int is_peek) {
601         struct CtdlMessage *msg = NULL;
602         StrBuf *section;
603         StrBuf *partial;
604         int is_partial = 0;
605         size_t pstart, pbytes;
606         int loading_body_now = 0;
607         int need_body = 1;
608         int burn_the_cache = 0;
609         CitContext *CCC = CC;
610
611         /* extract section */
612         section = NewStrBufPlain(CKEY(item));
613         
614         if (strchr(ChrPtr(section), '[') != NULL) {
615                 StrBufStripAllBut(section, '[', ']');
616         }
617         CtdlLogPrintf(CTDL_DEBUG, "Section is: %s%s\n", 
618                       ChrPtr(section), 
619                       (StrLength(section) == 0) ? "(empty)" : ""
620         );
621
622         /* Burn the cache if we don't have the same section of the 
623          * same message again.
624          */
625         if (IMAP->cached_body != NULL) {
626                 if (IMAP->cached_bodymsgnum != msgnum) {
627                         burn_the_cache = 1;
628                 }
629                 else if ( (!IMAP->cached_body_withbody) && (need_body) ) {
630                         burn_the_cache = 1;
631                 }
632                 else if (strcasecmp(IMAP->cached_bodypart, ChrPtr(section))) {
633                         burn_the_cache = 1;
634                 }
635                 if (burn_the_cache) {
636                         /* Yup, go ahead and burn the cache. */
637                         free(IMAP->cached_body);
638                         IMAP->cached_body_len = 0;
639                         IMAP->cached_body = NULL;
640                         IMAP->cached_bodymsgnum = (-1);
641                         strcpy(IMAP->cached_bodypart, "");
642                 }
643         }
644
645         /* extract partial */
646         partial = NewStrBufPlain(CKEY(item));
647         if (strchr(ChrPtr(partial), '<') != NULL) {
648                 StrBufStripAllBut(partial, '<', '>');
649                 is_partial = 1;
650         }
651         if (is_partial == 0) 
652                 if (StrLength(partial) > 0) 
653                         CtdlLogPrintf(CTDL_DEBUG, 
654                                       "Partial is %s\n", 
655                                       ChrPtr(partial));
656
657         if (IMAP->cached_body == NULL) {
658                 CCC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
659                 loading_body_now = 1;
660                 msg = CtdlFetchMessage(msgnum, (need_body ? 1 : 0));
661         }
662
663         /* Now figure out what the client wants, and get it */
664
665         if (!loading_body_now) {
666                 /* What we want is already in memory */
667         }
668
669         else if ( (!strcmp(ChrPtr(section), "1")) && (msg->cm_format_type != 4) ) {
670                 CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_NONE, 0, 1, SUPPRESS_ENV_TO);
671         }
672
673         else if (StrLength(section) == 0) {
674                 CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_ALL, 0, 1, SUPPRESS_ENV_TO);
675         }
676
677         /*
678          * If the client asked for just headers, or just particular header
679          * fields, strip it down.
680          */
681         else if (!strncasecmp(ChrPtr(section), "HEADER", 6)) {
682                 /* This used to work with HEADERS_FAST, but then Apple got stupid with their
683                  * IMAP library and this broke Mail.App and iPhone Mail, so we had to change it
684                  * to HEADERS_ONLY so the trendy hipsters with their iPhones can read mail.
685                  */
686                 CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_ONLY, 0, 1, SUPPRESS_ENV_TO);
687                 imap_strip_headers(section);
688         }
689
690         /*
691          * Strip it down if the client asked for everything _except_ headers.
692          */
693         else if (!strncasecmp(ChrPtr(section), "TEXT", 4)) {
694                 CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_NONE, 0, 1, SUPPRESS_ENV_TO);
695         }
696
697         /*
698          * Anything else must be a part specifier.
699          * (Note value of 1 passed as 'dont_decode' so client gets it encoded)
700          */
701         else {
702                 mime_parser(msg->cm_fields['M'], NULL,
703                                 *imap_load_part, NULL, NULL,
704                                 section,
705                                 1);
706         }
707
708         if (loading_body_now) {
709                 IMAP->cached_body_len = StrLength(CCC->redirect_buffer);
710                 IMAP->cached_body = SmashStrBuf(&CCC->redirect_buffer);
711                 IMAP->cached_bodymsgnum = msgnum;
712                 IMAP->cached_body_withbody = need_body;
713                 strcpy(IMAP->cached_bodypart, ChrPtr(section));
714         }
715
716         if (is_partial == 0) {
717                 cprintf("BODY[%s] {" SIZE_T_FMT "}\r\n", ChrPtr(section), IMAP->cached_body_len);
718                 pstart = 0;
719                 pbytes = IMAP->cached_body_len;
720         }
721         else {
722                 sscanf(ChrPtr(partial), SIZE_T_FMT "." SIZE_T_FMT, &pstart, &pbytes);
723                 if (pbytes > (IMAP->cached_body_len - pstart)) {
724                         pbytes = IMAP->cached_body_len - pstart;
725                 }
726                 cprintf("BODY[%s]<" SIZE_T_FMT "> {" SIZE_T_FMT "}\r\n", ChrPtr(section), pstart, pbytes);
727         }
728
729         FreeStrBuf(&partial);
730
731         /* Here we go -- output it */
732         client_write(&IMAP->cached_body[pstart], pbytes);
733
734         if (msg != NULL) {
735                 CtdlFreeMessage(msg);
736         }
737
738         /* Mark this message as "seen" *unless* this is a "peek" operation */
739         if (is_peek == 0) {
740                 CtdlSetSeen(&msgnum, 1, 1, ctdlsetseen_seen, NULL, NULL);
741         }
742 }
743
744 /*
745  * Called immediately before outputting a multipart bodystructure
746  */
747 void imap_fetch_bodystructure_pre(
748                 char *name, char *filename, char *partnum, char *disp,
749                 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
750                 char *cbid, void *cbuserdata
751                 ) {
752
753         cprintf("(");
754 }
755
756
757
758 /*
759  * Called immediately after outputting a multipart bodystructure
760  */
761 void imap_fetch_bodystructure_post(
762                 char *name, char *filename, char *partnum, char *disp,
763                 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
764                 char *cbid, void *cbuserdata
765                 ) {
766
767         char subtype[128];
768
769         cprintf(" ");
770
771         /* disposition */
772         extract_token(subtype, cbtype, 1, '/', sizeof subtype);
773         plain_imap_strout(subtype);
774
775         /* body language */
776         /* cprintf(" NIL"); We thought we needed this at one point, but maybe we don't... */
777
778         cprintf(")");
779 }
780
781
782
783 /*
784  * Output the info for a MIME part in the format required by BODYSTRUCTURE.
785  *
786  */
787 void imap_fetch_bodystructure_part(
788                 char *name, char *filename, char *partnum, char *disp,
789                 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
790                 char *cbid, void *cbuserdata
791                 ) {
792
793         int have_cbtype = 0;
794         int have_encoding = 0;
795         int lines = 0;
796         size_t i;
797         char cbmaintype[128];
798         char cbsubtype[128];
799
800         if (cbtype != NULL) if (!IsEmptyStr(cbtype)) have_cbtype = 1;
801         if (have_cbtype) {
802                 extract_token(cbmaintype, cbtype, 0, '/', sizeof cbmaintype);
803                 extract_token(cbsubtype, cbtype, 1, '/', sizeof cbsubtype);
804         }
805         else {
806                 strcpy(cbmaintype, "TEXT");
807                 strcpy(cbsubtype, "PLAIN");
808         }
809
810         cprintf("(");
811         plain_imap_strout(cbmaintype);                                  /* body type */
812         cprintf(" ");
813         plain_imap_strout(cbsubtype);                                           /* body subtype */
814         cprintf(" ");
815
816         cprintf("(");                                                   /* begin body parameter list */
817
818         /* "NAME" must appear as the first parameter.  This is not required by IMAP,
819          * but the Asterisk voicemail application blindly assumes that NAME will be in
820          * the first position.  If it isn't, it rejects the message.
821          */
822         if (name != NULL) if (!IsEmptyStr(name)) {
823                 cprintf("\"NAME\" ");
824                 plain_imap_strout(name);
825                 cprintf(" ");
826         }
827
828         cprintf("\"CHARSET\" ");
829         if (cbcharset == NULL) {
830                 plain_imap_strout("US-ASCII");
831         }
832         else if (cbcharset[0] == 0) {
833                 plain_imap_strout("US-ASCII");
834         }
835         else {
836                 plain_imap_strout(cbcharset);
837         }
838         cprintf(") ");                                                  /* end body parameter list */
839
840         cprintf("NIL ");                                                /* Body ID */
841         cprintf("NIL ");                                                /* Body description */
842
843         if (encoding != NULL) if (encoding[0] != 0)  have_encoding = 1;
844         if (have_encoding) {
845                 plain_imap_strout(encoding);
846         }
847         else {
848                 plain_imap_strout("7BIT");
849         }
850         cprintf(" ");
851
852         /* The next field is the size of the part in bytes. */
853         cprintf("%ld ", (long)length);  /* bytes */
854
855         /* The next field is the number of lines in the part, if and only
856          * if the part is TEXT.  More gratuitous complexity.
857          */
858         if (!strcasecmp(cbmaintype, "TEXT")) {
859                 if (length) for (i=0; i<length; ++i) {
860                         if (((char *)content)[i] == '\n') ++lines;
861                 }
862                 cprintf("%d ", lines);
863         }
864
865         /* More gratuitous complexity */
866         if ((!strcasecmp(cbmaintype, "MESSAGE"))
867            && (!strcasecmp(cbsubtype, "RFC822"))) {
868                 /* FIXME: message/rfc822 also needs to output the envelope structure,
869                  * body structure, and line count of the encapsulated message.  Fortunately
870                  * there are not yet any clients depending on this, so we can get away
871                  * with not implementing it for now.
872                  */
873         }
874
875         /* MD5 value of body part; we can get away with NIL'ing this */
876         cprintf("NIL ");
877
878         /* Disposition */
879         if (disp == NULL) {
880                 cprintf("NIL");
881         }
882         else if (IsEmptyStr(disp)) {
883                 cprintf("NIL");
884         }
885         else {
886                 cprintf("(");
887                 plain_imap_strout(disp);
888                 if (filename != NULL) if (!IsEmptyStr(filename)) {
889                         cprintf(" (\"FILENAME\" ");
890                         plain_imap_strout(filename);
891                         cprintf(")");
892                 }
893                 cprintf(")");
894         }
895
896         /* Body language (not defined yet) */
897         cprintf(" NIL)");
898 }
899
900
901
902 /*
903  * Spew the BODYSTRUCTURE data for a message.
904  *
905  */
906 void imap_fetch_bodystructure (long msgnum, const char *item,
907                 struct CtdlMessage *msg) {
908         const char *rfc822 = NULL;
909         const char *rfc822_body = NULL;
910         size_t rfc822_len;
911         size_t rfc822_headers_len;
912         size_t rfc822_body_len;
913         const char *ptr = NULL;
914         char *pch;
915         char buf[SIZ];
916         int lines = 0;
917
918         /* Handle NULL message gracefully */
919         if (msg == NULL) {
920                 cprintf("BODYSTRUCTURE (\"TEXT\" \"PLAIN\" "
921                         "(\"CHARSET\" \"US-ASCII\") NIL NIL "
922                         "\"7BIT\" 0 0)");
923                 return;
924         }
925
926         /* For non-RFC822 (ordinary Citadel) messages, this is short and
927          * sweet...
928          */
929         if (msg->cm_format_type != FMT_RFC822) {
930
931                 /* *sigh* We have to RFC822-format the message just to be able
932                  * to measure it.  FIXME use smi cached fields if possible
933                  */
934
935                 CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
936                 CtdlOutputPreLoadedMsg(msg, MT_RFC822, 0, 0, 1, SUPPRESS_ENV_TO);
937                 rfc822_len = StrLength(CC->redirect_buffer);
938                 rfc822 = pch = SmashStrBuf(&CC->redirect_buffer);
939
940                 ptr = rfc822;
941                 do {
942                         ptr = memreadline(ptr, buf, sizeof buf);
943                         ++lines;
944                         if ((IsEmptyStr(buf)) && (rfc822_body == NULL)) {
945                                 rfc822_body = ptr;
946                         }
947                 } while (*ptr != 0);
948
949                 rfc822_headers_len = rfc822_body - rfc822;
950                 rfc822_body_len = rfc822_len - rfc822_headers_len;
951                 free(pch);
952
953                 cprintf("BODYSTRUCTURE (\"TEXT\" \"PLAIN\" "
954                         "(\"CHARSET\" \"US-ASCII\") NIL NIL "
955                         "\"7BIT\" " SIZE_T_FMT " %d)", rfc822_body_len, lines);
956
957                 return;
958         }
959
960         /* For messages already stored in RFC822 format, we have to parse. */
961         cprintf("BODYSTRUCTURE ");
962         mime_parser(msg->cm_fields['M'],
963                         NULL,
964                         *imap_fetch_bodystructure_part, /* part */
965                         *imap_fetch_bodystructure_pre,  /* pre-multi */
966                         *imap_fetch_bodystructure_post, /* post-multi */
967                         NULL,
968                         1);     /* don't decode -- we want it as-is */
969 }
970
971
972 /*
973  * imap_do_fetch() calls imap_do_fetch_msg() to output the data of an
974  * individual message, once it has been selected for output.
975  */
976 void imap_do_fetch_msg(int seq, citimap_command *Cmd) {
977         int i;
978         citimap *Imap = IMAP;
979         struct CtdlMessage *msg = NULL;
980         int body_loaded = 0;
981
982         /* Don't attempt to fetch bogus messages or UID's */
983         if (seq < 1) return;
984         if (Imap->msgids[seq-1] < 1L) return;
985
986         buffer_output();
987         cprintf("* %d FETCH (", seq);
988
989         for (i=0; i<Cmd->num_parms; ++i) {
990
991                 /* Fetchable without going to the message store at all */
992                 if (!strcasecmp(Cmd->Params[i].Key, "UID")) {
993                         imap_fetch_uid(seq);
994                 }
995                 else if (!strcasecmp(Cmd->Params[i].Key, "FLAGS")) {
996                         imap_fetch_flags(seq-1);
997                 }
998
999                 /* Potentially fetchable from cache, if the client requests
1000                  * stuff from the same message several times in a row.
1001                  */
1002                 else if (!strcasecmp(Cmd->Params[i].Key, "RFC822")) {
1003                         imap_fetch_rfc822(Imap->msgids[seq-1], Cmd->Params[i].Key);
1004                 }
1005                 else if (!strcasecmp(Cmd->Params[i].Key, "RFC822.HEADER")) {
1006                         imap_fetch_rfc822(Imap->msgids[seq-1], Cmd->Params[i].Key);
1007                 }
1008                 else if (!strcasecmp(Cmd->Params[i].Key, "RFC822.SIZE")) {
1009                         imap_fetch_rfc822(Imap->msgids[seq-1], Cmd->Params[i].Key);
1010                 }
1011                 else if (!strcasecmp(Cmd->Params[i].Key, "RFC822.TEXT")) {
1012                         imap_fetch_rfc822(Imap->msgids[seq-1], Cmd->Params[i].Key);
1013                 }
1014
1015                 /* BODY fetches do their own fetching and caching too. */
1016                 else if (!strncasecmp(Cmd->Params[i].Key, "BODY[", 5)) {
1017                         imap_fetch_body(Imap->msgids[seq-1], Cmd->Params[i], 0);
1018                 }
1019                 else if (!strncasecmp(Cmd->Params[i].Key, "BODY.PEEK[", 10)) {
1020                         imap_fetch_body(Imap->msgids[seq-1], Cmd->Params[i], 1);
1021                 }
1022
1023                 /* Otherwise, load the message into memory.
1024                  */
1025                 else if (!strcasecmp(Cmd->Params[i].Key, "BODYSTRUCTURE")) {
1026                         if ((msg != NULL) && (!body_loaded)) {
1027                                 CtdlFreeMessage(msg);   /* need the whole thing */
1028                                 msg = NULL;
1029                         }
1030                         if (msg == NULL) {
1031                                 msg = CtdlFetchMessage(Imap->msgids[seq-1], 1);
1032                                 body_loaded = 1;
1033                         }
1034                         imap_fetch_bodystructure(Imap->msgids[seq-1],
1035                                         Cmd->Params[i].Key, msg);
1036                 }
1037                 else if (!strcasecmp(Cmd->Params[i].Key, "ENVELOPE")) {
1038                         if (msg == NULL) {
1039                                 msg = CtdlFetchMessage(Imap->msgids[seq-1], 0);
1040                                 body_loaded = 0;
1041                         }
1042                         imap_fetch_envelope(msg);
1043                 }
1044                 else if (!strcasecmp(Cmd->Params[i].Key, "INTERNALDATE")) {
1045                         if (msg == NULL) {
1046                                 msg = CtdlFetchMessage(Imap->msgids[seq-1], 0);
1047                                 body_loaded = 0;
1048                         }
1049                         imap_fetch_internaldate(msg);
1050                 }
1051
1052                 if (i != Cmd->num_parms-1) cprintf(" ");
1053         }
1054
1055         cprintf(")\r\n");
1056         unbuffer_output();
1057         if (msg != NULL) {
1058                 CtdlFreeMessage(msg);
1059         }
1060 }
1061
1062
1063
1064 /*
1065  * imap_fetch() calls imap_do_fetch() to do its actual work, once it's
1066  * validated and boiled down the request a bit.
1067  */
1068 void imap_do_fetch(citimap_command *Cmd) {
1069         int i;
1070 #if 0
1071 /* debug output the parsed vector */
1072         {
1073                 int i;
1074                 CtdlLogPrintf(CTDL_DEBUG, "----- %ld params \n",
1075                               Cmd->num_parms);
1076
1077         for (i=0; i < Cmd->num_parms; i++) {
1078                 if (Cmd->Params[i].len != strlen(Cmd->Params[i].Key))
1079                         CtdlLogPrintf(CTDL_DEBUG, "*********** %ld != %ld : %s\n",
1080                                       Cmd->Params[i].len, 
1081                                       strlen(Cmd->Params[i].Key),
1082                                       Cmd->Params[i].Key);
1083                 else
1084                         CtdlLogPrintf(CTDL_DEBUG, "%ld : %s\n",
1085                                       Cmd->Params[i].len, 
1086                                       Cmd->Params[i].Key);
1087         }}
1088
1089 #endif
1090
1091         if (IMAP->num_msgs > 0) {
1092                 for (i = 0; i < IMAP->num_msgs; ++i) {
1093
1094                         /* Abort the fetch loop if the session breaks.
1095                          * This is important for users who keep mailboxes
1096                          * that are too big *and* are too impatient to
1097                          * let them finish loading.  :)
1098                          */
1099                         if (CC->kill_me) return;
1100
1101                         /* Get any message marked for fetch. */
1102                         if (IMAP->flags[i] & IMAP_SELECTED) {
1103                                 imap_do_fetch_msg(i+1, Cmd);
1104                         }
1105                 }
1106         }
1107 }
1108
1109
1110
1111 /*
1112  * Back end for imap_handle_macros()
1113  * Note that this function *only* looks at the beginning of the string.  It
1114  * is not a generic search-and-replace function.
1115  */
1116 void imap_macro_replace(StrBuf *Buf, long where, 
1117                         StrBuf *TmpBuf,
1118                         char *find, long findlen, 
1119                         char *replace, long replacelen) 
1120 {
1121
1122         if (StrLength(Buf) - where > findlen)
1123                 return;
1124
1125         if (!strncasecmp(ChrPtr(Buf) + where, find, findlen)) {
1126                 if (ChrPtr(Buf)[where + findlen] == ' ') {
1127                         StrBufPlain(TmpBuf, replace, replacelen);
1128                         StrBufAppendBufPlain(TmpBuf, HKEY(" "), 0);
1129                         StrBufReplaceToken(Buf, where, findlen, 
1130                                            SKEY(TmpBuf));
1131                 }
1132                 if (where + findlen == StrLength(Buf)) {
1133                         StrBufReplaceToken(Buf, where, findlen, 
1134                                            replace, replacelen);
1135                 }
1136         }
1137 }
1138
1139
1140
1141 /*
1142  * Handle macros embedded in FETCH data items.
1143  * (What the heck are macros doing in a wire protocol?  Are we trying to save
1144  * the computer at the other end the trouble of typing a lot of characters?)
1145  */
1146 void imap_handle_macros(citimap_command *Cmd) {
1147         long i;
1148         int nest = 0;
1149         StrBuf *Tmp = NewStrBuf();
1150
1151         for (i=0; i < StrLength(Cmd->CmdBuf); ++i) {
1152                 char ch = ChrPtr(Cmd->CmdBuf)[i];
1153                 if ((ch=='(') ||
1154                     (ch=='[') ||
1155                     (ch=='<') ||
1156                     (ch=='{')) ++nest;
1157                 else if ((ch==')') ||
1158                          (ch==']') ||
1159                          (ch=='>') ||
1160                          (ch=='}')) --nest;
1161
1162                 if (nest <= 0) {
1163                         imap_macro_replace(Cmd->CmdBuf, i,
1164                                            Tmp, 
1165                                            HKEY("ALL"),
1166                                            HKEY("FLAGS INTERNALDATE RFC822.SIZE ENVELOPE")
1167                         );
1168                         imap_macro_replace(Cmd->CmdBuf, i,
1169                                            Tmp, 
1170                                            HKEY("BODY"),
1171                                            HKEY("BODYSTRUCTURE")
1172                         );
1173                         imap_macro_replace(Cmd->CmdBuf, i,
1174                                            Tmp, 
1175                                            HKEY("FAST"),
1176                                            HKEY("FLAGS INTERNALDATE RFC822.SIZE")
1177                         );
1178                         imap_macro_replace(Cmd->CmdBuf, i,
1179                                            Tmp, 
1180                                            HKEY("FULL"),
1181                                            HKEY("FLAGS INTERNALDATE RFC822.SIZE ENVELOPE BODY")
1182                         );
1183                 }
1184         }
1185         FreeStrBuf(&Tmp);
1186 }
1187
1188
1189 /*
1190  * Break out the data items requested, possibly a parenthesized list.
1191  * Returns the number of data items, or -1 if the list is invalid.
1192  * NOTE: this function alters the string it is fed, and uses it as a buffer
1193  * to hold the data for the pointers it returns.
1194  */
1195 int imap_extract_data_items(citimap_command *Cmd) 
1196 {
1197         int nArgs;
1198         int nest = 0;
1199         const char *pch, *end;
1200         long initial_len;
1201
1202         /* Convert all whitespace to ordinary space characters. */
1203         pch = ChrPtr(Cmd->CmdBuf);
1204         end = pch + StrLength(Cmd->CmdBuf);
1205
1206         while (pch < end)
1207         {
1208                 if (isspace(*pch)) 
1209                         StrBufPeek(Cmd->CmdBuf, pch, 0, ' ');
1210                 pch++;
1211         }
1212
1213         /* Strip leading and trailing whitespace, then strip leading and
1214          * trailing parentheses if it's a list
1215          */
1216         StrBufTrim(Cmd->CmdBuf);
1217         pch = ChrPtr(Cmd->CmdBuf);
1218         if ( (pch[0]=='(') && 
1219              (pch[StrLength(Cmd->CmdBuf)-1]==')') ) 
1220         {
1221                 StrBufCutRight(Cmd->CmdBuf, 1);
1222                 StrBufCutLeft(Cmd->CmdBuf, 1);
1223                 StrBufTrim(Cmd->CmdBuf);
1224         }
1225
1226         /* Parse any macro data items */
1227         imap_handle_macros(Cmd);
1228
1229         /*
1230          * Now break out the data items.  We throw in one trailing space in
1231          * order to avoid having to break out the last one manually.
1232          */
1233         nArgs = StrLength(Cmd->CmdBuf) / 10 + 10;
1234         nArgs = CmdAdjust(Cmd, nArgs, 0);
1235         initial_len = StrLength(Cmd->CmdBuf);
1236         Cmd->num_parms = 0;
1237         Cmd->Params[Cmd->num_parms].Key = pch = ChrPtr(Cmd->CmdBuf);
1238         end = Cmd->Params[Cmd->num_parms].Key + StrLength(Cmd->CmdBuf);
1239
1240         while (pch < end) 
1241         {
1242                 if ((*pch=='(') ||
1243                     (*pch=='[') ||
1244                     (*pch=='<') ||
1245                     (*pch=='{'))
1246                         ++nest;
1247
1248                 else if ((*pch==')') ||
1249                          (*pch==']') ||
1250                          (*pch=='>') ||
1251                          (*pch=='}'))
1252                         --nest;
1253
1254                 if ((nest <= 0) && (*pch==' ')) {
1255                         StrBufPeek(Cmd->CmdBuf, pch, 0, '\0');
1256                         Cmd->Params[Cmd->num_parms].len = 
1257                                 pch - Cmd->Params[Cmd->num_parms].Key;
1258
1259                         if (Cmd->num_parms + 1 >= Cmd->avail_parms) {
1260                                 nArgs = CmdAdjust(Cmd, nArgs * 2, 1);
1261                         }
1262                         Cmd->num_parms++;                       
1263                         Cmd->Params[Cmd->num_parms].Key = ++pch;
1264                 }
1265                 else if (pch + 1 == end) {
1266                         Cmd->Params[Cmd->num_parms].len = 
1267                                 pch - Cmd->Params[Cmd->num_parms].Key + 1;
1268
1269                         Cmd->num_parms++;                       
1270                 }
1271                 pch ++;
1272         }
1273         return Cmd->num_parms;
1274
1275 }
1276
1277
1278 /*
1279  * One particularly hideous aspect of IMAP is that we have to allow the client
1280  * to specify arbitrary ranges and/or sets of messages to fetch.  Citadel IMAP
1281  * handles this by setting the IMAP_SELECTED flag for each message specified in
1282  * the ranges/sets, then looping through the message array, outputting messages
1283  * with the flag set.  We don't bother returning an error if an out-of-range
1284  * number is specified (we just return quietly) because any client braindead
1285  * enough to request a bogus message number isn't going to notice the
1286  * difference anyway.
1287  *
1288  * This function clears out the IMAP_SELECTED bits, then sets that bit for each
1289  * message included in the specified range.
1290  *
1291  * Set is_uid to 1 to fetch by UID instead of sequence number.
1292  */
1293 void imap_pick_range(const char *supplied_range, int is_uid) {
1294         int i;
1295         int num_sets;
1296         int s;
1297         char setstr[SIZ], lostr[SIZ], histr[SIZ];
1298         long lo, hi;
1299         char actual_range[SIZ];
1300         citimap *Imap;
1301
1302         /* 
1303          * Handle the "ALL" macro
1304          */
1305         if (!strcasecmp(supplied_range, "ALL")) {
1306                 safestrncpy(actual_range, "1:*", sizeof actual_range);
1307         }
1308         else {
1309                 safestrncpy(actual_range, supplied_range, sizeof actual_range);
1310         }
1311
1312         Imap = IMAP;
1313         /*
1314          * Clear out the IMAP_SELECTED flags for all messages.
1315          */
1316         for (i = 0; i < Imap->num_msgs; ++i) {
1317                 Imap->flags[i] = Imap->flags[i] & ~IMAP_SELECTED;
1318         }
1319
1320         /*
1321          * Now set it for all specified messages.
1322          */
1323         num_sets = num_tokens(actual_range, ',');
1324         for (s=0; s<num_sets; ++s) {
1325                 extract_token(setstr, actual_range, s, ',', sizeof setstr);
1326
1327                 extract_token(lostr, setstr, 0, ':', sizeof lostr);
1328                 if (num_tokens(setstr, ':') >= 2) {
1329                         extract_token(histr, setstr, 1, ':', sizeof histr);
1330                         if (!strcmp(histr, "*")) snprintf(histr, sizeof histr, "%ld", LONG_MAX);
1331                 } 
1332                 else {
1333                         safestrncpy(histr, lostr, sizeof histr);
1334                 }
1335                 lo = atol(lostr);
1336                 hi = atol(histr);
1337
1338                 /* Loop through the array, flipping bits where appropriate */
1339                 for (i = 1; i <= Imap->num_msgs; ++i) {
1340                         if (is_uid) {   /* fetch by sequence number */
1341                                 if ( (Imap->msgids[i-1]>=lo)
1342                                    && (Imap->msgids[i-1]<=hi)) {
1343                                         Imap->flags[i-1] |= IMAP_SELECTED;
1344                                 }
1345                         }
1346                         else {          /* fetch by uid */
1347                                 if ( (i>=lo) && (i<=hi)) {
1348                                         Imap->flags[i-1] |= IMAP_SELECTED;
1349                                 }
1350                         }
1351                 }
1352         }
1353 }
1354
1355
1356
1357 /*
1358  * This function is called by the main command loop.
1359  */
1360 void imap_fetch(int num_parms, ConstStr *Params) {
1361         citimap_command Cmd;
1362         int num_items;
1363         
1364         if (num_parms < 4) {
1365                 cprintf("%s BAD invalid parameters\r\n", Params[0].Key);
1366                 return;
1367         }
1368
1369         imap_pick_range(Params[2].Key, 0);
1370
1371         memset(&Cmd, 0, sizeof(citimap_command));
1372         Cmd.CmdBuf = NewStrBufPlain(NULL, StrLength(IMAP->Cmd.CmdBuf));
1373         MakeStringOf(Cmd.CmdBuf, 3);
1374
1375         num_items = imap_extract_data_items(&Cmd);
1376         if (num_items < 1) {
1377                 cprintf("%s BAD invalid data item list\r\n", Params[0].Key);
1378                 FreeStrBuf(&Cmd.CmdBuf);
1379                 free(Cmd.Params);
1380                 return;
1381         }
1382
1383         imap_do_fetch(&Cmd);
1384         cprintf("%s OK FETCH completed\r\n", Params[0].Key);
1385         FreeStrBuf(&Cmd.CmdBuf);
1386         free(Cmd.Params);
1387 }
1388
1389 /*
1390  * This function is called by the main command loop.
1391  */
1392 void imap_uidfetch(int num_parms, ConstStr *Params) {
1393         citimap_command Cmd;
1394         int num_items;
1395         int i;
1396         int have_uid_item = 0;
1397
1398         if (num_parms < 5) {
1399                 cprintf("%s BAD invalid parameters\r\n", Params[0].Key);
1400                 return;
1401         }
1402
1403         imap_pick_range(Params[3].Key, 1);
1404
1405         memset(&Cmd, 0, sizeof(citimap_command));
1406         Cmd.CmdBuf = NewStrBufPlain(NULL, StrLength(IMAP->Cmd.CmdBuf));
1407
1408         MakeStringOf(Cmd.CmdBuf, 4);
1409 #if 0
1410         CtdlLogPrintf(CTDL_DEBUG, "-------%s--------\n", ChrPtr(Cmd.CmdBuf));
1411 #endif
1412         num_items = imap_extract_data_items(&Cmd);
1413         if (num_items < 1) {
1414                 cprintf("%s BAD invalid data item list\r\n", Params[0].Key);
1415                 FreeStrBuf(&Cmd.CmdBuf);
1416                 free(Cmd.Params);
1417                 return;
1418         }
1419
1420         /* If the "UID" item was not included, we include it implicitly
1421          * (at the beginning) because this is a UID FETCH command
1422          */
1423         for (i=0; i<num_items; ++i) {
1424                 if (!strcasecmp(Cmd.Params[i].Key, "UID")) ++have_uid_item;
1425         }
1426         if (have_uid_item == 0) {
1427                 if (Cmd.num_parms + 1 >= Cmd.avail_parms)
1428                         CmdAdjust(&Cmd, Cmd.avail_parms + 1, 1);
1429                 memmove(&Cmd.Params[1], 
1430                         &Cmd.Params[0], 
1431                         sizeof(ConstStr) * Cmd.num_parms);
1432
1433                 Cmd.num_parms++;
1434                 Cmd.Params[0] = (ConstStr){HKEY("UID")};
1435         }
1436
1437         imap_do_fetch(&Cmd);
1438         cprintf("%s OK UID FETCH completed\r\n", Params[0].Key);
1439         FreeStrBuf(&Cmd.CmdBuf);
1440         free(Cmd.Params);
1441 }
1442
1443