1 /* $NetBSD: misc.c,v 1.13 2006/05/21 19:26:43 christos Exp $ */
3 /* Copyright 1988,1990,1993,1994 by Paul Vixie
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
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)
23 static char rcsid
[] = "Id: misc.c,v 2.9 1994/01/15 20:43:43 vixie Exp";
25 __RCSID("$NetBSD: misc.c,v 1.13 2006/05/21 19:26:43 christos Exp $");
29 /* vix 26jan87 [RCS has the rest of the log]
30 * vix 30dec86 [written]
36 # include <sys/time.h>
52 #if defined(LOG_DAEMON) && !defined(LOG_CRON)
53 #define LOG_CRON LOG_DAEMON
56 static int in_file(char *, FILE *);
57 static void mkprint(char *, unsigned char *, int);
59 static int LogFD
= ERR
;
63 strcmp_until(const char *left
, const char *right
, int until
)
67 while (*left
&& *left
!= until
&& *left
== *right
) {
72 if ((*left
=='\0' || *left
== until
) &&
73 (*right
=='\0' || *right
== until
)) {
76 diff
= *left
- *right
;
83 /* strdtb(s) - delete trailing blanks in string 's' and return new length
90 /* scan forward to the null
95 /* scan backward to either the first character before the string,
96 * or the last non-blank in the string, whichever comes first.
99 while (x
>= s
&& isspace((unsigned char)*x
));
101 /* one character beyond where we stopped above is where the null
106 /* the difference between the position of the null character and
107 * the position of the first character of the string is the length.
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.
124 printf("this program was compiled without debugging enabled\n");
127 #else /* DEBUGGING */
134 const char * const *test
;
137 /* try to find debug flag name in our list.
139 for ( test
= DebugFlagNames
, mask
= 1;
140 *test
&& strcmp_until(*test
, pc
, ',');
147 "unrecognized debug flag <%s> <%s>\n",
154 /* skip to the next flag
156 while (*pc
&& *pc
!= ',')
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");
175 #endif /* DEBUGGING */
182 #if defined(BSD) || defined(POSIX)
183 if (seteuid(ROOT_UID
) < OK
) {
184 warn("cannot seteuid");
188 if (setuid(ROOT_UID
) < OK
) {
189 warn("cannot setuid");
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
);
209 warn("cannot create %s", CRONDIR
);
213 if (!S_ISDIR(sb
.st_mode
)) {
214 warnx("`%s' is not a directory, bailing out", CRONDIR
);
217 if (chdir(CRONDIR
) < OK
) {
218 warn("cannot chdir(%s), bailing out", CRONDIR
);
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
);
230 warn("cannot create %s", SPOOL_DIR
);
234 if (!S_ISDIR(sb
.st_mode
)) {
235 fprintf(stderr
, "'%s' is not a directory, bailing out.\n",
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.
252 acquire_daemonlock(int closeflag
)
254 static FILE *fp
= NULL
;
256 if (closeflag
&& fp
) {
263 char pidfile
[MAX_FNAME
];
264 char buf
[MAX_TEMPSTR
];
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
));
275 log_it("CRON", getpid(), "DEATH", buf
);
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
));
287 log_it("CRON", getpid(), "DEATH", buf
);
291 (void) fcntl(fd
, F_SETFD
, 1);
295 fprintf(fp
, "%d\n", getpid());
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
313 Set_LineNum(LineNumber
+ 1)
318 /* unget_char(ch, file) : like ungetc but do LineNumber processing
321 unget_char(int ch
, FILE *file
)
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
)
340 while (EOF
!= (ch
= get_char(file
)) && !strchr(terms
, ch
)) {
342 *string
++ = (char) ch
;
354 /* skip_comments(file) : read past comment (if any)
357 skip_comments(FILE *file
)
361 while (EOF
!= (ch
= get_char(file
))) {
362 /* ch is now the first character of a line.
365 while (ch
== ' ' || ch
== '\t')
371 /* ch is now the first non-blank character of a line.
374 if (ch
!= '\n' && ch
!= '#')
377 /* ch must be a newline or comment as first non-blank
378 * character on a line.
381 while (ch
!= '\n' && ch
!= EOF
)
384 /* ch is now the newline of a line which we're going to
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,
398 in_file(char *string
, FILE *file
)
400 char line
[MAX_TEMPSTR
];
403 while (fgets(line
, MAX_TEMPSTR
, file
)) {
405 line
[strlen(line
)-1] = '\0';
406 if (0 == strcmp(line
, string
))
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
;
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
))
431 (void)fcntl(fileno(allow
), F_SETFD
, FD_CLOEXEC
);
433 (void)fcntl(fileno(deny
), F_SETFD
, FD_CLOEXEC
);
441 return (in_file(username
, allow
));
443 return (!in_file(username
, deny
));
445 #if defined(ALLOW_ONLY_ROOT)
446 return (strcmp(username
, ROOT_USER
) == 0);
454 log_it(const char *username
, int xpid
, const char *event
, const char *detail
)
457 #if defined(LOG_FILE)
460 TIME_T now
= time((TIME_T
) 0);
461 struct tm
*t
= localtime(&now
);
465 static int syslog_open
= 0;
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
) +
473 msg
= malloc(msglen
);
476 LogFD
= open(LOG_FILE
, O_WRONLY
|O_APPEND
|O_CREAT
, 0600);
478 warn("can't open log file %s", LOG_FILE
);
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
488 snprintf(msg
, msglen
, "%s (%02d/%02d-%02d:%02d:%02d-%d) %s (%s)\n",
490 t
->tm_mon
+1, t
->tm_mday
, t
->tm_hour
, t
->tm_min
, t
->tm_sec
, pid
,
493 /* we have to run strlen() because sprintf() returns (char*) on old BSD
495 if (LogFD
< OK
|| write(LogFD
, msg
, strlen(msg
)) < OK
) {
497 warn("can't write to log file");
498 write(STDERR
, msg
, strlen(msg
));
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.
511 openlog(getprogname(), LOG_PID
, LOG_CRON
);
513 openlog(getprogname(), LOG_PID
);
515 syslog_open
= TRUE
; /* assume openlog success */
518 syslog(LOG_INFO
, "(%s) %s (%s)\n", username
, event
, detail
);
524 fprintf(stderr
, "log_it: (%s %d) %s (%s)\n",
525 username
, pid
, event
, detail
);
541 * (1) this routine is fairly slow
542 * (2) it returns a pointer to static storage
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;
552 /* select a return buffer */
554 rb
= &retbuf
[retsel
][0];
557 /* skip any leading terminators */
558 while (*s
&& (NULL
!= strchr(t
, *s
))) {
562 /* copy until next terminator or full buffer */
563 while (*s
&& (NULL
== strchr(t
, *s
)) && (rp
< &rb
[MAX_TEMPSTR
])) {
567 /* finish the return-string and return it */
574 * heavily ascii-dependent.
577 mkprint(char *dst
, unsigned char *src
, int len
)
579 while(len
> 0 && isblank((unsigned char) *src
))
582 strvisx(dst
, src
, len
, VIS_TAB
|VIS_NL
);
587 * returns a pointer to malloc'd storage, you must call free yourself.
590 mkprints(unsigned char *src
, unsigned int len
)
592 char *dst
= malloc(len
*4 + 1);
594 mkprint(dst
, src
, len
);
601 /* Sat, 27 Feb 1993 11:44:51 -0800 (CST)
602 * 1234567890123456789012345678901234567
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;
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';
624 #ifdef HAVE_SAVED_UIDS
625 static int save_euid
;
626 int swap_uids(void) { save_euid
= geteuid(); return seteuid(getuid()); }
628 int swap_uids_back() { return seteuid(save_euid
); }
630 #else /*HAVE_SAVED_UIDS*/
631 int swap_uids(void) { return setreuid(geteuid(), getuid()); }
633 int swap_uids_back() { return swap_uids(); }
635 #endif /*HAVE_SAVED_UIDS*/