/*
 * Copyright (c) 1983 Eric P. Allman
 * Copyright (c) 1988 Regents of the University of California.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#ifndef lint
static char sccsid[] = "@(#)collect.c	5.9 (Berkeley) 6/1/90";
static char rcsid[] = "@(#)$Id: collect.c,v 5.9.0.21 1993/11/29 21:34:41 avatar Exp $";
#endif /* not lint */

#include "sendmail.h"

static void tferror __P((FILE *));
static void eatfrom __P((const char *));

  /* * Stub out fsync */
/*
 #ifdef linux  
void fsync (int fd) {}
#endif
*/
/*
**  COLLECT -- read & parse message header & make temp file.
**
**	Creates a temporary file name and copies the standard
**	input to that file.  Leading UNIX-style "From" lines are
**	stripped off (after important information is extracted).
**
**	Parameters:
**		sayok -- if set, give an ARPANET style message
**			to say we are ready to collect input.
**
**	Returns:
**		none.
**
**	Side Effects:
**		Temp file is created and filled.
**		The from person may be set.
*/

void
collect(sayok)
	bool sayok;
{
	register FILE *tf;
	char buf[MAXFIELD+2];
	register char *p;
#ifdef BIT8
	char buf1[MAXFIELD+2];
	CHARSET *ch;
	char *chname, *chesc;
#endif /* BIT8 */

	/*
	**  Create the temp file name and create the file.
	*/

	/* newstr macro will call function arguments twice */
	p = queuename(CurEnv, 'd');
	CurEnv->e_df = newstr(p);
	if ((tf = dfopen(CurEnv->e_df, "w")) == NULL)
	{
		syserr("Cannot create %s", CurEnv->e_df);
		NoReturn = TRUE;
		finis();
	}
	(void) chmod(CurEnv->e_df, FileMode);

	/*
	**  Tell ARPANET to go ahead.
	*/

	if (sayok)
		message("354", "Enter mail, end with \".\" on a line by itself");

	/*
	**  Only need sfgetsinit() if we aren't being called from smtp(),
	**  since smtp() already called sfgetsinit() on this same InChannel.
	**  Only smtp() calls us with sayok==TRUE.
	*/
	if (!sayok)
		sfgetsinit();

	/*
	**  Try to read a UNIX-style From line
	*/

	/*
	 * Read errors here are caught inside the do loop.  sfgets() will
	 * set buf[0] to NULL and fixcrlf() will return immediately because
	 * of that.
	 */
	(void) sfgets(buf, sizeof buf, InChannel);
	fixcrlf(buf, FALSE);
#ifndef NOTUNIX
	if (!SaveFrom && strncmp(buf, "From ", 5) == 0)
	{
		eatfrom(buf);
		(void) sfgets(buf, sizeof buf, InChannel);
		fixcrlf(buf, FALSE);
	}
#endif /* NOTUNIX */

	/*
	**  real-time processes like uucico can put CPU cycles to better use.
	**  setpriority() could be used here but SYSV systems don't have it.
	*/
	if (NiceDelivery)
		(void) nice(NiceDelivery);

	/*
	**  Copy InChannel to temp file & do message editing.
	**	To keep certain mailers from getting confused,
	**	and to keep the output clean, lines that look
	**	like UNIX "From" lines are deleted in the header.
	**	(See above)
	*/

	do {
		int c;

		/* drop out on error */
		if (ferror(InChannel))
			break;

		/* if the line is too long, throw the rest away */
		if (index(buf, '\n') == NULL)
		{
			while ((c = getc(InChannel)) != '\n' && c != EOF)
				continue;
		}
		fixcrlf(buf, TRUE);

		/* see if the header is over */
		if (!isheader(buf))
			break;

		/* get the rest of this field */
		while ((c = getc(InChannel)) == ' ' || c == '\t')
		{
			p = &buf[strlen(buf)];
			*p++ = '\n';
			*p++ = c;
			if (sfgets(p, sizeof(buf) - (p - buf), InChannel) == NULL)
				break;
			fixcrlf(p, TRUE);
		}
		if (!feof(InChannel) && !ferror(InChannel))
			(void) ungetc(c, InChannel);

		CurEnv->e_msgsize += strlen(buf);

		/*
		**  Snarf header away.
		*/

		if (bitset(H_EOH, chompheader(buf, FALSE)))
			break;
	} while (sfgets(buf, sizeof(buf) - 2, InChannel) != NULL);

	if (tTd(30, 1))
		printf("EOH\n");

	/* throw away a blank line */
	if (buf[0] == '\0' && !ferror(InChannel))
		(void) sfgets(buf, sizeof(buf), InChannel);

	/*
	**  Collect the body of the message.
	*/

#ifdef BIT8
	chname = hvalue("x-charset");
	chesc = hvalue("x-char-esc");
	if (!chesc)
		chesc = "29";
	if (chname)
		ch = getchset(chname, atoi(chesc));
	else
		ch = CurEnv->e_from.q_mailer->m_charset;
#endif /* BIT8 */
#ifdef O_SYNC
	if (SuperSafe)
	{
		int fd = fileno(tf);
		int flags;

		if ((flags = fcntl(fd, F_GETFL)) != -1)
			(void) fcntl(fd, F_SETFL, flags | O_SYNC);
	}
#endif /* O_SYNC */

	do
	{
		register char *bp = buf;

		/* drop out on error */
		if (ferror(InChannel))
			break;
#ifdef BIT8
		if (ch)
		{
			strncnv(ascii, ch, (CHAR8U *)buf1, (CHAR8U *)buf, sizeof buf1);
			strncpy(buf, buf1, sizeof buf);
		}
#endif /* BIT8 */

		fixcrlf(buf, TRUE);

		/* check for end-of-message */
		if (!IgnrDot && buf[0] == '.' && (buf[1] == '\n' || buf[1] == '\0'))
			break;

		/* check for transparent dot */
		if (OpMode == MD_SMTP && !IgnrDot && bp[0] == '.' && bp[1] == '.')
			bp++;

		/*
		**  Figure message length, output the line to the temp
		**  file, and insert a newline if missing.
		*/

		CurEnv->e_msgsize += strlen(bp) + 1;
		fputs(bp, tf);
		putc('\n', tf);
		if (ferror(tf))
			tferror(tf);
	} while (sfgets(buf, sizeof(buf), InChannel) != NULL);

	if (fflush(tf) != 0)
		tferror(tf);
	if (!sayok)
		sfgetsfini();
	
	/*
	 * Since overly long headers are appended to the end of the message
	 * body, delay closing tf until eatheader is done.
	 */

	/* An EOF when running SMTP is an error */
	if ((feof(InChannel) || ferror(InChannel)) && OpMode == MD_SMTP)
	{
#ifdef LOG
		if (RealHostName != NULL && LogLevel > 0)
			syslog(LOG_NOTICE,
			    "collect: unexpected close on connection from %s: %m",
			    RealHostName);
#endif /* LOG */
		/*
		 * So many broken compilers out there...
		 * (feof(InChannel) ? usrerr: syserr)
		 *	("collect: unexpected close, from=%s",
		 *	    CurEnv->e_from.q_paddr);
		 */
		if (feof(InChannel))
			usrerr("collect: unexpected close, from=%s",
			    CurEnv->e_from.q_paddr);
		else
			syserr("collect: unexpected close, from=%s",
			    CurEnv->e_from.q_paddr);
		(void) fclose(tf);

		/* don't return an error indication */
		CurEnv->e_to = NULL;
		CurEnv->e_flags &= ~EF_FATALERRS;

		/* and don't try to deliver the partial message either */
		finis();
	}

	/*
	**  Find out some information from the headers.
	**	Examples are who is the from person & the date.
	*/

	eatheader(CurEnv, tf);
	(void) fflush(tf);
#ifndef O_SYNC
	if (SuperSafe && fsync(fileno(tf)) < 0)
		syserr("collect: fsync() of tf failed (%d)", errno);
#endif /* !O_SYNC */

	/* Now close the tf file */
	(void) fclose(tf);

	/*
	**  Add an Apparently-To: line if we have no recipient lines.
	*/

	if (hvalue("to") == NULL && hvalue("cc") == NULL &&
	    hvalue("bcc") == NULL && hvalue("apparently-to") == NULL)
	{
		register ADDRESS *q;

		/* create an Apparently-To: field */
		/*    that or reject the message.... */
		for (q = CurEnv->e_sendqueue; q != NULL; q = q->q_next)
		{
			if (q->q_alias != NULL)
				continue;
			if (tTd(30, 3))
				printf("Adding Apparently-To: %s\n", q->q_paddr);
			addheader("apparently-to", q->q_paddr, CurEnv);
		}
	}

	if ((CurEnv->e_dfp = fopen(CurEnv->e_df, "r")) == NULL)
		syserr("Cannot reopen %s", CurEnv->e_df);
}
/*
**  TFERROR -- signal error on writing the temporary file.
**
**	Parameters:
**		tf -- the file pointer for the temporary file.
**
**	Returns:
**		none.
**
**	Side Effects:
**		Gives an error message.
**		Arranges for following output to go elsewhere.
*/

