/*
** send.c -- send a composed message
**
** 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 <errno.h>
#include <signal.h>
#include <h/signals.h>
#include <h/mime.h>
#include <h/tws.h>
#include <h/utils.h>
#include <sysexits.h>
#include <sys/wait.h>
#include <unistd.h>
#include <ctype.h>
#include <sys/stat.h>
#include <locale.h>

#ifdef HAVE_SYS_TIME_H
# include <sys/time.h>
#endif
#include <time.h>

#ifdef HAVE_SYS_PARAM_H
# include <sys/param.h>
#endif

int debugsw = 0;  /* global */
char *altmsg = NULL;
char *annotext = NULL;
char *distfile = NULL;

/* name of temp file for body content */
static char body_file_name[MAXPATHLEN + 1];
/* name of mhbuild composition temporary file */
static char composition_file_name[MAXPATHLEN + 1]; 
static int field_size;  /* size of header field buffer */
static char *field;  /* header field buffer */
static FILE *draft_file;  /* draft file pointer */
static FILE *body_file;  /* body file pointer */
static FILE *composition_file;  /* composition file pointer */

/*
** static prototypes
*/
static int sendsbr(char **, int, char *, struct stat *);
static void anno(struct stat *);
static int sendaux(char **, int, char *, struct stat *);
static int attach(char *);
static int signandenc(char *);
static void clean_up_temporary_files(void);
static int get_line(void);
static void make_mime_composition_file_entry(char *);
static char* strexit(int status);


static struct swit switches[] = {
#define DEBUGSW  0
	{ "debug", -5 },
#define VERBSW  1
	{ "verbose", 0 },
#define NVERBSW  2
	{ "noverbose", 2 },
#define VERSIONSW  3
	{ "Version", 0 },
#define HELPSW  4
	{ "help", 0 },
	{ NULL, 0 }
};

char *version=VERSION;

