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