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