afcc9b1cdfb9e16ff49e08e7de611bed7cdcb2f4
[apps/madmutt.git] / postpone.c
1 /*
2  * Copyright notice from original mutt:
3  * Copyright (C) 1996-2002 Michael R. Elkins <me@mutt.org>
4  * Copyright (C) 1999-2000 Thomas Roessler <roessler@does-not-exist.org>
5  *
6  * This file is part of mutt-ng, see http://www.muttng.org/.
7  * It's licensed under the GNU General Public License,
8  * please see the file GPL in the top level source directory.
9  */
10
11 #if HAVE_CONFIG_H
12 # include "config.h"
13 #endif
14
15 #include <lib-lib/mem.h>
16 #include <lib-lib/str.h>
17 #include <lib-lib/ascii.h>
18 #include <lib-lib/macros.h>
19 #include <lib-lib/file.h>
20 #include <lib-lib/mapping.h>
21
22 #include <lib-mime/mime.h>
23
24 #include "mutt.h"
25 #include "enter.h"
26 #include "handler.h"
27 #include "mutt_menu.h"
28 #include "rfc1524.h"
29 #include "sort.h"
30 #include "thread.h"
31 #include "mx.h"
32 #ifdef USE_IMAP
33 #include "imap.h"
34 #include "imap/mx_imap.h"
35 #endif
36 #include "mutt_crypt.h"
37
38 #include "lib/debug.h"
39
40 #include <ctype.h>
41 #include <unistd.h>
42 #include <string.h>
43 #include <sys/stat.h>
44
45 static struct mapping_t PostponeHelp[] = {
46   {N_("Exit"),  OP_EXIT},
47   {N_("Del"),   OP_DELETE},
48   {N_("Undel"), OP_UNDELETE},
49   {N_("Help"),  OP_HELP},
50   {NULL,        OP_NULL}
51 };
52
53
54
55 static short PostCount = 0;
56 static CONTEXT *PostContext = NULL;
57 static short UpdateNumPostponed = 0;
58
59 /* Return the number of postponed messages.
60  * if force is 0, use a cached value if it is costly to get a fresh
61  * count (IMAP) - else check.
62  */
63 int mutt_num_postponed (int force)
64 {
65   struct stat st;
66   CONTEXT ctx;
67
68   static time_t LastModify = 0;
69   static char *OldPostponed = NULL;
70
71   if (UpdateNumPostponed) {
72     UpdateNumPostponed = 0;
73     force = 1;
74   }
75
76   if (Postponed != OldPostponed) {
77     OldPostponed = Postponed;
78     LastModify = 0;
79     force = 1;
80   }
81
82   if (!Postponed)
83     return 0;
84
85 #ifdef USE_IMAP
86   /* LastModify is useless for IMAP */
87   if (imap_is_magic (Postponed, NULL) == M_IMAP) {
88     if (force) {
89       short newpc;
90
91       newpc = imap_mailbox_check (Postponed, 0);
92       if (newpc >= 0) {
93         PostCount = newpc;
94         debug_print (2, ("%d postponed IMAP messages found.\n", PostCount));
95       }
96       else
97         debug_print (2, ("using old IMAP postponed count.\n"));
98     }
99     return PostCount;
100   }
101 #endif
102
103   if (stat (Postponed, &st) == -1) {
104     PostCount = 0;
105     LastModify = 0;
106     return (0);
107   }
108
109   if (S_ISDIR (st.st_mode)) {
110     /* if we have a maildir mailbox, we need to stat the "new" dir */
111
112     char buf[_POSIX_PATH_MAX];
113
114     snprintf (buf, sizeof (buf), "%s/new", Postponed);
115     if (access (buf, F_OK) == 0 && stat (buf, &st) == -1) {
116       PostCount = 0;
117       LastModify = 0;
118       return 0;
119     }
120   }
121
122   if (LastModify < st.st_mtime) {
123 #ifdef USE_NNTP
124     int optnews = option (OPTNEWS);
125 #endif
126     LastModify = st.st_mtime;
127
128     if (access (Postponed, R_OK | F_OK) != 0)
129       return (PostCount = 0);
130 #ifdef USE_NNTP
131     if (optnews)
132       unset_option (OPTNEWS);
133 #endif
134     if (mx_open_mailbox (Postponed, M_NOSORT | M_QUIET, &ctx) == NULL)
135       PostCount = 0;
136     else
137       PostCount = ctx.msgcount;
138     mx_fastclose_mailbox (&ctx);
139 #ifdef USE_NNTP
140     if (optnews)
141       set_option (OPTNEWS);
142 #endif
143   }
144
145   return (PostCount);
146 }
147
148 void mutt_update_num_postponed (void)
149 {
150   UpdateNumPostponed = 1;
151 }
152
153 static void post_entry (char *s, size_t slen, MUTTMENU * menu, int entry)
154 {
155   CONTEXT *ctx = (CONTEXT *) menu->data;
156
157   _mutt_make_string (s, slen, NONULL (HdrFmt), ctx, ctx->hdrs[entry],
158                      M_FORMAT_ARROWCURSOR);
159 }
160
161 static HEADER *select_msg (void)
162 {
163   MUTTMENU *menu;
164   int i, done = 0, r = -1;
165   char helpstr[SHORT_STRING];
166   short orig_sort;
167
168   menu = mutt_new_menu ();
169   menu->make_entry = post_entry;
170   menu->menu = MENU_POST;
171   menu->max = PostContext->msgcount;
172   menu->title = _("Postponed Messages");
173   menu->data = PostContext;
174   menu->help =
175     mutt_compile_help (helpstr, sizeof (helpstr), MENU_POST, PostponeHelp);
176
177   /* The postponed mailbox is setup to have sorting disabled, but the global
178    * Sort variable may indicate something different.   Sorting has to be
179    * disabled while the postpone menu is being displayed. */
180   orig_sort = Sort;
181   Sort = SORT_ORDER;
182
183   while (!done) {
184     switch (i = mutt_menuLoop (menu)) {
185     case OP_DELETE:
186     case OP_UNDELETE:
187       mutt_set_flag (PostContext, PostContext->hdrs[menu->current], M_DELETE,
188                      (i == OP_DELETE) ? 1 : 0);
189       PostCount = PostContext->msgcount - PostContext->deleted;
190       if (option (OPTRESOLVE) && menu->current < menu->max - 1) {
191         menu->oldcurrent = menu->current;
192         menu->current++;
193         if (menu->current >= menu->top + menu->pagelen) {
194           menu->top = menu->current;
195           menu->redraw = REDRAW_INDEX | REDRAW_STATUS;
196         }
197         else
198           menu->redraw |= REDRAW_MOTION_RESYNCH;
199       }
200       else
201         menu->redraw = REDRAW_CURRENT;
202       break;
203
204     case OP_GENERIC_SELECT_ENTRY:
205       r = menu->current;
206       done = 1;
207       break;
208
209     case OP_EXIT:
210       done = 1;
211       break;
212     }
213   }
214
215   Sort = orig_sort;
216   mutt_menuDestroy (&menu);
217   return (r > -1 ? PostContext->hdrs[r] : NULL);
218 }
219
220 /* args:
221  *      ctx     Context info, used when recalling a message to which
222  *              we reply.
223  *      hdr     envelope/attachment info for recalled message
224  *      cur     if message was a reply, `cur' is set to the message which
225  *              `hdr' is in reply to
226  *      fcc     fcc for the recalled message
227  *      fcclen  max length of fcc
228  *
229  * return vals:
230  *      -1              error/no messages
231  *      0               normal exit
232  *      SENDREPLY       recalled message is a reply
233  */
234 int mutt_get_postponed (CONTEXT * ctx, HEADER * hdr, HEADER ** cur, char *fcc,
235                         size_t fcclen)
236 {
237   HEADER *h;
238   int code = SENDPOSTPONED;
239   LIST *tmp;
240   LIST *last = NULL;
241   LIST *next;
242   char *p;
243   int opt_delete;
244
245   if (!Postponed)
246     return (-1);
247
248   if ((PostContext = mx_open_mailbox (Postponed, M_NOSORT, NULL)) == NULL) {
249     PostCount = 0;
250     mutt_error _("No postponed messages.");
251
252     return (-1);
253   }
254
255   if (!PostContext->msgcount) {
256     PostCount = 0;
257     mx_close_mailbox (PostContext, NULL);
258     p_delete(&PostContext);
259     mutt_error _("No postponed messages.");
260
261     return (-1);
262   }
263
264   if (PostContext->msgcount == 1) {
265     /* only one message, so just use that one. */
266     h = PostContext->hdrs[0];
267   }
268   else if ((h = select_msg ()) == NULL) {
269     mx_close_mailbox (PostContext, NULL);
270     p_delete(&PostContext);
271     return (-1);
272   }
273
274   if (mutt_prepare_template (NULL, PostContext, hdr, h, 0) < 0) {
275     mx_fastclose_mailbox (PostContext);
276     p_delete(&PostContext);
277     return (-1);
278   }
279
280   /* finished with this message, so delete it. */
281   mutt_set_flag (PostContext, h, M_DELETE, 1);
282
283   /* and consider it saved, so that it won't be moved to the trash folder */
284   mutt_set_flag (PostContext, h, M_APPENDED, 1);
285
286   /* update the count for the status display */
287   PostCount = PostContext->msgcount - PostContext->deleted;
288
289   /* avoid the "purge deleted messages" prompt */
290   opt_delete = quadoption (OPT_DELETE);
291   set_quadoption (OPT_DELETE, M_YES);
292   mx_close_mailbox (PostContext, NULL);
293   set_quadoption (OPT_DELETE, opt_delete);
294
295   p_delete(&PostContext);
296
297   for (tmp = hdr->env->userhdrs; tmp;) {
298     if (ascii_strncasecmp ("X-Mutt-References:", tmp->data, 18) == 0) {
299       if (ctx) {
300         /* if a mailbox is currently open, look to see if the orignal message
301            the user attempted to reply to is in this mailbox */
302         p = vskipspaces(tmp->data + 18);
303         if (!ctx->id_hash)
304           ctx->id_hash = mutt_make_id_hash (ctx);
305         *cur = hash_find (ctx->id_hash, p);
306       }
307
308       /* Remove the X-Mutt-References: header field. */
309       next = tmp->next;
310       if (last)
311         last->next = tmp->next;
312       else
313         hdr->env->userhdrs = tmp->next;
314       tmp->next = NULL;
315       mutt_free_list (&tmp);
316       tmp = next;
317       if (*cur)
318         code |= SENDREPLY;
319     }
320     else if (ascii_strncasecmp ("X-Mutt-Fcc:", tmp->data, 11) == 0) {
321       p = vskipspaces(tmp->data + 11);
322       m_strcpy(fcc, fcclen, p);
323       mutt_pretty_mailbox (fcc);
324
325       /* remove the X-Mutt-Fcc: header field */
326       next = tmp->next;
327       if (last)
328         last->next = tmp->next;
329       else
330         hdr->env->userhdrs = tmp->next;
331       tmp->next = NULL;
332       mutt_free_list (&tmp);
333       tmp = next;
334     }
335     else if ((m_strncmp("Pgp:", tmp->data, 4) == 0       /* this is generated
336                                                           * by old mutt versions
337                                                           */
338                  || m_strncmp("X-Mutt-PGP:", tmp->data, 11) == 0)) {
339       hdr->security = mutt_parse_crypt_hdr (strchr (tmp->data, ':') + 1, 1);
340       hdr->security |= APPLICATION_PGP;
341
342       /* remove the pgp field */
343       next = tmp->next;
344       if (last)
345         last->next = tmp->next;
346       else
347         hdr->env->userhdrs = tmp->next;
348       tmp->next = NULL;
349       mutt_free_list (&tmp);
350       tmp = next;
351     }
352     else if (m_strncmp("X-Mutt-SMIME:", tmp->data, 13) == 0) {
353       hdr->security = mutt_parse_crypt_hdr (strchr (tmp->data, ':') + 1, 1);
354       hdr->security |= APPLICATION_SMIME;
355
356       /* remove the smime field */
357       next = tmp->next;
358       if (last)
359         last->next = tmp->next;
360       else
361         hdr->env->userhdrs = tmp->next;
362       tmp->next = NULL;
363       mutt_free_list (&tmp);
364       tmp = next;
365     }
366
367 #ifdef MIXMASTER
368     else if (m_strncmp("X-Mutt-Mix:", tmp->data, 11) == 0) {
369       char *t;
370
371       mutt_free_list (&hdr->chain);
372
373       t = strtok (tmp->data + 11, " \t\n");
374       while (t) {
375         hdr->chain = mutt_add_list (hdr->chain, t);
376         t = strtok (NULL, " \t\n");
377       }
378
379       next = tmp->next;
380       if (last)
381         last->next = tmp->next;
382       else
383         hdr->env->userhdrs = tmp->next;
384       tmp->next = NULL;
385       mutt_free_list (&tmp);
386       tmp = next;
387     }
388 #endif
389
390     else {
391       last = tmp;
392       tmp = tmp->next;
393     }
394   }
395   return (code);
396 }
397
398
399
400 int mutt_parse_crypt_hdr (char *p, int set_signas)
401 {
402   int pgp = 0;
403   char pgp_sign_as[LONG_STRING] = "\0", *q;
404   char smime_cryptalg[LONG_STRING] = "\0";
405
406   for (p = vskipspaces(p); *p; p++) {
407     switch (*p) {
408     case 'e':
409     case 'E':
410       pgp |= ENCRYPT;
411       break;
412
413     case 's':
414     case 'S':
415       pgp |= SIGN;
416       q = pgp_sign_as;
417
418       if (*(p + 1) == '<') {
419         for (p += 2;
420              *p && *p != '>' && q < pgp_sign_as + sizeof (pgp_sign_as) - 1;
421              *q++ = *p++);
422
423         if (*p != '>') {
424           mutt_error _("Illegal PGP header");
425
426           return 0;
427         }
428       }
429
430       *q = '\0';
431       break;
432
433       /* This used to be the micalg parameter.
434        * 
435        * It's no longer needed, so we just skip the parameter in order
436        * to be able to recall old messages.
437        */
438     case 'm':
439     case 'M':
440       if (*(p + 1) == '<') {
441         for (p += 2; *p && *p != '>'; p++);
442         if (*p != '>') {
443           mutt_error _("Illegal PGP header");
444
445           return 0;
446         }
447       }
448
449       break;
450
451
452     case 'c':
453     case 'C':
454       q = smime_cryptalg;
455
456       if (*(p + 1) == '<') {
457         for (p += 2;
458              *p && *p != '>'
459              && q < smime_cryptalg + sizeof (smime_cryptalg) - 1;
460              *q++ = *p++);
461
462         if (*p != '>') {
463           mutt_error _("Illegal S/MIME header");
464
465           return 0;
466         }
467       }
468
469       *q = '\0';
470       break;
471
472     case 'i':
473     case 'I':
474       pgp |= INLINE;
475       break;
476
477     default:
478       mutt_error _("Illegal PGP header");
479       return 0;
480     }
481
482   }
483
484   /* the cryptalg field must not be empty */
485   if (*smime_cryptalg)
486     m_strreplace(&SmimeCryptAlg, smime_cryptalg);
487
488   if (set_signas || *pgp_sign_as)
489     m_strreplace(&PgpSignAs, pgp_sign_as);
490
491   return pgp;
492 }
493
494
495
496 int mutt_prepare_template (FILE * fp, CONTEXT * ctx, HEADER * newhdr,
497                            HEADER * hdr, short weed)
498 {
499   MESSAGE *msg = NULL;
500   char file[_POSIX_PATH_MAX];
501   BODY *b;
502   FILE *bfp;
503
504   int rv = -1;
505   STATE s;
506
507   p_clear(&s, 1);
508
509   if (!fp && (msg = mx_open_message (ctx, hdr->msgno)) == NULL)
510     return (-1);
511
512   if (!fp)
513     fp = msg->fp;
514
515   bfp = fp;
516
517   /* parse the message header and MIME structure */
518
519   fseeko (fp, hdr->offset, 0);
520   newhdr->offset = hdr->offset;
521   newhdr->env = mutt_read_rfc822_header (fp, newhdr, 1, weed);
522   newhdr->content->length = hdr->content->length;
523   mutt_parse_part (fp, newhdr->content);
524
525   p_delete(&newhdr->env->message_id);
526   p_delete(&newhdr->env->mail_followup_to);        /* really? */
527
528   /* decrypt pgp/mime encoded messages */
529
530   if ((APPLICATION_PGP | APPLICATION_SMIME) & hdr->security
531       && mutt_is_multipart_encrypted (newhdr->content))
532   {
533     int ccap = (APPLICATION_PGP | APPLICATION_SMIME) & hdr->security;
534     newhdr->security |= ENCRYPT | ccap;
535     if (!crypt_valid_passphrase (ccap))
536       goto err;
537
538     mutt_message _("Decrypting message...");
539
540     if (((ccap & APPLICATION_PGP)
541          && crypt_pgp_decrypt_mime (fp, &bfp, newhdr->content, &b) == -1)
542         || ((ccap & APPLICATION_SMIME)
543             && crypt_smime_decrypt_mime (fp, &bfp, newhdr->content, &b) == -1)
544         || b == NULL) {
545     err:
546       mx_close_message (&msg);
547       mutt_free_envelope (&newhdr->env);
548       mutt_free_body (&newhdr->content);
549       mutt_error _("Decryption failed.");
550
551       return -1;
552     }
553
554     mutt_free_body (&newhdr->content);
555     newhdr->content = b;
556
557     mutt_clear_error ();
558   }
559
560   /* 
561    * remove a potential multipart/signed layer - useful when
562    * resending messages 
563    */
564
565   if (mutt_is_multipart_signed (newhdr->content)) {
566     newhdr->security |= SIGN;
567     if (ascii_strcasecmp (mutt_get_parameter
568                           ("protocol", newhdr->content->parameter),
569                           "application/pgp-signature") == 0)
570       newhdr->security |= APPLICATION_PGP;
571     else
572       newhdr->security |= APPLICATION_SMIME;
573
574     /* destroy the signature */
575     mutt_free_body (&newhdr->content->parts->next);
576     newhdr->content = mutt_remove_multipart (newhdr->content);
577   }
578
579
580   /* 
581    * We don't need no primary multipart.
582    * Note: We _do_ preserve messages!
583    * 
584    * XXX - we don't handle multipart/alternative in any 
585    * smart way when sending messages.  However, one may
586    * consider this a feature.
587    * 
588    */
589
590   if (newhdr->content->type == TYPEMULTIPART)
591     newhdr->content = mutt_remove_multipart (newhdr->content);
592
593   s.fpin = bfp;
594
595   /* create temporary files for all attachments */
596   for (b = newhdr->content; b; b = b->next) {
597
598     /* what follows is roughly a receive-mode variant of
599      * mutt_get_tmp_attachment () from muttlib.c
600      */
601
602     file[0] = '\0';
603     if (b->filename) {
604       m_strcpy(file, sizeof(file), b->filename);
605       b->d_filename = m_strdup(b->filename);
606     }
607     else {
608       /* avoid Content-Disposition: header with temporary filename */
609       b->use_disp = 0;
610     }
611
612     /* set up state flags */
613
614     s.flags = 0;
615
616     if (b->type == TYPETEXT) {
617       if (!ascii_strcasecmp
618           ("yes", mutt_get_parameter ("x-mutt-noconv", b->parameter)))
619         b->noconv = 1;
620       else {
621         s.flags |= M_CHARCONV;
622         b->noconv = 0;
623       }
624
625       mutt_delete_parameter ("x-mutt-noconv", &b->parameter);
626     }
627
628     mutt_adv_mktemp (NULL, file, sizeof (file));
629     if ((s.fpout = safe_fopen (file, "w")) == NULL)
630       goto bail;
631
632
633     if (mutt_is_application_pgp (b) & (ENCRYPT | SIGN)) {
634
635       mutt_body_handler (b, &s);
636
637       newhdr->security |= mutt_is_application_pgp (newhdr->content);
638
639       b->type = TYPETEXT;
640       m_strreplace(&b->subtype, "plain");
641       mutt_delete_parameter ("x-action", &b->parameter);
642     }
643     else
644       mutt_decode_attachment (b, &s);
645
646     if (safe_fclose (&s.fpout) != 0)
647       goto bail;
648
649     m_strreplace(&b->filename, file);
650     b->unlink = 1;
651
652     mutt_stamp_attachment (b);
653
654     mutt_free_body (&b->parts);
655     if (b->hdr)
656       b->hdr->content = NULL;   /* avoid dangling pointer */
657   }
658
659   /* Fix encryption flags. */
660
661   /* No inline if multipart. */
662   if ((newhdr->security & INLINE) && newhdr->content->next)
663     newhdr->security &= ~INLINE;
664
665   /* Theoretically, both could be set. Take the one the user wants to set by default. */
666   if ((newhdr->security & APPLICATION_PGP)
667       && (newhdr->security & APPLICATION_SMIME)) {
668     if (option (OPTSMIMEISDEFAULT))
669       newhdr->security &= ~APPLICATION_PGP;
670     else
671       newhdr->security &= ~APPLICATION_SMIME;
672   }
673
674   rv = 0;
675
676 bail:
677
678   /* that's it. */
679   if (bfp != fp)
680     fclose (bfp);
681   if (msg)
682     mx_close_message (&msg);
683
684   if (rv == -1) {
685     mutt_free_envelope (&newhdr->env);
686     mutt_free_body (&newhdr->content);
687   }
688
689   return rv;
690 }