atrun.c revision 1.7.8.1 1 /* $NetBSD: atrun.c,v 1.7.8.1 2000/06/26 00:38:45 simonb Exp $ */
2
3 /*
4 * atrun.c - run jobs queued by at; run with root privileges.
5 * Copyright (C) 1993, 1994 Thomas Koenig
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. The name of the author(s) may not be used to endorse or promote
13 * products derived from this software without specific prior written
14 * permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19 * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 * THEORY OF LIABILITY, WETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28 /* System Headers */
29
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <sys/wait.h>
33 #include <sys/param.h>
34 #include <ctype.h>
35 #include <dirent.h>
36 #include <errno.h>
37 #include <fcntl.h>
38 #include <pwd.h>
39 #include <grp.h>
40 #include <signal.h>
41 #include <stddef.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <time.h>
46 #include <unistd.h>
47 #include <syslog.h>
48 #include <utmp.h>
49
50 #include <paths.h>
51
52 /* Local headers */
53
54 #define MAIN
55 #include "privs.h"
56 #include "pathnames.h"
57 #include "atrun.h"
58
59 /* File scope variables */
60
61 static char *namep;
62 #if 0
63 static char rcsid[] = "$OpenBSD: atrun.c,v 1.7 1997/09/08 22:12:10 millert Exp $";
64 #else
65 __RCSID("$NetBSD: atrun.c,v 1.7.8.1 2000/06/26 00:38:45 simonb Exp $");
66 #endif
67
68 static int debug = 0;
69
70 /* Local functions */
71 static void perr __P((const char *));
72 static void perr2 __P((char *, char *));
73 static int write_string __P((int, const char *));
74 static void run_file __P((const char *, uid_t, gid_t));
75 static void become_user __P((struct passwd *, uid_t));
76
77 int main __P((int, char *[]));
78
79 static void
80 perr(a)
81 const char *a;
82 {
83 if (debug)
84 perror(a);
85 else
86 syslog(LOG_ERR, "%s: %m", a);
87
88 exit(EXIT_FAILURE);
89 }
90
91 static void
92 perr2(a, b)
93 char *a, *b;
94 {
95 if (debug) {
96 (void)fputs(a, stderr);
97 perror(b);
98 } else
99 syslog(LOG_ERR, "%s%s: %m", a, b);
100
101 exit(EXIT_FAILURE);
102 }
103
104 static int
105 write_string(fd, a)
106 int fd;
107 const char *a;
108 {
109 return(write(fd, a, strlen(a)));
110 }
111
112 static void
113 become_user(pentry, uid)
114 struct passwd *pentry;
115 uid_t uid;
116 {
117 if (initgroups(pentry->pw_name, pentry->pw_gid) < 0)
118 perr("Cannot init group list");
119
120 if (setegid(pentry->pw_gid) < 0 || setgid(pentry->pw_gid) < 0)
121 perr("Cannot change primary group");
122
123 if (setlogin(pentry->pw_name) < 0)
124 perr("Cannot set login name");
125
126 if (setuid(uid) < 0 || seteuid(uid) < 0)
127 perr("Cannot set user id");
128
129 if (chdir(pentry->pw_dir) < 0)
130 chdir("/");
131 }
132
133 static void
134 run_file(filename, uid, gid)
135 const char *filename;
136 uid_t uid;
137 gid_t gid;
138 {
139 /*
140 * Run a file by by spawning off a process which redirects I/O,
141 * spawns a subshell, then waits for it to complete and spawns another
142 * process to send mail to the user.
143 */
144 pid_t pid;
145 int fd_out, fd_in;
146 int queue;
147 char mailbuf[LOGIN_NAME_MAX], fmt[49];
148 char *mailname = NULL;
149 FILE *stream;
150 int send_mail = 0;
151 struct stat buf, lbuf;
152 off_t size;
153 struct passwd *pentry;
154 int fflags;
155 uid_t nuid;
156 gid_t ngid;
157
158 PRIV_START
159
160 if (chmod(filename, S_IRUSR) != 0)
161 perr("Cannot change file permissions");
162
163 PRIV_END
164
165 pid = fork();
166 if (pid == -1)
167 perr("Cannot fork");
168 else if (pid != 0)
169 return;
170
171 /*
172 * Let's see who we mail to. Hopefully, we can read it from the
173 * command file; if not, send it to the owner, or, failing that, to
174 * root.
175 */
176
177 pentry = getpwuid(uid);
178 if (pentry == NULL) {
179 syslog(LOG_ERR,"Userid %u not found - aborting job %s",
180 uid, filename);
181 exit(EXIT_FAILURE);
182 }
183 PRIV_START
184
185 stream = fopen(filename, "r");
186
187 PRIV_END
188
189 if (pentry->pw_expire && time(NULL) >= pentry->pw_expire) {
190 syslog(LOG_ERR, "Userid %u has expired - aborting job %s",
191 uid, filename);
192 exit(EXIT_FAILURE);
193 }
194
195 if (stream == NULL)
196 perr("Cannot open input file");
197
198 if ((fd_in = dup(fileno(stream))) < 0)
199 perr("Error duplicating input file descriptor");
200
201 if (fstat(fd_in, &buf) == -1)
202 perr("Error in fstat of input file descriptor");
203
204 PRIV_START
205
206 if (lstat(filename, &lbuf) == -1)
207 perr("Error in lstat of input file");
208
209 PRIV_END
210
211 if (S_ISLNK(lbuf.st_mode)) {
212 syslog(LOG_ERR, "Symbolic link encountered in job %s - aborting",
213 filename);
214 exit(EXIT_FAILURE);
215 }
216 if ((lbuf.st_dev != buf.st_dev) || (lbuf.st_ino != buf.st_ino) ||
217 (lbuf.st_uid != buf.st_uid) || (lbuf.st_gid != buf.st_gid) ||
218 (lbuf.st_size!=buf.st_size)) {
219 syslog(LOG_ERR, "Somebody changed files from under us for job %s - aborting", filename);
220 exit(EXIT_FAILURE);
221 }
222 if (buf.st_nlink > 1) {
223 syslog(LOG_ERR, "Somebody is trying to run a linked script for job %s",
224 filename);
225 exit(EXIT_FAILURE);
226 }
227 if ((fflags = fcntl(fd_in, F_GETFD)) < 0)
228 perr("Error in fcntl");
229
230 (void)fcntl(fd_in, F_SETFD, fflags & ~FD_CLOEXEC);
231
232 (void)snprintf(fmt, sizeof(fmt),
233 "#!/bin/sh\n# atrun uid=%%ld gid=%%ld\n# mail %%%ds %%d",
234 LOGIN_NAME_MAX);
235 if (fscanf(stream, fmt, &nuid, &ngid, mailbuf, &send_mail) != 4) {
236 syslog(LOG_ERR, "File %s is in wrong format - aborting",
237 filename);
238 exit(EXIT_FAILURE);
239 }
240 if (mailbuf[0] == '-') {
241 syslog(LOG_ERR, "illegal mail name %s in %s", mailbuf, filename);
242 exit(EXIT_FAILURE);
243 }
244 mailname = mailbuf;
245 if (nuid != uid) {
246 syslog(LOG_ERR, "Job %s - userid %u does not match file uid %u",
247 filename, nuid, uid);
248 exit(EXIT_FAILURE);
249 }
250 if (ngid != gid) {
251 syslog(LOG_ERR, "Job %s - groupid %u does not match file gid %u",
252 filename, ngid, gid);
253 exit(EXIT_FAILURE);
254 }
255 (void)fclose(stream);
256
257 PRIV_START
258
259 if (chdir(_PATH_ATSPOOL) < 0)
260 perr2("Cannot chdir to ", _PATH_ATSPOOL);
261
262 /*
263 * Create a file to hold the output of the job we are about to
264 * run. Write the mail header.
265 */
266
267 if ((fd_out = open(filename,
268 O_WRONLY | O_CREAT | O_EXCL, S_IWUSR | S_IRUSR)) < 0)
269 perr("Cannot create output file");
270
271 PRIV_END
272
273 write_string(fd_out, "To: ");
274 write_string(fd_out, mailname);
275 write_string(fd_out, "\nSubject: Output from your job ");
276 write_string(fd_out, filename);
277 write_string(fd_out, "\n\n");
278 if (fstat(fd_out, &buf) == -1)
279 perr("Error in fstat of output file descriptor");
280 size = buf.st_size;
281
282 (void)close(STDIN_FILENO);
283 (void)close(STDOUT_FILENO);
284 (void)close(STDERR_FILENO);
285
286 pid = fork();
287 if (pid < 0)
288 perr("Error in fork");
289 else if (pid == 0) {
290 char *nul = NULL;
291 char **nenvp = &nul;
292
293 /*
294 * Set up things for the child; we want standard input from
295 * the input file, and standard output and error sent to
296 * our output file.
297 */
298 if (lseek(fd_in, (off_t) 0, SEEK_SET) < 0)
299 perr("Error in lseek");
300
301 if (dup(fd_in) != STDIN_FILENO)
302 perr("Error in I/O redirection");
303
304 if (dup(fd_out) != STDOUT_FILENO)
305 perr("Error in I/O redirection");
306
307 if (dup(fd_out) != STDERR_FILENO)
308 perr("Error in I/O redirection");
309
310 (void)close(fd_in);
311 (void)close(fd_out);
312
313 PRIV_START
314
315 if (chdir(_PATH_ATJOBS) < 0)
316 perr2("Cannot chdir to ", _PATH_ATJOBS);
317
318 queue = *filename;
319
320 if (queue > 'b')
321 nice(queue - 'b');
322
323 become_user(pentry, uid);
324
325 if (execle("/bin/sh", "sh", (char *)NULL, nenvp) != 0)
326 perr("Exec failed for /bin/sh");
327
328 PRIV_END
329 }
330 /* We're the parent. Let's wait. */
331 (void)close(fd_in);
332 (void)close(fd_out);
333 waitpid(pid, (int *)NULL, 0);
334
335 /*
336 * Send mail. Unlink the output file first, so it is deleted
337 * after the run.
338 */
339 PRIV_START
340
341 if (stat(filename, &buf) == -1)
342 perr("Error in stat of output file");
343 if (open(filename, O_RDONLY) != STDIN_FILENO)
344 perr("Open of jobfile failed");
345
346 (void)unlink(filename);
347
348 PRIV_END
349
350 if ((buf.st_size != size) || send_mail) {
351 /* Fork off a child for sending mail */
352
353 PRIV_START
354
355 become_user(pentry, uid);
356
357 execl(_PATH_SENDMAIL, "sendmail", "-F", "Atrun Service",
358 "-odi", "-oem", "-t", (char *) NULL);
359 perr("Exec failed for mail command");
360
361 PRIV_END
362 }
363 exit(EXIT_SUCCESS);
364 }
365
366 /* Global functions */
367
368 int
369 main(argc, argv)
370 int argc;
371 char *argv[];
372 {
373 /*
374 * Browse through _PATH_ATJOBS, checking all the jobfiles wether
375 * they should be executed and or deleted. The queue is coded into
376 * the first byte of the job filename, the date (in minutes since
377 * Eon) as a hex number in the following eight bytes, followed by
378 * a dot and a serial number. A file which has not been executed
379 * yet is denoted by its execute - bit set. For those files which
380 * are to be executed, run_file() is called, which forks off a
381 * child which takes care of I/O redirection, forks off another
382 * child for execution and yet another one, optionally, for sending
383 * mail. Files which already have run are removed during the
384 * next invocation.
385 */
386 DIR *spool;
387 struct dirent *dirent;
388 struct stat buf;
389 unsigned long ctm;
390 int jobno;
391 char queue;
392 time_t now, run_time;
393 char batch_name[] = "Z2345678901234";
394 uid_t batch_uid;
395 gid_t batch_gid;
396 int c;
397 int run_batch;
398 double la, load_avg = ATRUN_MAXLOAD;
399
400 /*
401 * We don't need root privileges all the time; running under uid
402 * and gid nobody is fine except for privileged operations.
403 */
404 RELINQUISH_PRIVS_ROOT(NOBODY_UID, NOBODY_GID)
405
406 openlog("atrun", LOG_PID, LOG_CRON);
407
408 opterr = 0;
409 errno = 0;
410 while ((c = getopt(argc, argv, "dl:")) != -1) {
411 switch (c) {
412 case 'l':
413 if (sscanf(optarg, "%lf", &load_avg) != 1)
414 perr("garbled option -l");
415 if (load_avg <= 0.)
416 load_avg = ATRUN_MAXLOAD;
417 break;
418
419 case 'd':
420 debug++;
421 break;
422
423 case '?':
424 perr("unknown option");
425 break;
426
427 default:
428 perr("idiotic option - aborted");
429 break;
430 }
431 }
432
433 namep = argv[0];
434
435 PRIV_START
436
437 if (chdir(_PATH_ATJOBS) != 0)
438 perr2("Cannot change to ", _PATH_ATJOBS);
439
440
441 /*
442 * Main loop. Open spool directory for reading and look over all
443 * the files in there. If the filename indicates that the job
444 * should be run and the x bit is set, fork off a child which sets
445 * its user and group id to that of the files and exec a /bin/sh
446 * which executes the shell script. Unlink older files if they
447 * should no longer be run. For deletion, their r bit has to be
448 * turned on.
449 *
450 * Also, pick the oldest batch job to run, at most one per
451 * invocation of atrun.
452 */
453 if ((spool = opendir(".")) == NULL)
454 perr2("Cannot read ", _PATH_ATJOBS);
455
456 PRIV_END
457
458 now = time(NULL);
459 run_batch = 0;
460 batch_uid = (uid_t) -1;
461 batch_gid = (gid_t) -1;
462
463 while ((dirent = readdir(spool)) != NULL) {
464 PRIV_START
465
466 if (stat(dirent->d_name, &buf) != 0)
467 perr2("Cannot stat in ", _PATH_ATJOBS);
468
469 PRIV_END
470
471 /* We don't want directories */
472 if (!S_ISREG(buf.st_mode))
473 continue;
474
475 if (sscanf(dirent->d_name, "%c%5x%8lx", &queue, &jobno, &ctm) != 3)
476 continue;
477
478 run_time = (time_t) ctm * 60;
479
480 if ((S_IXUSR & buf.st_mode) && (run_time <= now)) {
481 if (isupper(queue) &&
482 (strcmp(batch_name, dirent->d_name) > 0)) {
483 run_batch = 1;
484 (void)strncpy(batch_name, dirent->d_name,
485 sizeof(batch_name));
486 batch_uid = buf.st_uid;
487 batch_gid = buf.st_gid;
488 }
489
490 /* The file is executable and old enough */
491 if (islower(queue))
492 run_file(dirent->d_name, buf.st_uid, buf.st_gid);
493 }
494
495 /* Delete older files */
496 if ((run_time < now) && !(S_IXUSR & buf.st_mode) &&
497 (S_IRUSR & buf.st_mode)) {
498 PRIV_START
499
500 (void)unlink(dirent->d_name);
501
502 PRIV_END
503 }
504 }
505
506 /* Run the single batch file, if any */
507 if (run_batch && ((getloadavg(&la, 1) == 1) && la < load_avg))
508 run_file(batch_name, batch_uid, batch_gid);
509
510 closelog();
511 exit(EXIT_SUCCESS);
512 }
513