xref: /freebsd/usr.sbin/cron/lib/misc.c (revision 66d48cdafe8f7138d892762e8c5a434536cda19d)
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 void mkprint(register char*, register unsigned char*, register int);
52 
53 
54 int
55 strcmp_until(left, right, until)
56 	char	*left;
57 	char	*right;
58 	int	until;
59 {
60 	register int	diff;
61 
62 	while (*left && *left != until && *left == *right) {
63 		left++;
64 		right++;
65 	}
66 
67 	if ((*left=='\0' || *left == until) &&
68 	    (*right=='\0' || *right == until)) {
69 		diff = 0;
70 	} else {
71 		diff = *left - *right;
72 	}
73 
74 	return diff;
75 }
76 
77 
78 /* strdtb(s) - delete trailing blanks in string 's' and return new length
79  */
80 int
81 strdtb(s)
82 	char	*s;
83 {
84 	char	*x = s;
85 
86 	/* scan forward to the null
87 	 */
88 	while (*x)
89 		x++;
90 
91 	/* scan backward to either the first character before the string,
92 	 * or the last non-blank in the string, whichever comes first.
93 	 */
94 	do	{x--;}
95 	while (x >= s && isspace(*x));
96 
97 	/* one character beyond where we stopped above is where the null
98 	 * goes.
99 	 */
100 	*++x = '\0';
101 
102 	/* the difference between the position of the null character and
103 	 * the position of the first character of the string is the length.
104 	 */
105 	return x - s;
106 }
107 
108 
109 int
110 set_debug_flags(flags)
111 	char	*flags;
112 {
113 	/* debug flags are of the form    flag[,flag ...]
114 	 *
115 	 * if an error occurs, print a message to stdout and return FALSE.
116 	 * otherwise return TRUE after setting ERROR_FLAGS.
117 	 */
118 
119 #if !DEBUGGING
120 
121 	printf("this program was compiled without debugging enabled\n");
122 	return FALSE;
123 
124 #else /* DEBUGGING */
125 
126 	char	*pc = flags;
127 
128 	DebugFlags = 0;
129 
130 	while (*pc) {
131 		char	**test;
132 		int	mask;
133 
134 		/* try to find debug flag name in our list.
135 		 */
136 		for (	test = DebugFlagNames, mask = 1;
137 			*test && strcmp_until(*test, pc, ',');
138 			test++, mask <<= 1
139 		    )
140 			;
141 
142 		if (!*test) {
143 			fprintf(stderr,
144 				"unrecognized debug flag <%s> <%s>\n",
145 				flags, pc);
146 			return FALSE;
147 		}
148 
149 		DebugFlags |= mask;
150 
151 		/* skip to the next flag
152 		 */
153 		while (*pc && *pc != ',')
154 			pc++;
155 		if (*pc == ',')
156 			pc++;
157 	}
158 
159 	if (DebugFlags) {
160 		int	flag;
161 
162 		fprintf(stderr, "debug flags enabled:");
163 
164 		for (flag = 0;  DebugFlagNames[flag];  flag++)
165 			if (DebugFlags & (1 << flag))
166 				fprintf(stderr, " %s", DebugFlagNames[flag]);
167 		fprintf(stderr, "\n");
168 	}
169 
170 	return TRUE;
171 
172 #endif /* DEBUGGING */
173 }
174 
175 
176 void
177 set_cron_uid()
178 {
179 #if defined(BSD) || defined(POSIX)
180 	if (seteuid(ROOT_UID) < OK)
181 		err(ERROR_EXIT, "seteuid");
182 #else
183 	if (setuid(ROOT_UID) < OK)
184 		err(ERROR_EXIT, "setuid");
185 #endif
186 }
187 
188 
189 void
190 set_cron_cwd()
191 {
192 	struct stat	sb;
193 
194 	/* first check for CRONDIR ("/var/cron" or some such)
195 	 */
196 	if (stat(CRONDIR, &sb) < OK && errno == ENOENT) {
197 		warn("%s", CRONDIR);
198 		if (OK == mkdir(CRONDIR, 0700)) {
199 			warnx("%s: created", CRONDIR);
200 			stat(CRONDIR, &sb);
201 		} else {
202 			err(ERROR_EXIT, "%s: mkdir", CRONDIR);
203 		}
204 	}
205 	if (!(sb.st_mode & S_IFDIR))
206 		err(ERROR_EXIT, "'%s' is not a directory, bailing out", CRONDIR);
207 	if (chdir(CRONDIR) < OK)
208 		err(ERROR_EXIT, "cannot chdir(%s), bailing out", CRONDIR);
209 
210 	/* CRONDIR okay (now==CWD), now look at SPOOL_DIR ("tabs" or some such)
211 	 */
212 	if (stat(SPOOL_DIR, &sb) < OK && errno == ENOENT) {
213 		warn("%s", SPOOL_DIR);
214 		if (OK == mkdir(SPOOL_DIR, 0700)) {
215 			warnx("%s: created", SPOOL_DIR);
216 			stat(SPOOL_DIR, &sb);
217 		} else {
218 			err(ERROR_EXIT, "%s: mkdir", SPOOL_DIR);
219 		}
220 	}
221 	if (!(sb.st_mode & S_IFDIR))
222 		err(ERROR_EXIT, "'%s' is not a directory, bailing out", SPOOL_DIR);
223 }
224 
225 
226 /* get_char(file) : like getc() but increment LineNumber on newlines
227  */
228 int
229 get_char(file)
230 	FILE	*file;
231 {
232 	int	ch;
233 
234 	ch = getc(file);
235 	if (ch == '\n')
236 		Set_LineNum(LineNumber + 1)
237 	return ch;
238 }
239 
240 
241 /* unget_char(ch, file) : like ungetc but do LineNumber processing
242  */
243 void
244 unget_char(ch, file)
245 	int	ch;
246 	FILE	*file;
247 {
248 	ungetc(ch, file);
249 	if (ch == '\n')
250 		Set_LineNum(LineNumber - 1)
251 }
252 
253 
254 /* get_string(str, max, file, termstr) : like fgets() but
255  *		(1) has terminator string which should include \n
256  *		(2) will always leave room for the null
257  *		(3) uses get_char() so LineNumber will be accurate
258  *		(4) returns EOF or terminating character, whichever
259  */
260 int
261 get_string(string, size, file, terms)
262 	char	*string;
263 	int	size;
264 	FILE	*file;
265 	char	*terms;
266 {
267 	int	ch;
268 
269 	while (EOF != (ch = get_char(file)) && !strchr(terms, ch)) {
270 		if (size > 1) {
271 			*string++ = (char) ch;
272 			size--;
273 		}
274 	}
275 
276 	if (size > 0)
277 		*string = '\0';
278 
279 	return ch;
280 }
281 
282 
283 /* skip_comments(file) : read past comment (if any)
284  */
285 void
286 skip_comments(file)
287 	FILE	*file;
288 {
289 	int	ch;
290 
291 	while (EOF != (ch = get_char(file))) {
292 		/* ch is now the first character of a line.
293 		 */
294 
295 		while (ch == ' ' || ch == '\t')
296 			ch = get_char(file);
297 
298 		if (ch == EOF)
299 			break;
300 
301 		/* ch is now the first non-blank character of a line.
302 		 */
303 
304 		if (ch != '\n' && ch != '#')
305 			break;
306 
307 		/* ch must be a newline or comment as first non-blank
308 		 * character on a line.
309 		 */
310 
311 		while (ch != '\n' && ch != EOF)
312 			ch = get_char(file);
313 
314 		/* ch is now the newline of a line which we're going to
315 		 * ignore.
316 		 */
317 	}
318 	if (ch != EOF)
319 		unget_char(ch, file);
320 }
321 
322 
323 /* int in_file(char *string, FILE *file)
324  *	return TRUE if one of the lines in file matches string exactly,
325  *	FALSE otherwise.
326  */
327 static int
328 in_file(char *string, FILE *file)
329 {
330 	char line[MAX_TEMPSTR];
331 
332 	rewind(file);
333 	while (fgets(line, MAX_TEMPSTR, file)) {
334 		if (line[0] != '\0')
335 			if (line[strlen(line)-1] == '\n')
336 				line[strlen(line)-1] = '\0';
337 		if (0 == strcmp(line, string))
338 			return TRUE;
339 	}
340 	return FALSE;
341 }
342 
343 
344 /* int allowed(char *username)
345  *	returns TRUE if (ALLOW_FILE exists and user is listed)
346  *	or (DENY_FILE exists and user is NOT listed)
347  *	or (neither file exists but user=="root" so it's okay)
348  */
349 int
350 allowed(username)
351 	char *username;
352 {
353 	FILE	*allow, *deny;
354 	int	isallowed;
355 
356 	isallowed = FALSE;
357 
358 	deny = NULL;
359 #if defined(ALLOW_FILE) && defined(DENY_FILE)
360 	if ((allow = fopen(ALLOW_FILE, "r")) == NULL && errno != ENOENT)
361 		goto out;
362 	if ((deny = fopen(DENY_FILE, "r")) == NULL && errno != ENOENT)
363 		goto out;
364 	Debug(DMISC, ("allow/deny enabled, %d/%d\n", !!allow, !!deny))
365 #else
366 	allow = NULL;
367 #endif
368 
369 	if (allow)
370 		isallowed = in_file(username, allow);
371 	else if (deny)
372 		isallowed = !in_file(username, deny);
373 	else {
374 #if defined(ALLOW_ONLY_ROOT)
375 		isallowed = (strcmp(username, ROOT_USER) == 0);
376 #else
377 		isallowed = TRUE;
378 #endif
379 	}
380 out:	if (allow)
381 		fclose(allow);
382 	if (deny)
383 		fclose(deny);
384 	return (isallowed);
385 }
386 
387 
388 void
389 log_it(username, xpid, event, detail)
390 	char	*username;
391 	int	xpid;
392 	char	*event;
393 	char	*detail;
394 {
395 	PID_T			pid = xpid;
396 #if defined(LOG_FILE)
397 	char			*msg;
398 	TIME_T			now = time((TIME_T) 0);
399 	register struct tm	*t = localtime(&now);
400 #endif /*LOG_FILE*/
401 
402 #if defined(SYSLOG)
403 	static int		syslog_open = 0;
404 #endif
405 
406 #if defined(LOG_FILE)
407 	/* we assume that MAX_TEMPSTR will hold the date, time, &punctuation.
408 	 */
409 	msg = malloc(strlen(username)
410 		     + strlen(event)
411 		     + strlen(detail)
412 		     + MAX_TEMPSTR);
413 
414 	if (msg == NULL)
415 		warnx("failed to allocate memory for log message");
416 	else {
417 		if (LogFD < OK) {
418 			LogFD = open(LOG_FILE, O_WRONLY|O_APPEND|O_CREAT, 0600);
419 			if (LogFD < OK) {
420 				warn("can't open log file %s", LOG_FILE);
421 			} else {
422 				(void) fcntl(LogFD, F_SETFD, 1);
423 			}
424 		}
425 
426 		/* we have to sprintf() it because fprintf() doesn't always
427 		 * write everything out in one chunk and this has to be
428 		 * atomically appended to the log file.
429 		 */
430 		sprintf(msg, "%s (%02d/%02d-%02d:%02d:%02d-%d) %s (%s)\n",
431 			username,
432 			t->tm_mon+1, t->tm_mday, t->tm_hour, t->tm_min,
433 			t->tm_sec, pid, event, detail);
434 
435 		/* we have to run strlen() because sprintf() returns (char*)
436 		 * on old BSD.
437 		 */
438 		if (LogFD < OK || write(LogFD, msg, strlen(msg)) < OK) {
439 			if (LogFD >= OK)
440 				warn("%s", LOG_FILE);
441 			warnx("can't write to log file");
442 			write(STDERR, msg, strlen(msg));
443 		}
444 
445 		free(msg);
446 	}
447 #endif /*LOG_FILE*/
448 
449 #if defined(SYSLOG)
450 	if (!syslog_open) {
451 		/* we don't use LOG_PID since the pid passed to us by
452 		 * our client may not be our own.  therefore we want to
453 		 * print the pid ourselves.
454 		 */
455 # ifdef LOG_DAEMON
456 		openlog(ProgramName, LOG_PID, LOG_CRON);
457 # else
458 		openlog(ProgramName, LOG_PID);
459 # endif
460 		syslog_open = TRUE;		/* assume openlog success */
461 	}
462 
463 	syslog(LOG_INFO, "(%s) %s (%s)\n", username, event, detail);
464 
465 #endif /*SYSLOG*/
466 
467 #if DEBUGGING
468 	if (DebugFlags) {
469 		fprintf(stderr, "log_it: (%s %d) %s (%s)\n",
470 			username, pid, event, detail);
471 	}
472 #endif
473 }
474 
475 
476 void
477 log_close() {
478 	if (LogFD != ERR) {
479 		close(LogFD);
480 		LogFD = ERR;
481 	}
482 }
483 
484 
485 /* two warnings:
486  *	(1) this routine is fairly slow
487  *	(2) it returns a pointer to static storage
488  */
489 char *
490 first_word(s, t)
491 	register char *s;	/* string we want the first word of */
492 	register char *t;	/* terminators, implicitly including \0 */
493 {
494 	static char retbuf[2][MAX_TEMPSTR + 1];	/* sure wish C had GC */
495 	static int retsel = 0;
496 	register char *rb, *rp;
497 
498 	/* select a return buffer */
499 	retsel = 1-retsel;
500 	rb = &retbuf[retsel][0];
501 	rp = rb;
502 
503 	/* skip any leading terminators */
504 	while (*s && (NULL != strchr(t, *s))) {
505 		s++;
506 	}
507 
508 	/* copy until next terminator or full buffer */
509 	while (*s && (NULL == strchr(t, *s)) && (rp < &rb[MAX_TEMPSTR])) {
510 		*rp++ = *s++;
511 	}
512 
513 	/* finish the return-string and return it */
514 	*rp = '\0';
515 	return rb;
516 }
517 
518 
519 /* warning:
520  *	heavily ascii-dependent.
521  */
522 void
523 mkprint(register char *dst, register unsigned char *src, register int len)
524 {
525 	while (len-- > 0)
526 	{
527 		register unsigned char ch = *src++;
528 
529 		if (ch < ' ') {			/* control character */
530 			*dst++ = '^';
531 			*dst++ = ch + '@';
532 		} else if (ch < 0177) {		/* printable */
533 			*dst++ = ch;
534 		} else if (ch == 0177) {	/* delete/rubout */
535 			*dst++ = '^';
536 			*dst++ = '?';
537 		} else {			/* parity character */
538 			sprintf(dst, "\\%03o", ch);
539 			dst += 4;
540 		}
541 	}
542 	*dst = '\0';
543 }
544 
545 
546 /* warning:
547  *	returns a pointer to malloc'd storage, you must call free yourself.
548  */
549 char *
550 mkprints(src, len)
551 	register unsigned char *src;
552 	register unsigned int len;
553 {
554 	register char *dst = malloc(len*4 + 1);
555 
556 	if (dst != NULL)
557 		mkprint(dst, src, len);
558 
559 	return dst;
560 }
561 
562 
563 #ifdef MAIL_DATE
564 /* Sat, 27 Feb 93 11:44:51 CST
565  * 123456789012345678901234567
566  */
567 char *
568 arpadate(clock)
569 	time_t *clock;
570 {
571 	time_t t = clock ?*clock :time(0L);
572 	struct tm *tm = localtime(&t);
573 	static char ret[32];	/* zone name might be >3 chars */
574 
575 	if (tm->tm_year >= 100)
576 		tm->tm_year += 1900;
577 
578 	(void) snprintf(ret, sizeof(ret), "%s, %2d %s %d %02d:%02d:%02d %s",
579 		       DowNames[tm->tm_wday],
580 		       tm->tm_mday,
581 		       MonthNames[tm->tm_mon],
582 		       tm->tm_year,
583 		       tm->tm_hour,
584 		       tm->tm_min,
585 		       tm->tm_sec,
586 		       TZONE(*tm));
587 	return ret;
588 }
589 #endif /*MAIL_DATE*/
590 
591 
592 #ifdef HAVE_SAVED_UIDS
593 static int save_euid;
594 int swap_uids() { save_euid = geteuid(); return seteuid(getuid()); }
595 int swap_uids_back() { return seteuid(save_euid); }
596 #else /*HAVE_SAVED_UIDS*/
597 int swap_uids() { return setreuid(geteuid(), getuid()); }
598 int swap_uids_back() { return swap_uids(); }
599 #endif /*HAVE_SAVED_UIDS*/
600