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