int
main(int argc, char **argv)
{
	int nmsgs = 0, nfiles = 0, distsw = 0, vecp = 1;
	int msgnum, status;
	int in, out;
	int n;
	char *cp, *maildir = NULL, *folder = NULL;
	char buf[BUFSIZ], **argp, **arguments;
	char *msgs[MAXARGS], *vec[MAXARGS];
	char *files[MAXARGS];
	struct msgs *mp;
	struct stat st;
	struct stat st2;

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

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

	arguments = getarguments(invo_name, argc, argv, 1);
	argp = 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\n", cp);

			case HELPSW:
				snprintf(buf, sizeof(buf),
						"%s [file] [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 DEBUGSW:
				debugsw++;
				/* fall */
			case VERBSW:
			case NVERBSW:
				vec[vecp++] = --cp;
				continue;
			}
		} else if (*cp == '+' || *cp == '@') {
			if (folder) {
				adios(EX_USAGE, NULL, "only one folder at a time!");
			} else {
				folder = mh_xstrdup(expandfol(cp));
			}
		} else {
			if (*cp == '/') {
				files[nfiles++] = cp;
			} else {
				msgs[nmsgs++] = cp;
			}
		}
	}

	if (!nmsgs && !nfiles) {
		msgs[nmsgs++] = seq_cur;
	}

	if (nmsgs) {
		folder = folder ? folder : draftfolder;
		maildir = toabsdir(folder);
		if (chdir(maildir) == NOTOK) {
			adios(EX_OSERR, maildir, "unable to change directory to");
		}
		if (!(mp = folder_read(folder))) {
			adios(EX_IOERR, NULL, "unable to read folder %s",
					folder);
		}
		if (mp->nummsg == 0) {
			adios(EX_DATAERR, NULL, "no messages in folder %s",
					folder);
		}
		/* parse all the msgranges/sequences and set SELECTED */
		for (msgnum = 0; msgnum < nmsgs; msgnum++) {
			if (!m_convert(mp, msgs[msgnum])) {
				exit(EX_USAGE);
			}
		}
		seq_setprev(mp);

		for (nmsgs = 0, msgnum = mp->lowsel;
				msgnum <= mp->hghsel; msgnum++) {
			if (is_selected(mp, msgnum)) {
				files[nfiles++] = mh_xstrdup(m_name(msgnum));
				unset_exists(mp, msgnum);
			}
		}

		mp->msgflags |= SEQMOD;
		seq_save(mp);
	}

	if (!(cp = getenv("SIGNATURE")) || !*cp) {
		if ((cp = context_find("signature")) && *cp) {
			m_putenv("SIGNATURE", cp);
		}
	}

	for (n = 0; n < nfiles; n++) {
		if (stat(files[n], &st) == NOTOK) {
			adios(EX_IOERR, files[n], "unable to stat draft file");
		}
	}

	if (!(annotext = getenv("mhannotate")) || !*annotext) {
		annotext = NULL;
	}
	if (!(altmsg = getenv("mhaltmsg")) || !*altmsg) {
		altmsg = NULL;  /* used by dist interface - see below */
	}

	if ((cp = getenv("mhdist")) && *cp && (distsw = atoi(cp)) && altmsg) {
		vec[vecp++] = "-dist";
		if ((in = open(altmsg, O_RDONLY)) == NOTOK) {
			adios(EX_IOERR, altmsg, "unable to open for reading");
		}
		fstat(in, &st2);
		distfile = mh_xstrdup(m_mktemp2(NULL, invo_name, NULL, NULL));
		if ((out = creat(distfile, (int)st2.st_mode & 0777))==NOTOK) {
			adios(EX_IOERR, distfile, "unable to open for writing");
		}
		cpydata(in, out, altmsg, distfile);
		close(in);
		close(out);
	} else {
		distfile = NULL;
	}

	if (!altmsg || stat(altmsg, &st) == NOTOK) {
		st.st_mtime = 0;
		st.st_dev = 0;
		st.st_ino = 0;
	}
	status = 0;
	vec[0] = "spost";
	for (n=3; n<OPEN_MAX; n++) {
		close(n);
	}

	for (n = 0; n < nfiles; n++) {
		switch (sendsbr(vec, vecp, files[n], &st)) {
		case DONE:
			exit(++status);
		case NOTOK:
			status++;  /* fall */
		case OK:
			break;
		}
	}

	context_save();
	return status;
}


/*
** message sending back-end
*/
static int
sendsbr(char **vec, int vecp, char *drft, struct stat *st)
{
	int status, dupfd;
	char *original_draft;

	/*
	** Save the original name of the draft file.  The name of the
	** draft file is changed to a temporary file containing the built
	** MIME message if there are attachments.  We need the original
	** name so that it can be renamed after the message is sent.
	*/
	original_draft = drft;

	/*
	** Convert the draft to a MIME message.
	** Use the mhbuild composition file for the draft if there was
	** a successful conversion because that now contains the MIME
	** message.  A nice side effect of this is that it leaves the
	** original draft file untouched so that it can be retrieved
	** and modified if desired.
	*/
	switch (attach(drft)) {
	case OK:
		/* successfully MIMEified: use generate draft */
		drft = composition_file_name;
		break;

	case NOTOK:
		return (NOTOK);

	case DONE:
		/* already in MIME format: keep original draft */
		break;
	}

	/*
	** Sign and encrypt the message as needed.
	** Use the mhbuild composition file for the draft if there was
	** a successful conversion because that now contains the MIME
	** message.  A nice side effect of this is that it leaves the
	** original draft file untouched so that it can be retrieved
	** and modified if desired.
	*/
	switch (signandenc(drft)) {
	case OK:
		drft = composition_file_name;
		break;

	case NOTOK:
		return (NOTOK);

	case DONE:
		break;
	}

	if ((status = sendaux(vec, vecp, drft, st)) == OK) {
		/* move original draft to +trash folder */
		/* temporary close stdin, for refile not to ask */
		dupfd = dup(0);
		close(0);
		if (execprogl("refile", "refile", "-file",
				original_draft, "+trash",
				(char *)NULL) != 0) {
			advise(NULL, "unable to trash the draft");
		}
		dup2(dupfd, 0);
		close(dupfd);
	} else {
		status = DONE;
	}

	if (distfile) {
		unlink(distfile);
	}

	/* Get rid of temporary files that we created for attachments. */
	if (drft == composition_file_name) {
		clean_up_temporary_files();
	}

	return status;
}

