/*
** mhstore.c -- store the contents of MIME messages
**
** This code is Copyright (c) 2002, by the authors of nmh.  See the
** COPYRIGHT file in the root directory of the nmh distribution for
** complete copyright information.
*/

#include <h/mh.h>
#include <fcntl.h>
#include <h/signals.h>
#include <errno.h>
#include <signal.h>
#include <h/tws.h>
#include <h/mime.h>
#include <h/mhparse.h>
#include <h/utils.h>
#include <unistd.h>
#include <sys/stat.h>
#include <locale.h>
#include <sysexits.h>

static struct swit switches[] = {
#define AUTOSW  0
	{ "auto", 0 },
#define NAUTOSW  1
	{ "noauto", 2 },
#define FILESW  2  /* interface from show */
	{ "file file", 0 },
#define PARTSW  3
	{ "part number", 0 },
#define TYPESW  4
	{ "type content", 0 },
#define VERSIONSW  5
	{ "Version", 0 },
#define HELPSW  6
	{ "help", 0 },
#define DEBUGSW  7
	{ "debug", -5 },
	{ NULL, 0 }
};

char *version=VERSION;

/* mhparse.c */
extern char *tmp;  /* directory to place temp files */

/* mhmisc.c */
extern int npart;
extern int ntype;
extern char *parts[NPARTS + 1];
extern char *types[NTYPES + 1];
extern int userrs;

int debugsw = 0;

#define quitser pipeser

/* mhparse.c */
CT parse_mime(char *);

/* mhmisc.c */
int part_ok(CT, int);
int type_ok(CT, int);
void set_endian(void);
void flush_errors(void);

/* mhfree.c */
void free_content(CT);
extern CT *cts;  /* The list of top-level contents to display */
void freects_done();

/*
** static prototypes
*/
static void pipeser(int);

int autosw = 1;

/*
** Cache of current directory.  This must be
** set before these routines are called.
*/
char *cwd;

/*
** The directory in which to store the contents.
*/
static char *dir;

/*
** Type for a compare function for qsort.  This keeps
** the compiler happy.
*/
typedef int (*qsort_comp) (const void *, const void *);


/* mhmisc.c */
int part_ok(CT, int);
int type_ok(CT, int);
int make_intermediates(char *);
void flush_errors(void);

/* mhshowsbr.c */
int show_content_aux(CT, int, char *, char *);

/*
** static prototypes
*/
static void store_single_message(CT);
static int store_switch(CT);
static int store_generic(CT);
static int store_multi(CT);
static int store_partial(CT);
static int store_external(CT);
static int ct_compar(CT *, CT *);
static int store_content(CT, CT);
static int output_content_file(CT, int);
static int output_content_folder(char *, char *);
static int parse_format_string(CT, char *, char *, int, char *);
static int copy_some_headers(FILE *, CT);
static void store_all_messages(CT *);


