]> git.saurik.com Git - apple/system_cmds.git/blame - atrun.tproj/atrun.c
system_cmds-597.1.1.tar.gz
[apple/system_cmds.git] / atrun.tproj / atrun.c
CommitLineData
2fc1e207
A
1/*
2 * atrun.c - run jobs queued by at; run with root privileges.
3 * Copyright (C) 1993, 1994 Thomas Koenig
1815bff5
A
4 *
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.
13 *
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.
2fc1e207 17 * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
1815bff5
A
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.
24 */
25
2fc1e207
A
26#ifndef lint
27static const char rcsid[] =
fc6d9e4b 28 "$FreeBSD: src/libexec/atrun/atrun.c,v 1.27 2009/12/25 10:30:54 ed Exp $";
2fc1e207
A
29#endif /* not lint */
30
1815bff5
A
31/* System Headers */
32
33#include <sys/fcntl.h>
34#include <sys/types.h>
35#include <sys/stat.h>
36#include <sys/wait.h>
2fc1e207
A
37#include <sys/param.h>
38#include <ctype.h>
1815bff5 39#include <dirent.h>
2fc1e207
A
40#include <err.h>
41#include <grp.h>
1815bff5
A
42#include <pwd.h>
43#include <signal.h>
fc6d9e4b 44#include <stdarg.h>
1815bff5
A
45#include <stddef.h>
46#include <stdio.h>
47#include <stdlib.h>
48#include <string.h>
2fc1e207 49#include <syslog.h>
1815bff5
A
50#include <time.h>
51#include <unistd.h>
2fc1e207 52#if 1
83f6dbe8 53#include <paths.h>
2fc1e207
A
54#else
55#include <getopt.h>
56#endif
fc6d9e4b
A
57#ifdef LOGIN_CAP
58#include <login_cap.h>
59#endif
60#ifdef PAM
61#include <security/pam_appl.h>
62#include <security/openpam.h>
34d340d7 63#endif
1815bff5
A
64
65/* Local headers */
66
67#define MAIN
68#include "privs.h"
69#include "pathnames.h"
fc6d9e4b 70
2fc1e207
A
71/* Macros */
72
73#ifndef ATJOB_DIR
74#define ATJOB_DIR _PATH_ATJOBS
75#endif
76
77#ifndef ATSPOOL_DIR
78#define ATSPOOL_DIR _PATH_ATSPOOL
79#endif
80
81#ifndef LOADAVG_MX
82#define LOADAVG_MX 1.5
83#endif
1815bff5
A
84
85/* File scope variables */
86
fc6d9e4b 87static const char * const atrun = "atrun"; /* service name for syslog etc. */
2fc1e207
A
88static int debug = 0;
89
fc6d9e4b
A
90void perr(const char *fmt, ...);
91void perrx(const char *fmt, ...);
2fc1e207 92static void usage(void);
1815bff5
A
93
94/* Local functions */
2fc1e207
A
95static int
96write_string(int fd, const char* a)
1815bff5 97{
2fc1e207 98 return write(fd, a, strlen(a));
1815bff5
A
99}
100
2fc1e207
A
101#undef DEBUG_FORK
102#ifdef DEBUG_FORK
103static pid_t
104myfork(void)
1815bff5 105{
2fc1e207
A
106 pid_t res;
107 res = fork();
108 if (res == 0)
109 kill(getpid(),SIGSTOP);
110 return res;
1815bff5
A
111}
112
2fc1e207
A
113#define fork myfork
114#endif
115
1815bff5 116static void
2fc1e207 117run_file(const char *filename, uid_t uid, gid_t gid)
1815bff5 118{
2fc1e207
A
119/* Run a file by spawning off a process which redirects I/O,
120 * spawns a subshell, then waits for it to complete and sends
121 * mail to the user.
122 */
123 pid_t pid;
124 int fd_out, fd_in;
125 int queue;
fc6d9e4b 126 char mailbuf[MAXLOGNAME], fmt[64];
2fc1e207
A
127 char *mailname = NULL;
128 FILE *stream;
129 int send_mail = 0;
130 struct stat buf, lbuf;
131 off_t size;
132 struct passwd *pentry;
133 int fflags;
134 long nuid;
135 long ngid;
fc6d9e4b
A
136#ifdef PAM
137 pam_handle_t *pamh = NULL;
138 int pam_err;
139 struct pam_conv pamc = {
140 .conv = openpam_nullconv,
141 .appdata_ptr = NULL
142 };
143#endif
2fc1e207
A
144
145 PRIV_START
146
147 if (chmod(filename, S_IRUSR) != 0)
148 {
149 perr("cannot change file permissions");
150 }
151
152 PRIV_END
153
154 pid = fork();
155 if (pid == -1)
156 perr("cannot fork");
157
158 else if (pid != 0)
159 return;
160
34d340d7
A
161#ifdef __APPLE__
162 {
163 pid_t pg = setsid();
164 if (pg == -1) syslog(LOG_ERR,"setsid() failed: %m");
165 }
166#endif
167
2fc1e207
A
168 /* Let's see who we mail to. Hopefully, we can read it from
169 * the command file; if not, send it to the owner, or, failing that,
170 * to root.
171 */
172
173 pentry = getpwuid(uid);
174 if (pentry == NULL)
fc6d9e4b
A
175 perrx("Userid %lu not found - aborting job %s",
176 (unsigned long) uid, filename);
177
178#ifdef PAM
2fc1e207
A
179 PRIV_START
180
fc6d9e4b
A
181 pam_err = pam_start(atrun, pentry->pw_name, &pamc, &pamh);
182 if (pam_err != PAM_SUCCESS)
183 perrx("cannot start PAM: %s", pam_strerror(pamh, pam_err));
184
185 pam_err = pam_acct_mgmt(pamh, PAM_SILENT);
186 /* Expired password shouldn't prevent the job from running. */
187 if (pam_err != PAM_SUCCESS && pam_err != PAM_NEW_AUTHTOK_REQD)
188 perrx("Account %s (userid %lu) unavailable for job %s: %s",
189 pentry->pw_name, (unsigned long)uid,
190 filename, pam_strerror(pamh, pam_err));
191
192 pam_end(pamh, pam_err);
2fc1e207
A
193
194 PRIV_END
fc6d9e4b 195#endif /* PAM */
2fc1e207 196
fc6d9e4b
A
197 PRIV_START
198
199 stream=fopen(filename, "r");
200
201 PRIV_END
1815bff5 202
2fc1e207
A
203 if (stream == NULL)
204 perr("cannot open input file");
1815bff5 205
2fc1e207
A
206 if ((fd_in = dup(fileno(stream))) <0)
207 perr("error duplicating input file descriptor");
1815bff5 208
2fc1e207
A
209 if (fstat(fd_in, &buf) == -1)
210 perr("error in fstat of input file descriptor");
1815bff5 211
2fc1e207
A
212 if (lstat(filename, &lbuf) == -1)
213 perr("error in fstat of input file");
1815bff5 214
fc6d9e4b
A
215 if (S_ISLNK(lbuf.st_mode))
216 perrx("Symbolic link encountered in job %s - aborting", filename);
217
2fc1e207
A
218 if ((lbuf.st_dev != buf.st_dev) || (lbuf.st_ino != buf.st_ino) ||
219 (lbuf.st_uid != buf.st_uid) || (lbuf.st_gid != buf.st_gid) ||
fc6d9e4b
A
220 (lbuf.st_size!=buf.st_size))
221 perrx("Somebody changed files from under us for job %s - aborting",
2fc1e207 222 filename);
fc6d9e4b
A
223
224 if (buf.st_nlink > 1)
225 perrx("Somebody is trying to run a linked script for job %s", filename);
226
2fc1e207
A
227 if ((fflags = fcntl(fd_in, F_GETFD)) <0)
228 perr("error in fcntl");
1815bff5 229
2fc1e207 230 fcntl(fd_in, F_SETFD, fflags & ~FD_CLOEXEC);
1815bff5 231
fc6d9e4b
A
232 snprintf(fmt, sizeof(fmt),
233 "#!/bin/sh\n# atrun uid=%%ld gid=%%ld\n# mail %%%ds %%d",
234 MAXLOGNAME - 1);
235
236 if (fscanf(stream, fmt, &nuid, &ngid, mailbuf, &send_mail) != 4)
237 perrx("File %s is in wrong format - aborting", filename);
238
239 if (mailbuf[0] == '-')
240 perrx("Illegal mail name %s in %s", mailbuf, filename);
241
2fc1e207 242 mailname = mailbuf;
fc6d9e4b
A
243
244 if (nuid != uid)
245 perrx("Job %s - userid %ld does not match file uid %lu",
2fc1e207 246 filename, nuid, (unsigned long)uid);
fc6d9e4b
A
247
248 if (ngid != gid)
249 perrx("Job %s - groupid %ld does not match file gid %lu",
2fc1e207 250 filename, ngid, (unsigned long)gid);
fc6d9e4b 251
2fc1e207 252 fclose(stream);
fc6d9e4b 253
2fc1e207 254 if (chdir(ATSPOOL_DIR) < 0)
fc6d9e4b 255 perr("cannot chdir to %s", ATSPOOL_DIR);
2fc1e207
A
256
257 /* Create a file to hold the output of the job we are about to run.
258 * Write the mail header.
259 */
260 if((fd_out=open(filename,
261 O_WRONLY | O_CREAT | O_EXCL, S_IWUSR | S_IRUSR)) < 0)
262 perr("cannot create output file");
263
264 write_string(fd_out, "Subject: Output from your job ");
265 write_string(fd_out, filename);
266 write_string(fd_out, "\n\n");
267 fstat(fd_out, &buf);
268 size = buf.st_size;
269
270 close(STDIN_FILENO);
271 close(STDOUT_FILENO);
272 close(STDERR_FILENO);
273
274 pid = fork();
275 if (pid < 0)
276 perr("error in fork");
277
278 else if (pid == 0)
279 {
280 char *nul = NULL;
281 char **nenvp = &nul;
282
283 /* Set up things for the child; we want standard input from the input file,
284 * and standard output and error sent to our output file.
285 */
0e393d50 286
2fc1e207
A
287 if (lseek(fd_in, (off_t) 0, SEEK_SET) < 0)
288 perr("error in lseek");
0e393d50 289
2fc1e207
A
290 if (dup(fd_in) != STDIN_FILENO)
291 perr("error in I/O redirection");
292
293 if (dup(fd_out) != STDOUT_FILENO)
294 perr("error in I/O redirection");
295
296 if (dup(fd_out) != STDERR_FILENO)
297 perr("error in I/O redirection");
1815bff5 298
2fc1e207
A
299 close(fd_in);
300 close(fd_out);
301 if (chdir(ATJOB_DIR) < 0)
fc6d9e4b 302 perr("cannot chdir to %s", ATJOB_DIR);
1815bff5 303
2fc1e207 304 queue = *filename;
1815bff5 305
2fc1e207 306 PRIV_START
1815bff5 307
2fc1e207
A
308 nice(tolower(queue) - 'a');
309
fc6d9e4b
A
310#ifdef LOGIN_CAP
311 /*
312 * For simplicity and safety, set all aspects of the user context
313 * except for a selected subset: Don't set priority, which was
314 * set based on the queue file name according to the tradition.
315 * Don't bother to set environment, including path vars, either
316 * because it will be discarded anyway. Although the job file
317 * should set umask, preset it here just in case.
318 */
319 if (setusercontext(NULL, pentry, uid, LOGIN_SETALL &
320 ~(LOGIN_SETPRIORITY | LOGIN_SETPATH | LOGIN_SETENV)) != 0)
321 exit(EXIT_FAILURE); /* setusercontext() logged the error */
322#else /* LOGIN_CAP */
2fc1e207
A
323 if (setgid(gid) < 0 || setegid(pentry->pw_gid) < 0)
324 perr("cannot change group");
1815bff5 325
34d340d7 326 if (initgroups(pentry->pw_name,pentry->pw_gid))
fc6d9e4b 327 perr("cannot init group access list");
34d340d7 328
2fc1e207
A
329 if (setlogin(pentry->pw_name))
330 perr("cannot set login name");
1815bff5 331
2fc1e207
A
332 if (setuid(uid) < 0 || seteuid(uid) < 0)
333 perr("cannot set user id");
fc6d9e4b 334#endif /* LOGIN_CAP */
1815bff5 335
2fc1e207
A
336 if (chdir(pentry->pw_dir))
337 chdir("/");
1815bff5 338
2fc1e207
A
339 if(execle("/bin/sh","sh",(char *) NULL, nenvp) != 0)
340 perr("exec failed for /bin/sh");
1815bff5 341
2fc1e207
A
342 PRIV_END
343 }
344 /* We're the parent. Let's wait.
345 */
346 close(fd_in);
347 close(fd_out);
348 waitpid(pid, (int *) NULL, 0);
349
350 /* Send mail. Unlink the output file first, so it is deleted after
351 * the run.
352 */
353 stat(filename, &buf);
354 if (open(filename, O_RDONLY) != STDIN_FILENO)
355 perr("open of jobfile failed");
356
357 unlink(filename);
358 if ((buf.st_size != size) || send_mail)
359 {
360 PRIV_START
1815bff5 361
fc6d9e4b
A
362#ifdef LOGIN_CAP
363 /*
364 * This time set full context to run the mailer.
365 */
366 if (setusercontext(NULL, pentry, uid, LOGIN_SETALL) != 0)
367 exit(EXIT_FAILURE); /* setusercontext() logged the error */
368#else /* LOGIN_CAP */
2fc1e207
A
369 if (setgid(gid) < 0 || setegid(pentry->pw_gid) < 0)
370 perr("cannot change group");
1815bff5 371
34d340d7 372 if (initgroups(pentry->pw_name,pentry->pw_gid))
fc6d9e4b 373 perr("cannot init group access list");
34d340d7 374
2fc1e207
A
375 if (setlogin(pentry->pw_name))
376 perr("cannot set login name");
1815bff5 377
2fc1e207
A
378 if (setuid(uid) < 0 || seteuid(uid) < 0)
379 perr("cannot set user id");
fc6d9e4b 380#endif /* LOGIN_CAP */
1815bff5 381
2fc1e207 382 if (chdir(pentry->pw_dir))
1815bff5
A
383 chdir("/");
384
2fc1e207
A
385#if 1
386 execl(_PATH_SENDMAIL, "sendmail", "-F", "Atrun Service",
387 "-odi", "-oem",
388 mailname, (char *) NULL);
389#else
390 execl(MAIL_CMD, MAIL_CMD, mailname, (char *) NULL);
391#endif
392 perr("exec failed for mail command");
1815bff5 393
2fc1e207
A
394 PRIV_END
395 }
396 exit(EXIT_SUCCESS);
1815bff5
A
397}
398
399/* Global functions */
400
2fc1e207
A
401/* Needed in gloadavg.c */
402void
fc6d9e4b 403perr(const char *fmt, ...)
2fc1e207 404{
fc6d9e4b
A
405 const char * const fmtadd = ": %m";
406 char nfmt[strlen(fmt) + strlen(fmtadd) + 1];
407 va_list ap;
408
409 va_start(ap, fmt);
2fc1e207
A
410 if (debug)
411 {
fc6d9e4b 412 vwarn(fmt, ap);
2fc1e207
A
413 }
414 else
fc6d9e4b
A
415 {
416 snprintf(nfmt, sizeof(nfmt), "%s%s", fmt, fmtadd);
417 vsyslog(LOG_ERR, nfmt, ap);
418 }
419 va_end(ap);
420
421 exit(EXIT_FAILURE);
422}
423
424void
425perrx(const char *fmt, ...)
426{
427 va_list ap;
428
429 va_start(ap, fmt);
430 if (debug)
431 vwarnx(fmt, ap);
432 else
433 vsyslog(LOG_ERR, fmt, ap);
434 va_end(ap);
2fc1e207
A
435
436 exit(EXIT_FAILURE);
437}
438
1815bff5 439int
2fc1e207 440main(int argc, char *argv[])
1815bff5 441{
2fc1e207
A
442/* Browse through ATJOB_DIR, checking all the jobfiles wether they should
443 * be executed and or deleted. The queue is coded into the first byte of
444 * the job filename, the date (in minutes since Eon) as a hex number in the
445 * following eight bytes, followed by a dot and a serial number. A file
446 * which has not been executed yet is denoted by its execute - bit set.
447 * For those files which are to be executed, run_file() is called, which forks
448 * off a child which takes care of I/O redirection, forks off another child
449 * for execution and yet another one, optionally, for sending mail.
450 * Files which already have run are removed during the next invocation.
451 */
452 DIR *spool;
453 struct dirent *dirent;
454 struct stat buf;
455 unsigned long ctm;
456 unsigned long jobno;
457 char queue;
458 time_t now, run_time;
459 char batch_name[] = "Z2345678901234";
460 uid_t batch_uid;
461 gid_t batch_gid;
462 int c;
463 int run_batch;
464 double load_avg = LOADAVG_MX, la;
465
466/* We don't need root privileges all the time; running under uid and gid daemon
467 * is fine.
468 */
469
470 RELINQUISH_PRIVS_ROOT(DAEMON_UID, DAEMON_GID)
471
fc6d9e4b 472 openlog(atrun, LOG_PID, LOG_CRON);
2fc1e207
A
473
474 opterr = 0;
475 while((c=getopt(argc, argv, "dl:"))!= -1)
476 {
477 switch (c)
478 {
479 case 'l':
480 if (sscanf(optarg, "%lf", &load_avg) != 1)
481 perr("garbled option -l");
482 if (load_avg <= 0.)
483 load_avg = LOADAVG_MX;
484 break;
485
486 case 'd':
487 debug ++;
488 break;
489
490 case '?':
491 default:
492 usage();
493 }
494 }
495
496 if (chdir(ATJOB_DIR) != 0)
fc6d9e4b 497 perr("cannot change to %s", ATJOB_DIR);
2fc1e207
A
498
499 /* Main loop. Open spool directory for reading and look over all the
500 * files in there. If the filename indicates that the job should be run
501 * and the x bit is set, fork off a child which sets its user and group
502 * id to that of the files and exec a /bin/sh which executes the shell
503 * script. Unlink older files if they should no longer be run. For
504 * deletion, their r bit has to be turned on.
505 *
506 * Also, pick the oldest batch job to run, at most one per invocation of
507 * atrun.
508 */
509 if ((spool = opendir(".")) == NULL)
fc6d9e4b 510 perr("cannot read %s", ATJOB_DIR);
2fc1e207
A
511
512 now = time(NULL);
513 run_batch = 0;
514 batch_uid = (uid_t) -1;
515 batch_gid = (gid_t) -1;
516
517 while ((dirent = readdir(spool)) != NULL) {
518 if (stat(dirent->d_name,&buf) != 0)
fc6d9e4b 519 perr("cannot stat in %s", ATJOB_DIR);
2fc1e207
A
520
521 /* We don't want directories
1815bff5 522 */
2fc1e207
A
523 if (!S_ISREG(buf.st_mode))
524 continue;
525
526 if (sscanf(dirent->d_name,"%c%5lx%8lx",&queue,&jobno,&ctm) != 3)
527 continue;
528
529 run_time = (time_t) ctm*60;
530
531 if ((S_IXUSR & buf.st_mode) && (run_time <=now)) {
fc6d9e4b 532 if ((isupper(queue) || queue == 'b') && (strcmp(batch_name,dirent->d_name) > 0)) {
2fc1e207 533 run_batch = 1;
fc6d9e4b 534 strlcpy(batch_name, dirent->d_name, sizeof(batch_name));
2fc1e207
A
535 batch_uid = buf.st_uid;
536 batch_gid = buf.st_gid;
537 }
538
539 /* The file is executable and old enough
1815bff5 540 */
2fc1e207
A
541 if (islower(queue))
542 run_file(dirent->d_name, buf.st_uid, buf.st_gid);
543 }
544 /* Delete older files
1815bff5 545 */
2fc1e207
A
546 if ((run_time < now) && !(S_IXUSR & buf.st_mode) && (S_IRUSR & buf.st_mode))
547 unlink(dirent->d_name);
548 }
549 /* run the single batch file, if any
550 */
551 if (run_batch && (getloadavg(&la, 1) == 1) && la < load_avg)
552 run_file(batch_name, batch_uid, batch_gid);
553
554 closelog();
34d340d7
A
555#if __APPLE__
556 // allow enough time for child processes to call setsid(2)
557 sleep(1);
558#endif
2fc1e207
A
559 exit(EXIT_SUCCESS);
560}
83f6dbe8 561
2fc1e207
A
562static void
563usage(void)
564{
565 if (debug)
566 fprintf(stderr, "usage: atrun [-l load_avg] [-d]\n");
567 else
568 syslog(LOG_ERR, "usage: atrun [-l load_avg] [-d]");
83f6dbe8 569
2fc1e207 570 exit(EXIT_FAILURE);
1815bff5 571}