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