Do not use .Xo/.Xc to work around ancient roff limits.
[netbsd-mini2440.git] / libexec / cron / misc.c
blob531377ae8a416a1446376d5be4a30ae2a418433a
1 /* Copyright 1988,1990,1993 by Paul Vixie
2 * All rights reserved
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.
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 char rcsid[] = "$Id: misc.c,v 1.1 1994/01/05 20:40:15 jtc Exp $";
20 #endif
22 /* vix 26jan87 [RCS has the rest of the log]
23 * vix 30dec86 [written]
27 #include "cron.h"
28 #include "externs.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 <errno.h>
37 #include <string.h>
38 #include <fcntl.h>
39 #if defined(SYSLOG)
40 # include <syslog.h>
41 #endif
44 #if defined(LOG_DAEMON) && !defined(LOG_CRON)
45 #define LOG_CRON LOG_DAEMON
46 #endif
49 int
50 strcmp_until(left, right, until)
51 char *left;
52 char *right;
53 int until;
55 register int diff;
57 while (*left && *left != until && *left == *right) {
58 left++;
59 right++;
62 if ((*left=='\0' || *left == until) &&
63 (*right=='\0' || *right == until)) {
64 diff = 0;
65 } else {
66 diff = *left - *right;
69 return diff;
73 /* strdtb(s) - delete trailing blanks in string 's' and return new length
75 int
76 strdtb(s)
77 char *s;
79 char *x = s;
81 /* scan forward to the null
83 while (*x)
84 x++;
86 /* scan backward to either the first character before the string,
87 * or the last non-blank in the string, whichever comes first.
89 do {x--;}
90 while (x >= s && isspace(*x));
92 /* one character beyond where we stopped above is where the null
93 * goes.
95 *++x = '\0';
97 /* the difference between the position of the null character and
98 * the position of the first character of the string is the length.
100 return x - s;
105 set_debug_flags(flags)
106 char *flags;
108 /* debug flags are of the form flag[,flag ...]
110 * if an error occurs, print a message to stdout and return FALSE.
111 * otherwise return TRUE after setting ERROR_FLAGS.
114 #if !DEBUGGING
116 printf("this program was compiled without debugging enabled\n");
117 return FALSE;
119 #else /* DEBUGGING */
121 char *pc = flags;
123 DebugFlags = 0;
125 while (*pc) {
126 char **test;
127 int mask;
129 /* try to find debug flag name in our list.
131 for ( test = DebugFlagNames, mask = 1;
132 *test && strcmp_until(*test, pc, ',');
133 test++, mask <<= 1
137 if (!*test) {
138 fprintf(stderr,
139 "unrecognized debug flag <%s> <%s>\n",
140 flags, pc);
141 return FALSE;
144 DebugFlags |= mask;
146 /* skip to the next flag
148 while (*pc && *pc != ',')
149 pc++;
150 if (*pc == ',')
151 pc++;
154 if (DebugFlags) {
155 int flag;
157 fprintf(stderr, "debug flags enabled:");
159 for (flag = 0; DebugFlagNames[flag]; flag++)
160 if (DebugFlags & (1 << flag))
161 fprintf(stderr, " %s", DebugFlagNames[flag]);
162 fprintf(stderr, "\n");
165 return TRUE;
167 #endif /* DEBUGGING */
171 void
172 set_cron_uid()
174 #if defined(BSD) || defined(POSIX)
175 if (seteuid(ROOT_UID) < OK) {
176 perror("seteuid");
177 exit(ERROR_EXIT);
179 #else
180 if (setuid(ROOT_UID) < OK) {
181 perror("setuid");
182 exit(ERROR_EXIT);
184 #endif
188 void
189 set_cron_cwd()
191 struct stat sb;
193 /* first check for CRONDIR ("/var/cron" or some such)
195 if (stat(CRONDIR, &sb) < OK && errno == ENOENT) {
196 perror(CRONDIR);
197 if (OK == mkdir(CRONDIR, 0700)) {
198 fprintf(stderr, "%s: created\n", CRONDIR);
199 stat(CRONDIR, &sb);
200 } else {
201 fprintf(stderr, "%s: ", CRONDIR);
202 perror("mkdir");
203 exit(ERROR_EXIT);
206 if (!(sb.st_mode & S_IFDIR)) {
207 fprintf(stderr, "'%s' is not a directory, bailing out.\n",
208 CRONDIR);
209 exit(ERROR_EXIT);
211 if (chdir(CRONDIR) < OK) {
212 fprintf(stderr, "cannot chdir(%s), bailing out.\n", CRONDIR);
213 perror(CRONDIR);
214 exit(ERROR_EXIT);
217 /* CRONDIR okay (now==CWD), now look at SPOOL_DIR ("tabs" or some such)
219 if (stat(SPOOL_DIR, &sb) < OK && errno == ENOENT) {
220 perror(SPOOL_DIR);
221 if (OK == mkdir(SPOOL_DIR, 0700)) {
222 fprintf(stderr, "%s: created\n", SPOOL_DIR);
223 stat(SPOOL_DIR, &sb);
224 } else {
225 fprintf(stderr, "%s: ", SPOOL_DIR);
226 perror("mkdir");
227 exit(ERROR_EXIT);
230 if (!(sb.st_mode & S_IFDIR)) {
231 fprintf(stderr, "'%s' is not a directory, bailing out.\n",
232 SPOOL_DIR);
233 exit(ERROR_EXIT);
238 /* acquire_daemonlock() - write our PID into /etc/cron.pid, unless
239 * another daemon is already running, which we detect here.
241 * note: main() calls us twice; once before forking, once after.
242 * we maintain static storage of the file pointer so that we
243 * can rewrite our PID into the PIDFILE after the fork.
245 * it would be great if fflush() disassociated the file buffer.
247 void
248 acquire_daemonlock(closeflag)
249 int closeflag;
251 static FILE *fp = NULL;
253 if (closeflag && fp) {
254 fclose(fp);
255 fp = NULL;
256 return;
259 if (!fp) {
260 char pidfile[MAX_FNAME];
261 char buf[MAX_TEMPSTR];
262 int otherpid, fd;
264 (void) sprintf(pidfile, PIDFILE, PIDDIR);
265 if ((-1 == (fd = open(pidfile, O_RDWR|O_CREAT, 0644)))
266 || (NULL == (fp = fdopen(fd, "r+")))
268 sprintf(buf, "can't open or create %s: %s",
269 pidfile, strerror(errno));
270 fprintf(stderr, "%s: %s\n", ProgramName, buf);
271 log_it("CRON", getpid(), "DEATH", buf);
272 exit(ERROR_EXIT);
275 if (flock(fd, LOCK_EX|LOCK_NB) < OK) {
276 int save_errno = errno;
278 fscanf(fp, "%d", &otherpid);
279 sprintf(buf, "can't lock %s, otherpid may be %d: %s",
280 pidfile, otherpid, strerror(save_errno));
281 fprintf(stderr, "%s: %s\n", ProgramName, buf);
282 log_it("CRON", getpid(), "DEATH", buf);
283 exit(ERROR_EXIT);
286 (void) fcntl(fd, F_SETFD, 1);
289 rewind(fp);
290 fprintf(fp, "%d\n", getpid());
291 fflush(fp);
292 (void) ftruncate(fileno(fp), ftell(fp));
294 /* abandon fd and fp even though the file is open. we need to
295 * keep it open and locked, but we don't need the handles elsewhere.
299 /* get_char(file) : like getc() but increment LineNumber on newlines
302 get_char(file)
303 FILE *file;
305 int ch;
307 ch = getc(file);
308 if (ch == '\n')
309 Set_LineNum(LineNumber + 1)
310 return ch;
314 /* unget_char(ch, file) : like ungetc but do LineNumber processing
316 void
317 unget_char(ch, file)
318 int ch;
319 FILE *file;
321 ungetc(ch, file);
322 if (ch == '\n')
323 Set_LineNum(LineNumber - 1)
327 /* get_string(str, max, file, termstr) : like fgets() but
328 * (1) has terminator string which should include \n
329 * (2) will always leave room for the null
330 * (3) uses get_char() so LineNumber will be accurate
331 * (4) returns EOF or terminating character, whichever
334 get_string(string, size, file, terms)
335 char *string;
336 int size;
337 FILE *file;
338 char *terms;
340 int ch;
342 while (EOF != (ch = get_char(file)) && !strchr(terms, ch)) {
343 if (size > 1) {
344 *string++ = (char) ch;
345 size--;
349 if (size > 0)
350 *string = '\0';
352 return ch;
356 /* skip_comments(file) : read past comment (if any)
358 void
359 skip_comments(file)
360 FILE *file;
362 int ch;
364 while (EOF != (ch = get_char(file))) {
365 /* ch is now the first character of a line.
368 while (ch == ' ' || ch == '\t')
369 ch = get_char(file);
371 if (ch == EOF)
372 break;
374 /* ch is now the first non-blank character of a line.
377 if (ch != '\n' && ch != '#')
378 break;
380 /* ch must be a newline or comment as first non-blank
381 * character on a line.
384 while (ch != '\n' && ch != EOF)
385 ch = get_char(file);
387 /* ch is now the newline of a line which we're going to
388 * ignore.
391 if (ch != EOF)
392 unget_char(ch, file);
396 /* int in_file(char *string, FILE *file)
397 * return TRUE if one of the lines in file matches string exactly,
398 * FALSE otherwise.
400 static int
401 in_file(string, file)
402 char *string;
403 FILE *file;
405 char line[MAX_TEMPSTR];
407 rewind(file);
408 while (fgets(line, MAX_TEMPSTR, file)) {
409 if (line[0] != '\0')
410 line[strlen(line)-1] = '\0';
411 if (0 == strcmp(line, string))
412 return TRUE;
414 return FALSE;
418 /* int allowed(char *username)
419 * returns TRUE if (ALLOW_FILE exists and user is listed)
420 * or (DENY_FILE exists and user is NOT listed)
421 * or (neither file exists but user=="root" so it's okay)
424 allowed(username)
425 char *username;
427 static int init = FALSE;
428 static FILE *allow, *deny;
430 if (!init) {
431 init = TRUE;
432 #if defined(ALLOW_FILE) && defined(DENY_FILE)
433 allow = fopen(ALLOW_FILE, "r");
434 deny = fopen(DENY_FILE, "r");
435 Debug(DMISC, ("allow/deny enabled, %d/%d\n", !!allow, !!deny))
436 #else
437 allow = NULL;
438 deny = NULL;
439 #endif
442 if (allow)
443 return (in_file(username, allow));
444 if (deny)
445 return (!in_file(username, deny));
447 #if defined(ALLOW_ONLY_ROOT)
448 return (strcmp(username, ROOT_USER) == 0);
449 #else
450 return TRUE;
451 #endif
455 void
456 log_it(username, pid, event, detail)
457 char *username;
458 int pid;
459 char *event;
460 char *detail;
462 #if defined(LOG_FILE)
463 char *msg;
464 TIME_T now = time((TIME_T) 0);
465 register struct tm *t = localtime(&now);
466 static int log_fd = -1;
467 #endif /*LOG_FILE*/
469 #if defined(SYSLOG)
470 static int syslog_open = 0;
471 #endif
473 #if defined(LOG_FILE)
474 /* we assume that MAX_TEMPSTR will hold the date, time, &punctuation.
476 msg = malloc(strlen(username)
477 + strlen(event)
478 + strlen(detail)
479 + MAX_TEMPSTR);
481 if (log_fd < OK) {
482 log_fd = open(LOG_FILE, O_WRONLY|O_APPEND|O_CREAT, 0600);
483 if (log_fd < OK) {
484 fprintf(stderr, "%s: can't open log file\n",
485 ProgramName);
486 perror(LOG_FILE);
487 } else {
488 (void) fcntl(log_fd, F_SETFD, 1);
492 /* we have to sprintf() it because fprintf() doesn't always write
493 * everything out in one chunk and this has to be atomically appended
494 * to the log file.
496 sprintf(msg, "%s (%02d/%02d-%02d:%02d:%02d-%d) %s (%s)\n",
497 username,
498 t->tm_mon+1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec, pid,
499 event, detail);
501 /* we have to run strlen() because sprintf() returns (char*) on old BSD
503 if (log_fd < OK || write(log_fd, msg, strlen(msg)) < OK) {
504 fprintf(stderr, "%s: can't write to log file\n", ProgramName);
505 if (log_fd >= OK)
506 perror(LOG_FILE);
507 write(STDERR, msg, strlen(msg));
510 free(msg);
511 #endif /*LOG_FILE*/
513 #if defined(SYSLOG)
514 if (!syslog_open) {
515 /* we don't use LOG_PID since the pid passed to us by
516 * our client may not be our own. therefore we want to
517 * print the pid ourselves.
519 # ifdef LOG_DAEMON
520 openlog(ProgramName, LOG_PID, LOG_CRON);
521 # else
522 openlog(ProgramName, LOG_PID);
523 # endif
524 syslog_open = TRUE; /* assume openlog success */
527 syslog(LOG_INFO, "(%s) %s (%s)\n", username, event, detail);
529 #endif /*SYSLOG*/
531 #if DEBUGGING
532 if (DebugFlags) {
533 fprintf(stderr, "log_it: (%s %d) %s (%s)\n",
534 username, pid, event, detail);
536 #endif
540 /* two warnings:
541 * (1) this routine is fairly slow
542 * (2) it returns a pointer to static storage
544 char *
545 first_word(s, t)
546 register char *s; /* string we want the first word of */
547 register char *t; /* terminators, implicitly including \0 */
549 static char retbuf[2][MAX_TEMPSTR + 1]; /* sure wish C had GC */
550 static int retsel = 0;
551 register char *rb, *rp;
553 /* select a return buffer */
554 retsel = 1-retsel;
555 rb = &retbuf[retsel][0];
556 rp = rb;
558 /* skip any leading terminators */
559 while (*s && (NULL != strchr(t, *s))) {
560 s++;
563 /* copy until next terminator or full buffer */
564 while (*s && (NULL == strchr(t, *s)) && (rp < &rb[MAX_TEMPSTR])) {
565 *rp++ = *s++;
568 /* finish the return-string and return it */
569 *rp = '\0';
570 return rb;
574 /* warning:
575 * heavily ascii-dependent.
577 void
578 mkprint(dst, src, len)
579 register char *dst;
580 register unsigned char *src;
581 register int len;
583 while (len-- > 0)
585 register unsigned char ch = *src++;
587 if (ch < ' ') { /* control character */
588 *dst++ = '^';
589 *dst++ = ch + '@';
590 } else if (ch < 0177) { /* printable */
591 *dst++ = ch;
592 } else if (ch == 0177) { /* delete/rubout */
593 *dst++ = '^';
594 *dst++ = '?';
595 } else { /* parity character */
596 sprintf(dst, "\\%03o", ch);
597 dst += 4;
600 *dst = '\0';
604 /* warning:
605 * returns a pointer to malloc'd storage, you must call free yourself.
607 char *
608 mkprints(src, len)
609 register unsigned char *src;
610 register unsigned int len;
612 register char *dst = malloc(len*4 + 1);
614 mkprint(dst, src, len);
616 return dst;
620 #ifdef MAIL_DATE
621 /* Sat, 27 Feb 93 11:44:51 CST
622 * 123456789012345678901234567
624 char *
625 arpadate(clock)
626 time_t *clock;
628 time_t t = clock ?*clock :time(0L);
629 struct tm *tm = localtime(&t);
630 static char ret[30]; /* zone name might be >3 chars */
632 (void) sprintf(ret, "%s, %2d %s %2d %02d:%02d:%02d %s",
633 DowNames[tm->tm_wday],
634 tm->tm_mday,
635 MonthNames[tm->tm_mon],
636 tm->tm_year,
637 tm->tm_hour,
638 tm->tm_min,
639 tm->tm_sec,
640 TZONE(*tm));
641 return ret;
643 #endif /*MAIL_DATE*/
646 #ifdef HAVE_SAVED_SUIDS
647 static int save_euid;
648 int swap_uids() { save_euid = geteuid(); return seteuid(getuid()); }
649 int swap_uids_back() { return seteuid(save_euid); }
650 #else /*HAVE_SAVED_UIDS*/
651 int swap_uids() { return setreuid(geteuid(), getuid()); }
652 int swap_uids_back() { return swap_uids(); }
653 #endif /*HAVE_SAVED_UIDS*/