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