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