misc.c revision 60825
1/* Copyright 1988,1990,1993,1994 by Paul Vixie
2 * All rights reserved
3 *
4 * Distribute freely, except: don't remove my name from the source or
5 * documentation (don't take credit for my work), mark your changes (don't
6 * get me blamed for your possible bugs), don't alter or remove this
7 * notice.  May be sold if buildable source is provided to buyer.  No
8 * warrantee of any kind, express or implied, is included with this
9 * software; use at your own risk, responsibility for damages (if any) to
10 * anyone resulting from the use of this software rests entirely with the
11 * user.
12 *
13 * Send bug reports, bug fixes, enhancements, requests, flames, etc., and
14 * I'll try to keep a version up to date.  I can be reached as follows:
15 * Paul Vixie          <paul@vix.com>          uunet!decwrl!vixie!paul
16 */
17
18#if !defined(lint) && !defined(LINT)
19static const char rcsid[] =
20  "$FreeBSD: head/usr.sbin/cron/lib/misc.c 60825 2000-05-23 13:44:00Z ghelmer $";
21#endif
22
23/* vix 26jan87 [RCS has the rest of the log]
24 * vix 30dec86 [written]
25 */
26
27
28#include "cron.h"
29#if SYS_TIME_H
30# include <sys/time.h>
31#else
32# include <time.h>
33#endif
34#include <sys/file.h>
35#include <sys/stat.h>
36#include <err.h>
37#include <errno.h>
38#include <string.h>
39#include <fcntl.h>
40#if defined(SYSLOG)
41# include <syslog.h>
42#endif
43
44
45#if defined(LOG_DAEMON) && !defined(LOG_CRON)
46#define LOG_CRON LOG_DAEMON
47#endif
48
49
50static int		LogFD = ERR;
51
52
53int
54strcmp_until(left, right, until)
55	char	*left;
56	char	*right;
57	int	until;
58{
59	register int	diff;
60
61	while (*left && *left != until && *left == *right) {
62		left++;
63		right++;
64	}
65
66	if ((*left=='\0' || *left == until) &&
67	    (*right=='\0' || *right == until)) {
68		diff = 0;
69	} else {
70		diff = *left - *right;
71	}
72
73	return diff;
74}
75
76
77/* strdtb(s) - delete trailing blanks in string 's' and return new length
78 */
79int
80strdtb(s)
81	char	*s;
82{
83	char	*x = s;
84
85	/* scan forward to the null
86	 */
87	while (*x)
88		x++;
89
90	/* scan backward to either the first character before the string,
91	 * or the last non-blank in the string, whichever comes first.
92	 */
93	do	{x--;}
94	while (x >= s && isspace(*x));
95
96	/* one character beyond where we stopped above is where the null
97	 * goes.
98	 */
99	*++x = '\0';
100
101	/* the difference between the position of the null character and
102	 * the position of the first character of the string is the length.
103	 */
104	return x - s;
105}
106
107
108int
109set_debug_flags(flags)
110	char	*flags;
111{
112	/* debug flags are of the form    flag[,flag ...]
113	 *
114	 * if an error occurs, print a message to stdout and return FALSE.
115	 * otherwise return TRUE after setting ERROR_FLAGS.
116	 */
117
118#if !DEBUGGING
119
120	printf("this program was compiled without debugging enabled\n");
121	return FALSE;
122
123#else /* DEBUGGING */
124
125	char	*pc = flags;
126
127	DebugFlags = 0;
128
129	while (*pc) {
130		char	**test;
131		int	mask;
132
133		/* try to find debug flag name in our list.
134		 */
135		for (	test = DebugFlagNames, mask = 1;
136			*test && strcmp_until(*test, pc, ',');
137			test++, mask <<= 1
138		    )
139			;
140
141		if (!*test) {
142			fprintf(stderr,
143				"unrecognized debug flag <%s> <%s>\n",
144				flags, pc);
145			return FALSE;
146		}
147
148		DebugFlags |= mask;
149
150		/* skip to the next flag
151		 */
152		while (*pc && *pc != ',')
153			pc++;
154		if (*pc == ',')
155			pc++;
156	}
157
158	if (DebugFlags) {
159		int	flag;
160
161		fprintf(stderr, "debug flags enabled:");
162
163		for (flag = 0;  DebugFlagNames[flag];  flag++)
164			if (DebugFlags & (1 << flag))
165				fprintf(stderr, " %s", DebugFlagNames[flag]);
166		fprintf(stderr, "\n");
167	}
168
169	return TRUE;
170
171#endif /* DEBUGGING */
172}
173
174
175void
176set_cron_uid()
177{
178#if defined(BSD) || defined(POSIX)
179	if (seteuid(ROOT_UID) < OK)
180		err(ERROR_EXIT, "seteuid");
181#else
182	if (setuid(ROOT_UID) < OK)
183		err(ERROR_EXIT, "setuid");
184#endif
185}
186
187
188void
189set_cron_cwd()
190{
191	struct stat	sb;
192
193	/* first check for CRONDIR ("/var/cron" or some such)
194	 */
195	if (stat(CRONDIR, &sb) < OK && errno == ENOENT) {
196		warn("%s", CRONDIR);
197		if (OK == mkdir(CRONDIR, 0700)) {
198			warnx("%s: created", CRONDIR);
199			stat(CRONDIR, &sb);
200		} else {
201			err(ERROR_EXIT, "%s: mkdir", CRONDIR);
202		}
203	}
204	if (!(sb.st_mode & S_IFDIR))
205		err(ERROR_EXIT, "'%s' is not a directory, bailing out", CRONDIR);
206	if (chdir(CRONDIR) < OK)
207		err(ERROR_EXIT, "cannot chdir(%s), bailing out", CRONDIR);
208
209	/* CRONDIR okay (now==CWD), now look at SPOOL_DIR ("tabs" or some such)
210	 */
211	if (stat(SPOOL_DIR, &sb) < OK && errno == ENOENT) {
212		warn("%s", SPOOL_DIR);
213		if (OK == mkdir(SPOOL_DIR, 0700)) {
214			warnx("%s: created", SPOOL_DIR);
215			stat(SPOOL_DIR, &sb);
216		} else {
217			err(ERROR_EXIT, "%s: mkdir", SPOOL_DIR);
218		}
219	}
220	if (!(sb.st_mode & S_IFDIR))
221		err(ERROR_EXIT, "'%s' is not a directory, bailing out", SPOOL_DIR);
222}
223
224
225/* acquire_daemonlock() - write our PID into /etc/cron.pid, unless
226 *	another daemon is already running, which we detect here.
227 *
228 * note: main() calls us twice; once before forking, once after.
229 *	we maintain static storage of the file pointer so that we
230 *	can rewrite our PID into the PIDFILE after the fork.
231 *
232 * it would be great if fflush() disassociated the file buffer.
233 */
234void
235acquire_daemonlock(closeflag)
236	int closeflag;
237{
238	static	FILE	*fp = NULL;
239
240	if (closeflag && fp) {
241		fclose(fp);
242		fp = NULL;
243		return;
244	}
245
246	if (!fp) {
247		char	pidfile[MAX_FNAME];
248		char	buf[MAX_TEMPSTR];
249		int	fd, otherpid;
250
251		(void) sprintf(pidfile, PIDFILE, PIDDIR);
252		if ((-1 == (fd = open(pidfile, O_RDWR|O_CREAT, 0644)))
253		    || (NULL == (fp = fdopen(fd, "r+")))
254		    ) {
255			sprintf(buf, "can't open or create %s: %s",
256				pidfile, strerror(errno));
257			log_it("CRON", getpid(), "DEATH", buf);
258			errx(ERROR_EXIT, "%s", buf);
259		}
260
261		if (flock(fd, LOCK_EX|LOCK_NB) < OK) {
262			int save_errno = errno;
263
264			fscanf(fp, "%d", &otherpid);
265			sprintf(buf, "can't lock %s, otherpid may be %d: %s",
266				pidfile, otherpid, strerror(save_errno));
267			log_it("CRON", getpid(), "DEATH", buf);
268			errx(ERROR_EXIT, "%s", buf);
269		}
270
271		(void) fcntl(fd, F_SETFD, 1);
272	}
273
274	rewind(fp);
275	fprintf(fp, "%d\n", getpid());
276	fflush(fp);
277	(void) ftruncate(fileno(fp), ftell(fp));
278
279	/* abandon fd and fp even though the file is open. we need to
280	 * keep it open and locked, but we don't need the handles elsewhere.
281	 */
282}
283
284/* get_char(file) : like getc() but increment LineNumber on newlines
285 */
286int
287get_char(file)
288	FILE	*file;
289{
290	int	ch;
291
292	ch = getc(file);
293	if (ch == '\n')
294		Set_LineNum(LineNumber + 1)
295	return ch;
296}
297
298
299/* unget_char(ch, file) : like ungetc but do LineNumber processing
300 */
301void
302unget_char(ch, file)
303	int	ch;
304	FILE	*file;
305{
306	ungetc(ch, file);
307	if (ch == '\n')
308		Set_LineNum(LineNumber - 1)
309}
310
311
312/* get_string(str, max, file, termstr) : like fgets() but
313 *		(1) has terminator string which should include \n
314 *		(2) will always leave room for the null
315 *		(3) uses get_char() so LineNumber will be accurate
316 *		(4) returns EOF or terminating character, whichever
317 */
318int
319get_string(string, size, file, terms)
320	char	*string;
321	int	size;
322	FILE	*file;
323	char	*terms;
324{
325	int	ch;
326
327	while (EOF != (ch = get_char(file)) && !strchr(terms, ch)) {
328		if (size > 1) {
329			*string++ = (char) ch;
330			size--;
331		}
332	}
333
334	if (size > 0)
335		*string = '\0';
336
337	return ch;
338}
339
340
341/* skip_comments(file) : read past comment (if any)
342 */
343void
344skip_comments(file)
345	FILE	*file;
346{
347	int	ch;
348
349	while (EOF != (ch = get_char(file))) {
350		/* ch is now the first character of a line.
351		 */
352
353		while (ch == ' ' || ch == '\t')
354			ch = get_char(file);
355
356		if (ch == EOF)
357			break;
358
359		/* ch is now the first non-blank character of a line.
360		 */
361
362		if (ch != '\n' && ch != '#')
363			break;
364
365		/* ch must be a newline or comment as first non-blank
366		 * character on a line.
367		 */
368
369		while (ch != '\n' && ch != EOF)
370			ch = get_char(file);
371
372		/* ch is now the newline of a line which we're going to
373		 * ignore.
374		 */
375	}
376	if (ch != EOF)
377		unget_char(ch, file);
378}
379
380
381/* int in_file(char *string, FILE *file)
382 *	return TRUE if one of the lines in file matches string exactly,
383 *	FALSE otherwise.
384 */
385static int
386in_file(string, file)
387	char *string;
388	FILE *file;
389{
390	char line[MAX_TEMPSTR];
391
392	rewind(file);
393	while (fgets(line, MAX_TEMPSTR, file)) {
394		if (line[0] != '\0')
395			line[strlen(line)-1] = '\0';
396		if (0 == strcmp(line, string))
397			return TRUE;
398	}
399	return FALSE;
400}
401
402
403/* int allowed(char *username)
404 *	returns TRUE if (ALLOW_FILE exists and user is listed)
405 *	or (DENY_FILE exists and user is NOT listed)
406 *	or (neither file exists but user=="root" so it's okay)
407 */
408int
409allowed(username)
410	char *username;
411{
412	static int	init = FALSE;
413	static FILE	*allow, *deny;
414
415	if (!init) {
416		init = TRUE;
417#if defined(ALLOW_FILE) && defined(DENY_FILE)
418		allow = fopen(ALLOW_FILE, "r");
419		deny = fopen(DENY_FILE, "r");
420		Debug(DMISC, ("allow/deny enabled, %d/%d\n", !!allow, !!deny))
421#else
422		allow = NULL;
423		deny = NULL;
424#endif
425	}
426
427	if (allow)
428		return (in_file(username, allow));
429	if (deny)
430		return (!in_file(username, deny));
431
432#if defined(ALLOW_ONLY_ROOT)
433	return (strcmp(username, ROOT_USER) == 0);
434#else
435	return TRUE;
436#endif
437}
438
439
440void
441log_it(username, xpid, event, detail)
442	char	*username;
443	int	xpid;
444	char	*event;
445	char	*detail;
446{
447	PID_T			pid = xpid;
448#if defined(LOG_FILE)
449	char			*msg;
450	TIME_T			now = time((TIME_T) 0);
451	register struct tm	*t = localtime(&now);
452#endif /*LOG_FILE*/
453
454#if defined(SYSLOG)
455	static int		syslog_open = 0;
456#endif
457
458#if defined(LOG_FILE)
459	/* we assume that MAX_TEMPSTR will hold the date, time, &punctuation.
460	 */
461	msg = malloc(strlen(username)
462		     + strlen(event)
463		     + strlen(detail)
464		     + MAX_TEMPSTR);
465
466	if (msg == NULL)
467		warnx("failed to allocate memory for log message");
468	else {
469		if (LogFD < OK) {
470			LogFD = open(LOG_FILE, O_WRONLY|O_APPEND|O_CREAT, 0600);
471			if (LogFD < OK) {
472				warn("can't open log file %s", LOG_FILE);
473			} else {
474				(void) fcntl(LogFD, F_SETFD, 1);
475			}
476		}
477
478		/* we have to sprintf() it because fprintf() doesn't always
479		 * write everything out in one chunk and this has to be
480		 * atomically appended to the log file.
481		 */
482		sprintf(msg, "%s (%02d/%02d-%02d:%02d:%02d-%d) %s (%s)\n",
483			username,
484			t->tm_mon+1, t->tm_mday, t->tm_hour, t->tm_min,
485			t->tm_sec, pid, event, detail);
486
487		/* we have to run strlen() because sprintf() returns (char*)
488		 * on old BSD.
489		 */
490		if (LogFD < OK || write(LogFD, msg, strlen(msg)) < OK) {
491			if (LogFD >= OK)
492				warn("%s", LOG_FILE);
493			warnx("can't write to log file");
494			write(STDERR, msg, strlen(msg));
495		}
496
497		free(msg);
498	}
499#endif /*LOG_FILE*/
500
501#if defined(SYSLOG)
502	if (!syslog_open) {
503		/* we don't use LOG_PID since the pid passed to us by
504		 * our client may not be our own.  therefore we want to
505		 * print the pid ourselves.
506		 */
507# ifdef LOG_DAEMON
508		openlog(ProgramName, LOG_PID, LOG_CRON);
509# else
510		openlog(ProgramName, LOG_PID);
511# endif
512		syslog_open = TRUE;		/* assume openlog success */
513	}
514
515	syslog(LOG_INFO, "(%s) %s (%s)\n", username, event, detail);
516
517#endif /*SYSLOG*/
518
519#if DEBUGGING
520	if (DebugFlags) {
521		fprintf(stderr, "log_it: (%s %d) %s (%s)\n",
522			username, pid, event, detail);
523	}
524#endif
525}
526
527
528void
529log_close() {
530	if (LogFD != ERR) {
531		close(LogFD);
532		LogFD = ERR;
533	}
534}
535
536
537/* two warnings:
538 *	(1) this routine is fairly slow
539 *	(2) it returns a pointer to static storage
540 */
541char *
542first_word(s, t)
543	register char *s;	/* string we want the first word of */
544	register char *t;	/* terminators, implicitly including \0 */
545{
546	static char retbuf[2][MAX_TEMPSTR + 1];	/* sure wish C had GC */
547	static int retsel = 0;
548	register char *rb, *rp;
549
550	/* select a return buffer */
551	retsel = 1-retsel;
552	rb = &retbuf[retsel][0];
553	rp = rb;
554
555	/* skip any leading terminators */
556	while (*s && (NULL != strchr(t, *s))) {
557		s++;
558	}
559
560	/* copy until next terminator or full buffer */
561	while (*s && (NULL == strchr(t, *s)) && (rp < &rb[MAX_TEMPSTR])) {
562		*rp++ = *s++;
563	}
564
565	/* finish the return-string and return it */
566	*rp = '\0';
567	return rb;
568}
569
570
571/* warning:
572 *	heavily ascii-dependent.
573 */
574void
575mkprint(dst, src, len)
576	register char *dst;
577	register unsigned char *src;
578	register int len;
579{
580	while (len-- > 0)
581	{
582		register unsigned char ch = *src++;
583
584		if (ch < ' ') {			/* control character */
585			*dst++ = '^';
586			*dst++ = ch + '@';
587		} else if (ch < 0177) {		/* printable */
588			*dst++ = ch;
589		} else if (ch == 0177) {	/* delete/rubout */
590			*dst++ = '^';
591			*dst++ = '?';
592		} else {			/* parity character */
593			sprintf(dst, "\\%03o", ch);
594			dst += 4;
595		}
596	}
597	*dst = '\0';
598}
599
600
601/* warning:
602 *	returns a pointer to malloc'd storage, you must call free yourself.
603 */
604char *
605mkprints(src, len)
606	register unsigned char *src;
607	register unsigned int len;
608{
609	register char *dst = malloc(len*4 + 1);
610
611	if (dst != NULL)
612		mkprint(dst, src, len);
613
614	return dst;
615}
616
617
618#ifdef MAIL_DATE
619/* Sat, 27 Feb 93 11:44:51 CST
620 * 123456789012345678901234567
621 */
622char *
623arpadate(clock)
624	time_t *clock;
625{
626	time_t t = clock ?*clock :time(0L);
627	struct tm *tm = localtime(&t);
628	static char ret[32];	/* zone name might be >3 chars */
629
630	if (tm->tm_year >= 100)
631		tm->tm_year += 1900;
632
633	(void) snprintf(ret, sizeof(ret), "%s, %2d %s %d %02d:%02d:%02d %s",
634		       DowNames[tm->tm_wday],
635		       tm->tm_mday,
636		       MonthNames[tm->tm_mon],
637		       tm->tm_year,
638		       tm->tm_hour,
639		       tm->tm_min,
640		       tm->tm_sec,
641		       TZONE(*tm));
642	return ret;
643}
644#endif /*MAIL_DATE*/
645
646
647#ifdef HAVE_SAVED_UIDS
648static int save_euid;
649int swap_uids() { save_euid = geteuid(); return seteuid(getuid()); }
650int swap_uids_back() { return seteuid(save_euid); }
651#else /*HAVE_SAVED_UIDS*/
652int swap_uids() { return setreuid(geteuid(), getuid()); }
653int swap_uids_back() { return swap_uids(); }
654#endif /*HAVE_SAVED_UIDS*/
655