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