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