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