No empty .Rs/.Re
[netbsd-mini2440.git] / usr.sbin / cron / misc.c
blob495a30e3d6bca9ec2c9c7cbee36c743eee049c13
1 /* $NetBSD: misc.c,v 1.13 2006/05/21 19:26:43 christos Exp $ */
3 /* Copyright 1988,1990,1993,1994 by Paul Vixie
4 * All rights reserved
6 * Distribute freely, except: don't remove my name from the source or
7 * documentation (don't take credit for my work), mark your changes (don't
8 * get me blamed for your possible bugs), don't alter or remove this
9 * notice. May be sold if buildable source is provided to buyer. No
10 * warrantee of any kind, express or implied, is included with this
11 * software; use at your own risk, responsibility for damages (if any) to
12 * anyone resulting from the use of this software rests entirely with the
13 * user.
15 * Send bug reports, bug fixes, enhancements, requests, flames, etc., and
16 * I'll try to keep a version up to date. I can be reached as follows:
17 * Paul Vixie <paul@vix.com> uunet!decwrl!vixie!paul
20 #include <sys/cdefs.h>
21 #if !defined(lint) && !defined(LINT)
22 #if 0
23 static char rcsid[] = "Id: misc.c,v 2.9 1994/01/15 20:43:43 vixie Exp";
24 #else
25 __RCSID("$NetBSD: misc.c,v 1.13 2006/05/21 19:26:43 christos Exp $");
26 #endif
27 #endif
29 /* vix 26jan87 [RCS has the rest of the log]
30 * vix 30dec86 [written]
34 #include "cron.h"
35 #if SYS_TIME_H
36 # include <sys/time.h>
37 #else
38 # include <time.h>
39 #endif
40 #include <sys/file.h>
41 #include <sys/stat.h>
42 #include <err.h>
43 #include <errno.h>
44 #include <string.h>
45 #include <fcntl.h>
46 #if defined(SYSLOG)
47 # include <syslog.h>
48 #endif
49 #include <ctype.h>
50 #include <vis.h>
52 #if defined(LOG_DAEMON) && !defined(LOG_CRON)
53 #define LOG_CRON LOG_DAEMON
54 #endif
56 static int in_file(char *, FILE *);
57 static void mkprint(char *, unsigned char *, int);
59 static int LogFD = ERR;
62 int
63 strcmp_until(const char *left, const char *right, int until)
65 int diff;
67 while (*left && *left != until && *left == *right) {
68 left++;
69 right++;
72 if ((*left=='\0' || *left == until) &&
73 (*right=='\0' || *right == until)) {
74 diff = 0;
75 } else {
76 diff = *left - *right;
79 return diff;
83 /* strdtb(s) - delete trailing blanks in string 's' and return new length
85 int
86 strdtb(char *s)
88 char *x = s;
90 /* scan forward to the null
92 while (*x)
93 x++;
95 /* scan backward to either the first character before the string,
96 * or the last non-blank in the string, whichever comes first.
98 do {x--;}
99 while (x >= s && isspace((unsigned char)*x));
101 /* one character beyond where we stopped above is where the null
102 * goes.
104 *++x = '\0';
106 /* the difference between the position of the null character and
107 * the position of the first character of the string is the length.
109 return x - s;
114 set_debug_flags(char *flags)
116 /* debug flags are of the form flag[,flag ...]
118 * if an error occurs, print a message to stdout and return FALSE.
119 * otherwise return TRUE after setting ERROR_FLAGS.
122 #if !DEBUGGING
124 printf("this program was compiled without debugging enabled\n");
125 return FALSE;
127 #else /* DEBUGGING */
129 char *pc = flags;
131 DebugFlags = 0;
133 while (*pc) {
134 const char * const *test;
135 int mask;
137 /* try to find debug flag name in our list.
139 for ( test = DebugFlagNames, mask = 1;
140 *test && strcmp_until(*test, pc, ',');
141 test++, mask <<= 1
145 if (!*test) {
146 fprintf(stderr,
147 "unrecognized debug flag <%s> <%s>\n",
148 flags, pc);
149 return FALSE;
152 DebugFlags |= mask;
154 /* skip to the next flag
156 while (*pc && *pc != ',')
157 pc++;
158 if (*pc == ',')
159 pc++;
162 if (DebugFlags) {
163 int flag;
165 fprintf(stderr, "debug flags enabled:");
167 for (flag = 0; DebugFlagNames[flag]; flag++)
168 if (DebugFlags & (1 << flag))
169 fprintf(stderr, " %s", DebugFlagNames[flag]);
170 fprintf(stderr, "\n");
173 return TRUE;
175 #endif /* DEBUGGING */
179 void
180 set_cron_uid(void)
182 #if defined(BSD) || defined(POSIX)
183 if (seteuid(ROOT_UID) < OK) {
184 warn("cannot seteuid");
185 exit(ERROR_EXIT);
187 #else
188 if (setuid(ROOT_UID) < OK) {
189 warn("cannot setuid");
190 exit(ERROR_EXIT);
192 #endif
196 void
197 set_cron_cwd(void)
199 struct stat sb;
201 /* first check for CRONDIR ("/var/cron" or some such)
203 if (stat(CRONDIR, &sb) < OK && errno == ENOENT) {
204 warn("cannot stat %s", CRONDIR);
205 if (OK == mkdir(CRONDIR, 0700)) {
206 fprintf(stderr, "%s: created\n", CRONDIR);
207 stat(CRONDIR, &sb);
208 } else {
209 warn("cannot create %s", CRONDIR);
210 exit(ERROR_EXIT);
213 if (!S_ISDIR(sb.st_mode)) {
214 warnx("`%s' is not a directory, bailing out", CRONDIR);
215 exit(ERROR_EXIT);
217 if (chdir(CRONDIR) < OK) {
218 warn("cannot chdir(%s), bailing out", CRONDIR);
219 exit(ERROR_EXIT);
222 /* CRONDIR okay (now==CWD), now look at SPOOL_DIR ("tabs" or some such)
224 if (stat(SPOOL_DIR, &sb) < OK && errno == ENOENT) {
225 warn("cannot stat %s", SPOOL_DIR);
226 if (OK == mkdir(SPOOL_DIR, 0700)) {
227 fprintf(stderr, "%s: created\n", SPOOL_DIR);
228 stat(SPOOL_DIR, &sb);
229 } else {
230 warn("cannot create %s", SPOOL_DIR);
231 exit(ERROR_EXIT);
234 if (!S_ISDIR(sb.st_mode)) {
235 fprintf(stderr, "'%s' is not a directory, bailing out.\n",
236 SPOOL_DIR);
237 exit(ERROR_EXIT);
242 /* acquire_daemonlock() - write our PID into /etc/cron.pid, unless
243 * another daemon is already running, which we detect here.
245 * note: main() calls us twice; once before forking, once after.
246 * we maintain static storage of the file pointer so that we
247 * can rewrite our PID into the PIDFILE after the fork.
249 * it would be great if fflush() disassociated the file buffer.
251 void
252 acquire_daemonlock(int closeflag)
254 static FILE *fp = NULL;
256 if (closeflag && fp) {
257 fclose(fp);
258 fp = NULL;
259 return;
262 if (!fp) {
263 char pidfile[MAX_FNAME];
264 char buf[MAX_TEMPSTR];
265 int fd, otherpid;
267 (void) snprintf(pidfile, sizeof(pidfile), PIDFILE, PIDDIR);
268 if ((-1 == (fd = open(pidfile, O_RDWR|O_CREAT, 0644)))
269 || (NULL == (fp = fdopen(fd, "r+")))
271 snprintf(buf, sizeof(buf),
272 "can't open or create %s: %s",
273 pidfile, strerror(errno));
274 warnx(buf);
275 log_it("CRON", getpid(), "DEATH", buf);
276 exit(ERROR_EXIT);
279 if (flock(fd, LOCK_EX|LOCK_NB) < OK) {
280 int save_errno = errno;
282 fscanf(fp, "%d", &otherpid);
283 snprintf(buf, sizeof(buf),
284 "can't lock %s, otherpid may be %d: %s",
285 pidfile, otherpid, strerror(save_errno));
286 warnx(buf);
287 log_it("CRON", getpid(), "DEATH", buf);
288 exit(ERROR_EXIT);
291 (void) fcntl(fd, F_SETFD, 1);
294 rewind(fp);
295 fprintf(fp, "%d\n", getpid());
296 fflush(fp);
297 (void) ftruncate(fileno(fp), ftell(fp));
299 /* abandon fd and fp even though the file is open. we need to
300 * keep it open and locked, but we don't need the handles elsewhere.
304 /* get_char(file) : like getc() but increment LineNumber on newlines
307 get_char(FILE *file)
309 int ch;
311 ch = getc(file);
312 if (ch == '\n')
313 Set_LineNum(LineNumber + 1)
314 return ch;
318 /* unget_char(ch, file) : like ungetc but do LineNumber processing
320 void
321 unget_char(int ch, FILE *file)
323 ungetc(ch, file);
324 if (ch == '\n')
325 Set_LineNum(LineNumber - 1)
329 /* get_string(str, max, file, termstr) : like fgets() but
330 * (1) has terminator string which should include \n
331 * (2) will always leave room for the null
332 * (3) uses get_char() so LineNumber will be accurate
333 * (4) returns EOF or terminating character, whichever
336 get_string(char *string, int size, FILE *file, const char *terms)
338 int ch;
340 while (EOF != (ch = get_char(file)) && !strchr(terms, ch)) {
341 if (size > 1) {
342 *string++ = (char) ch;
343 size--;
347 if (size > 0)
348 *string = '\0';
350 return ch;
354 /* skip_comments(file) : read past comment (if any)
356 void
357 skip_comments(FILE *file)
359 int ch;
361 while (EOF != (ch = get_char(file))) {
362 /* ch is now the first character of a line.
365 while (ch == ' ' || ch == '\t')
366 ch = get_char(file);
368 if (ch == EOF)
369 break;
371 /* ch is now the first non-blank character of a line.
374 if (ch != '\n' && ch != '#')
375 break;
377 /* ch must be a newline or comment as first non-blank
378 * character on a line.
381 while (ch != '\n' && ch != EOF)
382 ch = get_char(file);
384 /* ch is now the newline of a line which we're going to
385 * ignore.
388 if (ch != EOF)
389 unget_char(ch, file);
393 /* int in_file(char *string, FILE *file)
394 * return TRUE if one of the lines in file matches string exactly,
395 * FALSE otherwise.
397 static int
398 in_file(char *string, FILE *file)
400 char line[MAX_TEMPSTR];
402 rewind(file);
403 while (fgets(line, MAX_TEMPSTR, file)) {
404 if (line[0] != '\0')
405 line[strlen(line)-1] = '\0';
406 if (0 == strcmp(line, string))
407 return TRUE;
409 return FALSE;
413 /* int allowed(char *username)
414 * returns TRUE if (ALLOW_FILE exists and user is listed)
415 * or (DENY_FILE exists and user is NOT listed)
416 * or (neither file exists but user=="root" so it's okay)
419 allowed(char *username)
421 static int init = FALSE;
422 static FILE *allow, *deny;
424 if (!init) {
425 init = TRUE;
426 #if defined(ALLOW_FILE) && defined(DENY_FILE)
427 allow = fopen(ALLOW_FILE, "r");
428 deny = fopen(DENY_FILE, "r");
429 Debug(DMISC, ("allow/deny enabled, %d/%d\n", !!allow, !!deny))
430 if (allow)
431 (void)fcntl(fileno(allow), F_SETFD, FD_CLOEXEC);
432 if (deny)
433 (void)fcntl(fileno(deny), F_SETFD, FD_CLOEXEC);
434 #else
435 allow = NULL;
436 deny = NULL;
437 #endif
440 if (allow)
441 return (in_file(username, allow));
442 if (deny)
443 return (!in_file(username, deny));
445 #if defined(ALLOW_ONLY_ROOT)
446 return (strcmp(username, ROOT_USER) == 0);
447 #else
448 return TRUE;
449 #endif
453 void
454 log_it(const char *username, int xpid, const char *event, const char *detail)
456 PID_T pid = xpid;
457 #if defined(LOG_FILE)
458 char *msg;
459 size_t msglen;
460 TIME_T now = time((TIME_T) 0);
461 struct tm *t = localtime(&now);
462 #endif /*LOG_FILE*/
464 #if defined(SYSLOG)
465 static int syslog_open = 0;
466 #endif
468 #if defined(LOG_FILE)
469 /* we assume that MAX_TEMPSTR will hold the date, time, &punctuation.
471 msglen = strlen(username) + strlen(event) + strlen(detail) +
472 MAX_TEMPSTR;
473 msg = malloc(msglen);
475 if (LogFD < OK) {
476 LogFD = open(LOG_FILE, O_WRONLY|O_APPEND|O_CREAT, 0600);
477 if (LogFD < OK) {
478 warn("can't open log file %s", LOG_FILE);
479 } else {
480 (void) fcntl(LogFD, F_SETFD, 1);
484 /* we have to snprintf() it because fprintf() doesn't always write
485 * everything out in one chunk and this has to be atomically appended
486 * to the log file.
488 snprintf(msg, msglen, "%s (%02d/%02d-%02d:%02d:%02d-%d) %s (%s)\n",
489 username,
490 t->tm_mon+1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec, pid,
491 event, detail);
493 /* we have to run strlen() because sprintf() returns (char*) on old BSD
495 if (LogFD < OK || write(LogFD, msg, strlen(msg)) < OK) {
496 if (LogFD >= OK)
497 warn("can't write to log file");
498 write(STDERR, msg, strlen(msg));
501 free(msg);
502 #endif /*LOG_FILE*/
504 #if defined(SYSLOG)
505 if (!syslog_open) {
506 /* we don't use LOG_PID since the pid passed to us by
507 * our client may not be our own. therefore we want to
508 * print the pid ourselves.
510 # ifdef LOG_DAEMON
511 openlog(getprogname(), LOG_PID, LOG_CRON);
512 # else
513 openlog(getprogname(), LOG_PID);
514 # endif
515 syslog_open = TRUE; /* assume openlog success */
518 syslog(LOG_INFO, "(%s) %s (%s)\n", username, event, detail);
520 #endif /*SYSLOG*/
522 #if DEBUGGING
523 if (DebugFlags) {
524 fprintf(stderr, "log_it: (%s %d) %s (%s)\n",
525 username, pid, event, detail);
527 #endif
531 void
532 log_close(void) {
533 if (LogFD != ERR) {
534 close(LogFD);
535 LogFD = ERR;
540 /* two warnings:
541 * (1) this routine is fairly slow
542 * (2) it returns a pointer to static storage
544 char *
545 first_word(char *s, /* string we want the first word of */
546 const char *t /* terminators, implicitly including \0 */)
548 static char retbuf[2][MAX_TEMPSTR + 1]; /* sure wish C had GC */
549 static int retsel = 0;
550 char *rb, *rp;
552 /* select a return buffer */
553 retsel = 1-retsel;
554 rb = &retbuf[retsel][0];
555 rp = rb;
557 /* skip any leading terminators */
558 while (*s && (NULL != strchr(t, *s))) {
559 s++;
562 /* copy until next terminator or full buffer */
563 while (*s && (NULL == strchr(t, *s)) && (rp < &rb[MAX_TEMPSTR])) {
564 *rp++ = *s++;
567 /* finish the return-string and return it */
568 *rp = '\0';
569 return rb;
573 /* warning:
574 * heavily ascii-dependent.
576 static void
577 mkprint(char *dst, unsigned char *src, int len)
579 while(len > 0 && isblank((unsigned char) *src))
580 len--, src++;
582 strvisx(dst, src, len, VIS_TAB|VIS_NL);
586 /* warning:
587 * returns a pointer to malloc'd storage, you must call free yourself.
589 char *
590 mkprints(unsigned char *src, unsigned int len)
592 char *dst = malloc(len*4 + 1);
594 mkprint(dst, src, len);
596 return dst;
600 #ifdef MAIL_DATE
601 /* Sat, 27 Feb 1993 11:44:51 -0800 (CST)
602 * 1234567890123456789012345678901234567
604 char *
605 arpadate(time_t *clock)
607 static char ret[64]; /* zone name might be >3 chars */
608 time_t t = clock ? *clock : time(NULL);
609 struct tm *tm = localtime(&t);
610 int hours = tm->tm_gmtoff / 3600;
611 int minutes = (tp->tm_gmtoff - (hours * 3600)) / 60;
613 if (minutes < 0)
614 minutes = -minutes;
616 (void)strftime(ret, sizeof(ret), "%a, %e %b %Y %T ????? (%Z)", &tm);
617 (void)snprintf(strchr(ret, '?'), "% .2d%.2d", hours, minutes);
618 ret[sizeof(ret) - 1] = '\0';
619 return ret;
621 #endif /*MAIL_DATE*/
624 #ifdef HAVE_SAVED_UIDS
625 static int save_euid;
626 int swap_uids(void) { save_euid = geteuid(); return seteuid(getuid()); }
627 #if 0
628 int swap_uids_back() { return seteuid(save_euid); }
629 #endif
630 #else /*HAVE_SAVED_UIDS*/
631 int swap_uids(void) { return setreuid(geteuid(), getuid()); }
632 #if 0
633 int swap_uids_back() { return swap_uids(); }
634 #endif
635 #endif /*HAVE_SAVED_UIDS*/