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