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