xref: /original-bsd/usr.sbin/sendmail/src/util.c (revision cb36a3b0)
1 /*
2  * Copyright (c) 1983 Eric P. Allman
3  * Copyright (c) 1988 Regents of the University of California.
4  * All rights reserved.
5  *
6  * %sccs.include.redist.c%
7  */
8 
9 #ifndef lint
10 static char sccsid[] = "@(#)util.c	6.16 (Berkeley) 04/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 -- uid to compare against.
381 **		mode -- mode bits that must match.
382 **
383 **	Returns:
384 **		0 if fn exists, is owned by uid, and matches mode.
385 **		An errno otherwise.  The actual errno is cleared.
386 **
387 **	Side Effects:
388 **		none.
389 */
390 
391 int
392 safefile(fn, uid, mode)
393 	char *fn;
394 	uid_t uid;
395 	int mode;
396 {
397 	struct stat stbuf;
398 
399 	if (stat(fn, &stbuf) < 0)
400 	{
401 		int ret = errno;
402 
403 		errno = 0;
404 		return ret;
405 	}
406 	if (stbuf.st_uid == uid && (stbuf.st_mode & mode) == mode)
407 		return 0;
408 	return EPERM;
409 }
410 /*
411 **  FIXCRLF -- fix <CR><LF> in line.
412 **
413 **	Looks for the <CR><LF> combination and turns it into the
414 **	UNIX canonical <NL> character.  It only takes one line,
415 **	i.e., it is assumed that the first <NL> found is the end
416 **	of the line.
417 **
418 **	Parameters:
419 **		line -- the line to fix.
420 **		stripnl -- if true, strip the newline also.
421 **
422 **	Returns:
423 **		none.
424 **
425 **	Side Effects:
426 **		line is changed in place.
427 */
428 
429 fixcrlf(line, stripnl)
430 	char *line;
431 	bool stripnl;
432 {
433 	register char *p;
434 
435 	p = strchr(line, '\n');
436 	if (p == NULL)
437 		return;
438 	if (p > line && p[-1] == '\r')
439 		p--;
440 	if (!stripnl)
441 		*p++ = '\n';
442 	*p = '\0';
443 }
444 /*
445 **  DFOPEN -- determined file open
446 **
447 **	This routine has the semantics of fopen, except that it will
448 **	keep trying a few times to make this happen.  The idea is that
449 **	on very loaded systems, we may run out of resources (inodes,
450 **	whatever), so this tries to get around it.
451 */
452 
453 FILE *
454 dfopen(filename, mode)
455 	char *filename;
456 	char *mode;
457 {
458 	register int tries;
459 	register FILE *fp;
460 	struct stat st;
461 
462 	for (tries = 0; tries < 10; tries++)
463 	{
464 		sleep((unsigned) (10 * tries));
465 		errno = 0;
466 		fp = fopen(filename, mode);
467 		if (fp != NULL)
468 			break;
469 		if (errno != ENFILE && errno != EINTR)
470 			break;
471 	}
472 	if (fp != NULL && fstat(fileno(fp), &st) >= 0 && S_ISREG(st.st_mode))
473 	{
474 		int locktype;
475 		extern bool lockfile();
476 
477 		/* lock the file to avoid accidental conflicts */
478 		if (*mode == 'w' || *mode == 'a')
479 			locktype = LOCK_EX;
480 		else
481 			locktype = LOCK_SH;
482 		(void) lockfile(fileno(fp), filename, locktype);
483 		errno = 0;
484 	}
485 	return (fp);
486 }
487 /*
488 **  PUTLINE -- put a line like fputs obeying SMTP conventions
489 **
490 **	This routine always guarantees outputing a newline (or CRLF,
491 **	as appropriate) at the end of the string.
492 **
493 **	Parameters:
494 **		l -- line to put.
495 **		fp -- file to put it onto.
496 **		m -- the mailer used to control output.
497 **
498 **	Returns:
499 **		none
500 **
501 **	Side Effects:
502 **		output of l to fp.
503 */
504 
505 putline(l, fp, m)
506 	register char *l;
507 	FILE *fp;
508 	MAILER *m;
509 {
510 	register char *p;
511 	register char svchar;
512 
513 	/* strip out 0200 bits -- these can look like TELNET protocol */
514 	if (bitnset(M_7BITS, m->m_flags))
515 	{
516 		for (p = l; svchar = *p; ++p)
517 			if (svchar & 0200)
518 				*p = svchar &~ 0200;
519 	}
520 
521 	do
522 	{
523 		/* find the end of the line */
524 		p = strchr(l, '\n');
525 		if (p == NULL)
526 			p = &l[strlen(l)];
527 
528 		/* check for line overflow */
529 		while (m->m_linelimit > 0 && (p - l) > m->m_linelimit)
530 		{
531 			register char *q = &l[m->m_linelimit - 1];
532 
533 			svchar = *q;
534 			*q = '\0';
535 			if (l[0] == '.' && bitnset(M_XDOT, m->m_flags))
536 				(void) putc('.', fp);
537 			fputs(l, fp);
538 			(void) putc('!', fp);
539 			fputs(m->m_eol, fp);
540 			*q = svchar;
541 			l = q;
542 		}
543 
544 		/* output last part */
545 		if (l[0] == '.' && bitnset(M_XDOT, m->m_flags))
546 			(void) putc('.', fp);
547 		for ( ; l < p; ++l)
548 			(void) putc(*l, fp);
549 		fputs(m->m_eol, fp);
550 		if (*l == '\n')
551 			++l;
552 	} while (l[0] != '\0');
553 }
554 /*
555 **  XUNLINK -- unlink a file, doing logging as appropriate.
556 **
557 **	Parameters:
558 **		f -- name of file to unlink.
559 **
560 **	Returns:
561 **		none.
562 **
563 **	Side Effects:
564 **		f is unlinked.
565 */
566 
567 xunlink(f)
568 	char *f;
569 {
570 	register int i;
571 
572 # ifdef LOG
573 	if (LogLevel > 98)
574 		syslog(LOG_DEBUG, "%s: unlink %s", CurEnv->e_id, f);
575 # endif /* LOG */
576 
577 	i = unlink(f);
578 # ifdef LOG
579 	if (i < 0 && LogLevel > 97)
580 		syslog(LOG_DEBUG, "%s: unlink-fail %d", f, errno);
581 # endif /* LOG */
582 }
583 /*
584 **  XFCLOSE -- close a file, doing logging as appropriate.
585 **
586 **	Parameters:
587 **		fp -- file pointer for the file to close
588 **		a, b -- miscellaneous crud to print for debugging
589 **
590 **	Returns:
591 **		none.
592 **
593 **	Side Effects:
594 **		fp is closed.
595 */
596 
597 xfclose(fp, a, b)
598 	FILE *fp;
599 	char *a, *b;
600 {
601 	if (tTd(53, 99))
602 		printf("xfclose(%x) %s %s\n", fp, a, b);
603 	if (fclose(fp) < 0 && tTd(53, 99))
604 		printf("xfclose FAILURE: %s\n", errstring(errno));
605 }
606 /*
607 **  SFGETS -- "safe" fgets -- times out and ignores random interrupts.
608 **
609 **	Parameters:
610 **		buf -- place to put the input line.
611 **		siz -- size of buf.
612 **		fp -- file to read from.
613 **		timeout -- the timeout before error occurs.
614 **
615 **	Returns:
616 **		NULL on error (including timeout).  This will also leave
617 **			buf containing a null string.
618 **		buf otherwise.
619 **
620 **	Side Effects:
621 **		none.
622 */
623 
624 static jmp_buf	CtxReadTimeout;
625 
626 char *
627 sfgets(buf, siz, fp, timeout)
628 	char *buf;
629 	int siz;
630 	FILE *fp;
631 	time_t timeout;
632 {
633 	register EVENT *ev = NULL;
634 	register char *p;
635 	static int readtimeout();
636 
637 	/* set the timeout */
638 	if (timeout != 0)
639 	{
640 		if (setjmp(CtxReadTimeout) != 0)
641 		{
642 # ifdef LOG
643 			syslog(LOG_NOTICE,
644 			    "timeout waiting for input from %s\n",
645 			    CurHostName? CurHostName: "local");
646 # endif
647 			errno = 0;
648 			usrerr("451 timeout waiting for input");
649 			buf[0] = '\0';
650 			return (NULL);
651 		}
652 		ev = setevent(timeout, readtimeout, 0);
653 	}
654 
655 	/* try to read */
656 	p = NULL;
657 	while (p == NULL && !feof(fp) && !ferror(fp))
658 	{
659 		errno = 0;
660 		p = fgets(buf, siz, fp);
661 		if (errno == EINTR)
662 			clearerr(fp);
663 	}
664 
665 	/* clear the event if it has not sprung */
666 	clrevent(ev);
667 
668 	/* clean up the books and exit */
669 	LineNumber++;
670 	if (p == NULL)
671 	{
672 		buf[0] = '\0';
673 		return (NULL);
674 	}
675 	if (!EightBit)
676 		for (p = buf; *p != '\0'; p++)
677 			*p &= ~0200;
678 	return (buf);
679 }
680 
681 static
682 readtimeout()
683 {
684 	longjmp(CtxReadTimeout, 1);
685 }
686 /*
687 **  FGETFOLDED -- like fgets, but know about folded lines.
688 **
689 **	Parameters:
690 **		buf -- place to put result.
691 **		n -- bytes available.
692 **		f -- file to read from.
693 **
694 **	Returns:
695 **		input line(s) on success, NULL on error or EOF.
696 **		This will normally be buf -- unless the line is too
697 **			long, when it will be xalloc()ed.
698 **
699 **	Side Effects:
700 **		buf gets lines from f, with continuation lines (lines
701 **		with leading white space) appended.  CRLF's are mapped
702 **		into single newlines.  Any trailing NL is stripped.
703 */
704 
705 char *
706 fgetfolded(buf, n, f)
707 	char *buf;
708 	register int n;
709 	FILE *f;
710 {
711 	register char *p = buf;
712 	char *bp = buf;
713 	register int i;
714 
715 	n--;
716 	while ((i = getc(f)) != EOF)
717 	{
718 		if (i == '\r')
719 		{
720 			i = getc(f);
721 			if (i != '\n')
722 			{
723 				if (i != EOF)
724 					(void) ungetc(i, f);
725 				i = '\r';
726 			}
727 		}
728 		if (--n <= 0)
729 		{
730 			/* allocate new space */
731 			char *nbp;
732 			int nn;
733 
734 			nn = (p - bp);
735 			if (nn < MEMCHUNKSIZE)
736 				nn *= 2;
737 			else
738 				nn += MEMCHUNKSIZE;
739 			nbp = xalloc(nn);
740 			bcopy(bp, nbp, p - bp);
741 			p = &nbp[p - bp];
742 			if (bp != buf)
743 				free(bp);
744 			bp = nbp;
745 			n = nn - (p - bp);
746 		}
747 		*p++ = i;
748 		if (i == '\n')
749 		{
750 			LineNumber++;
751 			i = getc(f);
752 			if (i != EOF)
753 				(void) ungetc(i, f);
754 			if (i != ' ' && i != '\t')
755 				break;
756 		}
757 	}
758 	if (p == bp)
759 		return (NULL);
760 	*--p = '\0';
761 	return (bp);
762 }
763 /*
764 **  CURTIME -- return current time.
765 **
766 **	Parameters:
767 **		none.
768 **
769 **	Returns:
770 **		the current time.
771 **
772 **	Side Effects:
773 **		none.
774 */
775 
776 time_t
777 curtime()
778 {
779 	auto time_t t;
780 
781 	(void) time(&t);
782 	return (t);
783 }
784 /*
785 **  ATOBOOL -- convert a string representation to boolean.
786 **
787 **	Defaults to "TRUE"
788 **
789 **	Parameters:
790 **		s -- string to convert.  Takes "tTyY" as true,
791 **			others as false.
792 **
793 **	Returns:
794 **		A boolean representation of the string.
795 **
796 **	Side Effects:
797 **		none.
798 */
799 
800 bool
801 atobool(s)
802 	register char *s;
803 {
804 	if (*s == '\0' || strchr("tTyY", *s) != NULL)
805 		return (TRUE);
806 	return (FALSE);
807 }
808 /*
809 **  ATOOCT -- convert a string representation to octal.
810 **
811 **	Parameters:
812 **		s -- string to convert.
813 **
814 **	Returns:
815 **		An integer representing the string interpreted as an
816 **		octal number.
817 **
818 **	Side Effects:
819 **		none.
820 */
821 
822 atooct(s)
823 	register char *s;
824 {
825 	register int i = 0;
826 
827 	while (*s >= '0' && *s <= '7')
828 		i = (i << 3) | (*s++ - '0');
829 	return (i);
830 }
831 /*
832 **  WAITFOR -- wait for a particular process id.
833 **
834 **	Parameters:
835 **		pid -- process id to wait for.
836 **
837 **	Returns:
838 **		status of pid.
839 **		-1 if pid never shows up.
840 **
841 **	Side Effects:
842 **		none.
843 */
844 
845 waitfor(pid)
846 	int pid;
847 {
848 	auto int st;
849 	int i;
850 
851 	do
852 	{
853 		errno = 0;
854 		i = wait(&st);
855 	} while ((i >= 0 || errno == EINTR) && i != pid);
856 	if (i < 0)
857 		st = -1;
858 	return (st);
859 }
860 /*
861 **  BITINTERSECT -- tell if two bitmaps intersect
862 **
863 **	Parameters:
864 **		a, b -- the bitmaps in question
865 **
866 **	Returns:
867 **		TRUE if they have a non-null intersection
868 **		FALSE otherwise
869 **
870 **	Side Effects:
871 **		none.
872 */
873 
874 bool
875 bitintersect(a, b)
876 	BITMAP a;
877 	BITMAP b;
878 {
879 	int i;
880 
881 	for (i = BITMAPBYTES / sizeof (int); --i >= 0; )
882 		if ((a[i] & b[i]) != 0)
883 			return (TRUE);
884 	return (FALSE);
885 }
886 /*
887 **  BITZEROP -- tell if a bitmap is all zero
888 **
889 **	Parameters:
890 **		map -- the bit map to check
891 **
892 **	Returns:
893 **		TRUE if map is all zero.
894 **		FALSE if there are any bits set in map.
895 **
896 **	Side Effects:
897 **		none.
898 */
899 
900 bool
901 bitzerop(map)
902 	BITMAP map;
903 {
904 	int i;
905 
906 	for (i = BITMAPBYTES / sizeof (int); --i >= 0; )
907 		if (map[i] != 0)
908 			return (FALSE);
909 	return (TRUE);
910 }
911 /*
912 **  STRCONTAINEDIN -- tell if one string is contained in another
913 **
914 **	Parameters:
915 **		a -- possible substring.
916 **		b -- possible superstring.
917 **
918 **	Returns:
919 **		TRUE if a is contained in b.
920 **		FALSE otherwise.
921 */
922 
923 bool
924 strcontainedin(a, b)
925 	register char *a;
926 	register char *b;
927 {
928 	int l;
929 
930 	l = strlen(a);
931 	for (;;)
932 	{
933 		b = strchr(b, a[0]);
934 		if (b == NULL)
935 			return FALSE;
936 		if (strncmp(a, b, l) == 0)
937 			return TRUE;
938 		b++;
939 	}
940 }
941