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