static int
attach(char *draft_file_name)
{
	char buf[MAXPATHLEN + 6];
	int c;
	int length = strlen(attach_hdr);
	char *p;

	if(distfile) {
		return DONE;
	}

	if (!(draft_file = fopen(draft_file_name, "r"))) {
		adios(EX_IOERR, NULL, "can't open draft file `%s'.", draft_file_name);
	}

	/* We'll grow the buffer as needed. */
	field = mh_xcalloc(field_size = 256, sizeof(char));

	/*
	** MIMEify
	*/

	/* Make names for the temporary files.  */
	strncpy(body_file_name,
			m_mktemp(toabsdir(invo_name), NULL, NULL),
			sizeof (body_file_name));
	strncpy(composition_file_name,
			m_mktemp(toabsdir(invo_name), NULL, NULL),
			sizeof (composition_file_name));

	body_file = fopen(body_file_name, "w");
	composition_file = fopen(composition_file_name, "w");

	if (!body_file || !composition_file) {
		clean_up_temporary_files();
		adios(EX_IOERR, NULL, "unable to open all of the temporary files.");
	}

	/* Copy non-attachment header fields to the temp composition file. */
	rewind(draft_file);
	while (get_line() != EOF && *field && *field != '-') {
		if (strncasecmp(field, VRSN_FIELD, strlen(VRSN_FIELD))==0 &&
				field[strlen(VRSN_FIELD)] == ':') {
			/*
			** The draft is already in MIME format, thus
			** back out and use the original draft file.
			*/
			clean_up_temporary_files();
			return DONE;
		}

		if (strncasecmp(field, attach_hdr, length) != 0 ||
				field[length] != ':') {
			fprintf(composition_file, "%s\n", field);
		}
	}
	fputs("--------\n", composition_file);

	/* Copy the message body to the temporary file. */
	while ((c = getc(draft_file)) != EOF) {
		putc(c, body_file);
	}
	fclose(body_file);

	/* Add a mhbuild MIME composition file line for the body */
	/* charset will be discovered/guessed by mhbuild */
	fprintf(composition_file, "#text/plain %s\n", body_file_name);

	/*
	** Now, go back to the beginning of the draft file and look for
	** header fields that specify attachments.  Add a mhbuild MIME
	** composition file for each.
	*/
	rewind(draft_file);
	while (get_line() != EOF && *field && *field != '-') {
		if (strncasecmp(field, attach_hdr, length) == 0 &&
				field[length] == ':') {
			p = trim(field+length+1);
			if (*p == '+') {
				/* forwarded message */
				fprintf(composition_file, "#forw [forwarded message(s)] %s\n", p);
			} else {
				/* regular attachment */
				make_mime_composition_file_entry(p);
			}
		}
	}
	fclose(composition_file);

	/* We're ready to roll! */
	if (execprogl("mhbuild", "mhbuild", composition_file_name,
			(char *)NULL) != 0) {
		/* some problem */
		clean_up_temporary_files();
		return (NOTOK);
	}
	/* Remove the automatically created backup of mhbuild. */
	snprintf(buf, sizeof buf, "%s.orig", composition_file_name);
	if (unlink(buf) == -1) {
		advise(NULL, "unable to remove original composition file.");
	}

	return (OK);
}

