From b127095ec801766f86ca2d2798aad7d00d9af26d Mon Sep 17 00:00:00 2001 From: =?utf8?q?Marcela=20Ma=C5=A1l=C3=A1=C5=88ov=C3=A1?= Date: Fri, 29 May 2009 15:49:04 +0200 Subject: [PATCH] Beautify the code with indent. Thanks for .indent.pro to Martin Klozik. --- src/.indent.pro | 32 ++++ src/cron.c | 253 ++++++++++++-------------- src/crontab.c | 372 ++++++++++++++++++-------------------- src/database.c | 202 +++++++++++---------- src/do_command.c | 339 +++++++++++++++++------------------ src/entry.c | 256 +++++++++++++------------- src/env.c | 68 ++++--- src/job.c | 18 +- src/misc.c | 382 ++++++++++++++++++--------------------- src/popen.c | 67 ++++--- src/security.c | 457 ++++++++++++++++++++++++----------------------- src/user.c | 85 +++++---- 12 files changed, 1233 insertions(+), 1298 deletions(-) create mode 100644 src/.indent.pro diff --git a/src/.indent.pro b/src/.indent.pro new file mode 100644 index 0000000..36235da --- /dev/null +++ b/src/.indent.pro @@ -0,0 +1,32 @@ +--blank-before-sizeof +--brace-indent0 +--braces-on-func-def-line +--braces-on-if-line +--braces-on-struct-decl-line +--break-after-boolean-operator +--case-brace-indentation0 +--case-indentation0 +--comment-indentation0 +--continuation-indentation4 +--cuddle-do-while +--declaration-comment-column0 +--declaration-indentation0 +--dont-break-function-decl-args +--dont-break-procedure-type +--dont-line-up-parentheses +--honour-newlines +--indent-level4 +--line-length80 +--paren-indentation4 +--preprocessor-indentation1 +--no-blank-lines-after-commas +--space-after-cast +--space-after-for +--space-after-if +--space-after-while +--space-special-semicolon +--no-space-after-parentheses +--no-space-after-function-call-names +--start-left-side-of-comments +--struct-brace-indentation4 +--tab-size4 diff --git a/src/cron.c b/src/cron.c index 3e18d10..fea297a 100644 --- a/src/cron.c +++ b/src/cron.c @@ -26,38 +26,35 @@ #if defined WITH_INOTIFY int inotify_enabled; #else -#define inotify_enabled 0 +# define inotify_enabled 0 #endif enum timejump { negative, small, medium, large }; -static void usage(void), - run_reboot_jobs(cron_db *), - find_jobs(int, cron_db *, int, int), - set_time(int), - cron_sleep(int, cron_db *), - sigchld_handler(int), - sighup_handler(int), - sigchld_reaper(void), - quit(int), - parse_args(int c, char *v[]); - -static volatile sig_atomic_t got_sighup, got_sigchld; -static int timeRunning, virtualTime, clockTime; -static long GMToff; +static void usage(void), +run_reboot_jobs(cron_db *), +find_jobs(int, cron_db *, int, int), +set_time(int), +cron_sleep(int, cron_db *), +sigchld_handler(int), +sighup_handler(int), +sigchld_reaper(void), quit(int), parse_args(int c, char *v[]); + +static volatile sig_atomic_t got_sighup, got_sigchld; +static int timeRunning, virtualTime, clockTime; +static long GMToff; #if defined WITH_INOTIFY -#define NUM_WATCHES 3 +# define NUM_WATCHES 3 int wd[NUM_WATCHES]; -const char *watchpaths[NUM_WATCHES] = { SPOOL_DIR, SYS_CROND_DIR, SYSCRONTAB }; +const char *watchpaths[NUM_WATCHES] = {SPOOL_DIR, SYS_CROND_DIR, SYSCRONTAB}; -void -set_cron_unwatched(int fd) { +void set_cron_unwatched(int fd) { int i; - - for (i = 0; i < sizeof(wd)/sizeof(wd[0]); ++i) { + + for (i = 0; i < sizeof (wd) / sizeof (wd[0]); ++i) { if (wd[i] < 0) { inotify_rm_watch(fd, wd[i]); wd[i] = -1; @@ -65,8 +62,7 @@ set_cron_unwatched(int fd) { } } -void -set_cron_watched(int fd) { +void set_cron_watched(int fd) { pid_t pid = getpid(); int i; @@ -75,7 +71,7 @@ set_cron_watched(int fd) { return; } - for (i = 0; i < sizeof(wd)/sizeof(wd[0]); ++i) { + for (i = 0; i < sizeof (wd) / sizeof (wd[0]); ++i) { int w; w = inotify_add_watch(fd, watchpaths[i], @@ -83,8 +79,10 @@ set_cron_watched(int fd) { IN_MOVED_FROM | IN_MOVE_SELF | IN_DELETE | IN_DELETE_SELF); if (w < 0) { if (wd[i] != -1) { - log_it("CRON", pid, "This directory or file can't be watched", watchpaths[i], errno); - log_it("CRON", pid, "INFO", "running without inotify support", 0); + log_it("CRON", pid, "This directory or file can't be watched", + watchpaths[i], errno); + log_it("CRON", pid, "INFO", "running without inotify support", + 0); } inotify_enabled = 0; set_cron_unwatched(fd); @@ -101,8 +99,7 @@ set_cron_watched(int fd) { } #endif -static void -handle_signals(cron_db *database) { +static void handle_signals(cron_db * database) { if (got_sighup) { got_sighup = 0; #if defined WITH_INOTIFY @@ -122,21 +119,20 @@ handle_signals(cron_db *database) { } } -static void -usage(void) { +static void usage(void) { const char **dflags; - fprintf(stderr, "usage: %s [-n] [-p] [-m ] [-x [", ProgramName); + fprintf(stderr, "usage: %s [-n] [-p] [-m ] [-x [", + ProgramName); for (dflags = DebugFlagNames; *dflags; dflags++) fprintf(stderr, "%s%s", *dflags, dflags[1] ? "," : "]"); fprintf(stderr, "]\n"); exit(ERROR_EXIT); } -int -main(int argc, char *argv[]) { +int main(int argc, char *argv[]) { struct sigaction sact; - cron_db database; + cron_db database; int fd; char *cs; pid_t pid = getpid(); @@ -158,7 +154,7 @@ main(int argc, char *argv[]) { NoFork = 0; parse_args(argc, argv); - bzero((char *)&sact, sizeof sact); + bzero((char *) &sact, sizeof sact); sigemptyset(&sact.sa_mask); sact.sa_flags = 0; #ifdef SA_RESTART @@ -176,31 +172,32 @@ main(int argc, char *argv[]) { set_cron_uid(); set_cron_cwd(); - if (putenv("PATH="_PATH_DEFPATH) < 0) { + if (putenv("PATH=" _PATH_DEFPATH) < 0) { log_it("CRON", pid, "DEATH", "can't putenv PATH", errno); exit(1); } - - if ( getenv("CRON_VALIDATE_MAILRCPTS") != 0L ) - ValidateMailRcpts=1; + + if (getenv("CRON_VALIDATE_MAILRCPTS") != 0L) + ValidateMailRcpts = 1; /* Get the default locale character set for the mail * "Content-Type: ...; charset=" header */ - setlocale(LC_ALL,""); /* set locale to system defaults or to - that specified by any LC_* env vars */ - if ( ( cs = nl_langinfo( CODESET ) ) != 0L ) - strncpy( cron_default_mail_charset, cs, MAX_ENVSTR ); + setlocale(LC_ALL, ""); /* set locale to system defaults or to + * that specified by any LC_* env vars */ + if ((cs = nl_langinfo(CODESET)) != 0L) + strncpy(cron_default_mail_charset, cs, MAX_ENVSTR); else - strcpy( cron_default_mail_charset, "US-ASCII" ); - + strcpy(cron_default_mail_charset, "US-ASCII"); + /* if there are no debug flags turned on, fork as a daemon should. */ if (DebugFlags) { #if DEBUGGING - (void) fprintf(stderr, "[%ld] cron started\n", (long)getpid()); + (void) fprintf(stderr, "[%ld] cron started\n", (long) getpid()); #endif - } else if (NoFork == 0) { + } + else if (NoFork == 0) { switch (fork()) { case -1: log_it("CRON", pid, "DEATH", "can't fork", errno); @@ -233,7 +230,7 @@ main(int argc, char *argv[]) { load_database(&database); #if defined WITH_INOTIFY - for (i = 0; i < sizeof(wd)/sizeof(wd[0]); ++i) { + for (i = 0; i < sizeof (wd) / sizeof (wd[0]); ++i) { /* initialize to negative number other than -1 * so an eventual error is reported for the first time */ @@ -282,7 +279,7 @@ main(int argc, char *argv[]) { check_inotify_database(&database); } else { - if(load_database(&database)) + if (load_database(&database)) /* try reinstating the watches */ set_cron_watched(fd); } @@ -294,9 +291,9 @@ main(int argc, char *argv[]) { if (timeDiff == 1) { virtualTime = timeRunning; find_jobs(virtualTime, &database, TRUE, TRUE); - } else { - if (timeDiff > (3*MINUTE_COUNT) || - timeDiff < -(3*MINUTE_COUNT)) + } + else { + if (timeDiff > (3 * MINUTE_COUNT) || timeDiff < -(3 * MINUTE_COUNT)) wakeupKind = large; else if (timeDiff > 5) wakeupKind = medium; @@ -313,8 +310,8 @@ main(int argc, char *argv[]) { * minute until caught up. */ Debug(DSCH, ("[%ld], normal case %d minutes to go\n", - (long)pid, timeDiff)) - do { + (long) pid, timeDiff)) + do { if (job_runqueue()) sleep(10); virtualTime++; @@ -335,22 +332,20 @@ main(int argc, char *argv[]) { * housekeeping. */ Debug(DSCH, ("[%ld], DST begins %d minutes to go\n", - (long)pid, timeDiff)) - /* run wildcard jobs for current minute */ - find_jobs(timeRunning, &database, TRUE, FALSE); - + (long) pid, timeDiff)) + /* run wildcard jobs for current minute */ + find_jobs(timeRunning, &database, TRUE, FALSE); + /* run fixed-time jobs for each minute missed */ do { if (job_runqueue()) sleep(10); virtualTime++; - find_jobs(virtualTime, &database, - FALSE, TRUE); + find_jobs(virtualTime, &database, FALSE, TRUE); set_time(FALSE); - } while (virtualTime< timeRunning && - clockTime == timeRunning); + } while (virtualTime < timeRunning && clockTime == timeRunning); break; - + case negative: /* * case 3: timeDiff is a small or medium-sized @@ -361,17 +356,16 @@ main(int argc, char *argv[]) { * change until we are caught up. */ Debug(DSCH, ("[%ld], DST ends %d minutes to go\n", - (long)pid, timeDiff)) - find_jobs(timeRunning, &database, TRUE, FALSE); + (long) pid, timeDiff)) + find_jobs(timeRunning, &database, TRUE, FALSE); break; default: /* * other: time has changed a *lot*, * jump virtual time, and run everything */ - Debug(DSCH, ("[%ld], clock jumped\n", - (long)pid)) - virtualTime = timeRunning; + Debug(DSCH, ("[%ld], clock jumped\n", (long) pid)) + virtualTime = timeRunning; find_jobs(timeRunning, &database, TRUE, TRUE); } } @@ -391,8 +385,7 @@ main(int argc, char *argv[]) { #endif } -static void -run_reboot_jobs(cron_db *db) { +static void run_reboot_jobs(cron_db * db) { user *u; entry *e; int reboot; @@ -400,12 +393,14 @@ run_reboot_jobs(cron_db *db) { /* lock exist - skip reboot jobs */ if (access(REBOOT_LOCK, F_OK) == 0) { - log_it("CRON", pid, "INFO", "@reboot jobs will be run at computer's startup.", 0); + log_it("CRON", pid, "INFO", + "@reboot jobs will be run at computer's startup.", 0); return; } /* lock doesn't exist - create lock, run reboot jobs */ - if ((reboot = creat(REBOOT_LOCK, S_IRUSR&S_IWUSR)) < 0) - log_it("CRON", pid, "INFO", "Can't create lock for reboot jobs.", errno); + if ((reboot = creat(REBOOT_LOCK, S_IRUSR & S_IWUSR)) < 0) + log_it("CRON", pid, "INFO", "Can't create lock for reboot jobs.", + errno); else close(reboot); @@ -418,16 +413,15 @@ run_reboot_jobs(cron_db *db) { (void) job_runqueue(); } -static void -find_jobs(int vtime, cron_db *db, int doWild, int doNonWild) { +static void find_jobs(int vtime, cron_db * db, int doWild, int doNonWild) { char *orig_tz, *job_tz; - time_t virtualSecond = vtime * SECONDS_PER_MINUTE; + time_t virtualSecond = vtime * SECONDS_PER_MINUTE; struct tm *tm = gmtime(&virtualSecond); int minute, hour, dom, month, dow; user *u; entry *e; - const char *uname; - struct passwd *pw = NULL; + const char *uname; + struct passwd *pw = NULL; /* make 0-based values out of these so we can use them as indicies */ @@ -451,38 +445,38 @@ find_jobs(int vtime, cron_db *db, int doWild, int doNonWild) { maketime(NULL, orig_tz); Debug(DSCH, ("[%ld] tick(%d,%d,%d,%d,%d) %s %s\n", - (long)getpid(), minute, hour, dom, month, dow, - doWild?" ":"No wildcard",doNonWild?" ":"Wildcard only")) - /* the dom/dow situation is odd. '* * 1,15 * Sun' will run on the - * first and fifteenth AND every Sunday; '* * * * Sun' will run *only* - * on Sundays; '* * 1,15 * *' will run *only* the 1st and 15th. this - * is why we keep 'e->dow_star' and 'e->dom_star'. yes, it's bizarre. - * like many bizarre things, it's the standard. - */ - for (u = db->head; u != NULL; u = u->next) { + (long) getpid(), minute, hour, dom, month, dow, + doWild ? " " : "No wildcard", doNonWild ? " " : "Wildcard only")) + /* the dom/dow situation is odd. '* * 1,15 * Sun' will run on the + * first and fifteenth AND every Sunday; '* * * * Sun' will run *only* + * on Sundays; '* * 1,15 * *' will run *only* the 1st and 15th. this + * is why we keep 'e->dow_star' and 'e->dom_star'. yes, it's bizarre. + * like many bizarre things, it's the standard. + */ + for (u = db->head; u != NULL; u = u->next) { for (e = u->crontab; e != NULL; e = e->next) { - Debug(DSCH|DEXT, ("user [%s:%ld:%ld:...] cmd=\"%s\"\n", - e->pwd->pw_name, (long)e->pwd->pw_uid, - (long)e->pwd->pw_gid, e->cmd)) - uname = e->pwd->pw_name; + Debug(DSCH | DEXT, ("user [%s:%ld:%ld:...] cmd=\"%s\"\n", + e->pwd->pw_name, (long) e->pwd->pw_uid, + (long) e->pwd->pw_gid, e->cmd)) + uname = e->pwd->pw_name; /* check if user exists in time of job is being run f.e. ldap */ if ((pw = getpwnam(uname)) != NULL) { job_tz = env_get("CRON_TZ", e->envp); maketime(job_tz, orig_tz); /* here we test whether time is NOW */ if (bit_test(e->minute, minute) && - bit_test(e->hour, hour) && - bit_test(e->month, month) && - ( ((e->flags & DOM_STAR) || (e->flags & DOW_STAR)) - ? (bit_test(e->dow,dow) && bit_test(e->dom,dom)) - : (bit_test(e->dow,dow) || bit_test(e->dom,dom)) - ) - ) { + bit_test(e->hour, hour) && + bit_test(e->month, month) && + (((e->flags & DOM_STAR) || (e->flags & DOW_STAR)) + ? (bit_test(e->dow, dow) && bit_test(e->dom, dom)) + : (bit_test(e->dow, dow) || bit_test(e->dom, dom)) + ) + ) { if ((doNonWild && - !(e->flags & (MIN_STAR|HR_STAR))) || - (doWild && (e->flags & (MIN_STAR|HR_STAR)))) - job_add(e, u); /*will add job, if it isn't in queue already for NOW.*/ - } + !(e->flags & (MIN_STAR | HR_STAR))) || + (doWild && (e->flags & (MIN_STAR | HR_STAR)))) + job_add(e, u); /*will add job, if it isn't in queue already for NOW. */ + } } } } @@ -497,8 +491,7 @@ find_jobs(int vtime, cron_db *db, int doWild, int doNonWild) { * These are used for computing what time it really is right now. * Note that clockTime is a unix wallclock time converted to minutes. */ -static void -set_time(int initialize) { +static void set_time(int initialize) { struct tm tm; static int isdst; @@ -509,26 +502,25 @@ set_time(int initialize) { if (initialize || tm.tm_isdst != isdst) { isdst = tm.tm_isdst; GMToff = get_gmtoff(&StartTime, &tm); - Debug(DSCH, ("[%ld] GMToff=%ld\n", - (long)getpid(), (long)GMToff)) + Debug(DSCH, ("[%ld] GMToff=%ld\n", (long) getpid(), (long) GMToff)) } - clockTime = (StartTime + GMToff) / (time_t)SECONDS_PER_MINUTE; + clockTime = (StartTime + GMToff) / (time_t) SECONDS_PER_MINUTE; } /* * Try to just hit the next minute. */ -static void -cron_sleep(int target, cron_db *db) { +static void cron_sleep(int target, cron_db * db) { time_t t1, t2; int seconds_to_wait; t1 = time(NULL) + GMToff; - seconds_to_wait = (int)(target * SECONDS_PER_MINUTE - t1) + 1; + seconds_to_wait = (int) (target * SECONDS_PER_MINUTE - t1) + 1; Debug(DSCH, ("[%ld] Target time=%ld, sec-to-wait=%d\n", - (long)getpid(), (long)target*SECONDS_PER_MINUTE, seconds_to_wait)) + (long) getpid(), (long) target * SECONDS_PER_MINUTE, + seconds_to_wait)) - while (seconds_to_wait > 0 && seconds_to_wait < 65) { + while (seconds_to_wait > 0 && seconds_to_wait < 65) { sleep((unsigned int) seconds_to_wait); /* @@ -539,29 +531,25 @@ cron_sleep(int target, cron_db *db) { handle_signals(db); t2 = time(NULL) + GMToff; - seconds_to_wait -= (int)(t2 - t1); + seconds_to_wait -= (int) (t2 - t1); t1 = t2; } } -static void -sighup_handler(int x) { +static void sighup_handler(int x) { got_sighup = 1; } -static void -sigchld_handler(int x) { +static void sigchld_handler(int x) { got_sigchld = 1; } -static void -quit(int x) { +static void quit(int x) { (void) unlink(_PATH_CRON_PID); _exit(0); } -static void -sigchld_reaper(void) { +static void sigchld_reaper(void) { WAIT_T waiter; PID_T pid; @@ -571,26 +559,21 @@ sigchld_reaper(void) { case -1: if (errno == EINTR) continue; - Debug(DPROC, - ("[%ld] sigchld...no children\n", - (long)getpid())) - break; + Debug(DPROC, ("[%ld] sigchld...no children\n", (long) getpid())) + break; case 0: - Debug(DPROC, - ("[%ld] sigchld...no dead kids\n", - (long)getpid())) - break; + Debug(DPROC, ("[%ld] sigchld...no dead kids\n", (long) getpid())) + break; default: Debug(DPROC, - ("[%ld] sigchld...pid #%ld died, stat=%d\n", - (long)getpid(), (long)pid, WEXITSTATUS(waiter))) - break; + ("[%ld] sigchld...pid #%ld died, stat=%d\n", + (long) getpid(), (long) pid, WEXITSTATUS(waiter))) + break; } } while (pid > 0); } -static void -parse_args(int argc, char *argv[]) { +static void parse_args(int argc, char *argv[]) { int argch; while (-1 != (argch = getopt(argc, argv, "npx:m:"))) { @@ -605,7 +588,7 @@ parse_args(int argc, char *argv[]) { NoFork = 1; break; case 'p': - PermitAnyCrontab=1; + PermitAnyCrontab = 1; break; case 'm': strncpy(MailCmd, optarg, MAX_COMMAND); diff --git a/src/crontab.c b/src/crontab.c index 38fe785..bcf9a33 100644 --- a/src/crontab.c +++ b/src/crontab.c @@ -28,51 +28,49 @@ #include #ifdef WITH_SELINUX -#include -#include -#include +# include +# include +# include #endif #define NHEADER_LINES 0 -enum opt_t { opt_unknown, opt_list, opt_delete, opt_edit, opt_replace }; +enum opt_t {opt_unknown, opt_list, opt_delete, opt_edit, opt_replace}; #if DEBUGGING -static char *Options[] = { "???", "list", "delete", "edit", "replace" }; -# ifdef WITH_SELINUX -static char *getoptargs = "u:lerisx:"; -# else -static char *getoptargs = "u:lerix:"; -# endif +static char *Options[] = {"???", "list", "delete", "edit", "replace"}; + +# ifdef WITH_SELINUX +static char *getoptargs = "u:lerisx:"; +# else +static char *getoptargs = "u:lerix:"; +# endif #else -# ifdef WITH_SELINUX -static char *getoptargs = "u:leris"; -# else -static char *getoptargs = "u:leri"; -# endif +# ifdef WITH_SELINUX +static char *getoptargs = "u:leris"; +# else +static char *getoptargs = "u:leri"; +# endif #endif -static char *selinux_context = 0; - -static PID_T Pid; -static char User[MAX_UNAME], RealUser[MAX_UNAME]; -static char Filename[MAX_FNAME], TempFilename[MAX_FNAME]; -static FILE *NewCrontab; -static int CheckErrorCount; -static int PromptOnDelete; -static enum opt_t Option; -static struct passwd *pw; -static void list_cmd(void), - delete_cmd(void), - edit_cmd(void), - poke_daemon(void), - check_error(const char *), - parse_args(int c, char *v[]), - die(int); -static int replace_cmd(void); -static char *tmp_path(void); - -static void -usage(const char *msg) { +static char *selinux_context = 0; + +static PID_T Pid; +static char User[MAX_UNAME], RealUser[MAX_UNAME]; +static char Filename[MAX_FNAME], TempFilename[MAX_FNAME]; +static FILE *NewCrontab; +static int CheckErrorCount; +static int PromptOnDelete; +static enum opt_t Option; +static struct passwd *pw; +static void list_cmd(void), +delete_cmd(void), +edit_cmd(void), +poke_daemon(void), +check_error(const char *), parse_args(int c, char *v[]), die(int); +static int replace_cmd(void); +static char *tmp_path(void); + +static void usage(const char *msg) { fprintf(stderr, "%s: usage error: %s\n", ProgramName, msg); fprintf(stderr, "usage:\t%s [-u user] file\n", ProgramName); fprintf(stderr, "\t%s [-u user] [ -e | -l | -r ]\n", ProgramName); @@ -87,10 +85,9 @@ usage(const char *msg) { exit(ERROR_EXIT); } -int -main(int argc, char *argv[]) { +int main(int argc, char *argv[]) { int exitstatus; - + Pid = getpid(); ProgramName = argv[0]; MailCmd[0] = '\0'; @@ -101,12 +98,12 @@ main(int argc, char *argv[]) { #if defined(BSD) setlinebuf(stderr); #endif - char *n="-"; /*set the n string to - so we have a valid string to use*/ - /*should we desire to make changes to behavior later.*/ - if(argv[1] == NULL){ /* change behavior to allow crontab to take stdin with no '-'*/ - argv[1] =n; + char *n = "-"; /*set the n string to - so we have a valid string to use */ + /*should we desire to make changes to behavior later. */ + if (argv[1] == NULL) { /* change behavior to allow crontab to take stdin with no '-' */ + argv[1] = n; } - parse_args(argc, argv); /* sets many globals, opens a file */ + parse_args(argc, argv); /* sets many globals, opens a file */ set_cron_cwd(); if (!allowed(RealUser, CRON_ALLOW, CRON_DENY)) { fprintf(stderr, @@ -149,11 +146,9 @@ main(int argc, char *argv[]) { } cron_close_pam(); exit(exitstatus); - /*NOTREACHED*/ -} + /*NOTREACHED*/} -static void -parse_args(int argc, char *argv[]) { +static void parse_args(int argc, char *argv[]) { int argch; if (!(pw = getpwuid(getuid()))) { @@ -181,16 +176,14 @@ parse_args(int argc, char *argv[]) { #endif case 'u': if (MY_UID(pw) != ROOT_UID) { - fprintf(stderr, - "must be privileged to use -u\n"); + fprintf(stderr, "must be privileged to use -u\n"); exit(ERROR_EXIT); } - - if( crontab_security_access() != 0 ) - { - fprintf(stderr, - "Access denied by SELinux, must be privileged to use -u\n"); - exit(ERROR_EXIT); + + if (crontab_security_access() != 0) { + fprintf(stderr, + "Access denied by SELinux, must be privileged to use -u\n"); + exit(ERROR_EXIT); } if (!(pw = getpwnam(optarg))) { @@ -218,18 +211,16 @@ parse_args(int argc, char *argv[]) { Option = opt_edit; break; case 'i': - PromptOnDelete = 1; + PromptOnDelete = 1; break; #ifdef WITH_SELINUX - case 's': - if ( getprevcon( (security_context_t*)&(selinux_context) ) ) - { - fprintf(stderr, - "Cannot obtain SELinux process context\n"); + case 's': + if (getprevcon((security_context_t *) & (selinux_context))) { + fprintf(stderr, "Cannot obtain SELinux process context\n"); exit(ERROR_EXIT); } break; -#endif +#endif default: usage("unrecognized option"); } @@ -240,13 +231,15 @@ parse_args(int argc, char *argv[]) { if (Option != opt_unknown) { if (argv[optind] != NULL) usage("no arguments permitted after this option"); - } else { + } + else { if (argv[optind] != NULL) { Option = opt_replace; if (strlen(argv[optind]) >= sizeof Filename) usage("filename too long"); - (void) strcpy (Filename, argv[optind]); - } else + (void) strcpy(Filename, argv[optind]); + } + else usage("file name must be specified for replace"); } @@ -282,11 +275,10 @@ parse_args(int argc, char *argv[]) { } Debug(DMISC, ("user=%s, file=%s, option=%s\n", - User, Filename, Options[(int)Option])) + User, Filename, Options[(int) Option])) } -static void -list_cmd(void) { +static void list_cmd(void) { char n[MAX_FNAME]; FILE *f; int ch; @@ -307,21 +299,20 @@ list_cmd(void) { /* file is open. copy to stdout, close. */ Set_LineNum(1) - while (EOF != (ch = get_char(f))) + while (EOF != (ch = get_char(f))) putchar(ch); fclose(f); } -static void -delete_cmd(void) { - char n[MAX_FNAME]=""; - if( PromptOnDelete == 1 ) - { - printf("crontab: really delete %s's crontab? ", User); - fflush(stdout); - if( (fgets(n, MAX_FNAME-1, stdin)==0L) - ||((n[0] != 'Y') && (n[0] != 'y')) - ) exit(0); +static void delete_cmd(void) { + char n[MAX_FNAME] = ""; + if (PromptOnDelete == 1) { + printf("crontab: really delete %s's crontab? ", User); + fflush(stdout); + if ((fgets(n, MAX_FNAME - 1, stdin) == 0L) + || ((n[0] != 'Y') && (n[0] != 'y')) + ) + exit(0); } log_it(RealUser, Pid, "DELETE", User, 0); @@ -339,31 +330,28 @@ delete_cmd(void) { poke_daemon(); } -static void -check_error(const char *msg) { +static void check_error(const char *msg) { CheckErrorCount++; - fprintf(stderr, "\"%s\":%d: %s\n", Filename, LineNumber-1, msg); + fprintf(stderr, "\"%s\":%d: %s\n", Filename, LineNumber - 1, msg); } -static char * -tmp_path() { - char *tmpdir; +static char *tmp_path() { + char *tmpdir; - tmpdir = getenv("TMPDIR"); - return tmpdir ? tmpdir : "/tmp"; + tmpdir = getenv("TMPDIR"); + return tmpdir ? tmpdir : "/tmp"; } -static void -edit_cmd(void) { +static void edit_cmd(void) { char n[MAX_FNAME], q[MAX_TEMPSTR], *editor; FILE *f; - int ch='\0', t; + int ch = '\0', t; struct stat statbuf; struct utimbuf utimebuf; WAIT_T waiter; PID_T pid, xpid; int uid; - + log_it(RealUser, Pid, "BEGIN EDIT", User, 0); if (!glue_strings(n, sizeof n, SPOOL_DIR, User, '/')) { fprintf(stderr, "path too long\n"); @@ -374,8 +362,7 @@ edit_cmd(void) { perror(n); exit(ERROR_EXIT); } - fprintf(stderr, "no crontab for %s - using an empty one\n", - User); + fprintf(stderr, "no crontab for %s - using an empty one\n", User); if (!(f = fopen(_PATH_DEVNULL, "r"))) { perror(_PATH_DEVNULL); exit(ERROR_EXIT); @@ -383,12 +370,12 @@ edit_cmd(void) { } /* Turn off signals. */ - (void)signal(SIGHUP, SIG_IGN); - (void)signal(SIGINT, SIG_IGN); - (void)signal(SIGQUIT, SIG_IGN); + (void) signal(SIGHUP, SIG_IGN); + (void) signal(SIGINT, SIG_IGN); + (void) signal(SIGQUIT, SIG_IGN); if (!glue_strings(Filename, sizeof Filename, tmp_path(), - "crontab.XXXXXXXXXX", '/')) { + "crontab.XXXXXXXXXX", '/')) { fprintf(stderr, "path too long\n"); goto fatal; } @@ -399,46 +386,42 @@ edit_cmd(void) { goto fatal; } - setreuid(uid,0); + setreuid(uid, 0); if (!(NewCrontab = fdopen(t, "r+"))) { perror("fdopen"); goto fatal; } Set_LineNum(1) - /* - * NHEADER_LINES processing removed for clarity - * (NHEADER_LINES == 0 in all Red Hat crontabs) - */ - - /* copy the rest of the crontab (if any) to the temp file. - */ - if (EOF != ch) + /* + * NHEADER_LINES processing removed for clarity + * (NHEADER_LINES == 0 in all Red Hat crontabs) + */ + /* copy the rest of the crontab (if any) to the temp file. + */ + if (EOF != ch) while (EOF != (ch = get_char(f))) putc(ch, NewCrontab); #ifdef WITH_SELINUX - if ( selinux_context ) - { - context_t ccon = NULL; - const char *level = NULL; - - if (!(ccon = context_new(selinux_context))) - { - fprintf(stderr, "context_new failed\n"); - goto fatal; - } - - if (!(level = context_range_get(ccon))) - { - fprintf(stderr, "context_range failed\n"); - goto fatal; - } - - fprintf(NewCrontab,"MLS_LEVEL=%s\n", level); - context_free(ccon); + if (selinux_context) { + context_t ccon = NULL; + const char *level = NULL; + + if (!(ccon = context_new(selinux_context))) { + fprintf(stderr, "context_new failed\n"); + goto fatal; + } + + if (!(level = context_range_get(ccon))) { + fprintf(stderr, "context_range failed\n"); + goto fatal; + } + + fprintf(NewCrontab, "MLS_LEVEL=%s\n", level); + context_free(ccon); freecon(selinux_context); - selinux_context = NULL; + selinux_context = NULL; } #endif @@ -451,18 +434,18 @@ edit_cmd(void) { utimebuf.actime = 0; utimebuf.modtime = 0; utime(Filename, &utimebuf); - again: + again: rewind(NewCrontab); if (ferror(NewCrontab)) { fprintf(stderr, "%s: error while writing new crontab to %s\n", ProgramName, Filename); - fatal: + fatal: unlink(Filename); exit(ERROR_EXIT); } if (((editor = getenv("VISUAL")) == NULL || *editor == '\0') && - ((editor = getenv("EDITOR")) == NULL || *editor == '\0')) { + ((editor = getenv("EDITOR")) == NULL || *editor == '\0')) { editor = EDITOR; } @@ -489,15 +472,13 @@ edit_cmd(void) { exit(ERROR_EXIT); } if (!glue_strings(q, sizeof q, editor, Filename, ' ')) { - fprintf(stderr, "%s: editor command line too long\n", - ProgramName); + fprintf(stderr, "%s: editor command line too long\n", ProgramName); exit(ERROR_EXIT); } - execlp(_PATH_BSHELL, _PATH_BSHELL, "-c", q, (char *)0); + execlp(_PATH_BSHELL, _PATH_BSHELL, "-c", q, (char *) 0); perror(editor); exit(ERROR_EXIT); - /*NOTREACHED*/ - default: + /*NOTREACHED*/ default: /* parent */ break; } @@ -507,28 +488,33 @@ edit_cmd(void) { xpid = waitpid(pid, &waiter, 0); if (xpid == -1) { if (errno != EINTR) - fprintf(stderr, "%s: waitpid() failed waiting for PID %ld from \"%s\": %s\n", - ProgramName, (long)pid, editor, strerror(errno)); - } else if (xpid != pid) { + fprintf(stderr, + "%s: waitpid() failed waiting for PID %ld from \"%s\": %s\n", + ProgramName, (long) pid, editor, strerror(errno)); + } + else if (xpid != pid) { fprintf(stderr, "%s: wrong PID (%ld != %ld) from \"%s\"\n", - ProgramName, (long)xpid, (long)pid, editor); + ProgramName, (long) xpid, (long) pid, editor); goto fatal; - } else if (WIFEXITED(waiter) && WEXITSTATUS(waiter)) { + } + else if (WIFEXITED(waiter) && WEXITSTATUS(waiter)) { fprintf(stderr, "%s: \"%s\" exited with status %d\n", ProgramName, editor, WEXITSTATUS(waiter)); goto fatal; - } else if (WIFSIGNALED(waiter)) { + } + else if (WIFSIGNALED(waiter)) { fprintf(stderr, "%s: \"%s\" killed; signal %d (%score dumped)\n", ProgramName, editor, WTERMSIG(waiter), - WCOREDUMP(waiter) ?"" :"no "); + WCOREDUMP(waiter) ? "" : "no "); goto fatal; - } else + } + else break; } - (void)signal(SIGHUP, SIG_DFL); - (void)signal(SIGINT, SIG_DFL); - (void)signal(SIGQUIT, SIG_DFL); + (void) signal(SIGHUP, SIG_DFL); + (void) signal(SIGINT, SIG_DFL); + (void) signal(SIGQUIT, SIG_DFL); /* lstat doesn't make any harm, because * the file is stat'ed only when crontab is touched @@ -538,37 +524,33 @@ edit_cmd(void) { goto fatal; } - if ( !S_ISREG(statbuf.st_mode) ) - { - fprintf(stderr, "%s: illegal crontab\n", - ProgramName); - goto remove; + if (!S_ISREG(statbuf.st_mode)) { + fprintf(stderr, "%s: illegal crontab\n", ProgramName); + goto remove; } if (statbuf.st_mtime == 0) { - fprintf(stderr, "%s: no changes made to crontab\n", - ProgramName); + fprintf(stderr, "%s: no changes made to crontab\n", ProgramName); goto remove; } fprintf(stderr, "%s: installing new crontab\n", ProgramName); - fclose(NewCrontab); + fclose(NewCrontab); if (swap_uids() < OK) { - perror("swapping uids"); - goto remove; + perror("swapping uids"); + goto remove; } if (!(NewCrontab = fopen(Filename, "r+"))) { - perror("cannot read new crontab"); - goto remove; + perror("cannot read new crontab"); + goto remove; } if (swap_uids_back() < OK) { - perror("swapping uids back"); - exit(ERROR_EXIT); + perror("swapping uids back"); + exit(ERROR_EXIT); } - if( NewCrontab == 0L ) - { - perror("fopen"); - goto fatal; + if (NewCrontab == 0L) { + perror("fopen"); + goto fatal; } switch (replace_cmd()) { case 0: @@ -578,8 +560,8 @@ edit_cmd(void) { printf("Do you want to retry the same edit? "); fflush(stdout); q[0] = '\0'; - if( fgets(q, sizeof q, stdin) == 0L ) - continue; + if (fgets(q, sizeof q, stdin) == 0L) + continue; switch (q[0]) { case 'y': case 'Y': @@ -591,20 +573,18 @@ edit_cmd(void) { fprintf(stderr, "Enter Y or N\n"); } } - /*NOTREACHED*/ - case -2: - abandon: - fprintf(stderr, "%s: edits left in %s\n", - ProgramName, Filename); + /*NOTREACHED*/ case -2: + abandon: + fprintf(stderr, "%s: edits left in %s\n", ProgramName, Filename); goto done; default: fprintf(stderr, "%s: panic: bad switch() in replace_cmd()\n", ProgramName); goto fatal; } - remove: + remove: unlink(Filename); - done: + done: log_it(RealUser, Pid, "END EDIT", User, 0); } @@ -612,8 +592,7 @@ edit_cmd(void) { * -1 on syntax error * -2 on install error */ -static int -replace_cmd(void) { +static int replace_cmd(void) { char n[MAX_FNAME], envstr[MAX_ENVSTR]; FILE *tmp; int ch, eof, fd; @@ -628,7 +607,7 @@ replace_cmd(void) { } if (!glue_strings(TempFilename, sizeof TempFilename, SPOOL_DIR, - "tmp.XXXXXXXXXX", '/')) { + "tmp.XXXXXXXXXX", '/')) { TempFilename[0] = '\0'; fprintf(stderr, "path too long\n"); return (-2); @@ -656,25 +635,25 @@ replace_cmd(void) { *fprintf(tmp, "# (Cron version %s)\n", CRON_VERSION); */ #ifdef WITH_SELINUX - if ( selinux_context ) - fprintf(tmp,"SELINUX_ROLE_TYPE=%s\n", selinux_context); + if (selinux_context) + fprintf(tmp, "SELINUX_ROLE_TYPE=%s\n", selinux_context); #endif /* copy the crontab to the tmp */ rewind(NewCrontab); Set_LineNum(1) - while (EOF != (ch = get_char(NewCrontab))) + while (EOF != (ch = get_char(NewCrontab))) putc(ch, tmp); - if( ftruncate(fileno(tmp), ftell(tmp)) == -1 ) - { - fprintf(stderr, "%s: error while writing new crontab to %s\n", - ProgramName, TempFilename); - fclose(tmp); - error = -2; - goto done; - } - fflush(tmp); rewind(tmp); + if (ftruncate(fileno(tmp), ftell(tmp)) == -1) { + fprintf(stderr, "%s: error while writing new crontab to %s\n", + ProgramName, TempFilename); + fclose(tmp); + error = -2; + goto done; + } + fflush(tmp); + rewind(tmp); if (ferror(tmp)) { fprintf(stderr, "%s: error while writing new crontab to %s\n", ProgramName, TempFilename); @@ -688,10 +667,11 @@ replace_cmd(void) { /* BUG: was reporting errors after the EOF if there were any errors * in the file proper -- kludged it by stopping after first error. - * vix 31mar87 + * vix 31mar87 */ Set_LineNum(1 - NHEADER_LINES) - CheckErrorCount = 0; eof = FALSE; + CheckErrorCount = 0; + eof = FALSE; while (!CheckErrorCount && !eof) { switch (load_env(envstr, tmp)) { case ERR: @@ -719,7 +699,7 @@ replace_cmd(void) { goto done; } - file_owner = (getgid() == getegid()) ? ROOT_UID : pw->pw_uid; + file_owner = (getgid() == getegid())? ROOT_UID : pw->pw_uid; #ifdef HAS_FCHOWN if (fchown(fileno(tmp), file_owner, -1) < OK) { @@ -760,7 +740,7 @@ replace_cmd(void) { poke_daemon(); -done: + done: (void) signal(SIGHUP, SIG_DFL); (void) signal(SIGINT, SIG_DFL); (void) signal(SIGQUIT, SIG_DFL); @@ -771,8 +751,7 @@ done: return (error); } -static void -poke_daemon(void) { +static void poke_daemon(void) { if (utime(SPOOL_DIR, NULL) < OK) { fprintf(stderr, "crontab: can't update mtime on spooldir\n"); perror(SPOOL_DIR); @@ -780,8 +759,7 @@ poke_daemon(void) { } } -static void -die(int x) { +static void die(int x) { if (TempFilename[0]) (void) unlink(TempFilename); _exit(ERROR_EXIT); diff --git a/src/database.c b/src/database.c index 8281654..a517d07 100644 --- a/src/database.c +++ b/src/database.c @@ -32,64 +32,65 @@ /* reasonable guess as to size of 1024 events */ #define BUF_LEN (1024 * (EVENT_SIZE + 16)) -static void overwrite_database(cron_db *, cron_db *); +static void overwrite_database(cron_db *, cron_db *); -static void process_crontab(const char *, const char *, - const char *, - cron_db *, cron_db *); +static void process_crontab(const char *, const char *, + const char *, cron_db *, cron_db *); -static int not_a_crontab( DIR_T *dp ); +static int not_a_crontab(DIR_T * dp); /* return 1 if we should skip this file */ -static void max_mtime( char *dir_name, struct stat *max_st ); +static void max_mtime(char *dir_name, struct stat *max_st); /* record max mtime of any file under dir_name in max_st */ static int check_open(const char *tabname, const char *fname, const char *uname, - struct passwd *pw, time_t *mtime) { + struct passwd *pw, time_t * mtime) { struct stat statbuf; int crontab_fd; pid_t pid = getpid(); - if ((crontab_fd = open(tabname, O_RDONLY|O_NONBLOCK|O_NOFOLLOW, 0)) == -1) { + if ((crontab_fd = + open(tabname, O_RDONLY | O_NONBLOCK | O_NOFOLLOW, 0)) == -1) { log_it(uname, pid, "CAN'T OPEN", tabname, errno); - return(-1); + return (-1); } if (fstat(crontab_fd, &statbuf) < OK) { log_it(uname, pid, "STAT FAILED", tabname, errno); close(crontab_fd); - return(-1); + return (-1); } *mtime = statbuf.st_mtime; if (PermitAnyCrontab == 0) { if (!S_ISREG(statbuf.st_mode)) { log_it(uname, pid, "NOT REGULAR", tabname, 0); close(crontab_fd); - return(-1); + return (-1); } if ((statbuf.st_mode & 07533) != 0400) { log_it(uname, pid, "BAD FILE MODE", tabname, 0); close(crontab_fd); - return(-1); + return (-1); } if (statbuf.st_uid != ROOT_UID && (pw == NULL || - statbuf.st_uid != pw->pw_uid || strcmp(uname, pw->pw_name) != 0)) { + statbuf.st_uid != pw->pw_uid || + strcmp(uname, pw->pw_name) != 0)) { log_it(uname, pid, "WRONG FILE OWNER", tabname, 0); close(crontab_fd); - return(-1); + return (-1); } if (pw && statbuf.st_nlink != 1) { log_it(uname, pid, "BAD LINK COUNT", tabname, 0); close(crontab_fd); - return(-1); + return (-1); } } - return(crontab_fd); + return (crontab_fd); } static void process_crontab(const char *uname, const char *fname, const char *tabname, - cron_db *new_db, cron_db *old_db) { + cron_db * new_db, cron_db * old_db) { struct passwd *pw = NULL; int crontab_fd = -1; user *u; @@ -98,21 +99,22 @@ process_crontab(const char *uname, const char *fname, const char *tabname, if (fname == NULL) { /* must be set to something for logging purposes. - */ + */ fname = "*system*"; - } else if ((pw = getpwnam(uname)) == NULL) { + } + else if ((pw = getpwnam(uname)) == NULL) { /* file doesn't have a user in passwd file. - */ + */ log_it(uname, getpid(), "ORPHAN", "no passwd entry", 0); goto next_crontab; } - + if ((crontab_fd = check_open(tabname, fname, uname, pw, &mtime)) == -1) goto next_crontab; Debug(DLOAD, ("\t%s:", fname)) - u = find_user(old_db, fname, crond_crontab ? tabname : NULL ); /* find user in old_db */ + u = find_user(old_db, fname, crond_crontab ? tabname : NULL); /* find user in old_db */ if (u != NULL) { /* if crontab has not changed since we last read it @@ -120,7 +122,7 @@ process_crontab(const char *uname, const char *fname, const char *tabname, */ if (u->mtime == mtime) { Debug(DLOAD, (" [no change, using old data]")) - unlink_user(old_db, u); + unlink_user(old_db, u); link_user(new_db, u); goto next_crontab; } @@ -133,7 +135,7 @@ process_crontab(const char *uname, const char *fname, const char *tabname, * we finish with the crontab... */ Debug(DLOAD, (" [delete old data]")) - unlink_user(old_db, u); + unlink_user(old_db, u); free_user(u); log_it(fname, getpid(), "RELOAD", tabname, 0); } @@ -147,13 +149,12 @@ process_crontab(const char *uname, const char *fname, const char *tabname, next_crontab: if (crontab_fd != -1) { Debug(DLOAD, (" [done]\n")) - close(crontab_fd); + close(crontab_fd); } } #if defined WITH_INOTIFY -void -check_inotify_database(cron_db *old_db) { +void check_inotify_database(cron_db * old_db) { cron_db new_db; DIR_T *dp; DIR *dir; @@ -178,7 +179,8 @@ check_inotify_database(cron_db *old_db) { else if (FD_ISSET(old_db->ifd, &rfds)) { new_db.head = new_db.tail = NULL; new_db.ifd = old_db->ifd; - while ((retval=read(old_db->ifd, buf, sizeof(buf))) == -1 && errno == EINTR); + while ((retval = read(old_db->ifd, buf, sizeof (buf))) == -1 && + errno == EINTR) ; if (retval == 0) { /* this should not happen as the buffer is large enough */ @@ -192,7 +194,7 @@ check_inotify_database(cron_db *old_db) { */ (void) exit(ERROR_EXIT); } - + /* we must reinstate the watches here - TODO reinstate only watches * which get IN_IGNORED event */ @@ -204,14 +206,16 @@ check_inotify_database(cron_db *old_db) { if (!(dir = opendir(SYS_CROND_DIR))) { log_it("CRON", pid, "OPENDIR FAILED", SYS_CROND_DIR, errno); - } else { + } + else { while (NULL != (dp = readdir(dir))) { - char tabname[MAXNAMLEN+1]; + char tabname[MAXNAMLEN + 1]; if (not_a_crontab(dp)) continue; - if (!glue_strings(tabname, sizeof tabname, SYS_CROND_DIR, dp->d_name, '/')) + if (!glue_strings(tabname, sizeof tabname, SYS_CROND_DIR, + dp->d_name, '/')) continue; process_crontab("root", NULL, tabname, &new_db, old_db); } @@ -220,16 +224,18 @@ check_inotify_database(cron_db *old_db) { if (!(dir = opendir(SPOOL_DIR))) { log_it("CRON", pid, "OPENDIR FAILED", SPOOL_DIR, errno); - } else { + } + else { while (NULL != (dp = readdir(dir))) { - char fname[MAXNAMLEN+1], tabname[MAXNAMLEN+1]; + char fname[MAXNAMLEN + 1], tabname[MAXNAMLEN + 1]; if (not_a_crontab(dp)) continue; strncpy(fname, dp->d_name, MAXNAMLEN); - if (!glue_strings(tabname, sizeof tabname, SPOOL_DIR, dp->d_name, '/')) + if (!glue_strings(tabname, sizeof tabname, SPOOL_DIR, + dp->d_name, '/')) continue; process_crontab(fname, fname, tabname, &new_db, old_db); } @@ -252,53 +258,53 @@ check_inotify_database(cron_db *old_db) { } #endif -static void -overwrite_database(cron_db *old_db, cron_db *new_db) { +static void overwrite_database(cron_db * old_db, cron_db * new_db) { user *u, *nu; /* whatever's left in the old database is now junk. - */ + */ Debug(DLOAD, ("unlinking old database:\n")) - for (u = old_db->head; u != NULL; u = nu) { + for (u = old_db->head; u != NULL; u = nu) { Debug(DLOAD, ("\t%s\n", u->name)) - nu = u->next; + nu = u->next; unlink_user(old_db, u); free_user(u); } /* overwrite the database control block with the new one. - */ + */ *old_db = *new_db; } -int -load_database(cron_db *old_db) { +int load_database(cron_db * old_db) { struct stat statbuf, syscron_stat, crond_stat; cron_db new_db; DIR_T *dp; DIR *dir; pid_t pid = getpid(); - Debug(DLOAD, ("[%ld] load_database()\n", (long)pid)) + Debug(DLOAD, ("[%ld] load_database()\n", (long) pid)) - /* before we start loading any data, do a stat on SPOOL_DIR - * so that if anything changes as of this moment (i.e., before we've - * cached any of the database), we'll see the changes next time. - */ - if (stat(SPOOL_DIR, &statbuf) < OK) { + /* before we start loading any data, do a stat on SPOOL_DIR + * so that if anything changes as of this moment (i.e., before we've + * cached any of the database), we'll see the changes next time. + */ + if (stat(SPOOL_DIR, &statbuf) < OK) { log_it("CRON", pid, "STAT FAILED", SPOOL_DIR, errno); statbuf.st_mtime = 0; - } else { + } + else { /* As pointed out in Red Hat bugzilla 198019, with modern Linux it * is possible to modify a file without modifying the mtime of the * containing directory. Hence, we must check the mtime of each file: - */ + */ max_mtime(SPOOL_DIR, &statbuf); } if (stat(SYS_CROND_DIR, &crond_stat) < OK) { log_it("CRON", pid, "STAT FAILED", SYS_CROND_DIR, errno); crond_stat.st_mtime = 0; - } else { + } + else { max_mtime(SYS_CROND_DIR, &crond_stat); } @@ -315,11 +321,11 @@ load_database(cron_db *old_db) { * time this function is called. */ if (old_db->mtime == TMAX(crond_stat.st_mtime, - TMAX(statbuf.st_mtime, syscron_stat.st_mtime)) - ){ + TMAX(statbuf.st_mtime, syscron_stat.st_mtime)) + ) { Debug(DLOAD, ("[%ld] spool dir mtime unch, no load needed.\n", - (long)pid)) - return 0; + (long) pid)) + return 0; } /* something's different. make a new database, moving unchanged @@ -328,7 +334,7 @@ load_database(cron_db *old_db) { * we're done is chaff -- crontabs that disappeared. */ new_db.mtime = TMAX(crond_stat.st_mtime, - TMAX(statbuf.st_mtime, syscron_stat.st_mtime)); + TMAX(statbuf.st_mtime, syscron_stat.st_mtime)); new_db.head = new_db.tail = NULL; #if defined WITH_INOTIFY new_db.ifd = old_db->ifd; @@ -339,14 +345,16 @@ load_database(cron_db *old_db) { if (!(dir = opendir(SYS_CROND_DIR))) { log_it("CRON", pid, "OPENDIR FAILED", SYS_CROND_DIR, errno); - } else { + } + else { while (NULL != (dp = readdir(dir))) { - char tabname[MAXNAMLEN+1]; + char tabname[MAXNAMLEN + 1]; - if ( not_a_crontab( dp ) ) + if (not_a_crontab(dp)) continue; - if (!glue_strings(tabname, sizeof tabname, SYS_CROND_DIR, dp->d_name, '/')) + if (!glue_strings(tabname, sizeof tabname, SYS_CROND_DIR, + dp->d_name, '/')) continue; /* XXX log? */ process_crontab("root", NULL, tabname, &new_db, old_db); @@ -361,11 +369,12 @@ load_database(cron_db *old_db) { if (!(dir = opendir(SPOOL_DIR))) { log_it("CRON", pid, "OPENDIR FAILED", SPOOL_DIR, errno); - } else { + } + else { while (NULL != (dp = readdir(dir))) { - char fname[MAXNAMLEN+1], tabname[MAXNAMLEN+1]; + char fname[MAXNAMLEN + 1], tabname[MAXNAMLEN + 1]; - if ( not_a_crontab( dp ) ) + if (not_a_crontab(dp)) continue; strncpy(fname, dp->d_name, MAXNAMLEN); @@ -386,11 +395,10 @@ load_database(cron_db *old_db) { overwrite_database(old_db, &new_db); Debug(DLOAD, ("load_database is done\n")) - return 1; + return 1; } -void -link_user(cron_db *db, user *u) { +void link_user(cron_db * db, user * u) { if (db->head == NULL) db->head = u; if (db->tail) @@ -400,8 +408,7 @@ link_user(cron_db *db, user *u) { db->tail = u; } -void -unlink_user(cron_db *db, user *u) { +void unlink_user(cron_db * db, user * u) { if (u->prev == NULL) db->head = u->next; else @@ -413,21 +420,20 @@ unlink_user(cron_db *db, user *u) { u->next->prev = u->prev; } -user * -find_user(cron_db *db, const char *name, const char *tabname) { +user *find_user(cron_db * db, const char *name, const char *tabname) { user *u; - for (u = db->head; u != NULL; u = u->next) - if ( (strcmp(u->name, name) == 0) - &&( (tabname == NULL) - || ( strcmp(tabname, u->tabname) == 0 ) - ) - ) break; + for (u = db->head; u != NULL; u = u->next) + if ((strcmp(u->name, name) == 0) + && ((tabname == NULL) + || (strcmp(tabname, u->tabname) == 0) + ) + ) + break; return (u); } -static int not_a_crontab( DIR_T *dp ) -{ +static int not_a_crontab(DIR_T * dp) { int len; /* avoid file names beginning with ".". this is good @@ -436,33 +442,32 @@ static int not_a_crontab( DIR_T *dp ) * hidden files in here anyway */ if (dp->d_name[0] == '.') - return(1); + return (1); /* ignore files starting with # and ending with ~ */ if (dp->d_name[0] == '#') - return(1); + return (1); len = strlen(dp->d_name); if (len >= MAXNAMLEN) - return(1); /* XXX log? */ + return (1); /* XXX log? */ if ((len > 0) && (dp->d_name[len - 1] == '~')) - return(1); + return (1); if ((len > 8) && (strncmp(dp->d_name + len - 8, ".rpmsave", 8) == 0)) - return(1); + return (1); if ((len > 8) && (strncmp(dp->d_name + len - 8, ".rpmorig", 8) == 0)) - return(1); + return (1); if ((len > 7) && (strncmp(dp->d_name + len - 7, ".rpmnew", 7) == 0)) - return(1); + return (1); - return(0); + return (0); } -static void max_mtime( char *dir_name, struct stat *max_st ) -{ - DIR * dir; +static void max_mtime(char *dir_name, struct stat *max_st) { + DIR *dir; DIR_T *dp; struct stat st; @@ -471,21 +476,20 @@ static void max_mtime( char *dir_name, struct stat *max_st ) return; } - while (NULL != (dp = readdir(dir))) - { - char tabname[MAXNAMLEN+1]; + while (NULL != (dp = readdir(dir))) { + char tabname[MAXNAMLEN + 1]; - if ( not_a_crontab ( dp ) ) + if (not_a_crontab(dp)) continue; if (!glue_strings(tabname, sizeof tabname, dir_name, dp->d_name, '/')) continue; /* XXX log? */ - if ( stat( tabname, &st ) < OK ) - continue; /* XXX log? */ - - if ( st.st_mtime > max_st->st_mtime ) - max_st->st_mtime = st.st_mtime; + if (stat(tabname, &st) < OK) + continue; /* XXX log? */ + + if (st.st_mtime > max_st->st_mtime) + max_st->st_mtime = st.st_mtime; } closedir(dir); } diff --git a/src/do_command.c b/src/do_command.c index c7af7af..6a73410 100644 --- a/src/do_command.c +++ b/src/do_command.c @@ -21,25 +21,24 @@ #include -static void child_process(entry *, user *); -static int safe_p(const char *, const char *); +static void child_process(entry *, user *); +static int safe_p(const char *, const char *); -void -do_command(entry *e, user *u) { +void do_command(entry * e, user * u) { pid_t pid = getpid(); Debug(DPROC, ("[%ld] do_command(%s, (%s,%ld,%ld))\n", - (long)pid, e->cmd, u->name, - (long)e->pwd->pw_uid, (long)e->pwd->pw_gid)) - - /* fork to become asynchronous -- parent process is done immediately, - * and continues to run the normal cron code, which means return to - * tick(). the child and grandchild don't leave this function, alive. - * - * vfork() is unsuitable, since we have much to do, and the parent - * needs to be able to run off and fork other processes. - */ - switch (fork()) { + (long) pid, e->cmd, u->name, + (long) e->pwd->pw_uid, (long) e->pwd->pw_gid)) + + /* fork to become asynchronous -- parent process is done immediately, + * and continues to run the normal cron code, which means return to + * tick(). the child and grandchild don't leave this function, alive. + * + * vfork() is unsuitable, since we have much to do, and the parent + * needs to be able to run off and fork other processes. + */ + switch (fork()) { case -1: log_it("CRON", pid, "can't fork", "do_command", errno); break; @@ -47,43 +46,39 @@ do_command(entry *e, user *u) { /* child process */ acquire_daemonlock(1); child_process(e, u); - Debug(DPROC, ("[%ld] child process done, exiting\n", - (long)getpid())) - _exit(OK_EXIT); + Debug(DPROC, ("[%ld] child process done, exiting\n", (long) getpid())) + _exit(OK_EXIT); break; default: /* parent process */ break; } - Debug(DPROC, ("[%ld] main process returning to work\n",(long)pid)) + Debug(DPROC, ("[%ld] main process returning to work\n", (long) pid)) } -static void -child_process(entry *e, user *u) { +static void child_process(entry * e, user * u) { int stdin_pipe[2], stdout_pipe[2]; char *input_data, *usernm, *mailto, *mailfrom; - int children = 0; - char **jobenv=0L; - pid_t pid = getpid(); + int children = 0; + char **jobenv = 0L; + pid_t pid = getpid(); /* Set up the Red Hat security context for both mail/minder and job processes: - */ - if ( cron_set_job_security_context( e, u, &jobenv ) != 0 ) - { - //syslog(LOG_INFO, "CRON (%s) ERROR: cannot set security context", e->pwd->pw_name); - exit(ERROR_EXIT); + */ + if (cron_set_job_security_context(e, u, &jobenv) != 0) { + //syslog(LOG_INFO, "CRON (%s) ERROR: cannot set security context", e->pwd->pw_name); + exit(ERROR_EXIT); } - Debug(DPROC, ("[%ld] child_process('%s')\n", (long)getpid(), e->cmd)) - + Debug(DPROC, ("[%ld] child_process('%s')\n", (long) getpid(), e->cmd)) #ifdef CAPITALIZE_FOR_PS - /* mark ourselves as different to PS command watchers by upshifting - * our program name. This has no effect on some kernels. - */ - /*local*/{ - char *pch; + /* mark ourselves as different to PS command watchers by upshifting + * our program name. This has no effect on some kernels. + */ + /*local */ { + char *pch; - for (pch = ProgramName; *pch; pch++) + for (pch = ProgramName; *pch; pch++) *pch = MkUpper(*pch); } #endif /* CAPITALIZE_FOR_PS */ @@ -103,18 +98,16 @@ child_process(entry *e, user *u) { /* create some pipes to talk to our future child */ - if( pipe(stdin_pipe) == -1 ) /* child's stdin */ - { - log_it("CRON", pid, "pipe() failed", "stdin_pipe", errno); - return; + if (pipe(stdin_pipe) == -1) { /* child's stdin */ + log_it("CRON", pid, "pipe() failed", "stdin_pipe", errno); + return; + } + + if (pipe(stdout_pipe) == -1) { /* child's stdout */ + log_it("CRON", pid, "pipe() failed", "stdout_pipe", errno); + return; } - if( pipe(stdout_pipe) == -1 ) /* child's stdout */ - { - log_it("CRON", pid, "pipe() failed", "stdout_pipe", errno); - return; - } - /* since we are a forked process, we can diddle the command string * we were passed -- nobody else is going to use it again, right? * @@ -124,14 +117,13 @@ child_process(entry *e, user *u) { * from it. Subsequent %'s will be transformed into newlines, * but that happens later. */ - /*local*/{ + /*local */ { int escaped = FALSE; int ch; char *p; for (input_data = p = e->cmd; - (ch = *input_data) != '\0'; - input_data++, p++) { + (ch = *input_data) != '\0'; input_data++, p++) { if (p != input_data) *p = ch; if (escaped) { @@ -160,12 +152,10 @@ child_process(entry *e, user *u) { log_it("CRON", pid, "can't fork", "child_process", errno); cron_close_pam(); exit(ERROR_EXIT); - /*NOTREACHED*/ - case 0: - Debug(DPROC, ("[%ld] grandchild process fork()'ed\n", - (long)getpid())) + /*NOTREACHED*/ case 0: + Debug(DPROC, ("[%ld] grandchild process fork()'ed\n", (long) getpid())) - if (cron_change_user_permanently(e->pwd) < 0) + if (cron_change_user_permanently(e->pwd) < 0) _exit(ERROR_EXIT); /* write a log message. we've waited this long to do it @@ -174,7 +164,7 @@ child_process(entry *e, user *u) { * PID is part of the log message. */ if ((e->flags & DONT_LOG) == 0) { - char *x = mkprints((u_char *)e->cmd, strlen(e->cmd)); + char *x = mkprints((u_char *) e->cmd, strlen(e->cmd)); log_it(usernm, getpid(), "CMD", x, 0); free(x); @@ -222,19 +212,16 @@ child_process(entry *e, user *u) { * Exec the command. */ { - char *shell = env_get("SHELL", jobenv); + char *shell = env_get("SHELL", jobenv); -# if DEBUGGING +#if DEBUGGING if (DebugFlags & DTEST) { - fprintf(stderr, - "debug DTEST is on, not exec'ing command.\n"); - fprintf(stderr, - "\tcmd='%s' shell='%s'\n", e->cmd, shell); + fprintf(stderr, "debug DTEST is on, not exec'ing command.\n"); + fprintf(stderr, "\tcmd='%s' shell='%s'\n", e->cmd, shell); _exit(OK_EXIT); } -# endif /*DEBUGGING*/ - - execle(shell, shell, "-c", e->cmd, (char *)0, jobenv); +#endif /*DEBUGGING*/ + execle(shell, shell, "-c", e->cmd, (char *) 0, jobenv); fprintf(stderr, "execl: couldn't exec `%s'\n", shell); perror("execl"); _exit(ERROR_EXIT); @@ -252,12 +239,12 @@ child_process(entry *e, user *u) { * the user's command. */ - Debug(DPROC, ("[%ld] child continues, closing pipes\n",(long)getpid())) + Debug(DPROC, ("[%ld] child continues, closing pipes\n", (long) getpid())) - /* close the ends of the pipe that will only be referenced in the - * grandchild process... - */ - close(stdin_pipe[READ_PIPE]); + /* close the ends of the pipe that will only be referenced in the + * grandchild process... + */ + close(stdin_pipe[READ_PIPE]); close(stdout_pipe[WRITE_PIPE]); /* @@ -278,24 +265,25 @@ child_process(entry *e, user *u) { int ch; Debug(DPROC, ("[%ld] child2 sending data to grandchild\n", - (long)getpid())) + (long) getpid())) - /* close the pipe we don't use, since we inherited it and - * are part of its reference count now. - */ - close(stdout_pipe[READ_PIPE]); + /* close the pipe we don't use, since we inherited it and + * are part of its reference count now. + */ + close(stdout_pipe[READ_PIPE]); if (cron_change_user_permanently(e->pwd) < 0) _exit(ERROR_EXIT); /* translation: - * \% -> % - * % -> \n - * \x -> \x for all x != % + * \% -> % + * % -> \n + * \x -> \x for all x != % */ while ((ch = *input_data++) != '\0') { if (escaped) { if (ch != '%') putc('\\', out); - } else { + } + else { if (ch == '%') ch = '\n'; } @@ -316,8 +304,8 @@ child_process(entry *e, user *u) { fclose(out); Debug(DPROC, ("[%ld] child2 done sending to grandchild\n", - (long)getpid())) - exit(0); + (long) getpid())) + exit(0); } /* close the pipe to the grandkiddie's stdin, since its wicked uncle @@ -335,25 +323,25 @@ child_process(entry *e, user *u) { */ Debug(DPROC, ("[%ld] child reading output from grandchild\n", - (long)getpid())) + (long) getpid())) - /*local*/{ - FILE *in = fdopen(stdout_pipe[READ_PIPE], "r"); - int ch = getc(in); + /*local */ { + FILE *in = fdopen(stdout_pipe[READ_PIPE], "r"); + int ch = getc(in); if (ch != EOF) { - FILE *mail=0L; - int bytes = 1; - int status = 0; + FILE *mail = 0L; + int bytes = 1; + int status = 0; - Debug(DPROC|DEXT, - ("[%ld] got data (%x:%c) from grandchild\n", - (long)getpid(), ch, ch)) + Debug(DPROC | DEXT, + ("[%ld] got data (%x:%c) from grandchild\n", + (long) getpid(), ch, ch)) - /* get name of recipient. this is MAILTO if set to a - * valid local username; USER otherwise. - */ - if (mailto) { + /* get name of recipient. this is MAILTO if set to a + * valid local username; USER otherwise. + */ + if (mailto) { /* MAILTO was present in the environment */ if (!*mailto) { @@ -361,7 +349,8 @@ child_process(entry *e, user *u) { */ mailto = NULL; } - } else { + } + else { /* MAILTO not present, set to USER. */ mailto = usernm; @@ -371,7 +360,7 @@ child_process(entry *e, user *u) { * root otherwise. */ if (!mailfrom || !*mailfrom || !safe_p(usernm, mailfrom)) { - mailfrom = calloc(5, sizeof(char)); + mailfrom = calloc(5, sizeof (char)); strcpy(mailfrom, "root"); } @@ -380,73 +369,69 @@ child_process(entry *e, user *u) { * up the mail command and subjects and stuff... */ - if (mailto - &&( (ValidateMailRcpts==0) || safe_p(usernm, mailto) ) - /* Why validate the mail recipient name ? All mailers do this anyway... JVD */ - ) - { - char **env; - char mailcmd[MAX_COMMAND]; - char hostname[MAXHOSTNAMELEN]; - char *content_type = env_get("CONTENT_TYPE",jobenv), - *content_transfer_encoding = env_get("CONTENT_TRANSFER_ENCODING",jobenv); + if (mailto && ((ValidateMailRcpts == 0) || safe_p(usernm, mailto)) + /* Why validate the mail recipient name ? All mailers do this anyway... JVD */ + ) { + char **env; + char mailcmd[MAX_COMMAND]; + char hostname[MAXHOSTNAMELEN]; + char *content_type = env_get("CONTENT_TYPE", jobenv), + *content_transfer_encoding = + env_get("CONTENT_TRANSFER_ENCODING", jobenv); gethostname(hostname, MAXHOSTNAMELEN); - - if ( MailCmd[0] == '\0' ) - { + + if (MailCmd[0] == '\0') { if (strlens(MAILFMT, MAILARG, mailfrom, NULL) + 1 - >= sizeof mailcmd) { + >= sizeof mailcmd) { fprintf(stderr, "mailcmd too long\n"); (void) _exit(ERROR_EXIT); } - (void)sprintf(mailcmd, MAILFMT, MAILARG, mailfrom); - }else - { - strncpy( mailcmd, MailCmd, MAX_COMMAND ); + (void) sprintf(mailcmd, MAILFMT, MAILARG, mailfrom); + } + else { + strncpy(mailcmd, MailCmd, MAX_COMMAND); } if (!(mail = cron_popen(mailcmd, "w", e->pwd))) { perror(mailcmd); (void) _exit(ERROR_EXIT); } - + fprintf(mail, "From: %s (Cron Daemon)\n", mailfrom); fprintf(mail, "To: %s\n", mailto); fprintf(mail, "Subject: Cron <%s@%s> %s\n", - usernm, first_word(hostname, "."), - e->cmd); + usernm, first_word(hostname, "."), e->cmd); #ifdef MAIL_DATE - fprintf(mail, "Date: %s\n", - arpadate(&StartTime)); -#endif /*MAIL_DATE*/ - if ( content_type == 0L ) - { + fprintf(mail, "Date: %s\n", arpadate(&StartTime)); +#endif /*MAIL_DATE */ + if (content_type == 0L) { fprintf(mail, "Content-Type: text/plain; charset=%s\n", - cron_default_mail_charset - ); - }else - { /* user specified Content-Type header. - * disallow new-lines for security reasons - * (else users could specify arbitrary mail headers!) - */ - char *nl=content_type; - size_t ctlen = strlen(content_type); - while( (*nl != '\0') - && ((nl=strchr(nl,'\n')) != 0L) - && (nl < (content_type+ctlen)) - ) *nl = ' '; - fprintf(mail,"Content-Type: %s\n", content_type); + cron_default_mail_charset); } - if ( content_transfer_encoding != 0L ) - { - char *nl=content_transfer_encoding; + else { /* user specified Content-Type header. + * disallow new-lines for security reasons + * (else users could specify arbitrary mail headers!) + */ + char *nl = content_type; + size_t ctlen = strlen(content_type); + while ((*nl != '\0') + && ((nl = strchr(nl, '\n')) != 0L) + && (nl < (content_type + ctlen)) + ) + *nl = ' '; + fprintf(mail, "Content-Type: %s\n", content_type); + } + if (content_transfer_encoding != 0L) { + char *nl = content_transfer_encoding; size_t ctlen = strlen(content_transfer_encoding); - while( (*nl != '\0') - && ((nl=strchr(nl,'\n')) != 0L) - && (nl < (content_transfer_encoding+ctlen)) - ) *nl = ' '; - fprintf(mail,"Content-Transfer-Encoding: %s\n", content_transfer_encoding); + while ((*nl != '\0') + && ((nl = strchr(nl, '\n')) != 0L) + && (nl < (content_transfer_encoding + ctlen)) + ) + *nl = ' '; + fprintf(mail, "Content-Transfer-Encoding: %s\n", + content_transfer_encoding); } /* The Auto-Submitted header is @@ -454,9 +439,8 @@ child_process(entry *e, user *u) { */ fprintf(mail, "Auto-Submitted: auto-generated\n"); - for (env = jobenv; *env; env++) - fprintf(mail, "X-Cron-Env: <%s>\n", - *env); + for (env = jobenv; *env; env++) + fprintf(mail, "X-Cron-Env: <%s>\n", *env); fprintf(mail, "\n"); /* this was the first char from the pipe @@ -480,15 +464,14 @@ child_process(entry *e, user *u) { */ if (mailto) { - Debug(DPROC, ("[%ld] closing pipe to mail\n", - (long)getpid())) - /* Note: the pclose will probably see - * the termination of the grandchild - * in addition to the mail process, since - * it (the grandchild) is likely to exit - * after closing its stdout. - */ - status = cron_pclose(mail); + Debug(DPROC, ("[%ld] closing pipe to mail\n", (long) getpid())) + /* Note: the pclose will probably see + * the termination of the grandchild + * in addition to the mail process, since + * it (the grandchild) is likely to exit + * after closing its stdout. + */ + status = cron_pclose(mail); } /* if there was output and we could not mail it, @@ -499,18 +482,16 @@ child_process(entry *e, user *u) { char buf[MAX_TEMPSTR]; sprintf(buf, - "mailed %d byte%s of output but got status 0x%04x\n", - bytes, (bytes==1)?"":"s", - status); + "mailed %d byte%s of output but got status 0x%04x\n", + bytes, (bytes == 1) ? "" : "s", status); log_it(usernm, getpid(), "MAIL", buf, 0); } - } /*if data from grandchild*/ + } /*if data from grandchild */ - Debug(DPROC, ("[%ld] got EOF from grandchild\n", - (long)getpid())) + Debug(DPROC, ("[%ld] got EOF from grandchild\n", (long) getpid())) - fclose(in); /* also closes stdout_pipe[READ_PIPE] */ + fclose(in); /* also closes stdout_pipe[READ_PIPE] */ } /* wait for children to die. @@ -520,34 +501,32 @@ child_process(entry *e, user *u) { PID_T pid; Debug(DPROC, ("[%ld] waiting for grandchild #%d to finish\n", - (long)getpid(), children)) - while ((pid = wait(&waiter)) < OK && errno == EINTR) - ; + (long) getpid(), children)) + while ((pid = wait(&waiter)) < OK && errno == EINTR) ; if (pid < OK) { Debug(DPROC, - ("[%ld] no more grandchildren--mail written?\n", - (long)getpid())) - break; + ("[%ld] no more grandchildren--mail written?\n", + (long) getpid())) + break; } Debug(DPROC, ("[%ld] grandchild #%ld finished, status=%04x", - (long)getpid(), (long)pid, WEXITSTATUS(waiter))) - if (WIFSIGNALED(waiter) && WCOREDUMP(waiter)) + (long) getpid(), (long) pid, WEXITSTATUS(waiter))) + if (WIFSIGNALED(waiter) && WCOREDUMP(waiter)) Debug(DPROC, (", dumped core")) - Debug(DPROC, ("\n")) + Debug(DPROC, ("\n")) + } + cron_close_pam(); + env_free(jobenv); } - cron_close_pam(); - env_free(jobenv); -} -static int -safe_p(const char *usernm, const char *s) { - static const char safe_delim[] = "@!:%-.,_+"; /* conservative! */ +static int safe_p(const char *usernm, const char *s) { + static const char safe_delim[] = "@!:%-.,_+"; /* conservative! */ const char *t; int ch, first; for (t = s, first = 1; (ch = *t++) != '\0'; first = 0) { if (isascii(ch) && isprint(ch) && - (isalnum(ch) || (!first && strchr(safe_delim, ch)))) + (isalnum(ch) || (!first && strchr(safe_delim, ch)))) continue; log_it(usernm, getpid(), "UNSAFE", s, 0); return (FALSE); diff --git a/src/entry.c b/src/entry.c index 08e45f3..97cafc8 100644 --- a/src/entry.c +++ b/src/entry.c @@ -28,33 +28,31 @@ #include -typedef enum ecode { +typedef enum ecode { e_none, e_minute, e_hour, e_dom, e_month, e_dow, e_cmd, e_timespec, e_username, e_option, e_memory } ecode_e; -static const char *ecodes[] = - { - "no error", - "bad minute", - "bad hour", - "bad day-of-month", - "bad month", - "bad day-of-week", - "bad command", - "bad time specifier", - "bad username", - "bad option", - "out of memory" - }; - -static int get_list(bitstr_t *, int, int, const char *[], int, FILE *), - get_range(bitstr_t *, int, int, const char *[], int, FILE *), - get_number(int *, int, const char *[], int, FILE *, const char *), - set_element(bitstr_t *, int, int, int); - -void -free_entry(entry *e) { +static const char *ecodes[] = { + "no error", + "bad minute", + "bad hour", + "bad day-of-month", + "bad month", + "bad day-of-week", + "bad command", + "bad time specifier", + "bad username", + "bad option", + "out of memory" +}; + +static int get_list(bitstr_t *, int, int, const char *[], int, FILE *), +get_range(bitstr_t *, int, int, const char *[], int, FILE *), +get_number(int *, int, const char *[], int, FILE *, const char *), +set_element(bitstr_t *, int, int, int); + +void free_entry(entry * e) { free(e->cmd); free(e->pwd); env_free(e->envp); @@ -64,8 +62,8 @@ free_entry(entry *e) { /* return NULL if eof or syntax error occurs; * otherwise return a pointer to a new entry. */ -entry * -load_entry(FILE *file, void (*error_func)(), struct passwd *pw, char **envp) { +entry *load_entry(FILE * file, void (*error_func) (), struct passwd *pw, + char **envp) { /* this function reads one crontab entry -- the next -- from a file. * it skips any leading blank lines, ignores comments, and returns * NULL if for any reason the entry can't be read and parsed. @@ -74,12 +72,12 @@ load_entry(FILE *file, void (*error_func)(), struct passwd *pw, char **envp) { * * syntax: * user crontab: - * minutes hours doms months dows cmd\n + * minutes hours doms months dows cmd\n * system crontab (/etc/crontab): - * minutes hours doms months dows USERNAME cmd\n + * minutes hours doms months dows USERNAME cmd\n */ - ecode_e ecode = e_none; + ecode_e ecode = e_none; entry *e; int ch; char cmd[MAX_COMMAND]; @@ -88,7 +86,7 @@ load_entry(FILE *file, void (*error_func)(), struct passwd *pw, char **envp) { Debug(DPARS, ("load_entry()...about to eat comments\n")) - skip_comments(file); + skip_comments(file); ch = get_char(file); if (ch == EOF) @@ -99,7 +97,7 @@ load_entry(FILE *file, void (*error_func)(), struct passwd *pw, char **envp) { * of a list of minutes. */ - e = (entry *) calloc(sizeof(entry), sizeof(char)); + e = (entry *) calloc(sizeof (entry), sizeof (char)); if (ch == '@') { /* all of these should be flagged and load-limited; i.e., @@ -117,41 +115,47 @@ load_entry(FILE *file, void (*error_func)(), struct passwd *pw, char **envp) { ch = get_string(cmd, MAX_COMMAND, file, " \t\n"); if (!strcmp("reboot", cmd)) { e->flags |= WHEN_REBOOT; - } else if (!strcmp("yearly", cmd) || !strcmp("annually", cmd)){ + } + else if (!strcmp("yearly", cmd) || !strcmp("annually", cmd)) { bit_set(e->minute, 0); bit_set(e->hour, 0); bit_set(e->dom, 0); bit_set(e->month, 0); - bit_nset(e->dow, 0, (LAST_DOW-FIRST_DOW+1)); + bit_nset(e->dow, 0, (LAST_DOW - FIRST_DOW + 1)); e->flags |= DOW_STAR; - } else if (!strcmp("monthly", cmd)) { + } + else if (!strcmp("monthly", cmd)) { bit_set(e->minute, 0); bit_set(e->hour, 0); bit_set(e->dom, 0); - bit_nset(e->month, 0, (LAST_MONTH-FIRST_MONTH+1)); - bit_nset(e->dow, 0, (LAST_DOW-FIRST_DOW+1)); + bit_nset(e->month, 0, (LAST_MONTH - FIRST_MONTH + 1)); + bit_nset(e->dow, 0, (LAST_DOW - FIRST_DOW + 1)); e->flags |= DOW_STAR; - } else if (!strcmp("weekly", cmd)) { + } + else if (!strcmp("weekly", cmd)) { bit_set(e->minute, 0); bit_set(e->hour, 0); - bit_nset(e->dom, 0, (LAST_DOM-FIRST_DOM+1)); - bit_nset(e->month, 0, (LAST_MONTH-FIRST_MONTH+1)); + bit_nset(e->dom, 0, (LAST_DOM - FIRST_DOM + 1)); + bit_nset(e->month, 0, (LAST_MONTH - FIRST_MONTH + 1)); bit_set(e->dow, 0); e->flags |= DOW_STAR; - } else if (!strcmp("daily", cmd) || !strcmp("midnight", cmd)) { + } + else if (!strcmp("daily", cmd) || !strcmp("midnight", cmd)) { bit_set(e->minute, 0); bit_set(e->hour, 0); - bit_nset(e->dom, 0, (LAST_DOM-FIRST_DOM+1)); - bit_nset(e->month, 0, (LAST_MONTH-FIRST_MONTH+1)); - bit_nset(e->dow, 0, (LAST_DOW-FIRST_DOW+1)); - } else if (!strcmp("hourly", cmd)) { + bit_nset(e->dom, 0, (LAST_DOM - FIRST_DOM + 1)); + bit_nset(e->month, 0, (LAST_MONTH - FIRST_MONTH + 1)); + bit_nset(e->dow, 0, (LAST_DOW - FIRST_DOW + 1)); + } + else if (!strcmp("hourly", cmd)) { bit_set(e->minute, 0); - bit_nset(e->hour, 0, (LAST_HOUR-FIRST_HOUR+1)); - bit_nset(e->dom, 0, (LAST_DOM-FIRST_DOM+1)); - bit_nset(e->month, 0, (LAST_MONTH-FIRST_MONTH+1)); - bit_nset(e->dow, 0, (LAST_DOW-FIRST_DOW+1)); + bit_nset(e->hour, 0, (LAST_HOUR - FIRST_HOUR + 1)); + bit_nset(e->dom, 0, (LAST_DOM - FIRST_DOM + 1)); + bit_nset(e->month, 0, (LAST_MONTH - FIRST_MONTH + 1)); + bit_nset(e->dow, 0, (LAST_DOW - FIRST_DOW + 1)); e->flags |= HR_STAR; - } else { + } + else { ecode = e_timespec; goto eof; } @@ -163,13 +167,13 @@ load_entry(FILE *file, void (*error_func)(), struct passwd *pw, char **envp) { ecode = e_cmd; goto eof; } - } else { + } + else { Debug(DPARS, ("load_entry()...about to parse numerics\n")) - if (ch == '*') + if (ch == '*') e->flags |= MIN_STAR; - ch = get_list(e->minute, FIRST_MINUTE, LAST_MINUTE, - PPC_NULL, ch, file); + ch = get_list(e->minute, FIRST_MINUTE, LAST_MINUTE, PPC_NULL, ch, file); if (ch == EOF) { ecode = e_minute; goto eof; @@ -180,8 +184,7 @@ load_entry(FILE *file, void (*error_func)(), struct passwd *pw, char **envp) { if (ch == '*') e->flags |= HR_STAR; - ch = get_list(e->hour, FIRST_HOUR, LAST_HOUR, - PPC_NULL, ch, file); + ch = get_list(e->hour, FIRST_HOUR, LAST_HOUR, PPC_NULL, ch, file); if (ch == EOF) { ecode = e_hour; goto eof; @@ -192,8 +195,7 @@ load_entry(FILE *file, void (*error_func)(), struct passwd *pw, char **envp) { if (ch == '*') e->flags |= DOM_STAR; - ch = get_list(e->dom, FIRST_DOM, LAST_DOM, - PPC_NULL, ch, file); + ch = get_list(e->dom, FIRST_DOM, LAST_DOM, PPC_NULL, ch, file); if (ch == EOF) { ecode = e_dom; goto eof; @@ -202,8 +204,7 @@ load_entry(FILE *file, void (*error_func)(), struct passwd *pw, char **envp) { /* month */ - ch = get_list(e->month, FIRST_MONTH, LAST_MONTH, - MonthNames, ch, file); + ch = get_list(e->month, FIRST_MONTH, LAST_MONTH, MonthNames, ch, file); if (ch == EOF) { ecode = e_month; goto eof; @@ -214,8 +215,7 @@ load_entry(FILE *file, void (*error_func)(), struct passwd *pw, char **envp) { if (ch == '*') e->flags |= DOW_STAR; - ch = get_list(e->dow, FIRST_DOW, LAST_DOW, - DowNames, ch, file); + ch = get_list(e->dow, FIRST_DOW, LAST_DOW, DowNames, ch, file); if (ch == EOF) { ecode = e_dow; goto eof; @@ -238,13 +238,13 @@ load_entry(FILE *file, void (*error_func)(), struct passwd *pw, char **envp) { unget_char(ch, file); if (!pw) { - char *username = cmd; /* temp buffer */ + char *username = cmd; /* temp buffer */ Debug(DPARS, ("load_entry()...about to parse username\n")) - ch = get_string(username, MAX_COMMAND, file, " \t\n"); + ch = get_string(username, MAX_COMMAND, file, " \t\n"); - Debug(DPARS, ("load_entry()...got %s\n",username)) - if (ch == EOF || ch == '\n' || ch == '*') { + Debug(DPARS, ("load_entry()...got %s\n", username)) + if (ch == EOF || ch == '\n' || ch == '*') { ecode = e_cmd; goto eof; } @@ -255,7 +255,7 @@ load_entry(FILE *file, void (*error_func)(), struct passwd *pw, char **envp) { goto eof; } Debug(DPARS, ("load_entry()...uid %ld, gid %ld\n", - (long)pw->pw_uid, (long)pw->pw_gid)) + (long) pw->pw_uid, (long) pw->pw_gid)) } if ((e->pwd = pw_dup(pw)) == NULL) { @@ -272,78 +272,78 @@ load_entry(FILE *file, void (*error_func)(), struct passwd *pw, char **envp) { goto eof; } if (!env_get("SHELL", e->envp)) { - if (glue_strings(envstr, sizeof envstr, "SHELL", - _PATH_BSHELL, '=')) { + if (glue_strings(envstr, sizeof envstr, "SHELL", _PATH_BSHELL, '=')) { if ((tenvp = env_set(e->envp, envstr)) == NULL) { ecode = e_memory; goto eof; } e->envp = tenvp; - } else + } + else log_it("CRON", getpid(), "error", "can't set SHELL", 0); } if (!env_get("HOME", e->envp)) { - if (glue_strings(envstr, sizeof envstr, "HOME", - pw->pw_dir, '=')) { + if (glue_strings(envstr, sizeof envstr, "HOME", pw->pw_dir, '=')) { if ((tenvp = env_set(e->envp, envstr)) == NULL) { ecode = e_memory; goto eof; } e->envp = tenvp; - } else + } + else log_it("CRON", getpid(), "error", "can't set HOME", 0); } #ifndef LOGIN_CAP /* If login.conf is in used we will get the default PATH later. */ if (!env_get("PATH", e->envp)) { - if (glue_strings(envstr, sizeof envstr, "PATH", - _PATH_DEFPATH, '=')) { + if (glue_strings(envstr, sizeof envstr, "PATH", _PATH_DEFPATH, '=')) { if ((tenvp = env_set(e->envp, envstr)) == NULL) { ecode = e_memory; goto eof; } e->envp = tenvp; - } else + } + else log_it("CRON", getpid(), "error", "can't set PATH", 0); } #endif /* LOGIN_CAP */ - if (glue_strings(envstr, sizeof envstr, "LOGNAME", - pw->pw_name, '=')) { + if (glue_strings(envstr, sizeof envstr, "LOGNAME", pw->pw_name, '=')) { if ((tenvp = env_set(e->envp, envstr)) == NULL) { ecode = e_memory; goto eof; } e->envp = tenvp; - } else + } + else log_it("CRON", getpid(), "error", "can't set LOGNAME", 0); #if defined(BSD) || defined(__linux) - if (glue_strings(envstr, sizeof envstr, "USER", - pw->pw_name, '=')) { + if (glue_strings(envstr, sizeof envstr, "USER", pw->pw_name, '=')) { if ((tenvp = env_set(e->envp, envstr)) == NULL) { ecode = e_memory; goto eof; } e->envp = tenvp; - } else + } + else log_it("CRON", getpid(), "error", "can't set USER", 0); #endif Debug(DPARS, ("load_entry()...about to parse command\n")) - /* If the first character of the command is '-' it is a cron option. - */ - while ((ch = get_char(file)) == '-') { + /* If the first character of the command is '-' it is a cron option. + */ + while ((ch = get_char(file)) == '-') { switch (ch = get_char(file)) { case 'q': e->flags |= DONT_LOG; Skip_Nonblanks(ch, file) - break; + break; default: ecode = e_option; goto eof; } Skip_Blanks(ch, file) - if (ch == EOF || ch == '\n') { + if (ch == EOF || ch == '\n') { ecode = e_cmd; goto eof; } @@ -353,7 +353,7 @@ load_entry(FILE *file, void (*error_func)(), struct passwd *pw, char **envp) { /* Everything up to the next \n or EOF is part of the command... * too bad we don't know in advance how long it will be, since we * need to malloc a string for it... so, we limit it to MAX_COMMAND. - */ + */ ch = get_string(cmd, MAX_COMMAND, file, "\n"); /* a file without a \n before the EOF is rude, so we'll complain... @@ -372,11 +372,11 @@ load_entry(FILE *file, void (*error_func)(), struct passwd *pw, char **envp) { Debug(DPARS, ("load_entry()...returning successfully\n")) - /* success, fini, return pointer to the entry we just created... - */ - return (e); + /* success, fini, return pointer to the entry we just created... + */ + return (e); - eof: + eof: if (e->envp) env_free(e->envp); if (e->pwd) @@ -387,14 +387,13 @@ load_entry(FILE *file, void (*error_func)(), struct passwd *pw, char **envp) { while (ch != '\n' && !feof(file)) ch = get_char(file); if (ecode != e_none && error_func) - (*error_func)(ecodes[(int)ecode]); + (*error_func) (ecodes[(int) ecode]); return (NULL); } static int -get_list(bitstr_t *bits, int low, int high, const char *names[], - int ch, FILE *file) -{ +get_list(bitstr_t * bits, int low, int high, const char *names[], + int ch, FILE * file) { int done; /* we know that we point to a non-blank character here; @@ -403,14 +402,13 @@ get_list(bitstr_t *bits, int low, int high, const char *names[], * assume the same thing. */ - Debug(DPARS|DEXT, ("get_list()...entered\n")) + Debug(DPARS | DEXT, ("get_list()...entered\n")) - /* list = range {"," range} - */ - - /* clear the bit string, since the default is 'off'. - */ - bit_nclear(bits, 0, (high-low+1)); + /* list = range {"," range} + */ + /* clear the bit string, since the default is 'off'. + */ + bit_nclear(bits, 0, (high - low + 1)); /* process all ranges */ @@ -427,26 +425,25 @@ get_list(bitstr_t *bits, int low, int high, const char *names[], /* exiting. skip to some blanks, then skip over the blanks. */ Skip_Nonblanks(ch, file) - Skip_Blanks(ch, file) + Skip_Blanks(ch, file) - Debug(DPARS|DEXT, ("get_list()...exiting w/ %02x\n", ch)) + Debug(DPARS | DEXT, ("get_list()...exiting w/ %02x\n", ch)) - return (ch); + return (ch); } static int -get_range(bitstr_t *bits, int low, int high, const char *names[], - int ch, FILE *file) -{ +get_range(bitstr_t * bits, int low, int high, const char *names[], + int ch, FILE * file) { /* range = number | number "-" number [ "/" number ] */ int i, num1, num2, num3; - Debug(DPARS|DEXT, ("get_range()...entering, exit won't show\n")) + Debug(DPARS | DEXT, ("get_range()...entering, exit won't show\n")) - if (ch == '*') { + if (ch == '*') { /* '*' means "first-last" but can still be modified by /step */ num1 = low; @@ -454,7 +451,8 @@ get_range(bitstr_t *bits, int low, int high, const char *names[], ch = get_char(file); if (ch == EOF) return (EOF); - } else { + } + else { ch = get_number(&num1, low, names, ch, file, ",- \t\n"); if (ch == EOF) return (EOF); @@ -467,7 +465,8 @@ get_range(bitstr_t *bits, int low, int high, const char *names[], return (EOF); } return (ch); - } else { + } + else { /* eat the dash */ ch = get_char(file); @@ -499,7 +498,8 @@ get_range(bitstr_t *bits, int low, int high, const char *names[], ch = get_number(&num3, 0, PPC_NULL, ch, file, ", \t\n"); if (ch == EOF || num3 == 0) return (EOF); - } else { + } + else { /* no step. default==1. */ num3 = 1; @@ -510,7 +510,7 @@ get_range(bitstr_t *bits, int low, int high, const char *names[], * proposed conceptually by bob@acornrc, syntactically * designed then implemented by paul vixie). */ - for (i = num1; i <= num2; i += num3) + for (i = num1; i <= num2; i += num3) if (EOF == set_element(bits, low, high, i)) { unget_char(ch, file); return (EOF); @@ -520,8 +520,8 @@ get_range(bitstr_t *bits, int low, int high, const char *names[], } static int -get_number(int *numptr, int low, const char *names[], int ch, FILE *file, - const char *terms) { +get_number(int *numptr, int low, const char *names[], int ch, FILE * file, + const char *terms) { char temp[MAX_TEMPSTR], *pc; int len, i; @@ -529,7 +529,7 @@ get_number(int *numptr, int low, const char *names[], int ch, FILE *file, len = 0; /* first look for a number */ - while (isdigit((unsigned char)ch)) { + while (isdigit((unsigned char) ch)) { if (++len >= MAX_TEMPSTR) goto bad; *pc++ = ch; @@ -546,7 +546,7 @@ get_number(int *numptr, int low, const char *names[], int ch, FILE *file, /* no numbers, look for a string if we have any */ if (names) { - while (isalpha((unsigned char)ch)) { + while (isalpha((unsigned char) ch)) { if (++len >= MAX_TEMPSTR) goto bad; *pc++ = ch; @@ -554,30 +554,28 @@ get_number(int *numptr, int low, const char *names[], int ch, FILE *file, } *pc = '\0'; if (len != 0 && strchr(terms, ch)) { - for (i = 0; names[i] != NULL; i++) { - Debug(DPARS|DEXT, - ("get_num, compare(%s,%s)\n", names[i], - temp)) - if (!strcasecmp(names[i], temp)) { - *numptr = i+low; + for (i = 0; names[i] != NULL; i++) { + Debug(DPARS | DEXT, + ("get_num, compare(%s,%s)\n", names[i], temp)) + if (!strcasecmp(names[i], temp)) { + *numptr = i + low; return (ch); } } } } -bad: + bad: unget_char(ch, file); return (EOF); } -static int -set_element(bitstr_t *bits, int low, int high, int number) { - Debug(DPARS|DEXT, ("set_element(?,%d,%d,%d)\n", low, high, number)) +static int set_element(bitstr_t * bits, int low, int high, int number) { + Debug(DPARS | DEXT, ("set_element(?,%d,%d,%d)\n", low, high, number)) - if (number < low || number > high) + if (number < low || number > high) return (EOF); - bit_set(bits, (number-low)); + bit_set(bits, (number - low)); return (OK); } diff --git a/src/env.c b/src/env.c index a3ee99d..390eb64 100644 --- a/src/env.c +++ b/src/env.c @@ -21,17 +21,15 @@ #include -char ** -env_init(void) { - char **p = (char **) malloc(sizeof(char **)); +char **env_init(void) { + char **p = (char **) malloc(sizeof (char **)); if (p != NULL) p[0] = NULL; return (p); } -void -env_free(char **envp) { +void env_free(char **envp) { char **p; for (p = envp; *p != NULL; p++) @@ -39,14 +37,13 @@ env_free(char **envp) { free(envp); } -char ** -env_copy(char **envp) { +char **env_copy(char **envp) { int count, i, save_errno; char **p; - for (count = 0; envp[count] != NULL; count++); + for (count = 0; envp[count] != NULL; count++) ; - p = (char **) malloc((count+1) * sizeof(char *)); /* 1 for the NULL */ + p = (char **) malloc((count + 1) * sizeof (char *)); /* 1 for the NULL */ if (p != NULL) { for (i = 0; i < count; i++) if ((p[i] = strdup(envp[i])) == NULL) { @@ -62,8 +59,7 @@ env_copy(char **envp) { return (p); } -char ** -env_set(char **envp, char *envstr) { +char **env_set(char **envp, char *envstr) { int count, found; char **p, *envtmp; @@ -98,34 +94,33 @@ env_set(char **envp, char *envstr) { if ((envtmp = strdup(envstr)) == NULL) return (NULL); p = (char **) realloc((void *) envp, - (size_t) ((count+1) * sizeof(char **))); + (size_t) ((count + 1) * sizeof (char **))); if (p == NULL) { free(envtmp); return (NULL); } - p[count] = p[count-1]; - p[count-1] = envtmp; + p[count] = p[count - 1]; + p[count - 1] = envtmp; return (p); } /* The following states are used by load_env(), traversed in order: */ enum env_state { - NAMEI, /* First char of NAME, may be quote */ - NAME, /* Subsequent chars of NAME */ - EQ1, /* After end of name, looking for '=' sign */ - EQ2, /* After '=', skipping whitespace */ - VALUEI, /* First char of VALUE, may be quote */ - VALUE, /* Subsequent chars of VALUE */ - FINI, /* All done, skipping trailing whitespace */ - ERROR, /* Error */ + NAMEI, /* First char of NAME, may be quote */ + NAME, /* Subsequent chars of NAME */ + EQ1, /* After end of name, looking for '=' sign */ + EQ2, /* After '=', skipping whitespace */ + VALUEI, /* First char of VALUE, may be quote */ + VALUE, /* Subsequent chars of VALUE */ + FINI, /* All done, skipping trailing whitespace */ + ERROR, /* Error */ }; /* return ERR = end of file * FALSE = not an env setting (file was repositioned) * TRUE = was an env setting */ -int -load_env(char *envstr, FILE *f) { +int load_env(char *envstr, FILE * f) { long filepos; int fileline; enum env_state state; @@ -140,7 +135,7 @@ load_env(char *envstr, FILE *f) { Debug(DPARS, ("load_env, read <%s>\n", envstr)) - bzero(name, sizeof name); + bzero(name, sizeof name); bzero(val, sizeof val); str = name; state = NAMEI; @@ -166,9 +161,10 @@ load_env(char *envstr, FILE *f) { state = ERROR; break; } - } else { + } + else { if (state == NAME) { - if (isspace((unsigned char)*c)) { + if (isspace((unsigned char) *c)) { c++; state++; break; @@ -187,8 +183,9 @@ load_env(char *envstr, FILE *f) { state++; str = val; quotechar = '\0'; - } else { - if (!isspace((unsigned char)*c)) + } + else { + if (!isspace((unsigned char) *c)) state = ERROR; } c++; @@ -196,7 +193,7 @@ load_env(char *envstr, FILE *f) { case EQ2: case FINI: - if (isspace((unsigned char)*c)) + if (isspace((unsigned char) *c)) c++; else state++; @@ -208,14 +205,14 @@ load_env(char *envstr, FILE *f) { } if (state != FINI && !(state == VALUE && !quotechar)) { Debug(DPARS, ("load_env, not an env var, state = %d\n", state)) - fseek(f, filepos, 0); + fseek(f, filepos, 0); Set_LineNum(fileline); return (FALSE); } if (state == VALUE) { /* End of unquoted value: trim trailing whitespace */ c = val + strlen(val); - while (c > val && isspace((unsigned char)c[-1])) + while (c > val && isspace((unsigned char) c[-1])) *(--c) = '\0'; } @@ -228,11 +225,10 @@ load_env(char *envstr, FILE *f) { if (!glue_strings(envstr, MAX_ENVSTR, name, val, '=')) return (FALSE); Debug(DPARS, ("load_env, <%s> <%s> -> <%s>\n", name, val, envstr)) - return (TRUE); + return (TRUE); } -char * -env_get(char *name, char **envp) { +char *env_get(char *name, char **envp) { int len = strlen(name); char *p, *q; @@ -240,7 +236,7 @@ env_get(char *name, char **envp) { if (!(q = strchr(p, '='))) continue; if ((q - p) == len && !strncmp(p, name, len)) - return (q+1); + return (q + 1); } return (NULL); } diff --git a/src/job.c b/src/job.c index 04f8ce1..5ea7d98 100644 --- a/src/job.c +++ b/src/job.c @@ -21,16 +21,15 @@ #include -typedef struct _job { - struct _job *next; - entry *e; - user *u; +typedef struct _job { + struct _job *next; + entry *e; + user *u; } job; -static job *jhead = NULL, *jtail = NULL; +static job *jhead = NULL, *jtail = NULL; -void -job_add(entry *e, user *u) { +void job_add(entry * e, user * u) { job *j; /* if already on queue, keep going */ @@ -39,7 +38,7 @@ job_add(entry *e, user *u) { return; /* build a job queue element */ - if ((j = (job *)malloc(sizeof(job))) == NULL) + if ((j = (job *) malloc(sizeof (job))) == NULL) return; j->next = NULL; j->e = e; @@ -53,8 +52,7 @@ job_add(entry *e, user *u) { jtail = j; } -int -job_runqueue(void) { +int job_runqueue(void) { job *j, *jn; int run = 0; diff --git a/src/misc.c b/src/misc.c index a7c966f..c9f3054 100644 --- a/src/misc.c +++ b/src/misc.c @@ -25,16 +25,16 @@ #include #ifdef WITH_AUDIT -#include +# include #endif -#ifdef HAVE_FCNTL_H /* fcntl(2) */ +#ifdef HAVE_FCNTL_H /* fcntl(2) */ # include #endif -#ifdef HAVE_UNISTD_H /* lockf(3) */ +#ifdef HAVE_UNISTD_H /* lockf(3) */ # include #endif -#ifdef HAVE_FLOCK /* flock(2) */ +#ifdef HAVE_FLOCK /* flock(2) */ # include #endif #include @@ -48,7 +48,7 @@ #endif #ifndef FACILITY -#define FACILITY LOG_CRON +# define FACILITY LOG_CRON #endif static int LogFD = ERR; @@ -58,17 +58,16 @@ static int syslog_open = FALSE; #endif #if defined(HAVE_FCNTL) && defined(F_SETLK) -static int trylock_file(int fd) -{ - struct flock fl; +static int trylock_file(int fd) { + struct flock fl; - memset(&fl, '\0', sizeof(fl)); - fl.l_type = F_WRLCK; - fl.l_whence = SEEK_SET; - fl.l_start = 0; - fl.l_len = 0; + memset(&fl, '\0', sizeof (fl)); + fl.l_type = F_WRLCK; + fl.l_whence = SEEK_SET; + fl.l_start = 0; + fl.l_len = 0; - return fcntl(fd, F_SETLK, &fl); + return fcntl(fd, F_SETLK, &fl); } #elif defined(HAVE_LOCKF) # define trylock_file(fd) lockf((fd), F_TLOCK, 0) @@ -85,8 +84,7 @@ static int trylock_file(int fd) */ int glue_strings(char *buffer, size_t buffer_size, const char *a, const char *b, - char separator) -{ + char separator) { char *buf; char *buf_end; @@ -95,7 +93,7 @@ glue_strings(char *buffer, size_t buffer_size, const char *a, const char *b, buf_end = buffer + buffer_size; buf = buffer; - for ( /* nothing */; buf < buf_end && *a != '\0'; buf++, a++ ) + for ( /* nothing */ ; buf < buf_end && *a != '\0'; buf++, a++) *buf = *a; if (buf == buf_end) return (0); @@ -103,7 +101,7 @@ glue_strings(char *buffer, size_t buffer_size, const char *a, const char *b, *buf++ = separator; if (buf == buf_end) return (0); - for ( /* nothing */; buf < buf_end && *b != '\0'; buf++, b++ ) + for ( /* nothing */ ; buf < buf_end && *b != '\0'; buf++, b++) *buf = *b; if (buf == buf_end) return (0); @@ -111,15 +109,14 @@ glue_strings(char *buffer, size_t buffer_size, const char *a, const char *b, return (1); } -int -strcmp_until(const char *left, const char *right, char until) { +int strcmp_until(const char *left, const char *right, char until) { while (*left && *left != until && *left == *right) { left++; right++; } - if ((*left=='\0' || *left == until) && - (*right=='\0' || *right == until)) { + if ((*left == '\0' || *left == until) && (*right == '\0' || + *right == until)) { return (0); } return (*left - *right); @@ -127,9 +124,8 @@ strcmp_until(const char *left, const char *right, char until) { /* strdtb(s) - delete trailing blanks in string 's' and return new length */ -int -strdtb(char *s) { - char *x = s; +int strdtb(char *s) { + char *x = s; /* scan forward to the null */ @@ -139,8 +135,9 @@ strdtb(char *s) { /* scan backward to either the first character before the string, * or the last non-blank in the string, whichever comes first. */ - do {x--;} - while (x >= s && isspace((unsigned char)*x)); + do { + x--; + } while (x >= s && isspace((unsigned char) *x)); /* one character beyond where we stopped above is where the null * goes. @@ -153,8 +150,7 @@ strdtb(char *s) { return (x - s); } -int -set_debug_flags(const char *flags) { +int set_debug_flags(const char *flags) { /* debug flags are of the form flag[,flag ...] * * if an error occurs, print a message to stdout and return FALSE. @@ -173,20 +169,16 @@ set_debug_flags(const char *flags) { DebugFlags = 0; while (*pc) { - const char **test; - int mask; + const char **test; + int mask; /* try to find debug flag name in our list. */ for (test = DebugFlagNames, mask = 1; - *test != NULL && strcmp_until(*test, pc, ','); - test++, mask <<= 1) - ; + *test != NULL && strcmp_until(*test, pc, ','); test++, mask <<= 1) ; if (!*test) { - fprintf(stderr, - "unrecognized debug flag <%s> <%s>\n", - flags, pc); + fprintf(stderr, "unrecognized debug flag <%s> <%s>\n", flags, pc); return (FALSE); } @@ -205,7 +197,7 @@ set_debug_flags(const char *flags) { fprintf(stderr, "debug flags enabled:"); - for (flag = 0; DebugFlagNames[flag]; flag++) + for (flag = 0; DebugFlagNames[flag]; flag++) if (DebugFlags & (1 << flag)) fprintf(stderr, " %s", DebugFlagNames[flag]); fprintf(stderr, "\n"); @@ -216,8 +208,7 @@ set_debug_flags(const char *flags) { #endif /* DEBUGGING */ } -void -set_cron_uid(void) { +void set_cron_uid(void) { #if defined(BSD) || defined(POSIX) if (seteuid(ROOT_UID) < OK) { perror("seteuid"); @@ -231,8 +222,7 @@ set_cron_uid(void) { #endif } -void -set_cron_cwd(void) { +void set_cron_cwd(void) { struct stat sb; struct group *grp = NULL; @@ -246,30 +236,30 @@ set_cron_cwd(void) { if (OK == mkdir(SPOOL_DIR, 0700)) { fprintf(stderr, "%s: created\n", SPOOL_DIR); stat(SPOOL_DIR, &sb); - } else { + } + else { fprintf(stderr, "%s: ", SPOOL_DIR); perror("mkdir"); exit(ERROR_EXIT); } } if (!S_ISDIR(sb.st_mode)) { - fprintf(stderr, "'%s' is not a directory, bailing out.\n", - SPOOL_DIR); + fprintf(stderr, "'%s' is not a directory, bailing out.\n", SPOOL_DIR); exit(ERROR_EXIT); } if (grp != NULL) { if (sb.st_gid != grp->gr_gid) - if( chown(SPOOL_DIR, -1, grp->gr_gid) == -1 ) - { - fprintf(stderr,"chdir %s failed: %s\n", SPOOL_DIR, strerror(errno)); - exit(ERROR_EXIT); - } + if (chown(SPOOL_DIR, -1, grp->gr_gid) == -1) { + fprintf(stderr, "chdir %s failed: %s\n", SPOOL_DIR, + strerror(errno)); + exit(ERROR_EXIT); + } if (sb.st_mode != 01730) - if( chmod(SPOOL_DIR, 01730) == -1 ) - { - fprintf(stderr,"chmod 01730 %s failed: %s\n", SPOOL_DIR, strerror(errno)); - exit(ERROR_EXIT); - } + if (chmod(SPOOL_DIR, 01730) == -1) { + fprintf(stderr, "chmod 01730 %s failed: %s\n", SPOOL_DIR, + strerror(errno)); + exit(ERROR_EXIT); + } } } @@ -280,13 +270,12 @@ set_cron_cwd(void) { * we maintain static storage of the file pointer so that we * can rewrite our PID into _PATH_CRON_PID after the fork. */ -void -acquire_daemonlock(int closeflag) { +void acquire_daemonlock(int closeflag) { static int fd = -1; - char buf[3*MAX_FNAME]; + char buf[3 * MAX_FNAME]; const char *pidfile; char *ep; - long otherpid=-1; + long otherpid = -1; ssize_t num, len; pid_t pid = getpid(); @@ -302,11 +291,11 @@ acquire_daemonlock(int closeflag) { if (fd == -1) { pidfile = _PATH_CRON_PID; /* Initial mode is 0600 to prevent flock() race/DoS. */ - if ((fd = open(pidfile, O_RDWR|O_CREAT, 0600)) == -1) { + if ((fd = open(pidfile, O_RDWR | O_CREAT, 0600)) == -1) { int save_errno = errno; - sprintf(buf, "can't open or create %s", - pidfile); - fprintf(stderr, "%s: %s: %s\n", ProgramName, buf, strerror(save_errno)); + sprintf(buf, "can't open or create %s", pidfile); + fprintf(stderr, "%s: %s: %s\n", ProgramName, buf, + strerror(save_errno)); log_it("CRON", pid, "DEATH", buf, save_errno); exit(ERROR_EXIT); } @@ -314,19 +303,19 @@ acquire_daemonlock(int closeflag) { if (trylock_file(fd) < OK) { int save_errno = errno; - bzero(buf, sizeof(buf)); - if ((num = read(fd, buf, sizeof(buf) - 1)) > 0 && - (otherpid = strtol(buf, &ep, 10)) > 0 && - ep != buf && *ep == '\n' && otherpid != LONG_MAX) { - snprintf(buf, sizeof(buf), - "can't lock %s, otherpid may be %ld", - pidfile, otherpid); - } else { - snprintf(buf, sizeof(buf), - "can't lock %s, otherpid unknown", - pidfile); + bzero(buf, sizeof (buf)); + if ((num = read(fd, buf, sizeof (buf) - 1)) > 0 && + (otherpid = strtol(buf, &ep, 10)) > 0 && + ep != buf && *ep == '\n' && otherpid != LONG_MAX) { + snprintf(buf, sizeof (buf), + "can't lock %s, otherpid may be %ld", pidfile, otherpid); + } + else { + snprintf(buf, sizeof (buf), + "can't lock %s, otherpid unknown", pidfile); } - fprintf(stderr, "%s: %s: %s\n", ProgramName, buf, strerror(save_errno)); + fprintf(stderr, "%s: %s: %s\n", ProgramName, buf, + strerror(save_errno)); log_it("CRON", pid, "DEATH", buf, save_errno); exit(ERROR_EXIT); } @@ -334,15 +323,14 @@ acquire_daemonlock(int closeflag) { (void) fcntl(fd, F_SETFD, 1); } - sprintf(buf, "%ld\n", (long)pid); - (void) lseek(fd, (off_t)0, SEEK_SET); - len = strlen(buf); - if( (num = write(fd, buf, len)) != len ) - log_it("CRON", pid, "ERROR", "write() failed", errno); - else - { - if( ftruncate(fd, num) == -1 ) - log_it("CRON", pid, "ERROR", "ftruncate() failed", errno); + sprintf(buf, "%ld\n", (long) pid); + (void) lseek(fd, (off_t) 0, SEEK_SET); + len = strlen(buf); + if ((num = write(fd, buf, len)) != len) + log_it("CRON", pid, "ERROR", "write() failed", errno); + else { + if (ftruncate(fd, num) == -1) + log_it("CRON", pid, "ERROR", "ftruncate() failed", errno); } /* abandon fd even though the file is open. we need to keep @@ -352,33 +340,30 @@ acquire_daemonlock(int closeflag) { /* get_char(file) : like getc() but increment LineNumber on newlines */ -int -get_char(FILE *file) { +int get_char(FILE * file) { int ch; ch = getc(file); if (ch == '\n') Set_LineNum(LineNumber + 1) - return (ch); + return (ch); } /* unget_char(ch, file) : like ungetc but do LineNumber processing */ -void -unget_char(int ch, FILE *file) { +void unget_char(int ch, FILE * file) { ungetc(ch, file); if (ch == '\n') Set_LineNum(LineNumber - 1) } /* get_string(str, max, file, termstr) : like fgets() but - * (1) has terminator string which should include \n - * (2) will always leave room for the null - * (3) uses get_char() so LineNumber will be accurate - * (4) returns EOF or terminating character, whichever + * (1) has terminator string which should include \n + * (2) will always leave room for the null + * (3) uses get_char() so LineNumber will be accurate + * (4) returns EOF or terminating character, whichever */ -int -get_string(char *string, int size, FILE *file, char *terms) { +int get_string(char *string, int size, FILE * file, char *terms) { int ch; while (EOF != (ch = get_char(file)) && !strchr(terms, ch)) { @@ -396,14 +381,12 @@ get_string(char *string, int size, FILE *file, char *terms) { /* skip_comments(file) : read past comment (if any) */ -void -skip_comments(FILE *file) { +void skip_comments(FILE * file) { int ch; while (EOF != (ch = get_char(file))) { /* ch is now the first character of a line. */ - while (ch == ' ' || ch == '\t') ch = get_char(file); @@ -435,9 +418,7 @@ skip_comments(FILE *file) { * return TRUE if one of the lines in file matches string exactly, * FALSE if no lines match, and error on error. */ -static int -in_file(const char *string, FILE *file, int error) -{ +static int in_file(const char *string, FILE * file, int error) { char line[MAX_TEMPSTR]; char *endp; @@ -463,32 +444,33 @@ in_file(const char *string, FILE *file, int error) * or (deny_file exists and user is NOT listed). * root is always allowed. */ -int -allowed(const char *username, const char *allow_file, const char *deny_file) { - FILE *fp; - int isallowed; - char buf[128]; - - if ( getuid() == 0 ) - return TRUE; +int allowed(const char *username, const char *allow_file, + const char *deny_file) { + FILE *fp; + int isallowed; + char buf[128]; + + if (getuid() == 0) + return TRUE; isallowed = FALSE; if ((fp = fopen(allow_file, "r")) != NULL) { isallowed = in_file(username, fp, FALSE); fclose(fp); - if( ( getuid() == 0 ) && (!isallowed) ) - { - snprintf(buf,sizeof(buf),"root used -u for user %s not in cron.allow",username); - log_it("crontab", getpid(), "warning", buf, 0); - isallowed = TRUE; + if ((getuid() == 0) && (!isallowed)) { + snprintf(buf, sizeof (buf), + "root used -u for user %s not in cron.allow", username); + log_it("crontab", getpid(), "warning", buf, 0); + isallowed = TRUE; } - } else if ((fp = fopen(deny_file, "r")) != NULL) { + } + else if ((fp = fopen(deny_file, "r")) != NULL) { isallowed = !in_file(username, fp, FALSE); fclose(fp); - if( ( getuid() == 0 ) && (!isallowed) ) - { - snprintf(buf,sizeof(buf),"root used -u for user %s in cron.deny",username); - log_it("crontab", getpid(), "warning", buf, 0); - isallowed = TRUE; + if ((getuid() == 0) && (!isallowed)) { + snprintf(buf, sizeof (buf), + "root used -u for user %s in cron.deny", username); + log_it("crontab", getpid(), "warning", buf, 0); + isallowed = TRUE; } } #ifdef WITH_AUDIT @@ -502,8 +484,8 @@ allowed(const char *username, const char *allow_file, const char *deny_file) { return (isallowed); } -void -log_it(const char *username, PID_T xpid, const char *event, const char *detail, int err) { +void log_it(const char *username, PID_T xpid, const char *event, + const char *detail, int err) { #if defined(LOG_FILE) || DEBUGGING PID_T pid = xpid; #endif @@ -515,26 +497,23 @@ log_it(const char *username, PID_T xpid, const char *event, const char *detail, #if defined(LOG_FILE) /* we assume that MAX_TEMPSTR will hold the date, time, &punctuation. */ - msg = malloc(msg_size = - ( strlen(username) - + strlen(event) - + strlen(detail) - + MAX_TEMPSTR - ) - ); - if (msg == NULL) - { /* damn, out of mem and we did not test that before... */ - fprintf(stderr, "%s: Run OUT OF MEMORY while %s\n", - ProgramName, __FUNCTION__); - return; + msg = malloc(msg_size = (strlen(username) + + strlen(event) + + strlen(detail) + + MAX_TEMPSTR) + ); + if (msg == NULL) { /* damn, out of mem and we did not test that before... */ + fprintf(stderr, "%s: Run OUT OF MEMORY while %s\n", + ProgramName, __FUNCTION__); + return; } if (LogFD < OK) { - LogFD = open(LOG_FILE, O_WRONLY|O_APPEND|O_CREAT, 0600); + LogFD = open(LOG_FILE, O_WRONLY | O_APPEND | O_CREAT, 0600); if (LogFD < OK) { - fprintf(stderr, "%s: can't open log file\n", - ProgramName); + fprintf(stderr, "%s: can't open log file\n", ProgramName); perror(LOG_FILE); - } else { + } + else { (void) fcntl(LogFD, F_SETFD, 1); } } @@ -543,12 +522,10 @@ log_it(const char *username, PID_T xpid, const char *event, const char *detail, * everything out in one chunk and this has to be atomically appended * to the log file. */ - snprintf(msg, msg_size, "%s (%02d/%02d-%02d:%02d:%02d-%d) %s (%s)%s%s\n", - username, - t->tm_mon+1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec, pid, - event, detail, - err != 0 ? ": " : "", - err != 0 ? strerror(err) : ""); + snprintf(msg, msg_size, + "%s (%02d/%02d-%02d:%02d:%02d-%d) %s (%s)%s%s\n", username, + t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec, pid, + event, detail, err != 0 ? ": " : "", err != 0 ? strerror(err) : ""); /* we have to run strlen() because sprintf() returns (char*) on old BSD */ @@ -560,7 +537,7 @@ log_it(const char *username, PID_T xpid, const char *event, const char *detail, } free(msg); -#endif /*LOG_FILE*/ +#endif /*LOG_FILE */ #if defined(SYSLOG) if (!syslog_open) { @@ -569,29 +546,25 @@ log_it(const char *username, PID_T xpid, const char *event, const char *detail, # else openlog(ProgramName, LOG_PID); # endif - syslog_open = TRUE; /* assume openlog success */ + syslog_open = TRUE; /* assume openlog success */ } syslog(err != 0 ? LOG_ERR : LOG_INFO, "(%s) %s (%s)%s%s", username, event, detail, - err != 0 ? ": " : "", - err != 0 ? strerror(err) : ""); - + err != 0 ? ": " : "", err != 0 ? strerror(err) : ""); -#endif /*SYSLOG*/ +#endif /*SYSLOG*/ #if DEBUGGING if (DebugFlags) { fprintf(stderr, "log_it: (%s %ld) %s (%s)%s%s\n", - username, (long)pid, event, detail, - err != 0 ? ": " : "", - err != 0 ? strerror(err) : ""); + username, (long) pid, event, detail, + err != 0 ? ": " : "", err != 0 ? strerror(err) : ""); } #endif } -void -log_close(void) { +void log_close(void) { if (LogFD != ERR) { close(LogFD); LogFD = ERR; @@ -599,7 +572,7 @@ log_close(void) { #if defined(SYSLOG) closelog(); syslog_open = FALSE; -#endif /*SYSLOG*/ +#endif /*SYSLOG*/ } /* char *first_word(char *s, char *t) @@ -611,14 +584,13 @@ log_close(void) { * (1) this routine is fairly slow * (2) it returns a pointer to static storage */ -char * -first_word(char *s, char *t) { +char *first_word(char *s, char *t) { static char retbuf[2][MAX_TEMPSTR + 1]; /* sure wish C had GC */ static int retsel = 0; char *rb, *rp; /* select a return buffer */ - retsel = 1-retsel; + retsel = 1 - retsel; rb = &retbuf[retsel][0]; rp = rb; @@ -640,30 +612,27 @@ first_word(char *s, char *t) { /* warning: * heavily ascii-dependent. */ -void -mkprint(dst, src, len) - char *dst; - unsigned char *src; - int len; -{ - /* - * XXX - * We know this routine can't overflow the dst buffer because mkprints() - * allocated enough space for the worst case. - */ - while (len-- > 0) - { +void mkprint(char *dst, unsigned char *src, int len) { +/* + * XXX + * We know this routine can't overflow the dst buffer because mkprints() + * allocated enough space for the worst case. +*/ + while (len-- > 0) { unsigned char ch = *src++; - if (ch < ' ') { /* control character */ + if (ch < ' ') { /* control character */ *dst++ = '^'; *dst++ = ch + '@'; - } else if (ch < 0177) { /* printable */ + } + else if (ch < 0177) { /* printable */ *dst++ = ch; - } else if (ch == 0177) { /* delete/rubout */ + } + else if (ch == 0177) { /* delete/rubout */ *dst++ = '^'; *dst++ = '?'; - } else { /* parity character */ + } + else { /* parity character */ sprintf(dst, "\\%03o", ch); dst += 4; } @@ -674,12 +643,8 @@ mkprint(dst, src, len) /* warning: * returns a pointer to malloc'd storage, you must call free yourself. */ -char * -mkprints(src, len) - unsigned char *src; - unsigned int len; -{ - char *dst = malloc(len*4 + 1); +char *mkprints(unsigned char *src, unsigned int len) { + char *dst = malloc(len * 4 + 1); if (dst) mkprint(dst, src, len); @@ -691,67 +656,59 @@ mkprints(src, len) /* Sat, 27 Feb 1993 11:44:51 -0800 (CST) * 1234567890123456789012345678901234567 */ -char * -arpadate(clock) - time_t *clock; -{ +char *arpadate(time_t *clock) { time_t t = clock ? *clock : time((TIME_T) 0); struct tm tm = *localtime(&t); long gmtoff = get_gmtoff(&t, &tm); int hours = gmtoff / SECONDS_PER_HOUR; - int minutes = (gmtoff - (hours * SECONDS_PER_HOUR)) / SECONDS_PER_MINUTE; + int minutes = + (gmtoff - (hours * SECONDS_PER_HOUR)) / SECONDS_PER_MINUTE; static char ret[64]; /* zone name might be >3 chars */ - + (void) sprintf(ret, "%s, %2d %s %2d %02d:%02d:%02d %.2d%.2d (%s)", - DowNames[tm.tm_wday], - tm.tm_mday, - MonthNames[tm.tm_mon], - tm.tm_year + 1900, - tm.tm_hour, - tm.tm_min, - tm.tm_sec, - hours, - minutes, - TZONE(tm)); + DowNames[tm.tm_wday], + tm.tm_mday, + MonthNames[tm.tm_mon], + tm.tm_year + 1900, + tm.tm_hour, tm.tm_min, tm.tm_sec, hours, minutes, TZONE(tm)); return (ret); } -#endif /*MAIL_DATE*/ +#endif /*MAIL_DATE */ #ifdef HAVE_SAVED_UIDS -static uid_t save_euid; -static gid_t save_egid; + static uid_t save_euid; + static gid_t save_egid; int swap_uids(void) { save_egid = getegid(); save_euid = geteuid(); - return ((setegid(getgid()) || seteuid(getuid())) ? -1 : 0); + return ((setegid(getgid()) || seteuid(getuid()))? -1 : 0); } int swap_uids_back(void) { return ((setegid(save_egid) || seteuid(save_euid)) ? -1 : 0); } -#else /*HAVE_SAVED_UIDS*/ +#else /*HAVE_SAVED_UIDS */ int swap_uids(void) { - return ((setregid(getegid(), getgid()) || setreuid(geteuid(), getuid())) - ? -1 : 0); + return ((setregid(getegid(), getgid()) + || setreuid(geteuid(), getuid())) ? -1 : 0); } int swap_uids_back(void) { return (swap_uids()); } -#endif /*HAVE_SAVED_UIDS*/ +#endif /*HAVE_SAVED_UIDS */ -size_t -strlens(const char *last, ...) { +size_t strlens(const char *last, ...) { va_list ap; size_t ret = 0; const char *str; va_start(ap, last); for (str = last; str != NULL; str = va_arg(ap, const char *)) - ret += strlen(str); + ret += strlen(str); va_end(ap); return (ret); } @@ -763,8 +720,7 @@ strlens(const char *last, ...) { * If the local pointer is non-NULL it *must* point to a local copy. */ #ifndef HAVE_STRUCT_TM_TM_GMTOFF -long get_gmtoff(time_t *clock, struct tm *local) -{ +long get_gmtoff(time_t * clock, struct tm *local) { struct tm gmt; long offset; @@ -773,8 +729,8 @@ long get_gmtoff(time_t *clock, struct tm *local) local = localtime(clock); offset = (local->tm_sec - gmt.tm_sec) + - ((local->tm_min - gmt.tm_min) * 60) + - ((local->tm_hour - gmt.tm_hour) * 3600); + ((local->tm_min - gmt.tm_min) * 60) + + ((local->tm_hour - gmt.tm_hour) * 3600); /* Timezone may cause year rollover to happen on a different day. */ if (local->tm_year < gmt.tm_year) diff --git a/src/popen.c b/src/popen.c index e52f755..3229545 100644 --- a/src/popen.c +++ b/src/popen.c @@ -31,7 +31,7 @@ */ #ifdef HAVE_SYS_CDEFS_H -#include +# include #endif #include @@ -47,9 +47,7 @@ static int fds; #define MAX_ARGS 1024 -FILE * -cron_popen(char *program, const char *type, struct passwd *pw) -{ +FILE *cron_popen(char *program, const char *type, struct passwd *pw) { char *cp; FILE *iop; int argc, pdes[2]; @@ -63,17 +61,17 @@ cron_popen(char *program, const char *type, struct passwd *pw) #endif if ((*type != 'r' && *type != 'w') || type[1]) - return(NULL); + return (NULL); if (!pids) { if ((fds = getdtablesize()) <= 0) - return(NULL); - if (!(pids = (PID_T *)malloc((u_int)(fds * sizeof(PID_T))))) - return(NULL); - bzero((char *)pids, fds * sizeof(PID_T)); + return (NULL); + if (!(pids = (PID_T *) malloc((u_int) (fds * sizeof (PID_T))))) + return (NULL); + bzero((char *) pids, fds * sizeof (PID_T)); } if (pipe(pdes) < 0) - return(NULL); + return (NULL); /* break up string into pieces */ for (argc = 0, cp = program; argc < MAX_ARGS; cp = NULL) @@ -81,26 +79,27 @@ cron_popen(char *program, const char *type, struct passwd *pw) break; iop = NULL; - switch(pid = fork()) { - case -1: /* error */ - (void)close(pdes[0]); - (void)close(pdes[1]); + switch (pid = fork()) { + case -1: /* error */ + (void) close(pdes[0]); + (void) close(pdes[1]); goto pfree; /* NOTREACHED */ - case 0: /* child */ + case 0: /* child */ if (*type == 'r') { if (pdes[1] != STDOUT) { dup2(pdes[1], STDOUT); dup2(pdes[1], STDERR); /* stderr, too! */ - (void)close(pdes[1]); + (void) close(pdes[1]); } - (void)close(pdes[0]); - } else { + (void) close(pdes[0]); + } + else { if (pdes[0] != STDIN) { dup2(pdes[0], STDIN); - (void)close(pdes[0]); + (void) close(pdes[0]); } - (void)close(pdes[1]); + (void) close(pdes[1]); } if (execvp(argv[0], argv) < 0) { @@ -119,20 +118,19 @@ cron_popen(char *program, const char *type, struct passwd *pw) /* parent; assume fdopen can't fail... */ if (*type == 'r') { iop = fdopen(pdes[0], type); - (void)close(pdes[1]); - } else { + (void) close(pdes[1]); + } + else { iop = fdopen(pdes[1], type); - (void)close(pdes[0]); + (void) close(pdes[0]); } pids[fileno(iop)] = pid; -pfree: - return(iop); + pfree: + return (iop); } -int -cron_pclose(FILE *iop) -{ +int cron_pclose(FILE * iop) { int fdes; sigset_t oset, nset; WAIT_T stat_loc; @@ -143,17 +141,16 @@ cron_pclose(FILE *iop) * `popened' command, or, if already `pclosed'. */ if (pids == 0 || pids[fdes = fileno(iop)] == 0) - return(-1); - (void)fclose(iop); - + return (-1); + (void) fclose(iop); + sigemptyset(&nset); sigaddset(&nset, SIGINT); sigaddset(&nset, SIGQUIT); sigaddset(&nset, SIGHUP); - (void)sigprocmask(SIG_BLOCK, &nset, &oset); - while ((pid = wait(&stat_loc)) != pids[fdes] && pid != -1) - ; - (void)sigprocmask(SIG_SETMASK, &oset, NULL); + (void) sigprocmask(SIG_BLOCK, &nset, &oset); + while ((pid = wait(&stat_loc)) != pids[fdes] && pid != -1) ; + (void) sigprocmask(SIG_SETMASK, &oset, NULL); pids[fdes] = 0; return (pid == -1 ? -1 : WEXITSTATUS(stat_loc)); } diff --git a/src/security.c b/src/security.c index 26ede72..956db2d 100644 --- a/src/security.c +++ b/src/security.c @@ -22,42 +22,42 @@ #include #ifdef WITH_SELINUX -#include -#include -#include -#include -#include +# include +# include +# include +# include +# include #endif #ifdef WITH_AUDIT -#include +# include #endif #ifdef WITH_PAM static pam_handle_t *pamh = NULL; -static int pam_session_opened = 0; //global for open session +static int pam_session_opened = 0; //global for open session static const struct pam_conv conv = { - NULL + NULL }; static int cron_open_pam_session(struct passwd *pw); -#define PAM_FAIL_CHECK if (retcode != PAM_SUCCESS) { \ - fprintf(stderr,"\n%s\n",pam_strerror(pamh, retcode)); \ - if (pamh != NULL) { \ - if (pam_session_opened != 0) \ - pam_close_session(pamh, PAM_SILENT); \ - pam_end(pamh, retcode); \ - } \ - return(retcode); } +# define PAM_FAIL_CHECK if (retcode != PAM_SUCCESS) { \ + fprintf(stderr,"\n%s\n",pam_strerror(pamh, retcode)); \ + if (pamh != NULL) { \ + if (pam_session_opened != 0) \ + pam_close_session(pamh, PAM_SILENT); \ + pam_end(pamh, retcode); \ + } \ +return(retcode); } #endif -static char ** build_env(char **cronenv); +static char **build_env(char **cronenv); #ifdef WITH_SELINUX -static int cron_change_selinux_range( user *u, - security_context_t ucontext ); -static int cron_get_job_range( user *u, security_context_t *ucontextp, char **jobenv ); +static int cron_change_selinux_range(user * u, security_context_t ucontext); +static int cron_get_job_range(user * u, security_context_t * ucontextp, + char **jobenv); #endif void cron_restore_default_security_context() { @@ -66,162 +66,167 @@ void cron_restore_default_security_context() { #endif } -int cron_set_job_security_context(entry *e, user *u, char ***jobenv) { - time_t minutely_time = 0; +int cron_set_job_security_context(entry * e, user * u, char ***jobenv) { + time_t minutely_time = 0; #ifdef WITH_PAM - int ret; + int ret; #endif - if ((e->flags & MIN_STAR)==MIN_STAR) { + if ((e->flags & MIN_STAR) == MIN_STAR) { /* "minute-ly" job: Every minute for given hour/dow/month/dom. * Ensure that these jobs never run in the same minute: */ minutely_time = time(0); Debug(DSCH, ("Minute-ly job. Recording time %lu\n", minutely_time)) - } + } #ifdef WITH_PAM - if ((ret=cron_start_pam(e->pwd)) != 0) { - log_it(e->pwd->pw_name, getpid(), "FAILED to authorize user with PAM", pam_strerror(pamh, ret), 0); + if ((ret = cron_start_pam(e->pwd)) != 0) { + log_it(e->pwd->pw_name, getpid(), "FAILED to authorize user with PAM", + pam_strerror(pamh, ret), 0); return -1; - } + } #endif - *jobenv = build_env( e->envp ); + *jobenv = build_env(e->envp); #ifdef WITH_SELINUX - /* we must get the crontab context BEFORE changing user, else - * we'll not be permitted to read the cron spool directory :-) - */ - security_context_t ucontext=0; + /* we must get the crontab context BEFORE changing user, else + * we'll not be permitted to read the cron spool directory :-) + */ + security_context_t ucontext = 0; - if (cron_get_job_range(u, &ucontext, *jobenv) < OK) { - log_it(e->pwd->pw_name, getpid(), "ERROR", "failed to get SELinux context", 0); + if (cron_get_job_range(u, &ucontext, *jobenv) < OK) { + log_it(e->pwd->pw_name, getpid(), "ERROR", + "failed to get SELinux context", 0); return -1; - } + } - if (cron_change_selinux_range(u, ucontext) != 0) { - log_it(e->pwd->pw_name, getpid(),"ERROR", "failed to change SELinux context", 0); - if ( ucontext ) + if (cron_change_selinux_range(u, ucontext) != 0) { + log_it(e->pwd->pw_name, getpid(), "ERROR", + "failed to change SELinux context", 0); + if (ucontext) freecon(ucontext); return -1; - } - if (ucontext) + } + if (ucontext) freecon(ucontext); #endif #ifdef WITH_PAM - if ((ret=cron_open_pam_session(e->pwd)) != 0) { - log_it(e->pwd->pw_name, getpid(), "FAILED to open PAM security session", pam_strerror(pamh, ret), 0); + if ((ret = cron_open_pam_session(e->pwd)) != 0) { + log_it(e->pwd->pw_name, getpid(), + "FAILED to open PAM security session", pam_strerror(pamh, ret), 0); return -1; - } + } #endif - if (cron_change_user(e->pwd, env_get("HOME", *jobenv)) != 0) { + if (cron_change_user(e->pwd, env_get("HOME", *jobenv)) != 0) { log_it(e->pwd->pw_name, getpid(), "ERROR", "failed to change user", 0); return -1; - } + } - log_close(); + log_close(); - time_t job_run_time = time(0L); + time_t job_run_time = time(0L); - if ((minutely_time > 0) &&((job_run_time / 60) != (minutely_time / 60))) { - /* if a per-minute job is delayed into the next minute - * (eg. by network authentication method timeouts), skip it. - */ + if ((minutely_time > 0) && ((job_run_time / 60) != (minutely_time / 60))) { + /* if a per-minute job is delayed into the next minute + * (eg. by network authentication method timeouts), skip it. + */ struct tm tmS, tmN; char buf[256]; - + localtime_r(&job_run_time, &tmN); - localtime_r(&minutely_time,&tmS); - - snprintf(buf, sizeof(buf), "Job execution of per-minute job scheduled for " + localtime_r(&minutely_time, &tmS); + + snprintf(buf, sizeof (buf), + "Job execution of per-minute job scheduled for " "%.2u:%.2u delayed into subsequent minute %.2u:%.2u. Skipping job run.", tmS.tm_hour, tmS.tm_min, tmN.tm_hour, tmN.tm_min); log_it(e->pwd->pw_name, getpid(), "INFO", buf, 0); return -1; - } - return 0; + } + return 0; } int cron_start_pam(struct passwd *pw) { - int retcode = 0; + int retcode = 0; #if defined(WITH_PAM) - retcode = pam_start("crond", pw->pw_name, &conv, &pamh); - PAM_FAIL_CHECK; - retcode = pam_set_item(pamh, PAM_TTY, "cron"); - PAM_FAIL_CHECK; - retcode = pam_acct_mgmt(pamh, PAM_SILENT); - PAM_FAIL_CHECK; + retcode = pam_start("crond", pw->pw_name, &conv, &pamh); + PAM_FAIL_CHECK; + retcode = pam_set_item(pamh, PAM_TTY, "cron"); + PAM_FAIL_CHECK; + retcode = pam_acct_mgmt(pamh, PAM_SILENT); + PAM_FAIL_CHECK; #endif - - return retcode; + + return retcode; } static int cron_open_pam_session(struct passwd *pw) { - int retcode = 0; + int retcode = 0; #if defined(WITH_PAM) - retcode = pam_setcred(pamh, PAM_ESTABLISH_CRED | PAM_SILENT); - PAM_FAIL_CHECK; - retcode = pam_open_session(pamh, PAM_SILENT); - PAM_FAIL_CHECK; + retcode = pam_setcred(pamh, PAM_ESTABLISH_CRED | PAM_SILENT); + PAM_FAIL_CHECK; + retcode = pam_open_session(pamh, PAM_SILENT); + PAM_FAIL_CHECK; if (retcode == PAM_SUCCESS) - pam_session_opened = 1; + pam_session_opened = 1; #endif - return retcode; + return retcode; } void cron_close_pam(void) { #if defined(WITH_PAM) - if (pam_session_opened != 0) { - pam_setcred(pamh, PAM_DELETE_CRED | PAM_SILENT); - pam_close_session(pamh, PAM_SILENT); - } - pam_end(pamh, PAM_SUCCESS); + if (pam_session_opened != 0) { + pam_setcred(pamh, PAM_DELETE_CRED | PAM_SILENT); + pam_close_session(pamh, PAM_SILENT); + } + pam_end(pamh, PAM_SUCCESS); #endif } int cron_change_user(struct passwd *pw, char *homedir) { - pid_t pid = getpid(); - /* set our directory, uid and gid. Set gid first, since once - * we set uid, we've lost root privledges. - */ - if (setgid(pw->pw_gid) != 0) { + pid_t pid = getpid(); + /* set our directory, uid and gid. Set gid first, since once + * we set uid, we've lost root privledges. + */ + if (setgid(pw->pw_gid) != 0) { log_it("CRON", pid, "ERROR", "setgid failed", errno); return -1; - } + } - if (initgroups(pw->pw_name, pw->pw_gid) != 0) { + if (initgroups(pw->pw_name, pw->pw_gid) != 0) { log_it("CRON", pid, "ERROR", "initgroups failed", errno); - return -1; - } + return -1; + } - if (setreuid( pw->pw_uid, -1 ) != 0) { + if (setreuid(pw->pw_uid, -1) != 0) { log_it("CRON", pid, "ERROR", "setreuid failed", errno); return -1; - } + } - if (chdir(homedir) == -1) { - log_it("CRON", pid, "ERROR chdir failed", homedir, errno); - return -1; - } - return 0; + if (chdir(homedir) == -1) { + log_it("CRON", pid, "ERROR chdir failed", homedir, errno); + return -1; + } + return 0; } int cron_change_user_permanently(struct passwd *pw) { - if (setreuid( pw->pw_uid, pw->pw_uid ) != 0) { - log_it("CRON", getpid(), "ERROR", "setreuid failed", errno); - return -1; - } - return 0; + if (setreuid(pw->pw_uid, pw->pw_uid) != 0) { + log_it("CRON", getpid(), "ERROR", "setreuid failed", errno); + return -1; + } + return 0; } -static int cron_authorize_context -(security_context_t scontext,security_context_t file_context) { +static int cron_authorize_context(security_context_t scontext, + security_context_t file_context) { #ifdef WITH_SELINUX struct av_decision avd; int retval; @@ -234,26 +239,26 @@ static int cron_authorize_context * permission check for this purpose. */ retval = security_compute_av(scontext, file_context, - SECCLASS_FILE, bit, &avd); + SECCLASS_FILE, bit, &avd); if (retval || ((bit & avd.allowed) != bit)) return 0; #endif return 1; } -static int cron_authorize_range -(security_context_t scontext,security_context_t ucontext) { +static int cron_authorize_range(security_context_t scontext, + security_context_t ucontext) { #ifdef WITH_SELINUX struct av_decision avd; int retval; - unsigned int bit = CONTEXT__CONTAINS; + unsigned int bit = CONTEXT__CONTAINS; /* * Since crontab files are not directly executed, * so crond must ensure that any user specified range * falls within the seusers-specified range for that Linux user. */ retval = security_compute_av(scontext, ucontext, - SECCLASS_CONTEXT, bit, &avd); + SECCLASS_CONTEXT, bit, &avd); if (retval || ((bit & avd.allowed) != bit)) return 0; @@ -263,8 +268,9 @@ static int cron_authorize_range #if WITH_SELINUX /* always uses u->scontext as the default process context, then changes the - level, and retuns it in ucontextp (or NULL otherwise) */ -static int cron_get_job_range(user *u, security_context_t *ucontextp, char **jobenv) { + level, and retuns it in ucontextp (or NULL otherwise) */ +static int +cron_get_job_range(user * u, security_context_t * ucontextp, char **jobenv) { char *range; if (is_selinux_enabled() <= 0) @@ -274,93 +280,93 @@ static int cron_get_job_range(user *u, security_context_t *ucontextp, char **job *ucontextp = 0L; - if ((range = env_get("MLS_LEVEL",jobenv)) != 0L) { - context_t ccon; - if (!(ccon = context_new(u->scontext))) { - log_it(u->name, getpid(), "context_new FAILED for MLS_LEVEL", range, 0); - return -1; - } - - if (context_range_set(ccon, range)) { - log_it(u->name, getpid(), "context_range_set FAILED for MLS_LEVEL", - range, 0); - return -1; - } - - if (!(*ucontextp = context_str(ccon))) { - log_it(u->name, getpid(), "context_str FAILED for MLS_LEVEL", - range, 0); - return -1; - } - - if (!(*ucontextp = strdup(*ucontextp))) { - log_it(u->name, getpid(), "strdup FAILED for MLS_LEVEL", - range, 0); - return -1; - } - context_free(ccon); + if ((range = env_get("MLS_LEVEL", jobenv)) != 0L) { + context_t ccon; + if (!(ccon = context_new(u->scontext))) { + log_it(u->name, getpid(), "context_new FAILED for MLS_LEVEL", + range, 0); + return -1; + } + + if (context_range_set(ccon, range)) { + log_it(u->name, getpid(), + "context_range_set FAILED for MLS_LEVEL", range, 0); + return -1; + } + + if (!(*ucontextp = context_str(ccon))) { + log_it(u->name, getpid(), "context_str FAILED for MLS_LEVEL", + range, 0); + return -1; + } + + if (!(*ucontextp = strdup(*ucontextp))) { + log_it(u->name, getpid(), "strdup FAILED for MLS_LEVEL", range, 0); + return -1; + } + context_free(ccon); + } + else if (!u->scontext) { + /* cron_change_selinux_range() deals with this */ + return 0; + } + else if (!(*ucontextp = strdup(u->scontext))) { + log_it(u->name, getpid(), "strdup FAILED for MLS_LEVEL", range, 0); + return -1; } - else if (!u->scontext) { - /* cron_change_selinux_range() deals with this */ - return 0; - } - else if (!(*ucontextp = strdup(u->scontext))) { - log_it(u->name, getpid(), "strdup FAILED for MLS_LEVEL", - range, 0); - return -1; - } return 0; } #endif #ifdef WITH_SELINUX -static int cron_change_selinux_range(user *u,security_context_t ucontext) { +static int cron_change_selinux_range(user * u, security_context_t ucontext) { char *msg = NULL; if (is_selinux_enabled() <= 0) return 0; if (u->scontext == 0L) { - if (security_getenforce() > 0) - { - log_it( u->name, getpid(), - "NULL security context for user", - "", 0); + if (security_getenforce() > 0) { + log_it(u->name, getpid(), "NULL security context for user", "", 0); return -1; } else { - log_it( u->name, getpid(), + log_it(u->name, getpid(), "NULL security context for user, " - "but SELinux in permissive mode, continuing", - "", 0); + "but SELinux in permissive mode, continuing", "", 0); return 0; } } - if (strcmp(u->scontext, ucontext)) { - if (!cron_authorize_range( u->scontext, ucontext)) { + if (strcmp(u->scontext, ucontext)) { + if (!cron_authorize_range(u->scontext, ucontext)) { if (security_getenforce() > 0) { -#ifdef WITH_AUDIT - if (asprintf(&msg, "cron: Unauthorized MLS range acct=%s new_scontext=%s old_scontext=%s", - u->name, (char*)ucontext, u->scontext) >= 0) { +# ifdef WITH_AUDIT + if (asprintf(&msg, + "cron: Unauthorized MLS range acct=%s new_scontext=%s old_scontext=%s", + u->name, (char *) ucontext, u->scontext) >= 0) { int audit_fd = audit_open(); - audit_log_user_message(audit_fd, AUDIT_USER_ROLE_CHANGE, msg, NULL, NULL, NULL, 0); + audit_log_user_message(audit_fd, AUDIT_USER_ROLE_CHANGE, + msg, NULL, NULL, NULL, 0); close(audit_fd); free(msg); } -#endif - if (asprintf(&msg, "Unauthorized range in %s for user range in %s", - (char*)ucontext, u->scontext) >= 0) { +# endif + if (asprintf + (&msg, "Unauthorized range in %s for user range in %s", + (char *) ucontext, u->scontext) >= 0) { log_it(u->name, getpid(), "ERROR", msg, 0); free(msg); } return -1; } else { - if (asprintf(&msg, "Unauthorized range in %s for user range in %s," - " but SELinux in permissive mod, continuing", - (char*)ucontext, u->scontext) >= 0) { + if (asprintf + (&msg, + "Unauthorized range in %s for user range in %s," + " but SELinux in permissive mod, continuing", + (char *) ucontext, u->scontext) >= 0) { log_it(u->name, getpid(), "WARNING", msg, 0); free(msg); } @@ -370,17 +376,20 @@ static int cron_change_selinux_range(user *u,security_context_t ucontext) { if (setexeccon(ucontext) < 0 || setkeycreatecon(ucontext) < 0) { if (security_getenforce() > 0) { - if (asprintf(&msg, "Could not set exec or keycreate context to %s for user", - (char*)ucontext) >= 0) { + if (asprintf + (&msg, "Could not set exec or keycreate context to %s for user", + (char *) ucontext) >= 0) { log_it(u->name, getpid(), "ERROR", msg, 0); free(msg); } return -1; } else { - if (asprintf(&msg, "Could not set exec or keycreate context to %s for user," - " but SELinux in permissive mode, continuing", - (char*)ucontext) >= 0) { + if (asprintf + (&msg, + "Could not set exec or keycreate context to %s for user," + " but SELinux in permissive mode, continuing", + (char *) ucontext) >= 0) { log_it(u->name, getpid(), "WARNING", msg, 0); free(msg); } @@ -391,38 +400,41 @@ static int cron_change_selinux_range(user *u,security_context_t ucontext) { } #endif -int get_security_context( const char *name, - int crontab_fd, - security_context_t *rcontext, - const char *tabname) { +int +get_security_context(const char *name, int crontab_fd, + security_context_t * rcontext, const char *tabname) { #ifdef WITH_SELINUX - security_context_t scontext=NULL; - security_context_t file_context=NULL; - int retval=0; - char *seuser=NULL; - char *level=NULL; + security_context_t scontext = NULL; + security_context_t file_context = NULL; + int retval = 0; + char *seuser = NULL; + char *level = NULL; *rcontext = NULL; - if (is_selinux_enabled() <= 0) - return 0; + if (is_selinux_enabled() <= 0) + return 0; if (name != NULL) { if (getseuserbyname(name, &seuser, &level) < 0) { log_it(name, getpid(), "getseuserbyname FAILED", name, 0); - return (security_getenforce() > 0); + return (security_getenforce() > 0); } } - retval=get_default_context_with_level(name == NULL ? "system_u" : seuser, level, NULL, &scontext); + retval = get_default_context_with_level(name == NULL ? "system_u" : seuser, + level, NULL, &scontext); free(seuser); free(level); if (retval) { if (security_getenforce() > 0) { log_it(name, getpid(), "No SELinux security context", tabname, 0); return -1; - } else { - log_it(name, getpid(), "No security context but SELinux in permissive mode, continuing", tabname, 0); + } + else { + log_it(name, getpid(), + "No security context but SELinux in permissive mode, continuing", + tabname, 0); return 0; } } @@ -432,14 +444,17 @@ int get_security_context( const char *name, log_it(name, getpid(), "getfilecon FAILED", tabname, 0); freecon(scontext); return -1; - } else { - log_it(name, getpid(), "getfilecon FAILED but SELinux in permissive mode, continuing", tabname, 0); - *rcontext=scontext; + } + else { + log_it(name, getpid(), + "getfilecon FAILED but SELinux in permissive mode, continuing", + tabname, 0); + *rcontext = scontext; return 0; } } - - if (!cron_authorize_context( scontext, file_context)) { + + if (!cron_authorize_context(scontext, file_context)) { freecon(scontext); freecon(file_context); if (security_getenforce() > 0) { @@ -447,61 +462,61 @@ int get_security_context( const char *name, return -1; } else { - log_it(name, getpid(), - "Unauthorized SELinux context, but SELinux in permissive mode, continuing", - tabname, 0); - return 0; + log_it(name, getpid(), + "Unauthorized SELinux context, but SELinux in permissive mode, continuing", + tabname, 0); + return 0; } } freecon(file_context); - *rcontext=scontext; + *rcontext = scontext; #endif return 0; } -void free_security_context(security_context_t *scontext) { +void free_security_context(security_context_t * scontext) { #ifdef WITH_SELINUX - if (*scontext != NULL) { + if (*scontext != NULL) { freecon(*scontext); - *scontext=0L; - } -#endif + *scontext = 0L; + } +#endif } int crontab_security_access(void) { #ifdef WITH_SELINUX - if (is_selinux_enabled() > 0) - if (selinux_check_passwd_access(PASSWD__CRONTAB)!=0) - return -1; + if (is_selinux_enabled() > 0) + if (selinux_check_passwd_access(PASSWD__CRONTAB) != 0) + return -1; #endif - return 0; + return 0; } /* Build up the job environment from the PAM environment plus the - crontab environment */ -static char ** build_env(char **cronenv) -{ +* crontab environment +*/ +static char **build_env(char **cronenv) { #ifdef WITH_PAM - char **jobenv = cronenv; - char **pamenv = pam_getenvlist(pamh); - char *cronvar; - int count = 0; - jobenv = env_copy(pamenv); + char **jobenv = cronenv; + char **pamenv = pam_getenvlist(pamh); + char *cronvar; + int count = 0; + jobenv = env_copy(pamenv); - /* Now add the cron environment variables. Since env_set() - overwrites existing variables, this will let cron's - environment settings override pam's */ + /* Now add the cron environment variables. Since env_set() + * overwrites existing variables, this will let cron's + * environment settings override pam's */ - while ((cronvar = cronenv[count++])) { + while ((cronvar = cronenv[count++])) { if (!(jobenv = env_set(jobenv, cronvar))) { - log_it("CRON", getpid(), "Setting Cron environment variable failed", cronvar, 0); - return NULL; + log_it("CRON", getpid(), + "Setting Cron environment variable failed", cronvar, 0); + return NULL; } - } - return jobenv; + } + return jobenv; #else - return env_copy(cronenv); + return env_copy(cronenv); #endif } - diff --git a/src/user.c b/src/user.c index 5cfdd94..8551aca 100644 --- a/src/user.c +++ b/src/user.c @@ -27,17 +27,18 @@ static const char *FileName; static void -log_error(const char *msg) { - log_it("CRON", getpid(), msg, FileName, 0); +log_error (const char *msg) +{ + log_it ("CRON", getpid (), msg, FileName, 0); } void -free_user(user *u) { +free_user (user * u) { entry *e, *ne; free(u->name); free(u->tabname); - for (e = u->crontab; e != NULL; e = ne) { + for (e = u->crontab; e != NULL; e = ne) { ne = e->next; free_entry(e); } @@ -46,7 +47,8 @@ free_user(user *u) { } user * -load_user(int crontab_fd, struct passwd *pw, const char *uname, const char *fname, const char *tabname) { +load_user (int crontab_fd, struct passwd *pw, const char *uname, + const char *fname, const char *tabname) { char envstr[MAX_ENVSTR]; FILE *file; user *u; @@ -54,32 +56,31 @@ load_user(int crontab_fd, struct passwd *pw, const char *uname, const char *fnam int status, save_errno; char **envp, **tenvp; - if (!(file = fdopen(crontab_fd, "r"))) { + if (!(file = fdopen(crontab_fd, "r"))) { int save_errno = errno; - log_it(uname, getpid(), "FAILED", "fdopen on crontab_fd in load_user", save_errno); + log_it(uname, getpid (), "FAILED", "fdopen on crontab_fd in load_user", + save_errno); return (NULL); } Debug(DPARS, ("load_user()\n")) - /* file is open. build user entry, then read the crontab file. */ - if ((u = (user *) malloc(sizeof(user))) == NULL) + if ((u = (user *) malloc (sizeof (user))) == NULL) return (NULL); - if ( ((u->name = strdup(fname)) == NULL) - ||((u->tabname = strdup(tabname)) == NULL) - ){ + if (((u->name = strdup(fname)) == NULL) + || ((u->tabname = strdup(tabname)) == NULL)) { save_errno = errno; free(u); errno = save_errno; return (NULL); } - + u->crontab = NULL; /* init environment. this will be copied/augmented for each entry. - */ + */ if ((envp = env_init()) == NULL) { save_errno = errno; free(u->name); @@ -88,46 +89,44 @@ load_user(int crontab_fd, struct passwd *pw, const char *uname, const char *fnam return (NULL); } - if (get_security_context(pw == NULL ? NULL : uname, - crontab_fd, - &u->scontext, tabname) != 0) { - free_user(u); - u = NULL; - goto done; + if (get_security_context(pw == NULL ? NULL : uname, + crontab_fd, &u->scontext, tabname) != 0) { + free_user (u); + u = NULL; + goto done; } - + /* load the crontab - */ - while ((status = load_env(envstr, file)) >= OK) { + */ + while ((status = load_env (envstr, file)) >= OK) { switch (status) { - case ERR: - free_user(u); - u = NULL; - goto done; - case FALSE: - FileName = tabname; - e = load_entry(file, log_error, pw, envp); - if (e) { - e->next = u->crontab; - u->crontab = e; - } - break; - case TRUE: - if ((tenvp = env_set(envp, envstr)) == NULL) { - save_errno = errno; + case ERR: free_user(u); u = NULL; - errno = save_errno; goto done; - } + case FALSE: + FileName = tabname; + e = load_entry(file, log_error, pw, envp); + if (e) { + e->next = u->crontab; + u->crontab = e; + } + break; + case TRUE: + if ((tenvp = env_set (envp, envstr)) == NULL) { + save_errno = errno; + free_user(u); + u = NULL; + errno = save_errno; + goto done; + } envp = tenvp; break; } } - done: +done: env_free(envp); fclose(file); - Debug(DPARS, ("...load_user() done\n")) - return (u); + Debug(DPARS, ("...load_user() done\n")) return (u); } -- 2.40.0