1/*	$NetBSD$	*/
2
3/* Copyright 1988,1990,1993,1994 by Paul Vixie
4 * All rights reserved
5 */
6
7/*
8 * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
9 * Copyright (c) 1997,2000 by Internet Software Consortium, Inc.
10 *
11 * Permission to use, copy, modify, and distribute this software for any
12 * purpose with or without fee is hereby granted, provided that the above
13 * copyright notice and this permission notice appear in all copies.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES
16 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
17 * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR
18 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
19 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
20 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
21 * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
22 */
23#include <sys/cdefs.h>
24#if !defined(lint) && !defined(LINT)
25#if 0
26static char rcsid[] = "Id: misc.c,v 1.16 2004/01/23 18:56:43 vixie Exp";
27#else
28__RCSID("$NetBSD: misc.c,v 1.14 2008/02/16 07:26:00 matt Exp $");
29#endif
30#endif
31
32/* vix 26jan87 [RCS has the rest of the log]
33 * vix 30dec86 [written]
34 */
35
36#include "cron.h"
37#include <limits.h>
38#include <vis.h>
39
40#if defined(SYSLOG) && defined(LOG_FILE)
41# undef LOG_FILE
42#endif
43
44#if defined(LOG_DAEMON) && !defined(LOG_CRON)
45# define LOG_CRON LOG_DAEMON
46#endif
47
48#ifndef FACILITY
49#define FACILITY LOG_CRON
50#endif
51
52static int LogFD = ERR;
53
54#if defined(SYSLOG)
55static int syslog_open = FALSE;
56#endif
57
58static void mkprint(char *, char *, size_t);
59
60/*
61 * glue_strings is the overflow-safe equivalent of
62 *		sprintf(buffer, "%s%c%s", a, separator, b);
63 *
64 * returns 1 on success, 0 on failure.  'buffer' MUST NOT be used if
65 * glue_strings fails.
66 */
67int
68glue_strings(char *buffer, size_t buffer_size, const char *a, const char *b,
69	     char separator)
70{
71	char *buf;
72	char *buf_end;
73
74	if (buffer_size == 0)
75		return (0);
76	buf_end = buffer + buffer_size;
77	buf = buffer;
78
79	for ( /* nothing */; buf < buf_end && *a != '\0'; buf++, a++ )
80		*buf = *a;
81	if (buf == buf_end)
82		return (0);
83	if (separator != '/' || buf == buffer || buf[-1] != '/')
84		*buf++ = separator;
85	if (buf == buf_end)
86		return (0);
87	for ( /* nothing */; buf < buf_end && *b != '\0'; buf++, b++ )
88		*buf = *b;
89	if (buf == buf_end)
90		return (0);
91	*buf = '\0';
92	return (1);
93}
94
95int
96strcmp_until(const char *left, const char *right, char until) {
97	while (*left && *left != until && *left == *right) {
98		left++;
99		right++;
100	}
101
102	if ((*left=='\0' || *left == until) &&
103	    (*right=='\0' || *right == until)) {
104		return (0);
105	}
106	return (*left - *right);
107}
108
109#ifdef notdef
110/* strdtb(s) - delete trailing blanks in string 's' and return new length
111 */
112int
113strdtb(char *s) {
114	char	*x = s;
115
116	/* scan forward to the null
117	 */
118	while (*x)
119		x++;
120
121	/* scan backward to either the first character before the string,
122	 * or the last non-blank in the string, whichever comes first.
123	 */
124	do	{x--;}
125	while (x >= s && isspace((unsigned char)*x));
126
127	/* one character beyond where we stopped above is where the null
128	 * goes.
129	 */
130	*++x = '\0';
131
132	/* the difference between the position of the null character and
133	 * the position of the first character of the string is the length.
134	 */
135	return (int)(x - s);
136}
137#endif
138
139int
140set_debug_flags(const char *flags) {
141	/* debug flags are of the form    flag[,flag ...]
142	 *
143	 * if an error occurs, print a message to stdout and return FALSE.
144	 * otherwise return TRUE after setting ERROR_FLAGS.
145	 */
146
147#if !DEBUGGING
148
149	printf("this program was compiled without debugging enabled\n");
150	return (FALSE);
151
152#else /* DEBUGGING */
153
154	const char *pc = flags;
155
156	DebugFlags = 0;
157
158	while (*pc) {
159		const char	* const *test;
160		int		mask;
161
162		/* try to find debug flag name in our list.
163		 */
164		for (test = DebugFlagNames, mask = 1;
165		     *test != NULL && strcmp_until(*test, pc, ',');
166		     test++, mask <<= 1)
167			continue;
168
169		if (!*test) {
170			warnx("unrecognized debug flag <%s> <%s>\n", flags, pc);
171			return (FALSE);
172		}
173
174		DebugFlags |= mask;
175
176		/* skip to the next flag
177		 */
178		while (*pc && *pc != ',')
179			pc++;
180		if (*pc == ',')
181			pc++;
182	}
183
184	if (DebugFlags) {
185		int flag;
186
187		(void)fprintf(stderr, "debug flags enabled:");
188
189		for (flag = 0;  DebugFlagNames[flag];  flag++)
190			if (DebugFlags & (1 << flag))
191				(void)fprintf(stderr, " %s", DebugFlagNames[flag]);
192		(void)fprintf(stderr, "\n");
193	}
194
195	return (TRUE);
196
197#endif /* DEBUGGING */
198}
199
200void
201set_cron_uid(void) {
202#if defined(BSD) || defined(POSIX)
203	if (seteuid(ROOT_UID) < OK) {
204		err(ERROR_EXIT, "cannot seteuid");
205	}
206#else
207	if (setuid(ROOT_UID) < OK) {
208		err(ERROR_EXIT, "cannot setuid");
209	}
210#endif
211}
212
213void
214set_cron_cwd(void) {
215	struct stat sb;
216	struct group *grp = NULL;
217
218#ifdef CRON_GROUP
219	grp = getgrnam(CRON_GROUP);
220#endif
221	/* first check for CRONDIR ("/var/cron" or some such)
222	 */
223	if (stat(CRONDIR, &sb) < OK && errno == ENOENT) {
224		warn("Cannot stat `%s'", CRONDIR);
225		if (OK == mkdir(CRONDIR, 0710)) {
226			(void)fprintf(stderr, "%s: created\n", CRONDIR);
227			if (stat(CRONDIR, &sb) == -1)
228				err(ERROR_EXIT, "cannot stat `%s'", CRONDIR);
229		} else {
230			err(ERROR_EXIT, "cannot create `%s'", CRONDIR);
231		}
232	}
233	if (!S_ISDIR(sb.st_mode)) {
234		errx(ERROR_EXIT, "`%s' is not a directory, bailing out.",
235			CRONDIR);
236	}
237	if (chdir(CRONDIR) < OK) {
238		err(ERROR_EXIT, "cannot chdir `%s', bailing out.\n", CRONDIR);
239	}
240
241	/* CRONDIR okay (now==CWD), now look at SPOOL_DIR ("tabs" or some such)
242	 */
243	if (stat(SPOOL_DIR, &sb) < OK && errno == ENOENT) {
244		warn("cannot stat `%s'", SPOOL_DIR);
245		if (OK == mkdir(SPOOL_DIR, 0700)) {
246			(void)fprintf(stderr, "%s: created\n", SPOOL_DIR);
247			if (stat(SPOOL_DIR, &sb) == -1)
248				err(ERROR_EXIT, "cannot stat `%s'", CRONDIR);
249		} else {
250			err(ERROR_EXIT, "cannot create `%s'", SPOOL_DIR);
251		}
252	}
253	if (!S_ISDIR(sb.st_mode)) {
254		errx(ERROR_EXIT, "`%s' is not a directory, bailing out.",
255			SPOOL_DIR);
256	}
257	if (grp != NULL) {
258		if (sb.st_gid != grp->gr_gid)
259			if (chown(SPOOL_DIR, (uid_t)-1, grp->gr_gid) == -1)
260			    err(ERROR_EXIT, "cannot chown `%s'", SPOOL_DIR);
261		if (sb.st_mode != 01730)
262			if (chmod(SPOOL_DIR, 01730) == -1)
263			    err(ERROR_EXIT, "cannot chmod `%s'", SPOOL_DIR);
264	}
265}
266
267/* acquire_daemonlock() - write our PID into /etc/cron.pid, unless
268 *	another daemon is already running, which we detect here.
269 *
270 * note: main() calls us twice; once before forking, once after.
271 *	we maintain static storage of the file pointer so that we
272 *	can rewrite our PID into _PATH_CRON_PID after the fork.
273 */
274void
275acquire_daemonlock(int closeflag) {
276	static int fd = -1;
277	char buf[3*MAX_FNAME];
278	const char *pidfile;
279	char *ep;
280	long otherpid;
281	ssize_t num;
282
283	if (closeflag) {
284		/* close stashed fd for child so we don't leak it. */
285		if (fd != -1) {
286			(void)close(fd);
287			fd = -1;
288		}
289		return;
290	}
291
292	if (fd == -1) {
293		pidfile = _PATH_CRON_PID;
294		/* Initial mode is 0600 to prevent flock() race/DoS. */
295		if ((fd = open(pidfile, O_RDWR|O_CREAT, 0600)) == -1) {
296			(void)snprintf(buf, sizeof(buf),
297				"can't open or create %s: %s",
298				pidfile, strerror(errno));
299			log_it("CRON", getpid(), "DEATH", buf);
300			errx(ERROR_EXIT, "%s", buf);
301		}
302
303		if (flock(fd, LOCK_EX|LOCK_NB) < OK) {
304			int save_errno = errno;
305
306			memset(buf, 0, sizeof(buf));
307			if ((num = read(fd, buf, sizeof(buf) - 1)) > 0 &&
308			    (otherpid = strtol(buf, &ep, 10)) > 0 &&
309			    ep != buf && *ep == '\n' && otherpid != LONG_MAX) {
310				(void)snprintf(buf, sizeof(buf),
311				    "can't lock %s, otherpid may be %ld: %s",
312				    pidfile, otherpid, strerror(save_errno));
313			} else {
314				(void)snprintf(buf, sizeof(buf),
315				    "can't lock %s, otherpid unknown: %s",
316				    pidfile, strerror(save_errno));
317			}
318			log_it("CRON", getpid(), "DEATH", buf);
319			errx(ERROR_EXIT, "%s", buf);
320		}
321		(void) fchmod(fd, 0644);
322		(void) fcntl(fd, F_SETFD, 1);
323	}
324
325	(void)snprintf(buf, sizeof(buf), "%ld\n", (long)getpid());
326	(void) lseek(fd, (off_t)0, SEEK_SET);
327	num = write(fd, buf, strlen(buf));
328	(void) ftruncate(fd, num);
329
330	/* abandon fd even though the file is open. we need to keep
331	 * it open and locked, but we don't need the handles elsewhere.
332	 */
333}
334
335/* get_char(file) : like getc() but increment LineNumber on newlines
336 */
337int
338get_char(FILE *file) {
339	int ch;
340
341	ch = getc(file);
342	if (ch == '\n')
343		Set_LineNum(LineNumber + 1);
344	return (ch);
345}
346
347/* unget_char(ch, file) : like ungetc but do LineNumber processing
348 */
349void
350unget_char(int ch, FILE *file) {
351	(void)ungetc(ch, file);
352	if (ch == '\n')
353		Set_LineNum(LineNumber - 1);
354}
355
356/* get_string(str, max, file, termstr) : like fgets() but
357 *		(1) has terminator string which should include \n
358 *		(2) will always leave room for the null
359 *		(3) uses get_char() so LineNumber will be accurate
360 *		(4) returns EOF or terminating character, whichever
361 */
362int
363get_string(char *string, int size, FILE *file, const char *terms) {
364	int ch;
365
366	while (EOF != (ch = get_char(file)) && !strchr(terms, ch)) {
367		if (size > 1) {
368			*string++ = (char) ch;
369			size--;
370		}
371	}
372
373	if (size > 0)
374		*string = '\0';
375
376	return (ch);
377}
378
379/* skip_comments(file) : read past comment (if any)
380 */
381void
382skip_comments(FILE *file) {
383	int ch;
384
385	while (EOF != (ch = get_char(file))) {
386		/* ch is now the first character of a line.
387		 */
388
389		while (ch == ' ' || ch == '\t')
390			ch = get_char(file);
391
392		if (ch == EOF)
393			break;
394
395		/* ch is now the first non-blank character of a line.
396		 */
397
398		if (ch != '\n' && ch != '#')
399			break;
400
401		/* ch must be a newline or comment as first non-blank
402		 * character on a line.
403		 */
404
405		while (ch != '\n' && ch != EOF)
406			ch = get_char(file);
407
408		/* ch is now the newline of a line which we're going to
409		 * ignore.
410		 */
411	}
412	if (ch != EOF)
413		unget_char(ch, file);
414}
415
416void
417log_it(const char *username, PID_T xpid, const char *event, const char *detail) {
418#if defined(LOG_FILE) || DEBUGGING
419	PID_T pid = xpid;
420#endif
421#if defined(LOG_FILE)
422	char *msg;
423	size_t msglen;
424	TIME_T now = time((TIME_T) 0);
425	struct tm *t = localtime(&now);
426#endif /*LOG_FILE*/
427
428#if defined(LOG_FILE)
429	/* we assume that MAX_TEMPSTR will hold the date, time, &punctuation.
430	 */
431	msglen = strlen(username) + strlen(event) + strlen(detail) +
432	    MAX_TEMPSTR);
433	msg = malloc(msglen);
434	if (msg == NULL)
435		return;
436
437	if (LogFD < OK) {
438		LogFD = open(LOG_FILE, O_WRONLY|O_APPEND|O_CREAT, 0600);
439		if (LogFD < OK) {
440			warn("can't open log file `%s'", LOG_FILE);
441		} else {
442			(void) fcntl(LogFD, F_SETFD, FD_CLOEXEC);
443		}
444	}
445
446	/* we have to sprintf() it because fprintf() doesn't always write
447	 * everything out in one chunk and this has to be atomically appended
448	 * to the log file.
449	 */
450	(void)snprintf(msg, msglen,
451		"%s (%02d/%02d-%02d:%02d:%02d-%d) %s (%s)\n",
452		username,
453		t->tm_mon+1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec, pid,
454		event, detail);
455
456	/* we have to run strlen() because sprintf() returns (char*) on old BSD
457	 */
458	if (LogFD < OK || write(LogFD, msg, strlen(msg)) < OK) {
459		warn("can't write to log file");
460		write(STDERR, msg, strlen(msg));
461	}
462
463	free(msg);
464#endif /*LOG_FILE*/
465
466#if defined(SYSLOG)
467	if (!syslog_open) {
468# ifdef LOG_DAEMON
469		openlog(getprogname(), LOG_PID, FACILITY);
470# else
471		openlog(getprogname(), LOG_PID);
472# endif
473		syslog_open = TRUE;		/* assume openlog success */
474	}
475
476	syslog(LOG_INFO, "(%s) %s (%s)", username, event, detail);
477
478#endif /*SYSLOG*/
479
480#if DEBUGGING
481	if (DebugFlags) {
482		(void)fprintf(stderr, "log_it: (%s %ld) %s (%s)\n",
483			username, (long)pid, event, detail);
484	}
485#endif
486}
487
488void
489log_close(void) {
490	if (LogFD != ERR) {
491		(void)close(LogFD);
492		LogFD = ERR;
493	}
494#if defined(SYSLOG)
495	closelog();
496	syslog_open = FALSE;
497#endif /*SYSLOG*/
498}
499
500/* char *first_word(char *s, char *t)
501 *	return pointer to first word
502 * parameters:
503 *	s - string we want the first word of
504 *	t - terminators, implicitly including \0
505 * warnings:
506 *	(1) this routine is fairly slow
507 *	(2) it returns a pointer to static storage
508 */
509char *
510first_word(char *s, const char *t) {
511	static char retbuf[2][MAX_TEMPSTR + 1];	/* sure wish C had GC */
512	static int retsel = 0;
513	char *rb, *rp;
514
515	/* select a return buffer */
516	retsel = 1-retsel;
517	rb = &retbuf[retsel][0];
518	rp = rb;
519
520	/* skip any leading terminators */
521	while (*s && (NULL != strchr(t, *s))) {
522		s++;
523	}
524
525	/* copy until next terminator or full buffer */
526	while (*s && (NULL == strchr(t, *s)) && (rp < &rb[MAX_TEMPSTR])) {
527		*rp++ = *s++;
528	}
529
530	/* finish the return-string and return it */
531	*rp = '\0';
532	return (rb);
533}
534
535/* warning:
536 *	heavily ascii-dependent.
537 */
538static void
539mkprint(char *dst, char *src, size_t len)
540{
541	while(len > 0 && isblank((unsigned char) *src))
542		len--, src++;
543
544	(void)strvisx(dst, src, len, VIS_TAB|VIS_NL);
545}
546
547/* warning:
548 *	returns a pointer to malloc'd storage, you must call free yourself.
549 */
550char *
551mkprints(char *src, size_t len)
552{
553	char *dst = malloc(len*4 + 1);
554
555	if (dst)
556		mkprint(dst, src, len);
557
558	return (dst);
559}
560
561#ifdef MAIL_DATE
562/* Sat, 27 Feb 1993 11:44:51 -0800 (CST)
563 * 1234567890123456789012345678901234567
564 */
565char *
566arpadate(time_t *clock)
567{
568	time_t t = clock ? *clock : time((TIME_T) 0);
569	struct tm tm = *localtime(&t);
570	long gmtoff = get_gmtoff(&t, &tm);
571	int hours = gmtoff / SECONDS_PER_HOUR;
572	int minutes = (gmtoff - (hours * SECONDS_PER_HOUR)) / SECONDS_PER_MINUTE;
573	static char ret[64];	/* zone name might be >3 chars */
574
575	if (minutes < 0)
576		minutes = -minutes;
577
578	(void)strftime(ret, sizeof(ret), "%a, %e %b %Y %T ????? (%Z)", &tm);
579	(void)snprintf(strchr(ret, '?'), "% .2d%.2d", hours, minutes);
580	ret[sizeof(ret) - 1] = '\0';
581	return ret;
582}
583#endif /*MAIL_DATE*/
584
585size_t
586strlens(const char *last, ...) {
587	va_list ap;
588	size_t ret = 0;
589	const char *str;
590
591	va_start(ap, last);
592	for (str = last; str != NULL; str = va_arg(ap, const char *))
593		ret += strlen(str);
594	va_end(ap);
595	return (ret);
596}
597
598/* Return the offset from GMT in seconds (algorithm taken from sendmail).
599 *
600 * warning:
601 *	clobbers the static storage space used by localtime() and gmtime().
602 *	If the local pointer is non-NULL it *must* point to a local copy.
603 */
604#ifndef HAVE_TM_GMTOFF
605long get_gmtoff(time_t *clock, struct tm *local)
606{
607	struct tm gmt;
608	long offset;
609
610	gmt = *gmtime(clock);
611	if (local == NULL)
612		local = localtime(clock);
613
614	offset = (local->tm_sec - gmt.tm_sec) +
615	    ((local->tm_min - gmt.tm_min) * 60) +
616	    ((local->tm_hour - gmt.tm_hour) * 3600);
617
618	/* Timezone may cause year rollover to happen on a different day. */
619	if (local->tm_year < gmt.tm_year)
620		offset -= 24 * 3600;
621	else if (local->tm_year > gmt.tm_year)
622		offset -= 24 * 3600;
623	else if (local->tm_yday < gmt.tm_yday)
624		offset -= 24 * 3600;
625	else if (local->tm_yday > gmt.tm_yday)
626		offset += 24 * 3600;
627
628	return (offset);
629}
630#endif /* HAVE_TM_GMTOFF */
631