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