Rocco Rutte:
[apps/madmutt.git] / commands.c
1 /*
2  * Copyright notice from original mutt:
3  * Copyright (C) 1996-2000 Michael R. Elkins <me@mutt.org>
4  * Copyright (C) 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 "mutt.h"
16 #include "mutt_curses.h"
17 #include "mutt_menu.h"
18 #include "mime.h"
19 #include "sort.h"
20 #include "mailbox.h"
21 #include "copy.h"
22 #include "mx.h"
23 #include "pager.h"
24 #include "mutt_crypt.h"
25 #include "mutt_idna.h"
26 #include "rfc1524.h"
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 #include <fcntl.h>
30
31 #ifdef USE_IMAP
32 #include "imap.h"
33 #endif
34
35 #ifdef BUFFY_SIZE
36 #include "buffy.h"
37 #endif
38
39 #include <errno.h>
40 #include <unistd.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <sys/wait.h>
44 #include <sys/stat.h>
45 #include <sys/types.h>
46 #include <utime.h>
47
48 extern char *ReleaseDate;
49
50 /* The folder the user last saved to.  Used by ci_save_message() */
51 static char LastSaveFolder[_POSIX_PATH_MAX] = "";
52
53 int mutt_display_message (HEADER * cur)
54 {
55   char tempfile[_POSIX_PATH_MAX], buf[LONG_STRING];
56   int rc = 0, builtin = 0;
57   int cmflags = M_CM_DECODE | M_CM_DISPLAY | M_CM_CHARCONV;
58   FILE *fpout = NULL;
59   FILE *fpfilterout = NULL;
60   pid_t filterpid = -1;
61   int res;
62
63   snprintf (buf, sizeof (buf), "%s/%s", TYPE (cur->content),
64             cur->content->subtype);
65
66   mutt_parse_mime_message (Context, cur);
67   mutt_message_hook (Context, cur, M_MESSAGEHOOK);
68
69   /* see if crytpo is needed for this message.  if so, we should exit curses */
70   if (WithCrypto && cur->security) {
71     if (cur->security & ENCRYPT) {
72       if (cur->security & APPLICATION_SMIME)
73         crypt_smime_getkeys (cur->env);
74       if (!crypt_valid_passphrase (cur->security))
75         return 0;
76
77       cmflags |= M_CM_VERIFY;
78     }
79     else if (cur->security & SIGN) {
80       /* find out whether or not the verify signature */
81       if (query_quadoption (OPT_VERIFYSIG, _("Verify PGP signature?")) ==
82           M_YES) {
83         cmflags |= M_CM_VERIFY;
84       }
85     }
86   }
87
88   if (cmflags & M_CM_VERIFY || cur->security & ENCRYPT) {
89     if (cur->security & APPLICATION_PGP) {
90       if (cur->env->from)
91         crypt_pgp_invoke_getkeys (cur->env->from);
92
93       crypt_invoke_message (APPLICATION_PGP);
94     }
95
96     if (cur->security & APPLICATION_SMIME)
97       crypt_invoke_message (APPLICATION_SMIME);
98   }
99
100
101   mutt_mktemp (tempfile);
102   if ((fpout = safe_fopen (tempfile, "w")) == NULL) {
103     mutt_error _("Could not create temporary file!");
104
105     return (0);
106   }
107
108   if (DisplayFilter && *DisplayFilter) {
109     fpfilterout = fpout;
110     fpout = NULL;
111     /* mutt_endwin (NULL); */
112     filterpid = mutt_create_filter_fd (DisplayFilter, &fpout, NULL, NULL,
113                                        -1, fileno (fpfilterout), -1);
114     if (filterpid < 0) {
115       mutt_error (_("Cannot create display filter"));
116       safe_fclose (&fpfilterout);
117       unlink (tempfile);
118       return 0;
119     }
120   }
121
122   if (!Pager || mutt_strcmp (Pager, "builtin") == 0)
123     builtin = 1;
124   else {
125     mutt_make_string (buf, sizeof (buf), NONULL (PagerFmt), Context, cur);
126     fputs (buf, fpout);
127     fputs ("\n\n", fpout);
128   }
129
130   res = mutt_copy_message (fpout, Context, cur, cmflags,
131                            (option (OPTWEED) ? (CH_WEED | CH_REORDER) : 0) |
132                            CH_DECODE | CH_FROM);
133   if ((safe_fclose (&fpout) != 0 && errno != EPIPE) || res == -1) {
134     mutt_error (_("Could not copy message"));
135     if (fpfilterout != NULL) {
136       mutt_wait_filter (filterpid);
137       safe_fclose (&fpfilterout);
138     }
139     mutt_unlink (tempfile);
140     return 0;
141   }
142
143   if (fpfilterout != NULL && mutt_wait_filter (filterpid) != 0)
144     mutt_any_key_to_continue (NULL);
145
146   safe_fclose (&fpfilterout);   /* XXX - check result? */
147
148
149   if (WithCrypto) {
150     /* update crypto information for this message */
151     cur->security |= crypt_query (cur->content);
152
153     /* Remove color cache for this message, in case there
154        are color patterns for both ~g and ~V */
155     cur->pair = 0;
156   }
157
158   if (builtin) {
159     pager_t info;
160
161     if (WithCrypto
162         && (cur->security & APPLICATION_SMIME) && (cmflags & M_CM_VERIFY)) {
163       if (cur->security & GOODSIGN) {
164         if (!crypt_smime_verify_sender (cur))
165           mutt_message (_("S/MIME signature successfully verified."));
166         else
167           mutt_error (_("S/MIME certificate owner does not match sender."));
168       }
169       else if (cur->security & PARTSIGN)
170         mutt_message (_
171                       ("Warning: Part of this message has not been signed."));
172       else if (cur->security & SIGN || cur->security & BADSIGN)
173         mutt_error (_("S/MIME signature could NOT be verified."));
174     }
175
176     if (WithCrypto
177         && (cur->security & APPLICATION_PGP) && (cmflags & M_CM_VERIFY)) {
178       if (cur->security & GOODSIGN)
179         mutt_message (_("PGP signature successfully verified."));
180       else if (cur->security & PARTSIGN)
181         mutt_message (_
182                       ("Warning: Part of this message has not been signed."));
183       else
184         mutt_message (_("PGP signature could NOT be verified."));
185     }
186
187     /* Invoke the builtin pager */
188     memset (&info, 0, sizeof (pager_t));
189     info.hdr = cur;
190     info.ctx = Context;
191     rc = mutt_pager (NULL, tempfile, M_PAGER_MESSAGE, &info);
192   }
193   else {
194     int r;
195
196     mutt_endwin (NULL);
197     snprintf (buf, sizeof (buf), "%s %s", NONULL (Pager), tempfile);
198     if ((r = mutt_system (buf)) == -1)
199       mutt_error (_("Error running \"%s\"!"), buf);
200     unlink (tempfile);
201     keypad (stdscr, TRUE);
202     if (r != -1)
203       mutt_set_flag (Context, cur, M_READ, 1);
204     if (r != -1 && option (OPTPROMPTAFTER)) {
205       mutt_ungetch (mutt_any_key_to_continue _("Command: "), 0);
206       rc = km_dokey (MENU_PAGER);
207     }
208     else
209       rc = 0;
210   }
211
212   return rc;
213 }
214
215 void ci_bounce_message (HEADER * h, int *redraw)
216 {
217   char prompt[SHORT_STRING];
218   char buf[HUGE_STRING] = { 0 };
219   ADDRESS *adr = NULL;
220   char *err = NULL;
221   int rc;
222
223   if (h)
224     strfcpy (prompt, _("Bounce message to: "), sizeof (prompt));
225   else
226     strfcpy (prompt, _("Bounce tagged messages to: "), sizeof (prompt));
227
228   rc = mutt_get_field (prompt, buf, sizeof (buf), M_ALIAS);
229
230   if (option (OPTNEEDREDRAW)) {
231     unset_option (OPTNEEDREDRAW);
232     *redraw = REDRAW_FULL;
233   }
234
235   if (rc || !buf[0])
236     return;
237
238   if (!(adr = rfc822_parse_adrlist (adr, buf))) {
239     mutt_error _("Error parsing address!");
240
241     return;
242   }
243
244   adr = mutt_expand_aliases (adr);
245
246   if (mutt_addrlist_to_idna (adr, &err) < 0) {
247     mutt_error (_("Bad IDN: '%s'"), err);
248     FREE (&err);
249     rfc822_free_address (&adr);
250     return;
251   }
252
253   buf[0] = 0;
254   rfc822_write_address (buf, sizeof (buf), adr, 1);
255
256 #define extra_space (15 + 7 + 2)
257   snprintf (prompt, sizeof (prompt),
258             (h ? _("Bounce message to %s") : _("Bounce messages to %s")),
259             buf);
260
261   if (mutt_strwidth (prompt) > COLS - extra_space) {
262     mutt_format_string (prompt, sizeof (prompt),
263                         0, COLS - extra_space, 0, 0,
264                         prompt, sizeof (prompt), 0);
265     safe_strcat (prompt, sizeof (prompt), "...?");
266   }
267   else
268     safe_strcat (prompt, sizeof (prompt), "?");
269
270   if (query_quadoption (OPT_BOUNCE, prompt) != M_YES) {
271     rfc822_free_address (&adr);
272     CLEARLINE (LINES - 1);
273     mutt_message (h ? _("Message not bounced.") : _("Messages not bounced."));
274     return;
275   }
276
277   CLEARLINE (LINES - 1);
278
279   rc = mutt_bounce_message (NULL, h, adr);
280   rfc822_free_address (&adr);
281   /* If no error, or background, display message. */
282   if ((rc == 0) || (rc == S_BKG))
283     mutt_message (h ? _("Message bounced.") : _("Messages bounced."));
284 }
285
286 static void pipe_set_flags (int decode, int print, int *cmflags, int *chflags)
287 {
288   if (decode) {
289     *cmflags |= M_CM_DECODE | M_CM_CHARCONV;
290     *chflags |= CH_DECODE | CH_REORDER;
291
292     if (option (OPTWEED)) {
293       *chflags |= CH_WEED;
294       *cmflags |= M_CM_WEED;
295     }
296   }
297
298   if (print)
299     *cmflags |= M_CM_PRINTING;
300
301 }
302
303 static void pipe_msg (HEADER * h, FILE * fp, int decode, int print)
304 {
305   int cmflags = 0;
306   int chflags = CH_FROM;
307
308   pipe_set_flags (decode, print, &cmflags, &chflags);
309
310   if (WithCrypto && decode && h->security & ENCRYPT) {
311     if (!crypt_valid_passphrase (h->security))
312       return;
313     endwin ();
314   }
315
316   if (decode)
317     mutt_parse_mime_message (Context, h);
318
319   mutt_copy_message (fp, Context, h, cmflags, chflags);
320 }
321
322
323 /* the following code is shared between printing and piping */
324
325 static int _mutt_pipe_message (HEADER * h, char *cmd,
326                                int decode, int print, int split, char *sep)
327 {
328
329   int i, rc = 0;
330   pid_t thepid;
331   FILE *fpout;
332
333 /*   mutt_endwin (NULL); 
334
335      is this really needed here ? 
336      it makes the screen flicker on pgp and s/mime messages,
337      before asking for a passphrase...
338                                      Oliver Ehli */
339   if (h) {
340
341     mutt_message_hook (Context, h, M_MESSAGEHOOK);
342
343     if (WithCrypto && decode) {
344       mutt_parse_mime_message (Context, h);
345       if (h->security & ENCRYPT && !crypt_valid_passphrase (h->security))
346         return 1;
347     }
348     mutt_endwin (NULL);
349
350     if ((thepid = mutt_create_filter (cmd, &fpout, NULL, NULL)) < 0) {
351       mutt_perror _("Can't create filter process");
352
353       return 1;
354     }
355
356     pipe_msg (h, fpout, decode, print);
357     fclose (fpout);
358     rc = mutt_wait_filter (thepid);
359   }
360   else {                        /* handle tagged messages */
361
362     if (WithCrypto && decode) {
363       for (i = 0; i < Context->vcount; i++)
364         if (Context->hdrs[Context->v2r[i]]->tagged) {
365           mutt_message_hook (Context, Context->hdrs[Context->v2r[i]],
366                              M_MESSAGEHOOK);
367           mutt_parse_mime_message (Context, Context->hdrs[Context->v2r[i]]);
368           if (Context->hdrs[Context->v2r[i]]->security & ENCRYPT &&
369               !crypt_valid_passphrase (Context->hdrs[Context->v2r[i]]->
370                                        security))
371             return 1;
372         }
373     }
374
375     if (split) {
376       for (i = 0; i < Context->vcount; i++) {
377         if (Context->hdrs[Context->v2r[i]]->tagged) {
378           mutt_message_hook (Context, Context->hdrs[Context->v2r[i]],
379                              M_MESSAGEHOOK);
380           mutt_endwin (NULL);
381           if ((thepid = mutt_create_filter (cmd, &fpout, NULL, NULL)) < 0) {
382             mutt_perror _("Can't create filter process");
383
384             return 1;
385           }
386           pipe_msg (Context->hdrs[Context->v2r[i]], fpout, decode, print);
387           /* add the message separator */
388           if (sep)
389             fputs (sep, fpout);
390           safe_fclose (&fpout);
391           if (mutt_wait_filter (thepid) != 0)
392             rc = 1;
393         }
394       }
395     }
396     else {
397       mutt_endwin (NULL);
398       if ((thepid = mutt_create_filter (cmd, &fpout, NULL, NULL)) < 0) {
399         mutt_perror _("Can't create filter process");
400
401         return 1;
402       }
403       for (i = 0; i < Context->vcount; i++) {
404         if (Context->hdrs[Context->v2r[i]]->tagged) {
405           mutt_message_hook (Context, Context->hdrs[Context->v2r[i]],
406                              M_MESSAGEHOOK);
407           pipe_msg (Context->hdrs[Context->v2r[i]], fpout, decode, print);
408           /* add the message separator */
409           if (sep)
410             fputs (sep, fpout);
411         }
412       }
413       safe_fclose (&fpout);
414       if (mutt_wait_filter (thepid) != 0)
415         rc = 1;
416     }
417   }
418
419   if (rc || option (OPTWAITKEY))
420     mutt_any_key_to_continue (NULL);
421   return rc;
422 }
423
424 void mutt_pipe_message (HEADER * h)
425 {
426   char buffer[LONG_STRING];
427
428   buffer[0] = 0;
429   if (mutt_get_field (_("Pipe to command: "), buffer, sizeof (buffer), M_CMD)
430       != 0 || !buffer[0])
431     return;
432
433   mutt_expand_path (buffer, sizeof (buffer));
434   _mutt_pipe_message (h, buffer,
435                       option (OPTPIPEDECODE),
436                       0, option (OPTPIPESPLIT), PipeSep);
437 }
438
439 void mutt_print_message (HEADER * h)
440 {
441
442   if (quadoption (OPT_PRINT) && (!PrintCmd || !*PrintCmd)) {
443     mutt_message (_("No printing command has been defined."));
444     return;
445   }
446
447   if (query_quadoption (OPT_PRINT,
448                         h ? _("Print message?") : _("Print tagged messages?"))
449       != M_YES)
450     return;
451
452   if (_mutt_pipe_message (h, PrintCmd,
453                           option (OPTPRINTDECODE),
454                           1, option (OPTPRINTSPLIT), "\f") == 0)
455     mutt_message (h ? _("Message printed") : _("Messages printed"));
456   else
457     mutt_message (h ? _("Message could not be printed") :
458                   _("Messages could not be printed"));
459 }
460
461
462 int mutt_select_sort (int reverse)
463 {
464   int method = Sort;            /* save the current method in case of abort */
465
466   switch (mutt_multi_choice (reverse ?
467                              _
468                              ("Rev-Sort (d)ate/(f)rm/(r)ecv/(s)ubj/t(o)/(t)hread/(u)nsort/si(z)e/s(c)ore/s(p)am?: ")
469                              :
470                              _
471                              ("Sort (d)ate/(f)rm/(r)ecv/(s)ubj/t(o)/(t)hread/(u)nsort/si(z)e/s(c)ore/s(p)am?: "),
472                              _("dfrsotuzcp"))) {
473   case -1:                     /* abort - don't resort */
474     return -1;
475
476   case 1:                      /* (d)ate */
477     Sort = SORT_DATE;
478     break;
479
480   case 2:                      /* (f)rm */
481     Sort = SORT_FROM;
482     break;
483
484   case 3:                      /* (r)ecv */
485     Sort = SORT_RECEIVED;
486     break;
487
488   case 4:                      /* (s)ubj */
489     Sort = SORT_SUBJECT;
490     break;
491
492   case 5:                      /* t(o) */
493     Sort = SORT_TO;
494     break;
495
496   case 6:                      /* (t)hread */
497     Sort = SORT_THREADS;
498     break;
499
500   case 7:                      /* (u)nsort */
501     Sort = SORT_ORDER;
502     break;
503
504   case 8:                      /* si(z)e */
505     Sort = SORT_SIZE;
506     break;
507
508   case 9:                      /* s(c)ore */
509     Sort = SORT_SCORE;
510     break;
511
512   case 10:                     /* s(p)am */
513     Sort = SORT_SPAM;
514     break;
515   }
516   if (reverse)
517     Sort |= SORT_REVERSE;
518
519   return (Sort != method ? 0 : -1);     /* no need to resort if it's the same */
520 }
521
522 /* invoke a command in a subshell */
523 void mutt_shell_escape (void)
524 {
525   char buf[LONG_STRING];
526
527   buf[0] = 0;
528   if (mutt_get_field (_("Shell command: "), buf, sizeof (buf), M_CMD) == 0) {
529     if (!buf[0] && Shell)
530       strfcpy (buf, Shell, sizeof (buf));
531     if (buf[0]) {
532       CLEARLINE (LINES - 1);
533       mutt_endwin (NULL);
534       fflush (stdout);
535       if (mutt_system (buf) != 0 || option (OPTWAITKEY))
536         mutt_any_key_to_continue (NULL);
537     }
538   }
539 }
540
541 /* enter a mutt command */
542 void mutt_enter_command (void)
543 {
544   BUFFER err, token;
545   char buffer[LONG_STRING], errbuf[SHORT_STRING];
546   int r;
547
548   buffer[0] = 0;
549   if (mutt_get_field (":", buffer, sizeof (buffer), M_COMMAND) != 0
550       || !buffer[0])
551     return;
552   err.data = errbuf;
553   err.dsize = sizeof (errbuf);
554   memset (&token, 0, sizeof (token));
555   r = mutt_parse_rc_line (buffer, &token, &err);
556   FREE (&token.data);
557   if (errbuf[0]) {
558     /* since errbuf could potentially contain printf() sequences in it,
559        we must call mutt_error() in this fashion so that vsprintf()
560        doesn't expect more arguments that we passed */
561     if (r == 0)
562       mutt_message ("%s", errbuf);
563     else
564       mutt_error ("%s", errbuf);
565   }
566 }
567
568 void mutt_display_address (ENVELOPE * env)
569 {
570   char *pfx = NULL;
571   char buf[SHORT_STRING];
572   ADDRESS *adr = NULL;
573
574   adr = mutt_get_address (env, &pfx);
575
576   if (!adr)
577     return;
578
579   /* 
580    * Note: We don't convert IDNA to local representation this time.
581    * That is intentional, so the user has an opportunity to copy &
582    * paste the on-the-wire form of the address to other, IDN-unable
583    * software. 
584    */
585
586   buf[0] = 0;
587   rfc822_write_address (buf, sizeof (buf), adr, 0);
588   mutt_message ("%s: %s", pfx, buf);
589 }
590
591 static void set_copy_flags (HEADER * hdr, int decode, int decrypt,
592                             int *cmflags, int *chflags)
593 {
594   *cmflags = 0;
595   *chflags = CH_UPDATE_LEN;
596
597   if (WithCrypto && !decode && decrypt && (hdr->security & ENCRYPT)) {
598     if ((WithCrypto & APPLICATION_PGP)
599         && mutt_is_multipart_encrypted (hdr->content)) {
600       *chflags = CH_NONEWLINE | CH_XMIT | CH_MIME;
601       *cmflags = M_CM_DECODE_PGP;
602     }
603     else if ((WithCrypto & APPLICATION_PGP)
604              && mutt_is_application_pgp (hdr->content) & ENCRYPT)
605       decode = 1;
606     else if ((WithCrypto & APPLICATION_SMIME)
607              && mutt_is_application_smime (hdr->content) & ENCRYPT) {
608       *chflags = CH_NONEWLINE | CH_XMIT | CH_MIME;
609       *cmflags = M_CM_DECODE_SMIME;
610     }
611   }
612
613   if (decode) {
614     *chflags = CH_XMIT | CH_MIME | CH_TXTPLAIN;
615     *cmflags = M_CM_DECODE | M_CM_CHARCONV;
616
617     if (!decrypt) {             /* If decode doesn't kick in for decrypt, */
618       *chflags |= CH_DECODE;    /* then decode RFC 2047 headers, */
619
620       if (option (OPTWEED)) {
621         *chflags |= CH_WEED;    /* and respect $weed. */
622         *cmflags |= M_CM_WEED;
623       }
624     }
625   }
626 }
627
628 void _mutt_save_message (HEADER * h, CONTEXT * ctx, int delete, int decode,
629                          int decrypt)
630 {
631   int cmflags, chflags;
632
633   set_copy_flags (h, decode, decrypt, &cmflags, &chflags);
634
635   if (decode || decrypt)
636     mutt_parse_mime_message (Context, h);
637
638   if (mutt_append_message (ctx, Context, h, cmflags, chflags) == 0) {
639     if (delete) {
640       mutt_set_flag (Context, h, M_DELETE, 1);
641       if (option (OPTDELETEUNTAG))
642         mutt_set_flag (Context, h, M_TAG, 0);
643     }
644     mutt_set_flag (Context, h, M_APPENDED, 1);
645   }
646 }
647
648 /* returns 0 if the copy/save was successful, or -1 on error/abort */
649 int mutt_save_message (HEADER * h, int delete,
650                        int decode, int decrypt, int *redraw)
651 {
652   int i, need_buffy_cleanup;
653   int need_passphrase = 0, app = 0;
654   char prompt[SHORT_STRING], buf[_POSIX_PATH_MAX];
655   CONTEXT ctx;
656   struct stat st;
657
658 #ifdef BUFFY_SIZE
659   BUFFY *tmp = NULL;
660 #else
661   struct utimbuf ut;
662 #endif
663
664   *redraw = 0;
665
666
667   snprintf (prompt, sizeof (prompt),
668             decode ? (delete ? _("Decode-save%s to mailbox") :
669                       _("Decode-copy%s to mailbox")) :
670             (decrypt ? (delete ? _("Decrypt-save%s to mailbox") :
671                         _("Decrypt-copy%s to mailbox")) :
672              (delete ? _("Save%s to mailbox") : _("Copy%s to mailbox"))),
673             h ? "" : _(" tagged"));
674
675
676   if (h) {
677     if (WithCrypto) {
678       need_passphrase = h->security & ENCRYPT;
679       app = h->security;
680     }
681     mutt_message_hook (Context, h, M_MESSAGEHOOK);
682     mutt_default_save (buf, sizeof (buf), h);
683   }
684   else {
685     /* look for the first tagged message */
686
687     for (i = 0; i < Context->vcount; i++) {
688       if (Context->hdrs[Context->v2r[i]]->tagged) {
689         h = Context->hdrs[Context->v2r[i]];
690         break;
691       }
692     }
693
694
695     if (h) {
696       mutt_message_hook (Context, h, M_MESSAGEHOOK);
697       mutt_default_save (buf, sizeof (buf), h);
698       if (WithCrypto) {
699         need_passphrase = h->security & ENCRYPT;
700         app = h->security;
701       }
702       h = NULL;
703     }
704   }
705
706   mutt_pretty_mailbox (buf);
707   if (mutt_enter_fname (prompt, buf, sizeof (buf), redraw, 0) == -1)
708     return (-1);
709
710   if (*redraw != REDRAW_FULL) {
711     if (!h)
712       *redraw = REDRAW_INDEX | REDRAW_STATUS;
713     else
714       *redraw = REDRAW_STATUS;
715   }
716
717   if (!buf[0])
718     return (-1);
719
720   /* This is an undocumented feature of ELM pointed out to me by Felix von
721    * Leitner <leitner@prz.fu-berlin.de>
722    */
723   if (mutt_strcmp (buf, ".") == 0)
724     strfcpy (buf, LastSaveFolder, sizeof (buf));
725   else
726     strfcpy (LastSaveFolder, buf, sizeof (LastSaveFolder));
727
728   mutt_expand_path (buf, sizeof (buf));
729
730   /* check to make sure that this file is really the one the user wants */
731   if (mutt_save_confirm (buf, &st) != 0)
732     return -1;
733
734   if (WithCrypto && need_passphrase && (decode || decrypt)
735       && !crypt_valid_passphrase (app))
736     return -1;
737
738   mutt_message (_("Copying to %s..."), buf);
739
740 #ifdef USE_IMAP
741   if (Context->magic == M_IMAP && !(decode || decrypt) && mx_is_imap (buf)) {
742     switch (imap_copy_messages (Context, h, buf, delete)) {
743       /* success */
744     case 0:
745       mutt_clear_error ();
746       return 0;
747       /* non-fatal error: fall through to fetch/append */
748     case 1:
749       break;
750       /* fatal error, abort */
751     case -1:
752       return -1;
753     }
754   }
755 #endif
756
757   if (mx_open_mailbox (buf, M_APPEND, &ctx) != NULL) {
758     if (h)
759       _mutt_save_message (h, &ctx, delete, decode, decrypt);
760     else {
761       for (i = 0; i < Context->vcount; i++) {
762         if (Context->hdrs[Context->v2r[i]]->tagged) {
763           mutt_message_hook (Context, Context->hdrs[Context->v2r[i]],
764                              M_MESSAGEHOOK);
765           _mutt_save_message (Context->hdrs[Context->v2r[i]], &ctx, delete,
766                               decode, decrypt);
767         }
768       }
769     }
770
771     need_buffy_cleanup = (ctx.magic == M_MBOX || ctx.magic == M_MMDF);
772
773     mx_close_mailbox (&ctx, NULL);
774
775     if (need_buffy_cleanup) {
776 #ifdef BUFFY_SIZE
777       tmp = mutt_find_mailbox (buf);
778       if (tmp && tmp->new <= 0)
779         mutt_update_mailbox (tmp);
780 #else
781       /* fix up the times so buffy won't get confused */
782       if (st.st_mtime > st.st_atime) {
783         ut.actime = st.st_atime;
784         ut.modtime = time (NULL);
785         utime (buf, &ut);
786       }
787       else
788         utime (buf, NULL);
789 #endif
790     }
791
792     mutt_clear_error ();
793     return (0);
794   }
795
796   return -1;
797 }
798
799 int mutt_update_list_file (char *filename, char *section, char *key,
800                            char *line)
801 {
802   FILE *ifp;
803   FILE *ofp;
804   char buf[HUGE_STRING];
805   char oldfile[_POSIX_PATH_MAX];
806   char *c;
807   int ext = 0, done = 0, r = 0;
808
809   snprintf (oldfile, sizeof (oldfile), "%s.bak", filename);
810   dprint (1, (debugfile, "Renaming %s to %s\n", filename, oldfile));
811
812   /* if file not exist, create it */
813   if ((ifp = safe_fopen (filename, "a")))
814     fclose (ifp);
815   if (_mutt_rename_file (filename, oldfile, 1)) {
816     mutt_perror _("Unable to create backup file");
817
818     return (-1);
819   }
820   dprint (1, (debugfile, "Opening %s\n", oldfile));
821   if (!(ifp = safe_fopen (oldfile, "r"))) {
822     mutt_perror _("Unable to open backup file for reading");
823
824     return (-1);
825   }
826   dprint (1, (debugfile, "Opening %s\n", filename));
827   if (!(ofp = safe_fopen (filename, "w"))) {
828     fclose (ifp);
829     mutt_perror _("Unable to open new file for writing");
830
831     return (-1);
832   }
833   if (mx_lock_file (filename, fileno (ofp), 1, 0, 1)) {
834     fclose (ofp);
835     fclose (ifp);
836     mutt_error (_("Unable to lock %s, old file saved as %s"), filename,
837                 oldfile);
838     return (-1);
839   }
840
841   if (section) {
842     while (r != EOF && !done && fgets (buf, sizeof (buf), ifp)) {
843       r = fputs (buf, ofp);
844       c = buf;
845       while (*c && *c != '\n')
846         c++;
847       c[0] = 0;                 /* strip EOL */
848       if (!strncmp (buf, "#: ", 3) && !mutt_strcasecmp (buf + 3, section))
849         done++;
850     }
851     if (r != EOF && !done) {
852       snprintf (buf, sizeof (buf), "#: %s\n", section);
853       r = fputs (buf, ofp);
854     }
855     done = 0;
856   }
857
858   while (r != EOF && fgets (buf, sizeof (buf), ifp)) {
859     if (ext) {
860       c = buf;
861       while (*c && (*c != '\r') && (*c != '\n'))
862         c++;
863       c--;
864       if (*c != '\\')
865         ext = 0;
866     }
867     else if ((section && !strncmp (buf, "#: ", 3))) {
868       if (!done && line) {
869         fputs (line, ofp);
870         fputc ('\n', ofp);
871       }
872       r = fputs (buf, ofp);
873       done++;
874       break;
875     }
876     else if (key && !strncmp (buf, key, strlen (key)) &&
877              (!*key || buf[strlen (key)] == ' ')) {
878       c = buf;
879       ext = 0;
880       while (*c && (*c != '\r') && (*c != '\n'))
881         c++;
882       c--;
883       if (*c == '\\')
884         ext = 1;
885       if (!done && line) {
886         r = fputs (line, ofp);
887         if (*key)
888           r = fputc ('\n', ofp);
889         done++;
890       }
891     }
892     else {
893       r = fputs (buf, ofp);
894     }
895   }
896
897   while (r != EOF && fgets (buf, sizeof (buf), ifp))
898     r = fputs (buf, ofp);
899
900   /* If there wasn't a line to replace, put it on the end of the file */
901   if (r != EOF && !done && line) {
902     fputs (line, ofp);
903     r = fputc ('\n', ofp);
904   }
905   mx_unlock_file (filename, fileno (ofp), 0);
906   fclose (ofp);
907   fclose (ifp);
908   if (r != EOF) {
909     unlink (oldfile);
910     return 0;
911   }
912   unlink (filename);
913   mutt_error (_("Cannot write new %s, old file saved as %s"), filename,
914               oldfile);
915   return (-1);
916 }
917
918
919 void mutt_version (void)
920 {
921   mutt_message ("Mutt-ng %s (%s)", MUTT_VERSION, ReleaseDate);
922 }
923
924 void mutt_edit_content_type (HEADER * h, BODY * b, FILE * fp)
925 {
926   char buf[LONG_STRING];
927   char obuf[LONG_STRING];
928   char tmp[STRING];
929   PARAMETER *p;
930
931   char charset[STRING];
932   char *cp;
933
934   short charset_changed = 0;
935   short type_changed = 0;
936
937   cp = mutt_get_parameter ("charset", b->parameter);
938   strfcpy (charset, NONULL (cp), sizeof (charset));
939
940   snprintf (buf, sizeof (buf), "%s/%s", TYPE (b), b->subtype);
941   strfcpy (obuf, buf, sizeof (obuf));
942   if (b->parameter) {
943     size_t l;
944
945     for (p = b->parameter; p; p = p->next) {
946       l = strlen (buf);
947
948       rfc822_cat (tmp, sizeof (tmp), p->value, MimeSpecials);
949       snprintf (buf + l, sizeof (buf) - l, "; %s=%s", p->attribute, tmp);
950     }
951   }
952
953   if (mutt_get_field ("Content-Type: ", buf, sizeof (buf), 0) != 0 ||
954       buf[0] == 0)
955     return;
956
957   /* clean up previous junk */
958   mutt_free_parameter (&b->parameter);
959   FREE (&b->subtype);
960
961   mutt_parse_content_type (buf, b);
962
963
964   snprintf (tmp, sizeof (tmp), "%s/%s", TYPE (b), NONULL (b->subtype));
965   type_changed = ascii_strcasecmp (tmp, obuf);
966   charset_changed =
967     ascii_strcasecmp (charset, mutt_get_parameter ("charset", b->parameter));
968
969   /* if in send mode, check for conversion - current setting is default. */
970
971   if (!h && b->type == TYPETEXT && charset_changed) {
972     int r;
973
974     snprintf (tmp, sizeof (tmp), _("Convert to %s upon sending?"),
975               mutt_get_parameter ("charset", b->parameter));
976     if ((r = mutt_yesorno (tmp, !b->noconv)) != -1)
977       b->noconv = (r == M_NO);
978   }
979
980   /* inform the user */
981
982   snprintf (tmp, sizeof (tmp), "%s/%s", TYPE (b), NONULL (b->subtype));
983   if (type_changed)
984     mutt_message (_("Content-Type changed to %s."), tmp);
985   if (b->type == TYPETEXT && charset_changed) {
986     if (type_changed)
987       mutt_sleep (1);
988     mutt_message (_("Character set changed to %s; %s."),
989                   mutt_get_parameter ("charset", b->parameter),
990                   b->noconv ? _("not converting") : _("converting"));
991   }
992
993   b->force_charset |= charset_changed ? 1 : 0;
994
995   if (!is_multipart (b) && b->parts)
996     mutt_free_body (&b->parts);
997   if (!mutt_is_message_type (b->type, b->subtype) && b->hdr) {
998     b->hdr->content = NULL;
999     mutt_free_header (&b->hdr);
1000   }
1001
1002   if (fp && (is_multipart (b) || mutt_is_message_type (b->type, b->subtype)))
1003     mutt_parse_part (fp, b);
1004
1005   if (WithCrypto && h) {
1006     if (h->content == b)
1007       h->security = 0;
1008
1009     h->security |= crypt_query (b);
1010   }
1011 }
1012
1013
1014 static int _mutt_check_traditional_pgp (HEADER * h, int *redraw)
1015 {
1016   MESSAGE *msg;
1017   int rv = 0;
1018
1019   h->security |= PGP_TRADITIONAL_CHECKED;
1020
1021   mutt_parse_mime_message (Context, h);
1022   if ((msg = mx_open_message (Context, h->msgno)) == NULL)
1023     return 0;
1024   if (crypt_pgp_check_traditional (msg->fp, h->content, 0)) {
1025     h->security = crypt_query (h->content);
1026     *redraw |= REDRAW_FULL;
1027     rv = 1;
1028   }
1029
1030   h->security |= PGP_TRADITIONAL_CHECKED;
1031   mx_close_message (&msg);
1032   return rv;
1033 }
1034
1035 int mutt_check_traditional_pgp (HEADER * h, int *redraw)
1036 {
1037   int i;
1038   int rv = 0;
1039
1040   if (h && !(h->security & PGP_TRADITIONAL_CHECKED))
1041     rv = _mutt_check_traditional_pgp (h, redraw);
1042   else {
1043     for (i = 0; i < Context->vcount; i++)
1044       if (Context->hdrs[Context->v2r[i]]->tagged &&
1045           !(Context->hdrs[Context->v2r[i]]->
1046             security & PGP_TRADITIONAL_CHECKED))
1047         rv =
1048           _mutt_check_traditional_pgp (Context->hdrs[Context->v2r[i]], redraw)
1049           || rv;
1050   }
1051   return rv;
1052 }