1/*	$NetBSD: misc.c,v 1.5 2017/08/17 08:53:00 christos Exp $	*/
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.5 2017/08/17 08:53:00 christos 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#ifdef ENABLE_FIX_DIRECTORIES
224	if (stat(CRONDIR, &sb) < OK && errno == ENOENT) {
225		warn("Cannot stat `%s'", CRONDIR);
226		if (OK == mkdir(CRONDIR, 0710)) {
227			(void)fprintf(stderr, "%s: created\n", CRONDIR);
228			if (stat(CRONDIR, &sb) == -1)
229				err(ERROR_EXIT, "cannot stat `%s'", CRONDIR);
230		} else {
231			err(ERROR_EXIT, "cannot create `%s'", CRONDIR);
232		}
233	}
234	if (!S_ISDIR(sb.st_mode)) {
235		errx(ERROR_EXIT, "`%s' is not a directory, bailing out.",
236			CRONDIR);
237	}
238#endif /* ENABLE_FIX_DIRECTORIES */
239	if (chdir(CRONDIR) < OK) {
240		err(ERROR_EXIT, "cannot chdir `%s', bailing out.\n", CRONDIR);
241	}
242
243	/* CRONDIR okay (now==CWD), now look at SPOOL_DIR ("tabs" or some such)
244	 */
245#ifdef ENABLE_FIX_DIRECTORIES
246	if (stat(SPOOL_DIR, &sb) < OK && errno == ENOENT) {
247		warn("cannot stat `%s'", SPOOL_DIR);
248		if (OK == mkdir(SPOOL_DIR, 0700)) {
249			(void)fprintf(stderr, "%s: created\n", SPOOL_DIR);
250			if (stat(SPOOL_DIR, &sb) == -1)
251				err(ERROR_EXIT, "cannot stat `%s'", CRONDIR);
252		} else {
253			err(ERROR_EXIT, "cannot create `%s'", SPOOL_DIR);
254		}
255	}
256#else
257	if (stat(SPOOL_DIR, &sb)) {
258		err(ERROR_EXIT, "cannot stat `%s'", SPOOL_DIR);
259	}
260#endif /* ENABLE_FIX_DIRECTORIES */
261	if (!S_ISDIR(sb.st_mode)) {
262		errx(ERROR_EXIT, "`%s' is not a directory, bailing out.",
263			SPOOL_DIR);
264	}
265	if (grp != NULL) {
266		if (sb.st_gid != grp->gr_gid) {
267#ifdef ENABLE_FIX_DIRECTORIES
268			errx(ERROR_EXIT, "Bad group %d != %d for `%s'",
269			    (int)sb.st_gid, (int)grp->gr_gid, SPOOL_DIR);
270#else
271			if (chown(SPOOL_DIR, (uid_t)-1, grp->gr_gid) == -1)
272			    err(ERROR_EXIT, "cannot chown `%s'", SPOOL_DIR);
273#endif
274		}
275		if (sb.st_mode != 01730)
276#ifdef ENABLE_FIX_DIRECTORIES
277			errx(ERROR_EXIT, "Bad mode %#o != %#o for `%s'",
278			    (int)sb.st_mode, 01730, SPOOL_DIR);
279#else
280			if (chmod(SPOOL_DIR, 01730) == -1)
281			    err(ERROR_EXIT, "cannot chmod `%s'", SPOOL_DIR);
282#endif
283	}
284}
285
286/* acquire_daemonlock() - write our PID into /etc/cron.pid, unless
287 *	another daemon is already running, which we detect here.
288 *
289 * note: main() calls us twice; once before forking, once after.
290 *	we maintain static storage of the file pointer so that we
291 *	can rewrite our PID into _PATH_CRON_PID after the fork.
292 */
293void
294acquire_daemonlock(int closeflag) {
295	static int fd = -1;
296	char buf[3*MAX_FNAME];
297	const char *pidfile;
298	char *ep;
299	long otherpid;
300	ssize_t num;
301
302	if (closeflag) {
303		/* close stashed fd for child so we don't leak it. */
304		if (fd != -1) {
305			(void)close(fd);
306			fd = -1;
307		}
308		return;
309	}
310
311	if (fd == -1) {
312		pidfile = _PATH_CRON_PID;
313		/* Initial mode is 0600 to prevent flock() race/DoS. */
314		if ((fd = open(pidfile, O_RDWR|O_CREAT, 0600)) == -1) {
315			log_itx("CRON", getpid(), "DEATH",
316			    "can't open or create %s: %s",
317			    pidfile, strerror(errno));
318			exit(ERROR_EXIT);
319		}
320		/* fd must be > STDERR since we dup fd 0-2 to /dev/null */
321		if (fd <= STDERR) {
322			if (dup2(fd, STDERR + 1) < 0) {
323				log_itx("CRON", getpid(), "DEATH",
324				    "can't dup pid fd: %s", strerror(errno));
325 				exit(ERROR_EXIT);
326 			}
327			close(fd);
328			fd = STDERR + 1;
329		}
330
331		if (flock(fd, LOCK_EX|LOCK_NB) < OK) {
332			int save_errno = errno;
333
334			memset(buf, 0, sizeof(buf));
335			if ((num = read(fd, buf, sizeof(buf) - 1)) > 0 &&
336			    (otherpid = strtol(buf, &ep, 10)) > 0 &&
337			    ep != buf && *ep == '\n' && otherpid != LONG_MAX) {
338				log_itx("CRON", getpid(), "DEATH",
339				    "can't lock %s, otherpid may be %ld: %s",
340				    pidfile, otherpid, strerror(save_errno));
341			} else {
342				log_itx("CRON", getpid(), "DEATH",
343				    "can't lock %s, otherpid unknown: %s",
344				    pidfile, strerror(save_errno));
345			}
346			exit(ERROR_EXIT);
347		}
348		(void) fchmod(fd, 0644);
349		(void) fcntl(fd, F_SETFD, 1);
350	}
351
352	(void)snprintf(buf, sizeof(buf), "%ld\n", (long)getpid());
353	(void) lseek(fd, (off_t)0, SEEK_SET);
354	num = write(fd, buf, strlen(buf));
355	(void) ftruncate(fd, num);
356
357	/* abandon fd even though the file is open. we need to keep
358	 * it open and locked, but we don't need the handles elsewhere.
359	 */
360}
361
362/* get_char(file) : like getc() but increment LineNumber on newlines
363 */
364int
365get_char(FILE *file) {
366	int ch;
367
368	ch = getc(file);
369	if (ch == '\n')
370		Set_LineNum(LineNumber + 1);
371	return (ch);
372}
373
374/* unget_char(ch, file) : like ungetc but do LineNumber processing
375 */
376void
377unget_char(int ch, FILE *file) {
378	(void)ungetc(ch, file);
379	if (ch == '\n')
380		Set_LineNum(LineNumber - 1);
381}
382
383/* get_string(str, max, file, termstr) : like fgets() but
384 *		(1) has terminator string which should include \n
385 *		(2) will always leave room for the null
386 *		(3) uses get_char() so LineNumber will be accurate
387 *		(4) returns EOF or terminating character, whichever
388 */
389int
390get_string(char *string, int size, FILE *file, const char *terms) {
391	int ch;
392
393	while (EOF != (ch = get_char(file)) && !strchr(terms, ch)) {
394		if (size > 1) {
395			*string++ = (char) ch;
396			size--;
397		}
398	}
399
400	if (size > 0)
401		*string = '\0';
402
403	return (ch);
404}
405
406/* skip_comments(file) : read past comment (if any)
407 */
408void
409skip_comments(FILE *file) {
410	int ch;
411
412	while (EOF != (ch = get_char(file))) {
413		/* ch is now the first character of a line.
414		 */
415
416		while (ch == ' ' || ch == '\t')
417			ch = get_char(file);
418
419		if (ch == EOF)
420			break;
421
422		/* ch is now the first non-blank character of a line.
423		 */
424
425		if (ch != '\n' && ch != '#')
426			break;
427
428		/* ch must be a newline or comment as first non-blank
429		 * character on a line.
430		 */
431
432		while (ch != '\n' && ch != EOF)
433			ch = get_char(file);
434
435		/* ch is now the newline of a line which we're going to
436		 * ignore.
437		 */
438	}
439	if (ch != EOF)
440		unget_char(ch, file);
441}
442
443void
444log_itx(const char *username, PID_T xpid, const char *event, const char *fmt,
445    ...)
446{
447	char *detail;
448	va_list ap;
449	va_start(ap, fmt);
450	if (vasprintf(&detail, fmt, ap) == -1) {
451		va_end(ap);
452		return;
453	}
454	log_it(username, xpid, event, detail);
455	free(detail);
456}
457
458void
459log_it(const char *username, PID_T xpid, const char *event, const char *detail) {
460#if defined(LOG_FILE) || DEBUGGING
461	PID_T pid = xpid;
462#endif
463#if defined(LOG_FILE)
464	char *msg;
465	int msglen;
466	TIME_T now = time((TIME_T) 0);
467	struct tm *t = localtime(&now);
468
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, FD_CLOEXEC);
475		}
476	}
477
478	/* we have to sprintf() it because fprintf() doesn't always write
479	 * everything out in one chunk and this has to be atomically appended
480	 * to the log file.
481	 */
482	msglen = asprintf(&msg,
483	    "%s (%02d/%02d-%02d:%02d:%02d-%d) %s (%s)\n", username,
484	    t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec, pid,
485	    event, detail);
486	if (msglen == -1)
487		return;
488
489	if (LogFD < OK || write(LogFD, msg, (size_t)msglen) < OK) {
490		warn("can't write to log file");
491		write(STDERR, msg, (size_t)msglen);
492	}
493
494	free(msg);
495#endif /*LOG_FILE*/
496
497#if defined(SYSLOG)
498	if (!syslog_open) {
499# ifdef LOG_DAEMON
500		openlog(getprogname(), LOG_PID, FACILITY);
501# else
502		openlog(getprogname(), LOG_PID);
503# endif
504		syslog_open = TRUE;		/* assume openlog success */
505	}
506
507	syslog(LOG_INFO, "(%s) %s (%s)", username, event, detail);
508
509#endif /*SYSLOG*/
510
511#if DEBUGGING
512	if (DebugFlags) {
513		(void)fprintf(stderr, "log_it: (%s %ld) %s (%s)\n",
514			username, (long)pid, event, detail);
515	}
516#endif
517}
518
519void
520log_close(void) {
521	if (LogFD != ERR) {
522		(void)close(LogFD);
523		LogFD = ERR;
524	}
525#if defined(SYSLOG)
526	closelog();
527	syslog_open = FALSE;
528#endif /*SYSLOG*/
529}
530
531/* warning:
532 *	heavily ascii-dependent.
533 */
534static void
535mkprint(char *dst, char *src, size_t len)
536{
537	while(len > 0 && isblank((unsigned char) *src))
538		len--, src++;
539
540	(void)strvisx(dst, src, len, VIS_TAB|VIS_NL);
541}
542
543/* warning:
544 *	returns a pointer to malloc'd storage, you must call free yourself.
545 */
546char *
547mkprints(char *src, size_t len)
548{
549	char *dst = malloc(len*4 + 1);
550
551	if (dst)
552		mkprint(dst, src, len);
553
554	return (dst);
555}
556
557#ifdef MAIL_DATE
558/* Sat, 27 Feb 1993 11:44:51 -0800 (CST)
559 * 1234567890123456789012345678901234567
560 */
561char *
562arpadate(time_t *clock)
563{
564	time_t t = clock ? *clock : time((TIME_T) 0);
565	struct tm tm = *localtime(&t);
566	long gmtoff = get_gmtoff(&t, &tm);
567	int hours = gmtoff / SECONDS_PER_HOUR;
568	int minutes = (gmtoff - (hours * SECONDS_PER_HOUR)) / SECONDS_PER_MINUTE;
569	static char ret[64];	/* zone name might be >3 chars */
570
571	if (minutes < 0)
572		minutes = -minutes;
573
574	(void)strftime(ret, sizeof(ret), "%a, %e %b %Y %T ????? (%Z)", &tm);
575	(void)snprintf(strchr(ret, '?'), "% .2d%.2d", hours, minutes);
576	ret[sizeof(ret) - 1] = '\0';
577	return ret;
578}
579#endif /*MAIL_DATE*/
580
581size_t
582strlens(const char *last, ...) {
583	va_list ap;
584	size_t ret = 0;
585	const char *str;
586
587	va_start(ap, last);
588	for (str = last; str != NULL; str = va_arg(ap, const char *))
589		ret += strlen(str);
590	va_end(ap);
591	return (ret);
592}
593
594/* Return the offset from GMT in seconds (algorithm taken from sendmail).
595 *
596 * warning:
597 *	clobbers the static storage space used by localtime() and gmtime().
598 *	If the local pointer is non-NULL it *must* point to a local copy.
599 */
600#ifndef HAVE_TM_GMTOFF
601long get_gmtoff(time_t *clock, struct tm *local)
602{
603	struct tm gmt;
604	long offset;
605
606	gmt = *gmtime(clock);
607	if (local == NULL)
608		local = localtime(clock);
609
610	offset = (local->tm_sec - gmt.tm_sec) +
611	    ((local->tm_min - gmt.tm_min) * 60) +
612	    ((local->tm_hour - gmt.tm_hour) * 3600);
613
614	/* Timezone may cause year rollover to happen on a different day. */
615	if (local->tm_year < gmt.tm_year)
616		offset -= 24 * 3600;
617	else if (local->tm_year > gmt.tm_year)
618		offset -= 24 * 3600;
619	else if (local->tm_yday < gmt.tm_yday)
620		offset -= 24 * 3600;
621	else if (local->tm_yday > gmt.tm_yday)
622		offset += 24 * 3600;
623
624	return (offset);
625}
626#endif /* HAVE_TM_GMTOFF */
627