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