xref: /original-bsd/usr.sbin/sendmail/src/util.c (revision a0411884)
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[] = "@(#)util.c	8.29 (Berkeley) 01/24/94";
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 stripquotes(s)
35 	char *s;
36 {
37 	register char *p;
38 	register char *q;
39 	register char c;
40 
41 	if (s == NULL)
42 		return;
43 
44 	p = q = s;
45 	do
46 	{
47 		c = *p++;
48 		if (c == '\\')
49 			c = *p++;
50 		else if (c == '"')
51 			continue;
52 		*q++ = c;
53 	} while (c != '\0');
54 }
55 /*
56 **  XALLOC -- Allocate memory and bitch wildly on failure.
57 **
58 **	THIS IS A CLUDGE.  This should be made to give a proper
59 **	error -- but after all, what can we do?
60 **
61 **	Parameters:
62 **		sz -- size of area to allocate.
63 **
64 **	Returns:
65 **		pointer to data region.
66 **
67 **	Side Effects:
68 **		Memory is allocated.
69 */
70 
71 char *
72 xalloc(sz)
73 	register int sz;
74 {
75 	register char *p;
76 
77 	p = malloc((unsigned) sz);
78 	if (p == NULL)
79 	{
80 		syserr("Out of memory!!");
81 		abort();
82 		/* exit(EX_UNAVAILABLE); */
83 	}
84 	return (p);
85 }
86 /*
87 **  COPYPLIST -- copy list of pointers.
88 **
89 **	This routine is the equivalent of newstr for lists of
90 **	pointers.
91 **
92 **	Parameters:
93 **		list -- list of pointers to copy.
94 **			Must be NULL terminated.
95 **		copycont -- if TRUE, copy the contents of the vector
96 **			(which must be a string) also.
97 **
98 **	Returns:
99 **		a copy of 'list'.
100 **
101 **	Side Effects:
102 **		none.
103 */
104 
105 char **
106 copyplist(list, copycont)
107 	char **list;
108 	bool copycont;
109 {
110 	register char **vp;
111 	register char **newvp;
112 
113 	for (vp = list; *vp != NULL; vp++)
114 		continue;
115 
116 	vp++;
117 
118 	newvp = (char **) xalloc((int) (vp - list) * sizeof *vp);
119 	bcopy((char *) list, (char *) newvp, (int) (vp - list) * sizeof *vp);
120 
121 	if (copycont)
122 	{
123 		for (vp = newvp; *vp != NULL; vp++)
124 			*vp = newstr(*vp);
125 	}
126 
127 	return (newvp);
128 }
129 /*
130 **  COPYQUEUE -- copy address queue.
131 **
132 **	This routine is the equivalent of newstr for address queues
133 **	addresses marked with QDONTSEND aren't copied
134 **
135 **	Parameters:
136 **		addr -- list of address structures to copy.
137 **
138 **	Returns:
139 **		a copy of 'addr'.
140 **
141 **	Side Effects:
142 **		none.
143 */
144 
145 ADDRESS *
146 copyqueue(addr)
147 	ADDRESS *addr;
148 {
149 	register ADDRESS *newaddr;
150 	ADDRESS *ret;
151 	register ADDRESS **tail = &ret;
152 
153 	while (addr != NULL)
154 	{
155 		if (!bitset(QDONTSEND, addr->q_flags))
156 		{
157 			newaddr = (ADDRESS *) xalloc(sizeof(ADDRESS));
158 			STRUCTCOPY(*addr, *newaddr);
159 			*tail = newaddr;
160 			tail = &newaddr->q_next;
161 		}
162 		addr = addr->q_next;
163 	}
164 	*tail = NULL;
165 
166 	return ret;
167 }
168 /*
169 **  PRINTAV -- print argument vector.
170 **
171 **	Parameters:
172 **		av -- argument vector.
173 **
174 **	Returns:
175 **		none.
176 **
177 **	Side Effects:
178 **		prints av.
179 */
180 
181 printav(av)
182 	register char **av;
183 {
184 	while (*av != NULL)
185 	{
186 		if (tTd(0, 44))
187 			printf("\n\t%08x=", *av);
188 		else
189 			(void) putchar(' ');
190 		xputs(*av++);
191 	}
192 	(void) putchar('\n');
193 }
194 /*
195 **  LOWER -- turn letter into lower case.
196 **
197 **	Parameters:
198 **		c -- character to turn into lower case.
199 **
200 **	Returns:
201 **		c, in lower case.
202 **
203 **	Side Effects:
204 **		none.
205 */
206 
207 char
208 lower(c)
209 	register char c;
210 {
211 	return((isascii(c) && isupper(c)) ? tolower(c) : c);
212 }
213 /*
214 **  XPUTS -- put string doing control escapes.
215 **
216 **	Parameters:
217 **		s -- string to put.
218 **
219 **	Returns:
220 **		none.
221 **
222 **	Side Effects:
223 **		output to stdout
224 */
225 
226 xputs(s)
227 	register char *s;
228 {
229 	register int c;
230 	register struct metamac *mp;
231 	extern struct metamac MetaMacros[];
232 
233 	if (s == NULL)
234 	{
235 		printf("<null>");
236 		return;
237 	}
238 	while ((c = (*s++ & 0377)) != '\0')
239 	{
240 		if (!isascii(c))
241 		{
242 			if (c == MATCHREPL || c == MACROEXPAND)
243 			{
244 				putchar('$');
245 				continue;
246 			}
247 			for (mp = MetaMacros; mp->metaname != '\0'; mp++)
248 			{
249 				if ((mp->metaval & 0377) == c)
250 				{
251 					printf("$%c", mp->metaname);
252 					break;
253 				}
254 			}
255 			if (mp->metaname != '\0')
256 				continue;
257 			(void) putchar('\\');
258 			c &= 0177;
259 		}
260 		if (isprint(c))
261 		{
262 			putchar(c);
263 			continue;
264 		}
265 
266 		/* wasn't a meta-macro -- find another way to print it */
267 		switch (c)
268 		{
269 		  case '\0':
270 			continue;
271 
272 		  case '\n':
273 			c = 'n';
274 			break;
275 
276 		  case '\r':
277 			c = 'r';
278 			break;
279 
280 		  case '\t':
281 			c = 't';
282 			break;
283 
284 		  default:
285 			(void) putchar('^');
286 			(void) putchar(c ^ 0100);
287 			continue;
288 		}
289 	}
290 	(void) fflush(stdout);
291 }
292 /*
293 **  MAKELOWER -- Translate a line into lower case
294 **
295 **	Parameters:
296 **		p -- the string to translate.  If NULL, return is
297 **			immediate.
298 **
299 **	Returns:
300 **		none.
301 **
302 **	Side Effects:
303 **		String pointed to by p is translated to lower case.
304 **
305 **	Called By:
306 **		parse
307 */
308 
309 makelower(p)
310 	register char *p;
311 {
312 	register char c;
313 
314 	if (p == NULL)
315 		return;
316 	for (; (c = *p) != '\0'; p++)
317 		if (isascii(c) && isupper(c))
318 			*p = tolower(c);
319 }
320 /*
321 **  BUILDFNAME -- build full name from gecos style entry.
322 **
323 **	This routine interprets the strange entry that would appear
324 **	in the GECOS field of the password file.
325 **
326 **	Parameters:
327 **		p -- name to build.
328 **		login -- the login name of this user (for &).
329 **		buf -- place to put the result.
330 **
331 **	Returns:
332 **		none.
333 **
334 **	Side Effects:
335 **		none.
336 */
337 
338 buildfname(gecos, login, buf)
339 	register char *gecos;
340 	char *login;
341 	char *buf;
342 {
343 	register char *p;
344 	register char *bp = buf;
345 	int l;
346 
347 	if (*gecos == '*')
348 		gecos++;
349 
350 	/* find length of final string */
351 	l = 0;
352 	for (p = gecos; *p != '\0' && *p != ',' && *p != ';' && *p != '%'; p++)
353 	{
354 		if (*p == '&')
355 			l += strlen(login);
356 		else
357 			l++;
358 	}
359 
360 	/* now fill in buf */
361 	for (p = gecos; *p != '\0' && *p != ',' && *p != ';' && *p != '%'; p++)
362 	{
363 		if (*p == '&')
364 		{
365 			(void) strcpy(bp, login);
366 			*bp = toupper(*bp);
367 			while (*bp != '\0')
368 				bp++;
369 		}
370 		else
371 			*bp++ = *p;
372 	}
373 	*bp = '\0';
374 }
375 /*
376 **  SAFEFILE -- return true if a file exists and is safe for a user.
377 **
378 **	Parameters:
379 **		fn -- filename to check.
380 **		uid -- user id to compare against.
381 **		gid -- group id to compare against.
382 **		uname -- user name to compare against (used for group
383 **			sets).
384 **		flags -- modifiers:
385 **			SFF_MUSTOWN -- "uid" must own this file.
386 **			SFF_NOSLINK -- file cannot be a symbolic link.
387 **		mode -- mode bits that must match.
388 **
389 **	Returns:
390 **		0 if fn exists, is owned by uid, and matches mode.
391 **		An errno otherwise.  The actual errno is cleared.
392 **
393 **	Side Effects:
394 **		none.
395 */
396 
397 #include <grp.h>
398 
399 #ifndef S_IXOTH
400 # define S_IXOTH	(S_IEXEC >> 6)
401 #endif
402 
403 #ifndef S_IXGRP
404 # define S_IXGRP	(S_IEXEC >> 3)
405 #endif
406 
407 #ifndef S_IXUSR
408 # define S_IXUSR	(S_IEXEC)
409 #endif
410 
411 int
412 safefile(fn, uid, gid, uname, flags, mode)
413 	char *fn;
414 	uid_t uid;
415 	gid_t gid;
416 	char *uname;
417 	int flags;
418 	int mode;
419 {
420 	register char *p;
421 	register struct group *gr = NULL;
422 	struct stat stbuf;
423 
424 	if (tTd(54, 4))
425 		printf("safefile(%s, uid=%d, gid=%d, flags=%x, mode=%o):\n",
426 			fn, uid, gid, flags, mode);
427 	errno = 0;
428 
429 	for (p = fn; (p = strchr(++p, '/')) != NULL; *p = '/')
430 	{
431 		*p = '\0';
432 		if (stat(fn, &stbuf) < 0)
433 			break;
434 		if (uid == 0 && !bitset(SFF_ROOTOK, flags))
435 		{
436 			if (bitset(S_IXOTH, stbuf.st_mode))
437 				continue;
438 			break;
439 		}
440 		if (stbuf.st_uid == uid && bitset(S_IXUSR, stbuf.st_mode))
441 			continue;
442 		if (stbuf.st_gid == gid && bitset(S_IXGRP, stbuf.st_mode))
443 			continue;
444 #ifndef NO_GROUP_SET
445 		if (uname != NULL &&
446 		    ((gr != NULL && gr->gr_gid == stbuf.st_gid) ||
447 		     (gr = getgrgid(stbuf.st_gid)) != NULL))
448 		{
449 			register char **gp;
450 
451 			for (gp = gr->gr_mem; *gp != NULL; gp++)
452 				if (strcmp(*gp, uname) == 0)
453 					break;
454 			if (*gp != NULL && bitset(S_IXGRP, stbuf.st_mode))
455 				continue;
456 		}
457 #endif
458 		if (!bitset(S_IXOTH, stbuf.st_mode))
459 			break;
460 	}
461 	if (p != NULL)
462 	{
463 		int ret = errno;
464 
465 		if (ret == 0)
466 			ret = EACCES;
467 		if (tTd(54, 4))
468 			printf("\t[dir %s] %s\n", fn, errstring(ret));
469 		*p = '/';
470 		return ret;
471 	}
472 
473 #ifdef HASLSTAT
474 	if ((bitset(SFF_NOSLINK, flags) ? lstat(fn, &stbuf)
475 					: stat(fn, &stbuf)) < 0)
476 #else
477 	if (stat(fn, &stbuf) < 0)
478 #endif
479 	{
480 		int ret = errno;
481 
482 		if (tTd(54, 4))
483 			printf("\t%s\n", errstring(ret));
484 
485 		errno = 0;
486 		return ret;
487 	}
488 
489 #ifdef S_ISLNK
490 	if (bitset(SFF_NOSLINK, flags) && S_ISLNK(stbuf.st_mode))
491 	{
492 		if (tTd(54, 4))
493 			printf("\t[slink mode %o]\tEPERM\n", stbuf.st_mode);
494 		return EPERM;
495 	}
496 #endif
497 
498 	if (uid == 0 && !bitset(SFF_ROOTOK, flags))
499 		mode >>= 6;
500 	else if (stbuf.st_uid != uid)
501 	{
502 		mode >>= 3;
503 		if (stbuf.st_gid == gid)
504 			;
505 #ifndef NO_GROUP_SET
506 		else if (uname != NULL &&
507 			 ((gr != NULL && gr->gr_gid == stbuf.st_gid) ||
508 			  (gr = getgrgid(stbuf.st_gid)) != NULL))
509 		{
510 			register char **gp;
511 
512 			for (gp = gr->gr_mem; *gp != NULL; gp++)
513 				if (strcmp(*gp, uname) == 0)
514 					break;
515 			if (*gp == NULL)
516 				mode >>= 3;
517 		}
518 #endif
519 		else
520 			mode >>= 3;
521 	}
522 	if (tTd(54, 4))
523 		printf("\t[uid %d, stat %o, mode %o] ",
524 			stbuf.st_uid, stbuf.st_mode, mode);
525 	if ((stbuf.st_uid == uid || stbuf.st_uid == 0 ||
526 	     !bitset(SFF_MUSTOWN, flags)) &&
527 	    (stbuf.st_mode & mode) == mode)
528 	{
529 		if (tTd(54, 4))
530 			printf("\tOK\n");
531 		return 0;
532 	}
533 	if (tTd(54, 4))
534 		printf("\tEACCES\n");
535 	return EACCES;
536 }
537 /*
538 **  FIXCRLF -- fix <CR><LF> in line.
539 **
540 **	Looks for the <CR><LF> combination and turns it into the
541 **	UNIX canonical <NL> character.  It only takes one line,
542 **	i.e., it is assumed that the first <NL> found is the end
543 **	of the line.
544 **
545 **	Parameters:
546 **		line -- the line to fix.
547 **		stripnl -- if true, strip the newline also.
548 **
549 **	Returns:
550 **		none.
551 **
552 **	Side Effects:
553 **		line is changed in place.
554 */
555 
556 fixcrlf(line, stripnl)
557 	char *line;
558 	bool stripnl;
559 {
560 	register char *p;
561 
562 	p = strchr(line, '\n');
563 	if (p == NULL)
564 		return;
565 	if (p > line && p[-1] == '\r')
566 		p--;
567 	if (!stripnl)
568 		*p++ = '\n';
569 	*p = '\0';
570 }
571 /*
572 **  DFOPEN -- determined file open
573 **
574 **	This routine has the semantics of fopen, except that it will
575 **	keep trying a few times to make this happen.  The idea is that
576 **	on very loaded systems, we may run out of resources (inodes,
577 **	whatever), so this tries to get around it.
578 */
579 
580 #ifndef O_ACCMODE
581 # define O_ACCMODE	(O_RDONLY|O_WRONLY|O_RDWR)
582 #endif
583 
584 struct omodes
585 {
586 	int	mask;
587 	int	mode;
588 	char	*farg;
589 } OpenModes[] =
590 {
591 	O_ACCMODE,		O_RDONLY,		"r",
592 	O_ACCMODE|O_APPEND,	O_WRONLY,		"w",
593 	O_ACCMODE|O_APPEND,	O_WRONLY|O_APPEND,	"a",
594 	O_TRUNC,		0,			"w+",
595 	O_APPEND,		O_APPEND,		"a+",
596 	0,			0,			"r+",
597 };
598 
599 FILE *
600 dfopen(filename, omode, cmode)
601 	char *filename;
602 	int omode;
603 	int cmode;
604 {
605 	register int tries;
606 	int fd;
607 	register struct omodes *om;
608 	struct stat st;
609 
610 	for (om = OpenModes; om->mask != 0; om++)
611 		if ((omode & om->mask) == om->mode)
612 			break;
613 
614 	for (tries = 0; tries < 10; tries++)
615 	{
616 		sleep((unsigned) (10 * tries));
617 		errno = 0;
618 		fd = open(filename, omode, cmode);
619 		if (fd >= 0)
620 			break;
621 		if (errno != ENFILE && errno != EINTR)
622 			break;
623 	}
624 	if (fd >= 0 && fstat(fd, &st) >= 0 && S_ISREG(st.st_mode))
625 	{
626 		int locktype;
627 
628 		/* lock the file to avoid accidental conflicts */
629 		if ((omode & O_ACCMODE) != O_RDONLY)
630 			locktype = LOCK_EX;
631 		else
632 			locktype = LOCK_SH;
633 		(void) lockfile(fd, filename, NULL, locktype);
634 		errno = 0;
635 	}
636 	if (fd < 0)
637 		return NULL;
638 	else
639 		return fdopen(fd, om->farg);
640 }
641 /*
642 **  PUTLINE -- put a line like fputs obeying SMTP conventions
643 **
644 **	This routine always guarantees outputing a newline (or CRLF,
645 **	as appropriate) at the end of the string.
646 **
647 **	Parameters:
648 **		l -- line to put.
649 **		mci -- the mailer connection information.
650 **
651 **	Returns:
652 **		none
653 **
654 **	Side Effects:
655 **		output of l to fp.
656 */
657 
658 putline(l, mci)
659 	register char *l;
660 	register MCI *mci;
661 {
662 	register char *p;
663 	register char svchar;
664 
665 	/* strip out 0200 bits -- these can look like TELNET protocol */
666 	if (bitset(MCIF_7BIT, mci->mci_flags))
667 	{
668 		for (p = l; (svchar = *p) != '\0'; ++p)
669 			if (bitset(0200, svchar))
670 				*p = svchar &~ 0200;
671 	}
672 
673 	do
674 	{
675 		/* find the end of the line */
676 		p = strchr(l, '\n');
677 		if (p == NULL)
678 			p = &l[strlen(l)];
679 
680 		if (TrafficLogFile != NULL)
681 			fprintf(TrafficLogFile, "%05d >>> ", getpid());
682 
683 		/* check for line overflow */
684 		while (mci->mci_mailer->m_linelimit > 0 &&
685 		       (p - l) > mci->mci_mailer->m_linelimit)
686 		{
687 			register char *q = &l[mci->mci_mailer->m_linelimit - 1];
688 
689 			svchar = *q;
690 			*q = '\0';
691 			if (l[0] == '.' && bitnset(M_XDOT, mci->mci_mailer->m_flags))
692 			{
693 				(void) putc('.', mci->mci_out);
694 				if (TrafficLogFile != NULL)
695 					(void) putc('.', TrafficLogFile);
696 			}
697 			fputs(l, mci->mci_out);
698 			(void) putc('!', mci->mci_out);
699 			fputs(mci->mci_mailer->m_eol, mci->mci_out);
700 			if (TrafficLogFile != NULL)
701 				fprintf(TrafficLogFile, "%s!\n%05d >>> ",
702 					l, getpid());
703 			*q = svchar;
704 			l = q;
705 		}
706 
707 		/* output last part */
708 		if (l[0] == '.' && bitnset(M_XDOT, mci->mci_mailer->m_flags))
709 		{
710 			(void) putc('.', mci->mci_out);
711 			if (TrafficLogFile != NULL)
712 				(void) putc('.', TrafficLogFile);
713 		}
714 		if (TrafficLogFile != NULL)
715 			fprintf(TrafficLogFile, "%.*s\n", p - l, l);
716 		for ( ; l < p; ++l)
717 			(void) putc(*l, mci->mci_out);
718 		fputs(mci->mci_mailer->m_eol, mci->mci_out);
719 		if (*l == '\n')
720 			++l;
721 	} while (l[0] != '\0');
722 }
723 /*
724 **  XUNLINK -- unlink a file, doing logging as appropriate.
725 **
726 **	Parameters:
727 **		f -- name of file to unlink.
728 **
729 **	Returns:
730 **		none.
731 **
732 **	Side Effects:
733 **		f is unlinked.
734 */
735 
736 xunlink(f)
737 	char *f;
738 {
739 	register int i;
740 
741 # ifdef LOG
742 	if (LogLevel > 98)
743 		syslog(LOG_DEBUG, "%s: unlink %s", CurEnv->e_id, f);
744 # endif /* LOG */
745 
746 	i = unlink(f);
747 # ifdef LOG
748 	if (i < 0 && LogLevel > 97)
749 		syslog(LOG_DEBUG, "%s: unlink-fail %d", f, errno);
750 # endif /* LOG */
751 }
752 /*
753 **  XFCLOSE -- close a file, doing logging as appropriate.
754 **
755 **	Parameters:
756 **		fp -- file pointer for the file to close
757 **		a, b -- miscellaneous crud to print for debugging
758 **
759 **	Returns:
760 **		none.
761 **
762 **	Side Effects:
763 **		fp is closed.
764 */
765 
766 xfclose(fp, a, b)
767 	FILE *fp;
768 	char *a, *b;
769 {
770 	if (tTd(53, 99))
771 		printf("xfclose(%x) %s %s\n", fp, a, b);
772 #ifdef XDEBUG
773 	if (fileno(fp) == 1)
774 		syserr("xfclose(%s %s): fd = 1", a, b);
775 #endif
776 	if (fclose(fp) < 0 && tTd(53, 99))
777 		printf("xfclose FAILURE: %s\n", errstring(errno));
778 }
779 /*
780 **  SFGETS -- "safe" fgets -- times out and ignores random interrupts.
781 **
782 **	Parameters:
783 **		buf -- place to put the input line.
784 **		siz -- size of buf.
785 **		fp -- file to read from.
786 **		timeout -- the timeout before error occurs.
787 **		during -- what we are trying to read (for error messages).
788 **
789 **	Returns:
790 **		NULL on error (including timeout).  This will also leave
791 **			buf containing a null string.
792 **		buf otherwise.
793 **
794 **	Side Effects:
795 **		none.
796 */
797 
798 static jmp_buf	CtxReadTimeout;
799 static int	readtimeout();
800 
801 char *
802 sfgets(buf, siz, fp, timeout, during)
803 	char *buf;
804 	int siz;
805 	FILE *fp;
806 	time_t timeout;
807 	char *during;
808 {
809 	register EVENT *ev = NULL;
810 	register char *p;
811 
812 	/* set the timeout */
813 	if (timeout != 0)
814 	{
815 		if (setjmp(CtxReadTimeout) != 0)
816 		{
817 # ifdef LOG
818 			syslog(LOG_NOTICE,
819 			    "timeout waiting for input from %s during %s\n",
820 			    CurHostName? CurHostName: "local", during);
821 # endif
822 			errno = 0;
823 			usrerr("451 timeout waiting for input during %s",
824 				during);
825 			buf[0] = '\0';
826 #ifdef XDEBUG
827 			checkfd012(during);
828 #endif
829 			return (NULL);
830 		}
831 		ev = setevent(timeout, readtimeout, 0);
832 	}
833 
834 	/* try to read */
835 	p = NULL;
836 	while (!feof(fp) && !ferror(fp))
837 	{
838 		errno = 0;
839 		p = fgets(buf, siz, fp);
840 		if (p != NULL || errno != EINTR)
841 			break;
842 		clearerr(fp);
843 	}
844 
845 	/* clear the event if it has not sprung */
846 	clrevent(ev);
847 
848 	/* clean up the books and exit */
849 	LineNumber++;
850 	if (p == NULL)
851 	{
852 		buf[0] = '\0';
853 		if (TrafficLogFile != NULL)
854 			fprintf(TrafficLogFile, "%05d <<< [EOF]\n", getpid());
855 		return (NULL);
856 	}
857 	if (TrafficLogFile != NULL)
858 		fprintf(TrafficLogFile, "%05d <<< %s", getpid(), buf);
859 	if (SevenBit)
860 		for (p = buf; *p != '\0'; p++)
861 			*p &= ~0200;
862 	return (buf);
863 }
864 
865 static
866 readtimeout()
867 {
868 	longjmp(CtxReadTimeout, 1);
869 }
870 /*
871 **  FGETFOLDED -- like fgets, but know about folded lines.
872 **
873 **	Parameters:
874 **		buf -- place to put result.
875 **		n -- bytes available.
876 **		f -- file to read from.
877 **
878 **	Returns:
879 **		input line(s) on success, NULL on error or EOF.
880 **		This will normally be buf -- unless the line is too
881 **			long, when it will be xalloc()ed.
882 **
883 **	Side Effects:
884 **		buf gets lines from f, with continuation lines (lines
885 **		with leading white space) appended.  CRLF's are mapped
886 **		into single newlines.  Any trailing NL is stripped.
887 */
888 
889 char *
890 fgetfolded(buf, n, f)
891 	char *buf;
892 	register int n;
893 	FILE *f;
894 {
895 	register char *p = buf;
896 	char *bp = buf;
897 	register int i;
898 
899 	n--;
900 	while ((i = getc(f)) != EOF)
901 	{
902 		if (i == '\r')
903 		{
904 			i = getc(f);
905 			if (i != '\n')
906 			{
907 				if (i != EOF)
908 					(void) ungetc(i, f);
909 				i = '\r';
910 			}
911 		}
912 		if (--n <= 0)
913 		{
914 			/* allocate new space */
915 			char *nbp;
916 			int nn;
917 
918 			nn = (p - bp);
919 			if (nn < MEMCHUNKSIZE)
920 				nn *= 2;
921 			else
922 				nn += MEMCHUNKSIZE;
923 			nbp = xalloc(nn);
924 			bcopy(bp, nbp, p - bp);
925 			p = &nbp[p - bp];
926 			if (bp != buf)
927 				free(bp);
928 			bp = nbp;
929 			n = nn - (p - bp);
930 		}
931 		*p++ = i;
932 		if (i == '\n')
933 		{
934 			LineNumber++;
935 			i = getc(f);
936 			if (i != EOF)
937 				(void) ungetc(i, f);
938 			if (i != ' ' && i != '\t')
939 				break;
940 		}
941 	}
942 	if (p == bp)
943 		return (NULL);
944 	*--p = '\0';
945 	return (bp);
946 }
947 /*
948 **  CURTIME -- return current time.
949 **
950 **	Parameters:
951 **		none.
952 **
953 **	Returns:
954 **		the current time.
955 **
956 **	Side Effects:
957 **		none.
958 */
959 
960 time_t
961 curtime()
962 {
963 	auto time_t t;
964 
965 	(void) time(&t);
966 	return (t);
967 }
968 /*
969 **  ATOBOOL -- convert a string representation to boolean.
970 **
971 **	Defaults to "TRUE"
972 **
973 **	Parameters:
974 **		s -- string to convert.  Takes "tTyY" as true,
975 **			others as false.
976 **
977 **	Returns:
978 **		A boolean representation of the string.
979 **
980 **	Side Effects:
981 **		none.
982 */
983 
984 bool
985 atobool(s)
986 	register char *s;
987 {
988 	if (s == NULL || *s == '\0' || strchr("tTyY", *s) != NULL)
989 		return (TRUE);
990 	return (FALSE);
991 }
992 /*
993 **  ATOOCT -- convert a string representation to octal.
994 **
995 **	Parameters:
996 **		s -- string to convert.
997 **
998 **	Returns:
999 **		An integer representing the string interpreted as an
1000 **		octal number.
1001 **
1002 **	Side Effects:
1003 **		none.
1004 */
1005 
1006 atooct(s)
1007 	register char *s;
1008 {
1009 	register int i = 0;
1010 
1011 	while (*s >= '0' && *s <= '7')
1012 		i = (i << 3) | (*s++ - '0');
1013 	return (i);
1014 }
1015 /*
1016 **  WAITFOR -- wait for a particular process id.
1017 **
1018 **	Parameters:
1019 **		pid -- process id to wait for.
1020 **
1021 **	Returns:
1022 **		status of pid.
1023 **		-1 if pid never shows up.
1024 **
1025 **	Side Effects:
1026 **		none.
1027 */
1028 
1029 int
1030 waitfor(pid)
1031 	int pid;
1032 {
1033 #ifdef WAITUNION
1034 	union wait st;
1035 #else
1036 	auto int st;
1037 #endif
1038 	int i;
1039 
1040 	do
1041 	{
1042 		errno = 0;
1043 		i = wait(&st);
1044 	} while ((i >= 0 || errno == EINTR) && i != pid);
1045 	if (i < 0)
1046 		return -1;
1047 #ifdef WAITUNION
1048 	return st.w_status;
1049 #else
1050 	return st;
1051 #endif
1052 }
1053 /*
1054 **  BITINTERSECT -- tell if two bitmaps intersect
1055 **
1056 **	Parameters:
1057 **		a, b -- the bitmaps in question
1058 **
1059 **	Returns:
1060 **		TRUE if they have a non-null intersection
1061 **		FALSE otherwise
1062 **
1063 **	Side Effects:
1064 **		none.
1065 */
1066 
1067 bool
1068 bitintersect(a, b)
1069 	BITMAP a;
1070 	BITMAP b;
1071 {
1072 	int i;
1073 
1074 	for (i = BITMAPBYTES / sizeof (int); --i >= 0; )
1075 		if ((a[i] & b[i]) != 0)
1076 			return (TRUE);
1077 	return (FALSE);
1078 }
1079 /*
1080 **  BITZEROP -- tell if a bitmap is all zero
1081 **
1082 **	Parameters:
1083 **		map -- the bit map to check
1084 **
1085 **	Returns:
1086 **		TRUE if map is all zero.
1087 **		FALSE if there are any bits set in map.
1088 **
1089 **	Side Effects:
1090 **		none.
1091 */
1092 
1093 bool
1094 bitzerop(map)
1095 	BITMAP map;
1096 {
1097 	int i;
1098 
1099 	for (i = BITMAPBYTES / sizeof (int); --i >= 0; )
1100 		if (map[i] != 0)
1101 			return (FALSE);
1102 	return (TRUE);
1103 }
1104 /*
1105 **  STRCONTAINEDIN -- tell if one string is contained in another
1106 **
1107 **	Parameters:
1108 **		a -- possible substring.
1109 **		b -- possible superstring.
1110 **
1111 **	Returns:
1112 **		TRUE if a is contained in b.
1113 **		FALSE otherwise.
1114 */
1115 
1116 bool
1117 strcontainedin(a, b)
1118 	register char *a;
1119 	register char *b;
1120 {
1121 	int la;
1122 	int lb;
1123 	int c;
1124 
1125 	la = strlen(a);
1126 	lb = strlen(b);
1127 	c = *a;
1128 	if (isascii(c) && isupper(c))
1129 		c = tolower(c);
1130 	for (; lb-- >= la; b++)
1131 	{
1132 		if (*b != c && isascii(*b) && isupper(*b) && tolower(*b) != c)
1133 			continue;
1134 		if (strncasecmp(a, b, la) == 0)
1135 			return TRUE;
1136 	}
1137 	return FALSE;
1138 }
1139 /*
1140 **  CHECKFD012 -- check low numbered file descriptors
1141 **
1142 **	File descriptors 0, 1, and 2 should be open at all times.
1143 **	This routine verifies that, and fixes it if not true.
1144 **
1145 **	Parameters:
1146 **		where -- a tag printed if the assertion failed
1147 **
1148 **	Returns:
1149 **		none
1150 */
1151 
1152 checkfd012(where)
1153 	char *where;
1154 {
1155 #ifdef XDEBUG
1156 	register int i;
1157 	struct stat stbuf;
1158 
1159 	for (i = 0; i < 3; i++)
1160 	{
1161 		if (fstat(i, &stbuf) < 0 && errno != EOPNOTSUPP)
1162 		{
1163 			/* oops.... */
1164 			int fd;
1165 
1166 			syserr("%s: fd %d not open", where, i);
1167 			fd = open("/dev/null", i == 0 ? O_RDONLY : O_WRONLY, 0666);
1168 			if (fd != i)
1169 			{
1170 				(void) dup2(fd, i);
1171 				(void) close(fd);
1172 			}
1173 		}
1174 	}
1175 #endif /* XDEBUG */
1176 }
1177 /*
1178 **  PRINTOPENFDS -- print the open file descriptors (for debugging)
1179 **
1180 **	Parameters:
1181 **		logit -- if set, send output to syslog; otherwise
1182 **			print for debugging.
1183 **
1184 **	Returns:
1185 **		none.
1186 */
1187 
1188 #include <netdb.h>
1189 #include <arpa/inet.h>
1190 
1191 printopenfds(logit)
1192 	bool logit;
1193 {
1194 	register int fd;
1195 	extern int DtableSize;
1196 
1197 	for (fd = 0; fd < DtableSize; fd++)
1198 		dumpfd(fd, FALSE, logit);
1199 }
1200 /*
1201 **  DUMPFD -- dump a file descriptor
1202 **
1203 **	Parameters:
1204 **		fd -- the file descriptor to dump.
1205 **		printclosed -- if set, print a notification even if
1206 **			it is closed; otherwise print nothing.
1207 **		logit -- if set, send output to syslog instead of stdout.
1208 */
1209 
1210 dumpfd(fd, printclosed, logit)
1211 	int fd;
1212 	bool printclosed;
1213 	bool logit;
1214 {
1215 	register struct hostent *hp;
1216 	register char *p;
1217 	struct sockaddr_in sin;
1218 	auto int slen;
1219 	struct stat st;
1220 	char buf[200];
1221 
1222 	p = buf;
1223 	sprintf(p, "%3d: ", fd);
1224 	p += strlen(p);
1225 
1226 	if (fstat(fd, &st) < 0)
1227 	{
1228 		if (printclosed || errno != EBADF)
1229 		{
1230 			sprintf(p, "CANNOT STAT (%s)", errstring(errno));
1231 			goto printit;
1232 		}
1233 		return;
1234 	}
1235 
1236 	slen = fcntl(fd, F_GETFL, NULL);
1237 	if (slen != -1)
1238 	{
1239 		sprintf(p, "fl=0x%x, ", slen);
1240 		p += strlen(p);
1241 	}
1242 
1243 	sprintf(p, "mode=%o: ", st.st_mode);
1244 	p += strlen(p);
1245 	switch (st.st_mode & S_IFMT)
1246 	{
1247 #ifdef S_IFSOCK
1248 	  case S_IFSOCK:
1249 		sprintf(p, "SOCK ");
1250 		p += strlen(p);
1251 		slen = sizeof sin;
1252 		if (getsockname(fd, (struct sockaddr *) &sin, &slen) < 0)
1253 			sprintf(p, "(badsock)");
1254 		else
1255 		{
1256 			hp = gethostbyaddr((char *) &sin.sin_addr, slen, AF_INET);
1257 			sprintf(p, "%s/%d", hp == NULL ? inet_ntoa(sin.sin_addr)
1258 						   : hp->h_name, ntohs(sin.sin_port));
1259 		}
1260 		p += strlen(p);
1261 		sprintf(p, "->");
1262 		p += strlen(p);
1263 		slen = sizeof sin;
1264 		if (getpeername(fd, (struct sockaddr *) &sin, &slen) < 0)
1265 			sprintf(p, "(badsock)");
1266 		else
1267 		{
1268 			hp = gethostbyaddr((char *) &sin.sin_addr, slen, AF_INET);
1269 			sprintf(p, "%s/%d", hp == NULL ? inet_ntoa(sin.sin_addr)
1270 						   : hp->h_name, ntohs(sin.sin_port));
1271 		}
1272 		break;
1273 #endif
1274 
1275 	  case S_IFCHR:
1276 		sprintf(p, "CHR: ");
1277 		p += strlen(p);
1278 		goto defprint;
1279 
1280 	  case S_IFBLK:
1281 		sprintf(p, "BLK: ");
1282 		p += strlen(p);
1283 		goto defprint;
1284 
1285 #ifdef S_IFIFO
1286 	  case S_IFIFO:
1287 		sprintf(p, "FIFO: ");
1288 		p += strlen(p);
1289 		goto defprint;
1290 #endif
1291 
1292 #ifdef S_IFDIR
1293 	  case S_IFDIR:
1294 		sprintf(p, "DIR: ");
1295 		p += strlen(p);
1296 		goto defprint;
1297 #endif
1298 
1299 #ifdef S_IFLNK
1300 	  case S_IFLNK:
1301 		sprintf(p, "LNK: ");
1302 		p += strlen(p);
1303 		goto defprint;
1304 #endif
1305 
1306 	  default:
1307 defprint:
1308 		sprintf(p, "dev=%d/%d, ino=%d, nlink=%d, u/gid=%d/%d, size=%ld",
1309 			major(st.st_dev), minor(st.st_dev), st.st_ino,
1310 			st.st_nlink, st.st_uid, st.st_gid, st.st_size);
1311 		break;
1312 	}
1313 
1314 printit:
1315 	if (logit)
1316 		syslog(LOG_DEBUG, "%s", buf);
1317 	else
1318 		printf("%s\n", buf);
1319 }
1320 /*
1321 **  SHORTENSTRING -- return short version of a string
1322 **
1323 **	If the string is already short, just return it.  If it is too
1324 **	long, return the head and tail of the string.
1325 **
1326 **	Parameters:
1327 **		s -- the string to shorten.
1328 **		m -- the max length of the string.
1329 **
1330 **	Returns:
1331 **		Either s or a short version of s.
1332 */
1333 
1334 #ifndef MAXSHORTSTR
1335 # define MAXSHORTSTR	203
1336 #endif
1337 
1338 char *
1339 shortenstring(s, m)
1340 	register char *s;
1341 	int m;
1342 {
1343 	int l;
1344 	static char buf[MAXSHORTSTR + 1];
1345 
1346 	l = strlen(s);
1347 	if (l < m)
1348 		return s;
1349 	if (m > MAXSHORTSTR)
1350 		m = MAXSHORTSTR;
1351 	else if (m < 10)
1352 	{
1353 		if (m < 5)
1354 		{
1355 			strncpy(buf, s, m);
1356 			buf[m] = '\0';
1357 			return buf;
1358 		}
1359 		strncpy(buf, s, m - 3);
1360 		strcpy(buf + m - 3, "...");
1361 		return buf;
1362 	}
1363 	m = (m - 3) / 2;
1364 	strncpy(buf, s, m);
1365 	strcpy(buf + m, "...");
1366 	strcpy(buf + m + 3, s + l - m);
1367 	return buf;
1368 }
1369