Home | History | Annotate | Line # | Download | only in mail
mime_attach.c revision 1.12
      1 /*	$NetBSD: mime_attach.c,v 1.12 2009/04/10 13:08:25 christos Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2006 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Anon Ymous.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  * POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 
     32 #ifdef MIME_SUPPORT
     33 
     34 #include <sys/cdefs.h>
     35 #ifndef __lint__
     36 __RCSID("$NetBSD: mime_attach.c,v 1.12 2009/04/10 13:08:25 christos Exp $");
     37 #endif /* not __lint__ */
     38 
     39 #include <assert.h>
     40 #include <err.h>
     41 #include <fcntl.h>
     42 #include <libgen.h>
     43 #include <magic.h>
     44 #include <signal.h>
     45 #include <stdio.h>
     46 #include <stdlib.h>
     47 #include <string.h>
     48 #include <unistd.h>
     49 #include <util.h>
     50 
     51 #include "def.h"
     52 #include "extern.h"
     53 #ifdef USE_EDITLINE
     54 #include "complete.h"
     55 #endif
     56 #ifdef MIME_SUPPORT
     57 #include "mime.h"
     58 #include "mime_codecs.h"
     59 #include "mime_child.h"
     60 #endif
     61 #include "glob.h"
     62 #include "sig.h"
     63 
     64 #if 0
     65 /*
     66  * XXX - This block is for debugging only and eventually should go away.
     67  */
     68 # define SHOW_ALIST(a,b) show_alist(a,b)
     69 static void
     70 show_alist(struct attachment *alist, struct attachment *ap)
     71 {
     72 	(void)printf("alist=%p ap=%p\n", alist, ap);
     73 	for (ap = alist; ap; ap = ap->a_flink) {
     74 		(void)printf("ap=%p ap->a_flink=%p ap->a_blink=%p ap->a_name=%s\n",
     75 		    ap, ap->a_flink, ap->a_blink, ap->a_name ? ap->a_name : "<null>");
     76 	}
     77 }
     78 #else
     79 # define SHOW_ALIST(a,b)
     80 #endif
     81 
     82 #if 0
     83 #ifndef __lint__ /* Don't lint: the public routines may not be used. */
     84 /*
     85  * XXX - This block for is debugging only and eventually should go away.
     86  */
     87 static void
     88 show_name(const char *prefix, struct name *np)
     89 {
     90 	int i;
     91 
     92 	i = 0;
     93 	for (/*EMPTY*/; np; np = np->n_flink) {
     94 		(void)printf("%s[%d]: %s\n", prefix, i, np->n_name);
     95 		i++;
     96 	}
     97 }
     98 
     99 static void fput_mime_content(FILE *fp, struct Content *Cp);
    100 
    101 PUBLIC void
    102 show_attach(const char *prefix, struct attachment *ap)
    103 {
    104 	int i;
    105 	i = 1;
    106 	for (/*EMPTY*/; ap; ap = ap->a_flink) {
    107 		(void)printf("%s[%d]:\n", prefix, i);
    108 		fput_mime_content(stdout, &ap->a_Content);
    109 		i++;
    110 	}
    111 }
    112 
    113 PUBLIC void
    114 show_header(struct header *hp)
    115 {
    116 	show_name("TO", hp->h_to);
    117 	(void)printf("SUBJECT: %s\n", hp->h_subject);
    118 	show_name("CC", hp->h_cc);
    119 	show_name("BCC", hp->h_bcc);
    120 	show_name("SMOPTS", hp->h_smopts);
    121 	show_attach("ATTACH", hp->h_attach);
    122 }
    123 #endif	/* __lint__ */
    124 #endif
    125 
    126 /***************************
    127  * boundary string routines
    128  */
    129 static char *
    130 getrandstring(size_t length)
    131 {
    132 	void *vbin;
    133 	uint32_t *bin;
    134 	size_t binlen;
    135 	size_t i;
    136 	char *b64;
    137 
    138 	/* XXX - check this stuff again!!! */
    139 
    140 	binlen = 3 * roundup(length, 4) / 4;	/* bytes of binary to encode base64 */
    141 	bin = vbin = salloc(roundup(binlen, 4));
    142 	for (i = 0; i < roundup(binlen, 4) / 4; i++)
    143 		bin[i] = arc4random();
    144 
    145 	b64 = salloc(roundup(length, 4));
    146 	mime_bintob64(b64, vbin, binlen);
    147 	b64[length] = '\0';
    148 
    149 	return b64;
    150 }
    151 
    152 /*
    153  * Generate a boundary for MIME multipart messages.
    154  */
    155 static char *
    156 make_boundary(void)
    157 {
    158 #define BOUND_LEN 70	/* maximum length is 70 characters: RFC2046 sec 5.1.1 */
    159 
    160 	char *bound;
    161 	time_t	now;
    162 
    163 	(void)time(&now);
    164 	bound = salloc(BOUND_LEN);
    165 	(void)snprintf(bound, BOUND_LEN, "=_%08lx.%s",
    166 	    (long)now, getrandstring(BOUND_LEN - 12));
    167 	return bound;
    168 
    169 #undef BOUND_LEN
    170 }
    171 
    172 /***************************
    173  * Transfer coding routines
    174  */
    175 /*
    176  * We determine the recommended transfer encoding type for a file as
    177  * follows:
    178  *
    179  * 1) If there is a NULL byte or a stray CR (not in a CRLF
    180  *    combination) in the file, play it safe and use base64.
    181  *
    182  * 2) If any high bit is set, use quoted-printable if the content type
    183  *    is "text" and base64 otherwise.
    184  *
    185  * 3) Otherwise:
    186  *    a) use quoted-printable if there are any long lines, control
    187  *       chars (including CR), end-of-line blank space, or a missing
    188  *       terminating NL.
    189  *    b) use 7bit in all remaining case, including an empty file.
    190  *
    191  * NOTE: This means that CRLF text (MSDOS) files will be encoded
    192  * quoted-printable.
    193  */
    194 /*
    195  * RFC 821 imposes the following line length limit:
    196  *  The maximum total length of a text line including the
    197  *  <CRLF> is 1000 characters (but not counting the leading
    198  *  dot duplicated for transparency).
    199  */
    200 #define MIME_UNENCODED_LINE_MAX	(1000 - 2)
    201 static size_t
    202 line_limit(void)
    203 {
    204 	int limit;
    205 	const char *cp;
    206 	limit = -1;
    207 
    208 	if ((cp = value(ENAME_MIME_UNENC_LINE_MAX)) != NULL)
    209 		limit = atoi(cp);
    210 
    211 	if (limit < 0 || limit > MIME_UNENCODED_LINE_MAX)
    212 		limit = MIME_UNENCODED_LINE_MAX;
    213 
    214 	return (size_t)limit;
    215 }
    216 
    217 static inline int
    218 is_text(const char *ctype)
    219 {
    220 	return ctype &&
    221 	    strncasecmp(ctype, "text/", sizeof("text/") - 1) == 0;
    222 }
    223 
    224 static const char *
    225 content_encoding_core(void *fh, const char *ctype)
    226 {
    227 	int c, lastc;
    228 	int ctrlchar, endwhite;
    229 	size_t curlen, maxlen;
    230 
    231 	curlen = 0;
    232 	maxlen = 0;
    233 	ctrlchar = 0;
    234 	endwhite = 0;
    235 	lastc = EOF;
    236 	while ((c = fgetc(fh)) != EOF) {
    237 		curlen++;
    238 
    239 		if (c == '\0' || (lastc == '\r' && c != '\n'))
    240 			return MIME_TRANSFER_BASE64;
    241 
    242 		if (c > 0x7f) {
    243 			if (is_text(ctype))
    244 				return MIME_TRANSFER_QUOTED;
    245 			else
    246 				return MIME_TRANSFER_BASE64;
    247 		}
    248 		if (c == '\n') {
    249 			if (is_WSP(lastc))
    250 				endwhite = 1;
    251 			if (curlen > maxlen)
    252 				maxlen = curlen;
    253 			curlen = 0;
    254 		}
    255 		else if ((c < 0x20 && c != '\t') || c == 0x7f)
    256 			ctrlchar = 1;
    257 
    258 		lastc = c;
    259 	}
    260 	if (lastc == EOF) /* no characters read */
    261 		return MIME_TRANSFER_7BIT;
    262 
    263 	if (lastc != '\n' || ctrlchar || endwhite || maxlen > line_limit())
    264 		return MIME_TRANSFER_QUOTED;
    265 
    266 	return MIME_TRANSFER_7BIT;
    267 }
    268 
    269 static const char *
    270 content_encoding_by_name(const char *filename, const char *ctype)
    271 {
    272 	FILE *fp;
    273 	const char *enc;
    274 	fp = Fopen(filename, "r");
    275 	if (fp == NULL) {
    276 		warn("content_encoding_by_name: %s", filename);
    277 		return MIME_TRANSFER_BASE64;	/* safe */
    278 	}
    279 	enc = content_encoding_core(fp, ctype);
    280 	(void)Fclose(fp);
    281 	return enc;
    282 }
    283 
    284 static const char *
    285 content_encoding_by_fileno(int fd, const char *ctype)
    286 {
    287 	FILE *fp;
    288 	int fd2;
    289 	const char *encoding;
    290 	off_t cur_pos;
    291 
    292 	cur_pos = lseek(fd, (off_t)0, SEEK_CUR);
    293 	if ((fd2 = dup(fd)) == -1 ||
    294 	    (fp = Fdopen(fd2, "r")) == NULL) {
    295 		warn("content_encoding_by_fileno");
    296 		if (fd2 != -1)
    297 			(void)close(fd2);
    298 		return MIME_TRANSFER_BASE64;
    299 	}
    300 	encoding = content_encoding_core(fp, ctype);
    301 	(void)Fclose(fp);
    302 	(void)lseek(fd, cur_pos, SEEK_SET);
    303 	return encoding;
    304 }
    305 
    306 static const char *
    307 content_encoding(struct attachment *ap, const char *ctype)
    308 {
    309 	switch (ap->a_type) {
    310 	case ATTACH_FNAME:
    311 		return content_encoding_by_name(ap->a_name, ctype);
    312 	case ATTACH_MSG:
    313 		return "7bit";
    314 	case ATTACH_FILENO:
    315 		return content_encoding_by_fileno(ap->a_fileno, ctype);
    316 	case ATTACH_INVALID:
    317 	default:
    318 		/* This is a coding error! */
    319 		assert(/* CONSTCOND */ 0);
    320 		errx(EXIT_FAILURE, "invalid attachment type: %d", ap->a_type);
    321 		/* NOTREACHED */
    322 	}
    323 }
    324 
    325 /************************
    326  * Content type routines
    327  */
    328 /*
    329  * We use libmagic(3) to get the content type, except in the case of a
    330  * 0 or 1 byte file where libmagic gives rather useless results.
    331  */
    332 static const char *
    333 content_type_by_name(char *filename)
    334 {
    335 	const char *cp;
    336 	char *cp2;
    337 	magic_t magic;
    338 	struct stat sb;
    339 
    340 	/*
    341 	 * libmagic produces annoying results on very short files.
    342 	 * The common case is with mime-encode-message defined and an
    343 	 * empty message body.
    344 	 *
    345 	 * Note: a 1-byte message body always consists of a newline,
    346 	 * so size determines all there.  However, 1-byte attachments
    347 	 * (filename != NULL) could be anything, so check those.
    348 	 */
    349 	if ((filename != NULL && stat(filename, &sb) == 0) ||
    350 	    (filename == NULL && fstat(0, &sb) == 0)) {
    351 		if (sb.st_size < 2 && S_ISREG(sb.st_mode)) {
    352 			FILE *fp;
    353 			int ch;
    354 			if (sb.st_size == 0 || filename == NULL ||
    355 			    (fp = Fopen(filename, "r")) == NULL)
    356 				return "text/plain";
    357 
    358 			ch = fgetc(fp);
    359 			(void)Fclose(fp);
    360 
    361 			return isprint(ch) || isspace(ch) ?
    362 			    "text/plain" : "application/octet-stream";
    363 		}
    364 	}
    365 	magic = magic_open(MAGIC_MIME);
    366 	if (magic == NULL) {
    367 		warnx("magic_open: %s", magic_error(magic));
    368 		return NULL;
    369 	}
    370 	if (magic_load(magic, NULL) != 0) {
    371 		warnx("magic_load: %s", magic_error(magic));
    372 		return NULL;
    373 	}
    374 	cp = magic_file(magic, filename);
    375 	if (cp == NULL) {
    376 		warnx("magic_load: %s", magic_error(magic));
    377 		return NULL;
    378 	}
    379 	if (filename &&
    380 	    sasprintf(&cp2, "%s; name=\"%s\"", cp, basename(filename)) != -1)
    381 		cp = cp2;
    382 	else
    383 		cp = savestr(cp);
    384 	magic_close(magic);
    385 	return cp;
    386 }
    387 
    388 static const char *
    389 content_type_by_fileno(int fd)
    390 {
    391 	const char *cp;
    392 	off_t cur_pos;
    393 	int ofd;
    394 
    395 	cur_pos = lseek(fd, (off_t)0, SEEK_CUR);
    396 
    397 	ofd = dup(0);		/* save stdin */
    398 	if (dup2(fd, 0) == -1)	/* become stdin */
    399 		warn("dup2");
    400 
    401 	cp = content_type_by_name(NULL);
    402 
    403 	if (dup2(ofd, 0) == -1)	/* restore stdin */
    404 		warn("dup2");
    405 	(void)close(ofd);	/* close the copy */
    406 
    407 	(void)lseek(fd, cur_pos, SEEK_SET);
    408 	return cp;
    409 }
    410 
    411 static const char *
    412 content_type(struct attachment *ap)
    413 {
    414 	switch (ap->a_type) {
    415 	case ATTACH_FNAME:
    416 		return content_type_by_name(ap->a_name);
    417 	case ATTACH_MSG:
    418 		/*
    419 		 * Note: the encapusulated message header must include
    420 		 * at least one of the "Date:", "From:", or "Subject:"
    421 		 * fields.  See rfc2046 Sec 5.2.1.
    422 		 * XXX - Should we really test for this?
    423 		 */
    424 		return "message/rfc822";
    425 	case ATTACH_FILENO:
    426 		return content_type_by_fileno(ap->a_fileno);
    427 	case ATTACH_INVALID:
    428 	default:
    429 		/* This is a coding error! */
    430 		assert(/* CONSTCOND */ 0);
    431 		errx(EXIT_FAILURE, "invalid attachment type: %d", ap->a_type);
    432 		/* NOTREACHED */
    433 	}
    434 }
    435 
    436 /*************************
    437  * Other content routines
    438  */
    439 
    440 static const char *
    441 content_disposition(struct attachment *ap)
    442 {
    443 	switch (ap->a_type) {
    444 	case ATTACH_FNAME: {
    445 		char *disp;
    446 		(void)sasprintf(&disp, "attachment; filename=\"%s\"",
    447 		    basename(ap->a_name));
    448 		return disp;
    449 	}
    450 	case ATTACH_MSG:
    451 		return NULL;
    452 	case ATTACH_FILENO:
    453 		return "inline";
    454 
    455 	case ATTACH_INVALID:
    456 	default:
    457 		/* This is a coding error! */
    458 		assert(/* CONSTCOND */ 0);
    459 		errx(EXIT_FAILURE, "invalid attachment type: %d", ap->a_type);
    460 		/* NOTREACHED */
    461 	}
    462 }
    463 
    464 /*ARGSUSED*/
    465 static const char *
    466 content_id(struct attachment *ap __unused)
    467 {
    468 	/* XXX - to be written. */
    469 
    470 	return NULL;
    471 }
    472 
    473 static const char *
    474 content_description(struct attachment *attach, int attach_num)
    475 {
    476 	if (attach_num) {
    477 		char *description;
    478 		(void)sasprintf(&description, "attachment %d", attach_num);
    479 		return description;
    480 	}
    481 	else
    482 		return attach->a_Content.C_description;
    483 }
    484 
    485 /*******************************************
    486  * Routines to get the MIME content strings.
    487  */
    488 PUBLIC struct Content
    489 get_mime_content(struct attachment *ap, int i)
    490 {
    491 	struct Content Cp;
    492 
    493 	Cp.C_type	 = content_type(ap);
    494 	Cp.C_encoding	 = content_encoding(ap, Cp.C_type);
    495 	Cp.C_disposition = content_disposition(ap);
    496 	Cp.C_id		 = content_id(ap);
    497 	Cp.C_description = content_description(ap, i);
    498 
    499 	return Cp;
    500 }
    501 
    502 /******************
    503  * Output routines
    504  */
    505 static void
    506 fput_mime_content(FILE *fp, struct Content *Cp)
    507 {
    508 	(void)fprintf(fp, MIME_HDR_TYPE ": %s\n", Cp->C_type);
    509 	(void)fprintf(fp, MIME_HDR_ENCODING ": %s\n", Cp->C_encoding);
    510 	if (Cp->C_disposition)
    511 		(void)fprintf(fp, MIME_HDR_DISPOSITION ": %s\n",
    512 		    Cp->C_disposition);
    513 	if (Cp->C_id)
    514 		(void)fprintf(fp, MIME_HDR_ID ": %s\n", Cp->C_id);
    515 	if (Cp->C_description)
    516 		(void)fprintf(fp, MIME_HDR_DESCRIPTION ": %s\n",
    517 		    Cp->C_description);
    518 }
    519 
    520 static void
    521 fput_body(FILE *fi, FILE *fo, struct Content *Cp)
    522 {
    523 	mime_codec_t enc;
    524 
    525 	enc = mime_fio_encoder(Cp->C_encoding);
    526 	if (enc == NULL)
    527 		warnx("unknown transfer encoding type: %s\n", Cp->C_encoding);
    528 	else
    529 		enc(fi, fo, 0);
    530 }
    531 
    532 static void
    533 fput_attachment(FILE *fo, struct attachment *ap)
    534 {
    535 	FILE *fi;
    536 	struct Content *Cp = &ap->a_Content;
    537 
    538 	fput_mime_content(fo, &ap->a_Content);
    539 	(void)putc('\n', fo);
    540 
    541 	switch (ap->a_type) {
    542 	case ATTACH_FNAME:
    543 		fi = Fopen(ap->a_name, "r");
    544 		if (fi == NULL)
    545 			err(EXIT_FAILURE, "Fopen: %s", ap->a_name);
    546 		break;
    547 
    548 	case ATTACH_FILENO:
    549 		/*
    550 		 * XXX - we should really dup(2) here, however we are
    551 		 * finished with the attachment, so the Fclose() below
    552 		 * is OK for now.  This will be changed in the future.
    553 		 */
    554 		fi = Fdopen(ap->a_fileno, "r");
    555 		if (fi == NULL)
    556 			err(EXIT_FAILURE, "Fdopen: %d", ap->a_fileno);
    557 		break;
    558 
    559 	case ATTACH_MSG: {
    560 		char mailtempname[PATHSIZE];
    561 		int fd;
    562 
    563 		fi = NULL;	/* appease gcc */
    564 		(void)snprintf(mailtempname, sizeof(mailtempname),
    565 		    "%s/mail.RsXXXXXXXXXX", tmpdir);
    566 		if ((fd = mkstemp(mailtempname)) == -1 ||
    567 		    (fi = Fdopen(fd, "w+")) == NULL) {
    568 			if (fd != -1)
    569 				(void)close(fd);
    570 			err(EXIT_FAILURE, "%s", mailtempname);
    571 		}
    572 		(void)rm(mailtempname);
    573 
    574 		/*
    575 		 * This is only used for forwarding, so use the forwardtab[].
    576 		 *
    577 		 * XXX - sendmessage really needs a 'flags' argument
    578 		 * so we don't have to play games.
    579 		 */
    580 		ap->a_msg->m_size--;	/* XXX - remove trailing newline */
    581 		(void)fputc('>', fi);	/* XXX - hide the headerline */
    582 		if (sendmessage(ap->a_msg, fi, forwardtab, NULL, NULL))
    583 			(void)fprintf(stderr, ". . . forward failed, sorry.\n");
    584 		ap->a_msg->m_size++;
    585 
    586 		rewind(fi);
    587 		break;
    588 	}
    589 	case ATTACH_INVALID:
    590 	default:
    591 		/* This is a coding error! */
    592 		assert(/* CONSTCOND */ 0);
    593 		errx(EXIT_FAILURE, "invalid attachment type: %d", ap->a_type);
    594 	}
    595 
    596 	fput_body(fi, fo, Cp);
    597 	(void)Fclose(fi);
    598 }
    599 
    600 /***********************************
    601  * Higher level attachment routines.
    602  */
    603 
    604 static int
    605 mktemp_file(FILE **nfo, FILE **nfi, const char *hint)
    606 {
    607 	char tempname[PATHSIZE];
    608 	int fd, fd2;
    609 	(void)snprintf(tempname, sizeof(tempname), "%s/%sXXXXXXXXXX",
    610 	    tmpdir, hint);
    611 	if ((fd = mkstemp(tempname)) == -1 ||
    612 	    (*nfo = Fdopen(fd, "w")) == NULL) {
    613 		if (fd != -1)
    614 			(void)close(fd);
    615 		warn("%s", tempname);
    616 		return -1;
    617 	}
    618 	(void)rm(tempname);
    619 	if ((fd2 = dup(fd)) == -1 ||
    620 	    (*nfi = Fdopen(fd2, "r")) == NULL) {
    621 		warn("%s", tempname);
    622 		(void)Fclose(*nfo);
    623 		return -1;
    624 	}
    625 	return 0;
    626 }
    627 
    628 /*
    629  * Repackage the mail as a multipart MIME message.  This should always
    630  * be called whenever there are attachments, but might be called even
    631  * if there are none if we want to wrap the message in a MIME package.
    632  */
    633 PUBLIC FILE *
    634 mime_encode(FILE *fi, struct header *header)
    635 {
    636 	struct attachment map;	/* fake structure for the message body */
    637 	struct attachment *attach;
    638 	struct attachment *ap;
    639 	FILE *nfi, *nfo;
    640 
    641 	attach = header->h_attach;
    642 
    643 	/*
    644 	 * Make new phantom temporary file with read and write file
    645 	 * handles: nfi and nfo, resp.
    646 	 */
    647 	if (mktemp_file(&nfo, &nfi, "mail.Rs") != 0)
    648 		return fi;
    649 
    650 	(void)memset(&map, 0, sizeof(map));
    651 	map.a_type = ATTACH_FILENO;
    652 	map.a_fileno = fileno(fi);
    653 
    654  	map.a_Content = get_mime_content(&map, 0);
    655 
    656 	if (attach) {
    657 		/* Multi-part message:
    658 		 * Make an attachment structure for the body message
    659 		 * and make that the first element in the attach list.
    660 		 */
    661 		if (fsize(fi)) {
    662 			map.a_flink = attach;
    663 			attach->a_blink = &map;
    664 			attach = &map;
    665 		}
    666 
    667 		/* Construct our MIME boundary string - used by mime_putheader() */
    668 		header->h_mime_boundary = make_boundary();
    669 
    670 		(void)fprintf(nfo, "This is a multi-part message in MIME format.\n");
    671 
    672 		for (ap = attach; ap; ap = ap->a_flink) {
    673 			(void)fprintf(nfo, "\n--%s\n", header->h_mime_boundary);
    674 			fput_attachment(nfo, ap);
    675 		}
    676 
    677 		/* the final boundary with two attached dashes */
    678 		(void)fprintf(nfo, "\n--%s--\n", header->h_mime_boundary);
    679 	}
    680 	else {
    681 		/* Single-part message (no attachments):
    682 		 * Update header->h_Content (used by mime_putheader()).
    683 		 * Output the body contents.
    684 		 */
    685 		char *encoding;
    686 
    687 		header->h_Content = map.a_Content;
    688 
    689 		/* check for an encoding override */
    690 		if ((encoding = value(ENAME_MIME_ENCODE_MSG)) && *encoding)
    691 			header->h_Content.C_encoding = encoding;
    692 
    693 		fput_body(fi, nfo, &header->h_Content);
    694 	}
    695 	(void)Fclose(fi);
    696 	(void)Fclose(nfo);
    697 	rewind(nfi);
    698 	return nfi;
    699 }
    700 
    701 static char*
    702 check_filename(char *filename, char *canon_name)
    703 {
    704 	int fd;
    705 	struct stat sb;
    706 	char *fname = filename;
    707 
    708 	/* We need to expand '~' if we got here from '~@'.  The shell
    709 	 * does this otherwise.
    710 	 */
    711 	if (fname[0] == '~' && fname[1] == '/') {
    712 		if (homedir && homedir[0] != '~')
    713 			(void)easprintf(&fname, "%s/%s",
    714 			    homedir, fname + 2);
    715 	}
    716 	if (realpath(fname, canon_name) == NULL) {
    717 		warn("realpath: %s", filename);
    718 		canon_name = NULL;
    719 		goto done;
    720 	}
    721 	fd = open(canon_name, O_RDONLY, 0);
    722 	if (fd == -1) {
    723 		warnx("open: cannot read %s", filename);
    724 		canon_name = NULL;
    725 		goto done;
    726 	}
    727 	if (fstat(fd, &sb) == -1) {
    728 		warn("stat: %s", canon_name);
    729 		canon_name = NULL;
    730 		goto do_close;
    731 	}
    732 	if (!S_ISREG(sb.st_mode)) {
    733 		warnx("stat: %s is not a file", filename);
    734 		canon_name = NULL;
    735 	     /*	goto do_close; */
    736 	}
    737  do_close:
    738 	(void)close(fd);
    739  done:
    740 	if (fname != filename)
    741 		free(fname);
    742 
    743 	return canon_name;
    744 }
    745 
    746 static struct attachment *
    747 attach_one_file(struct attachment *ap, char *filename, int attach_num)
    748 {
    749 	char canon_name[MAXPATHLEN];
    750 	struct attachment *nap;
    751 
    752 	/*
    753 	 * 1) check that filename is really a readable file; return NULL if not.
    754 	 * 2) allocate an attachment structure.
    755 	 * 3) save cananonical name for filename, so cd won't screw things later.
    756 	 * 4) add the structure to the end of the chain.
    757 	 * 5) return the new attachment structure.
    758 	 */
    759 	if (check_filename(filename, canon_name) == NULL)
    760 		return NULL;
    761 
    762 	nap = csalloc(1, sizeof(*nap));
    763 	nap->a_type = ATTACH_FNAME;
    764 	nap->a_name = savestr(canon_name);
    765 
    766 	if (ap) {
    767 		for (/*EMPTY*/; ap->a_flink != NULL; ap = ap->a_flink)
    768 			continue;
    769 		ap->a_flink = nap;
    770 		nap->a_blink = ap;
    771 	}
    772 
    773 	if (attach_num)
    774 		nap->a_Content = get_mime_content(nap, attach_num);
    775 
    776 	return nap;
    777 }
    778 
    779 static char *
    780 get_line(el_mode_t *em, const char *pr, const char *str, int i)
    781 {
    782 	char *prompt;
    783 	char *line;
    784 
    785 	/*
    786 	 * Don't use a '\t' in the format string here as completion
    787 	 * seems to handle it badly.
    788 	 */
    789 	(void)easprintf(&prompt, "#%-7d %s: ", i, pr);
    790 	line = my_gets(em, prompt, __UNCONST(str));
    791 	if (line != NULL) {
    792 		(void)strip_WSP(line);	/* strip trailing whitespace */
    793 		line = skip_WSP(line);	/* skip leading white space */
    794 		line = savestr(line);	/* XXX - do we need this? */
    795 	}
    796 	else {
    797 		line = __UNCONST("");
    798 	}
    799 	free(prompt);
    800 
    801 	return line;
    802 }
    803 
    804 static void
    805 sget_line(el_mode_t *em, const char *pr, const char **str, int i)
    806 {
    807 	char *line;
    808 	line = get_line(em, pr, *str, i);
    809 	if (line != NULL && strcmp(line, *str) != 0)
    810 		*str = line;
    811 }
    812 
    813 static void
    814 sget_encoding(const char **str, const char *filename, const char *ctype, int num)
    815 {
    816 	const char *ename;
    817 	const char *defename;
    818 
    819 	defename = NULL;
    820 	ename = *str;
    821 	for (;;) {
    822 		ename = get_line(&elm.mime_enc, "encoding", ename, num);
    823 
    824 		if (*ename == '\0') {
    825 			if (defename == NULL)
    826 				defename = content_encoding_by_name(filename, ctype);
    827 			ename = defename;
    828 		}
    829 		else if (mime_fio_encoder(ename) == NULL) {
    830 			const void *cookie;
    831 			(void)printf("Sorry: valid encoding modes are: ");
    832 			cookie = NULL;
    833 			ename = mime_next_encoding_name(&cookie);
    834 			for (;;) {
    835 				(void)printf("%s", ename);
    836 				ename = mime_next_encoding_name(&cookie);
    837 				if (ename == NULL)
    838 					break;
    839 				(void)fputc(',', stdout);
    840 			}
    841 			(void)putchar('\n');
    842 			ename = *str;
    843 		}
    844 		else {
    845 			if (strcmp(ename, *str) != 0)
    846 				*str = savestr(ename);
    847 			break;
    848 		}
    849 	}
    850 }
    851 
    852 /*
    853  * Edit an attachment list.
    854  * Return the new attachment list.
    855  */
    856 static struct attachment *
    857 edit_attachlist(struct attachment *alist)
    858 {
    859 	struct attachment *ap;
    860 	char *line;
    861 	int attach_num;
    862 
    863 	(void)printf("Attachments:\n");
    864 
    865 	attach_num = 1;
    866 	ap = alist;
    867 	while (ap) {
    868 		SHOW_ALIST(alist, ap);
    869 
    870 		switch(ap->a_type) {
    871 		case ATTACH_MSG:
    872 			(void)printf("#%-7d message:  <not changeable>\n",
    873 			    attach_num);
    874 			break;
    875 		case ATTACH_FNAME:
    876 		case ATTACH_FILENO:
    877 			line = get_line(&elm.filec, "filename", ap->a_name, attach_num);
    878 			if (*line == '\0') {	/* omit this attachment */
    879 				if (ap->a_blink) {
    880 					struct attachment *next_ap;
    881 					next_ap = ap->a_flink;
    882 					ap = ap->a_blink;
    883 					ap->a_flink = next_ap;
    884 					if (next_ap)
    885 						next_ap->a_blink = ap;
    886 					else
    887 						goto done;
    888 				}
    889 				else {
    890 					alist = ap->a_flink;
    891 					if (alist)
    892 						alist->a_blink = NULL;
    893 				}
    894 			}
    895 			else {
    896 				char canon_name[MAXPATHLEN];
    897 				if (strcmp(line, ap->a_name) != 0) { /* new filename */
    898 					if (check_filename(line, canon_name) == NULL)
    899 						continue;
    900 					ap->a_name = savestr(canon_name);
    901 					ap->a_Content = get_mime_content(ap, 0);
    902 				}
    903 				sget_line(&elm.string, "description",
    904 				    &ap->a_Content.C_description, attach_num);
    905 				sget_encoding(&ap->a_Content.C_encoding, ap->a_name,
    906 				    ap->a_Content.C_type, attach_num);
    907 			}
    908 			break;
    909 		case ATTACH_INVALID:
    910 		default:
    911 			/* This is a coding error! */
    912 			assert(/* CONSTCOND */ 0);
    913 			errx(EXIT_FAILURE, "invalid attachment type: %d",
    914 			    ap->a_type);
    915 		}
    916 
    917 		attach_num++;
    918 		if (alist == NULL || ap->a_flink == NULL)
    919 			break;
    920 
    921 		ap = ap->a_flink;
    922 	}
    923 
    924 	ap = alist;
    925 	for (;;) {
    926 		struct attachment *nap;
    927 
    928 		SHOW_ALIST(alist, ap);
    929 
    930 		line = get_line(&elm.filec, "filename", "", attach_num);
    931 		if (*line == '\0')
    932 			break;
    933 
    934 		nap = attach_one_file(ap, line, attach_num);
    935 		if (nap == NULL)
    936 			continue;
    937 
    938 		if (alist == NULL)
    939 			alist = nap;
    940 		ap = nap;
    941 
    942 		sget_line(&elm.string, "description",
    943 		    &ap->a_Content.C_description, attach_num);
    944 		sget_encoding(&ap->a_Content.C_encoding, ap->a_name,
    945 		    ap->a_Content.C_type, attach_num);
    946 		attach_num++;
    947 	}
    948  done:
    949 	SHOW_ALIST(alist, ap);
    950 
    951 	return alist;
    952 }
    953 
    954 /*
    955  * Hook used by the '~@' escape to attach files.
    956  */
    957 PUBLIC struct attachment*
    958 mime_attach_files(struct attachment * volatile attach, char *linebuf)
    959 {
    960 	struct attachment *ap;
    961 	char *argv[MAXARGC];
    962 	int argc;
    963 	int attach_num;
    964 
    965 	argc = getrawlist(linebuf, argv, (int)__arraycount(argv));
    966 	attach_num = 1;
    967 	for (ap = attach; ap && ap->a_flink; ap = ap->a_flink)
    968 			attach_num++;
    969 
    970 	if (argc) {
    971 		int i;
    972 		for (i = 0; i < argc; i++) {
    973 			struct attachment *ap2;
    974 			ap2 = attach_one_file(ap, argv[i], attach_num);
    975 			if (ap2 != NULL) {
    976 				ap = ap2;
    977 				if (attach == NULL)
    978 					attach = ap;
    979 				attach_num++;
    980 			}
    981 		}
    982 	}
    983 	else {
    984 		attach = edit_attachlist(attach);
    985 		(void)printf("--- end attachments ---\n");
    986 	}
    987 
    988 	return attach;
    989 }
    990 
    991 /*
    992  * Hook called in main() to attach files registered by the '-a' flag.
    993  */
    994 PUBLIC struct attachment *
    995 mime_attach_optargs(struct name *optargs)
    996 {
    997 	struct attachment *attach;
    998 	struct attachment *ap;
    999 	struct name *np;
   1000 	char *expand_optargs;
   1001 	int attach_num;
   1002 
   1003 	expand_optargs = value(ENAME_MIME_ATTACH_LIST);
   1004 	attach_num = 1;
   1005 	ap = NULL;
   1006 	attach = NULL;
   1007 	for (np = optargs; np; np = np->n_flink) {
   1008 		char *argv[MAXARGC];
   1009 		int argc;
   1010 		int i;
   1011 
   1012 		if (expand_optargs != NULL)
   1013 			argc = getrawlist(np->n_name,
   1014 			    argv, (int)__arraycount(argv));
   1015 		else {
   1016 			if (np->n_name == '\0')
   1017 				argc = 0;
   1018 			else {
   1019 				argc = 1;
   1020 				argv[0] = np->n_name;
   1021 			}
   1022 			argv[argc] = NULL;/* be consistent with getrawlist() */
   1023 		}
   1024 		for (i = 0; i < argc; i++) {
   1025 			struct attachment *ap2;
   1026 			char *filename;
   1027 
   1028 			if (argv[i][0] == '/')	/* an absolute path */
   1029 				(void)easprintf(&filename, "%s", argv[i]);
   1030 			else
   1031 				(void)easprintf(&filename, "%s/%s",
   1032 				    origdir, argv[i]);
   1033 
   1034 			ap2 = attach_one_file(ap, filename, attach_num);
   1035 			if (ap2 != NULL) {
   1036 				ap = ap2;
   1037 				if (attach == NULL)
   1038 					attach = ap;
   1039 				attach_num++;
   1040 			}
   1041 			free(filename);
   1042 		}
   1043 	}
   1044 	return attach;
   1045 }
   1046 
   1047 /*
   1048  * Output MIME header strings as specified in the header structure.
   1049  */
   1050 PUBLIC void
   1051 mime_putheader(FILE *fp, struct header *header)
   1052 {
   1053 	(void)fprintf(fp, MIME_HDR_VERSION ": " MIME_VERSION "\n");
   1054 	if (header->h_attach) {
   1055 		(void)fprintf(fp, MIME_HDR_TYPE ": multipart/mixed;\n");
   1056 		(void)fprintf(fp, "\tboundary=\"%s\"\n", header->h_mime_boundary);
   1057 	}
   1058 	else {
   1059 		fput_mime_content(fp, &header->h_Content);
   1060 	}
   1061 }
   1062 
   1063 #endif /* MIME_SUPPORT */
   1064