23ae41c8332854eedce617d5be3a3c7c761a4992
[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 #ifdef USE_IMAP
22 #include "mx.h"
23 #include "imap.h"
24 #endif
25 #include "mutt_crypt.h"
26
27 #include "lib/mem.h"
28 #include "lib/intl.h"
29 #include "lib/str.h"
30
31 #include <ctype.h>
32 #include <unistd.h>
33 #include <string.h>
34 #include <sys/stat.h>
35
36 static struct mapping_t PostponeHelp[] = {
37   {N_("Exit"), OP_EXIT},
38   {N_("Del"), OP_DELETE},
39   {N_("Undel"), OP_UNDELETE},
40   {N_("Help"), OP_HELP},
41   {NULL}
42 };
43
44
45
46 static short PostCount = 0;
47 static CONTEXT *PostContext = NULL;
48 static short UpdateNumPostponed = 0;
49
50 /* Return the number of postponed messages.
51  * if force is 0, use a cached value if it is costly to get a fresh
52  * count (IMAP) - else check.
53  */
54 int mutt_num_postponed (int force)
55 {
56   struct stat st;
57   CONTEXT ctx;
58
59   static time_t LastModify = 0;
60   static char *OldPostponed = NULL;
61
62   if (UpdateNumPostponed) {
63     UpdateNumPostponed = 0;
64     force = 1;
65   }
66
67   if (Postponed != OldPostponed) {
68     OldPostponed = Postponed;
69     LastModify = 0;
70     force = 1;
71   }
72
73   if (!Postponed)
74     return 0;
75
76 #ifdef USE_IMAP
77   /* LastModify is useless for IMAP */
78   if (mx_get_magic (Postponed) == M_IMAP) {
79     if (force) {
80       short newpc;
81
82       newpc = imap_mailbox_check (Postponed, 0);
83       if (newpc >= 0) {
84         PostCount = newpc;
85         dprint (2,
86                 (debugfile,
87                  "mutt_num_postponed: %d postponed IMAP messages found.\n",
88                  PostCount));
89       }
90       else
91         dprint (2,
92                 (debugfile,
93                  "mutt_num_postponed: using old IMAP postponed count.\n"));
94     }
95     return PostCount;
96   }
97 #endif
98
99   if (stat (Postponed, &st) == -1) {
100     PostCount = 0;
101     LastModify = 0;
102     return (0);
103   }
104
105   if (S_ISDIR (st.st_mode)) {
106     /* if we have a maildir mailbox, we need to stat the "new" dir */
107
108     char buf[_POSIX_PATH_MAX];
109
110     snprintf (buf, sizeof (buf), "%s/new", Postponed);
111     if (access (buf, F_OK) == 0 && stat (buf, &st) == -1) {
112       PostCount = 0;
113       LastModify = 0;
114       return 0;
115     }
116   }
117
118   if (LastModify < st.st_mtime) {
119 #ifdef USE_NNTP
120     int optnews = option (OPTNEWS);
121 #endif
122     LastModify = st.st_mtime;
123
124     if (access (Postponed, R_OK | F_OK) != 0)
125       return (PostCount = 0);
126 #ifdef USE_NNTP
127     if (optnews)
128       unset_option (OPTNEWS);
129 #endif
130     if (mx_open_mailbox (Postponed, M_NOSORT | M_QUIET, &ctx) == NULL)
131       PostCount = 0;
132     else
133       PostCount = ctx.msgcount;
134     mx_fastclose_mailbox (&ctx);
135 #ifdef USE_NNTP
136     if (optnews)
137       set_option (OPTNEWS);
138 #endif
139   }
140
141   return (PostCount);
142 }
143
144 void mutt_update_num_postponed (void)
145 {
146   UpdateNumPostponed = 1;
147 }
148
149 static void post_entry (char *s, size_t slen, MUTTMENU * menu, int entry)
150 {
151   CONTEXT *ctx = (CONTEXT *) menu->data;
152
153   _mutt_make_string (s, slen, NONULL (HdrFmt), ctx, ctx->hdrs[entry],
154                      M_FORMAT_ARROWCURSOR);
155 }
156
157 static HEADER *select_msg (void)
158 {
159   MUTTMENU *menu;
160   int i, done = 0, r = -1;
161   char helpstr[SHORT_STRING];
162   short orig_sort;
163
164   menu = mutt_new_menu ();
165   menu->make_entry = post_entry;
166   menu->menu = MENU_POST;
167   menu->max = PostContext->msgcount;
168   menu->title = _("Postponed Messages");
169   menu->data = PostContext;
170   menu->help =
171     mutt_compile_help (helpstr, sizeof (helpstr), MENU_POST, PostponeHelp);
172
173   /* The postponed mailbox is setup to have sorting disabled, but the global
174    * Sort variable may indicate something different.   Sorting has to be
175    * disabled while the postpone menu is being displayed. */
176   orig_sort = Sort;
177   Sort = SORT_ORDER;
178
179   while (!done) {
180     switch (i = mutt_menuLoop (menu)) {
181     case OP_DELETE:
182     case OP_UNDELETE:
183       mutt_set_flag (PostContext, PostContext->hdrs[menu->current], M_DELETE,
184                      (i == OP_DELETE) ? 1 : 0);
185       PostCount = PostContext->msgcount - PostContext->deleted;
186       if (option (OPTRESOLVE) && menu->current < menu->max - 1) {
187         menu->oldcurrent = menu->current;
188         menu->current++;
189         if (menu->current >= menu->top + menu->pagelen) {
190           menu->top = menu->current;
191           menu->redraw = REDRAW_INDEX | REDRAW_STATUS;
192         }
193         else
194           menu->redraw |= REDRAW_MOTION_RESYNCH;
195       }
196       else
197         menu->redraw = REDRAW_CURRENT;
198       break;
199
200     case OP_GENERIC_SELECT_ENTRY:
201       r = menu->current;
202       done = 1;
203       break;
204
205     case OP_EXIT:
206       done = 1;
207       break;
208     }
209   }
210
211   Sort = orig_sort;
212   mutt_menuDestroy (&menu);
213   return (r > -1 ? PostContext->hdrs[r] : NULL);
214 }
215
216 /* args:
217  *      ctx     Context info, used when recalling a message to which
218  *              we reply.
219  *      hdr     envelope/attachment info for recalled message
220  *      cur     if message was a reply, `cur' is set to the message which
221  *              `hdr' is in reply to
222  *      fcc     fcc for the recalled message
223  *      fcclen  max length of fcc
224  *
225  * return vals:
226  *      -1              error/no messages
227  *      0               normal exit
228  *      SENDREPLY       recalled message is a reply
229  */
230 int mutt_get_postponed (CONTEXT * ctx, HEADER * hdr, HEADER ** cur, char *fcc,
231                         size_t fcclen)
232 {
233   HEADER *h;
234   int code = SENDPOSTPONED;
235   LIST *tmp;
236   LIST *last = NULL;
237   LIST *next;
238   char *p;
239   int opt_delete;
240
241   if (!Postponed)
242     return (-1);
243
244   if ((PostContext = mx_open_mailbox (Postponed, M_NOSORT, NULL)) == NULL) {
245     PostCount = 0;
246     mutt_error _("No postponed messages.");
247
248     return (-1);
249   }
250
251   if (!PostContext->msgcount) {
252     PostCount = 0;
253     mx_close_mailbox (PostContext, NULL);
254     FREE (&PostContext);
255     mutt_error _("No postponed messages.");
256
257     return (-1);
258   }
259
260   if (PostContext->msgcount == 1) {
261     /* only one message, so just use that one. */
262     h = PostContext->hdrs[0];
263   }
264   else if ((h = select_msg ()) == NULL) {
265     mx_close_mailbox (PostContext, NULL);
266     FREE (&PostContext);
267     return (-1);
268   }
269
270   if (mutt_prepare_template (NULL, PostContext, hdr, h, 0) < 0) {
271     mx_fastclose_mailbox (PostContext);
272     FREE (&PostContext);
273     return (-1);
274   }
275
276   /* finished with this message, so delete it. */
277   mutt_set_flag (PostContext, h, M_DELETE, 1);
278
279   /* and consider it saved, so that it won't be moved to the trash folder */
280   mutt_set_flag (PostContext, h, M_APPENDED, 1);
281
282   /* update the count for the status display */
283   PostCount = PostContext->msgcount - PostContext->deleted;
284
285   /* avoid the "purge deleted messages" prompt */
286   opt_delete = quadoption (OPT_DELETE);
287   set_quadoption (OPT_DELETE, M_YES);
288   mx_close_mailbox (PostContext, NULL);
289   set_quadoption (OPT_DELETE, opt_delete);
290
291   FREE (&PostContext);
292
293   for (tmp = hdr->env->userhdrs; tmp;) {
294     if (ascii_strncasecmp ("X-Mutt-References:", tmp->data, 18) == 0) {
295       if (ctx) {
296         /* if a mailbox is currently open, look to see if the orignal message
297            the user attempted to reply to is in this mailbox */
298         p = tmp->data + 18;
299         SKIPWS (p);
300         if (!ctx->id_hash)
301           ctx->id_hash = mutt_make_id_hash (ctx);
302         *cur = hash_find (ctx->id_hash, p);
303       }
304
305       /* Remove the X-Mutt-References: header field. */
306       next = tmp->next;
307       if (last)
308         last->next = tmp->next;
309       else
310         hdr->env->userhdrs = tmp->next;
311       tmp->next = NULL;
312       mutt_free_list (&tmp);
313       tmp = next;
314       if (*cur)
315         code |= SENDREPLY;
316     }
317     else if (ascii_strncasecmp ("X-Mutt-Fcc:", tmp->data, 11) == 0) {
318       p = tmp->data + 11;
319       SKIPWS (p);
320       strfcpy (fcc, p, fcclen);
321       mutt_pretty_mailbox (fcc);
322
323       /* remove the X-Mutt-Fcc: header field */
324       next = tmp->next;
325       if (last)
326         last->next = tmp->next;
327       else
328         hdr->env->userhdrs = tmp->next;
329       tmp->next = NULL;
330       mutt_free_list (&tmp);
331       tmp = next;
332     }
333     else if ((WithCrypto & APPLICATION_PGP)
334              && (safe_strncmp ("Pgp:", tmp->data, 4) == 0       /* this is generated
335                                                                  * by old mutt versions
336                                                                  */
337                  || safe_strncmp ("X-Mutt-PGP:", tmp->data, 11) == 0)) {
338       hdr->security = mutt_parse_crypt_hdr (strchr (tmp->data, ':') + 1, 1);
339       hdr->security |= APPLICATION_PGP;
340
341       /* remove the pgp field */
342       next = tmp->next;
343       if (last)
344         last->next = tmp->next;
345       else
346         hdr->env->userhdrs = tmp->next;
347       tmp->next = NULL;
348       mutt_free_list (&tmp);
349       tmp = next;
350     }
351     else if ((WithCrypto & APPLICATION_SMIME)
352              && safe_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 (safe_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   if (!WithCrypto)
407     return 0;
408
409   SKIPWS (p);
410   for (; *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   memset (&s, 0, sizeof (s));
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   fseek (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   FREE (&newhdr->env->message_id);
531   FREE (&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       strfcpy (file, b->filename, sizeof (file));
612       b->d_filename = safe_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 (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 }