xref: /original-bsd/usr.sbin/sendmail/src/util.c (revision a79d9c15)
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[] = "@(#)util.c	8.76 (Berkeley) 06/13/95";
11 #endif /* not lint */
12 
13 # include "sendmail.h"
14 # include <sysexits.h>
15 /*
16 **  STRIPQUOTES -- Strip quotes & quote bits from a string.
17 **
18 **	Runs through a string and strips off unquoted quote
19 **	characters and quote bits.  This is done in place.
20 **
21 **	Parameters:
22 **		s -- the string to strip.
23 **
24 **	Returns:
25 **		none.
26 **
27 **	Side Effects:
28 **		none.
29 **
30 **	Called By:
31 **		deliver
32 */
33 
34 void
35 stripquotes(s)
36 	char *s;
37 {
38 	register char *p;
39 	register char *q;
40 	register char c;
41 
42 	if (s == NULL)
43 		return;
44 
45 	p = q = s;
46 	do
47 	{
48 		c = *p++;
49 		if (c == '\\')
50 			c = *p++;
51 		else if (c == '"')
52 			continue;
53 		*q++ = c;
54 	} while (c != '\0');
55 }
56 /*
57 **  XALLOC -- Allocate memory and bitch wildly on failure.
58 **
59 **	THIS IS A CLUDGE.  This should be made to give a proper
60 **	error -- but after all, what can we do?
61 **
62 **	Parameters:
63 **		sz -- size of area to allocate.
64 **
65 **	Returns:
66 **		pointer to data region.
67 **
68 **	Side Effects:
69 **		Memory is allocated.
70 */
71 
72 char *
73 xalloc(sz)
74 	register int sz;
75 {
76 	register char *p;
77 
78 	/* some systems can't handle size zero mallocs */
79 	if (sz <= 0)
80 		sz = 1;
81 
82 	p = malloc((unsigned) sz);
83 	if (p == NULL)
84 	{
85 		syserr("!Out of memory!!");
86 		/* exit(EX_UNAVAILABLE); */
87 	}
88 	return (p);
89 }
90 /*
91 **  COPYPLIST -- copy list of pointers.
92 **
93 **	This routine is the equivalent of newstr for lists of
94 **	pointers.
95 **
96 **	Parameters:
97 **		list -- list of pointers to copy.
98 **			Must be NULL terminated.
99 **		copycont -- if TRUE, copy the contents of the vector
100 **			(which must be a string) also.
101 **
102 **	Returns:
103 **		a copy of 'list'.
104 **
105 **	Side Effects:
106 **		none.
107 */
108 
109 char **
110 copyplist(list, copycont)
111 	char **list;
112 	bool copycont;
113 {
114 	register char **vp;
115 	register char **newvp;
116 
117 	for (vp = list; *vp != NULL; vp++)
118 		continue;
119 
120 	vp++;
121 
122 	newvp = (char **) xalloc((int) (vp - list) * sizeof *vp);
123 	bcopy((char *) list, (char *) newvp, (int) (vp - list) * sizeof *vp);
124 
125 	if (copycont)
126 	{
127 		for (vp = newvp; *vp != NULL; vp++)
128 			*vp = newstr(*vp);
129 	}
130 
131 	return (newvp);
132 }
133 /*
134 **  COPYQUEUE -- copy address queue.
135 **
136 **	This routine is the equivalent of newstr for address queues
137 **	addresses marked with QDONTSEND aren't copied
138 **
139 **	Parameters:
140 **		addr -- list of address structures to copy.
141 **
142 **	Returns:
143 **		a copy of 'addr'.
144 **
145 **	Side Effects:
146 **		none.
147 */
148 
149 ADDRESS *
150 copyqueue(addr)
151 	ADDRESS *addr;
152 {
153 	register ADDRESS *newaddr;
154 	ADDRESS *ret;
155 	register ADDRESS **tail = &ret;
156 
157 	while (addr != NULL)
158 	{
159 		if (!bitset(QDONTSEND, addr->q_flags))
160 		{
161 			newaddr = (ADDRESS *) xalloc(sizeof(ADDRESS));
162 			STRUCTCOPY(*addr, *newaddr);
163 			*tail = newaddr;
164 			tail = &newaddr->q_next;
165 		}
166 		addr = addr->q_next;
167 	}
168 	*tail = NULL;
169 
170 	return ret;
171 }
172 /*
173 **  PRINTAV -- print argument vector.
174 **
175 **	Parameters:
176 **		av -- argument vector.
177 **
178 **	Returns:
179 **		none.
180 **
181 **	Side Effects:
182 **		prints av.
183 */
184 
185 void
186 printav(av)
187 	register char **av;
188 {
189 	while (*av != NULL)
190 	{
191 		if (tTd(0, 44))
192 			printf("\n\t%08x=", *av);
193 		else
194 			(void) putchar(' ');
195 		xputs(*av++);
196 	}
197 	(void) putchar('\n');
198 }
199 /*
200 **  LOWER -- turn letter into lower case.
201 **
202 **	Parameters:
203 **		c -- character to turn into lower case.
204 **
205 **	Returns:
206 **		c, in lower case.
207 **
208 **	Side Effects:
209 **		none.
210 */
211 
212 char
213 lower(c)
214 	register char c;
215 {
216 	return((isascii(c) && isupper(c)) ? tolower(c) : c);
217 }
218 /*
219 **  XPUTS -- put string doing control escapes.
220 **
221 **	Parameters:
222 **		s -- string to put.
223 **
224 **	Returns:
225 **		none.
226 **
227 **	Side Effects:
228 **		output to stdout
229 */
230 
231 void
232 xputs(s)
233 	register const char *s;
234 {
235 	register int c;
236 	register struct metamac *mp;
237 	extern struct metamac MetaMacros[];
238 
239 	if (s == NULL)
240 	{
241 		printf("<null>");
242 		return;
243 	}
244 	while ((c = (*s++ & 0377)) != '\0')
245 	{
246 		if (!isascii(c))
247 		{
248 			if (c == MATCHREPL)
249 			{
250 				putchar('$');
251 				continue;
252 			}
253 			if (c == MACROEXPAND)
254 			{
255 				putchar('$');
256 				if (bitset(0200, *s))
257 					printf("{%s}", macname(*s++ & 0377));
258 				continue;
259 			}
260 			for (mp = MetaMacros; mp->metaname != '\0'; mp++)
261 			{
262 				if ((mp->metaval & 0377) == c)
263 				{
264 					printf("$%c", mp->metaname);
265 					break;
266 				}
267 			}
268 			if (mp->metaname != '\0')
269 				continue;
270 			(void) putchar('\\');
271 			c &= 0177;
272 		}
273 		if (isprint(c))
274 		{
275 			putchar(c);
276 			continue;
277 		}
278 
279 		/* wasn't a meta-macro -- find another way to print it */
280 		switch (c)
281 		{
282 		  case '\n':
283 			c = 'n';
284 			break;
285 
286 		  case '\r':
287 			c = 'r';
288 			break;
289 
290 		  case '\t':
291 			c = 't';
292 			break;
293 
294 		  default:
295 			(void) putchar('^');
296 			(void) putchar(c ^ 0100);
297 			continue;
298 		}
299 		(void) putchar('\\');
300 		(void) putchar(c);
301 	}
302 	(void) fflush(stdout);
303 }
304 /*
305 **  MAKELOWER -- Translate a line into lower case
306 **
307 **	Parameters:
308 **		p -- the string to translate.  If NULL, return is
309 **			immediate.
310 **
311 **	Returns:
312 **		none.
313 **
314 **	Side Effects:
315 **		String pointed to by p is translated to lower case.
316 **
317 **	Called By:
318 **		parse
319 */
320 
321 void
322 makelower(p)
323 	register char *p;
324 {
325 	register char c;
326 
327 	if (p == NULL)
328 		return;
329 	for (; (c = *p) != '\0'; p++)
330 		if (isascii(c) && isupper(c))
331 			*p = tolower(c);
332 }
333 /*
334 **  BUILDFNAME -- build full name from gecos style entry.
335 **
336 **	This routine interprets the strange entry that would appear
337 **	in the GECOS field of the password file.
338 **
339 **	Parameters:
340 **		p -- name to build.
341 **		login -- the login name of this user (for &).
342 **		buf -- place to put the result.
343 **
344 **	Returns:
345 **		none.
346 **
347 **	Side Effects:
348 **		none.
349 */
350 
351 void
352 buildfname(gecos, login, buf)
353 	register char *gecos;
354 	char *login;
355 	char *buf;
356 {
357 	register char *p;
358 	register char *bp = buf;
359 	int l;
360 
361 	if (*gecos == '*')
362 		gecos++;
363 
364 	/* find length of final string */
365 	l = 0;
366 	for (p = gecos; *p != '\0' && *p != ',' && *p != ';' && *p != '%'; p++)
367 	{
368 		if (*p == '&')
369 			l += strlen(login);
370 		else
371 			l++;
372 	}
373 
374 	/* now fill in buf */
375 	for (p = gecos; *p != '\0' && *p != ',' && *p != ';' && *p != '%'; p++)
376 	{
377 		if (*p == '&')
378 		{
379 			(void) strcpy(bp, login);
380 			*bp = toupper(*bp);
381 			while (*bp != '\0')
382 				bp++;
383 		}
384 		else
385 			*bp++ = *p;
386 	}
387 	*bp = '\0';
388 }
389 /*
390 **  SAFEFILE -- return true if a file exists and is safe for a user.
391 **
392 **	Parameters:
393 **		fn -- filename to check.
394 **		uid -- user id to compare against.
395 **		gid -- group id to compare against.
396 **		uname -- user name to compare against (used for group
397 **			sets).
398 **		flags -- modifiers:
399 **			SFF_MUSTOWN -- "uid" must own this file.
400 **			SFF_NOSLINK -- file cannot be a symbolic link.
401 **		mode -- mode bits that must match.
402 **		st -- if set, points to a stat structure that will
403 **			get the stat info for the file.
404 **
405 **	Returns:
406 **		0 if fn exists, is owned by uid, and matches mode.
407 **		An errno otherwise.  The actual errno is cleared.
408 **
409 **	Side Effects:
410 **		none.
411 */
412 
413 #include <grp.h>
414 
415 #ifndef S_IXOTH
416 # define S_IXOTH	(S_IEXEC >> 6)
417 #endif
418 
419 #ifndef S_IXGRP
420 # define S_IXGRP	(S_IEXEC >> 3)
421 #endif
422 
423 #ifndef S_IXUSR
424 # define S_IXUSR	(S_IEXEC)
425 #endif
426 
427 #define ST_MODE_NOFILE	0171147		/* unlikely to occur */
428 
429 int
430 safefile(fn, uid, gid, uname, flags, mode, st)
431 	char *fn;
432 	uid_t uid;
433 	gid_t gid;
434 	char *uname;
435 	int flags;
436 	int mode;
437 	struct stat *st;
438 {
439 	register char *p;
440 	register struct group *gr = NULL;
441 	struct stat stbuf;
442 
443 	if (tTd(54, 4))
444 		printf("safefile(%s, uid=%d, gid=%d, flags=%x, mode=%o):\n",
445 			fn, uid, gid, flags, mode);
446 	errno = 0;
447 	if (st == NULL)
448 		st = &stbuf;
449 
450 	if (!bitset(SFF_NOPATHCHECK, flags) ||
451 	    (uid == 0 && !bitset(SFF_ROOTOK, flags)))
452 	{
453 		/* check the path to the file for acceptability */
454 		for (p = fn; (p = strchr(++p, '/')) != NULL; *p = '/')
455 		{
456 			*p = '\0';
457 			if (stat(fn, &stbuf) < 0)
458 				break;
459 			if (uid == 0 && bitset(S_IWGRP|S_IWOTH, stbuf.st_mode))
460 				message("051 WARNING: writable directory %s",
461 					fn);
462 			if (uid == 0 && !bitset(SFF_ROOTOK, flags))
463 			{
464 				if (bitset(S_IXOTH, stbuf.st_mode))
465 					continue;
466 				break;
467 			}
468 			if (stbuf.st_uid == uid &&
469 			    bitset(S_IXUSR, stbuf.st_mode))
470 				continue;
471 			if (stbuf.st_gid == gid &&
472 			    bitset(S_IXGRP, stbuf.st_mode))
473 				continue;
474 #ifndef NO_GROUP_SET
475 			if (uname != NULL &&
476 			    ((gr != NULL && gr->gr_gid == stbuf.st_gid) ||
477 			     (gr = getgrgid(stbuf.st_gid)) != NULL))
478 			{
479 				register char **gp;
480 
481 				for (gp = gr->gr_mem; gp != NULL && *gp != NULL; gp++)
482 					if (strcmp(*gp, uname) == 0)
483 						break;
484 				if (gp != NULL && *gp != NULL &&
485 				    bitset(S_IXGRP, stbuf.st_mode))
486 					continue;
487 			}
488 #endif
489 			if (!bitset(S_IXOTH, stbuf.st_mode))
490 				break;
491 		}
492 		if (p != NULL)
493 		{
494 			int ret = errno;
495 
496 			if (ret == 0)
497 				ret = EACCES;
498 			if (tTd(54, 4))
499 				printf("\t[dir %s] %s\n", fn, errstring(ret));
500 			*p = '/';
501 			return ret;
502 		}
503 	}
504 
505 #ifdef HASLSTAT
506 	if ((bitset(SFF_NOSLINK, flags) ? lstat(fn, st)
507 					: stat(fn, st)) < 0)
508 #else
509 	if (stat(fn, st) < 0)
510 #endif
511 	{
512 		int ret = errno;
513 
514 		if (tTd(54, 4))
515 			printf("\t%s\n", errstring(ret));
516 
517 		errno = 0;
518 		if (!bitset(SFF_CREAT, flags))
519 			return ret;
520 
521 		/* check to see if legal to create the file */
522 		p = strrchr(fn, '/');
523 		if (p == NULL)
524 			return ENOTDIR;
525 		*p = '\0';
526 		if (stat(fn, &stbuf) >= 0)
527 		{
528 			int md = S_IWRITE|S_IEXEC;
529 			if (stbuf.st_uid != uid)
530 				md >>= 6;
531 			if ((stbuf.st_mode & md) != md)
532 				errno = EACCES;
533 		}
534 		ret = errno;
535 		if (tTd(54, 4))
536 			printf("\t[final dir %s uid %d mode %o] %s\n",
537 				fn, stbuf.st_uid, stbuf.st_mode,
538 				errstring(ret));
539 		*p = '/';
540 		st->st_mode = ST_MODE_NOFILE;
541 		return ret;
542 	}
543 
544 #ifdef S_ISLNK
545 	if (bitset(SFF_NOSLINK, flags) && S_ISLNK(st->st_mode))
546 	{
547 		if (tTd(54, 4))
548 			printf("\t[slink mode %o]\tEPERM\n", st->st_mode);
549 		return EPERM;
550 	}
551 #endif
552 	if (bitset(SFF_REGONLY, flags) && !S_ISREG(st->st_mode))
553 	{
554 		if (tTd(54, 4))
555 			printf("\t[non-reg mode %o]\tEPERM\n", st->st_mode);
556 		return EPERM;
557 	}
558 	if (bitset(S_IWUSR|S_IWGRP|S_IWOTH, mode) && bitset(0111, st->st_mode))
559 	{
560 		if (tTd(29, 5))
561 			printf("failed (mode %o: x bits)\n", st->st_mode);
562 		return EPERM;
563 	}
564 
565 	if (bitset(SFF_SETUIDOK, flags))
566 	{
567 		if (bitset(S_ISUID, st->st_mode) &&
568 		    (st->st_uid != 0 || bitset(SFF_ROOTOK, flags)))
569 		{
570 			uid = st->st_uid;
571 			uname = NULL;
572 		}
573 		if (bitset(S_ISGID, st->st_mode) &&
574 		    (st->st_gid != 0 || bitset(SFF_ROOTOK, flags)))
575 			gid = st->st_gid;
576 	}
577 
578 	if (uid == 0 && !bitset(SFF_ROOTOK, flags))
579 		mode >>= 6;
580 	else if (st->st_uid != uid)
581 	{
582 		mode >>= 3;
583 		if (st->st_gid == gid)
584 			;
585 #ifndef NO_GROUP_SET
586 		else if (uname != NULL &&
587 			 ((gr != NULL && gr->gr_gid == st->st_gid) ||
588 			  (gr = getgrgid(st->st_gid)) != NULL))
589 		{
590 			register char **gp;
591 
592 			for (gp = gr->gr_mem; *gp != NULL; gp++)
593 				if (strcmp(*gp, uname) == 0)
594 					break;
595 			if (*gp == NULL)
596 				mode >>= 3;
597 		}
598 #endif
599 		else
600 			mode >>= 3;
601 	}
602 	if (tTd(54, 4))
603 		printf("\t[uid %d, stat %o, mode %o] ",
604 			st->st_uid, st->st_mode, mode);
605 	if ((st->st_uid == uid || st->st_uid == 0 ||
606 	     !bitset(SFF_MUSTOWN, flags)) &&
607 	    (st->st_mode & mode) == mode)
608 	{
609 		if (tTd(54, 4))
610 			printf("\tOK\n");
611 		return 0;
612 	}
613 	if (tTd(54, 4))
614 		printf("\tEACCES\n");
615 	return EACCES;
616 }
617 /*
618 **  SAFEFOPEN -- do a file open with extra checking
619 **
620 **	Parameters:
621 **		fn -- the file name to open.
622 **		omode -- the open-style mode flags.
623 **		cmode -- the create-style mode flags.
624 **		sff -- safefile flags.
625 **
626 **	Returns:
627 **		Same as fopen.
628 */
629 
630 #ifndef O_ACCMODE
631 # define O_ACCMODE	(O_RDONLY|O_WRONLY|O_RDWR)
632 #endif
633 
634 FILE *
635 safefopen(fn, omode, cmode, sff)
636 	char *fn;
637 	int omode;
638 	int cmode;
639 	int sff;
640 {
641 	int rval;
642 	FILE *fp;
643 	int smode;
644 	struct stat stb, sta;
645 
646 	if (bitset(O_CREAT, omode))
647 		sff |= SFF_CREAT;
648 	smode = 0;
649 	switch (omode & O_ACCMODE)
650 	{
651 	  case O_RDONLY:
652 		smode = S_IREAD;
653 		break;
654 
655 	  case O_WRONLY:
656 		smode = S_IWRITE;
657 		break;
658 
659 	  case O_RDWR:
660 		smode = S_IREAD|S_IWRITE;
661 		break;
662 
663 	  default:
664 		smode = 0;
665 		break;
666 	}
667 	if (bitset(SFF_OPENASROOT, sff))
668 		rval = safefile(fn, 0, 0, NULL, sff, smode, &stb);
669 	else
670 		rval = safefile(fn, RealUid, RealGid, RealUserName,
671 				sff, smode, &stb);
672 	if (rval != 0)
673 	{
674 		errno = rval;
675 		return NULL;
676 	}
677 	if (stb.st_mode == ST_MODE_NOFILE)
678 		omode |= O_EXCL;
679 
680 	fp = dfopen(fn, omode, cmode);
681 	if (fp == NULL)
682 		return NULL;
683 	if (bitset(O_EXCL, omode))
684 		return fp;
685 	if (fstat(fileno(fp), &sta) < 0 ||
686 	    sta.st_nlink != stb.st_nlink ||
687 	    sta.st_dev != stb.st_dev ||
688 	    sta.st_ino != stb.st_ino ||
689 	    sta.st_uid != stb.st_uid ||
690 	    sta.st_gid != stb.st_gid)
691 	{
692 		syserr("554 cannot open: file %s changed after open", fn);
693 		fclose(fp);
694 		errno = EPERM;
695 		return NULL;
696 	}
697 	return fp;
698 }
699 /*
700 **  FIXCRLF -- fix <CR><LF> in line.
701 **
702 **	Looks for the <CR><LF> combination and turns it into the
703 **	UNIX canonical <NL> character.  It only takes one line,
704 **	i.e., it is assumed that the first <NL> found is the end
705 **	of the line.
706 **
707 **	Parameters:
708 **		line -- the line to fix.
709 **		stripnl -- if true, strip the newline also.
710 **
711 **	Returns:
712 **		none.
713 **
714 **	Side Effects:
715 **		line is changed in place.
716 */
717 
718 void
719 fixcrlf(line, stripnl)
720 	char *line;
721 	bool stripnl;
722 {
723 	register char *p;
724 
725 	p = strchr(line, '\n');
726 	if (p == NULL)
727 		return;
728 	if (p > line && p[-1] == '\r')
729 		p--;
730 	if (!stripnl)
731 		*p++ = '\n';
732 	*p = '\0';
733 }
734 /*
735 **  DFOPEN -- determined file open
736 **
737 **	This routine has the semantics of fopen, except that it will
738 **	keep trying a few times to make this happen.  The idea is that
739 **	on very loaded systems, we may run out of resources (inodes,
740 **	whatever), so this tries to get around it.
741 */
742 
743 struct omodes
744 {
745 	int	mask;
746 	int	mode;
747 	char	*farg;
748 } OpenModes[] =
749 {
750 	O_ACCMODE,		O_RDONLY,		"r",
751 	O_ACCMODE|O_APPEND,	O_WRONLY,		"w",
752 	O_ACCMODE|O_APPEND,	O_WRONLY|O_APPEND,	"a",
753 	O_TRUNC,		0,			"w+",
754 	O_APPEND,		O_APPEND,		"a+",
755 	0,			0,			"r+",
756 };
757 
758 FILE *
759 dfopen(filename, omode, cmode)
760 	char *filename;
761 	int omode;
762 	int cmode;
763 {
764 	register int tries;
765 	int fd;
766 	register struct omodes *om;
767 	struct stat st;
768 
769 	for (om = OpenModes; om->mask != 0; om++)
770 		if ((omode & om->mask) == om->mode)
771 			break;
772 
773 	for (tries = 0; tries < 10; tries++)
774 	{
775 		sleep((unsigned) (10 * tries));
776 		errno = 0;
777 		fd = open(filename, omode, cmode);
778 		if (fd >= 0)
779 			break;
780 		switch (errno)
781 		{
782 		  case ENFILE:		/* system file table full */
783 		  case EINTR:		/* interrupted syscall */
784 #ifdef ETXTBSY
785 		  case ETXTBSY:		/* Apollo: net file locked */
786 #endif
787 			continue;
788 		}
789 		break;
790 	}
791 	if (fd >= 0 && fstat(fd, &st) >= 0 && S_ISREG(st.st_mode))
792 	{
793 		int locktype;
794 
795 		/* lock the file to avoid accidental conflicts */
796 		if ((omode & O_ACCMODE) != O_RDONLY)
797 			locktype = LOCK_EX;
798 		else
799 			locktype = LOCK_SH;
800 		(void) lockfile(fd, filename, NULL, locktype);
801 		errno = 0;
802 	}
803 	if (fd < 0)
804 		return NULL;
805 	else
806 		return fdopen(fd, om->farg);
807 }
808 /*
809 **  PUTLINE -- put a line like fputs obeying SMTP conventions
810 **
811 **	This routine always guarantees outputing a newline (or CRLF,
812 **	as appropriate) at the end of the string.
813 **
814 **	Parameters:
815 **		l -- line to put.
816 **		mci -- the mailer connection information.
817 **
818 **	Returns:
819 **		none
820 **
821 **	Side Effects:
822 **		output of l to fp.
823 */
824 
825 void
826 putline(l, mci)
827 	register char *l;
828 	register MCI *mci;
829 {
830 	putxline(l, mci, PXLF_MAPFROM);
831 }
832 /*
833 **  PUTXLINE -- putline with flags bits.
834 **
835 **	This routine always guarantees outputing a newline (or CRLF,
836 **	as appropriate) at the end of the string.
837 **
838 **	Parameters:
839 **		l -- line to put.
840 **		mci -- the mailer connection information.
841 **		pxflags -- flag bits:
842 **		    PXLF_MAPFROM -- map From_ to >From_.
843 **		    PXLF_STRIP8BIT -- strip 8th bit.
844 **
845 **	Returns:
846 **		none
847 **
848 **	Side Effects:
849 **		output of l to fp.
850 */
851 
852 void
853 putxline(l, mci, pxflags)
854 	register char *l;
855 	register MCI *mci;
856 	int pxflags;
857 {
858 	register char *p;
859 	register char svchar;
860 	int slop = 0;
861 
862 	/* strip out 0200 bits -- these can look like TELNET protocol */
863 	if (bitset(MCIF_7BIT, mci->mci_flags) ||
864 	    bitset(PXLF_STRIP8BIT, pxflags))
865 	{
866 		for (p = l; (svchar = *p) != '\0'; ++p)
867 			if (bitset(0200, svchar))
868 				*p = svchar &~ 0200;
869 	}
870 
871 	do
872 	{
873 		/* find the end of the line */
874 		p = strchr(l, '\n');
875 		if (p == NULL)
876 			p = &l[strlen(l)];
877 
878 		if (TrafficLogFile != NULL)
879 			fprintf(TrafficLogFile, "%05d >>> ", getpid());
880 
881 		/* check for line overflow */
882 		while (mci->mci_mailer->m_linelimit > 0 &&
883 		       (p - l + slop) > mci->mci_mailer->m_linelimit)
884 		{
885 			register char *q = &l[mci->mci_mailer->m_linelimit - slop - 1];
886 
887 			svchar = *q;
888 			*q = '\0';
889 			if (l[0] == '.' && slop == 0 &&
890 			    bitnset(M_XDOT, mci->mci_mailer->m_flags))
891 			{
892 				(void) putc('.', mci->mci_out);
893 				if (TrafficLogFile != NULL)
894 					(void) putc('.', TrafficLogFile);
895 			}
896 			else if (l[0] == 'F' && slop == 0 &&
897 				 bitset(PXLF_MAPFROM, pxflags) &&
898 				 strncmp(l, "From ", 5) == 0 &&
899 				 bitnset(M_ESCFROM, mci->mci_mailer->m_flags))
900 			{
901 				(void) putc('>', mci->mci_out);
902 				if (TrafficLogFile != NULL)
903 					(void) putc('>', TrafficLogFile);
904 			}
905 			fputs(l, mci->mci_out);
906 			(void) putc('!', mci->mci_out);
907 			fputs(mci->mci_mailer->m_eol, mci->mci_out);
908 			(void) putc(' ', mci->mci_out);
909 			if (TrafficLogFile != NULL)
910 				fprintf(TrafficLogFile, "%s!\n%05d >>>  ",
911 					l, getpid());
912 			*q = svchar;
913 			l = q;
914 			slop = 1;
915 		}
916 
917 		/* output last part */
918 		if (l[0] == '.' && slop == 0 &&
919 		    bitnset(M_XDOT, mci->mci_mailer->m_flags))
920 		{
921 			(void) putc('.', mci->mci_out);
922 			if (TrafficLogFile != NULL)
923 				(void) putc('.', TrafficLogFile);
924 		}
925 		if (TrafficLogFile != NULL)
926 			fprintf(TrafficLogFile, "%.*s\n", p - l, l);
927 		for ( ; l < p; ++l)
928 			(void) putc(*l, mci->mci_out);
929 		fputs(mci->mci_mailer->m_eol, mci->mci_out);
930 		if (*l == '\n')
931 			++l;
932 	} while (l[0] != '\0');
933 }
934 /*
935 **  XUNLINK -- unlink a file, doing logging as appropriate.
936 **
937 **	Parameters:
938 **		f -- name of file to unlink.
939 **
940 **	Returns:
941 **		none.
942 **
943 **	Side Effects:
944 **		f is unlinked.
945 */
946 
947 void
948 xunlink(f)
949 	char *f;
950 {
951 	register int i;
952 
953 # ifdef LOG
954 	if (LogLevel > 98)
955 		syslog(LOG_DEBUG, "%s: unlink %s", CurEnv->e_id, f);
956 # endif /* LOG */
957 
958 	i = unlink(f);
959 # ifdef LOG
960 	if (i < 0 && LogLevel > 97)
961 		syslog(LOG_DEBUG, "%s: unlink-fail %d", f, errno);
962 # endif /* LOG */
963 }
964 /*
965 **  XFCLOSE -- close a file, doing logging as appropriate.
966 **
967 **	Parameters:
968 **		fp -- file pointer for the file to close
969 **		a, b -- miscellaneous crud to print for debugging
970 **
971 **	Returns:
972 **		none.
973 **
974 **	Side Effects:
975 **		fp is closed.
976 */
977 
978 void
979 xfclose(fp, a, b)
980 	FILE *fp;
981 	char *a, *b;
982 {
983 	if (tTd(53, 99))
984 		printf("xfclose(%x) %s %s\n", fp, a, b);
985 #if XDEBUG
986 	if (fileno(fp) == 1)
987 		syserr("xfclose(%s %s): fd = 1", a, b);
988 #endif
989 	if (fclose(fp) < 0 && tTd(53, 99))
990 		printf("xfclose FAILURE: %s\n", errstring(errno));
991 }
992 /*
993 **  SFGETS -- "safe" fgets -- times out and ignores random interrupts.
994 **
995 **	Parameters:
996 **		buf -- place to put the input line.
997 **		siz -- size of buf.
998 **		fp -- file to read from.
999 **		timeout -- the timeout before error occurs.
1000 **		during -- what we are trying to read (for error messages).
1001 **
1002 **	Returns:
1003 **		NULL on error (including timeout).  This will also leave
1004 **			buf containing a null string.
1005 **		buf otherwise.
1006 **
1007 **	Side Effects:
1008 **		none.
1009 */
1010 
1011 static jmp_buf	CtxReadTimeout;
1012 static void	readtimeout();
1013 
1014 char *
1015 sfgets(buf, siz, fp, timeout, during)
1016 	char *buf;
1017 	int siz;
1018 	FILE *fp;
1019 	time_t timeout;
1020 	char *during;
1021 {
1022 	register EVENT *ev = NULL;
1023 	register char *p;
1024 
1025 	if (fp == NULL)
1026 	{
1027 		buf[0] = '\0';
1028 		return NULL;
1029 	}
1030 
1031 	/* set the timeout */
1032 	if (timeout != 0)
1033 	{
1034 		if (setjmp(CtxReadTimeout) != 0)
1035 		{
1036 # ifdef LOG
1037 			syslog(LOG_NOTICE,
1038 			    "timeout waiting for input from %s during %s\n",
1039 			    CurHostName? CurHostName: "local", during);
1040 # endif
1041 			errno = 0;
1042 			usrerr("451 timeout waiting for input during %s",
1043 				during);
1044 			buf[0] = '\0';
1045 #if XDEBUG
1046 			checkfd012(during);
1047 #endif
1048 			return (NULL);
1049 		}
1050 		ev = setevent(timeout, readtimeout, 0);
1051 	}
1052 
1053 	/* try to read */
1054 	p = NULL;
1055 	while (!feof(fp) && !ferror(fp))
1056 	{
1057 		errno = 0;
1058 		p = fgets(buf, siz, fp);
1059 		if (p != NULL || errno != EINTR)
1060 			break;
1061 		clearerr(fp);
1062 	}
1063 
1064 	/* clear the event if it has not sprung */
1065 	clrevent(ev);
1066 
1067 	/* clean up the books and exit */
1068 	LineNumber++;
1069 	if (p == NULL)
1070 	{
1071 		buf[0] = '\0';
1072 		if (TrafficLogFile != NULL)
1073 			fprintf(TrafficLogFile, "%05d <<< [EOF]\n", getpid());
1074 		return (NULL);
1075 	}
1076 	if (TrafficLogFile != NULL)
1077 		fprintf(TrafficLogFile, "%05d <<< %s", getpid(), buf);
1078 	if (SevenBitInput)
1079 	{
1080 		for (p = buf; *p != '\0'; p++)
1081 			*p &= ~0200;
1082 	}
1083 	else if (!HasEightBits)
1084 	{
1085 		for (p = buf; *p != '\0'; p++)
1086 		{
1087 			if (bitset(0200, *p))
1088 			{
1089 				HasEightBits = TRUE;
1090 				break;
1091 			}
1092 		}
1093 	}
1094 	return (buf);
1095 }
1096 
1097 static void
1098 readtimeout(timeout)
1099 	time_t timeout;
1100 {
1101 	longjmp(CtxReadTimeout, 1);
1102 }
1103 /*
1104 **  FGETFOLDED -- like fgets, but know about folded lines.
1105 **
1106 **	Parameters:
1107 **		buf -- place to put result.
1108 **		n -- bytes available.
1109 **		f -- file to read from.
1110 **
1111 **	Returns:
1112 **		input line(s) on success, NULL on error or EOF.
1113 **		This will normally be buf -- unless the line is too
1114 **			long, when it will be xalloc()ed.
1115 **
1116 **	Side Effects:
1117 **		buf gets lines from f, with continuation lines (lines
1118 **		with leading white space) appended.  CRLF's are mapped
1119 **		into single newlines.  Any trailing NL is stripped.
1120 */
1121 
1122 char *
1123 fgetfolded(buf, n, f)
1124 	char *buf;
1125 	register int n;
1126 	FILE *f;
1127 {
1128 	register char *p = buf;
1129 	char *bp = buf;
1130 	register int i;
1131 
1132 	n--;
1133 	while ((i = getc(f)) != EOF)
1134 	{
1135 		if (i == '\r')
1136 		{
1137 			i = getc(f);
1138 			if (i != '\n')
1139 			{
1140 				if (i != EOF)
1141 					(void) ungetc(i, f);
1142 				i = '\r';
1143 			}
1144 		}
1145 		if (--n <= 0)
1146 		{
1147 			/* allocate new space */
1148 			char *nbp;
1149 			int nn;
1150 
1151 			nn = (p - bp);
1152 			if (nn < MEMCHUNKSIZE)
1153 				nn *= 2;
1154 			else
1155 				nn += MEMCHUNKSIZE;
1156 			nbp = xalloc(nn);
1157 			bcopy(bp, nbp, p - bp);
1158 			p = &nbp[p - bp];
1159 			if (bp != buf)
1160 				free(bp);
1161 			bp = nbp;
1162 			n = nn - (p - bp);
1163 		}
1164 		*p++ = i;
1165 		if (i == '\n')
1166 		{
1167 			LineNumber++;
1168 			i = getc(f);
1169 			if (i != EOF)
1170 				(void) ungetc(i, f);
1171 			if (i != ' ' && i != '\t')
1172 				break;
1173 		}
1174 	}
1175 	if (p == bp)
1176 		return (NULL);
1177 	if (p[-1] == '\n')
1178 		p--;
1179 	*p = '\0';
1180 	return (bp);
1181 }
1182 /*
1183 **  CURTIME -- return current time.
1184 **
1185 **	Parameters:
1186 **		none.
1187 **
1188 **	Returns:
1189 **		the current time.
1190 **
1191 **	Side Effects:
1192 **		none.
1193 */
1194 
1195 time_t
1196 curtime()
1197 {
1198 	auto time_t t;
1199 
1200 	(void) time(&t);
1201 	return (t);
1202 }
1203 /*
1204 **  ATOBOOL -- convert a string representation to boolean.
1205 **
1206 **	Defaults to "TRUE"
1207 **
1208 **	Parameters:
1209 **		s -- string to convert.  Takes "tTyY" as true,
1210 **			others as false.
1211 **
1212 **	Returns:
1213 **		A boolean representation of the string.
1214 **
1215 **	Side Effects:
1216 **		none.
1217 */
1218 
1219 bool
1220 atobool(s)
1221 	register char *s;
1222 {
1223 	if (s == NULL || *s == '\0' || strchr("tTyY", *s) != NULL)
1224 		return (TRUE);
1225 	return (FALSE);
1226 }
1227 /*
1228 **  ATOOCT -- convert a string representation to octal.
1229 **
1230 **	Parameters:
1231 **		s -- string to convert.
1232 **
1233 **	Returns:
1234 **		An integer representing the string interpreted as an
1235 **		octal number.
1236 **
1237 **	Side Effects:
1238 **		none.
1239 */
1240 
1241 int
1242 atooct(s)
1243 	register char *s;
1244 {
1245 	register int i = 0;
1246 
1247 	while (*s >= '0' && *s <= '7')
1248 		i = (i << 3) | (*s++ - '0');
1249 	return (i);
1250 }
1251 /*
1252 **  WAITFOR -- wait for a particular process id.
1253 **
1254 **	Parameters:
1255 **		pid -- process id to wait for.
1256 **
1257 **	Returns:
1258 **		status of pid.
1259 **		-1 if pid never shows up.
1260 **
1261 **	Side Effects:
1262 **		none.
1263 */
1264 
1265 int
1266 waitfor(pid)
1267 	int pid;
1268 {
1269 #ifdef WAITUNION
1270 	union wait st;
1271 #else
1272 	auto int st;
1273 #endif
1274 	int i;
1275 
1276 	do
1277 	{
1278 		errno = 0;
1279 		i = wait(&st);
1280 	} while ((i >= 0 || errno == EINTR) && i != pid);
1281 	if (i < 0)
1282 		return -1;
1283 #ifdef WAITUNION
1284 	return st.w_status;
1285 #else
1286 	return st;
1287 #endif
1288 }
1289 /*
1290 **  BITINTERSECT -- tell if two bitmaps intersect
1291 **
1292 **	Parameters:
1293 **		a, b -- the bitmaps in question
1294 **
1295 **	Returns:
1296 **		TRUE if they have a non-null intersection
1297 **		FALSE otherwise
1298 **
1299 **	Side Effects:
1300 **		none.
1301 */
1302 
1303 bool
1304 bitintersect(a, b)
1305 	BITMAP a;
1306 	BITMAP b;
1307 {
1308 	int i;
1309 
1310 	for (i = BITMAPBYTES / sizeof (int); --i >= 0; )
1311 		if ((a[i] & b[i]) != 0)
1312 			return (TRUE);
1313 	return (FALSE);
1314 }
1315 /*
1316 **  BITZEROP -- tell if a bitmap is all zero
1317 **
1318 **	Parameters:
1319 **		map -- the bit map to check
1320 **
1321 **	Returns:
1322 **		TRUE if map is all zero.
1323 **		FALSE if there are any bits set in map.
1324 **
1325 **	Side Effects:
1326 **		none.
1327 */
1328 
1329 bool
1330 bitzerop(map)
1331 	BITMAP map;
1332 {
1333 	int i;
1334 
1335 	for (i = BITMAPBYTES / sizeof (int); --i >= 0; )
1336 		if (map[i] != 0)
1337 			return (FALSE);
1338 	return (TRUE);
1339 }
1340 /*
1341 **  STRCONTAINEDIN -- tell if one string is contained in another
1342 **
1343 **	Parameters:
1344 **		a -- possible substring.
1345 **		b -- possible superstring.
1346 **
1347 **	Returns:
1348 **		TRUE if a is contained in b.
1349 **		FALSE otherwise.
1350 */
1351 
1352 bool
1353 strcontainedin(a, b)
1354 	register char *a;
1355 	register char *b;
1356 {
1357 	int la;
1358 	int lb;
1359 	int c;
1360 
1361 	la = strlen(a);
1362 	lb = strlen(b);
1363 	c = *a;
1364 	if (isascii(c) && isupper(c))
1365 		c = tolower(c);
1366 	for (; lb-- >= la; b++)
1367 	{
1368 		if (*b != c && isascii(*b) && isupper(*b) && tolower(*b) != c)
1369 			continue;
1370 		if (strncasecmp(a, b, la) == 0)
1371 			return TRUE;
1372 	}
1373 	return FALSE;
1374 }
1375 /*
1376 **  CHECKFD012 -- check low numbered file descriptors
1377 **
1378 **	File descriptors 0, 1, and 2 should be open at all times.
1379 **	This routine verifies that, and fixes it if not true.
1380 **
1381 **	Parameters:
1382 **		where -- a tag printed if the assertion failed
1383 **
1384 **	Returns:
1385 **		none
1386 */
1387 
1388 void
1389 checkfd012(where)
1390 	char *where;
1391 {
1392 #if XDEBUG
1393 	register int i;
1394 	struct stat stbuf;
1395 
1396 	for (i = 0; i < 3; i++)
1397 	{
1398 		if (fstat(i, &stbuf) < 0 && errno != EOPNOTSUPP)
1399 		{
1400 			/* oops.... */
1401 			int fd;
1402 
1403 			syserr("%s: fd %d not open", where, i);
1404 			fd = open("/dev/null", i == 0 ? O_RDONLY : O_WRONLY, 0666);
1405 			if (fd != i)
1406 			{
1407 				(void) dup2(fd, i);
1408 				(void) close(fd);
1409 			}
1410 		}
1411 	}
1412 #endif /* XDEBUG */
1413 }
1414 /*
1415 **  PRINTOPENFDS -- print the open file descriptors (for debugging)
1416 **
1417 **	Parameters:
1418 **		logit -- if set, send output to syslog; otherwise
1419 **			print for debugging.
1420 **
1421 **	Returns:
1422 **		none.
1423 */
1424 
1425 #include <arpa/inet.h>
1426 
1427 void
1428 printopenfds(logit)
1429 	bool logit;
1430 {
1431 	register int fd;
1432 	extern int DtableSize;
1433 
1434 	for (fd = 0; fd < DtableSize; fd++)
1435 		dumpfd(fd, FALSE, logit);
1436 }
1437 /*
1438 **  DUMPFD -- dump a file descriptor
1439 **
1440 **	Parameters:
1441 **		fd -- the file descriptor to dump.
1442 **		printclosed -- if set, print a notification even if
1443 **			it is closed; otherwise print nothing.
1444 **		logit -- if set, send output to syslog instead of stdout.
1445 */
1446 
1447 void
1448 dumpfd(fd, printclosed, logit)
1449 	int fd;
1450 	bool printclosed;
1451 	bool logit;
1452 {
1453 	register char *p;
1454 	char *hp;
1455 	char *fmtstr;
1456 	SOCKADDR sa;
1457 	auto int slen;
1458 	struct stat st;
1459 	char buf[200];
1460 	extern char *hostnamebyanyaddr();
1461 
1462 	p = buf;
1463 	sprintf(p, "%3d: ", fd);
1464 	p += strlen(p);
1465 
1466 	if (fstat(fd, &st) < 0)
1467 	{
1468 		if (printclosed || errno != EBADF)
1469 		{
1470 			sprintf(p, "CANNOT STAT (%s)", errstring(errno));
1471 			goto printit;
1472 		}
1473 		return;
1474 	}
1475 
1476 	slen = fcntl(fd, F_GETFL, NULL);
1477 	if (slen != -1)
1478 	{
1479 		sprintf(p, "fl=0x%x, ", slen);
1480 		p += strlen(p);
1481 	}
1482 
1483 	sprintf(p, "mode=%o: ", st.st_mode);
1484 	p += strlen(p);
1485 	switch (st.st_mode & S_IFMT)
1486 	{
1487 #ifdef S_IFSOCK
1488 	  case S_IFSOCK:
1489 		sprintf(p, "SOCK ");
1490 		p += strlen(p);
1491 		slen = sizeof sa;
1492 		if (getsockname(fd, &sa.sa, &slen) < 0)
1493 			sprintf(p, "(%s)", errstring(errno));
1494 		else
1495 		{
1496 			hp = hostnamebyanyaddr(&sa);
1497 			if (sa.sa.sa_family == AF_INET)
1498 				sprintf(p, "%s/%d", hp, ntohs(sa.sin.sin_port));
1499 			else
1500 				sprintf(p, "%s", hp);
1501 		}
1502 		p += strlen(p);
1503 		sprintf(p, "->");
1504 		p += strlen(p);
1505 		slen = sizeof sa;
1506 		if (getpeername(fd, &sa.sa, &slen) < 0)
1507 			sprintf(p, "(%s)", errstring(errno));
1508 		else
1509 		{
1510 			hp = hostnamebyanyaddr(&sa);
1511 			if (sa.sa.sa_family == AF_INET)
1512 				sprintf(p, "%s/%d", hp, ntohs(sa.sin.sin_port));
1513 			else
1514 				sprintf(p, "%s", hp);
1515 		}
1516 		break;
1517 #endif
1518 
1519 	  case S_IFCHR:
1520 		sprintf(p, "CHR: ");
1521 		p += strlen(p);
1522 		goto defprint;
1523 
1524 	  case S_IFBLK:
1525 		sprintf(p, "BLK: ");
1526 		p += strlen(p);
1527 		goto defprint;
1528 
1529 #if defined(S_IFIFO) && (!defined(S_IFSOCK) || S_IFIFO != S_IFSOCK)
1530 	  case S_IFIFO:
1531 		sprintf(p, "FIFO: ");
1532 		p += strlen(p);
1533 		goto defprint;
1534 #endif
1535 
1536 #ifdef S_IFDIR
1537 	  case S_IFDIR:
1538 		sprintf(p, "DIR: ");
1539 		p += strlen(p);
1540 		goto defprint;
1541 #endif
1542 
1543 #ifdef S_IFLNK
1544 	  case S_IFLNK:
1545 		sprintf(p, "LNK: ");
1546 		p += strlen(p);
1547 		goto defprint;
1548 #endif
1549 
1550 	  default:
1551 defprint:
1552 		if (sizeof st.st_size > sizeof (long))
1553 			fmtstr = "dev=%d/%d, ino=%d, nlink=%d, u/gid=%d/%d, size=%qd";
1554 		else
1555 			fmtstr = "dev=%d/%d, ino=%d, nlink=%d, u/gid=%d/%d, size=%ld";
1556 		sprintf(p, fmtstr,
1557 			major(st.st_dev), minor(st.st_dev), st.st_ino,
1558 			st.st_nlink, st.st_uid, st.st_gid, st.st_size);
1559 		break;
1560 	}
1561 
1562 printit:
1563 #ifdef LOG
1564 	if (logit)
1565 		syslog(LOG_DEBUG, "%s", buf);
1566 	else
1567 #endif
1568 		printf("%s\n", buf);
1569 }
1570 /*
1571 **  SHORTENSTRING -- return short version of a string
1572 **
1573 **	If the string is already short, just return it.  If it is too
1574 **	long, return the head and tail of the string.
1575 **
1576 **	Parameters:
1577 **		s -- the string to shorten.
1578 **		m -- the max length of the string.
1579 **
1580 **	Returns:
1581 **		Either s or a short version of s.
1582 */
1583 
1584 #ifndef MAXSHORTSTR
1585 # define MAXSHORTSTR	203
1586 #endif
1587 
1588 char *
1589 shortenstring(s, m)
1590 	register const char *s;
1591 	int m;
1592 {
1593 	int l;
1594 	static char buf[MAXSHORTSTR + 1];
1595 
1596 	l = strlen(s);
1597 	if (l < m)
1598 		return (char *) s;
1599 	if (m > MAXSHORTSTR)
1600 		m = MAXSHORTSTR;
1601 	else if (m < 10)
1602 	{
1603 		if (m < 5)
1604 		{
1605 			strncpy(buf, s, m);
1606 			buf[m] = '\0';
1607 			return buf;
1608 		}
1609 		strncpy(buf, s, m - 3);
1610 		strcpy(buf + m - 3, "...");
1611 		return buf;
1612 	}
1613 	m = (m - 3) / 2;
1614 	strncpy(buf, s, m);
1615 	strcpy(buf + m, "...");
1616 	strcpy(buf + m + 3, s + l - m);
1617 	return buf;
1618 }
1619 /*
1620 **  SHORTEN_HOSTNAME -- strip local domain information off of hostname.
1621 **
1622 **	Parameters:
1623 **		host -- the host to shorten (stripped in place).
1624 **
1625 **	Returns:
1626 **		none.
1627 */
1628 
1629 void
1630 shorten_hostname(host)
1631 	char host[];
1632 {
1633 	register char *p;
1634 	char *mydom;
1635 	int i;
1636 	bool canon = FALSE;
1637 
1638 	/* strip off final dot */
1639 	p = &host[strlen(host) - 1];
1640 	if (*p == '.')
1641 	{
1642 		*p = '\0';
1643 		canon = TRUE;
1644 	}
1645 
1646 	/* see if there is any domain at all -- if not, we are done */
1647 	p = strchr(host, '.');
1648 	if (p == NULL)
1649 		return;
1650 
1651 	/* yes, we have a domain -- see if it looks like us */
1652 	mydom = macvalue('m', CurEnv);
1653 	if (mydom == NULL)
1654 		mydom = "";
1655 	i = strlen(++p);
1656 	if ((canon ? strcasecmp(p, mydom) : strncasecmp(p, mydom, i)) == 0 &&
1657 	    (mydom[i] == '.' || mydom[i] == '\0'))
1658 		*--p = '\0';
1659 }
1660 /*
1661 **  PROG_OPEN -- open a program for reading
1662 **
1663 **	Parameters:
1664 **		argv -- the argument list.
1665 **		pfd -- pointer to a place to store the file descriptor.
1666 **		e -- the current envelope.
1667 **
1668 **	Returns:
1669 **		pid of the process -- -1 if it failed.
1670 */
1671 
1672 int
1673 prog_open(argv, pfd, e)
1674 	char **argv;
1675 	int *pfd;
1676 	ENVELOPE *e;
1677 {
1678 	int pid;
1679 	int i;
1680 	int saveerrno;
1681 	int fdv[2];
1682 	char *p, *q;
1683 	char buf[MAXLINE + 1];
1684 	extern int DtableSize;
1685 
1686 	if (pipe(fdv) < 0)
1687 	{
1688 		syserr("%s: cannot create pipe for stdout", argv[0]);
1689 		return -1;
1690 	}
1691 	pid = fork();
1692 	if (pid < 0)
1693 	{
1694 		syserr("%s: cannot fork", argv[0]);
1695 		close(fdv[0]);
1696 		close(fdv[1]);
1697 		return -1;
1698 	}
1699 	if (pid > 0)
1700 	{
1701 		/* parent */
1702 		close(fdv[1]);
1703 		*pfd = fdv[0];
1704 		return pid;
1705 	}
1706 
1707 	/* child -- close stdin */
1708 	close(0);
1709 
1710 	/* stdout goes back to parent */
1711 	close(fdv[0]);
1712 	if (dup2(fdv[1], 1) < 0)
1713 	{
1714 		syserr("%s: cannot dup2 for stdout", argv[0]);
1715 		_exit(EX_OSERR);
1716 	}
1717 	close(fdv[1]);
1718 
1719 	/* stderr goes to transcript if available */
1720 	if (e->e_xfp != NULL)
1721 	{
1722 		if (dup2(fileno(e->e_xfp), 2) < 0)
1723 		{
1724 			syserr("%s: cannot dup2 for stderr", argv[0]);
1725 			_exit(EX_OSERR);
1726 		}
1727 	}
1728 
1729 	/* this process has no right to the queue file */
1730 	if (e->e_lockfp != NULL)
1731 		close(fileno(e->e_lockfp));
1732 
1733 	/* run as default user */
1734 	setgid(DefGid);
1735 	setuid(DefUid);
1736 
1737 	/* run in some directory */
1738 	if (ProgMailer != NULL)
1739 		p = ProgMailer->m_execdir;
1740 	else
1741 		p = NULL;
1742 	for (; p != NULL; p = q)
1743 	{
1744 		q = strchr(p, ':');
1745 		if (q != NULL)
1746 			*q = '\0';
1747 		expand(p, buf, sizeof buf, e);
1748 		if (q != NULL)
1749 			*q++ = ':';
1750 		if (buf[0] != '\0' && chdir(buf) >= 0)
1751 			break;
1752 	}
1753 	if (p == NULL)
1754 	{
1755 		/* backup directories */
1756 		if (chdir("/tmp") < 0)
1757 			(void) chdir("/");
1758 	}
1759 
1760 	/* arrange for all the files to be closed */
1761 	for (i = 3; i < DtableSize; i++)
1762 	{
1763 		register int j;
1764 
1765 		if ((j = fcntl(i, F_GETFD, 0)) != -1)
1766 			(void) fcntl(i, F_SETFD, j | 1);
1767 	}
1768 
1769 	/* now exec the process */
1770 	execve(argv[0], (ARGV_T) argv, (ARGV_T) UserEnviron);
1771 
1772 	/* woops!  failed */
1773 	saveerrno = errno;
1774 	syserr("%s: cannot exec", argv[0]);
1775 	if (transienterror(saveerrno))
1776 		_exit(EX_OSERR);
1777 	_exit(EX_CONFIG);
1778 }
1779 /*
1780 **  GET_COLUMN  -- look up a Column in a line buffer
1781 **
1782 **	Parameters:
1783 **		line -- the raw text line to search.
1784 **		col -- the column number to fetch.
1785 **		delim -- the delimiter between columns.  If null,
1786 **			use white space.
1787 **		buf -- the output buffer.
1788 **
1789 **	Returns:
1790 **		buf if successful.
1791 **		NULL otherwise.
1792 */
1793 
1794 char *
1795 get_column(line, col, delim, buf)
1796 	char line[];
1797 	int col;
1798 	char delim;
1799 	char buf[];
1800 {
1801 	char *p;
1802 	char *begin, *end;
1803 	int i;
1804 	char delimbuf[3];
1805 
1806 	if (delim == '\0')
1807 		strcpy(delimbuf, "\n\t ");
1808 	else
1809 	{
1810 		delimbuf[0] = delim;
1811 		delimbuf[1] = '\0';
1812 	}
1813 
1814 	p = line;
1815 	if (*p == '\0')
1816 		return NULL;			/* line empty */
1817 	if (*p == delim && col == 0)
1818 		return NULL;			/* first column empty */
1819 
1820 	begin = line;
1821 
1822 	if (col == 0 && delim == '\0')
1823 	{
1824 		while (*begin && isspace(*begin))
1825 			begin++;
1826 	}
1827 
1828 	for (i = 0; i < col; i++)
1829 	{
1830 		if ((begin = strpbrk(begin, delimbuf)) == NULL)
1831 			return NULL;		/* no such column */
1832 		begin++;
1833 		if (delim == '\0')
1834 		{
1835 			while (*begin && isspace(*begin))
1836 				begin++;
1837 		}
1838 	}
1839 
1840 	end = strpbrk(begin, delimbuf);
1841 	if (end == NULL)
1842 	{
1843 		strcpy(buf, begin);
1844 	}
1845 	else
1846 	{
1847 		strncpy(buf, begin, end - begin);
1848 		buf[end - begin] = '\0';
1849 	}
1850 	return buf;
1851 }
1852 /*
1853 **  CLEANSTRCPY -- copy string keeping out bogus characters
1854 **
1855 **	Parameters:
1856 **		t -- "to" string.
1857 **		f -- "from" string.
1858 **		l -- length of space available in "to" string.
1859 **
1860 **	Returns:
1861 **		none.
1862 */
1863 
1864 void
1865 cleanstrcpy(t, f, l)
1866 	register char *t;
1867 	register char *f;
1868 	int l;
1869 {
1870 #ifdef LOG
1871 	/* check for newlines and log if necessary */
1872 	(void) denlstring(f, TRUE, TRUE);
1873 #endif
1874 
1875 	l--;
1876 	while (l > 0 && *f != '\0')
1877 	{
1878 		if (isascii(*f) &&
1879 		    (isalnum(*f) || strchr("!#$%&'*+-./^_`{|}~", *f) != NULL))
1880 		{
1881 			l--;
1882 			*t++ = *f;
1883 		}
1884 		f++;
1885 	}
1886 	*t = '\0';
1887 }
1888 /*
1889 **  DENLSTRING -- convert newlines in a string to spaces
1890 **
1891 **	Parameters:
1892 **		s -- the input string
1893 **		strict -- if set, don't permit continuation lines.
1894 **		logattacks -- if set, log attempted attacks.
1895 **
1896 **	Returns:
1897 **		A pointer to a version of the string with newlines
1898 **		mapped to spaces.  This should be copied.
1899 */
1900 
1901 char *
1902 denlstring(s, strict, logattacks)
1903 	char *s;
1904 	bool strict;
1905 	bool logattacks;
1906 {
1907 	register char *p;
1908 	int l;
1909 	static char *bp = NULL;
1910 	static int bl = 0;
1911 
1912 	p = s;
1913 	while ((p = strchr(p, '\n')) != NULL)
1914 		if (strict || (*++p != ' ' && *p != '\t'))
1915 			break;
1916 	if (p == NULL)
1917 		return s;
1918 
1919 	l = strlen(s) + 1;
1920 	if (bl < l)
1921 	{
1922 		/* allocate more space */
1923 		if (bp != NULL)
1924 			free(bp);
1925 		bp = xalloc(l);
1926 		bl = l;
1927 	}
1928 	strcpy(bp, s);
1929 	for (p = bp; (p = strchr(p, '\n')) != NULL; )
1930 		*p++ = ' ';
1931 
1932 /*
1933 #ifdef LOG
1934 	if (logattacks)
1935 	{
1936 		syslog(LOG_NOTICE, "POSSIBLE ATTACK from %s: newline in string \"%s\"",
1937 			RealHostName == NULL ? "[UNKNOWN]" : RealHostName,
1938 			shortenstring(bp, 80));
1939 	}
1940 #endif
1941 */
1942 
1943 	return bp;
1944 }
1945