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
17 * $FreeBSD: src/usr.sbin/cron/lib/misc.c,v 1.8.2.2 2002/04/28 22:45:53 dwmalone Exp $
18 * $DragonFly: src/usr.sbin/cron/lib/misc.c,v 1.5 2004/12/18 22:48:03 swildner Exp $
21 /* vix 26jan87 [RCS has the rest of the log]
22 * vix 30dec86 [written]
28 # include <sys/time.h>
43 #if defined(LOG_DAEMON) && !defined(LOG_CRON)
44 #define LOG_CRON LOG_DAEMON
48 static int LogFD
= ERR
;
52 strcmp_until(char *left
, char *right
, int until
)
56 while (*left
&& *left
!= until
&& *left
== *right
) {
61 if ((*left
=='\0' || *left
== until
) &&
62 (*right
=='\0' || *right
== until
)) {
65 diff
= *left
- *right
;
72 /* strdtb(s) - delete trailing blanks in string 's' and return new length
79 /* scan forward to the null
84 /* scan backward to either the first character before the string,
85 * or the last non-blank in the string, whichever comes first.
88 while (x
>= s
&& isspace(*x
));
90 /* one character beyond where we stopped above is where the null
95 /* the difference between the position of the null character and
96 * the position of the first character of the string is the length.
103 set_debug_flags(char *flags
)
105 /* debug flags are of the form flag[,flag ...]
107 * if an error occurs, print a message to stdout and return FALSE.
108 * otherwise return TRUE after setting ERROR_FLAGS.
113 printf("this program was compiled without debugging enabled\n");
116 #else /* DEBUGGING */
126 /* try to find debug flag name in our list.
128 for ( test
= DebugFlagNames
, mask
= 1;
129 *test
&& strcmp_until(*test
, pc
, ',');
136 "unrecognized debug flag <%s> <%s>\n",
143 /* skip to the next flag
145 while (*pc
&& *pc
!= ',')
154 fprintf(stderr
, "debug flags enabled:");
156 for (flag
= 0; DebugFlagNames
[flag
]; flag
++)
157 if (DebugFlags
& (1 << flag
))
158 fprintf(stderr
, " %s", DebugFlagNames
[flag
]);
159 fprintf(stderr
, "\n");
164 #endif /* DEBUGGING */
171 #if defined(BSD) || defined(POSIX)
172 if (seteuid(ROOT_UID
) < OK
)
173 err(ERROR_EXIT
, "seteuid");
175 if (setuid(ROOT_UID
) < OK
)
176 err(ERROR_EXIT
, "setuid");
186 /* first check for CRONDIR ("/var/cron" or some such)
188 if (stat(CRONDIR
, &sb
) < OK
&& errno
== ENOENT
) {
190 if (OK
== mkdir(CRONDIR
, 0700)) {
191 warnx("%s: created", CRONDIR
);
194 err(ERROR_EXIT
, "%s: mkdir", CRONDIR
);
197 if (!(sb
.st_mode
& S_IFDIR
))
198 err(ERROR_EXIT
, "'%s' is not a directory, bailing out", CRONDIR
);
199 if (chdir(CRONDIR
) < OK
)
200 err(ERROR_EXIT
, "cannot chdir(%s), bailing out", CRONDIR
);
202 /* CRONDIR okay (now==CWD), now look at SPOOL_DIR ("tabs" or some such)
204 if (stat(SPOOL_DIR
, &sb
) < OK
&& errno
== ENOENT
) {
205 warn("%s", SPOOL_DIR
);
206 if (OK
== mkdir(SPOOL_DIR
, 0700)) {
207 warnx("%s: created", SPOOL_DIR
);
208 stat(SPOOL_DIR
, &sb
);
210 err(ERROR_EXIT
, "%s: mkdir", SPOOL_DIR
);
213 if (!(sb
.st_mode
& S_IFDIR
))
214 err(ERROR_EXIT
, "'%s' is not a directory, bailing out", SPOOL_DIR
);
218 /* acquire_daemonlock() - write our PID into /etc/cron.pid, unless
219 * another daemon is already running, which we detect here.
221 * note: main() calls us twice; once before forking, once after.
222 * we maintain static storage of the file pointer so that we
223 * can rewrite our PID into the PIDFILE after the fork.
225 * it would be great if fflush() disassociated the file buffer.
228 acquire_daemonlock(int closeflag
)
230 static FILE *fp
= NULL
;
232 if (closeflag
&& fp
) {
239 char pidfile
[MAX_FNAME
];
240 char buf
[MAX_TEMPSTR
];
243 sprintf(pidfile
, PIDFILE
, PIDDIR
);
244 if ((-1 == (fd
= open(pidfile
, O_RDWR
|O_CREAT
, 0644)))
245 || (NULL
== (fp
= fdopen(fd
, "r+")))
247 sprintf(buf
, "can't open or create %s: %s",
248 pidfile
, strerror(errno
));
249 log_it("CRON", getpid(), "DEATH", buf
);
250 errx(ERROR_EXIT
, "%s", buf
);
253 if (flock(fd
, LOCK_EX
|LOCK_NB
) < OK
) {
254 int save_errno
= errno
;
256 fscanf(fp
, "%d", &otherpid
);
257 sprintf(buf
, "can't lock %s, otherpid may be %d: %s",
258 pidfile
, otherpid
, strerror(save_errno
));
259 log_it("CRON", getpid(), "DEATH", buf
);
260 errx(ERROR_EXIT
, "%s", buf
);
263 fcntl(fd
, F_SETFD
, 1);
267 fprintf(fp
, "%d\n", getpid());
269 ftruncate(fileno(fp
), ftell(fp
));
271 /* abandon fd and fp even though the file is open. we need to
272 * keep it open and locked, but we don't need the handles elsewhere.
276 /* get_char(file) : like getc() but increment LineNumber on newlines
285 Set_LineNum(LineNumber
+ 1)
290 /* unget_char(ch, file) : like ungetc but do LineNumber processing
293 unget_char(int ch
, FILE *file
)
297 Set_LineNum(LineNumber
- 1)
301 /* get_string(str, max, file, termstr) : like fgets() but
302 * (1) has terminator string which should include \n
303 * (2) will always leave room for the null
304 * (3) uses get_char() so LineNumber will be accurate
305 * (4) returns EOF or terminating character, whichever
308 get_string(char *string
, int size
, FILE *file
, char *terms
)
312 while (EOF
!= (ch
= get_char(file
)) && !strchr(terms
, ch
)) {
314 *string
++ = (char) ch
;
326 /* skip_comments(file) : read past comment (if any)
329 skip_comments(FILE *file
)
333 while (EOF
!= (ch
= get_char(file
))) {
334 /* ch is now the first character of a line.
337 while (ch
== ' ' || ch
== '\t')
343 /* ch is now the first non-blank character of a line.
346 if (ch
!= '\n' && ch
!= '#')
349 /* ch must be a newline or comment as first non-blank
350 * character on a line.
353 while (ch
!= '\n' && ch
!= EOF
)
356 /* ch is now the newline of a line which we're going to
361 unget_char(ch
, file
);
365 /* int in_file(char *string, FILE *file)
366 * return TRUE if one of the lines in file matches string exactly,
370 in_file(char *string
, FILE *file
)
372 char line
[MAX_TEMPSTR
];
375 while (fgets(line
, MAX_TEMPSTR
, file
)) {
377 if (line
[strlen(line
)-1] == '\n')
378 line
[strlen(line
)-1] = '\0';
379 if (0 == strcmp(line
, string
))
386 /* int allowed(char *username)
387 * returns TRUE if (ALLOW_FILE exists and user is listed)
388 * or (DENY_FILE exists and user is NOT listed)
389 * or (neither file exists but user=="root" so it's okay)
392 allowed(char *username
)
394 static int init
= FALSE
;
395 static FILE *allow
, *deny
;
399 #if defined(ALLOW_FILE) && defined(DENY_FILE)
400 allow
= fopen(ALLOW_FILE
, "r");
401 deny
= fopen(DENY_FILE
, "r");
402 Debug(DMISC
, ("allow/deny enabled, %d/%d\n", !!allow
, !!deny
))
410 return (in_file(username
, allow
));
412 return (!in_file(username
, deny
));
414 #if defined(ALLOW_ONLY_ROOT)
415 return (strcmp(username
, ROOT_USER
) == 0);
423 log_it(char *username
, int xpid
, char *event
, char *detail
)
426 #if defined(LOG_FILE)
433 static int syslog_open
= 0;
436 #if defined(LOG_FILE)
437 now
= time((TIME_T
)0);
439 /* we assume that MAX_TEMPSTR will hold the date, time, &punctuation.
441 msg
= malloc(strlen(username
)
447 warnx("failed to allocate memory for log message");
450 LogFD
= open(LOG_FILE
, O_WRONLY
|O_APPEND
|O_CREAT
, 0600);
452 warn("can't open log file %s", LOG_FILE
);
454 fcntl(LogFD
, F_SETFD
, 1);
458 /* we have to sprintf() it because fprintf() doesn't always
459 * write everything out in one chunk and this has to be
460 * atomically appended to the log file.
462 sprintf(msg
, "%s (%02d/%02d-%02d:%02d:%02d-%d) %s (%s)\n",
464 t
->tm_mon
+1, t
->tm_mday
, t
->tm_hour
, t
->tm_min
,
465 t
->tm_sec
, pid
, event
, detail
);
467 /* we have to run strlen() because sprintf() returns (char*)
470 if (LogFD
< OK
|| write(LogFD
, msg
, strlen(msg
)) < OK
) {
472 warn("%s", LOG_FILE
);
473 warnx("can't write to log file");
474 write(STDERR
, msg
, strlen(msg
));
483 /* we don't use LOG_PID since the pid passed to us by
484 * our client may not be our own. therefore we want to
485 * print the pid ourselves.
488 openlog(ProgramName
, LOG_PID
, LOG_CRON
);
490 openlog(ProgramName
, LOG_PID
);
492 syslog_open
= TRUE
; /* assume openlog success */
495 syslog(LOG_INFO
, "(%s) %s (%s)\n", username
, event
, detail
);
501 fprintf(stderr
, "log_it: (%s %d) %s (%s)\n",
502 username
, pid
, event
, detail
);
518 * (1) this routine is fairly slow
519 * (2) it returns a pointer to static storage
521 * s string we want the first word of
522 * t terminators, implicitly including \0
525 first_word(char *s
, char *t
)
527 static char retbuf
[2][MAX_TEMPSTR
+ 1]; /* sure wish C had GC */
528 static int retsel
= 0;
531 /* select a return buffer */
533 rb
= &retbuf
[retsel
][0];
536 /* skip any leading terminators */
537 while (*s
&& (NULL
!= strchr(t
, *s
))) {
541 /* copy until next terminator or full buffer */
542 while (*s
&& (NULL
== strchr(t
, *s
)) && (rp
< &rb
[MAX_TEMPSTR
])) {
546 /* finish the return-string and return it */
553 * heavily ascii-dependent.
556 mkprint(char *dst
, unsigned char *src
, int len
)
560 unsigned char ch
= *src
++;
562 if (ch
< ' ') { /* control character */
565 } else if (ch
< 0177) { /* printable */
567 } else if (ch
== 0177) { /* delete/rubout */
570 } else { /* parity character */
571 sprintf(dst
, "\\%03o", ch
);
580 * returns a pointer to malloc'd storage, you must call free yourself.
583 mkprints(unsigned char *src
, unsigned int len
)
587 dst
= malloc(len
* 4 + 1);
589 mkprint(dst
, src
, len
);
596 /* Sat, 27 Feb 93 11:44:51 CST
597 * 123456789012345678901234567
600 arpadate(time_t *clock
)
602 time_t t
= clock
?*clock
:time(0L);
603 struct tm
*tm
= localtime(&t
);
604 static char ret
[32]; /* zone name might be >3 chars */
606 if (tm
->tm_year
>= 100)
609 snprintf(ret
, sizeof(ret
), "%s, %2d %s %d %02d:%02d:%02d %s",
610 DowNames
[tm
->tm_wday
],
612 MonthNames
[tm
->tm_mon
],
623 #ifdef HAVE_SAVED_UIDS
624 static int save_euid
;
628 save_euid
= geteuid();
629 return seteuid(getuid());
635 return seteuid(save_euid
);
637 #else /*HAVE_SAVED_UIDS*/
641 return setreuid(geteuid(), getuid());
648 #endif /*HAVE_SAVED_UIDS*/