1 /*
2  * Copyright (c) 1983 Eric P. Allman
3  * Copyright (c) 1988, 1993
4  *	The Regents of the University of California.  All rights reserved.
5  *
6  * %sccs.include.redist.c%
7  */
8 
9 #ifndef lint
10 static char sccsid[] = "@(#)collect.c	8.22 (Berkeley) 08/15/94";
11 #endif /* not lint */
12 
13 # include <errno.h>
14 # include "sendmail.h"
15 
16 /*
17 **  COLLECT -- read & parse message header & make temp file.
18 **
19 **	Creates a temporary file name and copies the standard
20 **	input to that file.  Leading UNIX-style "From" lines are
21 **	stripped off (after important information is extracted).
22 **
23 **	Parameters:
24 **		fp -- file to read.
25 **		smtpmode -- if set, we are running SMTP: give an RFC821
26 **			style message to say we are ready to collect
27 **			input, and never ignore a single dot to mean
28 **			end of message.
29 **		requeueflag -- this message will be requeued later, so
30 **			don't do final processing on it.
31 **		hdrp -- the location to stash the header.
32 **		e -- the current envelope.
33 **
34 **	Returns:
35 **		none.
36 **
37 **	Side Effects:
38 **		Temp file is created and filled.
39 **		The from person may be set.
40 */
41 
42 char	*CollectErrorMessage;
43 bool	CollectErrno;
44 
45 static jmp_buf	CtxCollectTimeout;
46 static int	collecttimeout();
47 static bool	CollectProgress;
48 static EVENT	*CollectTimeout;
49 
50 /* values for input state machine */
51 #define IS_NORM		0	/* middle of line */
52 #define IS_BOL		1	/* beginning of line */
53 #define IS_DOT		2	/* read a dot at beginning of line */
54 #define IS_DOTCR	3	/* read ".\r" at beginning of line */
55 #define IS_CR		4	/* read a carriage return */
56 
57 /* values for message state machine */
58 #define MS_UFROM	0	/* reading Unix from line */
59 #define MS_HEADER	1	/* reading message header */
60 #define MS_BODY		2	/* reading message body */
61 
62 
63 collect(fp, smtpmode, requeueflag, hdrp, e)
64 	FILE *fp;
65 	bool smtpmode;
66 	bool requeueflag;
67 	HDR **hdrp;
68 	register ENVELOPE *e;
69 {
70 	register FILE *tf;
71 	bool ignrdot = smtpmode ? FALSE : IgnrDot;
72 	time_t dbto = smtpmode ? TimeOuts.to_datablock : 0;
73 	register char *bp;
74 	register int c;
75 	bool inputerr = FALSE;
76 	bool headeronly = FALSE;
77 	char *buf;
78 	int buflen;
79 	int istate;
80 	int mstate;
81 	char *pbp;
82 	char peekbuf[8];
83 	char bufbuf[MAXLINE];
84 	extern bool isheader();
85 
86 	CollectErrorMessage = NULL;
87 	CollectErrno = 0;
88 	if (hdrp == NULL)
89 		hdrp = &e->e_header;
90 	else
91 		headeronly = TRUE;
92 
93 	/*
94 	**  Create the temp file name and create the file.
95 	*/
96 
97 	if (!headeronly)
98 	{
99 		struct stat stbuf;
100 
101 		e->e_df = queuename(e, 'd');
102 		e->e_df = newstr(e->e_df);
103 		if ((tf = dfopen(e->e_df, O_WRONLY|O_CREAT|O_TRUNC, FileMode)) == NULL)
104 		{
105 			syserr("Cannot create %s", e->e_df);
106 			e->e_flags |= EF_NORETURN;
107 			finis();
108 		}
109 		if (fstat(fileno(tf), &stbuf) < 0)
110 			e->e_dfino = -1;
111 		else
112 		{
113 			e->e_dfdev = stbuf.st_dev;
114 			e->e_dfino = stbuf.st_ino;
115 		}
116 		HasEightBits = FALSE;
117 	}
118 
119 	/*
120 	**  Tell ARPANET to go ahead.
121 	*/
122 
123 	if (smtpmode)
124 		message("354 Enter mail, end with \".\" on a line by itself");
125 
126 	/*
127 	**  Read the message.
128 	**
129 	**	This is done using two interleaved state machines.
130 	**	The input state machine is looking for things like
131 	**	hidden dots; the message state machine is handling
132 	**	the larger picture (e.g., header versus body).
133 	*/
134 
135 	buf = bp = bufbuf;
136 	buflen = sizeof bufbuf;
137 	pbp = peekbuf;
138 	istate = IS_BOL;
139 	mstate = SaveFrom ? MS_HEADER : MS_UFROM;
140 	CollectProgress = FALSE;
141 
142 	/* if transmitting binary, don't map NL to EOL */
143 	if (e->e_bodytype != NULL && strcasecmp(e->e_bodytype, "8BITMIME") == 0)
144 		e->e_flags |= EF_NL_NOT_EOL;
145 
146 	if (dbto != 0)
147 	{
148 		/* handle possible input timeout */
149 		if (setjmp(CtxCollectTimeout) != 0)
150 		{
151 #ifdef LOG
152 			syslog(LOG_NOTICE,
153 			    "timeout waiting for input from %s during message collect",
154 			    CurHostName ? CurHostName : "<local machine>");
155 #endif
156 			errno = 0;
157 			usrerr("451 timeout waiting for input during message collect");
158 			goto readerr;
159 		}
160 		CollectTimeout = setevent(dbto, collecttimeout, dbto);
161 	}
162 
163 	for (;;)
164 	{
165 		if (tTd(30, 35))
166 			printf("top, istate=%d, mstate=%d\n", istate, mstate);
167 		for (;;)
168 		{
169 			if (pbp > peekbuf)
170 				c = *--pbp;
171 			else
172 			{
173 				while (!feof(InChannel) && !ferror(InChannel))
174 				{
175 					errno = 0;
176 					c = fgetc(InChannel);
177 					if (errno != EINTR)
178 						break;
179 					clearerr(InChannel);
180 				}
181 				CollectProgress = TRUE;
182 				if (TrafficLogFile != NULL)
183 				{
184 					if (istate == IS_BOL)
185 						fprintf(TrafficLogFile, "%05d <<< ",
186 							getpid());
187 					if (c == EOF)
188 						fprintf(TrafficLogFile, "[EOF]\n");
189 					else
190 						fputc(c, TrafficLogFile);
191 				}
192 				if (c == EOF)
193 					goto readerr;
194 				if (SevenBitInput)
195 					c &= 0x7f;
196 				else
197 					HasEightBits |= bitset(0x80, c);
198 				e->e_msgsize++;
199 			}
200 			if (tTd(30, 94))
201 				printf("istate=%d, c=%c (0x%x)\n",
202 					istate, c, c);
203 			switch (istate)
204 			{
205 			  case IS_BOL:
206 				if (c == '.')
207 				{
208 					istate = IS_DOT;
209 					continue;
210 				}
211 				break;
212 
213 			  case IS_DOT:
214 				if (c == '\n' && !ignrdot &&
215 				    !bitset(EF_NL_NOT_EOL, e->e_flags))
216 					goto readerr;
217 				else if (c == '\r' &&
218 					 !bitset(EF_CRLF_NOT_EOL, e->e_flags))
219 				{
220 					istate = IS_DOTCR;
221 					continue;
222 				}
223 				else if (c != '.' ||
224 					 (OpMode != MD_SMTP &&
225 					  OpMode != MD_DAEMON &&
226 					  OpMode != MD_ARPAFTP))
227 				{
228 					*pbp++ = c;
229 					c = '.';
230 				}
231 				break;
232 
233 			  case IS_DOTCR:
234 				if (c == '\n')
235 					goto readerr;
236 				else
237 				{
238 					/* push back the ".\rx" */
239 					*pbp++ = c;
240 					*pbp++ = '\r';
241 					c = '.';
242 				}
243 				break;
244 
245 			  case IS_CR:
246 				if (c != '\n')
247 				{
248 					ungetc(c, InChannel);
249 					c = '\r';
250 				}
251 				else if (!bitset(EF_CRLF_NOT_EOL, e->e_flags))
252 					istate = IS_BOL;
253 				break;
254 			}
255 
256 			if (c == '\r')
257 			{
258 				istate = IS_CR;
259 				continue;
260 			}
261 			else if (c == '\n' && !bitset(EF_NL_NOT_EOL, e->e_flags))
262 				istate = IS_BOL;
263 			else
264 				istate = IS_NORM;
265 
266 			if (mstate == MS_BODY)
267 			{
268 				/* just put the character out */
269 				fputc(c, tf);
270 				continue;
271 			}
272 
273 			/* header -- buffer up */
274 			if (bp >= &buf[buflen - 2])
275 			{
276 				char *obuf;
277 
278 				if (mstate != MS_HEADER)
279 					break;
280 
281 				/* out of space for header */
282 				obuf = buf;
283 				if (buflen < MEMCHUNKSIZE)
284 					buflen *= 2;
285 				else
286 					buflen += MEMCHUNKSIZE;
287 				buf = xalloc(buflen);
288 				bcopy(obuf, buf, bp - obuf);
289 				bp = &buf[bp - obuf];
290 				if (obuf != bufbuf)
291 					free(obuf);
292 			}
293 			*bp++ = c;
294 			if (istate == IS_BOL)
295 				break;
296 		}
297 		*bp = '\0';
298 
299 nextstate:
300 		if (tTd(30, 35))
301 			printf("nextstate, istate=%d, mstate=%d, line = \"%s\"\n",
302 				istate, mstate, buf);
303 		switch (mstate)
304 		{
305 		  case MS_UFROM:
306 			mstate = MS_HEADER;
307 			if (strncmp(buf, "From ", 5) == 0)
308 			{
309 				eatfrom(buf, e);
310 				continue;
311 			}
312 			/* fall through */
313 
314 		  case MS_HEADER:
315 			if (!isheader(buf))
316 			{
317 				mstate = MS_BODY;
318 				goto nextstate;
319 			}
320 
321 			/* check for possible continuation line */
322 			do
323 			{
324 				clearerr(InChannel);
325 				errno = 0;
326 				c = fgetc(InChannel);
327 			} while (errno == EINTR);
328 			if (c != EOF)
329 				ungetc(c, InChannel);
330 			if (c == ' ' || c == '\t')
331 			{
332 				/* yep -- defer this */
333 				continue;
334 			}
335 
336 			/* trim off trailing CRLF or NL */
337 			if (*--bp != '\n' || *--bp != '\r')
338 				bp++;
339 			*bp = '\0';
340 			if (bitset(H_EOH, chompheader(buf, FALSE, e)))
341 				mstate = MS_BODY;
342 			break;
343 
344 		  case MS_BODY:
345 			if (tTd(30, 1))
346 				printf("EOH\n");
347 			if (headeronly)
348 				goto readerr;
349 			bp = buf;
350 
351 			/* toss blank line */
352 			if ((!bitset(EF_CRLF_NOT_EOL, e->e_flags) &&
353 				bp[0] == '\r' && bp[1] == '\n') ||
354 			    (!bitset(EF_NL_NOT_EOL, e->e_flags) &&
355 				bp[0] == '\n'))
356 			{
357 				break;
358 			}
359 
360 			/* if not a blank separator, write it out */
361 			while (*bp != '\0')
362 				fputc(*bp++, tf);
363 			break;
364 		}
365 		bp = buf;
366 	}
367 
368 readerr:
369 	if ((feof(fp) && smtpmode) || ferror(fp))
370 	{
371 		if (tTd(30, 1))
372 			printf("collect: read error\n");
373 		inputerr = TRUE;
374 	}
375 
376 	/* reset global timer */
377 	clrevent(CollectTimeout);
378 
379 	if (headeronly)
380 		return;
381 
382 	if (tf != NULL)
383 	{
384 		if (fflush(tf) != 0)
385 			tferror(tf, e);
386 		if (fsync(fileno(tf)) < 0 || fclose(tf) < 0)
387 		{
388 			tferror(tf, e);
389 			finis();
390 		}
391 	}
392 
393 	if (CollectErrorMessage != NULL && Errors <= 0)
394 	{
395 		if (CollectErrno != 0)
396 		{
397 			errno = CollectErrno;
398 			syserr(CollectErrorMessage, e->e_df);
399 			finis();
400 		}
401 		usrerr(CollectErrorMessage);
402 	}
403 	else if (inputerr && (OpMode == MD_SMTP || OpMode == MD_DAEMON))
404 	{
405 		/* An EOF when running SMTP is an error */
406 		char *host;
407 		char *problem;
408 
409 		host = RealHostName;
410 		if (host == NULL)
411 			host = "localhost";
412 
413 		if (feof(fp))
414 			problem = "unexpected close";
415 		else if (ferror(fp))
416 			problem = "I/O error";
417 		else
418 			problem = "read timeout";
419 # ifdef LOG
420 		if (LogLevel > 0 && feof(fp))
421 			syslog(LOG_NOTICE,
422 			    "collect: %s on connection from %s, sender=%s: %s\n",
423 			    problem, host, e->e_from.q_paddr, errstring(errno));
424 # endif
425 		if (feof(fp))
426 			usrerr("451 collect: %s on connection from %s, from=%s",
427 				problem, host, e->e_from.q_paddr);
428 		else
429 			syserr("451 collect: %s on connection from %s, from=%s",
430 				problem, host, e->e_from.q_paddr);
431 
432 		/* don't return an error indication */
433 		e->e_to = NULL;
434 		e->e_flags &= ~EF_FATALERRS;
435 		e->e_flags |= EF_CLRQUEUE;
436 
437 		/* and don't try to deliver the partial message either */
438 		if (InChild)
439 			ExitStat = EX_QUIT;
440 		finis();
441 	}
442 
443 	/*
444 	**  Find out some information from the headers.
445 	**	Examples are who is the from person & the date.
446 	*/
447 
448 	eatheader(e, !requeueflag);
449 
450 	/* collect statistics */
451 	if (OpMode != MD_VERIFY)
452 		markstats(e, (ADDRESS *) NULL);
453 
454 	/*
455 	**  Add an Apparently-To: line if we have no recipient lines.
456 	*/
457 
458 	if (hvalue("to", e->e_header) == NULL &&
459 	    hvalue("cc", e->e_header) == NULL &&
460 	    hvalue("bcc", e->e_header) == NULL &&
461 	    hvalue("apparently-to", e->e_header) == NULL)
462 	{
463 		register ADDRESS *q;
464 
465 		/* create an Apparently-To: field */
466 		/*    that or reject the message.... */
467 		for (q = e->e_sendqueue; q != NULL; q = q->q_next)
468 		{
469 			if (q->q_alias != NULL)
470 				continue;
471 			if (tTd(30, 3))
472 				printf("Adding Apparently-To: %s\n", q->q_paddr);
473 			addheader("Apparently-To", q->q_paddr, &e->e_header);
474 		}
475 	}
476 
477 	/* check for message too large */
478 	if (MaxMessageSize > 0 && e->e_msgsize > MaxMessageSize)
479 	{
480 		usrerr("552 Message exceeds maximum fixed size (%ld)",
481 			MaxMessageSize);
482 	}
483 
484 	/* check for illegal 8-bit data */
485 	if (HasEightBits)
486 	{
487 		e->e_flags |= EF_HAS8BIT;
488 		if (bitset(MM_MIME8BIT, MimeMode))
489 		{
490 			/* convert it to MIME */
491 			if (hvalue("MIME-Version", e->e_header) == NULL)
492 			{
493 				char mimebuf[20];
494 
495 				strcpy(mimebuf, "MIME-Version: 1.0");
496 				chompheader(mimebuf, FALSE, e);
497 			}
498 			if (e->e_bodytype == NULL)
499 				e->e_bodytype = "8BITMIME";
500 		}
501 		else if (!bitset(MM_PASS8BIT, MimeMode))
502 			usrerr("554 Eight bit data not allowed");
503 	}
504 
505 	if ((e->e_dfp = fopen(e->e_df, "r")) == NULL)
506 	{
507 		/* we haven't acked receipt yet, so just chuck this */
508 		syserr("Cannot reopen %s", e->e_df);
509 		finis();
510 	}
511 }
512 
513 
514 static
515 collecttimeout(timeout)
516 	time_t timeout;
517 {
518 	/* if no progress was made, die now */
519 	if (!CollectProgress)
520 		longjmp(CtxCollectTimeout, 1);
521 
522 	/* otherwise reset the timeout */
523 	CollectTimeout = setevent(timeout, collecttimeout, timeout);
524 	CollectProgress = FALSE;
525 }
526 /*
527 **  TFERROR -- signal error on writing the temporary file.
528 **
529 **	Parameters:
530 **		tf -- the file pointer for the temporary file.
531 **
532 **	Returns:
533 **		none.
534 **
535 **	Side Effects:
536 **		Gives an error message.
537 **		Arranges for following output to go elsewhere.
538 */
539 
540 tferror(tf, e)
541 	FILE *tf;
542 	register ENVELOPE *e;
543 {
544 	CollectErrno = errno;
545 	if (errno == ENOSPC)
546 	{
547 		struct stat st;
548 		long avail;
549 		long bsize;
550 
551 		e->e_flags |= EF_NORETURN;
552 		if (fstat(fileno(tf), &st) < 0)
553 			st.st_size = 0;
554 		(void) freopen(e->e_df, "w", tf);
555 		if (st.st_size <= 0)
556 			fprintf(tf, "\n*** Mail could not be accepted");
557 		else if (sizeof st.st_size > sizeof (long))
558 			fprintf(tf, "\n*** Mail of at least %qd bytes could not be accepted\n",
559 				st.st_size);
560 		else
561 			fprintf(tf, "\n*** Mail of at least %ld bytes could not be accepted\n",
562 				st.st_size);
563 		fprintf(tf, "*** at %s due to lack of disk space for temp file.\n",
564 			MyHostName);
565 		avail = freespace(QueueDir, &bsize);
566 		if (avail > 0)
567 		{
568 			if (bsize > 1024)
569 				avail *= bsize / 1024;
570 			else if (bsize < 1024)
571 				avail /= 1024 / bsize;
572 			fprintf(tf, "*** Currently, %ld kilobytes are available for mail temp files.\n",
573 				avail);
574 		}
575 		CollectErrorMessage = "452 Out of disk space for temp file";
576 	}
577 	else
578 	{
579 		CollectErrorMessage = "cannot write message body to disk (%s)";
580 	}
581 	(void) freopen("/dev/null", "w", tf);
582 }
583 /*
584 **  EATFROM -- chew up a UNIX style from line and process
585 **
586 **	This does indeed make some assumptions about the format
587 **	of UNIX messages.
588 **
589 **	Parameters:
590 **		fm -- the from line.
591 **
592 **	Returns:
593 **		none.
594 **
595 **	Side Effects:
596 **		extracts what information it can from the header,
597 **		such as the date.
598 */
599 
600 # ifndef NOTUNIX
601 
602 char	*DowList[] =
603 {
604 	"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", NULL
605 };
606 
607 char	*MonthList[] =
608 {
609 	"Jan", "Feb", "Mar", "Apr", "May", "Jun",
610 	"Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
611 	NULL
612 };
613 
614 eatfrom(fm, e)
615 	char *fm;
616 	register ENVELOPE *e;
617 {
618 	register char *p;
619 	register char **dt;
620 
621 	if (tTd(30, 2))
622 		printf("eatfrom(%s)\n", fm);
623 
624 	/* find the date part */
625 	p = fm;
626 	while (*p != '\0')
627 	{
628 		/* skip a word */
629 		while (*p != '\0' && *p != ' ')
630 			p++;
631 		while (*p == ' ')
632 			p++;
633 		if (!(isascii(*p) && isupper(*p)) ||
634 		    p[3] != ' ' || p[13] != ':' || p[16] != ':')
635 			continue;
636 
637 		/* we have a possible date */
638 		for (dt = DowList; *dt != NULL; dt++)
639 			if (strncmp(*dt, p, 3) == 0)
640 				break;
641 		if (*dt == NULL)
642 			continue;
643 
644 		for (dt = MonthList; *dt != NULL; dt++)
645 			if (strncmp(*dt, &p[4], 3) == 0)
646 				break;
647 		if (*dt != NULL)
648 			break;
649 	}
650 
651 	if (*p != '\0')
652 	{
653 		char *q;
654 		extern char *arpadate();
655 
656 		/* we have found a date */
657 		q = xalloc(25);
658 		(void) strncpy(q, p, 25);
659 		q[24] = '\0';
660 		q = arpadate(q);
661 		define('a', newstr(q), e);
662 	}
663 }
664 
665 # endif /* NOTUNIX */
666