int
main(int argc, char **argv)
{
	int msgnum;
	char *cp, *file = NULL, *folder = NULL;
	char *maildir, buf[100], **argp;
	char **arguments;
	struct msgs_array msgs = { 0, 0, NULL };
	struct msgs *mp = NULL;
	CT ct, *ctp;
	FILE *fp;

	if (atexit(freects_done) != 0) {
		adios(EX_OSERR, NULL, "atexit failed");
	}

	setlocale(LC_ALL, "");
	invo_name = mhbasename(argv[0]);

	/* read user profile/context */
	context_read();

	arguments = getarguments(invo_name, argc, argv, 1);
	argp = arguments;

	/*
	** Parse arguments
	*/
	while ((cp = *argp++)) {
		if (*cp == '-') {
			switch (smatch(++cp, switches)) {
			case AMBIGSW:
				ambigsw(cp, switches);
				exit(EX_USAGE);
			case UNKWNSW:
				adios(EX_USAGE, NULL, "-%s unknown", cp);

			case HELPSW:
				snprintf(buf, sizeof(buf), "%s [+folder] [msgs] [switches]", invo_name);
				print_help(buf, switches, 1);
				exit(argc == 2 ? EX_OK : EX_USAGE);
			case VERSIONSW:
				print_version(invo_name);
				exit(argc == 2 ? EX_OK : EX_USAGE);

			case AUTOSW:
				autosw++;
				continue;
			case NAUTOSW:
				autosw = 0;
				continue;

			case PARTSW:
				if (!(cp = *argp++) || *cp == '-')
					adios(EX_USAGE, NULL, "missing argument to %s",
							argp[-2]);
				if (npart >= NPARTS)
					adios(EX_USAGE, NULL, "too many parts (starting with %s), %d max", cp, NPARTS);
				parts[npart++] = cp;
				continue;

			case TYPESW:
				if (!(cp = *argp++) || *cp == '-')
					adios(EX_USAGE, NULL, "missing argument to %s",
							argp[-2]);
				if (ntype >= NTYPES)
					adios(EX_USAGE, NULL, "too many types (starting with %s), %d max", cp, NTYPES);
				types[ntype++] = cp;
				continue;

			case FILESW:
				if (!(cp = *argp++) || (*cp == '-' && cp[1]))
					adios(EX_USAGE, NULL, "missing argument to %s",
							argp[-2]);
				file = *cp == '-' ? cp : mh_xstrdup(expanddir(cp));
				continue;

			case DEBUGSW:
				debugsw = 1;
				continue;
			}
		}
		if (*cp == '+' || *cp == '@') {
			if (folder)
				adios(EX_USAGE, NULL, "only one folder at a time!");
			else
				folder = mh_xstrdup(expandfol(cp));
		} else
			app_msgarg(&msgs, cp);
	}

	/* null terminate the list of acceptable parts/types */
	parts[npart] = NULL;
	types[ntype] = NULL;

	set_endian();

	/*
	** Check if we've specified an additional profile
	*/
	if ((cp = getenv("MHSTORE"))) {
		if ((fp = fopen(cp, "r"))) {
			readconfig((struct node **) 0, fp, cp, 0);
			fclose(fp);
		} else {
			admonish("", "unable to read $MHSTORE profile (%s)",
					cp);
		}
	}

	/*
	** Read the standard profile setup
	*/
	if ((fp = fopen(cp = etcpath("mhn.defaults"), "r"))) {
		readconfig((struct node **) 0, fp, cp, 0);
		fclose(fp);
	}

	/*
	** Cache the current directory before we do any chdirs()'s.
	*/
	cwd = mh_xstrdup(pwd());

	/*
	** Check for storage directory.  If specified,
	** then store temporary files there.  Else we
	** store them in standard nmh directory.
	*/
	if ((cp = context_find(nmhstorage)) && *cp)
		tmp = concat(cp, "/", invo_name, NULL);
	else
		tmp = mh_xstrdup(toabsdir(invo_name));

	if (file && msgs.size)
		adios(EX_USAGE, NULL, "cannot specify msg and file at same time!");

	/*
	** check if message is coming from file
	*/
	if (file) {
		cts = mh_xcalloc(2, sizeof(*cts));
		ctp = cts;

		if ((ct = parse_mime(file)))
			*ctp++ = ct;
	} else {
		/*
		** message(s) are coming from a folder
		*/
		if (!msgs.size)
			app_msgarg(&msgs, seq_cur);
		if (!folder)
			folder = getcurfol();
		maildir = toabsdir(folder);

		if (chdir(maildir) == NOTOK)
			adios(EX_OSERR, maildir, "unable to change directory to");

		/* read folder and create message structure */
		if (!(mp = folder_read(folder)))
			adios(EX_IOERR, NULL, "unable to read folder %s", folder);

		/* check for empty folder */
		if (mp->nummsg == 0)
			adios(EX_DATAERR, NULL, "no messages in %s", folder);

		/* parse all the message ranges/sequences and set SELECTED */
		for (msgnum = 0; msgnum < msgs.size; msgnum++)
			if (!m_convert(mp, msgs.msgs[msgnum]))
				exit(EX_USAGE);
		seq_setprev(mp);  /* set the previous-sequence */

		cts = mh_xcalloc(mp->numsel + 1, sizeof(*cts));
		ctp = cts;

		for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
			if (is_selected(mp, msgnum)) {
				char *msgnam;

				msgnam = m_name(msgnum);
				if ((ct = parse_mime(msgnam)))
					*ctp++ = ct;
			}
		}
	}

	if (!*cts)
		exit(EX_SOFTWARE);

	userrs = 1;
	SIGNAL(SIGQUIT, quitser);
	SIGNAL(SIGPIPE, pipeser);

	/*
	** Get the associated umask for the relevant contents.
	*/
	for (ctp = cts; *ctp; ctp++) {
		struct stat st;

		ct = *ctp;
		if (type_ok(ct, 1) && !ct->c_umask) {
			if (stat(ct->c_file, &st) != NOTOK)
				ct->c_umask = ~(st.st_mode & 0777);
			else
				ct->c_umask = ~m_gmprot();
		}
	}

	/*
	** Store the message content
	*/
	store_all_messages(cts);

	/* Now free all the structures for the content */
	for (ctp = cts; *ctp; ctp++)
		free_content(*ctp);

	mh_free0(&cts);

	/* If reading from a folder, do some updating */
	if (mp) {
		context_replace(curfolder, folder); /* update current folder */
		seq_setcur(mp, mp->hghsel);  /* update current message */
		seq_save(mp);  /* synchronize sequences  */
		context_save();  /* save the context file  */
	}

	return 0;
}


