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