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