static void
pipeser(int i)
{
	if (i == SIGQUIT) {
		unlink("core");
		fflush(stdout);
		fprintf(stderr, "\n");
		fflush(stderr);
		exit(EX_TEMPFAIL);
	}

	exit(EX_IOERR);
	/* NOTREACHED */
}


/*
** Main entry point to store content from a collection of messages.
*/
static void
store_all_messages(CT *cts)
{
	CT ct, *ctp;
	char *cp;

	/*
	** Check for the directory in which to
	** store any contents.
	*/
	if ((cp = context_find(nmhstorage)) && *cp)
		dir = mh_xstrdup(cp);
	else
		dir = mh_xstrdup(cwd);

	for (ctp = cts; *ctp; ctp++) {
		ct = *ctp;
		store_single_message(ct);
	}

	flush_errors();
}


/*
** Entry point to store the content
** in a (single) message
*/

static void
store_single_message(CT ct)
{
	if (type_ok(ct, 1)) {
		umask(ct->c_umask);
		store_switch(ct);
		if (ct->c_fp) {
			fclose(ct->c_fp);
			ct->c_fp = NULL;
		}
		if (ct->c_ceclosefnx)
			(*ct->c_ceclosefnx) (ct);
	}
}


/*
** Switching routine to store different content types
*/

static int
store_switch(CT ct)
{
	switch (ct->c_type) {
	case CT_MULTIPART:
		return store_multi(ct);
		break;

	case CT_MESSAGE:
		switch (ct->c_subtype) {
		case MESSAGE_PARTIAL:
			return store_partial(ct);
			break;

		case MESSAGE_EXTERNAL:
			return store_external(ct);

		case MESSAGE_RFC822:
		default:
			return store_generic(ct);
			break;
		}
		break;

	case CT_APPLICATION:
	case CT_TEXT:
	case CT_AUDIO:
	case CT_IMAGE:
	case CT_VIDEO:
		return store_generic(ct);
		break;

	default:
		adios(EX_DATAERR, NULL, "unknown content type %d", ct->c_type);
		break;
	}

	return OK;  /* NOT REACHED */
}


/*
** Generic routine to store a MIME content.
** (application, audio, video, image, text, message/rfc922)
*/
static int
store_generic(CT ct)
{
	char **ap, **vp, *cp, *filename;
	CI ci = &ct->c_ctinfo;

	/*
	** Check if the content specifies a filename in its MIME parameters.
	** Don't bother with this for type "message"
	** (only the "message" subtype "rfc822" will use store_generic).
	*/
	if (autosw && ct->c_type != CT_MESSAGE) {
		/* First check for "filename" in Content-Disposition header */
		filename = extract_name_value("filename", ct->c_dispo);
		if (filename && strcmp(filename, ct->c_dispo)!=0) {
			/* We found "filename" */
			cp = mhbasename(filename);
			if (*cp && *cp!='.' && *cp!='|' && *cp!='!' &&
					!strchr(cp, '%')) {
				/* filename looks good: use it */
				ct->c_storeproc = mh_xstrdup(cp);
				goto finished;
			}
		}
		/*
		** Check the attribute/value pairs, for the attribute "name".
		** If found, take the basename, do a few sanity checks and
		** copy the value into c_storeproc.
		*/
		for (ap = ci->ci_attrs, vp = ci->ci_values; *ap; ap++,vp++) {
			if (mh_strcasecmp(*ap, "name")!=0) {
				continue;
			}
			cp = mhbasename(*vp);
			if (*cp && *cp!='.' && *cp!='|' && *cp!='!' &&
					!strchr(cp, '%')) {
				/* filename looks good: use it */
				ct->c_storeproc = mh_xstrdup(cp);
			}
			break;
		}
	}

finished:
	return store_content(ct, NULL);
}


