atrun.c revision 251625
11195Srgrimes/*
239590Sjkh *  atrun.c - run jobs queued by at; run with root privileges.
337Srgrimes *  Copyright (C) 1993, 1994 Thomas Koenig
438103Speter *
538103Speter * Redistribution and use in source and binary forms, with or without
628205Sjkh * modification, are permitted provided that the following conditions
739562Smax * are met:
825184Sjkh * 1. Redistributions of source code must retain the above copyright
914662Sphk *    notice, this list of conditions and the following disclaimer.
1039562Smax * 2. The name of the author(s) may not be used to endorse or promote
1139562Smax *    products derived from this software without specific prior written
1238711Sjb *    permission.
1338711Sjb *
141734Sjkh * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
1517639Swosch * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
1617639Swosch * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
1737Srgrimes * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
181773Sjkh * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
1936902Sguido * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20147Srgrimes * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2127487Sasami * THEORY OF LIABILITY, WETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2227487Sasami * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
2335832Sache * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2431071Sbrian */
2531071Sbrian
2630589Sjmb#ifndef lint
2737Srgrimesstatic const char rcsid[] =
2817639Swosch  "$FreeBSD: head/libexec/atrun/atrun.c 251625 2013-06-11 18:43:27Z ghelmer $";
29263Srgrimes#endif /* not lint */
302779Srgrimes
318857Srgrimes/* System Headers */
32993Srgrimes
33263Srgrimes#include <sys/fcntl.h>
3411635Sache#include <sys/file.h>
356744Sache#include <sys/types.h>
366744Sache#include <sys/stat.h>
376744Sache#ifdef __FreeBSD__
386744Sache#include <sys/sysctl.h>
396744Sache#endif
4038103Speter#include <sys/wait.h>
4137Srgrimes#include <sys/param.h>
424487Sphk#include <ctype.h>
436717Sphk#include <dirent.h>
4439590Sjkh#include <err.h>
4539590Sjkh#include <grp.h>
4639590Sjkh#include <pwd.h>
4739590Sjkh#include <signal.h>
485948Sjkh#include <stdarg.h>
494487Sphk#include <stddef.h>
501759Sjkh#include <stdio.h>
519970Sbde#include <stdlib.h>
5236902Sguido#include <string.h>
539970Sbde#include <syslog.h>
541759Sjkh#include <time.h>
559970Sbde#include <unistd.h>
561759Sjkh#ifdef __FreeBSD__
5728266Spst#include <paths.h>
5817639Swosch#else
5917639Swosch#include <getopt.h>
6017639Swosch#endif
6117645Swosch#ifdef LOGIN_CAP
6238160Sjb#include <login_cap.h>
6336415Sjkoshy#endif
641759Sjkh#ifdef PAM
659970Sbde#include <security/pam_appl.h>
6638711Sjb#include <security/openpam.h>
671759Sjkh#endif
681731Sjkh
699970Sbde/* Local headers */
7037Srgrimes
719970Sbde#include "gloadavg.h"
7237Srgrimes#define MAIN
739970Sbde#include "privs.h"
7437Srgrimes
759970Sbde/* Macros */
7637Srgrimes
7737Srgrimes#ifndef ATJOB_DIR
7837Srgrimes#define ATJOB_DIR "/usr/spool/atjobs/"
7937Srgrimes#endif
809970Sbde
811731Sjkh#ifndef ATSPOOL_DIR
829970Sbde#define ATSPOOL_DIR "/usr/spool/atspool/"
831731Sjkh#endif
849970Sbde
856177Samurai#ifndef LOADAVG_MX
8630589Sjmb#define LOADAVG_MX 1.5
8730589Sjmb#endif
889970Sbde
8937Srgrimes/* File scope variables */
909970Sbde
91147Srgrimesstatic const char * const atrun = "atrun"; /* service name for syslog etc. */
929970Sbdestatic int debug = 0;
93147Srgrimes
949970Sbdevoid perr(const char *fmt, ...);
9537Srgrimesvoid perrx(const char *fmt, ...);
969970Sbdestatic void usage(void);
97288Srgrimes
989970Sbde/* Local functions */
99147Srgrimesstatic int
10013378Sachewrite_string(int fd, const char* a)
10113378Sache{
10217104Spst    return write(fd, a, strlen(a));
10317104Spst}
1049970Sbde
105147Srgrimes#undef DEBUG_FORK
1069970Sbde#ifdef DEBUG_FORK
10737Srgrimesstatic pid_t
1089970Sbdemyfork(void)
1091759Sjkh{
1101759Sjkh	pid_t res;
1119970Sbde	res = fork();
1129970Sbde	if (res == 0)
1131759Sjkh	    kill(getpid(),SIGSTOP);
11437Srgrimes	return res;
115147Srgrimes}
1163654Sphk
1173654Sphk#define fork myfork
11811635Sache#endif
11911849Sache
12011635Sachestatic void
12111635Sacherun_file(const char *filename, uid_t uid, gid_t gid)
12211635Sache{
12311853Speter/* Run a file by spawning off a process which redirects I/O,
12411853Speter * spawns a subshell, then waits for it to complete and sends
12511853Speter * mail to the user.
12611635Sache */
12711635Sache    pid_t pid;
1283654Sphk    int fd_out, fd_in;
1297129Srgrimes    int queue;
1307129Srgrimes    char mailbuf[MAXLOGNAME], fmt[64];
131410Srgrimes    char *mailname = NULL;
1327129Srgrimes    FILE *stream;
13311635Sache    int send_mail = 0;
13411635Sache    struct stat buf, lbuf;
13511635Sache    off_t size;
13611635Sache    struct passwd *pentry;
13711635Sache    int fflags;
13811635Sache    long nuid;
1397129Srgrimes    long ngid;
14011635Sache#ifdef PAM
14111635Sache    pam_handle_t *pamh = NULL;
14211635Sache    int pam_err;
14311635Sache    struct pam_conv pamc = {
14411635Sache	.conv = openpam_nullconv,
14511635Sache	.appdata_ptr = NULL
14611635Sache    };
14711635Sache#endif
14811635Sache
14911635Sache    PRIV_START
150147Srgrimes
15137Srgrimes    if (chmod(filename, S_IRUSR) != 0)
152    {
153	perr("cannot change file permissions");
154    }
155
156    PRIV_END
157
158    pid = fork();
159    if (pid == -1)
160	perr("cannot fork");
161
162    else if (pid != 0)
163	return;
164
165    /* Let's see who we mail to.  Hopefully, we can read it from
166     * the command file; if not, send it to the owner, or, failing that,
167     * to root.
168     */
169
170    pentry = getpwuid(uid);
171    if (pentry == NULL)
172	perrx("Userid %lu not found - aborting job %s",
173		(unsigned long) uid, filename);
174
175#ifdef PAM
176    PRIV_START
177
178    pam_err = pam_start(atrun, pentry->pw_name, &pamc, &pamh);
179    if (pam_err != PAM_SUCCESS)
180	perrx("cannot start PAM: %s", pam_strerror(pamh, pam_err));
181
182    pam_err = pam_acct_mgmt(pamh, PAM_SILENT);
183    /* Expired password shouldn't prevent the job from running. */
184    if (pam_err != PAM_SUCCESS && pam_err != PAM_NEW_AUTHTOK_REQD)
185	perrx("Account %s (userid %lu) unavailable for job %s: %s",
186	    pentry->pw_name, (unsigned long)uid,
187	    filename, pam_strerror(pamh, pam_err));
188
189    pam_end(pamh, pam_err);
190
191    PRIV_END
192#endif /* PAM */
193
194    PRIV_START
195
196    stream=fopen(filename, "r");
197
198    PRIV_END
199
200    if (stream == NULL)
201	perr("cannot open input file");
202
203    if ((fd_in = dup(fileno(stream))) <0)
204	perr("error duplicating input file descriptor");
205
206    if (fstat(fd_in, &buf) == -1)
207	perr("error in fstat of input file descriptor");
208
209    if (lstat(filename, &lbuf) == -1)
210	perr("error in fstat of input file");
211
212    if (S_ISLNK(lbuf.st_mode))
213	perrx("Symbolic link encountered in job %s - aborting", filename);
214
215    if ((lbuf.st_dev != buf.st_dev) || (lbuf.st_ino != buf.st_ino) ||
216        (lbuf.st_uid != buf.st_uid) || (lbuf.st_gid != buf.st_gid) ||
217        (lbuf.st_size!=buf.st_size))
218	perrx("Somebody changed files from under us for job %s - aborting",
219		filename);
220
221    if (buf.st_nlink > 1)
222	perrx("Somebody is trying to run a linked script for job %s", filename);
223
224    if ((fflags = fcntl(fd_in, F_GETFD)) <0)
225	perr("error in fcntl");
226
227    fcntl(fd_in, F_SETFD, fflags & ~FD_CLOEXEC);
228
229    snprintf(fmt, sizeof(fmt),
230	"#!/bin/sh\n# atrun uid=%%ld gid=%%ld\n# mail %%%ds %%d",
231                          MAXLOGNAME - 1);
232
233    if (fscanf(stream, fmt, &nuid, &ngid, mailbuf, &send_mail) != 4)
234	perrx("File %s is in wrong format - aborting", filename);
235
236    if (mailbuf[0] == '-')
237	perrx("Illegal mail name %s in %s", mailbuf, filename);
238
239    mailname = mailbuf;
240
241    if (nuid != uid)
242	perrx("Job %s - userid %ld does not match file uid %lu",
243		filename, nuid, (unsigned long)uid);
244
245    if (ngid != gid)
246	perrx("Job %s - groupid %ld does not match file gid %lu",
247		filename, ngid, (unsigned long)gid);
248
249    fclose(stream);
250
251    if (chdir(ATSPOOL_DIR) < 0)
252	perr("cannot chdir to %s", ATSPOOL_DIR);
253
254    /* Create a file to hold the output of the job we are about to run.
255     * Write the mail header.
256     */
257    if((fd_out=open(filename,
258		O_WRONLY | O_CREAT | O_EXCL, S_IWUSR | S_IRUSR)) < 0)
259	perr("cannot create output file");
260
261    write_string(fd_out, "Subject: Output from your job ");
262    write_string(fd_out, filename);
263    write_string(fd_out, "\n\n");
264    fstat(fd_out, &buf);
265    size = buf.st_size;
266
267    close(STDIN_FILENO);
268    close(STDOUT_FILENO);
269    close(STDERR_FILENO);
270
271    pid = fork();
272    if (pid < 0)
273	perr("error in fork");
274
275    else if (pid == 0)
276    {
277	char *nul = NULL;
278	char **nenvp = &nul;
279
280	/* Set up things for the child; we want standard input from the input file,
281	 * and standard output and error sent to our output file.
282	 */
283
284	if (lseek(fd_in, (off_t) 0, SEEK_SET) < 0)
285	    perr("error in lseek");
286
287	if (dup(fd_in) != STDIN_FILENO)
288	    perr("error in I/O redirection");
289
290	if (dup(fd_out) != STDOUT_FILENO)
291	    perr("error in I/O redirection");
292
293	if (dup(fd_out) != STDERR_FILENO)
294	    perr("error in I/O redirection");
295
296	close(fd_in);
297	close(fd_out);
298	if (chdir(ATJOB_DIR) < 0)
299	    perr("cannot chdir to %s", ATJOB_DIR);
300
301	queue = *filename;
302
303	PRIV_START
304
305        nice(tolower(queue) - 'a');
306
307#ifdef LOGIN_CAP
308	/*
309	 * For simplicity and safety, set all aspects of the user context
310	 * except for a selected subset:  Don't set priority, which was
311	 * set based on the queue file name according to the tradition.
312	 * Don't bother to set environment, including path vars, either
313	 * because it will be discarded anyway.  Although the job file
314	 * should set umask, preset it here just in case.
315	 */
316	if (setusercontext(NULL, pentry, uid, LOGIN_SETALL &
317		~(LOGIN_SETPRIORITY | LOGIN_SETPATH | LOGIN_SETENV)) != 0)
318	    exit(EXIT_FAILURE);	/* setusercontext() logged the error */
319#else /* LOGIN_CAP */
320	if (initgroups(pentry->pw_name,pentry->pw_gid))
321	    perr("cannot init group access list");
322
323	if (setgid(gid) < 0 || setegid(pentry->pw_gid) < 0)
324	    perr("cannot change group");
325
326	if (setlogin(pentry->pw_name))
327	    perr("cannot set login name");
328
329	if (setuid(uid) < 0 || seteuid(uid) < 0)
330	    perr("cannot set user id");
331#endif /* LOGIN_CAP */
332
333	if (chdir(pentry->pw_dir))
334		chdir("/");
335
336	if(execle("/bin/sh","sh",(char *) NULL, nenvp) != 0)
337	    perr("exec failed for /bin/sh");
338
339	PRIV_END
340    }
341    /* We're the parent.  Let's wait.
342     */
343    close(fd_in);
344    close(fd_out);
345    waitpid(pid, (int *) NULL, 0);
346
347    /* Send mail.  Unlink the output file first, so it is deleted after
348     * the run.
349     */
350    stat(filename, &buf);
351    if (open(filename, O_RDONLY) != STDIN_FILENO)
352        perr("open of jobfile failed");
353
354    unlink(filename);
355    if ((buf.st_size != size) || send_mail)
356    {
357	PRIV_START
358
359#ifdef LOGIN_CAP
360	/*
361	 * This time set full context to run the mailer.
362	 */
363	if (setusercontext(NULL, pentry, uid, LOGIN_SETALL) != 0)
364	    exit(EXIT_FAILURE);	/* setusercontext() logged the error */
365#else /* LOGIN_CAP */
366	if (initgroups(pentry->pw_name,pentry->pw_gid))
367	    perr("cannot init group access list");
368
369	if (setgid(gid) < 0 || setegid(pentry->pw_gid) < 0)
370	    perr("cannot change group");
371
372	if (setlogin(pentry->pw_name))
373	    perr("cannot set login name");
374
375	if (setuid(uid) < 0 || seteuid(uid) < 0)
376	    perr("cannot set user id");
377#endif /* LOGIN_CAP */
378
379	if (chdir(pentry->pw_dir))
380		chdir("/");
381
382#ifdef __FreeBSD__
383	execl(_PATH_SENDMAIL, "sendmail", "-F", "Atrun Service",
384			"-odi", "-oem",
385			mailname, (char *) NULL);
386#else
387        execl(MAIL_CMD, MAIL_CMD, mailname, (char *) NULL);
388#endif
389	    perr("exec failed for mail command");
390
391	PRIV_END
392    }
393    exit(EXIT_SUCCESS);
394}
395
396/* Global functions */
397
398/* Needed in gloadavg.c */
399void
400perr(const char *fmt, ...)
401{
402    const char * const fmtadd = ": %m";
403    char nfmt[strlen(fmt) + strlen(fmtadd) + 1];
404    va_list ap;
405
406    va_start(ap, fmt);
407    if (debug)
408    {
409	vwarn(fmt, ap);
410    }
411    else
412    {
413	snprintf(nfmt, sizeof(nfmt), "%s%s", fmt, fmtadd);
414	vsyslog(LOG_ERR, nfmt, ap);
415    }
416    va_end(ap);
417
418    exit(EXIT_FAILURE);
419}
420
421void
422perrx(const char *fmt, ...)
423{
424    va_list ap;
425
426    va_start(ap, fmt);
427    if (debug)
428	vwarnx(fmt, ap);
429    else
430	vsyslog(LOG_ERR, fmt, ap);
431    va_end(ap);
432
433    exit(EXIT_FAILURE);
434}
435
436int
437main(int argc, char *argv[])
438{
439/* Browse through  ATJOB_DIR, checking all the jobfiles wether they should
440 * be executed and or deleted. The queue is coded into the first byte of
441 * the job filename, the date (in minutes since Eon) as a hex number in the
442 * following eight bytes, followed by a dot and a serial number.  A file
443 * which has not been executed yet is denoted by its execute - bit set.
444 * For those files which are to be executed, run_file() is called, which forks
445 * off a child which takes care of I/O redirection, forks off another child
446 * for execution and yet another one, optionally, for sending mail.
447 * Files which already have run are removed during the next invocation.
448 */
449    DIR *spool;
450    struct dirent *dirent;
451    struct stat buf;
452    unsigned long ctm;
453    unsigned long jobno;
454    char queue;
455    time_t now, run_time;
456    char batch_name[] = "Z2345678901234";
457    uid_t batch_uid;
458    gid_t batch_gid;
459    int c;
460    int run_batch;
461#ifdef __FreeBSD__
462    size_t ncpu, ncpusz;
463    double load_avg = -1;
464#else
465    double load_avg = LOADAVG_MX;
466#endif
467
468/* We don't need root privileges all the time; running under uid and gid daemon
469 * is fine.
470 */
471
472    RELINQUISH_PRIVS_ROOT(DAEMON_UID, DAEMON_GID)
473
474    openlog(atrun, LOG_PID, LOG_CRON);
475
476    opterr = 0;
477    while((c=getopt(argc, argv, "dl:"))!= -1)
478    {
479	switch (c)
480	{
481	case 'l':
482	    if (sscanf(optarg, "%lf", &load_avg) != 1)
483		perr("garbled option -l");
484#ifndef __FreeBSD__
485	    if (load_avg <= 0.)
486		load_avg = LOADAVG_MX;
487#endif
488	    break;
489
490	case 'd':
491	    debug ++;
492	    break;
493
494	case '?':
495	default:
496	    usage();
497	}
498    }
499
500    if (chdir(ATJOB_DIR) != 0)
501	perr("cannot change to %s", ATJOB_DIR);
502
503#ifdef __FreeBSD__
504    if (load_avg <= 0.) {
505	ncpusz = sizeof(size_t);
506	if (sysctlbyname("hw.ncpu", &ncpu, &ncpusz, NULL, 0) < 0)
507		ncpu = 1;
508	load_avg = LOADAVG_MX * ncpu;
509    }
510#endif
511
512    /* Main loop. Open spool directory for reading and look over all the
513     * files in there. If the filename indicates that the job should be run
514     * and the x bit is set, fork off a child which sets its user and group
515     * id to that of the files and exec a /bin/sh which executes the shell
516     * script. Unlink older files if they should no longer be run.  For
517     * deletion, their r bit has to be turned on.
518     *
519     * Also, pick the oldest batch job to run, at most one per invocation of
520     * atrun.
521     */
522    if ((spool = opendir(".")) == NULL)
523	perr("cannot read %s", ATJOB_DIR);
524
525    if (flock(dirfd(spool), LOCK_EX) == -1)
526	perr("cannot lock %s", ATJOB_DIR);
527
528    now = time(NULL);
529    run_batch = 0;
530    batch_uid = (uid_t) -1;
531    batch_gid = (gid_t) -1;
532
533    while ((dirent = readdir(spool)) != NULL) {
534	if (stat(dirent->d_name,&buf) != 0)
535	    perr("cannot stat in %s", ATJOB_DIR);
536
537	/* We don't want directories
538	 */
539	if (!S_ISREG(buf.st_mode))
540	    continue;
541
542	if (sscanf(dirent->d_name,"%c%5lx%8lx",&queue,&jobno,&ctm) != 3)
543	    continue;
544
545	run_time = (time_t) ctm*60;
546
547	if ((S_IXUSR & buf.st_mode) && (run_time <=now)) {
548	    if (isupper(queue) && (strcmp(batch_name,dirent->d_name) > 0)) {
549		run_batch = 1;
550		strlcpy(batch_name, dirent->d_name, sizeof(batch_name));
551		batch_uid = buf.st_uid;
552		batch_gid = buf.st_gid;
553	    }
554
555	/* The file is executable and old enough
556	 */
557	    if (islower(queue))
558		run_file(dirent->d_name, buf.st_uid, buf.st_gid);
559	}
560	/*  Delete older files
561	 */
562	if ((run_time < now) && !(S_IXUSR & buf.st_mode) && (S_IRUSR & buf.st_mode))
563	    unlink(dirent->d_name);
564    }
565    /* run the single batch file, if any
566    */
567    if (run_batch && (gloadavg() < load_avg))
568	run_file(batch_name, batch_uid, batch_gid);
569
570    closelog();
571    exit(EXIT_SUCCESS);
572}
573
574static void
575usage(void)
576{
577    if (debug)
578	fprintf(stderr, "usage: atrun [-l load_avg] [-d]\n");
579    else
580	syslog(LOG_ERR, "usage: atrun [-l load_avg] [-d]");
581
582    exit(EXIT_FAILURE);
583}
584