xref: /dragonfly/libexec/atrun/atrun.c (revision c9f721c2)
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.5 2004/09/20 19:32:19 joerg 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 #include <paths.h>
51 
52 #if (MAXLOGNAME-1) > UT_NAMESIZE
53 #define LOGNAMESIZE UT_NAMESIZE
54 #else
55 #define LOGNAMESIZE (MAXLOGNAME-1)
56 #endif
57 
58 /* Local headers */
59 
60 #include "gloadavg.h"
61 #include "privs.h"
62 
63 /* Macros */
64 
65 #ifndef ATJOB_DIR
66 #define ATJOB_DIR "/usr/spool/atjobs/"
67 #endif
68 
69 #ifndef ATSPOOL_DIR
70 #define ATSPOOL_DIR "/usr/spool/atspool/"
71 #endif
72 
73 #ifndef LOADAVG_MX
74 #define LOADAVG_MX 1.5
75 #endif
76 
77 uid_t real_uid, effective_uid;
78 gid_t real_gid, effective_gid;
79 
80 /* File scope variables */
81 
82 static int debug = 0;
83 
84 void		perr(const char *a);
85 static void	usage(void);
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(void)
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     uid_t nuid;
128     gid_t 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 __DragonFly__
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, sizeof(fmt),
209 	"#!/bin/sh\n# atrun uid=%%ld gid=%%ld\n# mail %%%ds %%d",
210                           LOGNAMESIZE);
211     if (fscanf(stream, fmt, &nuid, &ngid, mailbuf, &send_mail) != 4) {
212 	syslog(LOG_ERR,"File %s is in wrong format - aborting", filename);
213 	exit(EXIT_FAILURE);
214     }
215     if (mailbuf[0] == '-') {
216 	syslog(LOG_ERR,"illegal mail name %s in %s",mailbuf,filename);
217 	exit(EXIT_FAILURE);
218     }
219     mailname = mailbuf;
220     if (nuid != uid) {
221 	syslog(LOG_ERR,"Job %s - userid %u does not match file uid %lu",
222 		filename, nuid, (unsigned long)uid);
223 	exit(EXIT_FAILURE);
224     }
225     if (ngid != gid) {
226 	syslog(LOG_ERR,"Job %s - groupid %u does not match file gid %lu",
227 		filename, ngid, (unsigned long)gid);
228 	exit(EXIT_FAILURE);
229     }
230     fclose(stream);
231     if (chdir(ATSPOOL_DIR) < 0)
232 	perr("cannot chdir to " ATSPOOL_DIR);
233 
234     /* Create a file to hold the output of the job we are about to run.
235      * Write the mail header.
236      */
237     if((fd_out=open(filename,
238 		O_WRONLY | O_CREAT | O_EXCL, S_IWUSR | S_IRUSR)) < 0)
239 	perr("cannot create output file");
240 
241     write_string(fd_out, "Subject: Output from your job ");
242     write_string(fd_out, filename);
243     write_string(fd_out, "\n\n");
244     fstat(fd_out, &buf);
245     size = buf.st_size;
246 
247     close(STDIN_FILENO);
248     close(STDOUT_FILENO);
249     close(STDERR_FILENO);
250 
251     pid = fork();
252     if (pid < 0)
253 	perr("error in fork");
254 
255     else if (pid == 0)
256     {
257 	char *nul = NULL;
258 	char **nenvp = &nul;
259 
260 	/* Set up things for the child; we want standard input from the input file,
261 	 * and standard output and error sent to our output file.
262 	 */
263 
264 	if (lseek(fd_in, (off_t) 0, SEEK_SET) < 0)
265 	    perr("error in lseek");
266 
267 	if (dup(fd_in) != STDIN_FILENO)
268 	    perr("error in I/O redirection");
269 
270 	if (dup(fd_out) != STDOUT_FILENO)
271 	    perr("error in I/O redirection");
272 
273 	if (dup(fd_out) != STDERR_FILENO)
274 	    perr("error in I/O redirection");
275 
276 	close(fd_in);
277 	close(fd_out);
278 	if (chdir(ATJOB_DIR) < 0)
279 	    perr("cannot chdir to " ATJOB_DIR);
280 
281 	queue = *filename;
282 
283 	PRIV_START
284 
285         nice(tolower(queue) - 'a');
286 
287 	if (initgroups(pentry->pw_name,pentry->pw_gid))
288 	    perr("cannot delete saved userids");
289 
290 	if (setgid(gid) < 0 || setegid(pentry->pw_gid) < 0)
291 	    perr("cannot change group");
292 
293 	if (setlogin(pentry->pw_name))
294 	    perr("cannot set login name");
295 
296 	if (setuid(uid) < 0 || seteuid(uid) < 0)
297 	    perr("cannot set user id");
298 
299 	if (chdir(pentry->pw_dir))
300 		chdir("/");
301 
302 	if(execle("/bin/sh","sh",(char *) NULL, nenvp) != 0)
303 	    perr("exec failed for /bin/sh");
304 
305 	PRIV_END
306     }
307     /* We're the parent.  Let's wait.
308      */
309     close(fd_in);
310     close(fd_out);
311     waitpid(pid, (int *) NULL, 0);
312 
313     /* Send mail.  Unlink the output file first, so it is deleted after
314      * the run.
315      */
316     stat(filename, &buf);
317     if (open(filename, O_RDONLY) != STDIN_FILENO)
318         perr("open of jobfile failed");
319 
320     unlink(filename);
321     if ((buf.st_size != size) || send_mail)
322     {
323 	PRIV_START
324 
325 	if (initgroups(pentry->pw_name,pentry->pw_gid))
326 	    perr("cannot delete saved userids");
327 
328 	if (setgid(gid) < 0 || setegid(pentry->pw_gid) < 0)
329 	    perr("cannot change group");
330 
331 	if (setlogin(pentry->pw_name))
332 	    perr("cannot set login name");
333 
334 	if (setuid(uid) < 0 || seteuid(uid) < 0)
335 	    perr("cannot set user id");
336 
337 	if (chdir(pentry->pw_dir))
338 		chdir("/");
339 
340 	execl(_PATH_SENDMAIL, "sendmail", "-F", "Atrun Service",
341 			"-odi", "-oem",
342 			mailname, (char *) NULL);
343 	    perr("exec failed for mail command");
344 
345 	PRIV_END
346     }
347     exit(EXIT_SUCCESS);
348 }
349 
350 /* Global functions */
351 
352 /* Needed in gloadavg.c */
353 void
354 perr(const char *a)
355 {
356     if (debug)
357     {
358 	warn("%s", a);
359     }
360     else
361 	syslog(LOG_ERR, "%s: %m", a);
362 
363     exit(EXIT_FAILURE);
364 }
365 
366 int
367 main(int argc, char *argv[])
368 {
369 /* Browse through  ATJOB_DIR, checking all the jobfiles wether they should
370  * be executed and or deleted. The queue is coded into the first byte of
371  * the job filename, the date (in minutes since Eon) as a hex number in the
372  * following eight bytes, followed by a dot and a serial number.  A file
373  * which has not been executed yet is denoted by its execute - bit set.
374  * For those files which are to be executed, run_file() is called, which forks
375  * off a child which takes care of I/O redirection, forks off another child
376  * for execution and yet another one, optionally, for sending mail.
377  * Files which already have run are removed during the next invocation.
378  */
379     DIR *spool;
380     struct dirent *dirent;
381     struct stat buf;
382     unsigned long ctm;
383     unsigned long jobno;
384     char queue;
385     time_t now, run_time;
386     char batch_name[] = "Z2345678901234";
387     uid_t batch_uid;
388     gid_t batch_gid;
389     int c;
390     int run_batch;
391     double load_avg = LOADAVG_MX;
392 
393 /* We don't need root privileges all the time; running under uid and gid daemon
394  * is fine.
395  */
396 
397     RELINQUISH_PRIVS_ROOT(DAEMON_UID, DAEMON_GID)
398 
399     openlog("atrun", LOG_PID, LOG_CRON);
400 
401     opterr = 0;
402     while((c=getopt(argc, argv, "dl:"))!= -1)
403     {
404 	switch (c)
405 	{
406 	case 'l':
407 	    if (sscanf(optarg, "%lf", &load_avg) != 1)
408 		perr("garbled option -l");
409 	    if (load_avg <= 0.)
410 		load_avg = LOADAVG_MX;
411 	    break;
412 
413 	case 'd':
414 	    debug ++;
415 	    break;
416 
417 	case '?':
418 	default:
419 	    usage();
420 	}
421     }
422 
423     if (chdir(ATJOB_DIR) != 0)
424 	perr("cannot change to " ATJOB_DIR);
425 
426     /* Main loop. Open spool directory for reading and look over all the
427      * files in there. If the filename indicates that the job should be run
428      * and the x bit is set, fork off a child which sets its user and group
429      * id to that of the files and exec a /bin/sh which executes the shell
430      * script. Unlink older files if they should no longer be run.  For
431      * deletion, their r bit has to be turned on.
432      *
433      * Also, pick the oldest batch job to run, at most one per invocation of
434      * atrun.
435      */
436     if ((spool = opendir(".")) == NULL)
437 	perr("cannot read " ATJOB_DIR);
438 
439     now = time(NULL);
440     run_batch = 0;
441     batch_uid = (uid_t) -1;
442     batch_gid = (gid_t) -1;
443 
444     while ((dirent = readdir(spool)) != NULL) {
445 	if (stat(dirent->d_name,&buf) != 0)
446 	    perr("cannot stat in " ATJOB_DIR);
447 
448 	/* We don't want directories
449 	 */
450 	if (!S_ISREG(buf.st_mode))
451 	    continue;
452 
453 	if (sscanf(dirent->d_name,"%c%5lx%8lx",&queue,&jobno,&ctm) != 3)
454 	    continue;
455 
456 	run_time = (time_t) ctm*60;
457 
458 	if ((S_IXUSR & buf.st_mode) && (run_time <=now)) {
459 	    if (isupper(queue) && (strcmp(batch_name,dirent->d_name) > 0)) {
460 		run_batch = 1;
461 		strncpy(batch_name, dirent->d_name, sizeof(batch_name));
462 		batch_uid = buf.st_uid;
463 		batch_gid = buf.st_gid;
464 	    }
465 
466 	/* The file is executable and old enough
467 	 */
468 	    if (islower(queue))
469 		run_file(dirent->d_name, buf.st_uid, buf.st_gid);
470 	}
471 	/*  Delete older files
472 	 */
473 	if ((run_time < now) && !(S_IXUSR & buf.st_mode) && (S_IRUSR & buf.st_mode))
474 	    unlink(dirent->d_name);
475     }
476     /* run the single batch file, if any
477     */
478     if (run_batch && (gloadavg() < load_avg))
479 	run_file(batch_name, batch_uid, batch_gid);
480 
481     closelog();
482     exit(EXIT_SUCCESS);
483 }
484 
485 static void
486 usage()
487 {
488     if (debug)
489 	fprintf(stderr, "usage: atrun [-l load_avg] [-d]\n");
490     else
491 	syslog(LOG_ERR, "usage: atrun [-l load_avg] [-d]");
492 
493     exit(EXIT_FAILURE);
494 }
495