/*
** Store the content of a multipart message
*/

static int
store_multi(CT ct)
{
	int result;
	struct multipart *m = (struct multipart *) ct->c_ctparams;
	struct part *part;

	result = NOTOK;
	for (part = m->mp_parts; part; part = part->mp_next) {
		CT  p = part->mp_part;

		if (part_ok(p, 1) && type_ok(p, 1)) {
			result = store_switch(p);
			if (result == OK && ct->c_subtype == MULTI_ALTERNATE)
				break;
		}
	}

	return result;
}


/*
** Reassemble and store the contents of a collection
** of messages of type "message/partial".
*/

static int
store_partial(CT ct)
{
	int cur, hi, i;
	CT p, *ctp, *ctq;
	CT *base;
	struct partial *pm, *qm;

	qm = (struct partial *) ct->c_ctparams;
	if (qm->pm_stored)
		return OK;

	hi = i = 0;
	for (ctp = cts; *ctp; ctp++) {
		p = *ctp;
		if (p->c_type == CT_MESSAGE && p->c_subtype == ct->c_subtype) {
			pm = (struct partial *) p->c_ctparams;
			if (!pm->pm_stored &&
					strcmp(qm->pm_partid, pm->pm_partid)
					== 0) {
				pm->pm_marked = pm->pm_partno;
				if (pm->pm_maxno)
					hi = pm->pm_maxno;
				pm->pm_stored = 1;
				i++;
			} else
				pm->pm_marked = 0;
		}
	}

	if (hi == 0) {
		advise(NULL, "missing (at least) last part of multipart message");
		return NOTOK;
	}

	base = mh_xcalloc(i + 1, sizeof(*base));

	ctq = base;
	for (ctp = cts; *ctp; ctp++) {
		p = *ctp;
		if (p->c_type == CT_MESSAGE && p->c_subtype == ct->c_subtype) {
			pm = (struct partial *) p->c_ctparams;
			if (pm->pm_marked)
				*ctq++ = p;
		}
	}
	*ctq = NULL;

	if (i > 1)
		qsort((char *) base, i, sizeof(*base), (qsort_comp) ct_compar);

	cur = 1;
	for (ctq = base; *ctq; ctq++) {
		p = *ctq;
		pm = (struct partial *) p->c_ctparams;
		if (pm->pm_marked != cur) {
			if (pm->pm_marked == cur - 1) {
				admonish(NULL, "duplicate part %d of %d part multipart message", pm->pm_marked, hi);
				continue;
			}

missing_part:
			advise (NULL, "missing %spart %d of %d part multipart message", cur != hi ? "(at least) " : "", cur, hi);
			goto losing;
		} else
			cur++;
	}
	if (hi != --cur) {
		cur = hi;
		goto missing_part;
	}

	/*
	** Now cycle through the sorted list of messages of type
	** "message/partial" and save/append them to a file.
	*/

	ctq = base;
	ct = *ctq++;
	if (store_content(ct, NULL) == NOTOK) {
losing:
		mh_free0(&base);
		return NOTOK;
	}

	for (; *ctq; ctq++) {
		p = *ctq;
		if (store_content(p, ct) == NOTOK)
			goto losing;
	}

	mh_free0(&base);
	return OK;
}