static int
signandenc(char *draft_file_name)
{
	char buf[BUFSIZ];
	int dosign = 0;
	int doenc = 0;
	int ret;

	if(distfile) {
		return DONE;
	}

	if (!(draft_file = fopen(draft_file_name, "r"))) {
		adios(EX_IOERR, NULL, "can't open draft file `%s'.", draft_file_name);
	}

	/* We'll grow the buffer as needed. */
	field = mh_xcalloc(field_size = 256, sizeof(char));

	/* Scan the draft file for an attachment header field name. */
	while (get_line() != EOF && *field != '\0' && *field != '-') {
		if (strncasecmp(field, sign_hdr, strlen(sign_hdr))==0 &&
				field[strlen(sign_hdr)] == ':') {
			dosign = 1;
		}
		if (strncasecmp(field, enc_hdr, strlen(enc_hdr))==0 &&
				field[strlen(enc_hdr)] == ':') {
			doenc = 1;
		}
	}
	if (!dosign && !doenc) {
		return DONE;
	}

	strcpy(composition_file_name, draft_file_name);

	/* We're ready to roll! */
	if (doenc) {
		ret = execprogl("mhsign", "mhsign", "-m", "-e",
				draft_file_name, (char *)NULL);
	} else {
		ret = execprogl("mhsign", "mhsign", "-m",
				draft_file_name, (char *)NULL);
	}
	if (ret != 0) {
		/* some problem */
		return (NOTOK);
	}
	/* Remove the automatically created backup of mhsign. */
	snprintf(buf, sizeof buf, "%s.orig", draft_file_name);
	if (unlink(buf) == -1) {
		advise(NULL, "unable to remove original draft file.");
	}

	return (OK);
}

static void
clean_up_temporary_files(void)
{
	unlink(body_file_name);
	unlink(composition_file_name);

	return;
}

static int
get_line(void)
{
	int c;  /* current character */
	int n;  /* number of bytes in buffer */
	char *p;

	/*
	** Get a line from the input file, growing the field buffer as
	** needed.  We do this so that we can fit an entire line in the
	** buffer making it easy to do a string comparison on both the
	** field name and the field body which might be a long path name.
	*/
	for (n = 0, p = field; (c = getc(draft_file)) != EOF; *p++ = c) {
		if (c == '\n' && (c = getc(draft_file)) != ' ' && c != '\t') {
			ungetc(c, draft_file);
			c = '\n';
			break;
		}
		if (++n >= field_size - 1) {
			field = mh_xrealloc(field, field_size += 256);
			p = field + n - 1;
		}
	}
	*p = '\0';

	return (c);
}

static void
make_mime_composition_file_entry(char *file_name)
{
	FILE *fp;
	struct node *np;
	char *cp;
	char content_type[BUFSIZ];
	char cmdbuf[BUFSIZ];
	char *cmd = mimetypequeryproc;
	int semicolon = 0;

	for (np = m_defs; np; np = np->n_next) {
		if (strcasecmp(np->n_name, mimetypequery)==0) {
			cmd = np->n_field;
			break;
		}
	}
	snprintf(cmdbuf, sizeof cmdbuf, "%s %s", cmd, file_name);

	if (!(fp = popen(cmdbuf, "r"))) {
		clean_up_temporary_files();
		adios(EX_IOERR, NULL, "unable to determine content type with `%s'",
				cmdbuf);
	}
	if (fgets(content_type, sizeof content_type, fp) &&
			(cp = strrchr(content_type, '\n'))) {
		*cp = '\0';
	} else {
		strcpy(content_type, "application/octet-stream");
		admonish(NULL, "problems with `%s', using fall back type `%s'",
				cmdbuf, content_type);
	}
	pclose(fp);

	/* TODO: don't use access(2) because it checks for ruid, not euid */
	if (access(file_name, R_OK) != 0) {
		clean_up_temporary_files();
		adios(EX_IOERR, NULL, "unable to access file `%s'", file_name);
	}

	/* Check for broken file(1). See man page mh-profile(5). */
	for (cp=content_type; *cp; cp++) {
		if (isspace(*cp)) {
			if (!semicolon) {
				adios(EX_SOFTWARE, NULL, "Sorry, your Mime-Type-Query command (%s) is broken.\n\tThe output misses a semicolon before the whitespace.\n\tOutput was: %s", cmd, content_type);
			}
		} else if (*cp == ';') {
			semicolon = 1;
		} else {
			semicolon = 0;
		}
	}

	cp = (!(cp = strrchr(file_name, '/'))) ? file_name : cp + 1;
	fprintf(composition_file,
			"#%s; name=\"%s\" <> [%s] {attachment} %s\n",
			content_type, cp, cp, file_name);

	return;
}

