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