More or less completely rewrite memory.c..
[s-mailx.git] / sendout.c
blobff3d6a50318a9ba06ec20667f16cdf23f8b5cbec
1 /*@ S-nail - a mail user agent derived from Berkeley Mail.
2 *@ Message sending lifecycle, header composing, etc.
4 * Copyright (c) 2000-2004 Gunnar Ritter, Freiburg i. Br., Germany.
5 * Copyright (c) 2012 - 2016 Steffen (Daode) Nurpmeso <steffen@sdaoden.eu>.
6 */
7 /*
8 * Copyright (c) 1980, 1993
9 * The Regents of the University of California. All rights reserved.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. Neither the name of the University nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * SUCH DAMAGE.
35 #undef n_FILE
36 #define n_FILE sendout
38 #ifndef HAVE_AMALGAMATION
39 # include "nail.h"
40 #endif
42 #undef SEND_LINESIZE
43 #define SEND_LINESIZE \
44 ((1024 / B64_ENCODE_INPUT_PER_LINE) * B64_ENCODE_INPUT_PER_LINE)
46 enum fmt_flags {
47 FMT_DOMIME = 1<<0,
48 FMT_COMMA = GCOMMA,
49 FMT_FILES = GFILES,
50 _FMT_GMASK = FMT_COMMA | FMT_FILES
52 n_CTA(!(_FMT_GMASK & FMT_DOMIME),
53 "Code-required condition not satisfied but actual bit carrier value");
55 static char const *__sendout_ident; /* TODO temporary hack; rewrite puthead() */
56 static char * _sendout_boundary;
57 static si8_t _sendout_error;
59 static enum okay _putname(char const *line, enum gfield w,
60 enum sendaction action, size_t *gotcha,
61 char const *prefix, FILE *fo, struct name **xp,
62 enum gfield addflags);
64 /* Place Content-Type:, Content-Transfer-Encoding:, Content-Disposition:
65 * headers, respectively */
66 static int _put_ct(FILE *fo, char const *contenttype,
67 char const *charset);
68 SINLINE int _put_cte(FILE *fo, enum conversion conv);
69 static int _put_cd(FILE *fo, char const *cd, char const *filename);
71 /* Put all entries of the given header list */
72 static bool_t _sendout_header_list(FILE *fo, struct n_header_field *hfp,
73 bool_t nodisp);
75 /* Write an attachment to the file buffer, converting to MIME */
76 static int _attach_file(struct attachment *ap, FILE *fo);
77 static int __attach_file(struct attachment *ap, FILE *fo);
79 /* There are non-local receivers, collect credentials etc. */
80 static bool_t _sendbundle_setup_creds(struct sendbundle *sbpm,
81 bool_t signing_caps);
83 /* Attach a message to the file buffer */
84 static int attach_message(struct attachment *ap, FILE *fo);
86 /* Generate the body of a MIME multipart message */
87 static int make_multipart(struct header *hp, int convert, FILE *fi,
88 FILE *fo, char const *contenttype, char const *charset);
90 /* Prepend a header in front of the collected stuff and return the new file */
91 static FILE * infix(struct header *hp, FILE *fi);
93 /* Check whether Disposition-Notification-To: is desired */
94 static bool_t _check_dispo_notif(struct name *mdn, struct header *hp,
95 FILE *fo);
97 /* Send mail to a bunch of user names. The interface is through mail() */
98 static int sendmail_internal(void *v, int recipient_record);
100 /* Deal with file and pipe addressees */
101 static struct name * _outof(struct name *names, FILE *fo, bool_t *senderror);
103 /* Record outgoing mail if instructed to do so; in *record* unless to is set */
104 static bool_t mightrecord(FILE *fp, struct name *to, bool_t resend);
106 static bool_t a_sendout__savemail(char const *name, FILE *fp, bool_t resend);
108 /* */
109 static bool_t _transfer(struct sendbundle *sbp);
111 static bool_t __mta_start(struct sendbundle *sbp);
112 static char const ** __mta_prepare_args(struct name *to, struct header *hp);
113 static void __mta_debug(struct sendbundle *sbp, char const *mta,
114 char const **args);
116 /* Create a Message-ID: header field. Use either host name or from address */
117 static char * _message_id(struct header *hp);
119 /* Format the given header line to not exceed 72 characters */
120 static int fmt(char const *str, struct name *np, FILE *fo,
121 enum fmt_flags ff);
123 /* Rewrite a message for resending, adding the Resent-Headers */
124 static int infix_resend(FILE *fi, FILE *fo, struct message *mp,
125 struct name *to, int add_resent);
127 static enum okay
128 _putname(char const *line, enum gfield w, enum sendaction action,
129 size_t *gotcha, char const *prefix, FILE *fo, struct name **xp,
130 enum gfield addflags)
132 struct name *np;
133 enum okay rv = STOP;
134 NYD_ENTER;
136 np = lextract(line, GEXTRA | GFULL | addflags);
137 if (xp != NULL)
138 *xp = np;
139 if (np == NULL)
141 else if (fmt(prefix, np, fo, ((w & GCOMMA) |
142 ((action != SEND_TODISP) ? FMT_DOMIME : 0))))
143 rv = OKAY;
144 else if (gotcha != NULL)
145 ++(*gotcha);
146 NYD_LEAVE;
147 return rv;
150 static int
151 _put_ct(FILE *fo, char const *contenttype, char const *charset)
153 int rv, i;
154 NYD2_ENTER;
156 if ((rv = fprintf(fo, "Content-Type: %s", contenttype)) < 0)
157 goto jerr;
159 if (charset == NULL)
160 goto jend;
162 if (putc(';', fo) == EOF)
163 goto jerr;
164 ++rv;
166 if (strlen(contenttype) + sizeof("Content-Type: ;")-1 > 50) {
167 if (putc('\n', fo) == EOF)
168 goto jerr;
169 ++rv;
172 /* C99 */{
173 size_t l = strlen(charset);
174 char *lcs = salloc(l +1);
176 for(l = 0; *charset != '\0'; ++l, ++charset)
177 lcs[l] = lowerconv(*charset);
178 lcs[l] = '\0';
179 charset = lcs;
181 if ((i = fprintf(fo, " charset=%s", charset)) < 0)
182 goto jerr;
183 rv += i;
185 jend:
186 if (putc('\n', fo) == EOF)
187 goto jerr;
188 ++rv;
189 jleave:
190 NYD2_LEAVE;
191 return rv;
192 jerr:
193 rv = -1;
194 goto jleave;
197 SINLINE int
198 _put_cte(FILE *fo, enum conversion conv)
200 int rv;
201 NYD2_ENTER;
203 /* RFC 2045, 6.1.:
204 * This is the default value -- that is,
205 * "Content-Transfer-Encoding: 7BIT" is assumed if the
206 * Content-Transfer-Encoding header field is not present.
208 rv = (conv == CONV_7BIT) ? 0
209 : fprintf(fo, "Content-Transfer-Encoding: %s\n",
210 mime_enc_from_conversion(conv));
211 NYD2_LEAVE;
212 return rv;
215 static int
216 _put_cd(FILE *fo, char const *cd, char const *filename)
218 struct str f;
219 si8_t mpc;
220 int rv;
221 NYD2_ENTER;
223 f.s = NULL;
225 /* xxx Ugly with the trailing space in case of wrap! */
226 if ((rv = fprintf(fo, "Content-Disposition: %s; ", cd)) < 0)
227 goto jerr;
229 if (!(mpc = mime_param_create(&f, "filename", filename)))
230 goto jerr;
231 /* Always fold if result contains newlines */
232 if (mpc < 0 || f.l + rv > MIME_LINELEN) { /* FIXME MIME_LINELEN_MAX */
233 if (putc('\n', fo) == EOF || putc(' ', fo) == EOF)
234 goto jerr;
235 rv += 2;
237 if (fputs(f.s, fo) == EOF || putc('\n', fo) == EOF)
238 goto jerr;
239 rv += (int)++f.l;
241 jleave:
242 NYD2_LEAVE;
243 return rv;
244 jerr:
245 rv = -1;
246 goto jleave;
250 static bool_t
251 _sendout_header_list(FILE *fo, struct n_header_field *hfp, bool_t nodisp){
252 bool_t rv;
253 NYD2_ENTER;
255 for(rv = TRU1; hfp != NULL; hfp = hfp->hf_next)
256 if(fwrite(hfp->hf_dat, sizeof(char), hfp->hf_nl, fo) != hfp->hf_nl ||
257 putc(':', fo) == EOF || putc(' ', fo) == EOF ||
258 xmime_write(hfp->hf_dat + hfp->hf_nl +1, hfp->hf_bl, fo,
259 (!nodisp ? CONV_NONE : CONV_TOHDR),
260 (!nodisp ? TD_ISPR | TD_ICONV : TD_ICONV)) < 0 ||
261 putc('\n', fo) == EOF){
262 rv = FAL0;
263 break;
265 NYD_LEAVE;
266 return rv;
269 static int
270 _attach_file(struct attachment *ap, FILE *fo)
272 /* TODO of course, the MIME classification needs to performed once
273 * TODO only, not for each and every charset anew ... ;-// */
274 char *charset_iter_orig[2];
275 long offs;
276 int err = 0;
277 NYD_ENTER;
279 /* Is this already in target charset? Simply copy over */
280 if (ap->a_conv == AC_TMPFILE) {
281 err = __attach_file(ap, fo);
282 Fclose(ap->a_tmpf);
283 DBG( ap->a_tmpf = NULL; )
284 goto jleave;
287 /* If we don't apply charset conversion at all (fixed input=ouput charset)
288 * we also simply copy over, since it's the users desire */
289 if (ap->a_conv == AC_FIX_INCS) {
290 ap->a_charset = ap->a_input_charset;
291 err = __attach_file(ap, fo);
292 goto jleave;
295 /* Otherwise we need to iterate over all possible output charsets */
296 if ((offs = ftell(fo)) == -1) {
297 err = EIO;
298 goto jleave;
300 charset_iter_recurse(charset_iter_orig);
301 for (charset_iter_reset(NULL);; charset_iter_next()) {
302 if (!charset_iter_is_valid()) {
303 err = EILSEQ;
304 break;
306 err = __attach_file(ap, fo);
307 if (err == 0 || (err != EILSEQ && err != EINVAL))
308 break;
309 clearerr(fo);
310 if (fseek(fo, offs, SEEK_SET) == -1) {
311 err = EIO;
312 break;
314 if (ap->a_conv != AC_DEFAULT) {
315 err = EILSEQ;
316 break;
318 ap->a_charset = NULL;
320 charset_iter_restore(charset_iter_orig);
321 jleave:
322 NYD_LEAVE;
323 return err;
326 static int
327 __attach_file(struct attachment *ap, FILE *fo) /* XXX linelength */
329 int err = 0, do_iconv;
330 FILE *fi;
331 char const *charset;
332 enum conversion convert;
333 char *buf;
334 size_t bufsize, lncnt, inlen;
335 NYD_ENTER;
337 /* Either charset-converted temporary file, or plain path */
338 if (ap->a_conv == AC_TMPFILE) {
339 fi = ap->a_tmpf;
340 assert(ftell(fi) == 0);
341 } else if ((fi = Fopen(ap->a_name, "r")) == NULL) {
342 err = errno;
343 n_err(_("%s: %s\n"), n_shexp_quote_cp(ap->a_name, FAL0), strerror(err));
344 goto jleave;
347 /* MIME part header for attachment */
348 { char const *bn = ap->a_name, *ct;
350 if ((ct = strrchr(bn, '/')) != NULL)
351 bn = ++ct;
352 ct = ap->a_content_type;
353 charset = ap->a_charset;
354 convert = mime_type_classify_file(fi, (char const**)&ct,
355 &charset, &do_iconv);
356 if (charset == NULL || ap->a_conv == AC_FIX_INCS ||
357 ap->a_conv == AC_TMPFILE)
358 do_iconv = 0;
360 if (fprintf(fo, "\n--%s\n", _sendout_boundary) < 0 ||
361 _put_ct(fo, ct, charset) < 0 || _put_cte(fo, convert) < 0 ||
362 _put_cd(fo, ap->a_content_disposition, bn) < 0)
363 goto jerr_header;
365 if ((bn = ap->a_content_id) != NULL &&
366 fprintf(fo, "Content-ID: %s\n", bn) == -1)
367 goto jerr_header;
369 if ((bn = ap->a_content_description) != NULL &&
370 fprintf(fo, "Content-Description: %s\n", bn) == -1) /* TODO MIME! */
371 goto jerr_header;
373 if (putc('\n', fo) == EOF) {
374 jerr_header:
375 err = errno;
376 goto jerr_fclose;
380 #ifdef HAVE_ICONV
381 if (iconvd != (iconv_t)-1)
382 n_iconv_close(iconvd);
383 if (do_iconv) {
384 char const *tcs = charset_get_lc();
385 if (asccasecmp(charset, tcs) &&
386 (iconvd = n_iconv_open(charset, tcs)) == (iconv_t)-1 &&
387 (err = errno) != 0) {
388 if (err == EINVAL)
389 n_err(_("Cannot convert from %s to %s\n"), tcs, charset);
390 else
391 n_err(_("iconv_open: %s\n"), strerror(err));
392 goto jerr_fclose;
395 #endif
397 bufsize = SEND_LINESIZE;
398 buf = smalloc(bufsize);
399 if (convert == CONV_TOQP
400 #ifdef HAVE_ICONV
401 || iconvd != (iconv_t)-1
402 #endif
404 lncnt = fsize(fi);
405 for (;;) {
406 if (convert == CONV_TOQP
407 #ifdef HAVE_ICONV
408 || iconvd != (iconv_t)-1
409 #endif
411 if (fgetline(&buf, &bufsize, &lncnt, &inlen, fi, 0) == NULL)
412 break;
413 } else if ((inlen = fread(buf, sizeof *buf, bufsize, fi)) == 0)
414 break;
415 if (xmime_write(buf, inlen, fo, convert, TD_ICONV) < 0) {
416 err = errno;
417 goto jerr;
420 if (ferror(fi))
421 err = EDOM;
422 jerr:
423 free(buf);
424 jerr_fclose:
425 if (ap->a_conv != AC_TMPFILE)
426 Fclose(fi);
427 jleave:
428 NYD_LEAVE;
429 return err;
432 static bool_t
433 _sendbundle_setup_creds(struct sendbundle *sbp, bool_t signing_caps)
435 bool_t v15, rv = FAL0;
436 char *shost, *from;
437 #ifdef HAVE_SMTP
438 char const *smtp;
439 #endif
440 NYD_ENTER;
442 v15 = ok_blook(v15_compat);
443 shost = (v15 ? ok_vlook(smtp_hostname) : NULL);
444 from = ((signing_caps || !v15 || shost == NULL)
445 ? skin(myorigin(sbp->sb_hp)) : NULL);
447 if (signing_caps) {
448 if (from == NULL) {
449 #ifdef HAVE_SSL
450 n_err(_("No *from* address for signing specified\n"));
451 goto jleave;
452 #endif
453 } else
454 sbp->sb_signer.l = strlen(sbp->sb_signer.s = from);
457 #ifdef HAVE_SMTP
458 if ((smtp = ok_vlook(smtp)) == NULL) { /* TODO v15 url_creat(,ok_vlook(mta)*/
459 char const *proto;
461 /* *smtp* OBSOLETE message in mta_start() */
462 if ((smtp = ok_vlook(mta)) == NULL ||
463 (proto = n_servbyname(smtp, NULL)) == NULL || *proto == '\0') {
464 rv = TRU1;
465 goto jleave;
469 if (!url_parse(&sbp->sb_url, CPROTO_SMTP, smtp))
470 goto jleave;
472 if (v15) {
473 if (shost == NULL) {
474 if (from == NULL)
475 goto jenofrom;
476 sbp->sb_url.url_u_h.l = strlen(sbp->sb_url.url_u_h.s = from);
477 } else
478 __sendout_ident = sbp->sb_url.url_u_h.s;
479 if (!ccred_lookup(&sbp->sb_ccred, &sbp->sb_url))
480 goto jleave;
481 } else {
482 if (sbp->sb_url.url_had_user || sbp->sb_url.url_pass.s != NULL) {
483 n_err(_("New-style URL used without *v15-compat* being set\n"));
484 goto jleave;
486 /* TODO part of the entire myorigin() disaster, get rid of this! */
487 if (from == NULL) {
488 jenofrom:
489 n_err(_("Your configuration requires a *from* address, "
490 "but none was given\n"));
491 goto jleave;
493 if (!ccred_lookup_old(&sbp->sb_ccred, CPROTO_SMTP, from))
494 goto jleave;
495 sbp->sb_url.url_u_h.l = strlen(sbp->sb_url.url_u_h.s = from);
498 rv = TRU1;
499 #endif /* HAVE_SMTP */
500 #if defined HAVE_SSL || defined HAVE_SMTP
501 jleave:
502 #endif
503 NYD_LEAVE;
504 return rv;
507 static int
508 attach_message(struct attachment *ap, FILE *fo)
510 struct message *mp;
511 char const *ccp;
512 int rv;
513 NYD_ENTER;
515 fprintf(fo, "\n--%s\nContent-Type: message/rfc822\n"
516 "Content-Disposition: inline\n", _sendout_boundary);
517 if ((ccp = ap->a_content_description) != NULL)
518 fprintf(fo, "Content-Description: %s\n", ccp);/* TODO MIME! */
519 putc('\n', fo);
521 mp = message + ap->a_msgno - 1;
522 touch(mp);
523 rv = (sendmp(mp, fo, 0, NULL, SEND_RFC822, NULL) < 0) ? -1 : 0;
524 NYD_LEAVE;
525 return rv;
528 static int
529 make_multipart(struct header *hp, int convert, FILE *fi, FILE *fo,
530 char const *contenttype, char const *charset)
532 struct attachment *att;
533 int rv = -1;
534 NYD_ENTER;
536 fputs("This is a multi-part message in MIME format.\n", fo);
537 if (fsize(fi) != 0) {
538 char *buf;
539 size_t sz, bufsize, cnt;
541 if (fprintf(fo, "\n--%s\n", _sendout_boundary) < 0 ||
542 _put_ct(fo, contenttype, charset) < 0 ||
543 _put_cte(fo, convert) < 0 ||
544 fprintf(fo, "Content-Disposition: inline\n\n") < 0)
545 goto jleave;
547 buf = smalloc(bufsize = SEND_LINESIZE);
548 if (convert == CONV_TOQP
549 #ifdef HAVE_ICONV
550 || iconvd != (iconv_t)-1
551 #endif
553 fflush(fi);
554 cnt = fsize(fi);
556 for (;;) {
557 if (convert == CONV_TOQP
558 #ifdef HAVE_ICONV
559 || iconvd != (iconv_t)-1
560 #endif
562 if (fgetline(&buf, &bufsize, &cnt, &sz, fi, 0) == NULL)
563 break;
564 } else if ((sz = fread(buf, sizeof *buf, bufsize, fi)) == 0)
565 break;
567 if (xmime_write(buf, sz, fo, convert, TD_ICONV) < 0) {
568 free(buf);
569 goto jleave;
572 free(buf);
574 if (ferror(fi))
575 goto jleave;
578 for (att = hp->h_attach; att != NULL; att = att->a_flink) {
579 if (att->a_msgno) {
580 if (attach_message(att, fo) != 0)
581 goto jleave;
582 } else if (_attach_file(att, fo) != 0)
583 goto jleave;
586 /* the final boundary with two attached dashes */
587 fprintf(fo, "\n--%s--\n", _sendout_boundary);
588 rv = 0;
589 jleave:
590 NYD_LEAVE;
591 return rv;
594 static FILE *
595 infix(struct header *hp, FILE *fi) /* TODO check */
597 FILE *nfo, *nfi = NULL;
598 char *tempMail;
599 char const *contenttype, *charset = NULL;
600 enum conversion convert;
601 int do_iconv = 0, err;
602 #ifdef HAVE_ICONV
603 char const *tcs, *convhdr = NULL;
604 #endif
605 NYD_ENTER;
607 if ((nfo = Ftmp(&tempMail, "infix", OF_WRONLY | OF_HOLDSIGS | OF_REGISTER))
608 == NULL) {
609 n_perr(_("temporary mail file"), 0);
610 goto jleave;
612 if ((nfi = Fopen(tempMail, "r")) == NULL) {
613 n_perr(tempMail, 0);
614 Fclose(nfo);
616 Ftmp_release(&tempMail);
617 if (nfi == NULL)
618 goto jleave;
620 pstate &= ~PS_HEADER_NEEDED_MIME; /* TODO a hack should be carrier tracked */
622 contenttype = "text/plain"; /* XXX mail body - always text/plain, want XX? */
623 if((options & OPT_Mm_FLAG) && option_Mm_arg != NULL)
624 contenttype = option_Mm_arg;
625 convert = mime_type_classify_file(fi, &contenttype, &charset, &do_iconv);
627 #ifdef HAVE_ICONV
628 tcs = charset_get_lc();
629 if ((convhdr = need_hdrconv(hp))) {
630 if (iconvd != (iconv_t)-1) /* XXX */
631 n_iconv_close(iconvd);
632 if (asccasecmp(convhdr, tcs) != 0 &&
633 (iconvd = n_iconv_open(convhdr, tcs)) == (iconv_t)-1 &&
634 (err = errno) != 0)
635 goto jiconv_err;
637 #endif
638 if (puthead(FAL0, hp, nfo,
639 (GTO | GSUBJECT | GCC | GBCC | GNL | GCOMMA | GUA | GMIME | GMSGID |
640 GIDENT | GREF | GDATE), SEND_MBOX, convert, contenttype, charset))
641 goto jerr;
642 #ifdef HAVE_ICONV
643 if (iconvd != (iconv_t)-1)
644 n_iconv_close(iconvd);
645 #endif
647 #ifdef HAVE_ICONV
648 if (do_iconv && charset != NULL) { /*TODO charset->mime_type_classify_file*/
649 if (asccasecmp(charset, tcs) != 0 &&
650 (iconvd = n_iconv_open(charset, tcs)) == (iconv_t)-1 &&
651 (err = errno) != 0) {
652 jiconv_err:
653 if (err == EINVAL)
654 n_err(_("Cannot convert from %s to %s\n"), tcs, charset);
655 else
656 n_perr("iconv_open", 0);
657 goto jerr;
660 #endif
662 if (hp->h_attach != NULL) {
663 if (make_multipart(hp, convert, fi, nfo, contenttype, charset) != 0)
664 goto jerr;
665 } else {
666 size_t sz, bufsize, cnt;
667 char *buf;
669 if (convert == CONV_TOQP
670 #ifdef HAVE_ICONV
671 || iconvd != (iconv_t)-1
672 #endif
674 fflush(fi);
675 cnt = fsize(fi);
677 buf = smalloc(bufsize = SEND_LINESIZE);
678 for (err = 0;;) {
679 if (convert == CONV_TOQP
680 #ifdef HAVE_ICONV
681 || iconvd != (iconv_t)-1
682 #endif
684 if (fgetline(&buf, &bufsize, &cnt, &sz, fi, 0) == NULL)
685 break;
686 } else if ((sz = fread(buf, sizeof *buf, bufsize, fi)) == 0)
687 break;
688 if (xmime_write(buf, sz, nfo, convert, TD_ICONV) < 0) {
689 err = 1;
690 break;
693 free(buf);
695 if (err || ferror(fi)) {
696 jerr:
697 Fclose(nfo);
698 Fclose(nfi);
699 #ifdef HAVE_ICONV
700 if (iconvd != (iconv_t)-1)
701 n_iconv_close(iconvd);
702 #endif
703 nfi = NULL;
704 goto jleave;
708 #ifdef HAVE_ICONV
709 if (iconvd != (iconv_t)-1)
710 n_iconv_close(iconvd);
711 #endif
713 fflush(nfo);
714 if ((err = ferror(nfo)))
715 n_perr(_("temporary mail file"), 0);
716 Fclose(nfo);
717 if (!err) {
718 fflush_rewind(nfi);
719 Fclose(fi);
720 } else {
721 Fclose(nfi);
722 nfi = NULL;
724 jleave:
725 NYD_LEAVE;
726 return nfi;
729 static bool_t
730 _check_dispo_notif(struct name *mdn, struct header *hp, FILE *fo)
732 char const *from;
733 bool_t rv = TRU1;
734 NYD_ENTER;
736 /* TODO smtp_disposition_notification (RFC 3798): relation to return-path
737 * TODO not yet checked */
738 if (!ok_blook(disposition_notification_send))
739 goto jleave;
741 if (mdn != NULL && mdn != (struct name*)0x1)
742 from = mdn->n_name;
743 else if ((from = myorigin(hp)) == NULL) {
744 if (options & OPT_D_V)
745 n_err(_("*disposition-notification-send*: no *from* set\n"));
746 goto jleave;
749 if (fmt("Disposition-Notification-To:", nalloc(n_UNCONST(from), 0), fo, 0))
750 rv = FAL0;
751 jleave:
752 NYD_LEAVE;
753 return rv;
756 static int
757 sendmail_internal(void *v, int recipient_record)
759 struct header head;
760 char *str = v;
761 int rv;
762 NYD_ENTER;
764 memset(&head, 0, sizeof head);
765 head.h_to = lextract(str, GTO | GFULL);
766 rv = mail1(&head, 0, NULL, NULL, recipient_record, 0);
767 NYD_LEAVE;
768 return (rv == 0);
771 static struct name *
772 _outof(struct name *names, FILE *fo, bool_t *senderror)
774 ui32_t pipecnt, xcnt, i;
775 int *fda;
776 char const *sh;
777 struct name *np;
778 FILE *fin = NULL, *fout;
779 NYD_ENTER;
781 /* Look through all recipients and do a quick return if no file or pipe
782 * addressee is found */
783 fda = NULL; /* Silence cc */
784 for (pipecnt = xcnt = 0, np = names; np != NULL; np = np->n_flink) {
785 if (np->n_type & GDEL)
786 continue;
787 switch (np->n_flags & NAME_ADDRSPEC_ISFILEORPIPE) {
788 case NAME_ADDRSPEC_ISFILE:
789 ++xcnt;
790 break;
791 case NAME_ADDRSPEC_ISPIPE:
792 ++pipecnt;
793 break;
796 if (pipecnt == 0 && xcnt == 0)
797 goto jleave;
799 /* Otherwise create an array of file descriptors for each found pipe
800 * addressee to get around the dup(2)-shared-file-offset problem, i.e.,
801 * each pipe subprocess needs its very own file descriptor, and we need
802 * to deal with that.
803 * To make our life a bit easier let's just use the auto-reclaimed
804 * string storage */
805 if (pipecnt == 0 || (options & OPT_DEBUG)) {
806 pipecnt = 0;
807 fda = NULL;
808 sh = NULL;
809 } else {
810 fda = salloc(sizeof(int) * pipecnt);
811 for (i = 0; i < pipecnt; ++i)
812 fda[i] = -1;
813 sh = ok_vlook(SHELL);
816 for (np = names; np != NULL; np = np->n_flink) {
817 if (!(np->n_flags & NAME_ADDRSPEC_ISFILEORPIPE))
818 continue;
820 /* In days of old we removed the entry from the the list; now for sake of
821 * header expansion we leave it in and mark it as deleted */
822 np->n_type |= GDEL;
824 if(options & OPT_D_VV)
825 n_err(_(">>> Writing message via %s\n"),
826 n_shexp_quote_cp(np->n_name, FAL0));
827 if(options & OPT_DEBUG)
828 continue;
830 /* See if we have copied the complete message out yet. If not, do so */
831 if (image < 0) {
832 int c;
833 char *tempEdit;
835 if ((fout = Ftmp(&tempEdit, "outof",
836 OF_WRONLY | OF_HOLDSIGS | OF_REGISTER)) == NULL) {
837 n_perr(_("Creation of temporary image"), 0);
838 *senderror = TRU1;
839 goto jcant;
841 if ((image = open(tempEdit, O_RDWR | _O_CLOEXEC)) >= 0) {
842 _CLOEXEC_SET(image);
843 for (i = 0; i < pipecnt; ++i) {
844 int fd = open(tempEdit, O_RDONLY | _O_CLOEXEC);
845 if (fd < 0) {
846 close(image);
847 image = -1;
848 pipecnt = i;
849 break;
851 fda[i] = fd;
852 _CLOEXEC_SET(fd);
855 Ftmp_release(&tempEdit);
857 if (image < 0) {
858 n_perr(_("Creating descriptor duplicate of temporary image"), 0);
859 *senderror = TRU1;
860 Fclose(fout);
861 goto jcant;
864 fprintf(fout, "From %s %s", myname, time_current.tc_ctime);
865 c = EOF;
866 while (i = c, (c = getc(fo)) != EOF)
867 putc(c, fout);
868 rewind(fo);
869 if ((int)i != '\n')
870 putc('\n', fout);
871 putc('\n', fout);
872 fflush(fout);
873 if (ferror(fout)) {
874 n_perr(_("Finalizing write of temporary image"), 0);
875 Fclose(fout);
876 goto jcantfout;
878 Fclose(fout);
880 /* If we have to serve file addressees, open reader */
881 if (xcnt != 0 && (fin = Fdopen(image, "r", FAL0)) == NULL) {
882 n_perr(_("Failed to open a temporary image duplicate"), 0);
883 jcantfout:
884 *senderror = TRU1;
885 close(image);
886 image = -1;
887 goto jcant;
890 /* From now on use xcnt as a counter for pipecnt */
891 xcnt = 0;
894 /* Now either copy "image" to the desired file or give it as the standard
895 * input to the desired program as appropriate */
896 if (np->n_flags & NAME_ADDRSPEC_ISPIPE) {
897 int pid;
898 sigset_t nset;
900 sigemptyset(&nset);
901 sigaddset(&nset, SIGHUP);
902 sigaddset(&nset, SIGINT);
903 sigaddset(&nset, SIGQUIT);
904 pid = start_command(sh, &nset, fda[xcnt++], COMMAND_FD_NULL, "-c",
905 np->n_name + 1, NULL, NULL);
906 if (pid < 0) {
907 n_err(_("Piping message to %s failed\n"),
908 n_shexp_quote_cp(np->n_name, FAL0));
909 *senderror = TRU1;
910 goto jcant;
912 free_child(pid);
913 } else {
914 int c;
915 char const *fname = file_expand(np->n_name), *fnameq;
917 if (fname == NULL) {
918 *senderror = TRU1;
919 goto jcant;
921 fnameq = n_shexp_quote_cp(fname, FAL0);
923 if ((fout = Zopen(fname, "a")) == NULL) {
924 n_err(_("Writing message to %s failed: %s\n"),
925 fnameq, strerror(errno));
926 *senderror = TRU1;
927 goto jcant;
929 rewind(fin);
930 while ((c = getc(fin)) != EOF)
931 putc(c, fout);
932 if (ferror(fout)) {
933 n_err(_("Writing message to %s failed: %s\n"),
934 fnameq, _("write error"));
935 *senderror = TRU1;
937 Fclose(fout);
940 jcant:
941 if (image < 0)
942 goto jdelall;
945 jleave:
946 if (fin != NULL)
947 Fclose(fin);
948 for (i = 0; i < pipecnt; ++i)
949 close(fda[i]);
950 if (image >= 0) {
951 close(image);
952 image = -1;
954 NYD_LEAVE;
955 return names;
957 jdelall:
958 while (np != NULL) {
959 if (np->n_flags & NAME_ADDRSPEC_ISFILEORPIPE)
960 np->n_type |= GDEL;
961 np = np->n_flink;
963 goto jleave;
966 static bool_t
967 mightrecord(FILE *fp, struct name *to, bool_t resend)
969 char *cp, *cq;
970 char const *ep;
971 bool_t rv = TRU1;
972 NYD_ENTER;
974 if (options & OPT_DEBUG)
975 cp = NULL;
976 else if (to != NULL) {
977 cp = savestr(skinned_name(to));
978 for (cq = cp; *cq != '\0' && *cq != '@'; ++cq)
980 *cq = '\0';
981 } else
982 cp = ok_vlook(record);
984 if (cp != NULL) {
985 if ((ep = expand(cp)) == NULL) {
986 ep = "NULL";
987 goto jbail;
990 if (*ep != '/' && *ep != '+' && ok_blook(outfolder) &&
991 which_protocol(ep) == PROTO_FILE) {
992 size_t i = strlen(cp);
993 cq = salloc(i + 1 +1);
994 cq[0] = '+';
995 memcpy(cq + 1, cp, i +1);
996 cp = cq;
997 if ((ep = file_expand(cp)) == NULL) {
998 ep = "NULL";
999 goto jbail;
1003 if (!a_sendout__savemail(ep, fp, resend)) {
1004 jbail:
1005 n_err(_("Failed to save message in %s - message not sent\n"),
1006 n_shexp_quote_cp(ep, FAL0));
1007 exit_status |= EXIT_ERR;
1008 savedeadletter(fp, 1);
1009 rv = FAL0;
1012 NYD_LEAVE;
1013 return rv;
1016 static bool_t
1017 a_sendout__savemail(char const *name, FILE *fp, bool_t resend){
1018 FILE *fo;
1019 size_t bufsize, buflen, cnt;
1020 bool_t rv, emptyline;
1021 char *buf;
1022 NYD_ENTER;
1024 buf = smalloc(bufsize = LINESIZE);
1025 rv = emptyline = FAL0;
1027 if((fo = Zopen(name, "a+")) == NULL){
1028 if((fo = Zopen(name, "wx")) == NULL){
1029 n_perr(name, 0);
1030 goto j_leave;
1032 emptyline = TRU1;
1035 /* TODO RETURN check, but be aware of protocols: v15: Mailbox->lock()! */
1036 n_file_lock(fileno(fo), FLT_WRITE, 0,0, UIZ_MAX);
1038 rv = TRU1;
1040 if(!emptyline){
1041 if(fseek(fo, -2L, SEEK_END) == 0){ /* TODO Should be Mailbox::->append */
1042 switch(fread(buf, sizeof *buf, 2, fo)){
1043 case 2:
1044 if(buf[1] != '\n')
1045 emptyline = TRU1;
1046 break;
1047 case 1:
1048 if(buf[0] != '\n')
1049 emptyline = TRU1;
1050 break;
1051 default:
1052 if(ferror(fo)){
1053 n_perr(name, 0);
1054 rv = FAL0;
1055 goto jleave;
1058 if(emptyline){
1059 putc('\n', fo);
1060 fflush(fo);
1065 fflush_rewind(fp);
1067 fprintf(fo, "From %s %s", myname, time_current.tc_ctime);
1068 for(emptyline = FAL0, buflen = 0, cnt = fsize(fp);
1069 fgetline(&buf, &bufsize, &cnt, &buflen, fp, 0) != NULL;){
1070 /* Only if we are resending it can happen that we have to quote From_
1071 * lines here; we don't generate messages which are ambiguous ourselves */
1072 if(resend){
1073 if(emptyline && is_head(buf, buflen, FAL0))
1074 putc('>', fo);
1075 }DBG(else assert(!is_head(buf, buflen, FAL0)); )
1077 emptyline = (buflen > 0 && *buf == '\n');
1078 fwrite(buf, sizeof *buf, buflen, fo);
1080 if(buflen > 0 && buf[buflen - 1] != '\n')
1081 putc('\n', fo);
1082 putc('\n', fo);
1083 fflush(fo);
1084 if(ferror(fo)){
1085 n_perr(name, 0);
1086 rv = FAL0;
1089 jleave:
1090 really_rewind(fp);
1091 if(Fclose(fo) != 0)
1092 rv = FAL0;
1093 j_leave:
1094 free(buf);
1095 NYD_LEAVE;
1096 return rv;
1099 static bool_t
1100 _transfer(struct sendbundle *sbp)
1102 struct name *np;
1103 ui32_t cnt;
1104 bool_t rv = TRU1;
1105 NYD_ENTER;
1107 for (cnt = 0, np = sbp->sb_to; np != NULL;) {
1108 char const k[] = "smime-encrypt-";
1109 size_t nl = strlen(np->n_name);
1110 char *cp, *vs = ac_alloc(sizeof(k)-1 + nl +1);
1111 memcpy(vs, k, sizeof(k) -1);
1112 memcpy(vs + sizeof(k) -1, np->n_name, nl +1);
1114 if ((cp = vok_vlook(vs)) != NULL) {
1115 #ifdef HAVE_SSL
1116 FILE *ef;
1118 if ((ef = smime_encrypt(sbp->sb_input, cp, np->n_name)) != NULL) {
1119 FILE *fisave = sbp->sb_input;
1120 struct name *nsave = sbp->sb_to;
1122 sbp->sb_to = ndup(np, np->n_type & ~(GFULL | GSKIN));
1123 sbp->sb_input = ef;
1124 if (!__mta_start(sbp))
1125 rv = FAL0;
1126 sbp->sb_to = nsave;
1127 sbp->sb_input = fisave;
1129 Fclose(ef);
1130 } else {
1131 #else
1132 n_err(_("No SSL support compiled in\n"));
1133 rv = FAL0;
1134 #endif
1135 n_err(_("Message not sent to: %s\n"), np->n_name);
1136 _sendout_error = TRU1;
1137 #ifdef HAVE_SSL
1139 #endif
1140 rewind(sbp->sb_input);
1142 if (np->n_flink != NULL)
1143 np->n_flink->n_blink = np->n_blink;
1144 if (np->n_blink != NULL)
1145 np->n_blink->n_flink = np->n_flink;
1146 if (np == sbp->sb_to)
1147 sbp->sb_to = np->n_flink;
1148 np = np->n_flink;
1149 } else {
1150 ++cnt;
1151 np = np->n_flink;
1153 ac_free(vs);
1156 if (cnt > 0 && (ok_blook(smime_force_encryption) || !__mta_start(sbp)))
1157 rv = FAL0;
1158 NYD_LEAVE;
1159 return rv;
1162 static bool_t
1163 __mta_start(struct sendbundle *sbp)
1165 pid_t pid;
1166 sigset_t nset;
1167 char const **args, *mta;
1168 bool_t rv;
1169 NYD_ENTER;
1171 if((mta = ok_vlook(smtp)) != NULL){
1172 OBSOLETE(_("please don't use *smtp*, but assign an SMTP URL to *mta*"));
1173 /* For *smtp* the smtp:// protocol was optional; be simple: don't check
1174 * that *smtp* is misused with file:// or so */
1175 if(n_servbyname(mta, NULL) == NULL)
1176 mta = savecat("smtp://", mta);
1177 rv = TRU1;
1178 }else{
1179 char const *proto;
1181 if((proto = ok_vlook(sendmail)) != NULL)
1182 OBSOLETE(_("please use *mta* instead of *sendmail*"));
1183 if((mta = ok_vlook(mta)) == NULL){ /* TODO v15: mta = ok_vlook(mta); */
1184 if(proto == NULL){
1185 mta = VAL_MTA;
1186 rv = FAL0;
1187 }else
1188 rv = TRU1;
1190 /* TODO for now this is pretty hacky: in v15 we should simply create
1191 * TODO an URL object; i.e., be able to do so, and it does it right
1192 * TODO I.e.,: url_creat(&url, ok_vlook(mta)); */
1193 else if((proto = n_servbyname(mta, NULL)) != NULL){
1194 if(*proto == '\0'){
1195 mta += sizeof("file://") -1;
1196 rv = FAL0;
1197 }else
1198 rv = TRU1;
1199 }else
1200 rv = FAL0;
1203 if(!rv){
1204 char const *mta_base;
1206 if((mta = file_expand(mta_base = mta)) == NULL){
1207 n_err(_("*mta* variable expansion failure: %s\n"),
1208 n_shexp_quote_cp(mta_base, FAL0));
1209 goto jstop;
1212 args = __mta_prepare_args(sbp->sb_to, sbp->sb_hp);
1213 if (options & OPT_DEBUG) {
1214 __mta_debug(sbp, mta, args);
1215 rv = TRU1;
1216 goto jleave;
1218 } else {
1219 n_UNINIT(args, NULL);
1220 #ifndef HAVE_SMTP
1221 n_err(_("No SMTP support compiled in\n"));
1222 goto jstop;
1223 #else
1224 if (options & OPT_DEBUG) {
1225 (void)smtp_mta(sbp);
1226 rv = TRU1;
1227 goto jleave;
1229 #endif
1232 /* Fork, set up the temporary mail file as standard input for "mail", and
1233 * exec with the user list we generated far above */
1234 if ((pid = fork_child()) == -1) {
1235 n_perr("fork", 0);
1236 jstop:
1237 savedeadletter(sbp->sb_input, 0);
1238 _sendout_error = TRU1;
1239 goto jleave;
1241 if (pid == 0) {
1242 sigemptyset(&nset);
1243 sigaddset(&nset, SIGHUP);
1244 sigaddset(&nset, SIGINT);
1245 sigaddset(&nset, SIGQUIT);
1246 sigaddset(&nset, SIGTSTP);
1247 sigaddset(&nset, SIGTTIN);
1248 sigaddset(&nset, SIGTTOU);
1249 freopen("/dev/null", "r", stdin);
1250 #ifdef HAVE_SMTP
1251 if (rv) {
1252 prepare_child(&nset, 0, 1);
1253 if (smtp_mta(sbp))
1254 _exit(EXIT_OK);
1255 } else
1256 #endif
1258 char const *ecp;
1259 int e;
1261 prepare_child(&nset, fileno(sbp->sb_input), -1);
1262 execv(mta, n_UNCONST(args));
1263 e = errno;
1264 ecp = (e != ENOENT) ? strerror(e)
1265 : _("executable not found (adjust *mta* variable)");
1266 n_err(_("Cannot start %s: %s\n"), n_shexp_quote_cp(mta, FAL0), ecp);
1268 savedeadletter(sbp->sb_input, 1);
1269 n_err(_("... message not sent\n"));
1270 _exit(EXIT_ERR);
1273 if ((options & (OPT_DEBUG | OPT_VERB)) || ok_blook(sendwait)) {
1274 if (!(rv = wait_child(pid, NULL)))
1275 _sendout_error = TRU1;
1276 } else {
1277 free_child(pid);
1278 rv = TRU1;
1280 jleave:
1281 NYD_LEAVE;
1282 return rv;
1285 static char const **
1286 __mta_prepare_args(struct name *to, struct header *hp)
1288 size_t vas_cnt, i, j;
1289 char **vas;
1290 char const **args, *cp, *cp_v15compat;
1291 bool_t snda;
1292 NYD_ENTER;
1294 if((cp_v15compat = ok_vlook(sendmail_arguments)) != NULL)
1295 OBSOLETE(_("please use *mta-arguments*, not *sendmail-arguments*"));
1296 if((cp = ok_vlook(mta_arguments)) == NULL)
1297 cp = cp_v15compat;
1298 if ((cp /* TODO v15: = ok_vlook(mta_arguments)*/) == NULL) {
1299 vas_cnt = 0;
1300 vas = NULL;
1301 } else {
1302 /* Don't assume anything on the content but do allocate exactly j slots;
1303 * like this getrawlist will never overflow (and return -1) */
1304 j = strlen(cp);
1305 vas = n_lofi_alloc(sizeof(*vas) * j);
1306 vas_cnt = (size_t)getrawlist(FAL0, vas, j, cp, j);
1309 i = 4 + smopts_cnt + vas_cnt + 4 + 1 + count(to) + 1;
1310 args = salloc(i * sizeof(char*));
1312 if((cp_v15compat = ok_vlook(sendmail_progname)) != NULL)
1313 OBSOLETE(_("please use *mta-argv0*, not *sendmail-progname*"));
1314 if((cp = ok_vlook(mta_argv0)) == NULL)
1315 cp = cp_v15compat;
1316 if(cp == NULL)
1317 cp = VAL_MTA_ARGV0;
1318 args[0] = cp/* TODO v15: = ok_vlook(mta_argv0) */;
1320 if ((snda = ok_blook(sendmail_no_default_arguments)))
1321 OBSOLETE(_("please use *mta-no-default-arguments*, "
1322 "not *sendmail-no-default-arguments*"));
1323 snda |= ok_blook(mta_no_default_arguments);
1324 if ((snda /* TODO v15: = ok_blook(mta_no_default_arguments)*/))
1325 i = 1;
1326 else {
1327 args[1] = "-i";
1328 i = 2;
1329 if (ok_blook(metoo))
1330 args[i++] = "-m";
1331 if (options & OPT_VERB)
1332 args[i++] = "-v";
1335 for (j = 0; j < smopts_cnt; ++j, ++i)
1336 args[i] = smopts[j];
1338 for (j = 0; j < vas_cnt; ++j, ++i)
1339 args[i] = vas[j];
1341 /* -r option? In conjunction with -t we act compatible to postfix(1) and
1342 * ignore it (it is -f / -F there) if the message specified From:/Sender:.
1343 * The interdependency with -t has been resolved in puthead() */
1344 if (!snda && (options & OPT_r_FLAG)) {
1345 struct name const *np;
1347 if (hp != NULL && (np = hp->h_from) != NULL) {
1348 /* However, what wasn't resolved there was the case that the message
1349 * specified multiple From: addresses and a Sender: */
1350 if ((pstate & PS_t_FLAG) && hp->h_sender != NULL)
1351 np = hp->h_sender;
1353 if (np->n_fullextra != NULL) {
1354 args[i++] = "-F";
1355 args[i++] = np->n_fullextra;
1357 cp = np->n_name;
1358 } else {
1359 assert(option_r_arg == NULL);
1360 cp = skin(myorigin(NULL));
1363 if (cp != NULL) {
1364 args[i++] = "-f";
1365 args[i++] = cp;
1369 /* Terminate option list to avoid false interpretation of system-wide
1370 * aliases that start with hyphen */
1371 if (!snda)
1372 args[i++] = "--";
1374 /* Receivers follow */
1375 for (; to != NULL; to = to->n_flink)
1376 if (!(to->n_type & GDEL))
1377 args[i++] = to->n_name;
1378 args[i] = NULL;
1380 if(vas != NULL)
1381 n_lofi_free(vas);
1382 NYD_LEAVE;
1383 return args;
1386 static void
1387 __mta_debug(struct sendbundle *sbp, char const *mta, char const **args)
1389 size_t cnt, bufsize, llen;
1390 char *buf;
1391 NYD_ENTER;
1393 n_err(_(">>> MTA: %s, arguments:"), n_shexp_quote_cp(mta, FAL0));
1394 for (; *args != NULL; ++args)
1395 n_err(" %s", n_shexp_quote_cp(*args, FAL0));
1396 n_err("\n");
1398 fflush_rewind(sbp->sb_input);
1400 cnt = fsize(sbp->sb_input);
1401 buf = NULL;
1402 bufsize = 0;
1403 while (fgetline(&buf, &bufsize, &cnt, &llen, sbp->sb_input, TRU1) != NULL) {
1404 buf[--llen] = '\0';
1405 n_err(">>> %s\n", buf);
1407 if (buf != NULL)
1408 free(buf);
1409 NYD_LEAVE;
1412 static char *
1413 _message_id(struct header *hp)
1415 char *rv = NULL, sep;
1416 char const *h;
1417 size_t rl, i;
1418 struct tm *tmp;
1419 NYD_ENTER;
1421 if (hp != NULL && hp->h_message_id != NULL) {
1422 i = strlen(hp->h_message_id->n_name);
1423 rl = sizeof("Message-ID: <>") -1;
1424 rv = salloc(rl + i +1);
1425 memcpy(rv, "Message-ID: <", --rl);
1426 memcpy(rv + rl, hp->h_message_id->n_name, i);
1427 rl += i;
1428 rv[rl++] = '>';
1429 rv[rl] = '\0';
1430 goto jleave;
1433 if (ok_blook(message_id_disable))
1434 goto jleave;
1436 sep = '%';
1437 rl = 9;
1438 if ((h = __sendout_ident) != NULL)
1439 goto jgen;
1440 if (ok_vlook(hostname) != NULL) {
1441 h = nodename(1);
1442 sep = '@';
1443 rl = 15;
1444 goto jgen;
1446 if (hp != NULL && (h = skin(myorigin(hp))) != NULL && strchr(h, '@') != NULL)
1447 goto jgen;
1448 /* Up to MTA */
1449 goto jleave;
1451 jgen:
1452 tmp = &time_current.tc_gm;
1453 i = sizeof("Message-ID: <%04d%02d%02d%02d%02d%02d.%s%c%s>") -1 +
1454 rl + strlen(h);
1455 rv = salloc(i +1);
1456 snprintf(rv, i, "Message-ID: <%04d%02d%02d%02d%02d%02d.%s%c%s>",
1457 tmp->tm_year + 1900, tmp->tm_mon + 1, tmp->tm_mday,
1458 tmp->tm_hour, tmp->tm_min, tmp->tm_sec,
1459 getrandstring(rl), sep, h);
1460 rv[i] = '\0'; /* Because we don't test snprintf(3) return */
1461 jleave:
1462 NYD_LEAVE;
1463 return rv;
1466 static int
1467 fmt(char const *str, struct name *np, FILE *fo, enum fmt_flags ff)
1469 enum {
1470 m_INIT = 1<<0,
1471 m_COMMA = 1<<1,
1472 m_NOPF = 1<<2,
1473 m_NONAME = 1<<3,
1474 m_CSEEN = 1<<4
1475 } m = (ff & GCOMMA) ? m_COMMA : 0;
1476 ssize_t col, len;
1477 int rv = 1;
1478 NYD_ENTER;
1480 col = strlen(str);
1481 if (col) {
1482 fwrite(str, sizeof *str, col, fo);
1483 #undef _X
1484 #define _X(S) (col == sizeof(S) -1 && !asccasecmp(str, S))
1485 if (ff & GFILES) {
1487 } else if (_X("reply-to:") || _X("mail-followup-to:") ||
1488 _X("references:") || _X("disposition-notification-to:"))
1489 m |= m_NOPF | m_NONAME;
1490 else if (ok_blook(add_file_recipients)) {
1492 } else if (_X("to:") || _X("cc:") || _X("bcc:") || _X("resent-to:"))
1493 m |= m_NOPF;
1494 #undef _X
1497 for (; np != NULL; np = np->n_flink) {
1498 if (is_addr_invalid(np,
1499 EACM_NOLOG | (m & m_NONAME ? EACM_NONAME : EACM_NONE)))
1500 continue;
1501 /* File and pipe addresses only printed with set *add-file-recipients* */
1502 if ((m & m_NOPF) && is_fileorpipe_addr(np))
1503 continue;
1505 if ((m & (m_INIT | m_COMMA)) == (m_INIT | m_COMMA)) {
1506 if (putc(',', fo) == EOF)
1507 goto jleave;
1508 m |= m_CSEEN;
1509 ++col;
1512 len = strlen(np->n_fullname);
1513 if (np->n_flags & GREF)
1514 len += 2;
1515 ++col; /* The separating space */
1516 if ((m & m_INIT) && /*col > 1 &&*/ UICMP(z, col + len, >, 72)) {
1517 if (fputs("\n ", fo) == EOF)
1518 goto jleave;
1519 col = 1;
1520 m &= ~m_CSEEN;
1521 } else
1522 putc(' ', fo);
1523 m = (m & ~m_CSEEN) | m_INIT;
1526 char *hb = np->n_fullname;
1527 /* GREF needs to be placed in angle brackets, but which are missing */
1528 if (np->n_type & GREF) {
1529 hb = ac_alloc(len + 2 +1);
1530 hb[0] = '<';
1531 hb[len + 1] = '>';
1532 hb[len + 2] = '\0';
1533 memcpy(hb + 1, np->n_fullname, len);
1534 len += 2;
1536 len = xmime_write(hb, len, fo,
1537 ((ff & FMT_DOMIME) ? CONV_TOHDR_A : CONV_NONE), TD_ICONV);
1538 if (np->n_type & GREF)
1539 ac_free(hb);
1541 if (len < 0)
1542 goto jleave;
1543 col += len;
1546 if (putc('\n', fo) != EOF)
1547 rv = 0;
1548 jleave:
1549 NYD_LEAVE;
1550 return rv;
1553 static int
1554 infix_resend(FILE *fi, FILE *fo, struct message *mp, struct name *to,
1555 int add_resent)
1557 size_t cnt, c, bufsize = 0;
1558 char *buf = NULL;
1559 char const *cp;
1560 struct name *fromfield = NULL, *senderfield = NULL, *mdn;
1561 int rv = 1;
1562 NYD_ENTER;
1564 cnt = mp->m_size;
1566 /* Write the Resent-Fields */
1567 if (add_resent) {
1568 fputs("Resent-", fo);
1569 mkdate(fo, "Date");
1570 if ((cp = myaddrs(NULL)) != NULL) {
1571 if (_putname(cp, GCOMMA, SEND_MBOX, NULL, "Resent-From:", fo,
1572 &fromfield, 0))
1573 goto jleave;
1575 /* TODO RFC 5322: Resent-Sender SHOULD NOT be used if it's EQ -From: */
1576 if ((cp = ok_vlook(sender)) != NULL) {
1577 if (_putname(cp, GCOMMA, SEND_MBOX, NULL, "Resent-Sender:", fo,
1578 &senderfield, 0))
1579 goto jleave;
1581 if (fmt("Resent-To:", to, fo, FMT_COMMA))
1582 goto jleave;
1583 if (((cp = ok_vlook(stealthmua)) == NULL || !strcmp(cp, "noagent")) &&
1584 (cp = _message_id(NULL)) != NULL)
1585 fprintf(fo, "Resent-%s\n", cp);
1588 if ((mdn = n_UNCONST(check_from_and_sender(fromfield, senderfield))) == NULL)
1589 goto jleave;
1590 if (!_check_dispo_notif(mdn, NULL, fo))
1591 goto jleave;
1593 /* Write the original headers */
1594 while (cnt > 0) {
1595 if (fgetline(&buf, &bufsize, &cnt, &c, fi, 0) == NULL)
1596 break;
1597 if (ascncasecmp("status:", buf, 7) &&
1598 ascncasecmp("disposition-notification-to:", buf, 28) &&
1599 !is_head(buf, c, FAL0))
1600 fwrite(buf, sizeof *buf, c, fo);
1601 if (cnt > 0 && *buf == '\n')
1602 break;
1605 /* Write the message body */
1606 while (cnt > 0) {
1607 if (fgetline(&buf, &bufsize, &cnt, &c, fi, 0) == NULL)
1608 break;
1609 if (cnt == 0 && *buf == '\n')
1610 break;
1611 fwrite(buf, sizeof *buf, c, fo);
1613 if (buf != NULL)
1614 free(buf);
1615 if (ferror(fo)) {
1616 n_perr(_("temporary mail file"), 0);
1617 goto jleave;
1619 rv = 0;
1620 jleave:
1621 NYD_LEAVE;
1622 return rv;
1625 FL int
1626 mail(struct name *to, struct name *cc, struct name *bcc, char *subject,
1627 struct attachment *attach, char *quotefile, int recipient_record)
1629 struct header head;
1630 struct str in, out;
1631 NYD_ENTER;
1633 memset(&head, 0, sizeof head);
1635 /* The given subject may be in RFC1522 format. */
1636 if (subject != NULL) {
1637 in.s = subject;
1638 in.l = strlen(subject);
1639 mime_fromhdr(&in, &out, /* TODO ??? TD_ISPR |*/ TD_ICONV);
1640 head.h_subject = out.s;
1642 head.h_to = to;
1643 head.h_cc = cc;
1644 head.h_bcc = bcc;
1645 head.h_attach = attach;
1647 mail1(&head, 0, NULL, quotefile, recipient_record, 0);
1649 if (subject != NULL)
1650 free(out.s);
1651 NYD_LEAVE;
1652 return 0;
1655 FL int
1656 c_sendmail(void *v)
1658 int rv;
1659 NYD_ENTER;
1661 rv = sendmail_internal(v, 0);
1662 NYD_LEAVE;
1663 return rv;
1666 FL int
1667 c_Sendmail(void *v)
1669 int rv;
1670 NYD_ENTER;
1672 rv = sendmail_internal(v, 1);
1673 NYD_LEAVE;
1674 return rv;
1677 FL enum okay
1678 mail1(struct header *hp, int printheaders, struct message *quote,
1679 char *quotefile, int recipient_record, int doprefix)
1681 struct sendbundle sb;
1682 struct name *to;
1683 FILE *mtf, *nmtf;
1684 bool_t dosign;
1685 enum okay rv = STOP;
1686 NYD_ENTER;
1688 _sendout_error = FAL0;
1689 __sendout_ident = NULL;
1691 /* Update some globals we likely need first */
1692 time_current_update(&time_current, TRU1);
1694 /* Collect user's mail from standard input. Get the result as mtf */
1695 mtf = collect(hp, printheaders, quote, quotefile, doprefix, &_sendout_error);
1696 if (mtf == NULL)
1697 goto j_leave;
1699 dosign = TRUM1;
1701 /* */
1702 if (options & OPT_INTERACTIVE) {
1703 if (ok_blook(asksign))
1704 dosign = getapproval(_("Sign this message"), TRU1);
1707 if (fsize(mtf) == 0) {
1708 if (options & OPT_E_FLAG)
1709 goto jleave;
1710 if (hp->h_subject == NULL)
1711 printf(_("No message, no subject; hope that's ok\n"));
1712 else if (ok_blook(bsdcompat) || ok_blook(bsdmsgs))
1713 printf(_("Null message body; hope that's ok\n"));
1716 if (dosign == TRUM1)
1717 dosign = ok_blook(smime_sign); /* TODO USER@HOST <-> *from* +++!!! */
1718 #ifndef HAVE_SSL
1719 if (dosign) {
1720 n_err(_("No SSL support compiled in\n"));
1721 goto jleave;
1723 #endif
1725 /* XXX Update time_current again; once collect() offers editing of more
1726 * XXX headers, including Date:, this must only happen if Date: is the
1727 * XXX same that it was before collect() (e.g., postponing etc.).
1728 * XXX But *do* update otherwise because the mail seems to be backdated
1729 * XXX if the user edited some time, which looks odd and it happened
1730 * XXX to me that i got mis-dated response mails due to that... */
1731 time_current_update(&time_current, TRU1);
1733 /* TODO hrmpf; the MIME/send layer rewrite MUST address the init crap:
1734 * TODO setup the header ONCE; note this affects edit.c, collect.c ...,
1735 * TODO but: offer a hook that rebuilds/expands/checks/fixates all
1736 * TODO header fields ONCE, call that ONCE after user editing etc. has
1737 * TODO completed (one edit cycle) */
1739 /* Take the user names from the combined to and cc lists and do all the
1740 * alias processing. The POSIX standard says:
1741 * The names shall be substituted when alias is used as a recipient
1742 * address specified by the user in an outgoing message (that is,
1743 * other recipients addressed indirectly through the reply command
1744 * shall not be substituted in this manner).
1745 * S-nail thus violates POSIX, as has been pointed out correctly by
1746 * Martin Neitzel, but logic and usability of POSIX standards is not seldom
1747 * disputable anyway. Go for user friendliness */
1749 to = namelist_vaporise_head(hp,
1750 (EACM_NORMAL |
1751 (!(expandaddr_to_eaf() & EAF_NAME) ? EACM_NONAME : EACM_NONE)),
1752 TRU1, &_sendout_error);
1753 if (to == NULL) {
1754 n_err(_("No recipients specified\n"));
1755 goto jfail_dead;
1757 if (_sendout_error < 0) {
1758 n_err(_("Some addressees were classified as \"hard error\"\n"));
1759 goto jfail_dead;
1762 /* */
1763 memset(&sb, 0, sizeof sb);
1764 sb.sb_hp = hp;
1765 sb.sb_to = to;
1766 sb.sb_input = mtf;
1767 if ((dosign || count_nonlocal(to) > 0) &&
1768 !_sendbundle_setup_creds(&sb, (dosign > 0)))
1769 /* TODO saving $DEAD and recovering etc is not yet well defined */
1770 goto jfail_dead;
1772 /* 'Bit ugly kind of control flow until we find a charset that does it */
1773 for (charset_iter_reset(hp->h_charset);; charset_iter_next()) {
1774 int err;
1776 if (!charset_iter_is_valid())
1778 else if ((nmtf = infix(hp, mtf)) != NULL)
1779 break;
1780 else if ((err = errno) == EILSEQ || err == EINVAL) {
1781 rewind(mtf);
1782 continue;
1785 n_perr(_("Failed to create encoded message"), 0);
1786 goto jfail_dead;
1788 mtf = nmtf;
1790 /* */
1791 #ifdef HAVE_SSL
1792 if (dosign) {
1793 if ((nmtf = smime_sign(mtf, sb.sb_signer.s)) == NULL)
1794 goto jfail_dead;
1795 Fclose(mtf);
1796 mtf = nmtf;
1798 #endif
1800 /* TODO truly - i still don't get what follows: (1) we deliver file
1801 * TODO and pipe addressees, (2) we mightrecord() and (3) we transfer
1802 * TODO even if (1) savedeadletter() etc. To me this doesn't make sense? */
1804 /* Deliver pipe and file addressees */
1805 to = _outof(to, mtf, &_sendout_error);
1806 if (_sendout_error)
1807 savedeadletter(mtf, FAL0);
1809 to = elide(to); /* XXX needed only to drop GDELs due to _outof()! */
1811 { ui32_t cnt = count(to);
1812 if ((!recipient_record || cnt > 0) &&
1813 !mightrecord(mtf, (recipient_record ? to : NULL), FAL0))
1814 goto jleave;
1815 if (cnt > 0) {
1816 sb.sb_hp = hp;
1817 sb.sb_to = to;
1818 sb.sb_input = mtf;
1819 if (_transfer(&sb))
1820 rv = OKAY;
1821 } else if (!_sendout_error)
1822 rv = OKAY;
1824 jleave:
1825 Fclose(mtf);
1826 j_leave:
1827 if (_sendout_error)
1828 exit_status |= EXIT_SEND_ERROR;
1829 NYD_LEAVE;
1830 return rv;
1832 jfail_dead:
1833 _sendout_error = TRU1;
1834 savedeadletter(mtf, TRU1);
1835 n_err(_("... message not sent\n"));
1836 goto jleave;
1839 FL int
1840 mkdate(FILE *fo, char const *field)
1842 struct tm tmpgm, *tmptr;
1843 int tzdiff, tzdiff_hour, tzdiff_min, rv;
1844 NYD_ENTER;
1846 memcpy(&tmpgm, &time_current.tc_gm, sizeof tmpgm);
1847 tzdiff = time_current.tc_time - mktime(&tmpgm);
1848 tzdiff_hour = (int)(tzdiff / 60);
1849 tzdiff_min = tzdiff_hour % 60;
1850 tzdiff_hour /= 60;
1851 tmptr = &time_current.tc_local;
1852 if (tmptr->tm_isdst > 0)
1853 ++tzdiff_hour;
1854 rv = fprintf(fo, "%s: %s, %02d %s %04d %02d:%02d:%02d %+05d\n",
1855 field,
1856 weekday_names[tmptr->tm_wday],
1857 tmptr->tm_mday, month_names[tmptr->tm_mon],
1858 tmptr->tm_year + 1900, tmptr->tm_hour,
1859 tmptr->tm_min, tmptr->tm_sec,
1860 tzdiff_hour * 100 + tzdiff_min);
1861 NYD_LEAVE;
1862 return rv;
1865 FL int
1866 puthead(bool_t nosend_msg, struct header *hp, FILE *fo, enum gfield w,
1867 enum sendaction action, enum conversion convert, char const *contenttype,
1868 char const *charset)
1870 #define FMT_CC_AND_BCC() \
1871 do {\
1872 if ((w & GCC) && (hp->h_cc != NULL || nosend_msg == TRUM1)) {\
1873 if (fmt("Cc:", hp->h_cc, fo, ff))\
1874 goto jleave;\
1875 ++gotcha;\
1877 if ((w & GBCC) && (hp->h_bcc != NULL || nosend_msg == TRUM1)) {\
1878 if (fmt("Bcc:", hp->h_bcc, fo, ff))\
1879 goto jleave;\
1880 ++gotcha;\
1882 } while (0)
1884 char const *addr;
1885 size_t gotcha;
1886 struct name *np, *fromasender = NULL;
1887 int stealthmua, rv = 1;
1888 bool_t nodisp;
1889 enum fmt_flags ff;
1890 NYD_ENTER;
1892 if ((addr = ok_vlook(stealthmua)) != NULL)
1893 stealthmua = !strcmp(addr, "noagent") ? -1 : 1;
1894 else
1895 stealthmua = 0;
1896 gotcha = 0;
1897 nodisp = (action != SEND_TODISP);
1898 ff = (w & (GCOMMA | GFILES)) | (nodisp ? FMT_DOMIME : 0);
1900 if (w & GDATE)
1901 mkdate(fo, "Date"), ++gotcha;
1902 if (w & GIDENT) {
1903 if (hp->h_from == NULL || hp->h_sender == NULL)
1904 setup_from_and_sender(hp);
1906 if (hp->h_from != NULL) {
1907 if (fmt("From:", hp->h_from, fo, ff))
1908 goto jleave;
1909 ++gotcha;
1912 if (hp->h_sender != NULL) {
1913 if (fmt("Sender:", hp->h_sender, fo, ff))
1914 goto jleave;
1915 ++gotcha;
1918 fromasender = n_UNCONST(check_from_and_sender(hp->h_from, hp->h_sender));
1919 if (fromasender == NULL)
1920 goto jleave;
1921 /* Note that fromasender is (NULL,) 0x1 or real sender here */
1924 if ((w & GTO) && (hp->h_to != NULL || nosend_msg == TRUM1)) {
1925 if (fmt("To:", hp->h_to, fo, ff))
1926 goto jleave;
1927 ++gotcha;
1930 if (!ok_blook(bsdcompat) && !ok_blook(bsdorder))
1931 FMT_CC_AND_BCC();
1933 if ((w & GSUBJECT) && (hp->h_subject != NULL || nosend_msg == TRUM1)) {
1934 fwrite("Subject: ", sizeof(char), 9, fo);
1935 if (hp->h_subject != NULL) {
1936 char *sub = subject_re_trim(hp->h_subject);
1937 size_t sublen = strlen(sub);
1939 /* Trimmed something, (re-)add Re: */
1940 if (sub != hp->h_subject) {
1941 fwrite("Re: ", sizeof(char), 4, fo); /* RFC mandates eng. "Re: " */
1942 if (sublen > 0 &&
1943 xmime_write(sub, sublen, fo,
1944 (!nodisp ? CONV_NONE : CONV_TOHDR),
1945 (!nodisp ? TD_ISPR | TD_ICONV : TD_ICONV)) < 0)
1946 goto jleave;
1948 /* This may be, e.g., a Fwd: XXX yes, unfortunately we do like that */
1949 else if (*sub != '\0') {
1950 if (xmime_write(sub, sublen, fo, (!nodisp ? CONV_NONE : CONV_TOHDR),
1951 (!nodisp ? TD_ISPR | TD_ICONV : TD_ICONV)) < 0)
1952 goto jleave;
1955 ++gotcha;
1956 putc('\n', fo);
1959 if (ok_blook(bsdcompat) || ok_blook(bsdorder))
1960 FMT_CC_AND_BCC();
1962 if ((w & GMSGID) && stealthmua <= 0 && (addr = _message_id(hp)) != NULL) {
1963 fputs(addr, fo);
1964 putc('\n', fo);
1965 ++gotcha;
1968 if ((np = hp->h_ref) != NULL && (w & GREF)) {
1969 if (fmt("References:", np, fo, 0))
1970 goto jleave;
1971 if (hp->h_in_reply_to == NULL && np->n_name != NULL) {
1972 while (np->n_flink != NULL)
1973 np = np->n_flink;
1974 if (!is_addr_invalid(np, /* TODO check that on parser side! */
1975 /*EACM_STRICT | TODO '/' valid!! */ EACM_NOLOG | EACM_NONAME)) {
1976 fprintf(fo, "In-Reply-To: <%s>\n",np->n_name);/*TODO RFC5322 3.6.4*/
1977 ++gotcha;
1978 } else {
1979 n_err(_("Invalid address in mail header: %s\n"), np->n_name);
1980 goto jleave;
1984 if ((np = hp->h_in_reply_to) != NULL && (w & GREF)) {
1985 fprintf(fo, "In-Reply-To: <%s>\n", np->n_name);/*TODO RFC 5322 3.6.4*/
1986 ++gotcha;
1989 if (w & GIDENT) {
1990 /* Reply-To:. Be careful not to destroy a possible user input, duplicate
1991 * the list first.. TODO it is a terrible codebase.. */
1992 if ((np = hp->h_replyto) != NULL)
1993 np = namelist_dup(np, np->n_type);
1994 else if ((addr = ok_vlook(replyto)) != NULL)
1995 np = lextract(addr, GEXTRA | GFULL);
1996 if (np != NULL &&
1997 (np = elide(
1998 checkaddrs(usermap(np, TRU1), EACM_STRICT | EACM_NOLOG,
1999 NULL))) != NULL) {
2000 if (fmt("Reply-To:", np, fo, ff))
2001 goto jleave;
2002 ++gotcha;
2006 if ((w & GIDENT) && !nosend_msg) {
2007 /* Mail-Followup-To: TODO factor out this huge block of code */
2008 /* Place ourselfs in there if any non-subscribed list is an addressee */
2009 if ((hp->h_flags & HF_LIST_REPLY) || hp->h_mft != NULL ||
2010 ok_blook(followup_to)) {
2011 enum {_ANYLIST=1<<(HF__NEXT_SHIFT+0), _HADMFT=1<<(HF__NEXT_SHIFT+1)};
2013 ui32_t f = hp->h_flags | (hp->h_mft != NULL ? _HADMFT : 0);
2014 struct name *mft, *x;
2016 /* But for that, we have to remove all incarnations of ourselfs first.
2017 * TODO It is total crap that we have delete_alternates(), is_myname()
2018 * TODO or whatever; these work only with variables, not with data
2019 * TODO that is _currently_ in some header fields!!! v15.0: complete
2020 * TODO rewrite, object based, lazy evaluated, on-the-fly marked.
2021 * TODO then this should be a really cheap thing in here... */
2022 np = elide(delete_alternates(cat(
2023 namelist_dup(hp->h_to, GEXTRA | GFULL),
2024 namelist_dup(hp->h_cc, GEXTRA | GFULL))));
2025 addr = hp->h_list_post;
2027 for (mft = NULL; (x = np) != NULL;) {
2028 si8_t ml;
2029 np = np->n_flink;
2031 if ((ml = is_mlist(x->n_name, FAL0)) == MLIST_OTHER &&
2032 addr != NULL && !asccasecmp(addr, x->n_name))
2033 ml = MLIST_KNOWN;
2035 /* Any non-subscribed list? Add ourselves */
2036 switch (ml) {
2037 case MLIST_KNOWN:
2038 f |= HF_MFT_SENDER;
2039 /* FALLTHRU */
2040 case MLIST_SUBSCRIBED:
2041 f |= _ANYLIST;
2042 goto j_mft_add;
2043 case MLIST_OTHER:
2044 if (!(f & HF_LIST_REPLY)) {
2045 j_mft_add:
2046 if (!is_addr_invalid(x,
2047 EACM_STRICT | EACM_NOLOG | EACM_NONAME)) {
2048 x->n_flink = mft;
2049 mft = x;
2050 } /* XXX write some warning? if verbose?? */
2051 continue;
2053 /* And if this is a reply that honoured a MFT: header then we'll
2054 * also add all members of the original MFT: that are still
2055 * addressed by us, regardless of all other circumstances */
2056 else if (f & _HADMFT) {
2057 struct name *ox;
2058 for (ox = hp->h_mft; ox != NULL; ox = ox->n_flink)
2059 if (!asccasecmp(ox->n_name, x->n_name))
2060 goto j_mft_add;
2062 break;
2066 if (f & (_ANYLIST | _HADMFT) && mft != NULL) {
2067 if (((f & HF_MFT_SENDER) ||
2068 ((f & (_ANYLIST | _HADMFT)) == _HADMFT)) &&
2069 (np = fromasender) != NULL && np != (struct name*)0x1) {
2070 np = ndup(np, (np->n_type & ~GMASK) | GEXTRA | GFULL);
2071 np->n_flink = mft;
2072 mft = np;
2075 if (fmt("Mail-Followup-To:", mft, fo, ff))
2076 goto jleave;
2077 ++gotcha;
2081 if (!_check_dispo_notif(fromasender, hp, fo))
2082 goto jleave;
2085 if ((w & GUA) && stealthmua == 0)
2086 fprintf(fo, "User-Agent: %s %s\n", uagent, ok_vlook(version)), ++gotcha;
2088 /* The user may have placed headers when editing */
2089 if(1){
2090 struct n_header_field *hfp;
2092 if((hfp = hp->h_user_headers) != NULL){
2093 if(!_sendout_header_list(fo, hfp, nodisp))
2094 goto jleave;
2095 ++gotcha;
2099 /* Custom headers, as via `customhdr' */
2100 if(!nosend_msg){
2101 struct n_header_field *hfp;
2103 /* With iconv support we likely have a cached result */
2104 if((hfp = hp->h_custom_headers) == NULL)
2105 hp->h_custom_headers = hfp = n_customhdr_query();
2106 if(hfp != NULL){
2107 if(!_sendout_header_list(fo, hfp, nodisp))
2108 goto jleave;
2109 ++gotcha;
2113 /* We don't need MIME unless.. we need MIME?! */
2114 if ((w & GMIME) && ((pstate & PS_HEADER_NEEDED_MIME) ||
2115 hp->h_attach != NULL ||
2116 ((options & OPT_Mm_FLAG) && option_Mm_arg != NULL) ||
2117 convert != CONV_7BIT || asccasecmp(charset, "US-ASCII"))) {
2118 ++gotcha;
2119 fputs("MIME-Version: 1.0\n", fo);
2120 if (hp->h_attach != NULL) {
2121 _sendout_boundary = mime_param_boundary_create();/*TODO carrier*/
2122 fprintf(fo, "Content-Type: multipart/mixed;\n boundary=\"%s\"\n",
2123 _sendout_boundary);
2124 } else {
2125 if (_put_ct(fo, contenttype, charset) < 0 || _put_cte(fo, convert) < 0)
2126 goto jleave;
2130 if (gotcha && (w & GNL))
2131 putc('\n', fo);
2132 rv = 0;
2133 jleave:
2134 NYD_LEAVE;
2135 return rv;
2136 #undef FMT_CC_AND_BCC
2139 FL enum okay
2140 resend_msg(struct message *mp, struct name *to, int add_resent) /* TODO check */
2142 struct sendbundle sb;
2143 FILE *ibuf, *nfo, *nfi;
2144 char *tempMail;
2145 enum okay rv = STOP;
2146 NYD_ENTER;
2148 _sendout_error = FAL0;
2149 __sendout_ident = NULL;
2151 /* Update some globals we likely need first */
2152 time_current_update(&time_current, TRU1);
2154 if ((to = checkaddrs(to,
2155 (EACM_NORMAL |
2156 (!(expandaddr_to_eaf() & EAF_NAME) ? EACM_NONAME : EACM_NONE)),
2157 &_sendout_error)) == NULL)
2158 goto jleave;
2159 /* For the _sendout_error<0 case we want to wait until we can write DEAD! */
2160 if (_sendout_error < 0)
2161 n_err(_("Some addressees were classified as \"hard error\"\n"));
2163 if ((nfo = Ftmp(&tempMail, "resend", OF_WRONLY | OF_HOLDSIGS | OF_REGISTER))
2164 == NULL) {
2165 _sendout_error = TRU1;
2166 n_perr(_("temporary mail file"), 0);
2167 goto jleave;
2169 if ((nfi = Fopen(tempMail, "r")) == NULL)
2170 n_perr(tempMail, 0);
2171 Ftmp_release(&tempMail);
2172 if (nfi == NULL)
2173 goto jerr_o;
2175 if ((ibuf = setinput(&mb, mp, NEED_BODY)) == NULL)
2176 goto jerr_io;
2178 memset(&sb, 0, sizeof sb);
2179 sb.sb_to = to;
2180 sb.sb_input = nfi;
2181 if (count_nonlocal(to) > 0 && !_sendbundle_setup_creds(&sb, FAL0))
2182 /* ..wait until we can write DEAD */
2183 _sendout_error = -1;
2185 if (infix_resend(ibuf, nfo, mp, to, add_resent) != 0) {
2186 jfail_dead:
2187 savedeadletter(nfi, TRU1);
2188 n_err(_("... message not sent\n"));
2189 jerr_io:
2190 Fclose(nfi);
2191 jerr_o:
2192 Fclose(nfo);
2193 _sendout_error = TRU1;
2194 goto jleave;
2197 if (_sendout_error < 0)
2198 goto jfail_dead;
2200 Fclose(nfo);
2201 rewind(nfi);
2203 to = _outof(to, nfi, &_sendout_error);
2205 if (_sendout_error)
2206 savedeadletter(nfi, FAL0);
2208 if (count(to = elide(to)) != 0) {
2209 if (!ok_blook(record_resent) || mightrecord(nfi, NULL, TRU1)) {
2210 sb.sb_to = to;
2211 /*sb.sb_input = nfi;*/
2212 if (_transfer(&sb))
2213 rv = OKAY;
2215 } else if (!_sendout_error)
2216 rv = OKAY;
2218 Fclose(nfi);
2219 jleave:
2220 if (_sendout_error)
2221 exit_status |= EXIT_SEND_ERROR;
2222 NYD_LEAVE;
2223 return rv;
2226 FL void
2227 savedeadletter(FILE *fp, bool_t fflush_rewind_first){
2228 struct n_string line;
2229 int c;
2230 enum {a_NONE, a_INIT = 1<<0, a_BODY = 1<<1, a_NL = 1<<2} flags;
2231 ul_i bytes, lines;
2232 FILE *dbuf;
2233 char const *cp, *cpq;
2234 NYD_ENTER;
2236 if(!ok_blook(save))
2237 goto jleave;
2239 if(fflush_rewind_first){
2240 fflush(fp);
2241 rewind(fp);
2243 if(fsize(fp) == 0)
2244 goto jleave;
2246 cp = n_getdeadletter();
2247 cpq = n_shexp_quote_cp(cp, FAL0);
2249 if(options & OPT_DEBUG){
2250 n_err(_(">>> Would (try to) write $DEAD %s\n"), cpq);
2251 goto jleave;
2254 if((dbuf = Fopen(cp, "w")) == NULL){
2255 n_perr(_("Cannot save to $DEAD"), 0);
2256 goto jleave;
2258 n_file_lock(fileno(dbuf), FLT_WRITE, 0,0, UIZ_MAX); /* XXX Natomic */
2260 printf("%s ", cpq);
2261 fflush(stdout);
2263 /* TODO savedeadletter() non-conforming: should check whether we have any
2264 * TODO headers, if not we need to place "something", anything will do.
2265 * TODO MIME is completely missing, we use MBOXO quoting!! Yuck.
2266 * TODO I/O error handling missing. Yuck! */
2267 n_string_reserve(n_string_creat_auto(&line), 2 * SEND_LINESIZE);
2268 bytes = (ul_i)fprintf(dbuf, "From %s %s", myname, time_current.tc_ctime);
2269 lines = 1;
2270 for(flags = a_NONE, c = '\0'; c != EOF; bytes += line.s_len, ++lines){
2271 n_string_trunc(&line, 0);
2272 while((c = getc(fp)) != EOF && c != '\n')
2273 n_string_push_c(&line, c);
2275 /* TODO It may be that we have only some plain text. It may be that we
2276 * TODO have a complete MIME encoded message. We don't know, and we
2277 * TODO have no usable mechanism to dig it!! tWe need v15! */
2278 if(!(flags & a_INIT)){
2279 size_t i;
2281 /* Throw away leading empty lines! */
2282 if(line.s_len == 0)
2283 continue;
2284 for(i = 0; i < line.s_len; ++i){
2285 if(fieldnamechar(line.s_dat[i]))
2286 continue;
2287 if(line.s_dat[i] == ':'){
2288 flags |= a_INIT;
2289 break;
2290 }else{
2291 /* We have no headers, this is already a body line! */
2292 flags |= a_INIT | a_BODY;
2293 break;
2296 /* Well, i had to check whether the RFC allows this. Assume we've
2297 * passed the headers, too, then! */
2298 if(i == line.s_len)
2299 flags |= a_INIT | a_BODY;
2301 if(flags & a_BODY){
2302 if(line.s_len >= 5 && !memcmp(line.s_dat, "From ", 5))
2303 n_string_unshift_c(&line, '>');
2305 if(line.s_len == 0)
2306 flags |= a_BODY | a_NL;
2307 else
2308 flags &= ~a_NL;
2310 n_string_push_c(&line, '\n');
2311 fwrite(line.s_dat, sizeof *line.s_dat, line.s_len, dbuf);
2313 if(!(flags & a_NL)){
2314 putc('\n', dbuf);
2315 ++bytes;
2316 ++lines;
2318 n_string_gut(&line);
2320 Fclose(dbuf);
2321 printf("%lu/%lu\n", lines, bytes);
2322 fflush(stdout);
2324 rewind(fp);
2325 jleave:
2326 NYD_LEAVE;
2329 #undef SEND_LINESIZE
2331 /* s-it-mode */