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