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