Andreas Krennmair:
[apps/madmutt.git] / send.c
1 /*
2  * Copyright (C) 1996-2002 Michael R. Elkins <me@mutt.org>
3  * 
4  *     This program is free software; you can redistribute it and/or modify
5  *     it under the terms of the GNU General Public License as published by
6  *     the Free Software Foundation; either version 2 of the License, or
7  *     (at your option) any later version.
8  * 
9  *     This program is distributed in the hope that it will be useful,
10  *     but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *     GNU General Public License for more details.
13  * 
14  *     You should have received a copy of the GNU General Public License
15  *     along with this program; if not, write to the Free Software
16  *     Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
17  */
18
19 #if HAVE_CONFIG_H
20 # include "config.h"
21 #endif
22
23 #include "mutt.h"
24 #include "mutt_curses.h"
25 #include "rfc2047.h"
26 #include "keymap.h"
27 #include "mime.h"
28 #include "mailbox.h"
29 #include "copy.h"
30 #include "mx.h"
31 #include "mutt_crypt.h"
32 #include "mutt_idna.h"
33 #include "url.h"
34
35 #include <ctype.h>
36 #include <stdlib.h>
37 #include <unistd.h>
38 #include <string.h>
39 #include <errno.h>
40 #include <sys/stat.h>
41 #include <sys/wait.h>
42 #include <dirent.h>
43 #include <time.h>
44 #include <sys/types.h>
45 #include <utime.h>
46
47 #ifdef USE_NNTP
48 #include "nntp.h"
49 #endif
50
51 #ifdef MIXMASTER
52 #include "remailer.h"
53 #endif
54
55
56 static void append_signature (FILE * f)
57 {
58   FILE *tmpfp;
59   pid_t thepid;
60
61   if (SignOffString) {
62     fprintf (f, "\n%s", SignOffString);
63   }
64
65   if (Signature && (tmpfp = mutt_open_read (Signature, &thepid))) {
66     if (option (OPTSIGDASHES))
67       fputs ("\n-- \n", f);
68     else if (SignOffString)
69       fputs ("\n", f);
70     mutt_copy_stream (tmpfp, f);
71     fclose (tmpfp);
72     if (thepid != -1)
73       mutt_wait_filter (thepid);
74   }
75 }
76
77 /* compare two e-mail addresses and return 1 if they are equivalent */
78 static int mutt_addrcmp (ADDRESS * a, ADDRESS * b)
79 {
80   if (!a->mailbox || !b->mailbox)
81     return 0;
82   if (ascii_strcasecmp (a->mailbox, b->mailbox))
83     return 0;
84   return 1;
85 }
86
87 /* search an e-mail address in a list */
88 static int mutt_addrsrc (ADDRESS * a, ADDRESS * lst)
89 {
90   for (; lst; lst = lst->next) {
91     if (mutt_addrcmp (a, lst))
92       return (1);
93   }
94   return (0);
95 }
96
97 /* removes addresses from "b" which are contained in "a" */
98 static ADDRESS *mutt_remove_xrefs (ADDRESS * a, ADDRESS * b)
99 {
100   ADDRESS *top, *p, *prev = NULL;
101
102   top = b;
103   while (b) {
104     for (p = a; p; p = p->next) {
105       if (mutt_addrcmp (p, b))
106         break;
107     }
108     if (p) {
109       if (prev) {
110         prev->next = b->next;
111         b->next = NULL;
112         rfc822_free_address (&b);
113         b = prev;
114       }
115       else {
116         top = top->next;
117         b->next = NULL;
118         rfc822_free_address (&b);
119         b = top;
120       }
121     }
122     else {
123       prev = b;
124       b = b->next;
125     }
126   }
127   return top;
128 }
129
130 /* remove any address which matches the current user.  if `leave_only' is
131  * nonzero, don't remove the user's address if it is the only one in the list
132  */
133 static ADDRESS *remove_user (ADDRESS * a, int leave_only)
134 {
135   ADDRESS *top = NULL, *last = NULL;
136
137   while (a) {
138     if (!mutt_addr_is_user (a)) {
139       if (top) {
140         last->next = a;
141         last = last->next;
142       }
143       else
144         last = top = a;
145       a = a->next;
146       last->next = NULL;
147     }
148     else {
149       ADDRESS *tmp = a;
150
151       a = a->next;
152       if (!leave_only || a || last) {
153         tmp->next = NULL;
154         rfc822_free_address (&tmp);
155       }
156       else
157         last = top = tmp;
158     }
159   }
160   return top;
161 }
162
163 static ADDRESS *find_mailing_lists (ADDRESS * t, ADDRESS * c)
164 {
165   ADDRESS *top = NULL, *ptr = NULL;
166
167   for (; t || c; t = c, c = NULL) {
168     for (; t; t = t->next) {
169       if (mutt_is_mail_list (t) && !t->group) {
170         if (top) {
171           ptr->next = rfc822_cpy_adr_real (t);
172           ptr = ptr->next;
173         }
174         else
175           ptr = top = rfc822_cpy_adr_real (t);
176       }
177     }
178   }
179   return top;
180 }
181
182 static int edit_address (ADDRESS ** a, /* const */ char *field)
183 {
184   char buf[HUGE_STRING];
185   char *err = NULL;
186   int idna_ok = 0;
187
188   do {
189     buf[0] = 0;
190     mutt_addrlist_to_local (*a);
191     rfc822_write_address (buf, sizeof (buf), *a, 0);
192     if (mutt_get_field (field, buf, sizeof (buf), M_ALIAS) != 0)
193       return (-1);
194     rfc822_free_address (a);
195     *a = mutt_expand_aliases (mutt_parse_adrlist (NULL, buf));
196     if ((idna_ok = mutt_addrlist_to_idna (*a, &err)) != 0) {
197       mutt_error (_("Error: '%s' is a bad IDN."), err);
198       mutt_refresh ();
199       mutt_sleep (2);
200       FREE (&err);
201     }
202   }
203   while (idna_ok != 0);
204   return 0;
205 }
206
207 static int edit_envelope (ENVELOPE * en, int flags)
208 {
209   char buf[HUGE_STRING];
210   LIST *uh = UserHeader;
211   regmatch_t pat_match[1];
212
213 #ifdef USE_NNTP
214   if (option (OPTNEWSSEND)) {
215     if (en->newsgroups)
216       strfcpy (buf, en->newsgroups, sizeof (buf));
217     else
218       buf[0] = 0;
219     if (mutt_get_field ("Newsgroups: ", buf, sizeof (buf), 0) != 0)
220       return (-1);
221     FREE (&en->newsgroups);
222     en->newsgroups = safe_strdup (buf);
223
224     if (en->followup_to)
225       strfcpy (buf, en->followup_to, sizeof (buf));
226     else
227       buf[0] = 0;
228     if (option (OPTASKFOLLOWUP)
229         && mutt_get_field ("Followup-To: ", buf, sizeof (buf), 0) != 0)
230       return (-1);
231     FREE (&en->followup_to);
232     en->followup_to = safe_strdup (buf);
233
234     if (en->x_comment_to)
235       strfcpy (buf, en->x_comment_to, sizeof (buf));
236     else
237       buf[0] = 0;
238     if (option (OPTXCOMMENTTO) && option (OPTASKXCOMMENTTO)
239         && mutt_get_field ("X-Comment-To: ", buf, sizeof (buf), 0) != 0)
240       return (-1);
241     FREE (&en->x_comment_to);
242     en->x_comment_to = safe_strdup (buf);
243   }
244   else
245 #endif
246   {
247     if (edit_address (&en->to, "To: ") == -1 || en->to == NULL)
248       return (-1);
249     if (option (OPTASKCC) && edit_address (&en->cc, "Cc: ") == -1)
250       return (-1);
251     if (option (OPTASKBCC) && edit_address (&en->bcc, "Bcc: ") == -1)
252       return (-1);
253   }
254
255   if (en->subject) {
256     if (option (OPTFASTREPLY))
257       return (0);
258     else
259       strfcpy (buf, en->subject, sizeof (buf));
260   }
261   else {
262     char *p;
263
264     buf[0] = 0;
265     for (; uh; uh = uh->next) {
266       if (ascii_strncasecmp ("subject:", uh->data, 8) == 0) {
267         p = uh->data + 8;
268         SKIPWS (p);
269         strncpy (buf, p, sizeof (buf));
270       }
271     }
272   }
273
274   if ((flags & (SENDREPLY)) && option (OPTSTRIPWAS) && StripWasRegexp.rx &&
275       regexec (StripWasRegexp.rx, buf, 1, pat_match, 0) == 0) {
276     unsigned int pos = pat_match->rm_so;
277
278     if (ascii_strncasecmp (buf, "re: ", pos) != 0) {
279       buf[pos] = '\0';          /* kill match */
280       while (pos-- && buf[pos] == ' ')
281         buf[pos] = '\0';        /* remove trailing spaces */
282     }
283     else {
284       mutt_error (_("Ignoring $strip_was: Subject would be empty."));
285       sleep (2);
286     }
287   }
288   if (mutt_get_field ("Subject: ", buf, sizeof (buf), 0) != 0 || (!buf[0]
289                                                                   &&
290                                                                   query_quadoption
291                                                                   (OPT_SUBJECT,
292                                                                    _
293                                                                    ("No subject, abort?"))
294                                                                   != M_NO)) {
295     mutt_message _("No subject, aborting.");
296
297     return (-1);
298   }
299   mutt_str_replace (&en->subject, buf);
300
301   return 0;
302 }
303
304 #ifdef USE_NNTP
305 char *nntp_get_header (const char *s)
306 {
307   SKIPWS (s);
308   return safe_strdup (s);
309 }
310 #endif
311
312 static void process_user_recips (ENVELOPE * env)
313 {
314   LIST *uh = UserHeader;
315
316   for (; uh; uh = uh->next) {
317     if (ascii_strncasecmp ("to:", uh->data, 3) == 0)
318       env->to = rfc822_parse_adrlist (env->to, uh->data + 3);
319     else if (ascii_strncasecmp ("cc:", uh->data, 3) == 0)
320       env->cc = rfc822_parse_adrlist (env->cc, uh->data + 3);
321     else if (ascii_strncasecmp ("bcc:", uh->data, 4) == 0)
322       env->bcc = rfc822_parse_adrlist (env->bcc, uh->data + 4);
323 #ifdef USE_NNTP
324     else if (ascii_strncasecmp ("newsgroups:", uh->data, 11) == 0)
325       env->newsgroups = nntp_get_header (uh->data + 11);
326     else if (ascii_strncasecmp ("followup-to:", uh->data, 12) == 0)
327       env->followup_to = nntp_get_header (uh->data + 12);
328     else if (ascii_strncasecmp ("x-comment-to:", uh->data, 13) == 0)
329       env->x_comment_to = nntp_get_header (uh->data + 13);
330 #endif
331   }
332 }
333
334 static void process_user_header (ENVELOPE * env)
335 {
336   LIST *uh = UserHeader;
337   LIST *last = env->userhdrs;
338
339   if (last)
340     while (last->next)
341       last = last->next;
342
343   for (; uh; uh = uh->next) {
344     if (ascii_strncasecmp ("from:", uh->data, 5) == 0) {
345       /* User has specified a default From: address.  Remove default address */
346       rfc822_free_address (&env->from);
347       env->from = rfc822_parse_adrlist (env->from, uh->data + 5);
348     }
349     else if (ascii_strncasecmp ("reply-to:", uh->data, 9) == 0) {
350       rfc822_free_address (&env->reply_to);
351       env->reply_to = rfc822_parse_adrlist (env->reply_to, uh->data + 9);
352     }
353     else if (ascii_strncasecmp ("message-id:", uh->data, 11) == 0)
354       mutt_str_replace (&env->message_id, uh->data + 11);
355     else if (ascii_strncasecmp ("to:", uh->data, 3) != 0 &&
356              ascii_strncasecmp ("cc:", uh->data, 3) != 0 &&
357              ascii_strncasecmp ("bcc:", uh->data, 4) != 0 &&
358 #ifdef USE_NNTP
359              ascii_strncasecmp ("newsgroups:", uh->data, 11) != 0 &&
360              ascii_strncasecmp ("followup-to:", uh->data, 12) != 0 &&
361              ascii_strncasecmp ("x-comment-to:", uh->data, 13) != 0 &&
362 #endif
363              ascii_strncasecmp ("supersedes:", uh->data, 11) != 0 &&
364              ascii_strncasecmp ("subject:", uh->data, 8) != 0) {
365       if (last) {
366         last->next = mutt_new_list ();
367         last = last->next;
368       }
369       else
370         last = env->userhdrs = mutt_new_list ();
371       last->data = safe_strdup (uh->data);
372     }
373   }
374 }
375
376 LIST *mutt_copy_list (LIST * p)
377 {
378   LIST *t, *r = NULL, *l = NULL;
379
380   for (; p; p = p->next) {
381     t = (LIST *) safe_malloc (sizeof (LIST));
382     t->data = safe_strdup (p->data);
383     t->next = NULL;
384     if (l) {
385       r->next = t;
386       r = r->next;
387     }
388     else
389       l = r = t;
390   }
391   return (l);
392 }
393
394 void mutt_forward_intro (FILE * fp, HEADER * cur)
395 {
396   char buffer[STRING];
397
398   fputs ("----- Forwarded message from ", fp);
399   buffer[0] = 0;
400   rfc822_write_address (buffer, sizeof (buffer), cur->env->from, 1);
401   fputs (buffer, fp);
402   fputs (" -----\n\n", fp);
403 }
404
405 void mutt_forward_trailer (FILE * fp)
406 {
407   fputs ("\n----- End forwarded message -----\n", fp);
408 }
409
410
411 static int include_forward (CONTEXT * ctx, HEADER * cur, FILE * out)
412 {
413   int chflags = CH_DECODE, cmflags = 0;
414
415   mutt_parse_mime_message (ctx, cur);
416   mutt_message_hook (ctx, cur, M_MESSAGEHOOK);
417
418   if (WithCrypto && (cur->security & ENCRYPT) && option (OPTFORWDECODE)) {
419     /* make sure we have the user's passphrase before proceeding... */
420     crypt_valid_passphrase (cur->security);
421   }
422
423   mutt_forward_intro (out, cur);
424
425   if (option (OPTFORWDECODE)) {
426     cmflags |= M_CM_DECODE | M_CM_CHARCONV;
427     if (option (OPTWEED)) {
428       chflags |= CH_WEED | CH_REORDER;
429       cmflags |= M_CM_WEED;
430     }
431   }
432   if (option (OPTFORWQUOTE))
433     cmflags |= M_CM_PREFIX;
434
435   mutt_copy_message (out, ctx, cur, cmflags, chflags);
436   mutt_forward_trailer (out);
437   return 0;
438 }
439
440 void mutt_make_attribution (CONTEXT * ctx, HEADER * cur, FILE * out)
441 {
442   char buffer[STRING];
443
444   if (Attribution) {
445     mutt_make_string (buffer, sizeof (buffer), Attribution, ctx, cur);
446     fputs (buffer, out);
447     fputc ('\n', out);
448   }
449 }
450
451 void mutt_make_post_indent (CONTEXT * ctx, HEADER * cur, FILE * out)
452 {
453   char buffer[STRING];
454
455   if (PostIndentString) {
456     mutt_make_string (buffer, sizeof (buffer), PostIndentString, ctx, cur);
457     fputs (buffer, out);
458     fputc ('\n', out);
459   }
460 }
461
462 static int include_reply (CONTEXT * ctx, HEADER * cur, FILE * out)
463 {
464   int cmflags = M_CM_PREFIX | M_CM_DECODE | M_CM_CHARCONV | M_CM_REPLYING;
465   int chflags = CH_DECODE;
466
467   if (WithCrypto && (cur->security & ENCRYPT)) {
468     /* make sure we have the user's passphrase before proceeding... */
469     crypt_valid_passphrase (cur->security);
470   }
471
472   mutt_parse_mime_message (ctx, cur);
473   mutt_message_hook (ctx, cur, M_MESSAGEHOOK);
474
475   mutt_make_attribution (ctx, cur, out);
476
477   if (!option (OPTHEADER))
478     cmflags |= M_CM_NOHEADER;
479   if (option (OPTWEED)) {
480     chflags |= CH_WEED | CH_REORDER;
481     cmflags |= M_CM_WEED;
482   }
483
484   mutt_copy_message (out, ctx, cur, cmflags, chflags);
485
486   mutt_make_post_indent (ctx, cur, out);
487
488   return 0;
489 }
490
491 static int default_to (ADDRESS ** to, ENVELOPE * env, int flags, int hmfupto)
492 {
493   char prompt[STRING];
494   ADDRESS *tmp;
495
496   if (flags && env->mail_followup_to && hmfupto == M_YES) {
497     rfc822_append (to, env->mail_followup_to);
498     return 0;
499   }
500
501   /* Exit now if we're setting up the default Cc list for list-reply
502    * (only set if Mail-Followup-To is present and honoured).
503    */
504   if (flags & SENDLISTREPLY)
505     return 0;
506
507   /* If this message came from a mailing list, ask the user if he really
508    * intended to reply to the author only.
509    */
510   if (!(flags & SENDGROUPREPLY) && mutt_is_list_cc (0, env->to, env->cc)) {
511     switch (query_quadoption (OPT_LISTREPLY,
512                               _
513                               ("Message came from a mailing list. Reply to author only?")))
514     {
515     case M_NO:
516       tmp = find_mailing_lists (env->to, env->cc);
517       rfc822_append (to, tmp);
518       rfc822_free_address (&tmp);
519       return 0;
520     case -1:
521       return -1;                /* abort */
522     }
523   }
524
525   if (!option (OPTREPLYSELF) && mutt_addr_is_user (env->from)) {
526     /* mail is from the user, assume replying to recipients */
527     rfc822_append (to, env->to);
528   }
529   else if (env->reply_to) {
530     if ((mutt_addrcmp (env->from, env->reply_to) && !env->reply_to->next) ||
531         (option (OPTIGNORELISTREPLYTO) &&
532          mutt_is_mail_list (env->reply_to) &&
533          (mutt_addrsrc (env->reply_to, env->to) ||
534           mutt_addrsrc (env->reply_to, env->cc)))) {
535       /* If the Reply-To: address is a mailing list, assume that it was
536        * put there by the mailing list, and use the From: address
537        * 
538        * We also take the from header if our correspondant has a reply-to
539        * header which is identical to the electronic mail address given
540        * in his From header.
541        * 
542        */
543       rfc822_append (to, env->from);
544     }
545     else if (!(mutt_addrcmp (env->from, env->reply_to) &&
546                !env->reply_to->next) && quadoption (OPT_REPLYTO) != M_YES) {
547       /* There are quite a few mailing lists which set the Reply-To:
548        * header field to the list address, which makes it quite impossible
549        * to send a message to only the sender of the message.  This
550        * provides a way to do that.
551        */
552       snprintf (prompt, sizeof (prompt), _("Reply to %s%s?"),
553                 env->reply_to->mailbox, env->reply_to->next ? ",..." : "");
554       switch (query_quadoption (OPT_REPLYTO, prompt)) {
555       case M_YES:
556         rfc822_append (to, env->reply_to);
557         break;
558
559       case M_NO:
560         rfc822_append (to, env->from);
561         break;
562
563       default:
564         return (-1);            /* abort */
565       }
566     }
567     else
568       rfc822_append (to, env->reply_to);
569   }
570   else
571     rfc822_append (to, env->from);
572
573   return (0);
574 }
575
576 int mutt_fetch_recips (ENVELOPE * out, ENVELOPE * in, int flags)
577 {
578   char prompt[STRING];
579   ADDRESS *tmp;
580   int hmfupto = -1;
581
582   if ((flags & (SENDLISTREPLY | SENDGROUPREPLY)) && in->mail_followup_to) {
583     snprintf (prompt, sizeof (prompt), _("Follow-up to %s%s?"),
584               in->mail_followup_to->mailbox,
585               in->mail_followup_to->next ? ",..." : "");
586
587     if ((hmfupto = query_quadoption (OPT_MFUPTO, prompt)) == -1)
588       return -1;
589   }
590
591   if (flags & SENDLISTREPLY) {
592     tmp = find_mailing_lists (in->to, in->cc);
593     rfc822_append (&out->to, tmp);
594     rfc822_free_address (&tmp);
595
596     if (in->mail_followup_to && hmfupto == M_YES &&
597         default_to (&out->cc, in, flags & SENDLISTREPLY, hmfupto) == -1)
598       return (-1);              /* abort */
599   }
600   else {
601     if (default_to (&out->to, in, flags & SENDGROUPREPLY, hmfupto) == -1)
602       return (-1);              /* abort */
603
604     if ((flags & SENDGROUPREPLY)
605         && (!in->mail_followup_to || hmfupto != M_YES)) {
606       /* if(!mutt_addr_is_user(in->to)) */
607       rfc822_append (&out->cc, in->to);
608       rfc822_append (&out->cc, in->cc);
609     }
610   }
611   return 0;
612 }
613
614 LIST *mutt_make_references (ENVELOPE * e)
615 {
616   LIST *t = NULL, *l = NULL;
617
618   if (e->references)
619     l = mutt_copy_list (e->references);
620   else
621     l = mutt_copy_list (e->in_reply_to);
622
623   if (e->message_id) {
624     t = mutt_new_list ();
625     t->data = safe_strdup (e->message_id);
626     t->next = l;
627     l = t;
628   }
629
630   return l;
631 }
632
633 void mutt_fix_reply_recipients (ENVELOPE * env)
634 {
635   mutt_expand_aliases_env (env);
636
637   if (!option (OPTMETOO)) {
638     /* the order is important here.  do the CC: first so that if the
639      * the user is the only recipient, it ends up on the TO: field
640      */
641     env->cc = remove_user (env->cc, (env->to == NULL));
642     env->to = remove_user (env->to, (env->cc == NULL));
643   }
644
645   /* the CC field can get cluttered, especially with lists */
646   env->to = mutt_remove_duplicates (env->to);
647   env->cc = mutt_remove_duplicates (env->cc);
648   env->cc = mutt_remove_xrefs (env->to, env->cc);
649 }
650
651 void mutt_make_forward_subject (ENVELOPE * env, CONTEXT * ctx, HEADER * cur)
652 {
653   char buffer[STRING];
654
655   /* set the default subject for the message. */
656   mutt_make_string (buffer, sizeof (buffer), NONULL (ForwFmt), ctx, cur);
657   mutt_str_replace (&env->subject, buffer);
658 }
659
660 void mutt_make_misc_reply_headers (ENVELOPE * env, CONTEXT * ctx,
661                                    HEADER * cur, ENVELOPE * curenv)
662 {
663   /* This takes precedence over a subject that might have
664    * been taken from a List-Post header.  Is that correct?
665    */
666   if (curenv->real_subj) {
667     FREE (&env->subject);
668     env->subject = safe_malloc (mutt_strlen (curenv->real_subj) + 5);
669     sprintf (env->subject, "Re: %s", curenv->real_subj);        /* __SPRINTF_CHECKED__ */
670   }
671   else if (!env->subject)
672     env->subject = safe_strdup ("Re: your mail");
673
674 #ifdef USE_NNTP
675   if (option (OPTNEWSSEND) && option (OPTXCOMMENTTO) && curenv->from)
676     env->x_comment_to = safe_strdup (mutt_get_name (curenv->from));
677 #endif
678 }
679
680 void mutt_add_to_reference_headers (ENVELOPE * env, ENVELOPE * curenv,
681                                     LIST *** pp, LIST *** qq)
682 {
683   LIST **p = NULL, **q = NULL;
684
685   if (pp)
686     p = *pp;
687   if (qq)
688     q = *qq;
689
690   if (!p)
691     p = &env->references;
692   if (!q)
693     q = &env->in_reply_to;
694
695   while (*p)
696     p = &(*p)->next;
697   while (*q)
698     q = &(*q)->next;
699
700   *p = mutt_make_references (curenv);
701
702   if (curenv->message_id) {
703     *q = mutt_new_list ();
704     (*q)->data = safe_strdup (curenv->message_id);
705   }
706
707   if (pp)
708     *pp = p;
709   if (qq)
710     *qq = q;
711
712 }
713
714 static void
715 mutt_make_reference_headers (ENVELOPE * curenv, ENVELOPE * env, CONTEXT * ctx)
716 {
717   env->references = NULL;
718   env->in_reply_to = NULL;
719
720   if (!curenv) {
721     HEADER *h;
722     LIST **p = NULL, **q = NULL;
723     int i;
724
725     for (i = 0; i < ctx->vcount; i++) {
726       h = ctx->hdrs[ctx->v2r[i]];
727       if (h->tagged)
728         mutt_add_to_reference_headers (env, h->env, &p, &q);
729     }
730   }
731   else
732     mutt_add_to_reference_headers (env, curenv, NULL, NULL);
733 }
734
735 static int
736 envelope_defaults (ENVELOPE * env, CONTEXT * ctx, HEADER * cur, int flags)
737 {
738   ENVELOPE *curenv = NULL;
739   int i = 0, tag = 0;
740
741   if (!cur) {
742     tag = 1;
743     for (i = 0; i < ctx->vcount; i++)
744       if (ctx->hdrs[ctx->v2r[i]]->tagged) {
745         cur = ctx->hdrs[ctx->v2r[i]];
746         curenv = cur->env;
747         break;
748       }
749
750     if (!cur) {
751       /* This could happen if the user tagged some messages and then did
752        * a limit such that none of the tagged message are visible.
753        */
754       mutt_error _("No tagged messages are visible!");
755
756       return (-1);
757     }
758   }
759   else
760     curenv = cur->env;
761
762   if (flags & SENDREPLY) {
763 #ifdef USE_NNTP
764     if ((flags & SENDNEWS)) {
765       /* in case followup set Newsgroups: with Followup-To: if it present */
766       if (!env->newsgroups && curenv &&
767           mutt_strcasecmp (curenv->followup_to, "poster"))
768         env->newsgroups = safe_strdup (curenv->followup_to);
769     }
770     else
771 #endif
772     if (tag) {
773       HEADER *h;
774
775       for (i = 0; i < ctx->vcount; i++) {
776         h = ctx->hdrs[ctx->v2r[i]];
777         if (h->tagged && mutt_fetch_recips (env, h->env, flags) == -1)
778           return -1;
779       }
780     }
781     else if (mutt_fetch_recips (env, curenv, flags) == -1)
782       return -1;
783
784     if ((flags & SENDLISTREPLY) && !env->to) {
785       mutt_error _("No mailing lists found!");
786
787       return (-1);
788     }
789
790     mutt_make_misc_reply_headers (env, ctx, cur, curenv);
791     mutt_make_reference_headers (tag ? NULL : curenv, env, ctx);
792   }
793   else if (flags & SENDFORWARD)
794     mutt_make_forward_subject (env, ctx, cur);
795
796   return (0);
797 }
798
799 static int generate_body (FILE * tempfp,        /* stream for outgoing message */
800                           HEADER * msg, /* header for outgoing message */
801                           int flags,    /* compose mode */
802                           CONTEXT * ctx,        /* current mailbox */
803                           HEADER * cur)
804 {                               /* current message */
805   int i;
806   HEADER *h;
807   BODY *tmp;
808
809   if (flags & SENDREPLY) {
810     if ((i =
811          query_quadoption (OPT_INCLUDE,
812                            _("Include message in reply?"))) == -1)
813       return (-1);
814
815     if (i == M_YES) {
816       mutt_message _("Including quoted message...");
817
818       if (!cur) {
819         for (i = 0; i < ctx->vcount; i++) {
820           h = ctx->hdrs[ctx->v2r[i]];
821           if (h->tagged) {
822             if (include_reply (ctx, h, tempfp) == -1) {
823               mutt_error _("Could not include all requested messages!");
824
825               return (-1);
826             }
827             fputc ('\n', tempfp);
828           }
829         }
830       }
831       else
832         include_reply (ctx, cur, tempfp);
833
834     }
835   }
836   else if (flags & SENDFORWARD) {
837     if ((i =
838          query_quadoption (OPT_MIMEFWD,
839                            _("Forward as attachment?"))) == M_YES) {
840       BODY *last = msg->content;
841
842       mutt_message _("Preparing forwarded message...");
843
844       while (last && last->next)
845         last = last->next;
846
847       if (cur) {
848         tmp = mutt_make_message_attach (ctx, cur, 0);
849         if (last)
850           last->next = tmp;
851         else
852           msg->content = tmp;
853       }
854       else {
855         for (i = 0; i < ctx->vcount; i++) {
856           if (ctx->hdrs[ctx->v2r[i]]->tagged) {
857             tmp = mutt_make_message_attach (ctx, ctx->hdrs[ctx->v2r[i]], 0);
858             if (last) {
859               last->next = tmp;
860               last = tmp;
861             }
862             else
863               last = msg->content = tmp;
864           }
865         }
866       }
867     }
868     else if (i != -1) {
869       if (cur)
870         include_forward (ctx, cur, tempfp);
871       else
872         for (i = 0; i < ctx->vcount; i++)
873           if (ctx->hdrs[ctx->v2r[i]]->tagged)
874             include_forward (ctx, ctx->hdrs[ctx->v2r[i]], tempfp);
875     }
876     else if (i == -1)
877       return -1;
878   }
879   /* if (WithCrypto && (flags & SENDKEY)) */
880   else if ((WithCrypto & APPLICATION_PGP) && (flags & SENDKEY)) {
881     BODY *tmp;
882
883     if ((WithCrypto & APPLICATION_PGP)
884         && (tmp = crypt_pgp_make_key_attachment (NULL)) == NULL)
885       return -1;
886
887     tmp->next = msg->content;
888     msg->content = tmp;
889   }
890
891   mutt_clear_error ();
892
893   return (0);
894 }
895
896 void mutt_set_followup_to (ENVELOPE * e)
897 {
898   ADDRESS *t = NULL;
899   ADDRESS *from;
900
901   /* 
902    * Only generate the Mail-Followup-To if the user has requested it, and
903    * it hasn't already been set
904    */
905
906   if (!option (OPTFOLLOWUPTO))
907     return;
908 #ifdef USE_NNTP
909   if (option (OPTNEWSSEND)) {
910     if (!e->followup_to && e->newsgroups && (strrchr (e->newsgroups, ',')))
911       e->followup_to = safe_strdup (e->newsgroups);
912     return;
913   }
914 #endif
915
916   if (!e->mail_followup_to) {
917     if (mutt_is_list_cc (0, e->to, e->cc)) {
918       /* 
919        * this message goes to known mailing lists, so create a proper
920        * mail-followup-to header
921        */
922
923       t = rfc822_append (&e->mail_followup_to, e->to);
924       rfc822_append (&t, e->cc);
925     }
926
927     /* remove ourselves from the mail-followup-to header */
928     e->mail_followup_to = remove_user (e->mail_followup_to, 0);
929
930     /*
931      * If we are not subscribed to any of the lists in question,
932      * re-add ourselves to the mail-followup-to header.  The 
933      * mail-followup-to header generated is a no-op with group-reply,
934      * but makes sure list-reply has the desired effect.
935      */
936
937     if (e->mail_followup_to && !mutt_is_list_recipient (0, e->to, e->cc)) {
938       if (e->reply_to)
939         from = rfc822_cpy_adr (e->reply_to);
940       else if (e->from)
941         from = rfc822_cpy_adr (e->from);
942       else
943         from = mutt_default_from ();
944
945       if (from) {
946         /* Normally, this loop will not even be entered. */
947         for (t = from; t && t->next; t = t->next);
948
949         t->next = e->mail_followup_to;  /* t cannot be NULL at this point. */
950         e->mail_followup_to = from;
951       }
952     }
953
954     e->mail_followup_to = mutt_remove_duplicates (e->mail_followup_to);
955
956   }
957 }
958
959
960 /* look through the recipients of the message we are replying to, and if
961    we find an address that matches $alternates, we use that as the default
962    from field */
963 static ADDRESS *set_reverse_name (ENVELOPE * env)
964 {
965   ADDRESS *tmp;
966
967   for (tmp = env->to; tmp; tmp = tmp->next) {
968     if (mutt_addr_is_user (tmp))
969       break;
970   }
971   if (!tmp) {
972     for (tmp = env->cc; tmp; tmp = tmp->next) {
973       if (mutt_addr_is_user (tmp))
974         break;
975     }
976   }
977   if (!tmp && mutt_addr_is_user (env->from))
978     tmp = env->from;
979   if (tmp) {
980     tmp = rfc822_cpy_adr_real (tmp);
981     if (!option (OPTREVREAL))
982       FREE (&tmp->personal);
983     if (!tmp->personal)
984       tmp->personal = safe_strdup (Realname);
985   }
986   return (tmp);
987 }
988
989 ADDRESS *mutt_default_from (void)
990 {
991   ADDRESS *adr;
992   const char *fqdn = mutt_fqdn (1);
993
994   /* 
995    * Note: We let $from override $realname here.  Is this the right
996    * thing to do? 
997    */
998
999   if (From)
1000     adr = rfc822_cpy_adr_real (From);
1001   else if (option (OPTUSEDOMAIN)) {
1002     adr = rfc822_new_address ();
1003     adr->mailbox =
1004       safe_malloc (mutt_strlen (Username) + mutt_strlen (fqdn) + 2);
1005     sprintf (adr->mailbox, "%s@%s", NONULL (Username), NONULL (fqdn));  /* __SPRINTF_CHECKED__ */
1006   }
1007   else {
1008     adr = rfc822_new_address ();
1009     adr->mailbox = safe_strdup (NONULL (Username));
1010   }
1011
1012   return (adr);
1013 }
1014
1015 static int send_message (HEADER * msg)
1016 {
1017   char tempfile[_POSIX_PATH_MAX];
1018   FILE *tempfp;
1019   int i;
1020
1021   /* Write out the message in MIME form. */
1022   mutt_mktemp (tempfile);
1023   if ((tempfp = safe_fopen (tempfile, "w")) == NULL)
1024     return (-1);
1025
1026 #ifdef MIXMASTER
1027   mutt_write_rfc822_header (tempfp, msg->env, msg->content, 0,
1028                             msg->chain ? 1 : 0);
1029 #endif
1030 #ifndef MIXMASTER
1031   mutt_write_rfc822_header (tempfp, msg->env, msg->content, 0, 0);
1032 #endif
1033
1034   fputc ('\n', tempfp);         /* tie off the header. */
1035
1036   if ((mutt_write_mime_body (msg->content, tempfp) == -1)) {
1037     fclose (tempfp);
1038     unlink (tempfile);
1039     return (-1);
1040   }
1041
1042   if (fclose (tempfp) != 0) {
1043     mutt_perror (tempfile);
1044     unlink (tempfile);
1045     return (-1);
1046   }
1047
1048 #ifdef MIXMASTER
1049   if (msg->chain)
1050     return mix_send_message (msg->chain, tempfile);
1051 #endif
1052
1053   i = mutt_invoke_mta (msg->env->from, msg->env->to, msg->env->cc,
1054                        msg->env->bcc, tempfile,
1055                        (msg->content->encoding == ENC8BIT));
1056   return (i);
1057 }
1058
1059 /* rfc2047 encode the content-descriptions */
1060 static void encode_descriptions (BODY * b, short recurse)
1061 {
1062   BODY *t;
1063
1064   for (t = b; t; t = t->next) {
1065     if (t->description) {
1066       rfc2047_encode_string (&t->description);
1067     }
1068     if (recurse && t->parts)
1069       encode_descriptions (t->parts, recurse);
1070   }
1071 }
1072
1073 /* rfc2047 decode them in case of an error */
1074 static void decode_descriptions (BODY * b)
1075 {
1076   BODY *t;
1077
1078   for (t = b; t; t = t->next) {
1079     if (t->description) {
1080       rfc2047_decode (&t->description);
1081     }
1082     if (t->parts)
1083       decode_descriptions (t->parts);
1084   }
1085 }
1086
1087 int mutt_resend_message (FILE * fp, CONTEXT * ctx, HEADER * cur)
1088 {
1089   HEADER *msg = mutt_new_header ();
1090
1091   if (mutt_prepare_template (fp, ctx, msg, cur, 1) < 0)
1092     return -1;
1093
1094   return ci_send_message (SENDRESEND, msg, NULL, ctx, cur);
1095 }
1096
1097 int ci_send_message (int flags, /* send mode */
1098                      HEADER * msg,      /* template to use for new message */
1099                      char *tempfile,    /* file specified by -i or -H */
1100                      CONTEXT * ctx,     /* current mailbox */
1101                      HEADER * cur)
1102 {                               /* current message */
1103   char buffer[LONG_STRING];
1104   char fcc[_POSIX_PATH_MAX] = "";       /* where to copy this message */
1105   FILE *tempfp = NULL;
1106   BODY *pbody;
1107   int i, killfrom = 0;
1108   int fcc_error = 0;
1109   int free_clear_content = 0;
1110
1111   BODY *save_content = NULL;
1112   BODY *clear_content = NULL;
1113   char *pgpkeylist = NULL;
1114
1115   /* save current value of "pgp_sign_as" */
1116   char *signas = NULL;
1117   char *tag = NULL, *err = NULL;
1118
1119   int rv = -1;
1120
1121 #ifdef USE_NNTP
1122   if (flags & SENDNEWS)
1123     set_option (OPTNEWSSEND);
1124   else
1125     unset_option (OPTNEWSSEND);
1126 #endif
1127
1128   if (!flags && !msg && quadoption (OPT_RECALL) != M_NO &&
1129       mutt_num_postponed (1)) {
1130     /* If the user is composing a new message, check to see if there
1131      * are any postponed messages first.
1132      */
1133     if ((i =
1134          query_quadoption (OPT_RECALL, _("Recall postponed message?"))) == -1)
1135       return rv;
1136
1137     if (i == M_YES)
1138       flags |= SENDPOSTPONED;
1139   }
1140
1141
1142   if ((WithCrypto & APPLICATION_PGP) && (flags & SENDPOSTPONED))
1143     signas = safe_strdup (PgpSignAs);
1144
1145   /* Delay expansion of aliases until absolutely necessary--shouldn't
1146    * be necessary unless we are prompting the user or about to execute a
1147    * send-hook.
1148    */
1149
1150   if (!msg) {
1151     msg = mutt_new_header ();
1152
1153     if (flags == SENDPOSTPONED) {
1154       if ((flags =
1155            mutt_get_postponed (ctx, msg, &cur, fcc, sizeof (fcc))) < 0)
1156         goto cleanup;
1157 #ifdef USE_NNTP
1158       /*
1159        * If postponed message is a news article, it have
1160        * a "Newsgroups:" header line, then set appropriate flag.
1161        */
1162       if (msg->env->newsgroups) {
1163         flags |= SENDNEWS;
1164         set_option (OPTNEWSSEND);
1165       }
1166       else {
1167         flags &= ~SENDNEWS;
1168         unset_option (OPTNEWSSEND);
1169       }
1170 #endif
1171     }
1172
1173     if (flags & (SENDPOSTPONED | SENDRESEND)) {
1174       if ((tempfp = safe_fopen (msg->content->filename, "a+")) == NULL) {
1175         mutt_perror (msg->content->filename);
1176         goto cleanup;
1177       }
1178     }
1179
1180     if (!msg->env)
1181       msg->env = mutt_new_envelope ();
1182   }
1183
1184   /* Parse and use an eventual list-post header */
1185   if ((flags & SENDLISTREPLY)
1186       && cur && cur->env && cur->env->list_post) {
1187     /* Use any list-post header as a template */
1188     url_parse_mailto (msg->env, NULL, cur->env->list_post);
1189     /* We don't let them set the sender's address. */
1190     rfc822_free_address (&msg->env->from);
1191   }
1192
1193   if (!(flags & (SENDKEY | SENDPOSTPONED | SENDRESEND))) {
1194     pbody = mutt_new_body ();
1195     pbody->next = msg->content; /* don't kill command-line attachments */
1196     msg->content = pbody;
1197
1198     mutt_parse_content_type (ContentType, msg->content);
1199     msg->content->unlink = 1;
1200     msg->content->use_disp = 0;
1201     msg->content->disposition = DISPINLINE;
1202     if (option (OPTTEXTFLOWED) && msg->content->type == TYPETEXT
1203         && !ascii_strcasecmp (msg->content->subtype, "plain"))
1204       mutt_set_parameter ("format", "flowed", &msg->content->parameter);
1205
1206     if (!tempfile) {
1207       mutt_mktemp (buffer);
1208       tempfp = safe_fopen (buffer, "w+");
1209       msg->content->filename = safe_strdup (buffer);
1210     }
1211     else {
1212       tempfp = safe_fopen (tempfile, "a+");
1213       msg->content->filename = safe_strdup (tempfile);
1214     }
1215
1216     if (!tempfp) {
1217       dprint (1,
1218               (debugfile,
1219                "newsend_message: can't create tempfile %s (errno=%d)\n",
1220                msg->content->filename, errno));
1221       mutt_perror (msg->content->filename);
1222       goto cleanup;
1223     }
1224   }
1225
1226   /* this is handled here so that the user can match ~f in send-hook */
1227   if (cur && option (OPTREVNAME) && !(flags & (SENDPOSTPONED | SENDRESEND))) {
1228     /* we shouldn't have to worry about freeing `msg->env->from' before
1229      * setting it here since this code will only execute when doing some
1230      * sort of reply.  the pointer will only be set when using the -H command
1231      * line option.
1232      *
1233      * We shouldn't have to worry about alias expansion here since we are
1234      * either replying to a real or postponed message, therefore no aliases
1235      * should exist since the user has not had the opportunity to add
1236      * addresses to the list.  We just have to ensure the postponed messages
1237      * have their aliases expanded.
1238      */
1239
1240     msg->env->from = set_reverse_name (cur->env);
1241   }
1242
1243   if (!msg->env->from && option (OPTUSEFROM)
1244       && !(flags & (SENDPOSTPONED | SENDRESEND)))
1245     msg->env->from = mutt_default_from ();
1246
1247   if (flags & SENDBATCH) {
1248     mutt_copy_stream (stdin, tempfp);
1249     if (option (OPTHDRS)) {
1250       process_user_recips (msg->env);
1251       process_user_header (msg->env);
1252     }
1253     mutt_expand_aliases_env (msg->env);
1254   }
1255   else if (!(flags & (SENDPOSTPONED | SENDRESEND))) {
1256     if ((flags & (SENDREPLY | SENDFORWARD)) && ctx &&
1257         envelope_defaults (msg->env, ctx, cur, flags) == -1)
1258       goto cleanup;
1259
1260     if (option (OPTHDRS))
1261       process_user_recips (msg->env);
1262
1263     /* Expand aliases and remove duplicates/crossrefs */
1264     mutt_fix_reply_recipients (msg->env);
1265
1266 #ifdef USE_NNTP
1267     if ((flags & SENDNEWS) && ctx && ctx->magic == M_NNTP
1268         && !msg->env->newsgroups)
1269       msg->env->newsgroups = safe_strdup (((NNTP_DATA *) ctx->data)->group);
1270 #endif
1271
1272     if (!(flags & SENDMAILX) &&
1273         !(option (OPTAUTOEDIT) && option (OPTEDITHDRS)) &&
1274         !((flags & SENDREPLY) && option (OPTFASTREPLY))) {
1275       if (edit_envelope (msg->env, flags) == -1)
1276         goto cleanup;
1277     }
1278
1279     /* the from address must be set here regardless of whether or not
1280      * $use_from is set so that the `~P' (from you) operator in send-hook
1281      * patterns will work.  if $use_from is unset, the from address is killed
1282      * after send-hooks are evaulated */
1283
1284     if (!msg->env->from) {
1285       msg->env->from = mutt_default_from ();
1286       killfrom = 1;
1287     }
1288
1289     if ((flags & SENDREPLY) && cur) {
1290       /* change setting based upon message we are replying to */
1291       mutt_message_hook (ctx, cur, M_REPLYHOOK);
1292
1293       /*
1294        * set the replied flag for the message we are generating so that the
1295        * user can use ~Q in a send-hook to know when reply-hook's are also
1296        * being used.
1297        */
1298       msg->replied = 1;
1299     }
1300
1301     /* change settings based upon recipients */
1302
1303     mutt_message_hook (NULL, msg, M_SENDHOOK);
1304
1305     /*
1306      * Unset the replied flag from the message we are composing since it is
1307      * no longer required.  This is done here because the FCC'd copy of
1308      * this message was erroneously get the 'R'eplied flag when stored in
1309      * a maildir-style mailbox.
1310      */
1311     msg->replied = 0;
1312
1313     if (killfrom) {
1314       rfc822_free_address (&msg->env->from);
1315       killfrom = 0;
1316     }
1317
1318     if (option (OPTHDRS))
1319       process_user_header (msg->env);
1320
1321
1322     if (option (OPTSIGONTOP)
1323         && (!(flags & (SENDMAILX | SENDKEY)) && Editor
1324             && mutt_strcmp (Editor, "builtin") != 0))
1325       append_signature (tempfp);
1326
1327     /* include replies/forwarded messages, unless we are given a template */
1328     if (!tempfile && (ctx || !(flags & (SENDREPLY | SENDFORWARD)))
1329         && generate_body (tempfp, msg, flags, ctx, cur) == -1)
1330       goto cleanup;
1331
1332     if (!option (OPTSIGONTOP)
1333         && (!(flags & (SENDMAILX | SENDKEY)) && Editor
1334             && mutt_strcmp (Editor, "builtin") != 0))
1335       append_signature (tempfp);
1336
1337     /* 
1338      * this wants to be done _after_ generate_body, so message-hooks
1339      * can take effect.
1340      */
1341
1342     if (WithCrypto && !(flags & SENDMAILX)) {
1343       if (option (OPTCRYPTAUTOSIGN))
1344         msg->security |= SIGN;
1345       if (option (OPTCRYPTAUTOENCRYPT))
1346         msg->security |= ENCRYPT;
1347       if (option (OPTCRYPTREPLYENCRYPT) && cur && (cur->security & ENCRYPT))
1348         msg->security |= ENCRYPT;
1349       if (option (OPTCRYPTREPLYSIGN) && cur && (cur->security & SIGN))
1350         msg->security |= SIGN;
1351       if (option (OPTCRYPTREPLYSIGNENCRYPTED) && cur
1352           && (cur->security & ENCRYPT))
1353         msg->security |= SIGN;
1354       if (WithCrypto & APPLICATION_PGP && (msg->security & (ENCRYPT | SIGN))) {
1355         if (option (OPTPGPAUTOINLINE))
1356           msg->security |= INLINE;
1357         if (option (OPTPGPREPLYINLINE) && cur && (cur->security & INLINE))
1358           msg->security |= INLINE;
1359       }
1360     }
1361
1362     if (WithCrypto && msg->security) {
1363       /* 
1364        * When reypling / forwarding, use the original message's
1365        * crypto system.  According to the documentation,
1366        * smime_is_default should be disregarded here.
1367        * 
1368        * Problem: At least with forwarding, this doesn't really
1369        * make much sense. Should we have an option to completely
1370        * disable individual mechanisms at run-time?
1371        */
1372       if (cur) {
1373         if ((WithCrypto & APPLICATION_PGP) && option (OPTCRYPTAUTOPGP)
1374             && (cur->security & APPLICATION_PGP))
1375           msg->security |= APPLICATION_PGP;
1376         else if ((WithCrypto & APPLICATION_SMIME)
1377                  && option (OPTCRYPTAUTOSMIME)
1378                  && (cur->security & APPLICATION_SMIME))
1379           msg->security |= APPLICATION_SMIME;
1380       }
1381
1382       /*
1383        * No crypto mechanism selected? Use availability + smime_is_default
1384        * for the decision. 
1385        */
1386       if (!(msg->security & (APPLICATION_SMIME | APPLICATION_PGP))) {
1387         if ((WithCrypto & APPLICATION_SMIME) && option (OPTCRYPTAUTOSMIME)
1388             && option (OPTSMIMEISDEFAULT))
1389           msg->security |= APPLICATION_SMIME;
1390         else if ((WithCrypto & APPLICATION_PGP) && option (OPTCRYPTAUTOPGP))
1391           msg->security |= APPLICATION_PGP;
1392         else if ((WithCrypto & APPLICATION_SMIME)
1393                  && option (OPTCRYPTAUTOSMIME))
1394           msg->security |= APPLICATION_SMIME;
1395       }
1396     }
1397
1398     /* No permissible mechanisms found.  Don't sign or encrypt. */
1399     if (!(msg->security & (APPLICATION_SMIME | APPLICATION_PGP)))
1400       msg->security = 0;
1401   }
1402
1403   /* 
1404    * This hook is even called for postponed messages, and can, e.g., be
1405    * used for setting the editor, the sendmail path, or the
1406    * envelope sender.
1407    */
1408   mutt_message_hook (NULL, msg, M_SEND2HOOK);
1409
1410   /* wait until now to set the real name portion of our return address so
1411      that $realname can be set in a send-hook */
1412   if (msg->env->from && !msg->env->from->personal
1413       && !(flags & (SENDRESEND | SENDPOSTPONED)))
1414     msg->env->from->personal = safe_strdup (Realname);
1415
1416   if (!((WithCrypto & APPLICATION_PGP) && (flags & SENDKEY)))
1417     safe_fclose (&tempfp);
1418
1419   if (flags & SENDMAILX) {
1420     if (mutt_builtin_editor (msg->content->filename, msg, cur) == -1)
1421       goto cleanup;
1422   }
1423   else if (!(flags & SENDBATCH)) {
1424     struct stat st;
1425     time_t mtime = mutt_decrease_mtime (msg->content->filename, NULL);
1426
1427     mutt_update_encoding (msg->content);
1428
1429     /*
1430      * Select whether or not the user's editor should be called now.  We
1431      * don't want to do this when:
1432      * 1) we are sending a key/cert
1433      * 2) we are forwarding a message and the user doesn't want to edit it.
1434      *    This is controled by the quadoption $forward_edit.  However, if
1435      *    both $edit_headers and $autoedit are set, we want to ignore the
1436      *    setting of $forward_edit because the user probably needs to add the
1437      *    recipients.
1438      */
1439     if (!(flags & SENDKEY) &&
1440         ((flags & SENDFORWARD) == 0 ||
1441          (option (OPTEDITHDRS) && option (OPTAUTOEDIT)) ||
1442          query_quadoption (OPT_FORWEDIT,
1443                            _("Edit forwarded message?")) == M_YES)) {
1444       /* If the this isn't a text message, look for a mailcap edit command */
1445       if (mutt_needs_mailcap (msg->content))
1446         mutt_edit_attachment (msg->content);
1447       else if (!Editor || mutt_strcmp ("builtin", Editor) == 0)
1448         mutt_builtin_editor (msg->content->filename, msg, cur);
1449       else if (option (OPTEDITHDRS)) {
1450         mutt_env_to_local (msg->env);
1451         mutt_edit_headers (Editor, msg->content->filename, msg, fcc,
1452                            sizeof (fcc));
1453         mutt_env_to_idna (msg->env, NULL, NULL);
1454       }
1455       else
1456         mutt_edit_file (Editor, msg->content->filename);
1457
1458       mutt_message_hook (NULL, msg, M_SEND2HOOK);
1459     }
1460
1461     if (!(flags & (SENDPOSTPONED | SENDFORWARD | SENDKEY | SENDRESEND))) {
1462       if (stat (msg->content->filename, &st) == 0) {
1463         /* if the file was not modified, bail out now */
1464         if (mtime == st.st_mtime && !msg->content->next &&
1465             query_quadoption (OPT_ABORT,
1466                               _("Abort unmodified message?")) == M_YES) {
1467           mutt_message _("Aborted unmodified message.");
1468
1469           goto cleanup;
1470         }
1471       }
1472       else
1473         mutt_perror (msg->content->filename);
1474     }
1475   }
1476
1477   /* specify a default fcc.  if we are in batchmode, only save a copy of
1478    * the message if the value of $copy is yes or ask-yes */
1479
1480   if (!fcc[0] && !(flags & (SENDPOSTPONED))
1481       && (!(flags & SENDBATCH) || (quadoption (OPT_COPY) & 0x1))) {
1482     /* set the default FCC */
1483     if (!msg->env->from) {
1484       msg->env->from = mutt_default_from ();
1485       killfrom = 1;             /* no need to check $use_from because if the user specified
1486                                    a from address it would have already been set by now */
1487     }
1488     mutt_select_fcc (fcc, sizeof (fcc), msg);
1489     if (killfrom) {
1490       rfc822_free_address (&msg->env->from);
1491       killfrom = 0;
1492     }
1493   }
1494
1495
1496   mutt_update_encoding (msg->content);
1497
1498   if (!(flags & (SENDMAILX | SENDBATCH))) {
1499   main_loop:
1500
1501     fcc_error = 0;              /* reset value since we may have failed before */
1502     mutt_pretty_mailbox (fcc);
1503     i = mutt_compose_menu (msg, fcc, sizeof (fcc), cur);
1504     if (i == -1) {
1505       /* abort */
1506 #ifdef USE_NNTP
1507       if (flags & SENDNEWS)
1508         mutt_message (_("Article not posted."));
1509
1510       else
1511 #endif
1512         mutt_message _("Mail not sent.");
1513       goto cleanup;
1514     }
1515     else if (i == 1) {
1516       /* postpone the message until later. */
1517       if (msg->content->next)
1518         msg->content = mutt_make_multipart (msg->content);
1519
1520       /*
1521        * make sure the message is written to the right part of a maildir 
1522        * postponed folder.
1523        */
1524       msg->read = 0;
1525       msg->old = 0;
1526
1527       encode_descriptions (msg->content, 1);
1528       mutt_prepare_envelope (msg->env, 0);
1529       mutt_env_to_idna (msg->env, NULL, NULL);  /* Handle bad IDNAs the next time. */
1530
1531       if (!Postponed
1532           || mutt_write_fcc (NONULL (Postponed), msg,
1533                              (cur
1534                               && (flags & SENDREPLY)) ? cur->env->
1535                              message_id : NULL, 1, fcc) < 0) {
1536         msg->content = mutt_remove_multipart (msg->content);
1537         decode_descriptions (msg->content);
1538         mutt_unprepare_envelope (msg->env);
1539         goto main_loop;
1540       }
1541       mutt_update_num_postponed ();
1542       mutt_message _("Message postponed.");
1543
1544       goto cleanup;
1545     }
1546   }
1547
1548 #ifdef USE_NNTP
1549   if (!(flags & SENDNEWS))
1550 #endif
1551     if (!msg->env->to && !msg->env->cc && !msg->env->bcc) {
1552       if (!(flags & SENDBATCH)) {
1553         mutt_error _("No recipients are specified!");
1554
1555         goto main_loop;
1556       }
1557       else {
1558         puts _("No recipients were specified.");
1559
1560         goto cleanup;
1561       }
1562     }
1563
1564   if (mutt_env_to_idna (msg->env, &tag, &err)) {
1565     mutt_error (_("Bad IDN in \"%s\": '%s'"), tag, err);
1566     FREE (&err);
1567     if (!(flags & SENDBATCH))
1568       goto main_loop;
1569     else
1570       goto cleanup;
1571   }
1572
1573   if (!msg->env->subject && !(flags & SENDBATCH) &&
1574       (i =
1575        query_quadoption (OPT_SUBJECT,
1576                          _("No subject, abort sending?"))) != M_NO) {
1577     /* if the abort is automatic, print an error message */
1578     if (quadoption (OPT_SUBJECT) == M_YES)
1579       mutt_error _("No subject specified.");
1580
1581     goto main_loop;
1582   }
1583 #ifdef USE_NNTP
1584   if ((flags & SENDNEWS) && !msg->env->subject) {
1585     mutt_error _("No subject specified.");
1586
1587     goto main_loop;
1588   }
1589
1590   if ((flags & SENDNEWS) && !msg->env->newsgroups) {
1591     mutt_error _("No newsgroup specified.");
1592
1593     goto main_loop;
1594   }
1595 #endif
1596
1597   if (msg->content->next)
1598     msg->content = mutt_make_multipart (msg->content);
1599
1600   /* 
1601    * Ok, we need to do it this way instead of handling all fcc stuff in
1602    * one place in order to avoid going to main_loop with encoded "env"
1603    * in case of error.  Ugh.
1604    */
1605
1606   encode_descriptions (msg->content, 1);
1607
1608   /*
1609    * Make sure that clear_content and free_clear_content are
1610    * properly initialized -- we may visit this particular place in
1611    * the code multiple times, including after a failed call to
1612    * mutt_protect().
1613    */
1614
1615   clear_content = NULL;
1616   free_clear_content = 0;
1617
1618   if (WithCrypto) {
1619     if (msg->security) {
1620       /* save the decrypted attachments */
1621       clear_content = msg->content;
1622
1623       if ((crypt_get_keys (msg, &pgpkeylist) == -1) ||
1624           mutt_protect (msg, pgpkeylist) == -1) {
1625         msg->content = mutt_remove_multipart (msg->content);
1626
1627         FREE (&pgpkeylist);
1628
1629         decode_descriptions (msg->content);
1630         goto main_loop;
1631       }
1632       encode_descriptions (msg->content, 0);
1633     }
1634
1635     /* 
1636      * at this point, msg->content is one of the following three things:
1637      * - multipart/signed.  In this case, clear_content is a child.
1638      * - multipart/encrypted.  In this case, clear_content exists
1639      *   independently
1640      * - application/pgp.  In this case, clear_content exists independently.
1641      * - something else.  In this case, it's the same as clear_content.
1642      */
1643
1644     /* This is ugly -- lack of "reporting back" from mutt_protect(). */
1645
1646     if (clear_content && (msg->content != clear_content)
1647         && (msg->content->parts != clear_content))
1648       free_clear_content = 1;
1649   }
1650
1651   if (!option (OPTNOCURSES) && !(flags & SENDMAILX))
1652     mutt_message _("Sending message...");
1653
1654   mutt_prepare_envelope (msg->env, 1);
1655
1656   /* save a copy of the message, if necessary. */
1657
1658   mutt_expand_path (fcc, sizeof (fcc));
1659
1660
1661   /* Don't save a copy when we are in batch-mode, and the FCC
1662    * folder is on an IMAP server: This would involve possibly lots
1663    * of user interaction, which is not available in batch mode. 
1664    * 
1665    * Note: A patch to fix the problems with the use of IMAP servers
1666    * from non-curses mode is available from Brendan Cully.  However, 
1667    * I'd like to think a bit more about this before including it.
1668    */
1669
1670 #ifdef USE_IMAP
1671   if ((flags & SENDBATCH) && fcc[0] && mx_is_imap (fcc))
1672     fcc[0] = '\0';
1673 #endif
1674
1675   if (*fcc && mutt_strcmp ("/dev/null", fcc) != 0) {
1676     BODY *tmpbody = msg->content;
1677     BODY *save_sig = NULL;
1678     BODY *save_parts = NULL;
1679
1680     if (WithCrypto && msg->security && option (OPTFCCCLEAR))
1681       msg->content = clear_content;
1682
1683     /* check to see if the user wants copies of all attachments */
1684     if (!option (OPTFCCATTACH) && msg->content->type == TYPEMULTIPART) {
1685       if (WithCrypto
1686           && (mutt_strcmp (msg->content->subtype, "encrypted") == 0 ||
1687               mutt_strcmp (msg->content->subtype, "signed") == 0)) {
1688         if (clear_content->type == TYPEMULTIPART) {
1689           if (!(msg->security & ENCRYPT) && (msg->security & SIGN)) {
1690             /* save initial signature and attachments */
1691             save_sig = msg->content->parts->next;
1692             save_parts = clear_content->parts->next;
1693           }
1694
1695           /* this means writing only the main part */
1696           msg->content = clear_content->parts;
1697
1698           if (mutt_protect (msg, pgpkeylist) == -1) {
1699             /* we can't do much about it at this point, so
1700              * fallback to saving the whole thing to fcc
1701              */
1702             msg->content = tmpbody;
1703             save_sig = NULL;
1704             goto full_fcc;
1705           }
1706
1707           save_content = msg->content;
1708         }
1709       }
1710       else
1711         msg->content = msg->content->parts;
1712     }
1713
1714   full_fcc:
1715     if (msg->content) {
1716       /* update received time so that when storing to a mbox-style folder
1717        * the From_ line contains the current time instead of when the
1718        * message was first postponed.
1719        */
1720       msg->received = time (NULL);
1721       if (mutt_write_fcc (fcc, msg, NULL, 0, NULL) == -1) {
1722         /*
1723          * Error writing FCC, we should abort sending.
1724          */
1725         fcc_error = 1;
1726       }
1727     }
1728
1729     msg->content = tmpbody;
1730
1731     if (WithCrypto && save_sig) {
1732       /* cleanup the second signature structures */
1733       if (save_content->parts) {
1734         mutt_free_body (&save_content->parts->next);
1735         save_content->parts = NULL;
1736       }
1737       mutt_free_body (&save_content);
1738
1739       /* restore old signature and attachments */
1740       msg->content->parts->next = save_sig;
1741       msg->content->parts->parts->next = save_parts;
1742     }
1743     else if (WithCrypto && save_content) {
1744       /* destroy the new encrypted body. */
1745       mutt_free_body (&save_content);
1746     }
1747
1748   }
1749
1750
1751   /*
1752    * Don't attempt to send the message if the FCC failed.  Just pretend
1753    * the send failed as well so we give the user a chance to fix the
1754    * error.
1755    */
1756   if (fcc_error || (i = send_message (msg)) == -1) {
1757     if (!(flags & SENDBATCH)) {
1758       if (!WithCrypto);
1759       else if ((msg->security & ENCRYPT) || ((msg->security & SIGN)
1760                                              && msg->content->type ==
1761                                              TYPEAPPLICATION)) {
1762         mutt_free_body (&msg->content); /* destroy PGP data */
1763         msg->content = clear_content;   /* restore clear text. */
1764       }
1765       else if ((msg->security & SIGN) && msg->content->type == TYPEMULTIPART) {
1766         mutt_free_body (&msg->content->parts->next);    /* destroy sig */
1767         msg->content = mutt_remove_multipart (msg->content);
1768       }
1769
1770       msg->content = mutt_remove_multipart (msg->content);
1771       decode_descriptions (msg->content);
1772       mutt_unprepare_envelope (msg->env);
1773       goto main_loop;
1774     }
1775     else {
1776       puts _("Could not send the message.");
1777
1778       goto cleanup;
1779     }
1780   }
1781   else if (!option (OPTNOCURSES) && !(flags & SENDMAILX))
1782     mutt_message (i != 0 ? _("Sending in background.") :
1783 #ifdef USE_NNTP
1784                   (flags & SENDNEWS) ? _("Article posted.") :
1785                   _("Mail sent."));
1786 #else
1787                   _("Mail sent."));
1788 #endif
1789
1790   if (WithCrypto && (msg->security & ENCRYPT))
1791     FREE (&pgpkeylist);
1792
1793   if (WithCrypto && free_clear_content)
1794     mutt_free_body (&clear_content);
1795
1796   if (flags & SENDREPLY) {
1797     if (cur && ctx)
1798       mutt_set_flag (ctx, cur, M_REPLIED, 1);
1799     else if (!(flags & SENDPOSTPONED) && ctx && ctx->tagged) {
1800       for (i = 0; i < ctx->vcount; i++)
1801         if (ctx->hdrs[ctx->v2r[i]]->tagged)
1802           mutt_set_flag (ctx, ctx->hdrs[ctx->v2r[i]], M_REPLIED, 1);
1803     }
1804   }
1805
1806
1807   rv = 0;
1808
1809 cleanup:
1810
1811   if ((WithCrypto & APPLICATION_PGP) && (flags & SENDPOSTPONED)) {
1812     if (signas) {
1813       FREE (&PgpSignAs);
1814       PgpSignAs = signas;
1815     }
1816   }
1817
1818   safe_fclose (&tempfp);
1819   mutt_free_header (&msg);
1820
1821   return rv;
1822 }
1823
1824 /* vim: set sw=2: */