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