missing include
[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 ((WithCrypto & APPLICATION_PGP)
336              && (m_strncmp("Pgp:", tmp->data, 4) == 0       /* this is generated
337                                                                  * by old mutt versions
338                                                                  */
339                  || m_strncmp("X-Mutt-PGP:", tmp->data, 11) == 0)) {
340       hdr->security = mutt_parse_crypt_hdr (strchr (tmp->data, ':') + 1, 1);
341       hdr->security |= APPLICATION_PGP;
342
343       /* remove the pgp field */
344       next = tmp->next;
345       if (last)
346         last->next = tmp->next;
347       else
348         hdr->env->userhdrs = tmp->next;
349       tmp->next = NULL;
350       mutt_free_list (&tmp);
351       tmp = next;
352     }
353     else if ((WithCrypto & APPLICATION_SMIME)
354              && m_strncmp("X-Mutt-SMIME:", tmp->data, 13) == 0) {
355       hdr->security = mutt_parse_crypt_hdr (strchr (tmp->data, ':') + 1, 1);
356       hdr->security |= APPLICATION_SMIME;
357
358       /* remove the smime field */
359       next = tmp->next;
360       if (last)
361         last->next = tmp->next;
362       else
363         hdr->env->userhdrs = tmp->next;
364       tmp->next = NULL;
365       mutt_free_list (&tmp);
366       tmp = next;
367     }
368
369 #ifdef MIXMASTER
370     else if (m_strncmp("X-Mutt-Mix:", tmp->data, 11) == 0) {
371       char *t;
372
373       mutt_free_list (&hdr->chain);
374
375       t = strtok (tmp->data + 11, " \t\n");
376       while (t) {
377         hdr->chain = mutt_add_list (hdr->chain, t);
378         t = strtok (NULL, " \t\n");
379       }
380
381       next = tmp->next;
382       if (last)
383         last->next = tmp->next;
384       else
385         hdr->env->userhdrs = tmp->next;
386       tmp->next = NULL;
387       mutt_free_list (&tmp);
388       tmp = next;
389     }
390 #endif
391
392     else {
393       last = tmp;
394       tmp = tmp->next;
395     }
396   }
397   return (code);
398 }
399
400
401
402 int mutt_parse_crypt_hdr (char *p, int set_signas)
403 {
404   int pgp = 0;
405   char pgp_sign_as[LONG_STRING] = "\0", *q;
406   char smime_cryptalg[LONG_STRING] = "\0";
407
408   if (!WithCrypto)
409     return 0;
410
411   for (p = vskipspaces(p); *p; p++) {
412
413     switch (*p) {
414     case 'e':
415     case 'E':
416       pgp |= ENCRYPT;
417       break;
418
419     case 's':
420     case 'S':
421       pgp |= SIGN;
422       q = pgp_sign_as;
423
424       if (*(p + 1) == '<') {
425         for (p += 2;
426              *p && *p != '>' && q < pgp_sign_as + sizeof (pgp_sign_as) - 1;
427              *q++ = *p++);
428
429         if (*p != '>') {
430           mutt_error _("Illegal PGP header");
431
432           return 0;
433         }
434       }
435
436       *q = '\0';
437       break;
438
439       /* This used to be the micalg parameter.
440        * 
441        * It's no longer needed, so we just skip the parameter in order
442        * to be able to recall old messages.
443        */
444     case 'm':
445     case 'M':
446       if (*(p + 1) == '<') {
447         for (p += 2; *p && *p != '>'; p++);
448         if (*p != '>') {
449           mutt_error _("Illegal PGP header");
450
451           return 0;
452         }
453       }
454
455       break;
456
457
458     case 'c':
459     case 'C':
460       q = smime_cryptalg;
461
462       if (*(p + 1) == '<') {
463         for (p += 2;
464              *p && *p != '>'
465              && q < smime_cryptalg + sizeof (smime_cryptalg) - 1;
466              *q++ = *p++);
467
468         if (*p != '>') {
469           mutt_error _("Illegal S/MIME header");
470
471           return 0;
472         }
473       }
474
475       *q = '\0';
476       break;
477
478     case 'i':
479     case 'I':
480       pgp |= INLINE;
481       break;
482
483     default:
484       mutt_error _("Illegal PGP header");
485       return 0;
486     }
487
488   }
489
490   /* the cryptalg field must not be empty */
491   if ((WithCrypto & APPLICATION_SMIME) && *smime_cryptalg)
492     str_replace (&SmimeCryptAlg, smime_cryptalg);
493
494   if ((WithCrypto & APPLICATION_PGP) && (set_signas || *pgp_sign_as))
495     str_replace (&PgpSignAs, pgp_sign_as);
496
497   return pgp;
498 }
499
500
501
502 int mutt_prepare_template (FILE * fp, CONTEXT * ctx, HEADER * newhdr,
503                            HEADER * hdr, short weed)
504 {
505   MESSAGE *msg = NULL;
506   char file[_POSIX_PATH_MAX];
507   BODY *b;
508   FILE *bfp;
509
510   int rv = -1;
511   STATE s;
512
513   p_clear(&s, 1);
514
515   if (!fp && (msg = mx_open_message (ctx, hdr->msgno)) == NULL)
516     return (-1);
517
518   if (!fp)
519     fp = msg->fp;
520
521   bfp = fp;
522
523   /* parse the message header and MIME structure */
524
525   fseeko (fp, hdr->offset, 0);
526   newhdr->offset = hdr->offset;
527   newhdr->env = mutt_read_rfc822_header (fp, newhdr, 1, weed);
528   newhdr->content->length = hdr->content->length;
529   mutt_parse_part (fp, newhdr->content);
530
531   p_delete(&newhdr->env->message_id);
532   p_delete(&newhdr->env->mail_followup_to);        /* really? */
533
534   /* decrypt pgp/mime encoded messages */
535
536   if ((WithCrypto & (APPLICATION_PGP | APPLICATION_SMIME) & hdr->security)
537       && mutt_is_multipart_encrypted (newhdr->content)) {
538     int ccap =
539       WithCrypto & (APPLICATION_PGP | APPLICATION_SMIME) & hdr->security;
540     newhdr->security |= ENCRYPT | ccap;
541     if (!crypt_valid_passphrase (ccap))
542       goto err;
543
544     mutt_message _("Decrypting message...");
545
546     if (((ccap & APPLICATION_PGP)
547          && crypt_pgp_decrypt_mime (fp, &bfp, newhdr->content, &b) == -1)
548         || ((ccap & APPLICATION_SMIME)
549             && crypt_smime_decrypt_mime (fp, &bfp, newhdr->content, &b) == -1)
550         || b == NULL) {
551     err:
552       mx_close_message (&msg);
553       mutt_free_envelope (&newhdr->env);
554       mutt_free_body (&newhdr->content);
555       mutt_error _("Decryption failed.");
556
557       return -1;
558     }
559
560     mutt_free_body (&newhdr->content);
561     newhdr->content = b;
562
563     mutt_clear_error ();
564   }
565
566   /* 
567    * remove a potential multipart/signed layer - useful when
568    * resending messages 
569    */
570
571   if (WithCrypto && mutt_is_multipart_signed (newhdr->content)) {
572     newhdr->security |= SIGN;
573     if ((WithCrypto & APPLICATION_PGP)
574         &&
575         ascii_strcasecmp (mutt_get_parameter
576                           ("protocol", newhdr->content->parameter),
577                           "application/pgp-signature") == 0)
578       newhdr->security |= APPLICATION_PGP;
579     else if ((WithCrypto & APPLICATION_SMIME))
580       newhdr->security |= APPLICATION_SMIME;
581
582     /* destroy the signature */
583     mutt_free_body (&newhdr->content->parts->next);
584     newhdr->content = mutt_remove_multipart (newhdr->content);
585   }
586
587
588   /* 
589    * We don't need no primary multipart.
590    * Note: We _do_ preserve messages!
591    * 
592    * XXX - we don't handle multipart/alternative in any 
593    * smart way when sending messages.  However, one may
594    * consider this a feature.
595    * 
596    */
597
598   if (newhdr->content->type == TYPEMULTIPART)
599     newhdr->content = mutt_remove_multipart (newhdr->content);
600
601   s.fpin = bfp;
602
603   /* create temporary files for all attachments */
604   for (b = newhdr->content; b; b = b->next) {
605
606     /* what follows is roughly a receive-mode variant of
607      * mutt_get_tmp_attachment () from muttlib.c
608      */
609
610     file[0] = '\0';
611     if (b->filename) {
612       m_strcpy(file, sizeof(file), b->filename);
613       b->d_filename = m_strdup(b->filename);
614     }
615     else {
616       /* avoid Content-Disposition: header with temporary filename */
617       b->use_disp = 0;
618     }
619
620     /* set up state flags */
621
622     s.flags = 0;
623
624     if (b->type == TYPETEXT) {
625       if (!ascii_strcasecmp
626           ("yes", mutt_get_parameter ("x-mutt-noconv", b->parameter)))
627         b->noconv = 1;
628       else {
629         s.flags |= M_CHARCONV;
630         b->noconv = 0;
631       }
632
633       mutt_delete_parameter ("x-mutt-noconv", &b->parameter);
634     }
635
636     mutt_adv_mktemp (NULL, file, sizeof (file));
637     if ((s.fpout = safe_fopen (file, "w")) == NULL)
638       goto bail;
639
640
641     if ((WithCrypto & APPLICATION_PGP)
642         && (mutt_is_application_pgp (b) & (ENCRYPT | SIGN))) {
643
644       mutt_body_handler (b, &s);
645
646       newhdr->security |= mutt_is_application_pgp (newhdr->content);
647
648       b->type = TYPETEXT;
649       str_replace (&b->subtype, "plain");
650       mutt_delete_parameter ("x-action", &b->parameter);
651     }
652     else
653       mutt_decode_attachment (b, &s);
654
655     if (safe_fclose (&s.fpout) != 0)
656       goto bail;
657
658     str_replace (&b->filename, file);
659     b->unlink = 1;
660
661     mutt_stamp_attachment (b);
662
663     mutt_free_body (&b->parts);
664     if (b->hdr)
665       b->hdr->content = NULL;   /* avoid dangling pointer */
666   }
667
668   /* Fix encryption flags. */
669
670   /* No inline if multipart. */
671   if (WithCrypto && (newhdr->security & INLINE) && newhdr->content->next)
672     newhdr->security &= ~INLINE;
673
674   /* Do we even support multiple mechanisms? */
675   newhdr->security &= WithCrypto | ~(APPLICATION_PGP | APPLICATION_SMIME);
676
677   /* Theoretically, both could be set. Take the one the user wants to set by default. */
678   if ((newhdr->security & APPLICATION_PGP)
679       && (newhdr->security & APPLICATION_SMIME)) {
680     if (option (OPTSMIMEISDEFAULT))
681       newhdr->security &= ~APPLICATION_PGP;
682     else
683       newhdr->security &= ~APPLICATION_SMIME;
684   }
685
686   rv = 0;
687
688 bail:
689
690   /* that's it. */
691   if (bfp != fp)
692     fclose (bfp);
693   if (msg)
694     mx_close_message (&msg);
695
696   if (rv == -1) {
697     mutt_free_envelope (&newhdr->env);
698     mutt_free_body (&newhdr->content);
699   }
700
701   return rv;
702 }