xref: /freebsd/usr.sbin/cron/lib/misc.c (revision a0409676120c1e558d0ade943019934e0f15118d)
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)
19 static const char rcsid[] =
20   "$FreeBSD$";
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 
50 static int		LogFD = ERR;
51 
52 
53 int
54 strcmp_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  */
79 int
80 strdtb(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 
108 int
109 set_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 
175 void
176 set_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 
188 void
189 set_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 /* get_char(file) : like getc() but increment LineNumber on newlines
226  */
227 int
228 get_char(file)
229 	FILE	*file;
230 {
231 	int	ch;
232 
233 	ch = getc(file);
234 	if (ch == '\n')
235 		Set_LineNum(LineNumber + 1)
236 	return ch;
237 }
238 
239 
240 /* unget_char(ch, file) : like ungetc but do LineNumber processing
241  */
242 void
243 unget_char(ch, file)
244 	int	ch;
245 	FILE	*file;
246 {
247 	ungetc(ch, file);
248 	if (ch == '\n')
249 		Set_LineNum(LineNumber - 1)
250 }
251 
252 
253 /* get_string(str, max, file, termstr) : like fgets() but
254  *		(1) has terminator string which should include \n
255  *		(2) will always leave room for the null
256  *		(3) uses get_char() so LineNumber will be accurate
257  *		(4) returns EOF or terminating character, whichever
258  */
259 int
260 get_string(string, size, file, terms)
261 	char	*string;
262 	int	size;
263 	FILE	*file;
264 	char	*terms;
265 {
266 	int	ch;
267 
268 	while (EOF != (ch = get_char(file)) && !strchr(terms, ch)) {
269 		if (size > 1) {
270 			*string++ = (char) ch;
271 			size--;
272 		}
273 	}
274 
275 	if (size > 0)
276 		*string = '\0';
277 
278 	return ch;
279 }
280 
281 
282 /* skip_comments(file) : read past comment (if any)
283  */
284 void
285 skip_comments(file)
286 	FILE	*file;
287 {
288 	int	ch;
289 
290 	while (EOF != (ch = get_char(file))) {
291 		/* ch is now the first character of a line.
292 		 */
293 
294 		while (ch == ' ' || ch == '\t')
295 			ch = get_char(file);
296 
297 		if (ch == EOF)
298 			break;
299 
300 		/* ch is now the first non-blank character of a line.
301 		 */
302 
303 		if (ch != '\n' && ch != '#')
304 			break;
305 
306 		/* ch must be a newline or comment as first non-blank
307 		 * character on a line.
308 		 */
309 
310 		while (ch != '\n' && ch != EOF)
311 			ch = get_char(file);
312 
313 		/* ch is now the newline of a line which we're going to
314 		 * ignore.
315 		 */
316 	}
317 	if (ch != EOF)
318 		unget_char(ch, file);
319 }
320 
321 
322 /* int in_file(char *string, FILE *file)
323  *	return TRUE if one of the lines in file matches string exactly,
324  *	FALSE otherwise.
325  */
326 static int
327 in_file(char *string, FILE *file)
328 {
329 	char line[MAX_TEMPSTR];
330 
331 	rewind(file);
332 	while (fgets(line, MAX_TEMPSTR, file)) {
333 		if (line[0] != '\0')
334 			if (line[strlen(line)-1] == '\n')
335 				line[strlen(line)-1] = '\0';
336 		if (0 == strcmp(line, string))
337 			return TRUE;
338 	}
339 	return FALSE;
340 }
341 
342 
343 /* int allowed(char *username)
344  *	returns TRUE if (ALLOW_FILE exists and user is listed)
345  *	or (DENY_FILE exists and user is NOT listed)
346  *	or (neither file exists but user=="root" so it's okay)
347  */
348 int
349 allowed(username)
350 	char *username;
351 {
352 	FILE	*allow, *deny;
353 	int	isallowed;
354 
355 	isallowed = FALSE;
356 
357 	deny = NULL;
358 #if defined(ALLOW_FILE) && defined(DENY_FILE)
359 	if ((allow = fopen(ALLOW_FILE, "r")) == NULL && errno != ENOENT)
360 		goto out;
361 	if ((deny = fopen(DENY_FILE, "r")) == NULL && errno != ENOENT)
362 		goto out;
363 	Debug(DMISC, ("allow/deny enabled, %d/%d\n", !!allow, !!deny))
364 #else
365 	allow = NULL;
366 #endif
367 
368 	if (allow)
369 		isallowed = in_file(username, allow);
370 	else if (deny)
371 		isallowed = !in_file(username, deny);
372 	else {
373 #if defined(ALLOW_ONLY_ROOT)
374 		isallowed = (strcmp(username, ROOT_USER) == 0);
375 #else
376 		isallowed = TRUE;
377 #endif
378 	}
379 out:	if (allow)
380 		fclose(allow);
381 	if (deny)
382 		fclose(deny);
383 	return (isallowed);
384 }
385 
386 
387 void
388 log_it(char *username, int xpid, char *event, const char *detail)
389 {
390 #if defined(LOG_FILE) || DEBUGGING
391 	PID_T			pid = xpid;
392 #endif
393 #if defined(LOG_FILE)
394 	char			*msg;
395 	TIME_T			now = time((TIME_T) 0);
396 	register struct tm	*t = localtime(&now);
397 #endif /*LOG_FILE*/
398 
399 #if defined(SYSLOG)
400 	static int		syslog_open = 0;
401 #endif
402 
403 #if defined(LOG_FILE)
404 	/* we assume that MAX_TEMPSTR will hold the date, time, &punctuation.
405 	 */
406 	msg = malloc(strlen(username)
407 		     + strlen(event)
408 		     + strlen(detail)
409 		     + MAX_TEMPSTR);
410 
411 	if (msg == NULL)
412 		warnx("failed to allocate memory for log message");
413 	else {
414 		if (LogFD < OK) {
415 			LogFD = open(LOG_FILE, O_WRONLY|O_APPEND|O_CREAT, 0600);
416 			if (LogFD < OK) {
417 				warn("can't open log file %s", LOG_FILE);
418 			} else {
419 				(void) fcntl(LogFD, F_SETFD, 1);
420 			}
421 		}
422 
423 		/* we have to sprintf() it because fprintf() doesn't always
424 		 * write everything out in one chunk and this has to be
425 		 * atomically appended to the log file.
426 		 */
427 		sprintf(msg, "%s (%02d/%02d-%02d:%02d:%02d-%d) %s (%s)\n",
428 			username,
429 			t->tm_mon+1, t->tm_mday, t->tm_hour, t->tm_min,
430 			t->tm_sec, pid, event, detail);
431 
432 		/* we have to run strlen() because sprintf() returns (char*)
433 		 * on old BSD.
434 		 */
435 		if (LogFD < OK || write(LogFD, msg, strlen(msg)) < OK) {
436 			if (LogFD >= OK)
437 				warn("%s", LOG_FILE);
438 			warnx("can't write to log file");
439 			write(STDERR, msg, strlen(msg));
440 		}
441 
442 		free(msg);
443 	}
444 #endif /*LOG_FILE*/
445 
446 #if defined(SYSLOG)
447 	if (!syslog_open) {
448 		/* we don't use LOG_PID since the pid passed to us by
449 		 * our client may not be our own.  therefore we want to
450 		 * print the pid ourselves.
451 		 */
452 # ifdef LOG_DAEMON
453 		openlog(ProgramName, LOG_PID, LOG_CRON);
454 # else
455 		openlog(ProgramName, LOG_PID);
456 # endif
457 		syslog_open = TRUE;		/* assume openlog success */
458 	}
459 
460 	syslog(LOG_INFO, "(%s) %s (%s)\n", username, event, detail);
461 
462 #endif /*SYSLOG*/
463 
464 #if DEBUGGING
465 	if (DebugFlags) {
466 		fprintf(stderr, "log_it: (%s %d) %s (%s)\n",
467 			username, pid, event, detail);
468 	}
469 #endif
470 }
471 
472 
473 void
474 log_close() {
475 	if (LogFD != ERR) {
476 		close(LogFD);
477 		LogFD = ERR;
478 	}
479 }
480 
481 
482 /* two warnings:
483  *	(1) this routine is fairly slow
484  *	(2) it returns a pointer to static storage
485  */
486 char *
487 first_word(s, t)
488 	register char *s;	/* string we want the first word of */
489 	register char *t;	/* terminators, implicitly including \0 */
490 {
491 	static char retbuf[2][MAX_TEMPSTR + 1];	/* sure wish C had GC */
492 	static int retsel = 0;
493 	register char *rb, *rp;
494 
495 	/* select a return buffer */
496 	retsel = 1-retsel;
497 	rb = &retbuf[retsel][0];
498 	rp = rb;
499 
500 	/* skip any leading terminators */
501 	while (*s && (NULL != strchr(t, *s))) {
502 		s++;
503 	}
504 
505 	/* copy until next terminator or full buffer */
506 	while (*s && (NULL == strchr(t, *s)) && (rp < &rb[MAX_TEMPSTR])) {
507 		*rp++ = *s++;
508 	}
509 
510 	/* finish the return-string and return it */
511 	*rp = '\0';
512 	return rb;
513 }
514 
515 
516 /* warning:
517  *	heavily ascii-dependent.
518  */
519 static void
520 mkprint(register char *dst, register unsigned char *src, register int len)
521 {
522 	while (len-- > 0)
523 	{
524 		register unsigned char ch = *src++;
525 
526 		if (ch < ' ') {			/* control character */
527 			*dst++ = '^';
528 			*dst++ = ch + '@';
529 		} else if (ch < 0177) {		/* printable */
530 			*dst++ = ch;
531 		} else if (ch == 0177) {	/* delete/rubout */
532 			*dst++ = '^';
533 			*dst++ = '?';
534 		} else {			/* parity character */
535 			sprintf(dst, "\\%03o", ch);
536 			dst += 4;
537 		}
538 	}
539 	*dst = '\0';
540 }
541 
542 
543 /* warning:
544  *	returns a pointer to malloc'd storage, you must call free yourself.
545  */
546 char *
547 mkprints(src, len)
548 	register unsigned char *src;
549 	register unsigned int len;
550 {
551 	register char *dst = malloc(len*4 + 1);
552 
553 	if (dst != NULL)
554 		mkprint(dst, src, len);
555 
556 	return dst;
557 }
558 
559 
560 #ifdef MAIL_DATE
561 /* Sat, 27 Feb 93 11:44:51 CST
562  * 123456789012345678901234567
563  */
564 char *
565 arpadate(clock)
566 	time_t *clock;
567 {
568 	time_t t = clock ?*clock :time(0L);
569 	struct tm *tm = localtime(&t);
570 	static char ret[32];	/* zone name might be >3 chars */
571 
572 	if (tm->tm_year >= 100)
573 		tm->tm_year += 1900;
574 
575 	(void) snprintf(ret, sizeof(ret), "%s, %2d %s %d %02d:%02d:%02d %s",
576 		       DowNames[tm->tm_wday],
577 		       tm->tm_mday,
578 		       MonthNames[tm->tm_mon],
579 		       tm->tm_year,
580 		       tm->tm_hour,
581 		       tm->tm_min,
582 		       tm->tm_sec,
583 		       TZONE(*tm));
584 	return ret;
585 }
586 #endif /*MAIL_DATE*/
587 
588 
589 #ifdef HAVE_SAVED_UIDS
590 static int save_euid;
591 int swap_uids() { save_euid = geteuid(); return seteuid(getuid()); }
592 int swap_uids_back() { return seteuid(save_euid); }
593 #else /*HAVE_SAVED_UIDS*/
594 int swap_uids() { return setreuid(geteuid(), getuid()); }
595 int swap_uids_back() { return swap_uids(); }
596 #endif /*HAVE_SAVED_UIDS*/
597