static void
tferror(tf)
	FILE *tf;
{
	if (errno == ENOSPC)
	{
		(void) freopen(CurEnv->e_df, "w", tf);
		fputs("\nMAIL DELETED BECAUSE OF LACK OF DISK SPACE\n\n", tf);
		usrerr("452 Out of disk space for temp file");
	}
	else
		syserr("collect: Cannot write %s", CurEnv->e_df);
	(void) freopen("/dev/null", "w", tf);
}
/*
**  EATFROM -- chew up a UNIX style from line and process
**
**	This does indeed make some assumptions about the format
**	of UNIX messages.
**
**	Parameters:
**		fm -- the from line.
**
**	Returns:
**		none.
**
**	Side Effects:
**		extracts what information it can from the header,
**		such as the date.
*/

char	*DowList[] =
{
	"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", NULL
};

char	*MonthList[] =
{
	"Jan", "Feb", "Mar", "Apr", "May", "Jun",
	"Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
	NULL
};

#ifndef NOTUNIX

static void
eatfrom(fm)
	const char *fm;
{
	register const char *p = fm;
	register char **dt;

	if (tTd(30, 2))
		printf("eatfrom(%s)\n", fm);

	/* find the date part */
	while (*p != '\0')
	{
		/* skip a word */
		while (*p != '\0' && *p != ' ')
			p++;
		while (*p == ' ')
			p++;
		if (!isupper(*p) || p[3] != ' ' || p[13] != ':' || p[16] != ':')
			continue;

		/* we have a possible date */
		for (dt = DowList; *dt != NULL; dt++)
			if (strncmp(*dt, p, 3) == 0)
				break;
		if (*dt == NULL)
			continue;

		for (dt = MonthList; *dt != NULL; dt++)
			if (strncmp(*dt, &p[4], 3) == 0)
				break;
		if (*dt != NULL)
			break;
	}

	if (*p != (char) NULL)
	{
		char *q;

		/* we have found a date */
		q = xalloc(25);
		(void) strncpy(q, p, 25);
		q[24] = '\0';
		define('d', q, CurEnv);
		q = arpadate(q);
		define('a', newstr(q), CurEnv);
	}
}

#endif /* NOTUNIX */
