1 /*
2  * Copyright (C) 1996-9 Brandon Long <blong@fiction.net>
3  * Copyright (C) 1999-2009 Brendan Cully <brendan@kublai.com>
4  *
5  *     This program is free software; you can redistribute it and/or modify
6  *     it under the terms of the GNU General Public License as published by
7  *     the Free Software Foundation; either version 2 of the License, or
8  *     (at your option) any later version.
9  *
10  *     This program is distributed in the hope that it will be useful,
11  *     but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  *     GNU General Public License for more details.
14  *
15  *     You should have received a copy of the GNU General Public License
16  *     along with this program; if not, write to the Free Software
17  *     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18  *
19  */
20 
21 /* message parsing/updating functions */
22 
23 #if HAVE_CONFIG_H
24 # include "config.h"
25 #endif
26 
27 #include <errno.h>
28 #include <stdlib.h>
29 #include <ctype.h>
30 
31 #include "mutt.h"
32 #include "imap_private.h"
33 #include "message.h"
34 #include "mx.h"
35 
36 #ifdef HAVE_PGP
37 #include "pgp.h"
38 #endif
39 
40 #if USE_HCACHE
41 #include "hcache.h"
42 #endif
43 
44 #include "bcache.h"
45 
46 static FILE* msg_cache_get (IMAP_DATA* idata, HEADER* h);
47 static FILE* msg_cache_put (IMAP_DATA* idata, HEADER* h);
48 static int msg_cache_commit (IMAP_DATA* idata, HEADER* h);
49 
50 static void flush_buffer(char* buf, size_t* len, CONNECTION* conn);
51 static int msg_fetch_header (CONTEXT* ctx, IMAP_HEADER* h, char* buf,
52   FILE* fp);
53 static int msg_parse_fetch (IMAP_HEADER* h, char* s);
54 static char* msg_parse_flags (IMAP_HEADER* h, char* s);
55 
56 /* imap_read_headers:
57  * Changed to read many headers instead of just one. It will return the
58  * msgno of the last message read. It will return a value other than
59  * msgend if mail comes in while downloading headers (in theory).
60  */
imap_read_headers(IMAP_DATA * idata,int msgbegin,int msgend)61 int imap_read_headers (IMAP_DATA* idata, int msgbegin, int msgend)
62 {
63   CONTEXT* ctx;
64   char buf[LONG_STRING];
65   char *hdrreq = NULL;
66   FILE *fp;
67   char tempfile[_POSIX_PATH_MAX];
68   int msgno, idx;
69   IMAP_HEADER h;
70   IMAP_STATUS* status;
71   int rc, mfhrc, oldmsgcount;
72   int fetchlast = 0;
73   int maxuid = 0;
74   const char *want_headers = "DATE FROM SUBJECT TO CC MESSAGE-ID REFERENCES CONTENT-TYPE CONTENT-DESCRIPTION IN-REPLY-TO REPLY-TO LINES LIST-POST X-LABEL";
75   progress_t progress;
76   int retval = -1;
77 
78 #if USE_HCACHE
79   unsigned int *uid_validity = NULL;
80   unsigned int *puidnext = NULL;
81   unsigned int uidnext = 0;
82   int evalhc = 0;
83 #endif /* USE_HCACHE */
84 
85   ctx = idata->ctx;
86 
87   if (mutt_bit_isset (idata->capabilities,IMAP4REV1))
88   {
89     safe_asprintf (&hdrreq, "BODY.PEEK[HEADER.FIELDS (%s%s%s)]",
90                            want_headers, ImapHeaders ? " " : "", NONULL (ImapHeaders));
91   }
92   else if (mutt_bit_isset (idata->capabilities,IMAP4))
93   {
94     safe_asprintf (&hdrreq, "RFC822.HEADER.LINES (%s%s%s)",
95                            want_headers, ImapHeaders ? " " : "", NONULL (ImapHeaders));
96   }
97   else
98   {	/* Unable to fetch headers for lower versions */
99     mutt_error _("Unable to fetch headers from this IMAP server version.");
100     mutt_sleep (2);	/* pause a moment to let the user see the error */
101     goto error_out_0;
102   }
103 
104   /* instead of downloading all headers and then parsing them, we parse them
105    * as they come in. */
106   mutt_mktemp (tempfile, sizeof (tempfile));
107   if (!(fp = safe_fopen (tempfile, "w+")))
108   {
109     mutt_error (_("Could not create temporary file %s"), tempfile);
110     mutt_sleep (2);
111     goto error_out_0;
112   }
113   unlink (tempfile);
114 
115   /* make sure context has room to hold the mailbox */
116   while ((msgend) >= idata->ctx->hdrmax)
117     mx_alloc_memory (idata->ctx);
118 
119   oldmsgcount = ctx->msgcount;
120   idata->reopen &= ~(IMAP_REOPEN_ALLOW|IMAP_NEWMAIL_PENDING);
121   idata->newMailCount = 0;
122 
123 #if USE_HCACHE
124   idata->hcache = imap_hcache_open (idata, NULL);
125 
126   if (idata->hcache && !msgbegin)
127   {
128     uid_validity = mutt_hcache_fetch_raw (idata->hcache, "/UIDVALIDITY", imap_hcache_keylen);
129     puidnext = mutt_hcache_fetch_raw (idata->hcache, "/UIDNEXT", imap_hcache_keylen);
130     if (puidnext)
131     {
132       uidnext = *puidnext;
133       FREE (&puidnext);
134     }
135     if (uid_validity && uidnext && *uid_validity == idata->uid_validity)
136       evalhc = 1;
137     FREE (&uid_validity);
138   }
139   if (evalhc)
140   {
141     mutt_progress_init (&progress, _("Evaluating cache..."),
142 			M_PROGRESS_MSG, ReadInc, msgend + 1);
143 
144     snprintf (buf, sizeof (buf),
145       "UID FETCH 1:%u (UID FLAGS)", uidnext - 1);
146 
147     imap_cmd_start (idata, buf);
148 
149     rc = IMAP_CMD_CONTINUE;
150     for (msgno = msgbegin; rc == IMAP_CMD_CONTINUE; msgno++)
151     {
152       mutt_progress_update (&progress, msgno + 1, -1);
153 
154       memset (&h, 0, sizeof (h));
155       h.data = safe_calloc (1, sizeof (IMAP_HEADER_DATA));
156       do
157       {
158         mfhrc = 0;
159 
160         rc = imap_cmd_step (idata);
161         if (rc != IMAP_CMD_CONTINUE)
162 	{
163           /* suppress GCC aliasing warning */
164 	  imap_free_header_data ((void**) (void*) &h.data);
165           break;
166 	}
167 
168         /* hole in the header cache */
169         if (!evalhc)
170           continue;
171 
172         if ((mfhrc = msg_fetch_header (ctx, &h, idata->buf, NULL)) == -1)
173           continue;
174         else if (mfhrc < 0)
175 	{
176 	  imap_free_header_data ((void**) (void*) &h.data);
177           break;
178 	}
179 
180         if (!h.data->uid)
181         {
182           dprint (2, (debugfile, "imap_read_headers: skipping hcache FETCH "
183                       "response for unknown message number %d\n", h.sid));
184           mfhrc = -1;
185           continue;
186         }
187 
188         idx = h.sid - 1;
189         ctx->hdrs[idx] = imap_hcache_get (idata, h.data->uid);
190         if (ctx->hdrs[idx])
191         {
192   	  ctx->hdrs[idx]->index = idx;
193   	  /* messages which have not been expunged are ACTIVE (borrowed from mh
194   	   * folders) */
195   	  ctx->hdrs[idx]->active = 1;
196           ctx->hdrs[idx]->read = h.data->read;
197           ctx->hdrs[idx]->old = h.data->old;
198           ctx->hdrs[idx]->deleted = h.data->deleted;
199           ctx->hdrs[idx]->flagged = h.data->flagged;
200           ctx->hdrs[idx]->replied = h.data->replied;
201           ctx->hdrs[idx]->changed = h.data->changed;
202           /*  ctx->hdrs[msgno]->received is restored from mutt_hcache_restore */
203           ctx->hdrs[idx]->data = (void *) (h.data);
204 
205           ctx->msgcount++;
206           ctx->size += ctx->hdrs[idx]->content->length;
207         }
208 	else
209         {
210 	  /* bad header in the cache, we'll have to refetch. */
211           dprint (3, (debugfile, "bad cache entry at %d, giving up\n", h.sid - 1));
212           imap_free_header_data((void**) (void*) &h.data);
213           evalhc = 0;
214         }
215       }
216       while (rc != IMAP_CMD_OK && mfhrc == -1);
217       if (rc == IMAP_CMD_OK)
218         break;
219       if ((mfhrc < -1) || ((rc != IMAP_CMD_CONTINUE) && (rc != IMAP_CMD_OK)))
220       {
221         if (h.data)
222           imap_free_header_data ((void**) (void*) &h.data);
223         imap_hcache_close (idata);
224 	goto error_out_1;
225       }
226     }
227     /* could also look for first null header in case hcache is holey */
228     msgbegin = ctx->msgcount;
229   }
230 #endif /* USE_HCACHE */
231 
232   mutt_progress_init (&progress, _("Fetching message headers..."),
233 		      M_PROGRESS_MSG, ReadInc, msgend + 1);
234 
235   for (msgno = msgbegin; msgno <= msgend ; msgno++)
236   {
237     mutt_progress_update (&progress, msgno + 1, -1);
238 
239     /* we may get notification of new mail while fetching headers */
240     if (msgno + 1 > fetchlast)
241     {
242       char *cmd;
243 
244       fetchlast = msgend + 1;
245       safe_asprintf (&cmd, "FETCH %d:%d (UID FLAGS INTERNALDATE RFC822.SIZE %s)",
246                      msgno + 1, fetchlast, hdrreq);
247       imap_cmd_start (idata, cmd);
248       FREE (&cmd);
249     }
250 
251     rewind (fp);
252     memset (&h, 0, sizeof (h));
253     h.data = safe_calloc (1, sizeof (IMAP_HEADER_DATA));
254 
255     /* this DO loop does two things:
256      * 1. handles untagged messages, so we can try again on the same msg
257      * 2. fetches the tagged response at the end of the last message.
258      */
259     do
260     {
261       mfhrc = 0;
262 
263       rc = imap_cmd_step (idata);
264       if (rc != IMAP_CMD_CONTINUE)
265 	break;
266 
267       if ((mfhrc = msg_fetch_header (ctx, &h, idata->buf, fp)) == -1)
268 	continue;
269       else if (mfhrc < 0)
270 	break;
271 
272       if (!ftello (fp))
273       {
274         dprint (2, (debugfile, "msg_fetch_header: ignoring fetch response with no body\n"));
275         mfhrc = -1;
276         continue;
277       }
278 
279       /* make sure we don't get remnants from older larger message headers */
280       fputs ("\n\n", fp);
281 
282       idx = h.sid - 1;
283       if (idx > msgend)
284       {
285         dprint (1, (debugfile, "imap_read_headers: skipping FETCH response for "
286                     "unknown message number %d\n", h.sid));
287         mfhrc = -1;
288         continue;
289       }
290       /* May receive FLAGS updates in a separate untagged response (#2935) */
291       if (idx < ctx->msgcount)
292       {
293 	dprint (2, (debugfile, "imap_read_headers: message %d is not new\n",
294 		    h.sid));
295 	continue;
296       }
297 
298       ctx->hdrs[idx] = mutt_new_header ();
299 
300       ctx->hdrs[idx]->index = h.sid - 1;
301       /* messages which have not been expunged are ACTIVE (borrowed from mh
302        * folders) */
303       ctx->hdrs[idx]->active = 1;
304       ctx->hdrs[idx]->read = h.data->read;
305       ctx->hdrs[idx]->old = h.data->old;
306       ctx->hdrs[idx]->deleted = h.data->deleted;
307       ctx->hdrs[idx]->flagged = h.data->flagged;
308       ctx->hdrs[idx]->replied = h.data->replied;
309       ctx->hdrs[idx]->changed = h.data->changed;
310       ctx->hdrs[idx]->received = h.received;
311       ctx->hdrs[idx]->data = (void *) (h.data);
312 
313       if (maxuid < h.data->uid)
314         maxuid = h.data->uid;
315 
316       rewind (fp);
317       /* NOTE: if Date: header is missing, mutt_read_rfc822_header depends
318        *   on h.received being set */
319       ctx->hdrs[idx]->env = mutt_read_rfc822_header (fp, ctx->hdrs[idx],
320         0, 0);
321       /* content built as a side-effect of mutt_read_rfc822_header */
322       ctx->hdrs[idx]->content->length = h.content_length;
323       ctx->size += h.content_length;
324 
325 #if USE_HCACHE
326       imap_hcache_put (idata, ctx->hdrs[idx]);
327 #endif /* USE_HCACHE */
328 
329       ctx->msgcount++;
330     }
331     while ((rc != IMAP_CMD_OK) && ((mfhrc == -1) ||
332       ((msgno + 1) >= fetchlast)));
333 
334     if ((mfhrc < -1) || ((rc != IMAP_CMD_CONTINUE) && (rc != IMAP_CMD_OK)))
335     {
336       if (h.data)
337         imap_free_header_data ((void**) (void*) &h.data);
338 #if USE_HCACHE
339       imap_hcache_close (idata);
340 #endif
341       goto error_out_1;
342     }
343 
344     /* in case we get new mail while fetching the headers */
345     if (idata->reopen & IMAP_NEWMAIL_PENDING)
346     {
347       msgend = idata->newMailCount - 1;
348       while ((msgend) >= ctx->hdrmax)
349 	mx_alloc_memory (ctx);
350       idata->reopen &= ~IMAP_NEWMAIL_PENDING;
351       idata->newMailCount = 0;
352     }
353   }
354 
355   if (maxuid && (status = imap_mboxcache_get (idata, idata->mailbox, 0)))
356   status->uidnext = maxuid + 1;
357 
358 #if USE_HCACHE
359   mutt_hcache_store_raw (idata->hcache, "/UIDVALIDITY", &idata->uid_validity,
360                          sizeof (idata->uid_validity), imap_hcache_keylen);
361   if (maxuid && idata->uidnext < maxuid + 1)
362   {
363     dprint (2, (debugfile, "Overriding UIDNEXT: %u -> %u\n", idata->uidnext, maxuid + 1));
364     idata->uidnext = maxuid + 1;
365   }
366   if (idata->uidnext > 1)
367     mutt_hcache_store_raw (idata->hcache, "/UIDNEXT", &idata->uidnext,
368 			   sizeof (idata->uidnext), imap_hcache_keylen);
369 
370   imap_hcache_close (idata);
371 #endif /* USE_HCACHE */
372 
373   if (ctx->msgcount > oldmsgcount)
374   {
375     mx_alloc_memory(ctx);
376     mx_update_context (ctx, ctx->msgcount - oldmsgcount);
377   }
378 
379   idata->reopen |= IMAP_REOPEN_ALLOW;
380 
381   retval = msgend;
382 
383 error_out_1:
384   safe_fclose (&fp);
385 
386 error_out_0:
387   FREE (&hdrreq);
388 
389   return retval;
390 }
391 
imap_fetch_message(MESSAGE * msg,CONTEXT * ctx,int msgno)392 int imap_fetch_message (MESSAGE *msg, CONTEXT *ctx, int msgno)
393 {
394   IMAP_DATA* idata;
395   HEADER* h;
396   ENVELOPE* newenv;
397   char buf[LONG_STRING];
398   char path[_POSIX_PATH_MAX];
399   char *pc;
400   long bytes;
401   progress_t progressbar;
402   int uid;
403   int cacheno;
404   IMAP_CACHE *cache;
405   int read;
406   int rc;
407   /* Sam's weird courier server returns an OK response even when FETCH
408    * fails. Thanks Sam. */
409   short fetched = 0;
410 
411   idata = (IMAP_DATA*) ctx->data;
412   h = ctx->hdrs[msgno];
413 
414   if ((msg->fp = msg_cache_get (idata, h)))
415   {
416     if (HEADER_DATA(h)->parsed)
417       return 0;
418     else
419       goto parsemsg;
420   }
421 
422   /* we still do some caching even if imap_cachedir is unset */
423   /* see if we already have the message in our cache */
424   cacheno = HEADER_DATA(h)->uid % IMAP_CACHE_LEN;
425   cache = &idata->cache[cacheno];
426 
427   if (cache->path)
428   {
429     /* don't treat cache errors as fatal, just fall back. */
430     if (cache->uid == HEADER_DATA(h)->uid &&
431         (msg->fp = fopen (cache->path, "r")))
432       return 0;
433     else
434     {
435       unlink (cache->path);
436       FREE (&cache->path);
437     }
438   }
439 
440   if (!isendwin())
441     mutt_message _("Fetching message...");
442 
443   if (!(msg->fp = msg_cache_put (idata, h)))
444   {
445     cache->uid = HEADER_DATA(h)->uid;
446     mutt_mktemp (path, sizeof (path));
447     cache->path = safe_strdup (path);
448     if (!(msg->fp = safe_fopen (path, "w+")))
449     {
450       FREE (&cache->path);
451       return -1;
452     }
453   }
454 
455   /* mark this header as currently inactive so the command handler won't
456    * also try to update it. HACK until all this code can be moved into the
457    * command handler */
458   h->active = 0;
459 
460   snprintf (buf, sizeof (buf), "UID FETCH %u %s", HEADER_DATA(h)->uid,
461 	    (mutt_bit_isset (idata->capabilities, IMAP4REV1) ?
462 	     (option (OPTIMAPPEEK) ? "BODY.PEEK[]" : "BODY[]") :
463 	     "RFC822"));
464 
465   imap_cmd_start (idata, buf);
466   do
467   {
468     if ((rc = imap_cmd_step (idata)) != IMAP_CMD_CONTINUE)
469       break;
470 
471     pc = idata->buf;
472     pc = imap_next_word (pc);
473     pc = imap_next_word (pc);
474 
475     if (!ascii_strncasecmp ("FETCH", pc, 5))
476     {
477       while (*pc)
478       {
479 	pc = imap_next_word (pc);
480 	if (pc[0] == '(')
481 	  pc++;
482 	if (ascii_strncasecmp ("UID", pc, 3) == 0)
483 	{
484 	  pc = imap_next_word (pc);
485 	  uid = atoi (pc);
486 	  if (uid != HEADER_DATA(h)->uid)
487 	    mutt_error (_("The message index is incorrect. Try reopening the mailbox."));
488 	}
489 	else if ((ascii_strncasecmp ("RFC822", pc, 6) == 0) ||
490 		 (ascii_strncasecmp ("BODY[]", pc, 6) == 0))
491 	{
492 	  pc = imap_next_word (pc);
493 	  if (imap_get_literal_count(pc, &bytes) < 0)
494 	  {
495 	    imap_error ("imap_fetch_message()", buf);
496 	    goto bail;
497 	  }
498 	  mutt_progress_init (&progressbar, _("Fetching message..."),
499 			      M_PROGRESS_SIZE, NetInc, bytes);
500 	  if (imap_read_literal (msg->fp, idata, bytes, &progressbar) < 0)
501 	    goto bail;
502 	  /* pick up trailing line */
503 	  if ((rc = imap_cmd_step (idata)) != IMAP_CMD_CONTINUE)
504 	    goto bail;
505 	  pc = idata->buf;
506 
507 	  fetched = 1;
508 	}
509 	/* UW-IMAP will provide a FLAGS update here if the FETCH causes a
510 	 * change (eg from \Unseen to \Seen).
511 	 * Uncommitted changes in mutt take precedence. If we decide to
512 	 * incrementally update flags later, this won't stop us syncing */
513 	else if ((ascii_strncasecmp ("FLAGS", pc, 5) == 0) && !h->changed)
514 	{
515 	  if ((pc = imap_set_flags (idata, h, pc)) == NULL)
516 	    goto bail;
517 	}
518       }
519     }
520   }
521   while (rc == IMAP_CMD_CONTINUE);
522 
523   /* see comment before command start. */
524   h->active = 1;
525 
526   fflush (msg->fp);
527   if (ferror (msg->fp))
528   {
529     mutt_perror (cache->path);
530     goto bail;
531   }
532 
533   if (rc != IMAP_CMD_OK)
534     goto bail;
535 
536   if (!fetched || !imap_code (idata->buf))
537     goto bail;
538 
539   msg_cache_commit (idata, h);
540 
541   parsemsg:
542   /* Update the header information.  Previously, we only downloaded a
543    * portion of the headers, those required for the main display.
544    */
545   rewind (msg->fp);
546   /* It may be that the Status header indicates a message is read, but the
547    * IMAP server doesn't know the message has been \Seen. So we capture
548    * the server's notion of 'read' and if it differs from the message info
549    * picked up in mutt_read_rfc822_header, we mark the message (and context
550    * changed). Another possiblity: ignore Status on IMAP?*/
551   read = h->read;
552   newenv = mutt_read_rfc822_header (msg->fp, h, 0, 0);
553   mutt_merge_envelopes(h->env, &newenv);
554 
555   /* see above. We want the new status in h->read, so we unset it manually
556    * and let mutt_set_flag set it correctly, updating context. */
557   if (read != h->read)
558   {
559     h->read = read;
560     mutt_set_flag (ctx, h, M_NEW, read);
561   }
562 
563   h->lines = 0;
564   fgets (buf, sizeof (buf), msg->fp);
565   while (!feof (msg->fp))
566   {
567     h->lines++;
568     fgets (buf, sizeof (buf), msg->fp);
569   }
570 
571   h->content->length = ftell (msg->fp) - h->content->offset;
572 
573   /* This needs to be done in case this is a multipart message */
574 #if defined(HAVE_PGP) || defined(HAVE_SMIME)
575   h->security = crypt_query (h->content);
576 #endif
577 
578   mutt_clear_error();
579   rewind (msg->fp);
580   HEADER_DATA(h)->parsed = 1;
581 
582   return 0;
583 
584 bail:
585   safe_fclose (&msg->fp);
586   imap_cache_del (idata, h);
587   if (cache->path)
588   {
589     unlink (cache->path);
590     FREE (&cache->path);
591   }
592 
593   return -1;
594 }
595 
imap_append_message(CONTEXT * ctx,MESSAGE * msg)596 int imap_append_message (CONTEXT *ctx, MESSAGE *msg)
597 {
598   IMAP_DATA* idata;
599   FILE *fp;
600   char buf[LONG_STRING];
601   char mbox[LONG_STRING];
602   char mailbox[LONG_STRING];
603   char internaldate[IMAP_DATELEN];
604   size_t len;
605   progress_t progressbar;
606   size_t sent;
607   int c, last;
608   IMAP_MBOX mx;
609   int rc;
610 
611   idata = (IMAP_DATA*) ctx->data;
612 
613   if (imap_parse_path (ctx->path, &mx))
614     return -1;
615 
616   imap_fix_path (idata, mx.mbox, mailbox, sizeof (mailbox));
617   if (!*mailbox)
618     strfcpy (mailbox, "INBOX", sizeof (mailbox));
619 
620   if ((fp = fopen (msg->path, "r")) == NULL)
621   {
622     mutt_perror (msg->path);
623     goto fail;
624   }
625 
626   /* currently we set the \Seen flag on all messages, but probably we
627    * should scan the message Status header for flag info. Since we're
628    * already rereading the whole file for length it isn't any more
629    * expensive (it'd be nice if we had the file size passed in already
630    * by the code that writes the file, but that's a lot of changes.
631    * Ideally we'd have a HEADER structure with flag info here... */
632   for (last = EOF, len = 0; (c = fgetc(fp)) != EOF; last = c)
633   {
634     if(c == '\n' && last != '\r')
635       len++;
636 
637     len++;
638   }
639   rewind (fp);
640 
641   mutt_progress_init (&progressbar, _("Uploading message..."),
642 		      M_PROGRESS_SIZE, NetInc, len);
643 
644   imap_munge_mbox_name (mbox, sizeof (mbox), mailbox);
645   imap_make_date (internaldate, msg->received);
646   snprintf (buf, sizeof (buf), "APPEND %s (%s%s%s%s%s) \"%s\" {%lu}", mbox,
647 	    msg->flags.read    ? "\\Seen"      : "",
648 	    msg->flags.read && (msg->flags.replied || msg->flags.flagged) ? " " : "",
649 	    msg->flags.replied ? "\\Answered" : "",
650 	    msg->flags.replied && msg->flags.flagged ? " " : "",
651 	    msg->flags.flagged ? "\\Flagged"  : "",
652 	    internaldate,
653 	    (unsigned long) len);
654 
655   imap_cmd_start (idata, buf);
656 
657   do
658     rc = imap_cmd_step (idata);
659   while (rc == IMAP_CMD_CONTINUE);
660 
661   if (rc != IMAP_CMD_RESPOND)
662   {
663     char *pc;
664 
665     dprint (1, (debugfile, "imap_append_message(): command failed: %s\n",
666 		idata->buf));
667 
668     pc = idata->buf + SEQLEN;
669     SKIPWS (pc);
670     pc = imap_next_word (pc);
671     mutt_error ("%s", pc);
672     mutt_sleep (1);
673     safe_fclose (&fp);
674     goto fail;
675   }
676 
677   for (last = EOF, sent = len = 0; (c = fgetc(fp)) != EOF; last = c)
678   {
679     if (c == '\n' && last != '\r')
680       buf[len++] = '\r';
681 
682     buf[len++] = c;
683 
684     if (len > sizeof(buf) - 3)
685     {
686       sent += len;
687       flush_buffer(buf, &len, idata->conn);
688       mutt_progress_update (&progressbar, sent, -1);
689     }
690   }
691 
692   if (len)
693     flush_buffer(buf, &len, idata->conn);
694 
695   mutt_socket_write (idata->conn, "\r\n");
696   safe_fclose (&fp);
697 
698   do
699     rc = imap_cmd_step (idata);
700   while (rc == IMAP_CMD_CONTINUE);
701 
702   if (!imap_code (idata->buf))
703   {
704     char *pc;
705 
706     dprint (1, (debugfile, "imap_append_message(): command failed: %s\n",
707 		idata->buf));
708     pc = idata->buf + SEQLEN;
709     SKIPWS (pc);
710     pc = imap_next_word (pc);
711     mutt_error ("%s", pc);
712     mutt_sleep (1);
713     goto fail;
714   }
715 
716   FREE (&mx.mbox);
717   return 0;
718 
719  fail:
720   FREE (&mx.mbox);
721   return -1;
722 }
723 
724 /* imap_copy_messages: use server COPY command to copy messages to another
725  *   folder.
726  *   Return codes:
727  *      -1: error
728  *       0: success
729  *       1: non-fatal error - try fetch/append */
imap_copy_messages(CONTEXT * ctx,HEADER * h,char * dest,int delete)730 int imap_copy_messages (CONTEXT* ctx, HEADER* h, char* dest, int delete)
731 {
732   IMAP_DATA* idata;
733   BUFFER cmd, sync_cmd;
734   char mbox[LONG_STRING];
735   char mmbox[LONG_STRING];
736   char prompt[LONG_STRING];
737   int rc;
738   int n;
739   IMAP_MBOX mx;
740   int err_continue = M_NO;
741   int triedcreate = 0;
742 
743   idata = (IMAP_DATA*) ctx->data;
744 
745   if (imap_parse_path (dest, &mx))
746   {
747     dprint (1, (debugfile, "imap_copy_messages: bad destination %s\n", dest));
748     return -1;
749   }
750 
751   /* check that the save-to folder is in the same account */
752   if (!mutt_account_match (&(CTX_DATA->conn->account), &(mx.account)))
753   {
754     dprint (3, (debugfile, "imap_copy_messages: %s not same server as %s\n",
755       dest, ctx->path));
756     return 1;
757   }
758 
759   if (h && h->attach_del)
760   {
761     dprint (3, (debugfile, "imap_copy_messages: Message contains attachments to be deleted\n"));
762     return 1;
763   }
764 
765   imap_fix_path (idata, mx.mbox, mbox, sizeof (mbox));
766   if (!*mbox)
767     strfcpy (mbox, "INBOX", sizeof (mbox));
768   imap_munge_mbox_name (mmbox, sizeof (mmbox), mbox);
769 
770   /* loop in case of TRYCREATE */
771   do
772   {
773     memset (&sync_cmd, 0, sizeof (sync_cmd));
774     memset (&cmd, 0, sizeof (cmd));
775 
776     /* Null HEADER* means copy tagged messages */
777     if (!h)
778     {
779       /* if any messages have attachments to delete, fall through to FETCH
780        * and APPEND. TODO: Copy what we can with COPY, fall through for the
781        * remainder. */
782       for (n = 0; n < ctx->msgcount; n++)
783       {
784         if (ctx->hdrs[n]->tagged && ctx->hdrs[n]->attach_del)
785         {
786           dprint (3, (debugfile, "imap_copy_messages: Message contains attachments to be deleted\n"));
787           return 1;
788         }
789 
790         if (ctx->hdrs[n]->tagged && ctx->hdrs[n]->active &&
791             ctx->hdrs[n]->changed)
792         {
793           rc = imap_sync_message (idata, ctx->hdrs[n], &sync_cmd, &err_continue);
794           if (rc < 0)
795           {
796             dprint (1, (debugfile, "imap_copy_messages: could not sync\n"));
797             goto out;
798           }
799         }
800       }
801 
802       rc = imap_exec_msgset (idata, "UID COPY", mmbox, M_TAG, 0, 0);
803       if (!rc)
804       {
805         dprint (1, (debugfile, "imap_copy_messages: No messages tagged\n"));
806         rc = -1;
807         goto out;
808       }
809       else if (rc < 0)
810       {
811         dprint (1, (debugfile, "could not queue copy\n"));
812         goto out;
813       }
814       else
815         mutt_message (_("Copying %d messages to %s..."), rc, mbox);
816     }
817     else
818     {
819       mutt_message (_("Copying message %d to %s..."), h->index+1, mbox);
820       mutt_buffer_printf (&cmd, "UID COPY %u %s", HEADER_DATA (h)->uid, mmbox);
821 
822       if (h->active && h->changed)
823       {
824         rc = imap_sync_message (idata, h, &sync_cmd, &err_continue);
825         if (rc < 0)
826         {
827           dprint (1, (debugfile, "imap_copy_messages: could not sync\n"));
828           goto out;
829         }
830       }
831       if ((rc = imap_exec (idata, cmd.data, IMAP_CMD_QUEUE)) < 0)
832       {
833         dprint (1, (debugfile, "could not queue copy\n"));
834         goto out;
835       }
836     }
837 
838     /* let's get it on */
839     rc = imap_exec (idata, NULL, IMAP_CMD_FAIL_OK);
840     if (rc == -2)
841     {
842       if (triedcreate)
843       {
844         dprint (1, (debugfile, "Already tried to create mailbox %s\n", mbox));
845         break;
846       }
847       /* bail out if command failed for reasons other than nonexistent target */
848       if (ascii_strncasecmp (imap_get_qualifier (idata->buf), "[TRYCREATE]", 11))
849         break;
850       dprint (3, (debugfile, "imap_copy_messages: server suggests TRYCREATE\n"));
851       snprintf (prompt, sizeof (prompt), _("Create %s?"), mbox);
852       if (option (OPTCONFIRMCREATE) && mutt_yesorno (prompt, 1) < 1)
853       {
854         mutt_clear_error ();
855         goto out;
856       }
857       if (imap_create_mailbox (idata, mbox) < 0)
858         break;
859       triedcreate = 1;
860     }
861   }
862   while (rc == -2);
863 
864   if (rc != 0)
865   {
866     imap_error ("imap_copy_messages", idata->buf);
867     goto out;
868   }
869 
870   /* cleanup */
871   if (delete)
872   {
873     if (!h)
874       for (n = 0; n < ctx->msgcount; n++)
875       {
876         if (ctx->hdrs[n]->tagged)
877         {
878           mutt_set_flag (ctx, ctx->hdrs[n], M_DELETE, 1);
879           if (option (OPTDELETEUNTAG))
880             mutt_set_flag (ctx, ctx->hdrs[n], M_TAG, 0);
881         }
882       }
883     else
884     {
885       mutt_set_flag (ctx, h, M_DELETE, 1);
886       if (option (OPTDELETEUNTAG))
887         mutt_set_flag (ctx, h, M_TAG, 0);
888     }
889   }
890 
891   rc = 0;
892 
893  out:
894   if (cmd.data)
895     FREE (&cmd.data);
896   if (sync_cmd.data)
897     FREE (&sync_cmd.data);
898   FREE (&mx.mbox);
899 
900   return rc < 0 ? -1 : rc;
901 }
902 
msg_cache_open(IMAP_DATA * idata)903 static body_cache_t *msg_cache_open (IMAP_DATA *idata)
904 {
905   char mailbox[_POSIX_PATH_MAX];
906 
907   if (idata->bcache)
908     return idata->bcache;
909 
910   imap_cachepath (idata, idata->mailbox, mailbox, sizeof (mailbox));
911 
912   return mutt_bcache_open (&idata->conn->account, mailbox);
913 }
914 
msg_cache_get(IMAP_DATA * idata,HEADER * h)915 static FILE* msg_cache_get (IMAP_DATA* idata, HEADER* h)
916 {
917   char id[_POSIX_PATH_MAX];
918 
919   if (!idata || !h)
920     return NULL;
921 
922   idata->bcache = msg_cache_open (idata);
923   snprintf (id, sizeof (id), "%u-%u", idata->uid_validity, HEADER_DATA(h)->uid);
924   return mutt_bcache_get (idata->bcache, id);
925 }
926 
msg_cache_put(IMAP_DATA * idata,HEADER * h)927 static FILE* msg_cache_put (IMAP_DATA* idata, HEADER* h)
928 {
929   char id[_POSIX_PATH_MAX];
930 
931   if (!idata || !h)
932     return NULL;
933 
934   idata->bcache = msg_cache_open (idata);
935   snprintf (id, sizeof (id), "%u-%u", idata->uid_validity, HEADER_DATA(h)->uid);
936   return mutt_bcache_put (idata->bcache, id, 1);
937 }
938 
msg_cache_commit(IMAP_DATA * idata,HEADER * h)939 static int msg_cache_commit (IMAP_DATA* idata, HEADER* h)
940 {
941   char id[_POSIX_PATH_MAX];
942 
943   if (!idata || !h)
944     return -1;
945 
946   idata->bcache = msg_cache_open (idata);
947   snprintf (id, sizeof (id), "%u-%u", idata->uid_validity, HEADER_DATA(h)->uid);
948 
949   return mutt_bcache_commit (idata->bcache, id);
950 }
951 
imap_cache_del(IMAP_DATA * idata,HEADER * h)952 int imap_cache_del (IMAP_DATA* idata, HEADER* h)
953 {
954   char id[_POSIX_PATH_MAX];
955 
956   if (!idata || !h)
957     return -1;
958 
959   idata->bcache = msg_cache_open (idata);
960   snprintf (id, sizeof (id), "%u-%u", idata->uid_validity, HEADER_DATA(h)->uid);
961   return mutt_bcache_del (idata->bcache, id);
962 }
963 
msg_cache_clean_cb(const char * id,body_cache_t * bcache,void * data)964 static int msg_cache_clean_cb (const char* id, body_cache_t* bcache, void* data)
965 {
966   unsigned int uv, uid, n;
967   IMAP_DATA* idata = (IMAP_DATA*)data;
968 
969   if (sscanf (id, "%u-%u", &uv, &uid) != 2)
970     return 0;
971 
972   /* bad UID */
973   if (uv != idata->uid_validity)
974     mutt_bcache_del (bcache, id);
975 
976   /* TODO: presort UIDs, walk in order */
977   for (n = 0; n < idata->ctx->msgcount; n++)
978   {
979     if (uid == HEADER_DATA(idata->ctx->hdrs[n])->uid)
980       return 0;
981   }
982   mutt_bcache_del (bcache, id);
983 
984   return 0;
985 }
986 
imap_cache_clean(IMAP_DATA * idata)987 int imap_cache_clean (IMAP_DATA* idata)
988 {
989   idata->bcache = msg_cache_open (idata);
990   mutt_bcache_list (idata->bcache, msg_cache_clean_cb, idata);
991 
992   return 0;
993 }
994 
995 /* imap_add_keywords: concatenate custom IMAP tags to list, if they
996  *   appear in the folder flags list. Why wouldn't they? */
imap_add_keywords(char * s,HEADER * h,LIST * mailbox_flags,size_t slen)997 void imap_add_keywords (char* s, HEADER* h, LIST* mailbox_flags, size_t slen)
998 {
999   LIST *keywords;
1000 
1001   if (!mailbox_flags || !HEADER_DATA(h) || !HEADER_DATA(h)->keywords)
1002     return;
1003 
1004   keywords = HEADER_DATA(h)->keywords->next;
1005 
1006   while (keywords)
1007   {
1008     if (imap_has_flag (mailbox_flags, keywords->data))
1009     {
1010       safe_strcat (s, slen, keywords->data);
1011       safe_strcat (s, slen, " ");
1012     }
1013     keywords = keywords->next;
1014   }
1015 }
1016 
1017 /* imap_free_header_data: free IMAP_HEADER structure */
imap_free_header_data(void ** data)1018 void imap_free_header_data (void** data)
1019 {
1020   /* this should be safe even if the list wasn't used */
1021   mutt_free_list (&(((IMAP_HEADER_DATA*) *data)->keywords));
1022 
1023   FREE (data);		/* __FREE_CHECKED__ */
1024 }
1025 
1026 /* imap_set_flags: fill out the message header according to the flags from
1027  *   the server. Expects a flags line of the form "FLAGS (flag flag ...)" */
imap_set_flags(IMAP_DATA * idata,HEADER * h,char * s)1028 char* imap_set_flags (IMAP_DATA* idata, HEADER* h, char* s)
1029 {
1030   CONTEXT* ctx = idata->ctx;
1031   IMAP_HEADER newh;
1032   IMAP_HEADER_DATA* hd;
1033   unsigned char readonly;
1034 
1035   memset (&newh, 0, sizeof (newh));
1036   hd = h->data;
1037   newh.data = hd;
1038 
1039   dprint (2, (debugfile, "imap_fetch_message: parsing FLAGS\n"));
1040   if ((s = msg_parse_flags (&newh, s)) == NULL)
1041     return NULL;
1042 
1043   /* YAUH (yet another ugly hack): temporarily set context to
1044    * read-write even if it's read-only, so *server* updates of
1045    * flags can be processed by mutt_set_flag. ctx->changed must
1046    * be restored afterwards */
1047   readonly = ctx->readonly;
1048   ctx->readonly = 0;
1049 
1050   mutt_set_flag (ctx, h, M_NEW, !(hd->read || hd->old));
1051   mutt_set_flag (ctx, h, M_OLD, hd->old);
1052   mutt_set_flag (ctx, h, M_READ, hd->read);
1053   mutt_set_flag (ctx, h, M_DELETE, hd->deleted);
1054   mutt_set_flag (ctx, h, M_FLAG, hd->flagged);
1055   mutt_set_flag (ctx, h, M_REPLIED, hd->replied);
1056 
1057   /* this message is now definitively *not* changed (mutt_set_flag
1058    * marks things changed as a side-effect) */
1059   h->changed = 0;
1060   ctx->changed &= ~readonly;
1061   ctx->readonly = readonly;
1062 
1063   return s;
1064 }
1065 
1066 
1067 /* msg_fetch_header: import IMAP FETCH response into an IMAP_HEADER.
1068  *   Expects string beginning with * n FETCH.
1069  *   Returns:
1070  *      0 on success
1071  *     -1 if the string is not a fetch response
1072  *     -2 if the string is a corrupt fetch response */
msg_fetch_header(CONTEXT * ctx,IMAP_HEADER * h,char * buf,FILE * fp)1073 static int msg_fetch_header (CONTEXT* ctx, IMAP_HEADER* h, char* buf, FILE* fp)
1074 {
1075   IMAP_DATA* idata;
1076   long bytes;
1077   int rc = -1; /* default now is that string isn't FETCH response*/
1078 
1079   idata = (IMAP_DATA*) ctx->data;
1080 
1081   if (buf[0] != '*')
1082     return rc;
1083 
1084   /* skip to message number */
1085   buf = imap_next_word (buf);
1086   h->sid = atoi (buf);
1087 
1088   /* find FETCH tag */
1089   buf = imap_next_word (buf);
1090   if (ascii_strncasecmp ("FETCH", buf, 5))
1091     return rc;
1092 
1093   rc = -2; /* we've got a FETCH response, for better or worse */
1094   if (!(buf = strchr (buf, '(')))
1095     return rc;
1096   buf++;
1097 
1098   /* FIXME: current implementation - call msg_parse_fetch - if it returns -2,
1099    *   read header lines and call it again. Silly. */
1100   if ((rc = msg_parse_fetch (h, buf)) != -2 || !fp)
1101     return rc;
1102 
1103   if (imap_get_literal_count (buf, &bytes) == 0)
1104   {
1105     imap_read_literal (fp, idata, bytes, NULL);
1106 
1107     /* we may have other fields of the FETCH _after_ the literal
1108      * (eg Domino puts FLAGS here). Nothing wrong with that, either.
1109      * This all has to go - we should accept literals and nonliterals
1110      * interchangeably at any time. */
1111     if (imap_cmd_step (idata) != IMAP_CMD_CONTINUE)
1112       return rc;
1113 
1114     if (msg_parse_fetch (h, idata->buf) == -1)
1115       return rc;
1116   }
1117 
1118   rc = 0; /* success */
1119 
1120   /* subtract headers from message size - unfortunately only the subset of
1121    * headers we've requested. */
1122   h->content_length -= bytes;
1123 
1124   return rc;
1125 }
1126 
1127 /* msg_parse_fetch: handle headers returned from header fetch */
msg_parse_fetch(IMAP_HEADER * h,char * s)1128 static int msg_parse_fetch (IMAP_HEADER *h, char *s)
1129 {
1130   char tmp[SHORT_STRING];
1131   char *ptmp;
1132 
1133   if (!s)
1134     return -1;
1135 
1136   while (*s)
1137   {
1138     SKIPWS (s);
1139 
1140     if (ascii_strncasecmp ("FLAGS", s, 5) == 0)
1141     {
1142       if ((s = msg_parse_flags (h, s)) == NULL)
1143         return -1;
1144     }
1145     else if (ascii_strncasecmp ("UID", s, 3) == 0)
1146     {
1147       s += 3;
1148       SKIPWS (s);
1149       h->data->uid = (unsigned int) atoi (s);
1150 
1151       s = imap_next_word (s);
1152     }
1153     else if (ascii_strncasecmp ("INTERNALDATE", s, 12) == 0)
1154     {
1155       s += 12;
1156       SKIPWS (s);
1157       if (*s != '\"')
1158       {
1159         dprint (1, (debugfile, "msg_parse_fetch(): bogus INTERNALDATE entry: %s\n", s));
1160         return -1;
1161       }
1162       s++;
1163       ptmp = tmp;
1164       while (*s && *s != '\"')
1165         *ptmp++ = *s++;
1166       if (*s != '\"')
1167         return -1;
1168       s++; /* skip past the trailing " */
1169       *ptmp = 0;
1170       h->received = imap_parse_date (tmp);
1171     }
1172     else if (ascii_strncasecmp ("RFC822.SIZE", s, 11) == 0)
1173     {
1174       s += 11;
1175       SKIPWS (s);
1176       ptmp = tmp;
1177       while (isdigit ((unsigned char) *s))
1178         *ptmp++ = *s++;
1179       *ptmp = 0;
1180       h->content_length = atoi (tmp);
1181     }
1182     else if (!ascii_strncasecmp ("BODY", s, 4) ||
1183       !ascii_strncasecmp ("RFC822.HEADER", s, 13))
1184     {
1185       /* handle above, in msg_fetch_header */
1186       return -2;
1187     }
1188     else if (*s == ')')
1189       s++; /* end of request */
1190     else if (*s)
1191     {
1192       /* got something i don't understand */
1193       imap_error ("msg_parse_fetch", s);
1194       return -1;
1195     }
1196   }
1197 
1198   return 0;
1199 }
1200 
1201 /* msg_parse_flags: read a FLAGS token into an IMAP_HEADER */
msg_parse_flags(IMAP_HEADER * h,char * s)1202 static char* msg_parse_flags (IMAP_HEADER* h, char* s)
1203 {
1204   IMAP_HEADER_DATA* hd = h->data;
1205 
1206   /* sanity-check string */
1207   if (ascii_strncasecmp ("FLAGS", s, 5) != 0)
1208   {
1209     dprint (1, (debugfile, "msg_parse_flags: not a FLAGS response: %s\n",
1210       s));
1211     return NULL;
1212   }
1213   s += 5;
1214   SKIPWS(s);
1215   if (*s != '(')
1216   {
1217     dprint (1, (debugfile, "msg_parse_flags: bogus FLAGS response: %s\n",
1218       s));
1219     return NULL;
1220   }
1221   s++;
1222 
1223   mutt_free_list (&hd->keywords);
1224   hd->deleted = hd->flagged = hd->replied = hd->read = hd->old = 0;
1225 
1226   /* start parsing */
1227   while (*s && *s != ')')
1228   {
1229     if (ascii_strncasecmp ("\\deleted", s, 8) == 0)
1230     {
1231       s += 8;
1232       hd->deleted = 1;
1233     }
1234     else if (ascii_strncasecmp ("\\flagged", s, 8) == 0)
1235     {
1236       s += 8;
1237       hd->flagged = 1;
1238     }
1239     else if (ascii_strncasecmp ("\\answered", s, 9) == 0)
1240     {
1241       s += 9;
1242       hd->replied = 1;
1243     }
1244     else if (ascii_strncasecmp ("\\seen", s, 5) == 0)
1245     {
1246       s += 5;
1247       hd->read = 1;
1248     }
1249     else if (ascii_strncasecmp ("\\recent", s, 7) == 0)
1250       s += 7;
1251     else if (ascii_strncasecmp ("old", s, 3) == 0)
1252     {
1253       s += 3;
1254       hd->old = 1;
1255     }
1256     else
1257     {
1258       /* store custom flags as well */
1259       char ctmp;
1260       char* flag_word = s;
1261 
1262       if (!hd->keywords)
1263         hd->keywords = mutt_new_list ();
1264 
1265       while (*s && !ISSPACE (*s) && *s != ')')
1266         s++;
1267       ctmp = *s;
1268       *s = '\0';
1269       mutt_add_list (hd->keywords, flag_word);
1270       *s = ctmp;
1271     }
1272     SKIPWS(s);
1273   }
1274 
1275   /* wrap up, or note bad flags response */
1276   if (*s == ')')
1277     s++;
1278   else
1279   {
1280     dprint (1, (debugfile,
1281       "msg_parse_flags: Unterminated FLAGS response: %s\n", s));
1282     return NULL;
1283   }
1284 
1285   return s;
1286 }
1287 
flush_buffer(char * buf,size_t * len,CONNECTION * conn)1288 static void flush_buffer(char *buf, size_t *len, CONNECTION *conn)
1289 {
1290   buf[*len] = '\0';
1291   mutt_socket_write_n(conn, buf, *len);
1292   *len = 0;
1293 }
1294