/*
** Show how to retrieve content of type "message/external".
*/
static int
store_external(CT ct)
{
	char **ap, **ep;
	char *msg;
	FILE *fp;
	char buf[BUFSIZ];

	msg = add("You need to fetch the contents yourself:", NULL);
	ap = ct->c_ctinfo.ci_attrs;
	ep = ct->c_ctinfo.ci_values;
	for (; *ap; ap++, ep++) {
		msg = add(concat("\n\t", *ap, ": ", *ep, NULL), msg);
	}
	if (!(fp = fopen(ct->c_file, "r"))) {
		adios(EX_IOERR, ct->c_file, "unable to open");
	}
	fseek(fp, ct->c_begin, SEEK_SET);
	while (!feof(fp) && ftell(fp) < ct->c_end) {
		if (!fgets(buf, sizeof buf, fp)) {
			adios(EX_IOERR, ct->c_file, "unable to read");
		}
		*strchr(buf, '\n') = '\0';
		msg = add(concat("\n\t", buf, NULL), msg);
	}
	fclose(fp);
	advise(NULL, msg);
	return OK;
}


/*
** Compare the numbering from two different
** message/partials (needed for sorting).
*/

static int
ct_compar(CT *a, CT *b)
{
	struct partial *am = (struct partial *) ((*a)->c_ctparams);
	struct partial *bm = (struct partial *) ((*b)->c_ctparams);

	return (am->pm_marked - bm->pm_marked);
}


/*
** Store contents of a message or message part to
** a folder, a file, the standard output, or pass
** the contents to a command.
**
** If the current content to be saved is a followup part
** to a collection of messages of type "message/partial",
** then field "p" is a pointer to the Content structure
** to the first message/partial in the group.
*/

