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