xref: /netbsd-src/libexec/atrun/atrun.c (revision a5a68ff5f29de57339ca14f6c671c0a87714f1f8)
1 /*	$NetBSD: atrun.c,v 1.4 1997/10/07 10:49:16 mrg Exp $	*/
2 
3 /*
4  * atrun.c - run jobs queued by at; run with root privileges.
5  * Copyright (c) 1993 by Thomas Koenig
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. The name of the author(s) may not be used to endorse or promote
14  *    products derived from this software without specific prior written
15  *    permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 /* System Headers */
30 
31 #include <sys/types.h>
32 #include <sys/fcntl.h>
33 #include <sys/stat.h>
34 #include <sys/wait.h>
35 #include <dirent.h>
36 #include <errno.h>
37 #include <pwd.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 
47 #include <paths.h>
48 
49 /* Local headers */
50 
51 #define MAIN
52 #include "privs.h"
53 #include "pathnames.h"
54 #include "atrun.h"
55 
56 static void perr __P((const char *));
57 static int write_string __P((int, const char *));
58 static void run_file __P((const char *, uid_t));
59 int main __P((int, char *[]));
60 
61 /* File scope variables */
62 
63 static char *namep;
64 #ifndef lint
65 __RCSID("$NetBSD: atrun.c,v 1.4 1997/10/07 10:49:16 mrg Exp $");
66 #endif
67 
68 /* Local functions */
69 static void
70 perr(a)
71 	const char *a;
72 {
73 	syslog(LOG_ERR, "%s: %m", a);
74 	exit(EXIT_FAILURE);
75 }
76 
77 static int
78 write_string(fd, a)
79 	int fd;
80 	const char *a;
81 {
82 	return write(fd, a, strlen(a));
83 }
84 
85 static void
86 run_file(filename, uid)
87 	const char *filename;
88 	uid_t uid;
89 {
90 	/*
91 	 * Run a file by by spawning off a process which redirects I/O,
92 	 * spawns a subshell, then waits for it to complete and spawns another
93 	 * process to send mail to the user.
94 	 */
95 	pid_t pid;
96 	int fd_out, fd_in;
97 	int queue;
98 	char mailbuf[9];
99 	char *mailname = NULL;
100 	FILE *stream;
101 	int send_mail = 0;
102 	struct stat buf;
103 	off_t size;
104 	struct passwd *pentry;
105 	int fflags;
106 
107 	pid = fork();
108 	if (pid == -1)
109 		perr("Cannot fork");
110 	else if (pid > 0)
111 		return;
112 
113 	/*
114 	 * Let's see who we mail to.  Hopefully, we can read it from the
115 	 * command file; if not, send it to the owner, or, failing that, to
116 	 * root.
117 	 */
118 
119 	PRIV_START
120 
121 	    stream = fopen(filename, "r");
122 
123 	PRIV_END
124 
125 	pentry = getpwuid(uid);
126 	if (pentry == NULL)
127 		perr("UID not in password file!");
128 
129 	if (stream == NULL)
130 		perr("Cannot open input file");
131 
132 	if ((fd_in = dup(fileno(stream))) < 0)
133 		perr("Error duplicating input file descriptor");
134 
135 	if ((fflags = fcntl(fd_in, F_GETFD)) < 0)
136 		perr("Error in fcntl");
137 
138 	fcntl(fd_in, F_SETFD, fflags & ~FD_CLOEXEC);
139 
140 	if (fscanf(stream, "#! /bin/sh\n# mail %8s %d", mailbuf, &send_mail) == 2) {
141 		mailname = mailbuf;
142 	} else {
143 		mailname = pentry->pw_name;
144 	}
145 	fclose(stream);
146 	if (chdir(_PATH_ATSPOOL) < 0)
147 		perr("Cannot chdir to " _PATH_ATSPOOL);
148 
149 	/*
150 	 * Create a file to hold the output of the job we are  about to
151 	 * run. Write the mail header.
152 	 */
153 	if ((fd_out = open(filename,
154 		    O_WRONLY | O_CREAT | O_EXCL, S_IWUSR | S_IRUSR)) < 0)
155 		perr("Cannot create output file");
156 
157 	write_string(fd_out, "Subject: Output from your job ");
158 	write_string(fd_out, filename);
159 	write_string(fd_out, "\n\n");
160 	fstat(fd_out, &buf);
161 	size = buf.st_size;
162 
163 	close(STDIN_FILENO);
164 	close(STDOUT_FILENO);
165 	close(STDERR_FILENO);
166 
167 	pid = fork();
168 	if (pid < 0)
169 		perr("Error in fork");
170 	else if (pid == 0) {
171 		char *nul = NULL;
172 		char **nenvp = &nul;
173 
174 		/*
175 		 * Set up things for the child; we want standard input from
176 		 * the input file, and standard output and error sent to
177 		 * our output file.
178 		 */
179 
180 		if (lseek(fd_in, (off_t) 0, SEEK_SET) < 0)
181 			perr("Error in lseek");
182 
183 		if (dup(fd_in) != STDIN_FILENO)
184 			perr("Error in I/O redirection");
185 
186 		if (dup(fd_out) != STDOUT_FILENO)
187 			perr("Error in I/O redirection");
188 
189 		if (dup(fd_out) != STDERR_FILENO)
190 			perr("Error in I/O redirection");
191 
192 		close(fd_in);
193 		close(fd_out);
194 		if (chdir(_PATH_ATJOBS) < 0)
195 			perr("Cannot chdir to " _PATH_ATJOBS);
196 
197 		queue = *filename;
198 
199 		PRIV_START
200 
201 		    if (queue > 'b')
202 			nice(queue - 'b');
203 
204 		if (initgroups(pentry->pw_name, pentry->pw_gid) < 0)
205 			perr("Cannot init group list");
206 
207 		if (setgid(pentry->pw_gid) < 0)
208 			perr("Cannot change primary group");
209 
210 		if (setuid(uid) < 0)
211 			perr("Cannot set user id");
212 
213 		chdir("/");
214 
215 		if (execle("/bin/sh", "sh", (char *) NULL, nenvp) != 0)
216 			perr("Exec failed");
217 
218 		PRIV_END
219 	}
220 	/* We're the parent.  Let's wait. */
221 	close(fd_in);
222 	close(fd_out);
223 	waitpid(pid, (int *) NULL, 0);
224 
225 	stat(filename, &buf);
226 	if ((buf.st_size != size) || send_mail) {
227 		/* Fork off a child for sending mail */
228 		pid = fork();
229 		if (pid < 0)
230 			perr("Fork failed");
231 		else if (pid == 0) {
232 			if (open(filename, O_RDONLY) != STDIN_FILENO)
233 				perr("Cannot reopen output file");
234 
235 			execl(_PATH_SENDMAIL, _PATH_SENDMAIL, mailname,
236 			    (char *) NULL);
237 			perr("Exec failed");
238 		}
239 		waitpid(pid, (int *) NULL, 0);
240 	}
241 	unlink(filename);
242 	exit(EXIT_SUCCESS);
243 }
244 
245 /* Global functions */
246 
247 int
248 main(argc, argv)
249 	int argc;
250 	char *argv[];
251 {
252 	/*
253 	 * Browse through  _PATH_ATJOBS, checking all the jobfiles wether
254 	 * they should be executed and or deleted. The queue is coded into
255 	 * the first byte of the job filename, the date (in minutes since
256 	 * Eon) as a hex number in the following eight bytes, followed by
257 	 * a dot and a serial number.  A file which has not been executed
258 	 * yet is denoted by its execute - bit set.  For those files which
259 	 * are to be executed, run_file() is called, which forks off a
260 	 * child which takes care of I/O redirection, forks off another
261 	 * child for execution and yet another one, optionally, for sending
262 	 * mail.  Files which already have run are removed during the
263 	 * next invocation.
264 	 */
265 	DIR *spool;
266 	struct dirent *dirent;
267 	struct stat buf;
268 	int older;
269 	unsigned long ctm;
270 	char queue;
271 
272 	/*
273 	 * We don't need root privileges all the time; running under uid
274 	 * and gid daemon is fine.
275 	 */
276 
277 	RELINQUISH_PRIVS_ROOT(0) /* it's setuid root */
278 	openlog("atrun", LOG_PID, LOG_CRON);
279 
280 	namep = argv[0];
281 	if (chdir(_PATH_ATJOBS) != 0)
282 		perr("Cannot change to " _PATH_ATJOBS);
283 
284 	/*
285 	 * Main loop. Open spool directory for reading and look over all
286 	 * the files in there. If the filename indicates that the job
287 	 * should be run and the x bit is set, fork off a child which sets
288 	 * its user and group id to that of the files and exec a /bin/sh
289 	 * which executes the shell script. Unlink older files if they
290 	 * should no longer be run.  For deletion, their r bit has to be
291 	 * turned on.
292 	 */
293 	if ((spool = opendir(".")) == NULL)
294 		perr("Cannot read " _PATH_ATJOBS);
295 
296 	while ((dirent = readdir(spool)) != NULL) {
297 		double la;
298 
299 		if (stat(dirent->d_name, &buf) != 0)
300 			perr("Cannot stat in " _PATH_ATJOBS);
301 
302 		/* We don't want directories */
303 		if (!S_ISREG(buf.st_mode))
304 			continue;
305 
306 		if (sscanf(dirent->d_name, "%c%8lx", &queue, &ctm) != 2)
307 			continue;
308 
309 		if ((queue == 'b') && ((getloadavg(&la, 1) != 1) ||
310 		    (la > ATRUN_MAXLOAD)))
311 			continue;
312 
313 		older = (time_t) ctm *60 <= time(NULL);
314 
315 		/* The file is executable and old enough */
316 		if (older && (S_IXUSR & buf.st_mode)) {
317 			/*
318 			 * Now we know we want to run the file, we can turn
319 			 * off the execute bit
320 			 */
321 
322 			PRIV_START
323 
324 			    if (chmod(dirent->d_name, S_IRUSR) != 0)
325 				perr("Cannot change file permissions");
326 
327 			PRIV_END
328 
329 			run_file(dirent->d_name, buf.st_uid);
330 		}
331 		/* Delete older files */
332 		if (older && !(S_IXUSR & buf.st_mode) &&
333 		    (S_IRUSR & buf.st_mode))
334 			unlink(dirent->d_name);
335 	}
336 	closelog();
337 	exit(EXIT_SUCCESS);
338 }
339