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