1 /* Copyright 1988,1990,1993,1994 by Paul Vixie
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
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
18 #if !defined(lint) && !defined(LINT)
19 static const char rcsid[] =
20 "$FreeBSD: src/usr.sbin/cron/lib/misc.c,v 1.8.2.2 2002/04/28 22:45:53 dwmalone Exp $";
23 /* vix 26jan87 [RCS has the rest of the log]
24 * vix 30dec86 [written]
30 # include <sys/time.h>
45 #if defined(LOG_DAEMON) && !defined(LOG_CRON)
46 #define LOG_CRON LOG_DAEMON
50 static int LogFD = ERR;
54 strcmp_until(left, right, until)
61 while (*left && *left != until && *left == *right) {
66 if ((*left=='\0' || *left == until) &&
67 (*right=='\0' || *right == until)) {
70 diff = *left - *right;
77 /* strdtb(s) - delete trailing blanks in string 's' and return new length
85 /* scan forward to the null
90 /* scan backward to either the first character before the string,
91 * or the last non-blank in the string, whichever comes first.
94 while (x >= s && isspace(*x));
96 /* one character beyond where we stopped above is where the null
101 /* the difference between the position of the null character and
102 * the position of the first character of the string is the length.
109 set_debug_flags(flags)
112 /* debug flags are of the form flag[,flag ...]
114 * if an error occurs, print a message to stdout and return FALSE.
115 * otherwise return TRUE after setting ERROR_FLAGS.
120 printf("this program was compiled without debugging enabled\n");
123 #else /* DEBUGGING */
133 /* try to find debug flag name in our list.
135 for ( test = DebugFlagNames, mask = 1;
136 *test && strcmp_until(*test, pc, ',');
143 "unrecognized debug flag <%s> <%s>\n",
150 /* skip to the next flag
152 while (*pc && *pc != ',')
161 fprintf(stderr, "debug flags enabled:");
163 for (flag = 0; DebugFlagNames[flag]; flag++)
164 if (DebugFlags & (1 << flag))
165 fprintf(stderr, " %s", DebugFlagNames[flag]);
166 fprintf(stderr, "\n");
171 #endif /* DEBUGGING */
178 #if defined(BSD) || defined(POSIX)
179 if (seteuid(ROOT_UID) < OK)
180 err(ERROR_EXIT, "seteuid");
182 if (setuid(ROOT_UID) < OK)
183 err(ERROR_EXIT, "setuid");
193 /* first check for CRONDIR ("/var/cron" or some such)
195 if (stat(CRONDIR, &sb) < OK && errno == ENOENT) {
197 if (OK == mkdir(CRONDIR, 0700)) {
198 warnx("%s: created", CRONDIR);
201 err(ERROR_EXIT, "%s: mkdir", CRONDIR);
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);
209 /* CRONDIR okay (now==CWD), now look at SPOOL_DIR ("tabs" or some such)
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);
217 err(ERROR_EXIT, "%s: mkdir", SPOOL_DIR);
220 if (!(sb.st_mode & S_IFDIR))
221 err(ERROR_EXIT, "'%s' is not a directory, bailing out", SPOOL_DIR);
225 /* acquire_daemonlock() - write our PID into /etc/cron.pid, unless
226 * another daemon is already running, which we detect here.
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.
232 * it would be great if fflush() disassociated the file buffer.
235 acquire_daemonlock(closeflag)
238 static FILE *fp = NULL;
240 if (closeflag && fp) {
247 char pidfile[MAX_FNAME];
248 char buf[MAX_TEMPSTR];
251 (void) sprintf(pidfile, PIDFILE, PIDDIR);
252 if ((-1 == (fd = open(pidfile, O_RDWR|O_CREAT, 0644)))
253 || (NULL == (fp = fdopen(fd, "r+")))
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);
261 if (flock(fd, LOCK_EX|LOCK_NB) < OK) {
262 int save_errno = errno;
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);
271 (void) fcntl(fd, F_SETFD, 1);
275 fprintf(fp, "%d\n", getpid());
277 (void) ftruncate(fileno(fp), ftell(fp));
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.
284 /* get_char(file) : like getc() but increment LineNumber on newlines
294 Set_LineNum(LineNumber + 1)
299 /* unget_char(ch, file) : like ungetc but do LineNumber processing
308 Set_LineNum(LineNumber - 1)
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
319 get_string(string, size, file, terms)
327 while (EOF != (ch = get_char(file)) && !strchr(terms, ch)) {
329 *string++ = (char) ch;
341 /* skip_comments(file) : read past comment (if any)
349 while (EOF != (ch = get_char(file))) {
350 /* ch is now the first character of a line.
353 while (ch == ' ' || ch == '\t')
359 /* ch is now the first non-blank character of a line.
362 if (ch != '\n' && ch != '#')
365 /* ch must be a newline or comment as first non-blank
366 * character on a line.
369 while (ch != '\n' && ch != EOF)
372 /* ch is now the newline of a line which we're going to
377 unget_char(ch, file);
381 /* int in_file(char *string, FILE *file)
382 * return TRUE if one of the lines in file matches string exactly,
386 in_file(string, file)
390 char line[MAX_TEMPSTR];
393 while (fgets(line, MAX_TEMPSTR, file)) {
395 if (line[strlen(line)-1] == '\n')
396 line[strlen(line)-1] = '\0';
397 if (0 == strcmp(line, string))
404 /* int allowed(char *username)
405 * returns TRUE if (ALLOW_FILE exists and user is listed)
406 * or (DENY_FILE exists and user is NOT listed)
407 * or (neither file exists but user=="root" so it's okay)
413 static int init = FALSE;
414 static FILE *allow, *deny;
418 #if defined(ALLOW_FILE) && defined(DENY_FILE)
419 allow = fopen(ALLOW_FILE, "r");
420 deny = fopen(DENY_FILE, "r");
421 Debug(DMISC, ("allow/deny enabled, %d/%d\n", !!allow, !!deny))
429 return (in_file(username, allow));
431 return (!in_file(username, deny));
433 #if defined(ALLOW_ONLY_ROOT)
434 return (strcmp(username, ROOT_USER) == 0);
442 log_it(username, xpid, event, detail)
449 #if defined(LOG_FILE)
451 TIME_T now = time((TIME_T) 0);
452 register struct tm *t = localtime(&now);
456 static int syslog_open = 0;
459 #if defined(LOG_FILE)
460 /* we assume that MAX_TEMPSTR will hold the date, time, &punctuation.
462 msg = malloc(strlen(username)
468 warnx("failed to allocate memory for log message");
471 LogFD = open(LOG_FILE, O_WRONLY|O_APPEND|O_CREAT, 0600);
473 warn("can't open log file %s", LOG_FILE);
475 (void) fcntl(LogFD, F_SETFD, 1);
479 /* we have to sprintf() it because fprintf() doesn't always
480 * write everything out in one chunk and this has to be
481 * atomically appended to the log file.
483 sprintf(msg, "%s (%02d/%02d-%02d:%02d:%02d-%d) %s (%s)\n",
485 t->tm_mon+1, t->tm_mday, t->tm_hour, t->tm_min,
486 t->tm_sec, pid, event, detail);
488 /* we have to run strlen() because sprintf() returns (char*)
491 if (LogFD < OK || write(LogFD, msg, strlen(msg)) < OK) {
493 warn("%s", LOG_FILE);
494 warnx("can't write to log file");
495 write(STDERR, msg, strlen(msg));
504 /* we don't use LOG_PID since the pid passed to us by
505 * our client may not be our own. therefore we want to
506 * print the pid ourselves.
509 openlog(ProgramName, LOG_PID, LOG_CRON);
511 openlog(ProgramName, LOG_PID);
513 syslog_open = TRUE; /* assume openlog success */
516 syslog(LOG_INFO, "(%s) %s (%s)\n", username, event, detail);
522 fprintf(stderr, "log_it: (%s %d) %s (%s)\n",
523 username, pid, event, detail);
539 * (1) this routine is fairly slow
540 * (2) it returns a pointer to static storage
544 register char *s; /* string we want the first word of */
545 register char *t; /* terminators, implicitly including \0 */
547 static char retbuf[2][MAX_TEMPSTR + 1]; /* sure wish C had GC */
548 static int retsel = 0;
549 register char *rb, *rp;
551 /* select a return buffer */
553 rb = &retbuf[retsel][0];
556 /* skip any leading terminators */
557 while (*s && (NULL != strchr(t, *s))) {
561 /* copy until next terminator or full buffer */
562 while (*s && (NULL == strchr(t, *s)) && (rp < &rb[MAX_TEMPSTR])) {
566 /* finish the return-string and return it */
573 * heavily ascii-dependent.
576 mkprint(dst, src, len)
578 register unsigned char *src;
583 register unsigned char ch = *src++;
585 if (ch < ' ') { /* control character */
588 } else if (ch < 0177) { /* printable */
590 } else if (ch == 0177) { /* delete/rubout */
593 } else { /* parity character */
594 sprintf(dst, "\\%03o", ch);
603 * returns a pointer to malloc'd storage, you must call free yourself.
607 register unsigned char *src;
608 register unsigned int len;
610 register char *dst = malloc(len*4 + 1);
613 mkprint(dst, src, len);
620 /* Sat, 27 Feb 93 11:44:51 CST
621 * 123456789012345678901234567
627 time_t t = clock ?*clock :time(0L);
628 struct tm *tm = localtime(&t);
629 static char ret[32]; /* zone name might be >3 chars */
631 if (tm->tm_year >= 100)
634 (void) snprintf(ret, sizeof(ret), "%s, %2d %s %d %02d:%02d:%02d %s",
635 DowNames[tm->tm_wday],
637 MonthNames[tm->tm_mon],
648 #ifdef HAVE_SAVED_UIDS
649 static int save_euid;
650 int swap_uids() { save_euid = geteuid(); return seteuid(getuid()); }
651 int swap_uids_back() { return seteuid(save_euid); }
652 #else /*HAVE_SAVED_UIDS*/
653 int swap_uids() { return setreuid(geteuid(), getuid()); }
654 int swap_uids_back() { return swap_uids(); }
655 #endif /*HAVE_SAVED_UIDS*/