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