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