]>
git.saurik.com Git - apple/system_cmds.git/blob - at.tproj/at.c
9b9b67c0a55002350529e80e8a43c624b8f69ddc
2 * at.c : Put file into atrun queue
3 * Copyright (C) 1993, 1994 Thomas Koenig
5 * Atrun & Atq modifications
6 * Copyright (C) 1993 David Parsons
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
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
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(S) 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.
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD: /usr/local/www/cvsroot/FreeBSD/src/usr.bin/at/at.c,v 1.34 2011/11/06 20:30:21 ed Exp $");
36 #include <sys/param.h>
62 #include <get_compat.h>
64 #define COMPAT_MODE(a,b) (1)
65 #endif /* __APPLE__ */
71 #include "parsetime.h"
72 #include "pathnames.h"
81 #define ATJOB_DIR _PATH_ATJOBS
85 #define LFILE ATJOB_DIR ".lockfile"
92 #define ALARMC 10 /* Number of seconds to wait for timeout */
97 enum { ATQ
, ATRM
, AT
, BATCH
, CAT
}; /* what program we want to run */
99 /* File scope variables */
101 static const char *no_export
[] = {
102 "TERM", "TERMCAP", "DISPLAY", "_"
104 static int send_mail
= 0;
105 static char *atinput
= NULL
; /* where to get input from */
106 static char atqueue
= 0; /* which queue to examine for jobs (atq) */
108 /* External variables */
110 extern char **environ
;
112 char atfile
[] = ATJOB_DIR
"12345678901234";
113 char atverify
= 0; /* verify time instead of queuing job */
115 int posixly_correct
; /* Behave as per POSIX */
116 /* http://www.opengroup.org/onlinepubs/009695399/utilities/at.html */
118 /* Function declarations */
120 static void sigc(int signo
);
121 static void alarmc(int signo
);
122 static char *cwdname(void);
123 static void writefile(time_t runtimer
, char queue
);
124 static void list_jobs(long *, int);
125 static long nextjob(void);
126 static time_t ttime(const char *arg
);
127 static int in_job_list(long, long *, int);
128 static long *get_job_list(int, char *[], int *);
130 /* Signal catching functions */
133 sigc(int signo __unused
)
135 /* If the user presses ^C, remove the spool file and exit
148 alarmc(int signo __unused
)
152 /* Time out after some seconds. */
153 strlcpy(buf
, namep
, sizeof(buf
));
154 strlcat(buf
, ": file locking timed out\n", sizeof(buf
));
155 write(STDERR_FILENO
, buf
, strlen(buf
));
159 /* Local functions */
164 /* Read in the current directory; the name will be overwritten on
167 static char *ptr
= NULL
;
168 static size_t size
= SIZE
;
171 if ((ptr
= malloc(size
)) == NULL
)
172 errx(EXIT_FAILURE
, "virtual memory exhausted");
177 panic("out of memory");
179 if (getcwd(ptr
, size
-1) != NULL
)
183 perr("cannot get directory");
187 if ((ptr
= malloc(size
)) == NULL
)
188 errx(EXIT_FAILURE
, "virtual memory exhausted");
198 if ((fid
= fopen(ATJOB_DIR
".SEQ", "r+")) != NULL
) {
199 if (fscanf(fid
, "%5lx", &jobno
) == 1) {
201 jobno
= (1+jobno
) % 0xfffff; /* 2^20 jobs enough? */
202 fprintf(fid
, "%05lx\n", jobno
);
209 else if ((fid
= fopen(ATJOB_DIR
".SEQ", "w")) != NULL
) {
210 fprintf(fid
, "%05lx\n", jobno
= 1);
218 writefile(time_t runtimer
, char queue
)
220 /* This does most of the work if at or batch are invoked for writing a job.
223 char *ap
, *ppos
, *mailname
;
224 struct passwd
*pass_entry
;
226 int fdes
, lockdes
, fd2
;
228 struct sigaction act
;
233 char * oldpwd_str
= NULL
;
236 (void) setlocale(LC_TIME
, "");
239 /* Install the signal handler for SIGINT; terminate after removing the
240 * spool file if necessary
242 act
.sa_handler
= sigc
;
243 sigemptyset(&(act
.sa_mask
));
246 sigaction(SIGINT
, &act
, NULL
);
248 ppos
= atfile
+ strlen(ATJOB_DIR
);
250 /* Loop over all possible file names for running something at this
251 * particular time, see if a file is there; the first empty slot at any
252 * particular time is used. Lock the file LFILE first to make sure
253 * we're alone when doing this.
258 if ((lockdes
= open(LFILE
, O_WRONLY
| O_CREAT
, S_IWUSR
| S_IRUSR
)) < 0)
259 perr("cannot open lockfile " LFILE
);
261 lock
.l_type
= F_WRLCK
; lock
.l_whence
= SEEK_SET
; lock
.l_start
= 0;
264 act
.sa_handler
= alarmc
;
265 sigemptyset(&(act
.sa_mask
));
268 /* Set an alarm so a timeout occurs after ALARMC seconds, in case
269 * something is seriously broken.
271 sigaction(SIGALRM
, &act
, NULL
);
273 fcntl(lockdes
, F_SETLKW
, &lock
);
276 if ((jobno
= nextjob()) == EOF
)
277 perr("cannot generate job number");
279 sprintf(ppos
, "%c%5lx%8lx", queue
,
280 jobno
, (unsigned long) (runtimer
/60));
282 for(ap
=ppos
; *ap
!= '\0'; ap
++)
286 if (stat(atfile
, &statbuf
) != 0)
288 perr("cannot access " ATJOB_DIR
);
290 /* Create the file. The x bit is only going to be set after it has
291 * been completely written out, to make sure it is not executed in the
292 * meantime. To make sure they do not get deleted, turn off their r
293 * bit. Yes, this is a kluge.
295 cmask
= umask(S_IRUSR
| S_IWUSR
| S_IXUSR
);
296 if ((fdes
= creat(atfile
, O_WRONLY
)) == -1)
297 perr("cannot create atjob file");
299 if ((fd2
= dup(fdes
)) <0)
300 perr("error in dup() of job file");
302 if(fchown(fd2
, real_uid
, real_gid
) != 0)
303 perr("cannot give away file");
307 /* We no longer need suid root; now we just need to be able to write
308 * to the directory, if necessary.
311 REDUCE_PRIV(DAEMON_UID
, DAEMON_GID
)
313 /* We've successfully created the file; let's set the flag so it
314 * gets removed in case of an interrupt or error.
318 /* Now we can release the lock, so other people can access it
320 lock
.l_type
= F_UNLCK
; lock
.l_whence
= SEEK_SET
; lock
.l_start
= 0;
322 fcntl(lockdes
, F_SETLKW
, &lock
);
325 if((fp
= fdopen(fdes
, "w")) == NULL
)
326 panic("cannot reopen atjob file");
328 /* Get the userid to mail to, first by trying getlogin(),
329 * then from LOGNAME, finally from getpwuid().
331 mailname
= getlogin();
332 if (mailname
== NULL
)
333 mailname
= getenv("LOGNAME");
335 if ((mailname
== NULL
) || (mailname
[0] == '\0')
336 || (strlen(mailname
) >= MAXLOGNAME
) || (getpwnam(mailname
)==NULL
))
338 pass_entry
= getpwuid(real_uid
);
339 if (pass_entry
!= NULL
)
340 mailname
= pass_entry
->pw_name
;
343 if (atinput
!= (char *) NULL
)
345 fpin
= freopen(atinput
, "r", stdin
);
347 perr("cannot open input file");
349 fprintf(fp
, "#!/bin/sh\n# atrun uid=%ld gid=%ld\n# mail %.*s %d\n",
350 (long) real_uid
, (long) real_gid
, MAXLOGNAME
- 1, mailname
,
353 /* Write out the umask at the time of invocation
355 fprintf(fp
, "umask %lo\n", (unsigned long) cmask
);
357 /* Write out the environment. Anything that may look like a
358 * special character to the shell is quoted, except for \n, which is
359 * done with a pair of "'s. Don't export the no_export list (such
360 * as TERM or DISPLAY) because we don't want these.
362 for (atenv
= environ
; *atenv
!= NULL
; atenv
++)
367 eqp
= strchr(*atenv
, '=');
374 if(strncmp(*atenv
, "OLDPWD", (size_t) (eqp
-*atenv
)) == 0) {
377 if (!posixly_correct
) {
378 /* Test 891 expects TERM, etc. to show up in "at" env
379 so exclude them only when not posixly_correct */
380 for (i
=0; i
<sizeof(no_export
)/sizeof(no_export
[0]); i
++)
383 && (strncmp(*atenv
, no_export
[i
],
384 (size_t) (eqp
-*atenv
)) != 0);
392 fwrite(*atenv
, sizeof(char), eqp
-*atenv
, fp
);
393 for(ap
= eqp
;*ap
!= '\0'; ap
++)
396 fprintf(fp
, "\"\n\"");
401 case '%': case '/': case '{': case '[':
402 case ']': case '=': case '}': case '@':
403 case '+': case '#': case ',': case '.':
404 case ':': case '-': case '_':
414 fputs("; export ", fp
);
415 fwrite(*atenv
, sizeof(char), eqp
-*atenv
-1, fp
);
420 /* Cd to the directory at the time and write out all the
421 * commands the user supplies from stdin.
424 for (ap
= cwdname(); *ap
!= '\0'; ap
++)
427 fprintf(fp
, "\"\n\"");
430 if (*ap
!= '/' && !isalnum(*ap
))
436 /* Test cd's exit status: die if the original directory has been
437 * removed, become unreadable or whatever
439 fprintf(fp
, " || {\n\t echo 'Execution directory "
440 "inaccessible' >&2\n\t exit 1\n}\n");
442 /* Put OLDPWD back, since the cd has set it */
443 /* Although this is added to fix conformance test at.ex 891, it seems like */
444 /* the right thing to do always, so the code is not posix_pedantic only */
446 fprintf(fp
, "%s; export OLDPWD\n", oldpwd_str
);
448 fprintf(fp
, "unset OLDPWD\n");
451 while((ch
= getchar()) != EOF
)
456 panic("output error");
459 panic("input error");
463 /* Set the x bit so that we're ready to start executing
466 if (fchmod(fd2
, S_IRUSR
| S_IWUSR
| S_IXUSR
) < 0)
467 perr("cannot give away file");
470 if (posixly_correct
) {
472 char timestr
[TIMESIZE
];
473 runtime
= *localtime(&runtimer
);
474 strftime(timestr
, TIMESIZE
, "%a %b %e %T %Y", &runtime
);
475 fprintf(stderr
, "job %ld at %s\n", jobno
, timestr
);
477 fprintf(stderr
, "Job %ld will be executed using /bin/sh\n", jobno
);
481 in_job_list(long job
, long *joblist
, int len
)
485 for (i
= 0; i
< len
; i
++)
486 if (job
== joblist
[i
])
493 list_one_job(char *name
, long *joblist
, int len
, int *first
)
501 char timestr
[TIMESIZE
];
503 if (stat(name
, &buf
) != 0)
504 perr("cannot stat in " ATJOB_DIR
);
506 /* See it's a regular file and has its x bit turned on and
509 if (!S_ISREG(buf
.st_mode
)
510 || ((buf
.st_uid
!= real_uid
) && ! (real_uid
== 0))
511 || !(S_IXUSR
& buf
.st_mode
|| atverify
))
514 if(sscanf(name
, "%c%5lx%8lx", &queue
, &jobno
, &ctm
)!=3)
517 /* If jobs are given, only list those jobs */
518 if (joblist
&& !in_job_list(jobno
, joblist
, len
))
521 if (atqueue
&& (queue
!= atqueue
))
524 runtimer
= 60*(time_t) ctm
;
525 runtime
= *localtime(&runtimer
);
526 strftime(timestr
, TIMESIZE
, "%a %b %e %T %Y", &runtime
);
528 if (!posixly_correct
)
529 printf("Date\t\t\t\tOwner\t\tQueue\tJob#\n");
533 printf("%ld\t%s\n", jobno
, timestr
);
535 struct passwd
*pw
= getpwuid(buf
.st_uid
);
537 printf("%s\t%s\t%c%s\t%s\n",
539 pw
? pw
->pw_name
: "???",
541 (S_IXUSR
& buf
.st_mode
) ? "":"(done)",
547 list_jobs(long *joblist
, int len
)
549 /* List all a user's jobs in the queue, by looping through ATJOB_DIR,
550 * or everybody's if we are root
553 struct dirent
*dirent
;
557 (void) setlocale(LC_TIME
, "");
562 if (chdir(ATJOB_DIR
) != 0)
563 perr("cannot change to " ATJOB_DIR
);
565 if (joblist
) { /* Force order to match POSIX */
570 sprintf(jobglob
, "?%05lx*", joblist
[0]);
572 glob(jobglob
, GLOB_DOOFFS
, NULL
, &g
);
573 for (i
= 1; i
< len
; i
++) {
574 sprintf(jobglob
, "?%05lx*", joblist
[i
]);
575 glob(jobglob
, GLOB_DOOFFS
| GLOB_APPEND
, NULL
, &g
);
577 for (i
= 0; i
< g
.gl_pathc
; i
++) {
578 list_one_job(g
.gl_pathv
[i
], joblist
, len
, &first
);
582 if ((spool
= opendir(".")) == NULL
)
583 perr("cannot open " ATJOB_DIR
);
585 /* Loop over every file in the directory
587 while((dirent
= readdir(spool
)) != NULL
) {
588 list_one_job(dirent
->d_name
, joblist
, len
, &first
);
596 process_jobs(int argc
, char **argv
, int what
)
598 /* Delete every argument (job - ID) given
603 struct dirent
*dirent
;
610 if (chdir(ATJOB_DIR
) != 0)
611 perr("cannot change to " ATJOB_DIR
);
613 if ((spool
= opendir(".")) == NULL
)
614 perr("cannot open " ATJOB_DIR
);
618 /* Loop over every file in the directory
620 while((dirent
= readdir(spool
)) != NULL
) {
623 if (stat(dirent
->d_name
, &buf
) != 0)
624 perr("cannot stat in " ATJOB_DIR
);
627 if(sscanf(dirent
->d_name
, "%c%5lx%8lx", &queue
, &jobno
, &ctm
)!=3)
630 for (i
=optind
; i
< argc
; i
++) {
631 if (atoi(argv
[i
]) == jobno
|| strcmp(argv
[i
], dirent
->d_name
)==0) {
632 if ((buf
.st_uid
!= real_uid
) && !(real_uid
== 0))
633 errx(EXIT_FAILURE
, "%s: not owner", argv
[i
]);
639 if (unlink(dirent
->d_name
) != 0)
640 perr(dirent
->d_name
);
653 fp
= fopen(dirent
->d_name
,"r");
658 perr("cannot open file");
660 while((ch
= getc(fp
)) != EOF
) {
668 errx(EXIT_FAILURE
, "internal error, process_jobs = %d",
677 #define ATOI2(ar) ((ar)[0] - '0') * 10 + ((ar)[1] - '0'); (ar) += 2;
680 ttime(const char *arg
)
683 * This is pretty much a copy of stime_arg1() from touch.c. I changed
684 * the return value and the argument list because it's more convenient
685 * (IMO) to do everything in one place. - Joe Halpin
687 struct timeval tv
[2];
693 if (gettimeofday(&tv
[0], NULL
))
694 panic("Cannot get current time");
696 /* Start with the current time. */
698 if ((t
= localtime(&now
)) == NULL
)
700 /* [[CC]YY]MMDDhhmm[.SS] */
701 if ((p
= strchr(arg
, '.')) == NULL
)
702 t
->tm_sec
= 0; /* Seconds defaults to 0. */
704 if (strlen(p
+ 1) != 2)
707 t
->tm_sec
= ATOI2(p
);
711 switch(strlen(arg
)) {
712 case 12: /* CCYYMMDDhhmm */
713 t
->tm_year
= ATOI2(arg
);
717 case 10: /* YYMMDDhhmm */
719 yearset
= ATOI2(arg
);
720 t
->tm_year
+= yearset
;
722 yearset
= ATOI2(arg
);
723 t
->tm_year
= yearset
+ 2000;
725 t
->tm_year
-= 1900; /* Convert to UNIX time. */
727 case 8: /* MMDDhhmm */
728 t
->tm_mon
= ATOI2(arg
);
729 --t
->tm_mon
; /* Convert from 01-12 to 00-11 */
730 t
->tm_mday
= ATOI2(arg
);
731 t
->tm_hour
= ATOI2(arg
);
732 t
->tm_min
= ATOI2(arg
);
738 t
->tm_isdst
= -1; /* Figure out DST. */
739 tv
[0].tv_sec
= tv
[1].tv_sec
= mktime(t
);
740 if (tv
[0].tv_sec
!= -1)
745 "out of range or illegal time specification: [[CC]YY]MMDDhhmm[.SS]");
749 get_job_list(int argc
, char *argv
[], int *joblen
)
758 if ((joblist
= malloc(len
* sizeof(*joblist
))) == NULL
)
759 panic("out of memory");
761 for (i
= 0; i
< argc
; i
++) {
763 if ((joblist
[i
] = strtol(argv
[i
], &ep
, 10)) < 0 ||
764 ep
== argv
[i
] || *ep
!= '\0' || errno
)
765 panic("invalid job number");
774 main(int argc
, char **argv
)
777 char queue
= DEFAULT_AT_QUEUE
;
781 int program
= AT
; /* our default program */
782 const char *options
= "q:f:t:rmvldbc"; /* default options for at */
787 posixly_correct
= COMPAT_MODE("bin/at", "Unix2003");
795 /* Eat any leading paths
797 if ((pgm
= strrchr(argv
[0], '/')) == NULL
)
804 /* find out what this program is supposed to do
806 if (strcmp(pgm
, "atq") == 0) {
810 else if (strcmp(pgm
, "atrm") == 0) {
814 else if (strcmp(pgm
, "batch") == 0) {
819 /* process whatever options we can process
822 while ((c
=getopt(argc
, argv
, options
)) != -1)
824 case 'v': /* verify time settings */
828 case 'm': /* send mail when job is complete */
836 case 'q': /* specify queue */
837 if (strlen(optarg
) > 1)
840 atqueue
= queue
= *optarg
;
841 if (!(islower(queue
)||isupper(queue
)))
848 warnx("-d is deprecated; use -r instead");
849 /* fall through to 'r' */
862 timer
= ttime(optarg
);
890 /* end of options eating
893 /* select our program
895 if(!check_permission())
896 errx(EXIT_FAILURE
, "you do not have permission to use this program");
900 REDUCE_PRIV(DAEMON_UID
, DAEMON_GID
)
903 joblist
= get_job_list(argc
- optind
, argv
+ optind
, &joblen
);
904 list_jobs(joblist
, joblen
);
909 REDUCE_PRIV(DAEMON_UID
, DAEMON_GID
)
911 process_jobs(argc
, argv
, ATRM
);
916 process_jobs(argc
, argv
, CAT
);
921 * If timer is > -1, then the user gave the time with -t. In that
922 * case, it's already been set. If not, set it now.
925 timer
= parsetime(argc
, argv
);
929 struct tm
*tm
= localtime(&timer
);
930 fprintf(stderr
, "%s\n", asctime(tm
));
932 writefile(timer
, queue
);
937 queue
= toupper(queue
);
939 queue
= DEFAULT_BATCH_QUEUE
;
942 timer
= parsetime(argc
, argv
);
948 struct tm
*tm
= localtime(&timer
);
949 fprintf(stderr
, "%s\n", asctime(tm
));
952 writefile(timer
, queue
);
956 panic("internal error");