/*
** The back-end of the message sending back-end.
** Annotate original message, and call `spost' to send message.
*/
static int
sendaux(char **vec, int vecp, char *drft, struct stat *st)
{
	pid_t child_id;
	int status;
	char backup[BUFSIZ];

	vec[vecp++] = drft;
	if (distfile && distout(drft, distfile, backup) == NOTOK) {
		return DONE;
	}
	vec[vecp] = NULL;

	switch (child_id = fork()) {
	case -1:
		/* oops -- fork error */
		advise("fork", "unable to");
		return DONE;

	case 0:
		/* child process -- send it */
		execvp(*vec, vec);
		fprintf(stderr, "unable to exec ");
		perror(*vec);
		_exit(EX_OSERR);
		break;  /* NOT REACHED */

	default:
		/* parent process -- wait for it */
		status = pidwait(child_id, NOTOK);
		if (WIFEXITED(status) && WEXITSTATUS(status) == EX_OK) {
			if (annotext) {
				anno(st);
			}
		} else {
			/* spost failed */
			advise(NULL, "%s", strexit(status));
			if (distfile) {
				unlink(drft);
				if (rename(backup, drft) == NOTOK) {
					advise(drft, "unable to rename %s to",
							backup);
				}
			}
		}
	}

	return status ? NOTOK : status;
}


static void
anno(struct stat *st)
{
	struct stat st2;
	char *msgs, *folder;
	char buf[BUFSIZ];
	char *vec[MAXARGS];
	int vecp = 0;
	char *cp, *dp;

	if (altmsg && (stat(altmsg, &st2) == NOTOK ||
			st->st_mtime != st2.st_mtime ||
			st->st_dev != st2.st_dev ||
			st->st_ino != st2.st_ino)) {
		if (debugsw) {
			admonish(NULL, "$mhaltmsg mismatch");
		}
		return;
	}

	if (!(folder = getenv("mhfolder")) || !*folder) {
		if (debugsw) {
			admonish(NULL, "$mhfolder not set");
		}
		return;
	}
	if (!(msgs = getenv("mhmessages")) || !*msgs) {
		if (debugsw) {
			admonish(NULL, "$mhmessages not set");
		}
		return;
	}
	if (debugsw) {
		advise(NULL, "annotate as `%s': %s %s", annotext,
				folder, msgs);
	}
	vec[vecp++] = "anno";
	vec[vecp++] = "-comp";
	vec[vecp++] = annotext;
	snprintf(buf, sizeof buf, "+%s", folder);
	vec[vecp++] = buf;

	while (isspace(*msgs)) {
		msgs++;
	}
	for (cp=dp=msgs; *cp; cp++) {
		if (isspace(*cp)) {
			while (isspace(*cp)) {
				*cp++ = '\0';
			}
			vec[vecp++] = dp;
			dp = cp;
		}
	}
	vec[vecp++] = dp;
	vec[vecp] = NULL;
	if (execprog(*vec, vec) != 0) {
		advise(NULL, "unable to annotate");
	}
}


char*
strexit(int status)
{
	if (WIFSIGNALED(status)) {
		return "spost or sendmail killed by signal";
	}
	if (!WIFEXITED(status)) {
		return "message not delivered to anyone";
	}
	switch (WEXITSTATUS(status)) {
	case EX_TEMPFAIL:
		return "Temporary error, maybe the MTA has queued the message";
	default:
		return "message not delivered to anyone";
	}
}
