xref: /netbsd-src/usr.bin/mail/mime_attach.c (revision 404fbe5fb94ca1e054339640cabb2801ce52dd30)
1 /*	$NetBSD: mime_attach.c,v 1.10 2008/04/28 20:24:14 martin 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.10 2008/04/28 20:24:14 martin 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 <setjmp.h>
45 #include <signal.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <unistd.h>
50 #include <util.h>
51 
52 #include "def.h"
53 #include "extern.h"
54 #ifdef USE_EDITLINE
55 #include "complete.h"
56 #endif
57 #ifdef MIME_SUPPORT
58 #include "mime.h"
59 #include "mime_codecs.h"
60 #include "mime_child.h"
61 #endif
62 #include "glob.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 		warn("magic_open: %s", magic_error(magic));
368 		return NULL;
369 	}
370 	if (magic_load(magic, NULL) != 0) {
371 		warn("magic_load: %s", magic_error(magic));
372 		return NULL;
373 	}
374 	cp = magic_file(magic, filename);
375 	if (cp == NULL) {
376 		warn("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_getline(em, prompt, __UNCONST(str));
791 	/* LINTED */
792 	line = line ? savestr(line) : __UNCONST("");
793 	free(prompt);
794 
795 	return line;
796 }
797 
798 static void
799 sget_line(el_mode_t *em, const char *pr, const char **str, int i)
800 {
801 	char *line;
802 	line = get_line(em, pr, *str, i);
803 	if (strcmp(line, *str) != 0)
804 		*str = savestr(line);
805 }
806 
807 static void
808 sget_encoding(const char **str, const char *filename, const char *ctype, int num)
809 {
810 	const char *ename;
811 	const char *defename;
812 
813 	defename = NULL;
814 	ename = *str;
815 	for (;;) {
816 		ename = get_line(&elm.mime_enc, "encoding", ename, num);
817 
818 		if (*ename == '\0') {
819 			if (defename == NULL)
820 				defename = content_encoding_by_name(filename, ctype);
821 			ename = defename;
822 		}
823 		else if (mime_fio_encoder(ename) == NULL) {
824 			const void *cookie;
825 			(void)printf("Sorry: valid encoding modes are: ");
826 			cookie = NULL;
827 			ename = mime_next_encoding_name(&cookie);
828 			for (;;) {
829 				(void)printf("%s", ename);
830 				ename = mime_next_encoding_name(&cookie);
831 				if (ename == NULL)
832 					break;
833 				(void)fputc(',', stdout);
834 			}
835 			(void)putchar('\n');
836 			ename = *str;
837 		}
838 		else {
839 			if (strcmp(ename, *str) != 0)
840 				*str = savestr(ename);
841 			break;
842 		}
843 	}
844 }
845 
846 /*
847  * Edit an attachment list.
848  * Return the new attachment list.
849  */
850 static struct attachment *
851 edit_attachlist(struct attachment *alist)
852 {
853 	struct attachment *ap;
854 	char *line;
855 	int attach_num;
856 
857 	(void)printf("Attachments:\n");
858 
859 	attach_num = 1;
860 	ap = alist;
861 	while (ap) {
862 		SHOW_ALIST(alist, ap);
863 
864 		switch(ap->a_type) {
865 		case ATTACH_MSG:
866 			(void)printf("#%-7d message:  <not changeable>\n",
867 			    attach_num);
868 			break;
869 		case ATTACH_FNAME:
870 		case ATTACH_FILENO:
871 			line = get_line(&elm.filec, "filename", ap->a_name, attach_num);
872 			if (*line == '\0') {	/* omit this attachment */
873 				if (ap->a_blink) {
874 					struct attachment *next_ap;
875 					next_ap = ap->a_flink;
876 					ap = ap->a_blink;
877 					ap->a_flink = next_ap;
878 					if (next_ap)
879 						next_ap->a_blink = ap;
880 					else
881 						goto done;
882 				}
883 				else {
884 					alist = ap->a_flink;
885 					if (alist)
886 						alist->a_blink = NULL;
887 				}
888 			}
889 			else {
890 				char canon_name[MAXPATHLEN];
891 				if (strcmp(line, ap->a_name) != 0) { /* new filename */
892 					if (check_filename(line, canon_name) == NULL)
893 						continue;
894 					ap->a_name = savestr(canon_name);
895 					ap->a_Content = get_mime_content(ap, 0);
896 				}
897 				sget_line(&elm.string, "description",
898 				    &ap->a_Content.C_description, attach_num);
899 				sget_encoding(&ap->a_Content.C_encoding, ap->a_name,
900 				    ap->a_Content.C_type, attach_num);
901 			}
902 			break;
903 		case ATTACH_INVALID:
904 		default:
905 			/* This is a coding error! */
906 			assert(/* CONSTCOND */ 0);
907 			errx(EXIT_FAILURE, "invalid attachment type: %d",
908 			    ap->a_type);
909 		}
910 
911 		attach_num++;
912 		if (alist == NULL || ap->a_flink == NULL)
913 			break;
914 
915 		ap = ap->a_flink;
916 	}
917 
918 	ap = alist;
919 	for (;;) {
920 		struct attachment *nap;
921 
922 		SHOW_ALIST(alist, ap);
923 
924 		line = get_line(&elm.filec, "filename", "", attach_num);
925 		if (*line == '\0')
926 			break;
927 
928 		nap = attach_one_file(ap, line, attach_num);
929 		if (nap == NULL)
930 			continue;
931 
932 		if (alist == NULL)
933 			alist = nap;
934 		ap = nap;
935 
936 		sget_line(&elm.string, "description",
937 		    &ap->a_Content.C_description, attach_num);
938 		sget_encoding(&ap->a_Content.C_encoding, ap->a_name,
939 		    ap->a_Content.C_type, attach_num);
940 		attach_num++;
941 	}
942  done:
943 	SHOW_ALIST(alist, ap);
944 
945 	return alist;
946 }
947 
948 /*
949  * Hook used by the '~@' escape to attach files.
950  */
951 PUBLIC struct attachment*
952 mime_attach_files(struct attachment *attach, char *linebuf)
953 {
954 	struct attachment *ap;
955 	char *argv[MAXARGC];
956 	int argc;
957 	int attach_num;
958 
959 	argc = getrawlist(linebuf, argv, sizeofarray(argv));
960 	attach_num = 1;
961 	for (ap = attach; ap && ap->a_flink; ap = ap->a_flink)
962 			attach_num++;
963 
964 	if (argc) {
965 		int i;
966 		for (i = 0; i < argc; i++) {
967 			struct attachment *ap2;
968 			ap2 = attach_one_file(ap, argv[i], attach_num);
969 			if (ap2 != NULL) {
970 				ap = ap2;
971 				if (attach == NULL)
972 					attach = ap;
973 				attach_num++;
974 			}
975 		}
976 	}
977 	else {
978 		attach = edit_attachlist(attach);
979 		(void)printf("--- end attachments ---\n");
980 	}
981 
982 	return attach;
983 }
984 
985 /*
986  * Hook called in main() to attach files registered by the '-a' flag.
987  */
988 PUBLIC struct attachment *
989 mime_attach_optargs(struct name *optargs)
990 {
991 	struct attachment *attach;
992 	struct attachment *ap;
993 	struct name *np;
994 	char *expand_optargs;
995 	int attach_num;
996 
997 	expand_optargs = value(ENAME_MIME_ATTACH_LIST);
998 	attach_num = 1;
999 	ap = NULL;
1000 	attach = NULL;
1001 	for (np = optargs; np; np = np->n_flink) {
1002 		char *argv[MAXARGC];
1003 		int argc;
1004 		int i;
1005 
1006 		if (expand_optargs != NULL)
1007 			argc = getrawlist(np->n_name, argv, sizeofarray(argv));
1008 		else {
1009 			if (np->n_name == '\0')
1010 				argc = 0;
1011 			else {
1012 				argc = 1;
1013 				argv[0] = np->n_name;
1014 			}
1015 			argv[argc] = NULL;/* be consistent with getrawlist() */
1016 		}
1017 		for (i = 0; i < argc; i++) {
1018 			struct attachment *ap2;
1019 			char *filename;
1020 
1021 			if (argv[i][0] == '/')	/* an absolute path */
1022 				(void)easprintf(&filename, "%s", argv[i]);
1023 			else
1024 				(void)easprintf(&filename, "%s/%s",
1025 				    origdir, argv[i]);
1026 
1027 			ap2 = attach_one_file(ap, filename, attach_num);
1028 			if (ap2 != NULL) {
1029 				ap = ap2;
1030 				if (attach == NULL)
1031 					attach = ap;
1032 				attach_num++;
1033 			}
1034 			free(filename);
1035 		}
1036 	}
1037 	return attach;
1038 }
1039 
1040 /*
1041  * Output MIME header strings as specified in the header structure.
1042  */
1043 PUBLIC void
1044 mime_putheader(FILE *fp, struct header *header)
1045 {
1046 	(void)fprintf(fp, MIME_HDR_VERSION ": " MIME_VERSION "\n");
1047 	if (header->h_attach) {
1048 		(void)fprintf(fp, MIME_HDR_TYPE ": multipart/mixed;\n");
1049 		(void)fprintf(fp, "\tboundary=\"%s\"\n", header->h_mime_boundary);
1050 	}
1051 	else {
1052 		fput_mime_content(fp, &header->h_Content);
1053 	}
1054 }
1055 
1056 #endif /* MIME_SUPPORT */
1057