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