xref: /original-bsd/usr.sbin/sendmail/src/util.c (revision f51da917)
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.27 (Berkeley) 12/30/93";
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 **		fp -- file to put it onto.
650 **		m -- the mailer used to control output.
651 **
652 **	Returns:
653 **		none
654 **
655 **	Side Effects:
656 **		output of l to fp.
657 */
658 
659 putline(l, fp, m)
660 	register char *l;
661 	FILE *fp;
662 	MAILER *m;
663 {
664 	register char *p;
665 	register char svchar;
666 
667 	/* strip out 0200 bits -- these can look like TELNET protocol */
668 	if (bitnset(M_7BITS, m->m_flags))
669 	{
670 		for (p = l; (svchar = *p) != '\0'; ++p)
671 			if (bitset(0200, svchar))
672 				*p = svchar &~ 0200;
673 	}
674 
675 	do
676 	{
677 		/* find the end of the line */
678 		p = strchr(l, '\n');
679 		if (p == NULL)
680 			p = &l[strlen(l)];
681 
682 		if (TrafficLogFile != NULL)
683 			fprintf(TrafficLogFile, "%05d >>> ", getpid());
684 
685 		/* check for line overflow */
686 		while (m->m_linelimit > 0 && (p - l) > m->m_linelimit)
687 		{
688 			register char *q = &l[m->m_linelimit - 1];
689 
690 			svchar = *q;
691 			*q = '\0';
692 			if (l[0] == '.' && bitnset(M_XDOT, m->m_flags))
693 			{
694 				(void) putc('.', fp);
695 				if (TrafficLogFile != NULL)
696 					(void) putc('.', TrafficLogFile);
697 			}
698 			fputs(l, fp);
699 			(void) putc('!', fp);
700 			fputs(m->m_eol, fp);
701 			if (TrafficLogFile != NULL)
702 				fprintf(TrafficLogFile, "%s!\n%05d >>> ",
703 					l, getpid());
704 			*q = svchar;
705 			l = q;
706 		}
707 
708 		/* output last part */
709 		if (l[0] == '.' && bitnset(M_XDOT, m->m_flags))
710 		{
711 			(void) putc('.', fp);
712 			if (TrafficLogFile != NULL)
713 				(void) putc('.', TrafficLogFile);
714 		}
715 		if (TrafficLogFile != NULL)
716 			fprintf(TrafficLogFile, "%.*s\n", p - l, l);
717 		for ( ; l < p; ++l)
718 			(void) putc(*l, fp);
719 		fputs(m->m_eol, fp);
720 		if (*l == '\n')
721 			++l;
722 	} while (l[0] != '\0');
723 }
724 /*
725 **  XUNLINK -- unlink a file, doing logging as appropriate.
726 **
727 **	Parameters:
728 **		f -- name of file to unlink.
729 **
730 **	Returns:
731 **		none.
732 **
733 **	Side Effects:
734 **		f is unlinked.
735 */
736 
737 xunlink(f)
738 	char *f;
739 {
740 	register int i;
741 
742 # ifdef LOG
743 	if (LogLevel > 98)
744 		syslog(LOG_DEBUG, "%s: unlink %s", CurEnv->e_id, f);
745 # endif /* LOG */
746 
747 	i = unlink(f);
748 # ifdef LOG
749 	if (i < 0 && LogLevel > 97)
750 		syslog(LOG_DEBUG, "%s: unlink-fail %d", f, errno);
751 # endif /* LOG */
752 }
753 /*
754 **  XFCLOSE -- close a file, doing logging as appropriate.
755 **
756 **	Parameters:
757 **		fp -- file pointer for the file to close
758 **		a, b -- miscellaneous crud to print for debugging
759 **
760 **	Returns:
761 **		none.
762 **
763 **	Side Effects:
764 **		fp is closed.
765 */
766 
767 xfclose(fp, a, b)
768 	FILE *fp;
769 	char *a, *b;
770 {
771 	if (tTd(53, 99))
772 		printf("xfclose(%x) %s %s\n", fp, a, b);
773 #ifdef XDEBUG
774 	if (fileno(fp) == 1)
775 		syserr("xfclose(%s %s): fd = 1", a, b);
776 #endif
777 	if (fclose(fp) < 0 && tTd(53, 99))
778 		printf("xfclose FAILURE: %s\n", errstring(errno));
779 }
780 /*
781 **  SFGETS -- "safe" fgets -- times out and ignores random interrupts.
782 **
783 **	Parameters:
784 **		buf -- place to put the input line.
785 **		siz -- size of buf.
786 **		fp -- file to read from.
787 **		timeout -- the timeout before error occurs.
788 **		during -- what we are trying to read (for error messages).
789 **
790 **	Returns:
791 **		NULL on error (including timeout).  This will also leave
792 **			buf containing a null string.
793 **		buf otherwise.
794 **
795 **	Side Effects:
796 **		none.
797 */
798 
799 static jmp_buf	CtxReadTimeout;
800 static int	readtimeout();
801 
802 char *
803 sfgets(buf, siz, fp, timeout, during)
804 	char *buf;
805 	int siz;
806 	FILE *fp;
807 	time_t timeout;
808 	char *during;
809 {
810 	register EVENT *ev = NULL;
811 	register char *p;
812 
813 	/* set the timeout */
814 	if (timeout != 0)
815 	{
816 		if (setjmp(CtxReadTimeout) != 0)
817 		{
818 # ifdef LOG
819 			syslog(LOG_NOTICE,
820 			    "timeout waiting for input from %s during %s\n",
821 			    CurHostName? CurHostName: "local", during);
822 # endif
823 			errno = 0;
824 			usrerr("451 timeout waiting for input during %s",
825 				during);
826 			buf[0] = '\0';
827 #ifdef XDEBUG
828 			checkfd012(during);
829 #endif
830 			return (NULL);
831 		}
832 		ev = setevent(timeout, readtimeout, 0);
833 	}
834 
835 	/* try to read */
836 	p = NULL;
837 	while (!feof(fp) && !ferror(fp))
838 	{
839 		errno = 0;
840 		p = fgets(buf, siz, fp);
841 		if (p != NULL || errno != EINTR)
842 			break;
843 		clearerr(fp);
844 	}
845 
846 	/* clear the event if it has not sprung */
847 	clrevent(ev);
848 
849 	/* clean up the books and exit */
850 	LineNumber++;
851 	if (p == NULL)
852 	{
853 		buf[0] = '\0';
854 		if (TrafficLogFile != NULL)
855 			fprintf(TrafficLogFile, "%05d <<< [EOF]\n", getpid());
856 		return (NULL);
857 	}
858 	if (TrafficLogFile != NULL)
859 		fprintf(TrafficLogFile, "%05d <<< %s", getpid(), buf);
860 	if (SevenBit)
861 		for (p = buf; *p != '\0'; p++)
862 			*p &= ~0200;
863 	return (buf);
864 }
865 
866 static
867 readtimeout()
868 {
869 	longjmp(CtxReadTimeout, 1);
870 }
871 /*
872 **  FGETFOLDED -- like fgets, but know about folded lines.
873 **
874 **	Parameters:
875 **		buf -- place to put result.
876 **		n -- bytes available.
877 **		f -- file to read from.
878 **
879 **	Returns:
880 **		input line(s) on success, NULL on error or EOF.
881 **		This will normally be buf -- unless the line is too
882 **			long, when it will be xalloc()ed.
883 **
884 **	Side Effects:
885 **		buf gets lines from f, with continuation lines (lines
886 **		with leading white space) appended.  CRLF's are mapped
887 **		into single newlines.  Any trailing NL is stripped.
888 */
889 
890 char *
891 fgetfolded(buf, n, f)
892 	char *buf;
893 	register int n;
894 	FILE *f;
895 {
896 	register char *p = buf;
897 	char *bp = buf;
898 	register int i;
899 
900 	n--;
901 	while ((i = getc(f)) != EOF)
902 	{
903 		if (i == '\r')
904 		{
905 			i = getc(f);
906 			if (i != '\n')
907 			{
908 				if (i != EOF)
909 					(void) ungetc(i, f);
910 				i = '\r';
911 			}
912 		}
913 		if (--n <= 0)
914 		{
915 			/* allocate new space */
916 			char *nbp;
917 			int nn;
918 
919 			nn = (p - bp);
920 			if (nn < MEMCHUNKSIZE)
921 				nn *= 2;
922 			else
923 				nn += MEMCHUNKSIZE;
924 			nbp = xalloc(nn);
925 			bcopy(bp, nbp, p - bp);
926 			p = &nbp[p - bp];
927 			if (bp != buf)
928 				free(bp);
929 			bp = nbp;
930 			n = nn - (p - bp);
931 		}
932 		*p++ = i;
933 		if (i == '\n')
934 		{
935 			LineNumber++;
936 			i = getc(f);
937 			if (i != EOF)
938 				(void) ungetc(i, f);
939 			if (i != ' ' && i != '\t')
940 				break;
941 		}
942 	}
943 	if (p == bp)
944 		return (NULL);
945 	*--p = '\0';
946 	return (bp);
947 }
948 /*
949 **  CURTIME -- return current time.
950 **
951 **	Parameters:
952 **		none.
953 **
954 **	Returns:
955 **		the current time.
956 **
957 **	Side Effects:
958 **		none.
959 */
960 
961 time_t
962 curtime()
963 {
964 	auto time_t t;
965 
966 	(void) time(&t);
967 	return (t);
968 }
969 /*
970 **  ATOBOOL -- convert a string representation to boolean.
971 **
972 **	Defaults to "TRUE"
973 **
974 **	Parameters:
975 **		s -- string to convert.  Takes "tTyY" as true,
976 **			others as false.
977 **
978 **	Returns:
979 **		A boolean representation of the string.
980 **
981 **	Side Effects:
982 **		none.
983 */
984 
985 bool
986 atobool(s)
987 	register char *s;
988 {
989 	if (s == NULL || *s == '\0' || strchr("tTyY", *s) != NULL)
990 		return (TRUE);
991 	return (FALSE);
992 }
993 /*
994 **  ATOOCT -- convert a string representation to octal.
995 **
996 **	Parameters:
997 **		s -- string to convert.
998 **
999 **	Returns:
1000 **		An integer representing the string interpreted as an
1001 **		octal number.
1002 **
1003 **	Side Effects:
1004 **		none.
1005 */
1006 
1007 atooct(s)
1008 	register char *s;
1009 {
1010 	register int i = 0;
1011 
1012 	while (*s >= '0' && *s <= '7')
1013 		i = (i << 3) | (*s++ - '0');
1014 	return (i);
1015 }
1016 /*
1017 **  WAITFOR -- wait for a particular process id.
1018 **
1019 **	Parameters:
1020 **		pid -- process id to wait for.
1021 **
1022 **	Returns:
1023 **		status of pid.
1024 **		-1 if pid never shows up.
1025 **
1026 **	Side Effects:
1027 **		none.
1028 */
1029 
1030 int
1031 waitfor(pid)
1032 	int pid;
1033 {
1034 #ifdef WAITUNION
1035 	union wait st;
1036 #else
1037 	auto int st;
1038 #endif
1039 	int i;
1040 
1041 	do
1042 	{
1043 		errno = 0;
1044 		i = wait(&st);
1045 	} while ((i >= 0 || errno == EINTR) && i != pid);
1046 	if (i < 0)
1047 		return -1;
1048 #ifdef WAITUNION
1049 	return st.w_status;
1050 #else
1051 	return st;
1052 #endif
1053 }
1054 /*
1055 **  BITINTERSECT -- tell if two bitmaps intersect
1056 **
1057 **	Parameters:
1058 **		a, b -- the bitmaps in question
1059 **
1060 **	Returns:
1061 **		TRUE if they have a non-null intersection
1062 **		FALSE otherwise
1063 **
1064 **	Side Effects:
1065 **		none.
1066 */
1067 
1068 bool
1069 bitintersect(a, b)
1070 	BITMAP a;
1071 	BITMAP b;
1072 {
1073 	int i;
1074 
1075 	for (i = BITMAPBYTES / sizeof (int); --i >= 0; )
1076 		if ((a[i] & b[i]) != 0)
1077 			return (TRUE);
1078 	return (FALSE);
1079 }
1080 /*
1081 **  BITZEROP -- tell if a bitmap is all zero
1082 **
1083 **	Parameters:
1084 **		map -- the bit map to check
1085 **
1086 **	Returns:
1087 **		TRUE if map is all zero.
1088 **		FALSE if there are any bits set in map.
1089 **
1090 **	Side Effects:
1091 **		none.
1092 */
1093 
1094 bool
1095 bitzerop(map)
1096 	BITMAP map;
1097 {
1098 	int i;
1099 
1100 	for (i = BITMAPBYTES / sizeof (int); --i >= 0; )
1101 		if (map[i] != 0)
1102 			return (FALSE);
1103 	return (TRUE);
1104 }
1105 /*
1106 **  STRCONTAINEDIN -- tell if one string is contained in another
1107 **
1108 **	Parameters:
1109 **		a -- possible substring.
1110 **		b -- possible superstring.
1111 **
1112 **	Returns:
1113 **		TRUE if a is contained in b.
1114 **		FALSE otherwise.
1115 */
1116 
1117 bool
1118 strcontainedin(a, b)
1119 	register char *a;
1120 	register char *b;
1121 {
1122 	int la;
1123 	int lb;
1124 	int c;
1125 
1126 	la = strlen(a);
1127 	lb = strlen(b);
1128 	c = *a;
1129 	if (isascii(c) && isupper(c))
1130 		c = tolower(c);
1131 	for (; lb-- >= la; b++)
1132 	{
1133 		if (*b != c && isascii(*b) && isupper(*b) && tolower(*b) != c)
1134 			continue;
1135 		if (strncasecmp(a, b, la) == 0)
1136 			return TRUE;
1137 	}
1138 	return FALSE;
1139 }
1140 /*
1141 **  CHECKFD012 -- check low numbered file descriptors
1142 **
1143 **	File descriptors 0, 1, and 2 should be open at all times.
1144 **	This routine verifies that, and fixes it if not true.
1145 **
1146 **	Parameters:
1147 **		where -- a tag printed if the assertion failed
1148 **
1149 **	Returns:
1150 **		none
1151 */
1152 
1153 checkfd012(where)
1154 	char *where;
1155 {
1156 #ifdef XDEBUG
1157 	register int i;
1158 	struct stat stbuf;
1159 
1160 	for (i = 0; i < 3; i++)
1161 	{
1162 		if (fstat(i, &stbuf) < 0 && errno != EOPNOTSUPP)
1163 		{
1164 			/* oops.... */
1165 			int fd;
1166 
1167 			syserr("%s: fd %d not open", where, i);
1168 			fd = open("/dev/null", i == 0 ? O_RDONLY : O_WRONLY, 0666);
1169 			if (fd != i)
1170 			{
1171 				(void) dup2(fd, i);
1172 				(void) close(fd);
1173 			}
1174 		}
1175 	}
1176 #endif /* XDEBUG */
1177 }
1178 /*
1179 **  PRINTOPENFDS -- print the open file descriptors (for debugging)
1180 **
1181 **	Parameters:
1182 **		logit -- if set, send output to syslog; otherwise
1183 **			print for debugging.
1184 **
1185 **	Returns:
1186 **		none.
1187 */
1188 
1189 #include <netdb.h>
1190 #include <arpa/inet.h>
1191 
1192 printopenfds(logit)
1193 	bool logit;
1194 {
1195 	register int fd;
1196 	extern int DtableSize;
1197 
1198 	for (fd = 0; fd < DtableSize; fd++)
1199 		dumpfd(fd, FALSE, logit);
1200 }
1201 /*
1202 **  DUMPFD -- dump a file descriptor
1203 **
1204 **	Parameters:
1205 **		fd -- the file descriptor to dump.
1206 **		printclosed -- if set, print a notification even if
1207 **			it is closed; otherwise print nothing.
1208 **		logit -- if set, send output to syslog instead of stdout.
1209 */
1210 
1211 dumpfd(fd, printclosed, logit)
1212 	int fd;
1213 	bool printclosed;
1214 	bool logit;
1215 {
1216 	register struct hostent *hp;
1217 	register char *p;
1218 	struct sockaddr_in sin;
1219 	auto int slen;
1220 	struct stat st;
1221 	char buf[200];
1222 
1223 	p = buf;
1224 	sprintf(p, "%3d: ", fd);
1225 	p += strlen(p);
1226 
1227 	if (fstat(fd, &st) < 0)
1228 	{
1229 		if (printclosed || errno != EBADF)
1230 		{
1231 			sprintf(p, "CANNOT STAT (%s)", errstring(errno));
1232 			goto printit;
1233 		}
1234 		return;
1235 	}
1236 
1237 	slen = fcntl(fd, F_GETFL, NULL);
1238 	if (slen != -1)
1239 	{
1240 		sprintf(p, "fl=0x%x, ", slen);
1241 		p += strlen(p);
1242 	}
1243 
1244 	sprintf(p, "mode=%o: ", st.st_mode);
1245 	p += strlen(p);
1246 	switch (st.st_mode & S_IFMT)
1247 	{
1248 #ifdef S_IFSOCK
1249 	  case S_IFSOCK:
1250 		sprintf(p, "SOCK ");
1251 		p += strlen(p);
1252 		slen = sizeof sin;
1253 		if (getsockname(fd, (struct sockaddr *) &sin, &slen) < 0)
1254 			sprintf(p, "(badsock)");
1255 		else
1256 		{
1257 			hp = gethostbyaddr((char *) &sin.sin_addr, slen, AF_INET);
1258 			sprintf(p, "%s/%d", hp == NULL ? inet_ntoa(sin.sin_addr)
1259 						   : hp->h_name, ntohs(sin.sin_port));
1260 		}
1261 		p += strlen(p);
1262 		sprintf(p, "->");
1263 		p += strlen(p);
1264 		slen = sizeof sin;
1265 		if (getpeername(fd, (struct sockaddr *) &sin, &slen) < 0)
1266 			sprintf(p, "(badsock)");
1267 		else
1268 		{
1269 			hp = gethostbyaddr((char *) &sin.sin_addr, slen, AF_INET);
1270 			sprintf(p, "%s/%d", hp == NULL ? inet_ntoa(sin.sin_addr)
1271 						   : hp->h_name, ntohs(sin.sin_port));
1272 		}
1273 		break;
1274 #endif
1275 
1276 	  case S_IFCHR:
1277 		sprintf(p, "CHR: ");
1278 		p += strlen(p);
1279 		goto defprint;
1280 
1281 	  case S_IFBLK:
1282 		sprintf(p, "BLK: ");
1283 		p += strlen(p);
1284 		goto defprint;
1285 
1286 	  default:
1287 defprint:
1288 		sprintf(p, "dev=%d/%d, ino=%d, nlink=%d, u/gid=%d/%d, size=%ld",
1289 			major(st.st_dev), minor(st.st_dev), st.st_ino,
1290 			st.st_nlink, st.st_uid, st.st_gid, st.st_size);
1291 		break;
1292 	}
1293 
1294 printit:
1295 	if (logit)
1296 		syslog(LOG_DEBUG, "%s", buf);
1297 	else
1298 		printf("%s\n", buf);
1299 }
1300 /*
1301 **  SHORTENSTRING -- return short version of a string
1302 **
1303 **	If the string is already short, just return it.  If it is too
1304 **	long, return the head and tail of the string.
1305 **
1306 **	Parameters:
1307 **		s -- the string to shorten.
1308 **		m -- the max length of the string.
1309 **
1310 **	Returns:
1311 **		Either s or a short version of s.
1312 */
1313 
1314 #ifndef MAXSHORTSTR
1315 # define MAXSHORTSTR	203
1316 #endif
1317 
1318 char *
1319 shortenstring(s, m)
1320 	register char *s;
1321 	int m;
1322 {
1323 	int l;
1324 	static char buf[MAXSHORTSTR + 1];
1325 
1326 	l = strlen(s);
1327 	if (l < m)
1328 		return s;
1329 	if (m > MAXSHORTSTR)
1330 		m = MAXSHORTSTR;
1331 	else if (m < 10)
1332 	{
1333 		if (m < 5)
1334 		{
1335 			strncpy(buf, s, m);
1336 			buf[m] = '\0';
1337 			return buf;
1338 		}
1339 		strncpy(buf, s, m - 3);
1340 		strcpy(buf + m - 3, "...");
1341 		return buf;
1342 	}
1343 	m = (m - 3) / 2;
1344 	strncpy(buf, s, m);
1345 	strcpy(buf + m, "...");
1346 	strcpy(buf + m + 3, s + l - m);
1347 	return buf;
1348 }
1349