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