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