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