static int
store_content(CT ct, CT p)
{
	int appending = 0, msgnum = 0;
	int is_partial = 0, first_partial = 0;
	int last_partial = 0;
	char *cp, buffer[BUFSIZ];

	/*
	** Do special processing for messages of
	** type "message/partial".
	**
	** We first check if this content is of type
	** "message/partial".  If it is, then we need to check
	** whether it is the first and/or last in the group.
	**
	** Then if "p" is a valid pointer, it points to the Content
	** structure of the first partial in the group.  So we copy
	** the file name and/or folder name from that message.  In
	** this case, we also note that we will be appending.
	*/
	if (ct->c_type == CT_MESSAGE && ct->c_subtype == MESSAGE_PARTIAL) {
		struct partial *pm = (struct partial *) ct->c_ctparams;

		/* Yep, it's a message/partial */
		is_partial = 1;

		/* But is it the first and/or last in the collection? */
		if (pm->pm_partno == 1)
			first_partial = 1;
		if (pm->pm_maxno && pm->pm_partno == pm->pm_maxno)
			last_partial = 1;

		/*
		** If "p" is a valid pointer, then it points to the
		** Content structure for the first message in the group.
		** So we just copy the filename or foldername information
		** from the previous iteration of this function.
		*/
		if (p) {
			appending = 1;
			ct->c_storage = mh_xstrdup(p->c_storage);

			/* record the folder name */
			if (p->c_folder) {
				ct->c_folder = mh_xstrdup(p->c_folder);
			}
			goto got_filename;
		}
	}

	/*
	** Get storage formatting string.
	**
	** 1) If we have storeproc defined, then use that
	** 2) Else check for a mhstore-store-<type>/<subtype> entry
	** 3) Else check for a mhstore-store-<type> entry
	** 4) Else if content is "message", use "+" (current folder)
	** 5) Else use string "%m%P.%s".
	*/
	if (!(cp = ct->c_storeproc) || !*cp) {
		CI ci = &ct->c_ctinfo;

		snprintf(buffer, sizeof(buffer), "%s-store-%s/%s",
				invo_name, ci->ci_type, ci->ci_subtype);
		if ((cp = context_find(buffer)) == NULL || *cp == '\0') {
			snprintf(buffer, sizeof(buffer), "%s-store-%s",
					invo_name, ci->ci_type);
			if ((cp = context_find(buffer)) == NULL ||
					*cp == '\0') {
				cp = ct->c_type == CT_MESSAGE ?
						"+" : "%m%P.%s";
			}
		}
	}

	/*
	** Check the beginning of storage formatting string
	** to see if we are saving content to a folder.
	*/
	if (*cp == '+' || *cp == '@') {
		char *tmpfilenam, *folder;

		/* Store content in temporary file for now */
		tmpfilenam = m_mktemp(invo_name, NULL, NULL);
		ct->c_storage = mh_xstrdup(tmpfilenam);

		/* Get the folder name */
		if (cp[1])
			folder = mh_xstrdup(expandfol(cp));
		else
			folder = getcurfol();

		/* Check if folder exists */
		create_folder(toabsdir(folder), 0, exit);

		/* Record the folder name */
		ct->c_folder = mh_xstrdup(folder);

		if (cp[1])
			mh_free0(&folder);

		goto got_filename;
	}

	/*
	** Parse and expand the storage formatting string
	** in `cp' into `buffer'.
	*/
	parse_format_string(ct, cp, buffer, sizeof(buffer), dir);

	/*
	** If formatting begins with '|' or '!', then pass
	** content to standard input of a command and return.
	*/
	if (buffer[0] == '|' || buffer[0] == '!')
		return show_content_aux(ct, 0, buffer + 1, dir);

	/* record the filename */
	ct->c_storage = mh_xstrdup(buffer);

got_filename:
	/* flush the output stream */
	fflush(stdout);

	/* Now save or append the content to a file */
	if (output_content_file(ct, appending) == NOTOK)
		return NOTOK;

	/*
	** If necessary, link the file into a folder and remove
	** the temporary file.  If this message is a partial,
	** then only do this if it is the last one in the group.
	*/
	if (ct->c_folder && (!is_partial || last_partial)) {
		msgnum = output_content_folder(ct->c_folder, ct->c_storage);
		unlink(ct->c_storage);
		if (msgnum == NOTOK)
			return NOTOK;
	}

	/*
	** Now print out the name/number of the message
	** that we are storing.
	*/
	if (is_partial) {
		if (first_partial)
			fprintf(stderr, "reassembling partials ");
		if (last_partial)
			fprintf(stderr, "%s", ct->c_file);
		else
			fprintf(stderr, "%s,", ct->c_file);
	} else {
		fprintf(stderr, "storing message %s", ct->c_file);
		if (ct->c_partno)
			fprintf(stderr, " part %s", ct->c_partno);
	}

	/*
	** Unless we are in the "middle" of group of message/partials,
	** we now print the name of the file, folder, and/or message
	** to which we are storing the content.
	*/
	if (!is_partial || last_partial) {
		if (ct->c_folder) {
			fprintf(stderr, " to folder %s as message %d\n",
					ct->c_folder, msgnum);
		} else if (strcmp(ct->c_storage, "-")==0) {
			fprintf(stderr, " to stdout\n");
		} else {
			int cwdlen;

			cwdlen = strlen(cwd);
			fprintf(stderr, " as file %s\n",
					strncmp(ct->c_storage, cwd,
					cwdlen)!=0 ||
					ct->c_storage[cwdlen] != '/' ?
					ct->c_storage :
					ct->c_storage + cwdlen + 1);
		}
	}

	return OK;
}


/*
** Output content to a file
*/

