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