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