static int
output_content_file(CT ct, int appending)
{
	int filterstate;
	char *file, buffer[BUFSIZ];
	long pos, last;
	FILE *fp;

	/*
	** If the pathname contains directories, make sure
	** all of them exist.
	*/
	if (strchr(ct->c_storage, '/') && make_intermediates(ct->c_storage)
			== NOTOK)
		return NOTOK;

	if (ct->c_encoding != CE_7BIT) {
		int cc, fd;

		if (!ct->c_ceopenfnx) {
			advise(NULL, "don't know how to decode part %s of message %s", ct->c_partno, ct->c_file);
			return NOTOK;
		}

		file = appending || strcmp(ct->c_storage, "-")==0 ?
				NULL : ct->c_storage;
		if ((fd = (*ct->c_ceopenfnx) (ct, &file)) == NOTOK)
			return NOTOK;
		if (strcmp(file, ct->c_storage)==0) {
			(*ct->c_ceclosefnx) (ct);
			return OK;
		}

		/*
		** Send to standard output
		*/
		if (strcmp(ct->c_storage, "-")==0) {
			int gd;

			if ((gd = dup(fileno(stdout))) == NOTOK) {
				advise("stdout", "unable to dup");
losing:
				(*ct->c_ceclosefnx) (ct);
				return NOTOK;
			}
			if ((fp = fdopen(gd, appending ? "a" : "w")) == NULL) {
				advise("stdout", "unable to fdopen (%d, \"%s\") from", gd, appending ? "a" : "w");
				close(gd);
				goto losing;
			}
		} else {
			/*
			** Open output file
			*/
			if ((fp = fopen(ct->c_storage, appending ? "a" : "w"))
					== NULL) {
				advise(ct->c_storage, "unable to fopen for %s",
						appending ?
						"appending" : "writing");
				goto losing;
			}
		}

		/*
		** Filter the header fields of the initial enclosing
		** message/partial into the file.
		*/
		if (ct->c_type == CT_MESSAGE && ct->c_subtype == MESSAGE_PARTIAL) {
			struct partial *pm = (struct partial *) ct->c_ctparams;

			if (pm->pm_partno == 1)
				copy_some_headers(fp, ct);
		}

		for (;;) {
			switch (cc = read(fd, buffer, sizeof(buffer))) {
			case NOTOK:
				advise(file, "error reading content from");
				break;

			case OK:
				break;

			default:
				fwrite(buffer, sizeof(*buffer), cc, fp);
				continue;
			}
			break;
		}

		(*ct->c_ceclosefnx) (ct);

		if (cc != NOTOK && fflush(fp))
			advise(ct->c_storage, "error writing to");

		fclose(fp);

		return (cc != NOTOK ? OK : NOTOK);
	}

	if (!ct->c_fp && (ct->c_fp = fopen(ct->c_file, "r")) == NULL) {
		advise(ct->c_file, "unable to open for reading");
		return NOTOK;
	}

	pos = ct->c_begin;
	last = ct->c_end;
	fseek(ct->c_fp, pos, SEEK_SET);

	if (strcmp(ct->c_storage, "-")==0) {
		int gd;

		if ((gd = dup(fileno(stdout))) == NOTOK) {
			advise("stdout", "unable to dup");
			return NOTOK;
		}
		if ((fp = fdopen(gd, appending ? "a" : "w")) == NULL) {
			advise("stdout", "unable to fdopen (%d, \"%s\") from",
					gd, appending ? "a" : "w");
			close(gd);
			return NOTOK;
		}
	} else {
		if ((fp = fopen(ct->c_storage, appending ? "a" : "w"))
				== NULL) {
			advise(ct->c_storage, "unable to fopen for %s",
					appending ? "appending" : "writing");
			return NOTOK;
		}
	}

	/*
	** Copy a few of the header fields of the initial
	** enclosing message/partial into the file.
	*/
	filterstate = 0;
	if (ct->c_type == CT_MESSAGE && ct->c_subtype == MESSAGE_PARTIAL) {
		struct partial *pm = (struct partial *) ct->c_ctparams;

		if (pm->pm_partno == 1) {
			copy_some_headers(fp, ct);
			filterstate = 1;
		}
	}

	while (fgets(buffer, sizeof(buffer) - 1, ct->c_fp)) {
		if ((pos += strlen(buffer)) > last) {
			int diff;

			diff = strlen(buffer) - (pos - last);
			if (diff >= 0)
				buffer[diff] = '\0';
		}
		/*
		** If this is the first content of a group of
		** message/partial contents, then we only copy a few
		** of the header fields of the enclosed message.
		*/
		if (filterstate) {
			switch (buffer[0]) {
			case ' ':
			case '\t':
				if (filterstate < 0)
					buffer[0] = 0;
				break;

			case '\n':
				filterstate = 0;
				break;

			default:
				if (!uprf(buffer, XXX_FIELD_PRF) && !uprf(buffer, VRSN_FIELD) && !uprf(buffer, "Subject:") && !uprf(buffer, "Message-ID:")) {
					filterstate = -1;
					buffer[0] = 0;
					break;
				}
				filterstate = 1;
				break;
			}
		}
		fputs(buffer, fp);
		if (pos >= last)
			break;
	}

	if (fflush(fp))
		advise(ct->c_storage, "error writing to");

	fclose(fp);
	fclose(ct->c_fp);
	ct->c_fp = NULL;
	return OK;
}


