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