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