indent(1): Support "f" and "F" floating constant suffixes.
[freebsd-src.git] / libexec / atrun / atrun.c
blob7b11e7bb1997c1a6dfe6c7388fa3d5ebcdd3de94
1 /*
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
7 * are met:
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
12 * permission.
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.
26 #ifndef lint
27 static const char rcsid[] =
28 "$FreeBSD$";
29 #endif /* not lint */
31 /* System Headers */
33 #include <sys/fcntl.h>
34 #include <sys/file.h>
35 #include <sys/types.h>
36 #include <sys/stat.h>
37 #ifdef __FreeBSD__
38 #include <sys/sysctl.h>
39 #endif
40 #include <sys/wait.h>
41 #include <sys/param.h>
42 #include <ctype.h>
43 #include <dirent.h>
44 #include <err.h>
45 #include <grp.h>
46 #include <pwd.h>
47 #include <signal.h>
48 #include <stdarg.h>
49 #include <stddef.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <syslog.h>
54 #include <time.h>
55 #include <unistd.h>
56 #ifdef __FreeBSD__
57 #include <paths.h>
58 #else
59 #include <getopt.h>
60 #endif
61 #ifdef LOGIN_CAP
62 #include <login_cap.h>
63 #endif
64 #ifdef PAM
65 #include <security/pam_appl.h>
66 #include <security/openpam.h>
67 #endif
69 /* Local headers */
71 #include "gloadavg.h"
72 #define MAIN
73 #include "privs.h"
75 /* Macros */
77 #ifndef ATJOB_DIR
78 #define ATJOB_DIR "/usr/spool/atjobs/"
79 #endif
81 #ifndef ATSPOOL_DIR
82 #define ATSPOOL_DIR "/usr/spool/atspool/"
83 #endif
85 #ifndef LOADAVG_MX
86 #define LOADAVG_MX 1.5
87 #endif
89 /* File scope variables */
91 static const char * const atrun = "atrun"; /* service name for syslog etc. */
92 static int debug = 0;
94 void perr(const char *fmt, ...);
95 void perrx(const char *fmt, ...);
96 static void usage(void);
98 /* Local functions */
99 static int
100 write_string(int fd, const char* a)
102 return write(fd, a, strlen(a));
105 #undef DEBUG_FORK
106 #ifdef DEBUG_FORK
107 static pid_t
108 myfork(void)
110 pid_t res;
111 res = fork();
112 if (res == 0)
113 kill(getpid(),SIGSTOP);
114 return res;
117 #define fork myfork
118 #endif
120 static void
121 run_file(const char *filename, uid_t uid, gid_t gid)
123 /* Run a file by spawning off a process which redirects I/O,
124 * spawns a subshell, then waits for it to complete and sends
125 * mail to the user.
127 pid_t pid;
128 int fd_out, fd_in;
129 int queue;
130 char mailbuf[MAXLOGNAME], fmt[64];
131 char *mailname = NULL;
132 FILE *stream;
133 int send_mail = 0;
134 struct stat buf, lbuf;
135 off_t size;
136 struct passwd *pentry;
137 int fflags;
138 long nuid;
139 long ngid;
140 #ifdef PAM
141 pam_handle_t *pamh = NULL;
142 int pam_err;
143 struct pam_conv pamc = {
144 .conv = openpam_nullconv,
145 .appdata_ptr = NULL
147 #endif
149 PRIV_START
151 if (chmod(filename, S_IRUSR) != 0)
153 perr("cannot change file permissions");
156 PRIV_END
158 pid = fork();
159 if (pid == -1)
160 perr("cannot fork");
162 else if (pid != 0)
163 return;
165 /* Let's see who we mail to. Hopefully, we can read it from
166 * the command file; if not, send it to the owner, or, failing that,
167 * to root.
170 pentry = getpwuid(uid);
171 if (pentry == NULL)
172 perrx("Userid %lu not found - aborting job %s",
173 (unsigned long) uid, filename);
175 #ifdef PAM
176 PRIV_START
178 pam_err = pam_start(atrun, pentry->pw_name, &pamc, &pamh);
179 if (pam_err != PAM_SUCCESS)
180 perrx("cannot start PAM: %s", pam_strerror(pamh, pam_err));
182 pam_err = pam_acct_mgmt(pamh, PAM_SILENT);
183 /* Expired password shouldn't prevent the job from running. */
184 if (pam_err != PAM_SUCCESS && pam_err != PAM_NEW_AUTHTOK_REQD)
185 perrx("Account %s (userid %lu) unavailable for job %s: %s",
186 pentry->pw_name, (unsigned long)uid,
187 filename, pam_strerror(pamh, pam_err));
189 pam_end(pamh, pam_err);
191 PRIV_END
192 #endif /* PAM */
194 PRIV_START
196 stream=fopen(filename, "r");
198 PRIV_END
200 if (stream == NULL)
201 perr("cannot open input file %s", filename);
203 if ((fd_in = dup(fileno(stream))) <0)
204 perr("error duplicating input file descriptor");
206 if (fstat(fd_in, &buf) == -1)
207 perr("error in fstat of input file descriptor");
209 if (lstat(filename, &lbuf) == -1)
210 perr("error in fstat of input file");
212 if (S_ISLNK(lbuf.st_mode))
213 perrx("Symbolic link encountered in job %s - aborting", filename);
215 if ((lbuf.st_dev != buf.st_dev) || (lbuf.st_ino != buf.st_ino) ||
216 (lbuf.st_uid != buf.st_uid) || (lbuf.st_gid != buf.st_gid) ||
217 (lbuf.st_size!=buf.st_size))
218 perrx("Somebody changed files from under us for job %s - aborting",
219 filename);
221 if (buf.st_nlink > 1)
222 perrx("Somebody is trying to run a linked script for job %s", filename);
224 if ((fflags = fcntl(fd_in, F_GETFD)) <0)
225 perr("error in fcntl");
227 fcntl(fd_in, F_SETFD, fflags & ~FD_CLOEXEC);
229 snprintf(fmt, sizeof(fmt),
230 "#!/bin/sh\n# atrun uid=%%ld gid=%%ld\n# mail %%%ds %%d",
231 MAXLOGNAME - 1);
233 if (fscanf(stream, fmt, &nuid, &ngid, mailbuf, &send_mail) != 4)
234 perrx("File %s is in wrong format - aborting", filename);
236 if (mailbuf[0] == '-')
237 perrx("Illegal mail name %s in %s", mailbuf, filename);
239 mailname = mailbuf;
241 if (nuid != uid)
242 perrx("Job %s - userid %ld does not match file uid %lu",
243 filename, nuid, (unsigned long)uid);
245 if (ngid != gid)
246 perrx("Job %s - groupid %ld does not match file gid %lu",
247 filename, ngid, (unsigned long)gid);
249 fclose(stream);
251 if (chdir(ATSPOOL_DIR) < 0)
252 perr("cannot chdir to %s", ATSPOOL_DIR);
254 /* Create a file to hold the output of the job we are about to run.
255 * Write the mail header.
257 if((fd_out=open(filename,
258 O_WRONLY | O_CREAT | O_EXCL, S_IWUSR | S_IRUSR)) < 0)
259 perr("cannot create output file");
261 write_string(fd_out, "Subject: Output from your job ");
262 write_string(fd_out, filename);
263 write_string(fd_out, "\n\n");
264 fstat(fd_out, &buf);
265 size = buf.st_size;
267 close(STDIN_FILENO);
268 close(STDOUT_FILENO);
269 close(STDERR_FILENO);
271 pid = fork();
272 if (pid < 0)
273 perr("error in fork");
275 else if (pid == 0)
277 char *nul = NULL;
278 char **nenvp = &nul;
280 /* Set up things for the child; we want standard input from the input file,
281 * and standard output and error sent to our output file.
284 if (lseek(fd_in, (off_t) 0, SEEK_SET) < 0)
285 perr("error in lseek");
287 if (dup(fd_in) != STDIN_FILENO)
288 perr("error in I/O redirection");
290 if (dup(fd_out) != STDOUT_FILENO)
291 perr("error in I/O redirection");
293 if (dup(fd_out) != STDERR_FILENO)
294 perr("error in I/O redirection");
296 close(fd_in);
297 close(fd_out);
298 if (chdir(ATJOB_DIR) < 0)
299 perr("cannot chdir to %s", ATJOB_DIR);
301 queue = *filename;
303 PRIV_START
305 nice(tolower(queue) - 'a');
307 #ifdef LOGIN_CAP
309 * For simplicity and safety, set all aspects of the user context
310 * except for a selected subset: Don't set priority, which was
311 * set based on the queue file name according to the tradition.
312 * Don't bother to set environment, including path vars, either
313 * because it will be discarded anyway. Although the job file
314 * should set umask, preset it here just in case.
316 if (setusercontext(NULL, pentry, uid, LOGIN_SETALL &
317 ~(LOGIN_SETPRIORITY | LOGIN_SETPATH | LOGIN_SETENV)) != 0)
318 exit(EXIT_FAILURE); /* setusercontext() logged the error */
319 #else /* LOGIN_CAP */
320 if (initgroups(pentry->pw_name,pentry->pw_gid))
321 perr("cannot init group access list");
323 if (setgid(gid) < 0 || setegid(pentry->pw_gid) < 0)
324 perr("cannot change group");
326 if (setlogin(pentry->pw_name))
327 perr("cannot set login name");
329 if (setuid(uid) < 0 || seteuid(uid) < 0)
330 perr("cannot set user id");
331 #endif /* LOGIN_CAP */
333 if (chdir(pentry->pw_dir))
334 chdir("/");
336 if(execle("/bin/sh","sh",(char *) NULL, nenvp) != 0)
337 perr("exec failed for /bin/sh");
339 PRIV_END
341 /* We're the parent. Let's wait.
343 close(fd_in);
344 close(fd_out);
345 waitpid(pid, (int *) NULL, 0);
347 /* Send mail. Unlink the output file first, so it is deleted after
348 * the run.
350 stat(filename, &buf);
351 if (open(filename, O_RDONLY) != STDIN_FILENO)
352 perr("open of jobfile failed");
354 unlink(filename);
355 if ((buf.st_size != size) || send_mail)
357 PRIV_START
359 #ifdef LOGIN_CAP
361 * This time set full context to run the mailer.
363 if (setusercontext(NULL, pentry, uid, LOGIN_SETALL) != 0)
364 exit(EXIT_FAILURE); /* setusercontext() logged the error */
365 #else /* LOGIN_CAP */
366 if (initgroups(pentry->pw_name,pentry->pw_gid))
367 perr("cannot init group access list");
369 if (setgid(gid) < 0 || setegid(pentry->pw_gid) < 0)
370 perr("cannot change group");
372 if (setlogin(pentry->pw_name))
373 perr("cannot set login name");
375 if (setuid(uid) < 0 || seteuid(uid) < 0)
376 perr("cannot set user id");
377 #endif /* LOGIN_CAP */
379 if (chdir(pentry->pw_dir))
380 chdir("/");
382 #ifdef __FreeBSD__
383 execl(_PATH_SENDMAIL, "sendmail", "-F", "Atrun Service",
384 "-odi", "-oem",
385 mailname, (char *) NULL);
386 #else
387 execl(MAIL_CMD, MAIL_CMD, mailname, (char *) NULL);
388 #endif
389 perr("exec failed for mail command");
391 PRIV_END
393 exit(EXIT_SUCCESS);
396 /* Global functions */
398 /* Needed in gloadavg.c */
399 void
400 perr(const char *fmt, ...)
402 const char * const fmtadd = ": %m";
403 char nfmt[strlen(fmt) + strlen(fmtadd) + 1];
404 va_list ap;
406 va_start(ap, fmt);
407 if (debug)
409 vwarn(fmt, ap);
411 else
413 snprintf(nfmt, sizeof(nfmt), "%s%s", fmt, fmtadd);
414 vsyslog(LOG_ERR, nfmt, ap);
416 va_end(ap);
418 exit(EXIT_FAILURE);
421 void
422 perrx(const char *fmt, ...)
424 va_list ap;
426 va_start(ap, fmt);
427 if (debug)
428 vwarnx(fmt, ap);
429 else
430 vsyslog(LOG_ERR, fmt, ap);
431 va_end(ap);
433 exit(EXIT_FAILURE);
437 main(int argc, char *argv[])
439 /* Browse through ATJOB_DIR, checking all the jobfiles wether they should
440 * be executed and or deleted. The queue is coded into the first byte of
441 * the job filename, the date (in minutes since Eon) as a hex number in the
442 * following eight bytes, followed by a dot and a serial number. A file
443 * which has not been executed yet is denoted by its execute - bit set.
444 * For those files which are to be executed, run_file() is called, which forks
445 * off a child which takes care of I/O redirection, forks off another child
446 * for execution and yet another one, optionally, for sending mail.
447 * Files which already have run are removed during the next invocation.
449 DIR *spool;
450 struct dirent *dirent;
451 struct stat buf;
452 unsigned long ctm;
453 unsigned long jobno;
454 char queue;
455 time_t now, run_time;
456 char batch_name[] = "Z2345678901234";
457 uid_t batch_uid;
458 gid_t batch_gid;
459 int c;
460 int run_batch;
461 #ifdef __FreeBSD__
462 size_t ncpusz;
463 double load_avg = -1;
464 int ncpu;
465 #else
466 double load_avg = LOADAVG_MX;
467 #endif
469 /* We don't need root privileges all the time; running under uid and gid daemon
470 * is fine.
473 RELINQUISH_PRIVS_ROOT(DAEMON_UID, DAEMON_GID)
475 openlog(atrun, LOG_PID, LOG_CRON);
477 opterr = 0;
478 while((c=getopt(argc, argv, "dl:"))!= -1)
480 switch (c)
482 case 'l':
483 if (sscanf(optarg, "%lf", &load_avg) != 1)
484 perr("garbled option -l");
485 #ifndef __FreeBSD__
486 if (load_avg <= 0.)
487 load_avg = LOADAVG_MX;
488 #endif
489 break;
491 case 'd':
492 debug ++;
493 break;
495 case '?':
496 default:
497 usage();
501 if (chdir(ATJOB_DIR) != 0)
502 perr("cannot change to %s", ATJOB_DIR);
504 #ifdef __FreeBSD__
505 if (load_avg <= 0.) {
506 ncpusz = sizeof(size_t);
507 if (sysctlbyname("hw.ncpu", &ncpu, &ncpusz, NULL, 0) < 0)
508 ncpu = 1;
509 load_avg = LOADAVG_MX * ncpu;
511 #endif
513 /* Main loop. Open spool directory for reading and look over all the
514 * files in there. If the filename indicates that the job should be run
515 * and the x bit is set, fork off a child which sets its user and group
516 * id to that of the files and exec a /bin/sh which executes the shell
517 * script. Unlink older files if they should no longer be run. For
518 * deletion, their r bit has to be turned on.
520 * Also, pick the oldest batch job to run, at most one per invocation of
521 * atrun.
523 if ((spool = opendir(".")) == NULL)
524 perr("cannot read %s", ATJOB_DIR);
526 if (flock(dirfd(spool), LOCK_EX) == -1)
527 perr("cannot lock %s", ATJOB_DIR);
529 now = time(NULL);
530 run_batch = 0;
531 batch_uid = (uid_t) -1;
532 batch_gid = (gid_t) -1;
534 while ((dirent = readdir(spool)) != NULL) {
535 if (stat(dirent->d_name,&buf) != 0)
536 perr("cannot stat in %s", ATJOB_DIR);
538 /* We don't want directories
540 if (!S_ISREG(buf.st_mode))
541 continue;
543 if (sscanf(dirent->d_name,"%c%5lx%8lx",&queue,&jobno,&ctm) != 3)
544 continue;
546 run_time = (time_t) ctm*60;
548 if ((S_IXUSR & buf.st_mode) && (run_time <=now)) {
549 if (isupper(queue) && (strcmp(batch_name,dirent->d_name) > 0)) {
550 run_batch = 1;
551 strlcpy(batch_name, dirent->d_name, sizeof(batch_name));
552 batch_uid = buf.st_uid;
553 batch_gid = buf.st_gid;
556 /* The file is executable and old enough
558 if (islower(queue))
559 run_file(dirent->d_name, buf.st_uid, buf.st_gid);
561 /* Delete older files
563 if ((run_time < now) && !(S_IXUSR & buf.st_mode) && (S_IRUSR & buf.st_mode))
564 unlink(dirent->d_name);
566 /* run the single batch file, if any
568 if (run_batch && (gloadavg() < load_avg))
569 run_file(batch_name, batch_uid, batch_gid);
571 if (flock(dirfd(spool), LOCK_UN) == -1)
572 perr("cannot unlock %s", ATJOB_DIR);
574 if (closedir(spool) == -1)
575 perr("cannot closedir %s", ATJOB_DIR);
577 closelog();
578 exit(EXIT_SUCCESS);
581 static void
582 usage(void)
584 if (debug)
585 fprintf(stderr, "usage: atrun [-l load_avg] [-d]\n");
586 else
587 syslog(LOG_ERR, "usage: atrun [-l load_avg] [-d]");
589 exit(EXIT_FAILURE);