/*
** Add a file to a folder.
**
** Return the new message number of the file
** when added to the folder.  Return -1, if
** there is an error.
*/

static int
output_content_folder(char *folder, char *filename)
{
	int msgnum;
	struct msgs *mp;

	/* Read the folder. */
	if ((mp = folder_read(folder))) {
		/* Link file into folder */
		msgnum = folder_addmsg(&mp, filename, 0, 0, 0, 0, NULL);
	} else {
		advise(NULL, "unable to read folder %s", folder);
		return NOTOK;
	}

	/* free folder structure */
	folder_free(mp);

	/*
	** Return msgnum.  We are relying on the fact that
	** msgnum will be -1, if folder_addmsg() had an error.
	*/
	return msgnum;
}


/*
** Parse and expand the storage formatting string
** pointed to by "cp" into "buffer".
*/

static int
parse_format_string(CT ct, char *cp, char *buffer, int buflen, char *dir)
{
	int len;
	char *bp;
	CI ci = &ct->c_ctinfo;

	/*
	** If storage string is "-", just copy it, and
	** return (send content to standard output).
	*/
	if (cp[0] == '-' && cp[1] == '\0') {
		strncpy(buffer, cp, buflen);
		return 0;
	}

	bp = buffer;
	bp[0] = '\0';

	/*
	** If formatting string is a pathname that doesn't
	** begin with '/', then preface the path with the
	** appropriate directory.
	*/
	if (*cp != '/' && *cp != '|' && *cp != '!') {
		snprintf(bp, buflen, "%s/", dir[1] ? dir : "");
		len = strlen(bp);
		bp += len;
		buflen -= len;
	}

	for (; *cp; cp++) {

		/* We are processing a storage escape */
		if (*cp == '%') {
			switch (*++cp) {
			case 'a':
				/*
				** Insert parameters from Content-Type.
				** This is only valid for '|' commands.
				*/
				if (buffer[0] != '|' && buffer[0] != '!') {
					*bp++ = *--cp;
					*bp = '\0';
					buflen--;
					continue;
				} else {
					char **ap, **ep;
					char *s = "";

					for (ap=ci->ci_attrs, ep=ci->ci_values;
							 *ap; ap++, ep++) {
						snprintf(bp, buflen,
								"%s%s=\"%s\"",
								s, *ap, *ep);
						len = strlen(bp);
						bp += len;
						buflen -= len;
						s = " ";
					}
				}
				break;

			case 'm':
				/* insert message number */
				snprintf(bp, buflen, "%s",
						mhbasename(ct->c_file));
				break;

			case 'P':
				/* insert part number with leading dot */
				if (ct->c_partno)
					snprintf(bp, buflen, ".%s",
							ct->c_partno);
				break;

			case 'p':
				/* insert part number withouth leading dot */
				if (ct->c_partno)
					strncpy(bp, ct->c_partno, buflen);
				break;

			case 't':
				/* insert content type */
				strncpy(bp, ci->ci_type, buflen);
				break;

			case 's':
				/* insert content subtype */
				strncpy(bp, ci->ci_subtype, buflen);
				break;

			case '%':
				/* insert the character % */
				goto raw;

			default:
				*bp++ = *--cp;
				*bp = '\0';
				buflen--;
				continue;
			}

			/* Advance bp and decrement buflen */
			len = strlen(bp);
			bp += len;
			buflen -= len;

		} else {
raw:
			*bp++ = *cp;
			*bp = '\0';
			buflen--;
		}
	}

	return 0;
}


/*
** Copy some of the header fields of the initial message/partial
** message into the header of the reassembled message.
*/

static int
copy_some_headers(FILE *out, CT ct)
{
	HF hp;

	hp = ct->c_first_hf;  /* start at first header field */

	while (hp) {
		/*
		** A few of the header fields of the enclosing
		** messages are not copied.
		*/
		if (!uprf(hp->name, XXX_FIELD_PRF) &&
				mh_strcasecmp(hp->name, VRSN_FIELD) &&
				mh_strcasecmp(hp->name, "Subject") &&
				mh_strcasecmp(hp->name, "Message-ID"))
			fprintf(out, "%s:%s", hp->name, hp->value);
		hp = hp->next;  /* next header field */
	}

	return OK;
}
