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