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