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