xref: /freebsd/contrib/sendmail/src/collect.c (revision 81d1ffee089aab2652954909acbe6aadd8a1a72c)
1 /*
2  * Copyright (c) 1998-2002 Sendmail, Inc. and its suppliers.
3  *	All rights reserved.
4  * Copyright (c) 1983, 1995-1997 Eric P. Allman.  All rights reserved.
5  * Copyright (c) 1988, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * By using this file, you agree to the terms and conditions set
9  * forth in the LICENSE file which can be found at the top level of
10  * the sendmail distribution.
11  *
12  */
13 
14 #include <sendmail.h>
15 
16 SM_RCSID("@(#)$Id: collect.c,v 8.242.2.3 2002/12/03 17:06:30 gshapiro Exp $")
17 
18 static void	collecttimeout __P((time_t));
19 static void	dferror __P((SM_FILE_T *volatile, char *, ENVELOPE *));
20 static void	eatfrom __P((char *volatile, ENVELOPE *));
21 static void	collect_doheader __P((ENVELOPE *));
22 static SM_FILE_T *collect_dfopen __P((ENVELOPE *));
23 static SM_FILE_T *collect_eoh __P((ENVELOPE *, int, int));
24 
25 /*
26 **  COLLECT_EOH -- end-of-header processing in collect()
27 **
28 **	Called by collect() when it encounters the blank line
29 **	separating the header from the message body, or when it
30 **	encounters EOF in a message that contains only a header.
31 **
32 **	Parameters:
33 **		e -- envelope
34 **		numhdrs -- number of headers
35 **		hdrslen -- length of headers
36 **
37 **	Results:
38 **		NULL, or handle to open data file
39 **
40 **	Side Effects:
41 **		end-of-header check ruleset is invoked.
42 **		envelope state is updated.
43 **		headers may be added and deleted.
44 **		selects the queue.
45 **		opens the data file.
46 */
47 
48 static SM_FILE_T *
49 collect_eoh(e, numhdrs, hdrslen)
50 	ENVELOPE *e;
51 	int numhdrs;
52 	int hdrslen;
53 {
54 	char hnum[16];
55 	char hsize[16];
56 
57 	/* call the end-of-header check ruleset */
58 	(void) sm_snprintf(hnum, sizeof hnum, "%d", numhdrs);
59 	(void) sm_snprintf(hsize, sizeof hsize, "%d", hdrslen);
60 	if (tTd(30, 10))
61 		sm_dprintf("collect: rscheck(\"check_eoh\", \"%s $| %s\")\n",
62 			   hnum, hsize);
63 	(void) rscheck("check_eoh", hnum, hsize, e, RSF_UNSTRUCTURED|RSF_COUNT,
64 			3, NULL, e->e_id);
65 
66 	/*
67 	**  Process the header,
68 	**  select the queue, open the data file.
69 	*/
70 
71 	collect_doheader(e);
72 	return collect_dfopen(e);
73 }
74 
75 /*
76 **  COLLECT_DOHEADER -- process header in collect()
77 **
78 **	Called by collect() after it has finished parsing the header,
79 **	but before it selects the queue and creates the data file.
80 **	The results of processing the header will affect queue selection.
81 **
82 **	Parameters:
83 **		e -- envelope
84 **
85 **	Results:
86 **		none.
87 **
88 **	Side Effects:
89 **		envelope state is updated.
90 **		headers may be added and deleted.
91 */
92 
93 static void
94 collect_doheader(e)
95 	ENVELOPE *e;
96 {
97 	/*
98 	**  Find out some information from the headers.
99 	**	Examples are who is the from person & the date.
100 	*/
101 
102 	eatheader(e, true, false);
103 
104 	if (GrabTo && e->e_sendqueue == NULL)
105 		usrerr("No recipient addresses found in header");
106 
107 	/*
108 	**  If we have a Return-Receipt-To:, turn it into a DSN.
109 	*/
110 
111 	if (RrtImpliesDsn && hvalue("return-receipt-to", e->e_header) != NULL)
112 	{
113 		ADDRESS *q;
114 
115 		for (q = e->e_sendqueue; q != NULL; q = q->q_next)
116 			if (!bitset(QHASNOTIFY, q->q_flags))
117 				q->q_flags |= QHASNOTIFY|QPINGONSUCCESS;
118 	}
119 
120 	/*
121 	**  Add an appropriate recipient line if we have none.
122 	*/
123 
124 	if (hvalue("to", e->e_header) != NULL ||
125 	    hvalue("cc", e->e_header) != NULL ||
126 	    hvalue("apparently-to", e->e_header) != NULL)
127 	{
128 		/* have a valid recipient header -- delete Bcc: headers */
129 		e->e_flags |= EF_DELETE_BCC;
130 	}
131 	else if (hvalue("bcc", e->e_header) == NULL)
132 	{
133 		/* no valid recipient headers */
134 		register ADDRESS *q;
135 		char *hdr = NULL;
136 
137 		/* create a recipient field */
138 		switch (NoRecipientAction)
139 		{
140 		  case NRA_ADD_APPARENTLY_TO:
141 			hdr = "Apparently-To";
142 			break;
143 
144 		  case NRA_ADD_TO:
145 			hdr = "To";
146 			break;
147 
148 		  case NRA_ADD_BCC:
149 			addheader("Bcc", " ", 0, e);
150 			break;
151 
152 		  case NRA_ADD_TO_UNDISCLOSED:
153 			addheader("To", "undisclosed-recipients:;", 0, e);
154 			break;
155 		}
156 
157 		if (hdr != NULL)
158 		{
159 			for (q = e->e_sendqueue; q != NULL; q = q->q_next)
160 			{
161 				if (q->q_alias != NULL)
162 					continue;
163 				if (tTd(30, 3))
164 					sm_dprintf("Adding %s: %s\n",
165 						hdr, q->q_paddr);
166 				addheader(hdr, q->q_paddr, 0, e);
167 			}
168 		}
169 	}
170 }
171 
172 /*
173 **  COLLECT_DFOPEN -- open the message data file
174 **
175 **	Called by collect() after it has finished processing the header.
176 **	Queue selection occurs at this point, possibly based on the
177 **	envelope's recipient list and on header information.
178 **
179 **	Parameters:
180 **		e -- envelope
181 **
182 **	Results:
183 **		NULL, or a pointer to an open data file,
184 **		into which the message body will be written by collect().
185 **
186 **	Side Effects:
187 **		Calls syserr, sets EF_FATALERRS and returns NULL
188 **		if there is insufficient disk space.
189 **		Aborts process if data file could not be opened.
190 **		Otherwise, the queue is selected,
191 **		e->e_{dfino,dfdev,msgsize,flags} are updated,
192 **		and a pointer to an open data file is returned.
193 */
194 
195 static SM_FILE_T *
196 collect_dfopen(e)
197 	ENVELOPE *e;
198 {
199 	MODE_T oldumask = 0;
200 	int dfd;
201 	struct stat stbuf;
202 	SM_FILE_T *df;
203 	char *dfname;
204 
205 	if (!setnewqueue(e))
206 		return NULL;
207 
208 	dfname = queuename(e, DATAFL_LETTER);
209 	if (bitset(S_IWGRP, QueueFileMode))
210 		oldumask = umask(002);
211 	df = bfopen(dfname, QueueFileMode, DataFileBufferSize,
212 		    SFF_OPENASROOT);
213 	if (bitset(S_IWGRP, QueueFileMode))
214 		(void) umask(oldumask);
215 	if (df == NULL)
216 	{
217 		syserr("@Cannot create %s", dfname);
218 		e->e_flags |= EF_NO_BODY_RETN;
219 		flush_errors(true);
220 		finis(true, true, ExitStat);
221 		/* NOTREACHED */
222 	}
223 	dfd = sm_io_getinfo(df, SM_IO_WHAT_FD, NULL);
224 	if (dfd < 0 || fstat(dfd, &stbuf) < 0)
225 		e->e_dfino = -1;
226 	else
227 	{
228 		e->e_dfdev = stbuf.st_dev;
229 		e->e_dfino = stbuf.st_ino;
230 	}
231 	e->e_flags |= EF_HAS_DF;
232 	return df;
233 }
234 
235 /*
236 **  COLLECT -- read & parse message header & make temp file.
237 **
238 **	Creates a temporary file name and copies the standard
239 **	input to that file.  Leading UNIX-style "From" lines are
240 **	stripped off (after important information is extracted).
241 **
242 **	Parameters:
243 **		fp -- file to read.
244 **		smtpmode -- if set, we are running SMTP: give an RFC821
245 **			style message to say we are ready to collect
246 **			input, and never ignore a single dot to mean
247 **			end of message.
248 **		hdrp -- the location to stash the header.
249 **		e -- the current envelope.
250 **
251 **	Returns:
252 **		none.
253 **
254 **	Side Effects:
255 **		If successful,
256 **		- Data file is created and filled, and e->e_dfp is set.
257 **		- The from person may be set.
258 **		If the "enough disk space" check fails,
259 **		- syserr is called.
260 **		- e->e_dfp is NULL.
261 **		- e->e_flags & EF_FATALERRS is set.
262 **		- collect() returns.
263 **		If data file cannot be created, the process is terminated.
264 */
265 
266 static jmp_buf	CtxCollectTimeout;
267 static bool	volatile CollectProgress;
268 static SM_EVENT	*volatile CollectTimeout = NULL;
269 
270 /* values for input state machine */
271 #define IS_NORM		0	/* middle of line */
272 #define IS_BOL		1	/* beginning of line */
273 #define IS_DOT		2	/* read a dot at beginning of line */
274 #define IS_DOTCR	3	/* read ".\r" at beginning of line */
275 #define IS_CR		4	/* read a carriage return */
276 
277 /* values for message state machine */
278 #define MS_UFROM	0	/* reading Unix from line */
279 #define MS_HEADER	1	/* reading message header */
280 #define MS_BODY		2	/* reading message body */
281 #define MS_DISCARD	3	/* discarding rest of message */
282 
283 void
284 collect(fp, smtpmode, hdrp, e)
285 	SM_FILE_T *fp;
286 	bool smtpmode;
287 	HDR **hdrp;
288 	register ENVELOPE *e;
289 {
290 	register SM_FILE_T *volatile df;
291 	volatile bool ignrdot;
292 	volatile time_t dbto;
293 	register char *volatile bp;
294 	volatile int c;
295 	volatile bool inputerr;
296 	bool headeronly;
297 	char *volatile buf;
298 	volatile int buflen;
299 	volatile int istate;
300 	volatile int mstate;
301 	volatile int hdrslen;
302 	volatile int numhdrs;
303 	volatile int afd;
304 	unsigned char *volatile pbp;
305 	unsigned char peekbuf[8];
306 	char bufbuf[MAXLINE];
307 
308 	df = NULL;
309 	ignrdot = smtpmode ? false : IgnrDot;
310 	dbto = smtpmode ? TimeOuts.to_datablock : 0;
311 	c = SM_IO_EOF;
312 	inputerr = false;
313 	headeronly = hdrp != NULL;
314 	hdrslen = 0;
315 	numhdrs = 0;
316 	HasEightBits = false;
317 	buf = bp = bufbuf;
318 	buflen = sizeof bufbuf;
319 	pbp = peekbuf;
320 	istate = IS_BOL;
321 	mstate = SaveFrom ? MS_HEADER : MS_UFROM;
322 	CollectProgress = false;
323 
324 	/*
325 	**  Tell ARPANET to go ahead.
326 	*/
327 
328 	if (smtpmode)
329 		message("354 Enter mail, end with \".\" on a line by itself");
330 
331 	if (tTd(30, 2))
332 		sm_dprintf("collect\n");
333 
334 	/*
335 	**  Read the message.
336 	**
337 	**	This is done using two interleaved state machines.
338 	**	The input state machine is looking for things like
339 	**	hidden dots; the message state machine is handling
340 	**	the larger picture (e.g., header versus body).
341 	*/
342 
343 	if (dbto != 0)
344 	{
345 		/* handle possible input timeout */
346 		if (setjmp(CtxCollectTimeout) != 0)
347 		{
348 			if (LogLevel > 2)
349 				sm_syslog(LOG_NOTICE, e->e_id,
350 					  "timeout waiting for input from %s during message collect",
351 					  CURHOSTNAME);
352 			errno = 0;
353 			if (smtpmode)
354 			{
355 				/*
356 				**  Override e_message in usrerr() as this
357 				**  is the reason for failure that should
358 				**  be logged for undelivered recipients.
359 				*/
360 
361 				e->e_message = NULL;
362 			}
363 			usrerr("451 4.4.1 timeout waiting for input during message collect");
364 			goto readerr;
365 		}
366 		CollectTimeout = sm_setevent(dbto, collecttimeout, dbto);
367 	}
368 
369 	e->e_msgsize = 0;
370 	for (;;)
371 	{
372 		if (tTd(30, 35))
373 			sm_dprintf("top, istate=%d, mstate=%d\n", istate,
374 				   mstate);
375 		for (;;)
376 		{
377 			if (pbp > peekbuf)
378 				c = *--pbp;
379 			else
380 			{
381 				while (!sm_io_eof(fp) && !sm_io_error(fp))
382 				{
383 					errno = 0;
384 					c = sm_io_getc(fp, SM_TIME_DEFAULT);
385 					if (c == SM_IO_EOF && errno == EINTR)
386 					{
387 						/* Interrupted, retry */
388 						sm_io_clearerr(fp);
389 						continue;
390 					}
391 					break;
392 				}
393 				CollectProgress = true;
394 				if (TrafficLogFile != NULL && !headeronly)
395 				{
396 					if (istate == IS_BOL)
397 						(void) sm_io_fprintf(TrafficLogFile,
398 							SM_TIME_DEFAULT,
399 							"%05d <<< ",
400 							(int) CurrentPid);
401 					if (c == SM_IO_EOF)
402 						(void) sm_io_fprintf(TrafficLogFile,
403 							SM_TIME_DEFAULT,
404 							"[EOF]\n");
405 					else
406 						(void) sm_io_putc(TrafficLogFile,
407 							SM_TIME_DEFAULT,
408 							c);
409 				}
410 				if (c == SM_IO_EOF)
411 					goto readerr;
412 				if (SevenBitInput)
413 					c &= 0x7f;
414 				else
415 					HasEightBits |= bitset(0x80, c);
416 			}
417 			if (tTd(30, 94))
418 				sm_dprintf("istate=%d, c=%c (0x%x)\n",
419 					istate, (char) c, c);
420 			switch (istate)
421 			{
422 			  case IS_BOL:
423 				if (c == '.')
424 				{
425 					istate = IS_DOT;
426 					continue;
427 				}
428 				break;
429 
430 			  case IS_DOT:
431 				if (c == '\n' && !ignrdot &&
432 				    !bitset(EF_NL_NOT_EOL, e->e_flags))
433 					goto readerr;
434 				else if (c == '\r' &&
435 					 !bitset(EF_CRLF_NOT_EOL, e->e_flags))
436 				{
437 					istate = IS_DOTCR;
438 					continue;
439 				}
440 				else if (ignrdot ||
441 					 (c != '.' &&
442 					  OpMode != MD_SMTP &&
443 					  OpMode != MD_DAEMON &&
444 					  OpMode != MD_ARPAFTP))
445 
446 				{
447 					*pbp++ = c;
448 					c = '.';
449 				}
450 				break;
451 
452 			  case IS_DOTCR:
453 				if (c == '\n' && !ignrdot)
454 					goto readerr;
455 				else
456 				{
457 					/* push back the ".\rx" */
458 					*pbp++ = c;
459 					if (OpMode != MD_SMTP &&
460 					    OpMode != MD_DAEMON &&
461 					    OpMode != MD_ARPAFTP)
462 					{
463 						*pbp++ = '\r';
464 						c = '.';
465 					}
466 					else
467 						c = '\r';
468 				}
469 				break;
470 
471 			  case IS_CR:
472 				if (c == '\n')
473 					istate = IS_BOL;
474 				else
475 				{
476 					(void) sm_io_ungetc(fp, SM_TIME_DEFAULT,
477 							    c);
478 					c = '\r';
479 					istate = IS_NORM;
480 				}
481 				goto bufferchar;
482 			}
483 
484 			if (c == '\r' && !bitset(EF_CRLF_NOT_EOL, e->e_flags))
485 			{
486 				istate = IS_CR;
487 				continue;
488 			}
489 			else if (c == '\n' && !bitset(EF_NL_NOT_EOL,
490 						      e->e_flags))
491 				istate = IS_BOL;
492 			else
493 				istate = IS_NORM;
494 
495 bufferchar:
496 			if (!headeronly)
497 			{
498 				/* no overflow? */
499 				if (e->e_msgsize >= 0)
500 				{
501 					e->e_msgsize++;
502 					if (MaxMessageSize > 0 &&
503 					    !bitset(EF_TOOBIG, e->e_flags) &&
504 					    e->e_msgsize > MaxMessageSize)
505 						 e->e_flags |= EF_TOOBIG;
506 				}
507 			}
508 			switch (mstate)
509 			{
510 			  case MS_BODY:
511 				/* just put the character out */
512 				if (!bitset(EF_TOOBIG, e->e_flags))
513 					(void) sm_io_putc(df, SM_TIME_DEFAULT,
514 							  c);
515 
516 				/* FALLTHROUGH */
517 
518 			  case MS_DISCARD:
519 				continue;
520 			}
521 
522 			/* header -- buffer up */
523 			if (bp >= &buf[buflen - 2])
524 			{
525 				char *obuf;
526 
527 				if (mstate != MS_HEADER)
528 					break;
529 
530 				/* out of space for header */
531 				obuf = buf;
532 				if (buflen < MEMCHUNKSIZE)
533 					buflen *= 2;
534 				else
535 					buflen += MEMCHUNKSIZE;
536 				buf = xalloc(buflen);
537 				memmove(buf, obuf, bp - obuf);
538 				bp = &buf[bp - obuf];
539 				if (obuf != bufbuf)
540 					sm_free(obuf);  /* XXX */
541 			}
542 
543 			/*
544 			**  XXX Notice: the logic here is broken.
545 			**  An input to sendmail that doesn't contain a
546 			**  header but starts immediately with the body whose
547 			**  first line contain characters which match the
548 			**  following "if" will cause problems: those
549 			**  characters will NOT appear in the output...
550 			**  Do we care?
551 			*/
552 
553 			if (c >= 0200 && c <= 0237)
554 			{
555 #if 0	/* causes complaints -- figure out something for 8.n+1 */
556 				usrerr("Illegal character 0x%x in header", c);
557 #else /* 0 */
558 				/* EMPTY */
559 #endif /* 0 */
560 			}
561 			else if (c != '\0')
562 			{
563 				*bp++ = c;
564 				++hdrslen;
565 				if (!headeronly &&
566 				    MaxHeadersLength > 0 &&
567 				    hdrslen > MaxHeadersLength)
568 				{
569 					sm_syslog(LOG_NOTICE, e->e_id,
570 						  "headers too large (%d max) from %s during message collect",
571 						  MaxHeadersLength,
572 						  CURHOSTNAME);
573 					errno = 0;
574 					e->e_flags |= EF_CLRQUEUE;
575 					e->e_status = "5.6.0";
576 					usrerrenh(e->e_status,
577 						  "552 Headers too large (%d max)",
578 						  MaxHeadersLength);
579 					mstate = MS_DISCARD;
580 				}
581 			}
582 			if (istate == IS_BOL)
583 				break;
584 		}
585 		*bp = '\0';
586 
587 nextstate:
588 		if (tTd(30, 35))
589 			sm_dprintf("nextstate, istate=%d, mstate=%d, line = \"%s\"\n",
590 				istate, mstate, buf);
591 		switch (mstate)
592 		{
593 		  case MS_UFROM:
594 			mstate = MS_HEADER;
595 #ifndef NOTUNIX
596 			if (strncmp(buf, "From ", 5) == 0)
597 			{
598 				bp = buf;
599 				eatfrom(buf, e);
600 				continue;
601 			}
602 #endif /* ! NOTUNIX */
603 			/* FALLTHROUGH */
604 
605 		  case MS_HEADER:
606 			if (!isheader(buf))
607 			{
608 				mstate = MS_BODY;
609 				goto nextstate;
610 			}
611 
612 			/* check for possible continuation line */
613 			do
614 			{
615 				sm_io_clearerr(fp);
616 				errno = 0;
617 				c = sm_io_getc(fp, SM_TIME_DEFAULT);
618 			} while (c == SM_IO_EOF && errno == EINTR);
619 			if (c != SM_IO_EOF)
620 				(void) sm_io_ungetc(fp, SM_TIME_DEFAULT, c);
621 			if (c == ' ' || c == '\t')
622 			{
623 				/* yep -- defer this */
624 				continue;
625 			}
626 
627 			/* trim off trailing CRLF or NL */
628 			if (*--bp != '\n' || *--bp != '\r')
629 				bp++;
630 			*bp = '\0';
631 
632 			if (bitset(H_EOH, chompheader(buf,
633 						      CHHDR_CHECK | CHHDR_USER,
634 						      hdrp, e)))
635 			{
636 				mstate = MS_BODY;
637 				goto nextstate;
638 			}
639 			numhdrs++;
640 			break;
641 
642 		  case MS_BODY:
643 			if (tTd(30, 1))
644 				sm_dprintf("EOH\n");
645 
646 			if (headeronly)
647 				goto readerr;
648 
649 			df = collect_eoh(e, numhdrs, hdrslen);
650 			if (df == NULL)
651 				e->e_flags |= EF_TOOBIG;
652 
653 			bp = buf;
654 
655 			/* toss blank line */
656 			if ((!bitset(EF_CRLF_NOT_EOL, e->e_flags) &&
657 				bp[0] == '\r' && bp[1] == '\n') ||
658 			    (!bitset(EF_NL_NOT_EOL, e->e_flags) &&
659 				bp[0] == '\n'))
660 			{
661 				break;
662 			}
663 
664 			/* if not a blank separator, write it out */
665 			if (!bitset(EF_TOOBIG, e->e_flags))
666 			{
667 				while (*bp != '\0')
668 					(void) sm_io_putc(df, SM_TIME_DEFAULT,
669 							  *bp++);
670 			}
671 			break;
672 		}
673 		bp = buf;
674 	}
675 
676 readerr:
677 	if ((sm_io_eof(fp) && smtpmode) || sm_io_error(fp))
678 	{
679 		const char *errmsg;
680 
681 		if (sm_io_eof(fp))
682 			errmsg = "unexpected close";
683 		else
684 			errmsg = sm_errstring(errno);
685 		if (tTd(30, 1))
686 			sm_dprintf("collect: premature EOM: %s\n", errmsg);
687 		if (LogLevel > 1)
688 			sm_syslog(LOG_WARNING, e->e_id,
689 				"collect: premature EOM: %s", errmsg);
690 		inputerr = true;
691 	}
692 
693 	/* reset global timer */
694 	if (CollectTimeout != NULL)
695 		sm_clrevent(CollectTimeout);
696 
697 	if (headeronly)
698 		return;
699 
700 	if (mstate != MS_BODY)
701 	{
702 		/* no body or discard, so we never opened the data file */
703 		SM_ASSERT(df == NULL);
704 		df = collect_eoh(e, numhdrs, hdrslen);
705 	}
706 
707 	if (df == NULL)
708 	{
709 		/* skip next few clauses */
710 		/* EMPTY */
711 	}
712 	else if (sm_io_flush(df, SM_TIME_DEFAULT) != 0 || sm_io_error(df))
713 	{
714 		dferror(df, "sm_io_flush||sm_io_error", e);
715 		flush_errors(true);
716 		finis(true, true, ExitStat);
717 		/* NOTREACHED */
718 	}
719 	else if (SuperSafe != SAFE_REALLY)
720 	{
721 		/* skip next few clauses */
722 		/* EMPTY */
723 	}
724 	else if (sm_io_setinfo(df, SM_BF_COMMIT, NULL) < 0 && errno != EINVAL)
725 	{
726 		int save_errno = errno;
727 
728 		if (save_errno == EEXIST)
729 		{
730 			char *dfile;
731 			struct stat st;
732 			int dfd;
733 
734 			dfile = queuename(e, DATAFL_LETTER);
735 			if (stat(dfile, &st) < 0)
736 				st.st_size = -1;
737 			errno = EEXIST;
738 			syserr("@collect: bfcommit(%s): already on disk, size = %ld",
739 			       dfile, (long) st.st_size);
740 			dfd = sm_io_getinfo(df, SM_IO_WHAT_FD, NULL);
741 			if (dfd >= 0)
742 				dumpfd(dfd, true, true);
743 		}
744 		errno = save_errno;
745 		dferror(df, "bfcommit", e);
746 		flush_errors(true);
747 		finis(save_errno != EEXIST, true, ExitStat);
748 	}
749 	else if ((afd = sm_io_getinfo(df, SM_IO_WHAT_FD, NULL)) >= 0 &&
750 		 fsync(afd) < 0)
751 	{
752 		dferror(df, "fsync", e);
753 		flush_errors(true);
754 		finis(true, true, ExitStat);
755 		/* NOTREACHED */
756 	}
757 	else if (sm_io_close(df, SM_TIME_DEFAULT) < 0)
758 	{
759 		dferror(df, "sm_io_close", e);
760 		flush_errors(true);
761 		finis(true, true, ExitStat);
762 		/* NOTREACHED */
763 	}
764 	else
765 	{
766 		/* everything is happily flushed to disk */
767 		df = NULL;
768 
769 		/* remove from available space in filesystem */
770 		updfs(e, false, true);
771 	}
772 
773 	/* An EOF when running SMTP is an error */
774 	if (inputerr && (OpMode == MD_SMTP || OpMode == MD_DAEMON))
775 	{
776 		char *host;
777 		char *problem;
778 		ADDRESS *q;
779 
780 		host = RealHostName;
781 		if (host == NULL)
782 			host = "localhost";
783 
784 		if (sm_io_eof(fp))
785 			problem = "unexpected close";
786 		else if (sm_io_error(fp))
787 			problem = "I/O error";
788 		else
789 			problem = "read timeout";
790 		if (LogLevel > 0 && sm_io_eof(fp))
791 			sm_syslog(LOG_NOTICE, e->e_id,
792 				"collect: %s on connection from %.100s, sender=%s",
793 				problem, host,
794 				shortenstring(e->e_from.q_paddr, MAXSHORTSTR));
795 		if (sm_io_eof(fp))
796 			usrerr("451 4.4.1 collect: %s on connection from %s, from=%s",
797 				problem, host,
798 				shortenstring(e->e_from.q_paddr, MAXSHORTSTR));
799 		else
800 			syserr("451 4.4.1 collect: %s on connection from %s, from=%s",
801 				problem, host,
802 				shortenstring(e->e_from.q_paddr, MAXSHORTSTR));
803 
804 		/* don't return an error indication */
805 		e->e_to = NULL;
806 		e->e_flags &= ~EF_FATALERRS;
807 		e->e_flags |= EF_CLRQUEUE;
808 
809 		/* Don't send any message notification to sender */
810 		for (q = e->e_sendqueue; q != NULL; q = q->q_next)
811 		{
812 			if (QS_IS_DEAD(q->q_state))
813 				continue;
814 			q->q_state = QS_FATALERR;
815 		}
816 
817 		finis(true, true, ExitStat);
818 		/* NOTREACHED */
819 	}
820 
821 	/* Log collection information. */
822 	if (bitset(EF_LOGSENDER, e->e_flags) && LogLevel > 4)
823 	{
824 		logsender(e, e->e_msgid);
825 		e->e_flags &= ~EF_LOGSENDER;
826 	}
827 
828 	/* check for message too large */
829 	if (bitset(EF_TOOBIG, e->e_flags))
830 	{
831 		e->e_flags |= EF_NO_BODY_RETN|EF_CLRQUEUE;
832 		if (!bitset(EF_FATALERRS, e->e_flags))
833 		{
834 			e->e_status = "5.2.3";
835 			usrerrenh(e->e_status,
836 				"552 Message exceeds maximum fixed size (%ld)",
837 				MaxMessageSize);
838 			if (LogLevel > 6)
839 				sm_syslog(LOG_NOTICE, e->e_id,
840 					"message size (%ld) exceeds maximum (%ld)",
841 					e->e_msgsize, MaxMessageSize);
842 		}
843 	}
844 
845 	/* check for illegal 8-bit data */
846 	if (HasEightBits)
847 	{
848 		e->e_flags |= EF_HAS8BIT;
849 		if (!bitset(MM_PASS8BIT|MM_MIME8BIT, MimeMode) &&
850 		    !bitset(EF_IS_MIME, e->e_flags))
851 		{
852 			e->e_status = "5.6.1";
853 			usrerrenh(e->e_status, "554 Eight bit data not allowed");
854 		}
855 	}
856 	else
857 	{
858 		/* if it claimed to be 8 bits, well, it lied.... */
859 		if (e->e_bodytype != NULL &&
860 		    sm_strcasecmp(e->e_bodytype, "8BITMIME") == 0)
861 			e->e_bodytype = "7BIT";
862 	}
863 
864 	if (SuperSafe == SAFE_REALLY && !bitset(EF_FATALERRS, e->e_flags))
865 	{
866 		char *dfname = queuename(e, DATAFL_LETTER);
867 		if ((e->e_dfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, dfname,
868 					   SM_IO_RDONLY, NULL)) == NULL)
869 		{
870 			/* we haven't acked receipt yet, so just chuck this */
871 			syserr("@Cannot reopen %s", dfname);
872 			finis(true, true, ExitStat);
873 			/* NOTREACHED */
874 		}
875 	}
876 	else
877 		e->e_dfp = df;
878 
879 	/* collect statistics */
880 	if (OpMode != MD_VERIFY)
881 		markstats(e, (ADDRESS *) NULL, STATS_NORMAL);
882 }
883 
884 static void
885 collecttimeout(timeout)
886 	time_t timeout;
887 {
888 	int save_errno = errno;
889 
890 	/*
891 	**  NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER.  DO NOT ADD
892 	**	ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
893 	**	DOING.
894 	*/
895 
896 	if (CollectProgress)
897 	{
898 		/* reset the timeout */
899 		CollectTimeout = sm_sigsafe_setevent(timeout, collecttimeout,
900 						     timeout);
901 		CollectProgress = false;
902 	}
903 	else
904 	{
905 		/* event is done */
906 		CollectTimeout = NULL;
907 	}
908 
909 	/* if no progress was made or problem resetting event, die now */
910 	if (CollectTimeout == NULL)
911 	{
912 		errno = ETIMEDOUT;
913 		longjmp(CtxCollectTimeout, 1);
914 	}
915 	errno = save_errno;
916 }
917 /*
918 **  DFERROR -- signal error on writing the data file.
919 **
920 **	Called by collect().  Collect() always terminates the process
921 **	immediately after calling dferror(), which means that the SMTP
922 **	session will be terminated, which means that any error message
923 **	issued by dferror must be a 421 error, as per RFC 821.
924 **
925 **	Parameters:
926 **		df -- the file pointer for the data file.
927 **		msg -- detailed message.
928 **		e -- the current envelope.
929 **
930 **	Returns:
931 **		none.
932 **
933 **	Side Effects:
934 **		Gives an error message.
935 **		Arranges for following output to go elsewhere.
936 */
937 
938 static void
939 dferror(df, msg, e)
940 	SM_FILE_T *volatile df;
941 	char *msg;
942 	register ENVELOPE *e;
943 {
944 	char *dfname;
945 
946 	dfname = queuename(e, DATAFL_LETTER);
947 	setstat(EX_IOERR);
948 	if (errno == ENOSPC)
949 	{
950 #if STAT64 > 0
951 		struct stat64 st;
952 #else /* STAT64 > 0 */
953 		struct stat st;
954 #endif /* STAT64 > 0 */
955 		long avail;
956 		long bsize;
957 
958 		e->e_flags |= EF_NO_BODY_RETN;
959 
960 		if (
961 #if STAT64 > 0
962 		    fstat64(sm_io_getinfo(df, SM_IO_WHAT_FD, NULL), &st)
963 #else /* STAT64 > 0 */
964 		    fstat(sm_io_getinfo(df, SM_IO_WHAT_FD, NULL), &st)
965 #endif /* STAT64 > 0 */
966 		    < 0)
967 		  st.st_size = 0;
968 		(void) sm_io_reopen(SmFtStdio, SM_TIME_DEFAULT, dfname,
969 				    SM_IO_WRONLY, NULL, df);
970 		if (st.st_size <= 0)
971 			(void) sm_io_fprintf(df, SM_TIME_DEFAULT,
972 				"\n*** Mail could not be accepted");
973 		else
974 			(void) sm_io_fprintf(df, SM_TIME_DEFAULT,
975 				"\n*** Mail of at least %llu bytes could not be accepted\n",
976 				(ULONGLONG_T) st.st_size);
977 		(void) sm_io_fprintf(df, SM_TIME_DEFAULT,
978 			"*** at %s due to lack of disk space for temp file.\n",
979 			MyHostName);
980 		avail = freediskspace(qid_printqueue(e->e_qgrp, e->e_qdir),
981 				      &bsize);
982 		if (avail > 0)
983 		{
984 			if (bsize > 1024)
985 				avail *= bsize / 1024;
986 			else if (bsize < 1024)
987 				avail /= 1024 / bsize;
988 			(void) sm_io_fprintf(df, SM_TIME_DEFAULT,
989 				"*** Currently, %ld kilobytes are available for mail temp files.\n",
990 				avail);
991 		}
992 #if 0
993 		/* Wrong response code; should be 421. */
994 		e->e_status = "4.3.1";
995 		usrerrenh(e->e_status, "452 Out of disk space for temp file");
996 #else /* 0 */
997 		syserr("421 4.3.1 Out of disk space for temp file");
998 #endif /* 0 */
999 	}
1000 	else
1001 		syserr("421 4.3.0 collect: Cannot write %s (%s, uid=%d, gid=%d)",
1002 			dfname, msg, (int) geteuid(), (int) getegid());
1003 	if (sm_io_reopen(SmFtStdio, SM_TIME_DEFAULT, SM_PATH_DEVNULL,
1004 			 SM_IO_WRONLY, NULL, df) == NULL)
1005 		sm_syslog(LOG_ERR, e->e_id,
1006 			  "dferror: sm_io_reopen(\"/dev/null\") failed: %s",
1007 			  sm_errstring(errno));
1008 }
1009 /*
1010 **  EATFROM -- chew up a UNIX style from line and process
1011 **
1012 **	This does indeed make some assumptions about the format
1013 **	of UNIX messages.
1014 **
1015 **	Parameters:
1016 **		fm -- the from line.
1017 **
1018 **	Returns:
1019 **		none.
1020 **
1021 **	Side Effects:
1022 **		extracts what information it can from the header,
1023 **		such as the date.
1024 */
1025 
1026 #ifndef NOTUNIX
1027 
1028 static char	*DowList[] =
1029 {
1030 	"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", NULL
1031 };
1032 
1033 static char	*MonthList[] =
1034 {
1035 	"Jan", "Feb", "Mar", "Apr", "May", "Jun",
1036 	"Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
1037 	NULL
1038 };
1039 
1040 static void
1041 eatfrom(fm, e)
1042 	char *volatile fm;
1043 	register ENVELOPE *e;
1044 {
1045 	register char *p;
1046 	register char **dt;
1047 
1048 	if (tTd(30, 2))
1049 		sm_dprintf("eatfrom(%s)\n", fm);
1050 
1051 	/* find the date part */
1052 	p = fm;
1053 	while (*p != '\0')
1054 	{
1055 		/* skip a word */
1056 		while (*p != '\0' && *p != ' ')
1057 			p++;
1058 		while (*p == ' ')
1059 			p++;
1060 		if (strlen(p) < 17)
1061 		{
1062 			/* no room for the date */
1063 			return;
1064 		}
1065 		if (!(isascii(*p) && isupper(*p)) ||
1066 		    p[3] != ' ' || p[13] != ':' || p[16] != ':')
1067 			continue;
1068 
1069 		/* we have a possible date */
1070 		for (dt = DowList; *dt != NULL; dt++)
1071 			if (strncmp(*dt, p, 3) == 0)
1072 				break;
1073 		if (*dt == NULL)
1074 			continue;
1075 
1076 		for (dt = MonthList; *dt != NULL; dt++)
1077 		{
1078 			if (strncmp(*dt, &p[4], 3) == 0)
1079 				break;
1080 		}
1081 		if (*dt != NULL)
1082 			break;
1083 	}
1084 
1085 	if (*p != '\0')
1086 	{
1087 		char *q, buf[25];
1088 
1089 		/* we have found a date */
1090 		(void) sm_strlcpy(buf, p, sizeof(buf));
1091 		q = arpadate(buf);
1092 		macdefine(&e->e_macro, A_TEMP, 'a', q);
1093 	}
1094 }
1095 #endif /* ! NOTUNIX */
1096