2 * atrun.c - run jobs queued by at; run with root privileges.
3 * Copyright (C) 1993, 1994 Thomas Koenig
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. The name of the author(s) may not be used to endorse or promote
11 * products derived from this software without specific prior written
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
15 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17 * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
18 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21 * THEORY OF LIABILITY, WETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 * $FreeBSD: src/libexec/atrun/atrun.c,v 1.26 2007/06/15 12:02:16 yar Exp $
26 * $DragonFly: src/libexec/atrun/atrun.c,v 1.5 2004/09/20 19:32:19 joerg Exp $
31 #include <sys/fcntl.h>
32 #include <sys/types.h>
35 #include <sys/param.h>
53 #include <login_cap.h>
56 #include <security/pam_appl.h>
57 #include <security/openpam.h>
60 #if (MAXLOGNAME-1) > UT_NAMESIZE
61 #define LOGNAMESIZE UT_NAMESIZE
63 #define LOGNAMESIZE (MAXLOGNAME-1)
74 #define ATJOB_DIR "/usr/spool/atjobs/"
78 #define ATSPOOL_DIR "/usr/spool/atspool/"
82 #define LOADAVG_MX 1.5
85 uid_t real_uid
, effective_uid
;
86 gid_t real_gid
, effective_gid
;
88 /* File scope variables */
90 static const char * const atrun
= "atrun"; /* service name for syslog etc. */
93 void perr(const char *fmt
, ...);
94 void perrx(const char *fmt
, ...);
95 static void usage(void);
99 write_string(int fd
, const char* a
)
101 return write(fd
, a
, strlen(a
));
112 kill(getpid(),SIGSTOP
);
120 run_file(const char *filename
, uid_t uid
, gid_t gid
)
122 /* Run a file by spawning off a process which redirects I/O,
123 * spawns a subshell, then waits for it to complete and sends
129 char mailbuf
[LOGNAMESIZE
+ 1], fmt
[49];
130 char *mailname
= NULL
;
133 struct stat buf
, lbuf
;
135 struct passwd
*pentry
;
140 pam_handle_t
*pamh
= NULL
;
142 struct pam_conv pamc
= {
143 .conv
= openpam_nullconv
,
150 if (chmod(filename
, S_IRUSR
) != 0)
152 perr("cannot change file permissions");
164 /* Let's see who we mail to. Hopefully, we can read it from
165 * the command file; if not, send it to the owner, or, failing that,
169 pentry
= getpwuid(uid
);
171 perrx("Userid %lu not found - aborting job %s",
172 (unsigned long) uid
, filename
);
177 pam_err
= pam_start(atrun
, pentry
->pw_name
, &pamc
, &pamh
);
178 if (pam_err
!= PAM_SUCCESS
)
179 perrx("cannot start PAM: %s", pam_strerror(pamh
, pam_err
));
181 pam_err
= pam_acct_mgmt(pamh
, PAM_SILENT
);
182 /* Expired password shouldn't prevent the job from running. */
183 if (pam_err
!= PAM_SUCCESS
&& pam_err
!= PAM_NEW_AUTHTOK_REQD
)
184 perrx("Account %s (userid %lu) unavailable for job %s: %s",
185 pentry
->pw_name
, (unsigned long)uid
,
186 filename
, pam_strerror(pamh
, pam_err
));
188 pam_end(pamh
, pam_err
);
195 stream
=fopen(filename
, "r");
200 perr("cannot open input file");
202 if ((fd_in
= dup(fileno(stream
))) <0)
203 perr("error duplicating input file descriptor");
205 if (fstat(fd_in
, &buf
) == -1)
206 perr("error in fstat of input file descriptor");
208 if (lstat(filename
, &lbuf
) == -1)
209 perr("error in fstat of input file");
211 if (S_ISLNK(lbuf
.st_mode
))
212 perrx("Symbolic link encountered in job %s - aborting", filename
);
214 if ((lbuf
.st_dev
!= buf
.st_dev
) || (lbuf
.st_ino
!= buf
.st_ino
) ||
215 (lbuf
.st_uid
!= buf
.st_uid
) || (lbuf
.st_gid
!= buf
.st_gid
) ||
216 (lbuf
.st_size
!=buf
.st_size
))
217 perrx("Somebody changed files from under us for job %s - aborting",
220 if (buf
.st_nlink
> 1)
221 perrx("Somebody is trying to run a linked script for job %s", filename
);
223 if ((fflags
= fcntl(fd_in
, F_GETFD
)) <0)
224 perr("error in fcntl");
226 fcntl(fd_in
, F_SETFD
, fflags
& ~FD_CLOEXEC
);
228 snprintf(fmt
, sizeof(fmt
),
229 "#!/bin/sh\n# atrun uid=%%ld gid=%%ld\n# mail %%%ds %%d",
232 if (fscanf(stream
, fmt
, &nuid
, &ngid
, mailbuf
, &send_mail
) != 4)
233 perrx("File %s is in wrong format - aborting", filename
);
235 if (mailbuf
[0] == '-')
236 perrx("Illegal mail name %s in %s", mailbuf
, filename
);
241 perrx("Job %s - userid %ld does not match file uid %lu",
242 filename
, nuid
, (unsigned long)uid
);
245 perrx("Job %s - groupid %ld does not match file gid %lu",
246 filename
, ngid
, (unsigned long)gid
);
250 if (chdir(ATSPOOL_DIR
) < 0)
251 perr("cannot chdir to %s", ATSPOOL_DIR
);
253 /* Create a file to hold the output of the job we are about to run.
254 * Write the mail header.
256 if((fd_out
=open(filename
,
257 O_WRONLY
| O_CREAT
| O_EXCL
, S_IWUSR
| S_IRUSR
)) < 0)
258 perr("cannot create output file");
260 write_string(fd_out
, "Subject: Output from your job ");
261 write_string(fd_out
, filename
);
262 write_string(fd_out
, "\n\n");
267 close(STDOUT_FILENO
);
268 close(STDERR_FILENO
);
272 perr("error in fork");
279 /* Set up things for the child; we want standard input from the input file,
280 * and standard output and error sent to our output file.
283 if (lseek(fd_in
, (off_t
) 0, SEEK_SET
) < 0)
284 perr("error in lseek");
286 if (dup(fd_in
) != STDIN_FILENO
)
287 perr("error in I/O redirection");
289 if (dup(fd_out
) != STDOUT_FILENO
)
290 perr("error in I/O redirection");
292 if (dup(fd_out
) != STDERR_FILENO
)
293 perr("error in I/O redirection");
297 if (chdir(ATJOB_DIR
) < 0)
298 perr("cannot chdir to %s", ATJOB_DIR
);
304 nice(tolower(queue
) - 'a');
308 * For simplicity and safety, set all aspects of the user context
309 * except for a selected subset: Don't set priority, which was
310 * set based on the queue file name according to the tradition.
311 * Don't bother to set environment, including path vars, either
312 * because it will be discarded anyway. Although the job file
313 * should set umask, preset it here just in case.
315 if (setusercontext(NULL
, pentry
, uid
, LOGIN_SETALL
&
316 ~(LOGIN_SETPRIORITY
| LOGIN_SETPATH
| LOGIN_SETENV
)) != 0)
317 exit(EXIT_FAILURE
); /* setusercontext() logged the error */
318 #else /* LOGIN_CAP */
319 if (initgroups(pentry
->pw_name
,pentry
->pw_gid
))
320 perr("cannot init group access list");
322 if (setgid(gid
) < 0 || setegid(pentry
->pw_gid
) < 0)
323 perr("cannot change group");
325 if (setlogin(pentry
->pw_name
))
326 perr("cannot set login name");
328 if (setuid(uid
) < 0 || seteuid(uid
) < 0)
329 perr("cannot set user id");
330 #endif /* LOGIN_CAP */
332 if (chdir(pentry
->pw_dir
))
335 if(execle("/bin/sh","sh",NULL
, nenvp
) != 0)
336 perr("exec failed for /bin/sh");
340 /* We're the parent. Let's wait.
344 waitpid(pid
, NULL
, 0);
346 /* Send mail. Unlink the output file first, so it is deleted after
349 stat(filename
, &buf
);
350 if (open(filename
, O_RDONLY
) != STDIN_FILENO
)
351 perr("open of jobfile failed");
354 if ((buf
.st_size
!= size
) || send_mail
)
360 * This time set full context to run the mailer.
362 if (setusercontext(NULL
, pentry
, uid
, LOGIN_SETALL
) != 0)
363 exit(EXIT_FAILURE
); /* setusercontext() logged the error */
364 #else /* LOGIN_CAP */
365 if (initgroups(pentry
->pw_name
,pentry
->pw_gid
))
366 perr("cannot init group access list");
368 if (setgid(gid
) < 0 || setegid(pentry
->pw_gid
) < 0)
369 perr("cannot change group");
371 if (setlogin(pentry
->pw_name
))
372 perr("cannot set login name");
374 if (setuid(uid
) < 0 || seteuid(uid
) < 0)
375 perr("cannot set user id");
376 #endif /* LOGIN_CAP */
378 if (chdir(pentry
->pw_dir
))
381 execl(_PATH_SENDMAIL
, "sendmail", "-F", "Atrun Service",
384 perr("exec failed for mail command");
391 /* Global functions */
393 /* Needed in gloadavg.c */
395 perr(const char *fmt
, ...)
397 const char * const fmtadd
= ": %m";
398 char nfmt
[strlen(fmt
) + strlen(fmtadd
) + 1];
408 snprintf(nfmt
, sizeof(nfmt
), "%s%s", fmt
, fmtadd
);
409 vsyslog(LOG_ERR
, nfmt
, ap
);
417 perrx(const char *fmt
, ...)
425 vsyslog(LOG_ERR
, fmt
, ap
);
432 main(int argc
, char *argv
[])
434 /* Browse through ATJOB_DIR, checking all the jobfiles wether they should
435 * be executed and or deleted. The queue is coded into the first byte of
436 * the job filename, the date (in minutes since Eon) as a hex number in the
437 * following eight bytes, followed by a dot and a serial number. A file
438 * which has not been executed yet is denoted by its execute - bit set.
439 * For those files which are to be executed, run_file() is called, which forks
440 * off a child which takes care of I/O redirection, forks off another child
441 * for execution and yet another one, optionally, for sending mail.
442 * Files which already have run are removed during the next invocation.
445 struct dirent
*dirent
;
450 time_t now
, run_time
;
451 char batch_name
[] = "Z2345678901234";
456 double load_avg
= LOADAVG_MX
;
458 /* We don't need root privileges all the time; running under uid and gid daemon
462 RELINQUISH_PRIVS_ROOT(DAEMON_UID
, DAEMON_GID
)
464 openlog(atrun
, LOG_PID
, LOG_CRON
);
467 while((c
=getopt(argc
, argv
, "dl:"))!= -1)
472 if (sscanf(optarg
, "%lf", &load_avg
) != 1)
473 perr("garbled option -l");
475 load_avg
= LOADAVG_MX
;
488 if (chdir(ATJOB_DIR
) != 0)
489 perr("cannot change to %s", ATJOB_DIR
);
491 /* Main loop. Open spool directory for reading and look over all the
492 * files in there. If the filename indicates that the job should be run
493 * and the x bit is set, fork off a child which sets its user and group
494 * id to that of the files and exec a /bin/sh which executes the shell
495 * script. Unlink older files if they should no longer be run. For
496 * deletion, their r bit has to be turned on.
498 * Also, pick the oldest batch job to run, at most one per invocation of
501 if ((spool
= opendir(".")) == NULL
)
502 perr("cannot read %s", ATJOB_DIR
);
506 batch_uid
= (uid_t
) -1;
507 batch_gid
= (gid_t
) -1;
509 while ((dirent
= readdir(spool
)) != NULL
) {
510 if (stat(dirent
->d_name
,&buf
) != 0)
511 perr("cannot stat in %s", ATJOB_DIR
);
513 /* We don't want directories
515 if (!S_ISREG(buf
.st_mode
))
518 if (sscanf(dirent
->d_name
,"%c%5lx%8lx",&queue
,&jobno
,&ctm
) != 3)
521 run_time
= (time_t) ctm
*60;
523 if ((S_IXUSR
& buf
.st_mode
) && (run_time
<=now
)) {
524 if (isupper(queue
) && (strcmp(batch_name
,dirent
->d_name
) > 0)) {
526 strlcpy(batch_name
, dirent
->d_name
, sizeof(batch_name
));
527 batch_uid
= buf
.st_uid
;
528 batch_gid
= buf
.st_gid
;
531 /* The file is executable and old enough
534 run_file(dirent
->d_name
, buf
.st_uid
, buf
.st_gid
);
536 /* Delete older files
538 if ((run_time
< now
) && !(S_IXUSR
& buf
.st_mode
) && (S_IRUSR
& buf
.st_mode
))
539 unlink(dirent
->d_name
);
541 /* run the single batch file, if any
543 if (run_batch
&& (gloadavg() < load_avg
))
544 run_file(batch_name
, batch_uid
, batch_gid
);
554 fprintf(stderr
, "usage: atrun [-l load_avg] [-d]\n");
556 syslog(LOG_ERR
, "usage: atrun [-l load_avg] [-d]");