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