]>
git.saurik.com Git - apple/system_cmds.git/blob - at.tproj/at.c
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: src/usr.bin/at/at.c,v 1.29 2002/07/22 11:32:16 robert 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 const char *no_export
[] =
103 "TERM", "TERMCAP", "DISPLAY", "_"
105 static int send_mail
= 0;
107 /* External variables */
109 extern char **environ
;
111 char atfile
[] = ATJOB_DIR
"12345678901234";
113 char *atinput
= (char*)0; /* where to get input from */
114 char atqueue
= 0; /* which queue to examine for jobs (atq) */
115 char atverify
= 0; /* verify time instead of queuing job */
117 int posixly_correct
; /* Behave as per POSIX */
118 /* http://www.opengroup.org/onlinepubs/009695399/utilities/at.html */
120 /* Function declarations */
122 static void sigc(int signo
);
123 static void alarmc(int signo
);
124 static char *cwdname(void);
125 static void writefile(time_t runtimer
, char queue
);
126 static void list_jobs(long *, int);
127 static long nextjob(void);
128 static time_t ttime(const char *arg
);
129 static int in_job_list(long, long *, int);
130 static long *get_job_list(int, char *[], int *);
132 /* Signal catching functions */
134 static void sigc(int signo __unused
)
136 /* If the user presses ^C, remove the spool file and exit
148 static void 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 */
161 static char *cwdname(void)
163 /* Read in the current directory; the name will be overwritten on
166 static char *ptr
= NULL
;
167 static size_t size
= SIZE
;
170 if ((ptr
= malloc(size
)) == NULL
)
171 errx(EXIT_FAILURE
, "virtual memory exhausted");
176 panic("out of memory");
178 if (getcwd(ptr
, size
-1) != NULL
)
182 perr("cannot get directory");
186 if ((ptr
= malloc(size
)) == NULL
)
187 errx(EXIT_FAILURE
, "virtual memory exhausted");
197 if ((fid
= fopen(ATJOB_DIR
".SEQ", "r+")) != (FILE*)0) {
198 if (fscanf(fid
, "%5lx", &jobno
) == 1) {
200 jobno
= (1+jobno
) % 0xfffff; /* 2^20 jobs enough? */
201 fprintf(fid
, "%05lx\n", jobno
);
208 else if ((fid
= fopen(ATJOB_DIR
".SEQ", "w")) != (FILE*)0) {
209 fprintf(fid
, "%05lx\n", jobno
= 1);
217 writefile(time_t runtimer
, char queue
)
219 /* This does most of the work if at or batch are invoked for writing a job.
222 char *ap
, *ppos
, *mailname
;
223 struct passwd
*pass_entry
;
225 int fdes
, lockdes
, fd2
;
227 struct sigaction act
;
232 char * oldpwd_str
= NULL
;
235 (void) setlocale(LC_TIME
, "");
238 /* Install the signal handler for SIGINT; terminate after removing the
239 * spool file if necessary
241 act
.sa_handler
= sigc
;
242 sigemptyset(&(act
.sa_mask
));
245 sigaction(SIGINT
, &act
, NULL
);
247 ppos
= atfile
+ strlen(ATJOB_DIR
);
249 /* Loop over all possible file names for running something at this
250 * particular time, see if a file is there; the first empty slot at any
251 * particular time is used. Lock the file LFILE first to make sure
252 * we're alone when doing this.
257 if ((lockdes
= open(LFILE
, O_WRONLY
| O_CREAT
, S_IWUSR
| S_IRUSR
)) < 0)
258 perr("cannot open lockfile " LFILE
);
260 lock
.l_type
= F_WRLCK
; lock
.l_whence
= SEEK_SET
; lock
.l_start
= 0;
263 act
.sa_handler
= alarmc
;
264 sigemptyset(&(act
.sa_mask
));
267 /* Set an alarm so a timeout occurs after ALARMC seconds, in case
268 * something is seriously broken.
270 sigaction(SIGALRM
, &act
, NULL
);
272 fcntl(lockdes
, F_SETLKW
, &lock
);
275 if ((jobno
= nextjob()) == EOF
)
276 perr("cannot generate job number");
278 sprintf(ppos
, "%c%5lx%8lx", queue
,
279 jobno
, (unsigned long) (runtimer
/60));
281 for(ap
=ppos
; *ap
!= '\0'; ap
++)
285 if (stat(atfile
, &statbuf
) != 0)
287 perr("cannot access " ATJOB_DIR
);
289 /* Create the file. The x bit is only going to be set after it has
290 * been completely written out, to make sure it is not executed in the
291 * meantime. To make sure they do not get deleted, turn off their r
292 * bit. Yes, this is a kluge.
294 cmask
= umask(S_IRUSR
| S_IWUSR
| S_IXUSR
);
295 if ((fdes
= creat(atfile
, O_WRONLY
)) == -1)
296 perr("cannot create atjob file");
298 if ((fd2
= dup(fdes
)) <0)
299 perr("error in dup() of job file");
301 if(fchown(fd2
, real_uid
, real_gid
) != 0)
302 perr("cannot give away file");
306 /* We no longer need suid root; now we just need to be able to write
307 * to the directory, if necessary.
310 REDUCE_PRIV(DAEMON_UID
, DAEMON_GID
)
312 /* We've successfully created the file; let's set the flag so it
313 * gets removed in case of an interrupt or error.
317 /* Now we can release the lock, so other people can access it
319 lock
.l_type
= F_UNLCK
; lock
.l_whence
= SEEK_SET
; lock
.l_start
= 0;
321 fcntl(lockdes
, F_SETLKW
, &lock
);
324 if((fp
= fdopen(fdes
, "w")) == NULL
)
325 panic("cannot reopen atjob file");
327 /* Get the userid to mail to, first by trying getlogin(),
328 * then from LOGNAME, finally from getpwuid().
330 mailname
= getlogin();
331 if (mailname
== NULL
)
332 mailname
= getenv("LOGNAME");
334 if ((mailname
== NULL
) || (mailname
[0] == '\0')
335 || (strlen(mailname
) >= MAXLOGNAME
) || (getpwnam(mailname
)==NULL
))
337 pass_entry
= getpwuid(real_uid
);
338 if (pass_entry
!= NULL
)
339 mailname
= pass_entry
->pw_name
;
342 if (atinput
!= (char *) NULL
)
344 fpin
= freopen(atinput
, "r", stdin
);
346 perr("cannot open input file");
348 fprintf(fp
, "#!/bin/sh\n# atrun uid=%ld gid=%ld\n# mail %.*s %d\n",
349 (long) real_uid
, (long) real_gid
, MAXLOGNAME
- 1, mailname
,
352 /* Write out the umask at the time of invocation
354 fprintf(fp
, "umask %lo\n", (unsigned long) cmask
);
356 /* Write out the environment. Anything that may look like a
357 * special character to the shell is quoted, except for \n, which is
358 * done with a pair of "'s. Don't export the no_export list (such
359 * as TERM or DISPLAY) because we don't want these.
361 for (atenv
= environ
; *atenv
!= NULL
; atenv
++)
366 eqp
= strchr(*atenv
, '=');
373 if(strncmp(*atenv
, "OLDPWD", (size_t) (eqp
-*atenv
)) == 0) {
376 if (!posixly_correct
) {
377 /* Test 891 expects TERM, etc. to show up in "at" env
378 so exclude them only when not posixly_correct */
379 for (i
=0; i
<sizeof(no_export
)/sizeof(no_export
[0]); i
++)
382 && (strncmp(*atenv
, no_export
[i
],
383 (size_t) (eqp
-*atenv
)) != 0);
391 fwrite(*atenv
, sizeof(char), eqp
-*atenv
, fp
);
392 for(ap
= eqp
;*ap
!= '\0'; ap
++)
395 fprintf(fp
, "\"\n\"");
400 case '%': case '/': case '{': case '[':
401 case ']': case '=': case '}': case '@':
402 case '+': case '#': case ',': case '.':
403 case ':': case '-': case '_':
413 fputs("; export ", fp
);
414 fwrite(*atenv
, sizeof(char), eqp
-*atenv
-1, fp
);
419 /* Cd to the directory at the time and write out all the
420 * commands the user supplies from stdin.
423 for (ap
= cwdname(); *ap
!= '\0'; ap
++)
426 fprintf(fp
, "\"\n\"");
429 if (*ap
!= '/' && !isalnum(*ap
))
435 /* Test cd's exit status: die if the original directory has been
436 * removed, become unreadable or whatever
438 fprintf(fp
, " || {\n\t echo 'Execution directory "
439 "inaccessible' >&2\n\t exit 1\n}\n");
441 /* Put OLDPWD back, since the cd has set it */
442 /* Although this is added to fix conformance test at.ex 891, it seems like */
443 /* the right thing to do always, so the code is not posix_pedantic only */
445 fprintf(fp
, "%s; export OLDPWD\n", oldpwd_str
);
447 fprintf(fp
, "unset OLDPWD\n");
450 while((ch
= getchar()) != EOF
)
455 panic("output error");
458 panic("input error");
462 /* Set the x bit so that we're ready to start executing
465 if (fchmod(fd2
, S_IRUSR
| S_IWUSR
| S_IXUSR
) < 0)
466 perr("cannot give away file");
469 if (posixly_correct
) {
471 char timestr
[TIMESIZE
];
472 runtime
= *localtime(&runtimer
);
473 strftime(timestr
, TIMESIZE
, "%a %b %e %T %Y", &runtime
);
474 fprintf(stderr
, "job %ld at %s\n", jobno
, timestr
);
476 fprintf(stderr
, "Job %ld will be executed using /bin/sh\n", jobno
);
480 in_job_list(long job
, long *joblist
, int len
)
484 for (i
= 0; i
< len
; i
++)
485 if (job
== joblist
[i
])
492 list_one_job(char *name
, long *joblist
, int len
, int *first
)
500 char timestr
[TIMESIZE
];
502 if (stat(name
, &buf
) != 0)
503 perr("cannot stat in " ATJOB_DIR
);
505 /* See it's a regular file and has its x bit turned on and
508 if (!S_ISREG(buf
.st_mode
)
509 || ((buf
.st_uid
!= real_uid
) && ! (real_uid
== 0))
510 || !(S_IXUSR
& buf
.st_mode
|| atverify
))
513 if(sscanf(name
, "%c%5lx%8lx", &queue
, &jobno
, &ctm
)!=3)
516 /* If jobs are given, only list those jobs */
517 if (joblist
&& !in_job_list(jobno
, joblist
, len
))
520 if (atqueue
&& (queue
!= atqueue
))
523 runtimer
= 60*(time_t) ctm
;
524 runtime
= *localtime(&runtimer
);
525 strftime(timestr
, TIMESIZE
, "%a %b %e %T %Y", &runtime
);
527 if (!posixly_correct
)
528 printf("Date\t\t\t\tOwner\t\tQueue\tJob#\n");
532 printf("%ld\t%s\n", jobno
, timestr
);
534 struct passwd
*pw
= getpwuid(buf
.st_uid
);
536 printf("%s\t%s\t%c%s\t%s\n",
538 pw
? pw
->pw_name
: "???",
540 (S_IXUSR
& buf
.st_mode
) ? "":"(done)",
546 list_jobs(long *joblist
, int len
)
548 /* List all a user's jobs in the queue, by looping through ATJOB_DIR,
549 * or everybody's if we are root
552 struct dirent
*dirent
;
556 (void) setlocale(LC_TIME
, "");
561 if (chdir(ATJOB_DIR
) != 0)
562 perr("cannot change to " ATJOB_DIR
);
564 if (joblist
) { /* Force order to match POSIX */
569 sprintf(jobglob
, "?%05lx*", joblist
[0]);
571 glob(jobglob
, GLOB_DOOFFS
, NULL
, &g
);
572 for (i
= 1; i
< len
; i
++) {
573 sprintf(jobglob
, "?%05lx*", joblist
[i
]);
574 glob(jobglob
, GLOB_DOOFFS
| GLOB_APPEND
, NULL
, &g
);
576 for (i
= 0; i
< g
.gl_pathc
; i
++) {
577 list_one_job(g
.gl_pathv
[i
], joblist
, len
, &first
);
581 if ((spool
= opendir(".")) == NULL
)
582 perr("cannot open " ATJOB_DIR
);
584 /* Loop over every file in the directory
586 while((dirent
= readdir(spool
)) != NULL
) {
587 list_one_job(dirent
->d_name
, joblist
, len
, &first
);
595 process_jobs(int argc
, char **argv
, int what
)
597 /* Delete every argument (job - ID) given
602 struct dirent
*dirent
;
609 if (chdir(ATJOB_DIR
) != 0)
610 perr("cannot change to " ATJOB_DIR
);
612 if ((spool
= opendir(".")) == NULL
)
613 perr("cannot open " ATJOB_DIR
);
617 /* Loop over every file in the directory
619 while((dirent
= readdir(spool
)) != NULL
) {
622 if (stat(dirent
->d_name
, &buf
) != 0)
623 perr("cannot stat in " ATJOB_DIR
);
626 if(sscanf(dirent
->d_name
, "%c%5lx%8lx", &queue
, &jobno
, &ctm
)!=3)
629 for (i
=optind
; i
< argc
; i
++) {
630 if (atoi(argv
[i
]) == jobno
|| strcmp(argv
[i
], dirent
->d_name
)==0) {
631 if ((buf
.st_uid
!= real_uid
) && !(real_uid
== 0))
632 errx(EXIT_FAILURE
, "%s: not owner", argv
[i
]);
638 if (unlink(dirent
->d_name
) != 0)
639 perr(dirent
->d_name
);
652 fp
= fopen(dirent
->d_name
,"r");
657 perr("cannot open file");
659 while((ch
= getc(fp
)) != EOF
) {
666 errx(EXIT_FAILURE
, "internal error, process_jobs = %d",
674 #define ATOI2(ar) ((ar)[0] - '0') * 10 + ((ar)[1] - '0'); (ar) += 2;
677 ttime(const char *arg
)
680 * This is pretty much a copy of stime_arg1() from touch.c. I changed
681 * the return value and the argument list because it's more convenient
682 * (IMO) to do everything in one place. - Joe Halpin
684 struct timeval tv
[2];
690 if (gettimeofday(&tv
[0], NULL
))
691 panic("Cannot get current time");
693 /* Start with the current time. */
695 if ((t
= localtime(&now
)) == NULL
)
697 /* [[CC]YY]MMDDhhmm[.SS] */
698 if ((p
= strchr(arg
, '.')) == NULL
)
699 t
->tm_sec
= 0; /* Seconds defaults to 0. */
701 if (strlen(p
+ 1) != 2)
704 t
->tm_sec
= ATOI2(p
);
708 switch(strlen(arg
)) {
709 case 12: /* CCYYMMDDhhmm */
710 t
->tm_year
= ATOI2(arg
);
714 case 10: /* YYMMDDhhmm */
716 yearset
= ATOI2(arg
);
717 t
->tm_year
+= yearset
;
719 yearset
= ATOI2(arg
);
720 t
->tm_year
= yearset
+ 2000;
722 t
->tm_year
-= 1900; /* Convert to UNIX time. */
724 case 8: /* MMDDhhmm */
725 t
->tm_mon
= ATOI2(arg
);
726 --t
->tm_mon
; /* Convert from 01-12 to 00-11 */
727 t
->tm_mday
= ATOI2(arg
);
728 t
->tm_hour
= ATOI2(arg
);
729 t
->tm_min
= ATOI2(arg
);
735 t
->tm_isdst
= -1; /* Figure out DST. */
736 tv
[0].tv_sec
= tv
[1].tv_sec
= mktime(t
);
737 if (tv
[0].tv_sec
!= -1)
742 "out of range or illegal time specification: [[CC]YY]MMDDhhmm[.SS]");
746 get_job_list(int argc
, char *argv
[], int *joblen
)
755 if ((joblist
= malloc(len
* sizeof(*joblist
))) == NULL
)
756 panic("out of memory");
758 for (i
= 0; i
< argc
; i
++) {
760 if ((joblist
[i
] = strtol(argv
[i
], &ep
, 10)) < 0 ||
761 ep
== argv
[i
] || *ep
!= '\0' || errno
)
762 panic("invalid job number");
771 main(int argc
, char **argv
)
774 char queue
= DEFAULT_AT_QUEUE
;
778 int program
= AT
; /* our default program */
779 const char *options
= "q:f:t:rmvldbc"; /* default options for at */
784 posixly_correct
= COMPAT_MODE("bin/at", "Unix2003");
792 /* Eat any leading paths
794 if ((pgm
= strrchr(argv
[0], '/')) == NULL
)
801 /* find out what this program is supposed to do
803 if (strcmp(pgm
, "atq") == 0) {
807 else if (strcmp(pgm
, "atrm") == 0) {
811 else if (strcmp(pgm
, "batch") == 0) {
816 /* process whatever options we can process
819 while ((c
=getopt(argc
, argv
, options
)) != -1)
821 case 'v': /* verify time settings */
825 case 'm': /* send mail when job is complete */
833 case 'q': /* specify queue */
834 if (strlen(optarg
) > 1)
837 atqueue
= queue
= *optarg
;
838 if (!(islower(queue
)||isupper(queue
)))
845 warnx("-d is deprecated; use -r instead");
846 /* fall through to 'r' */
859 timer
= ttime(optarg
);
887 /* end of options eating
890 /* select our program
892 if(!check_permission())
893 errx(EXIT_FAILURE
, "you do not have permission to use this program");
897 REDUCE_PRIV(DAEMON_UID
, DAEMON_GID
)
900 joblist
= get_job_list(argc
- optind
, argv
+ optind
, &joblen
);
901 list_jobs(joblist
, joblen
);
906 REDUCE_PRIV(DAEMON_UID
, DAEMON_GID
)
908 process_jobs(argc
, argv
, ATRM
);
913 process_jobs(argc
, argv
, CAT
);
918 * If timer is > -1, then the user gave the time with -t. In that
919 * case, it's already been set. If not, set it now.
922 timer
= parsetime(argc
, argv
);
926 struct tm
*tm
= localtime(&timer
);
927 fprintf(stderr
, "%s\n", asctime(tm
));
929 writefile(timer
, queue
);
934 queue
= toupper(queue
);
936 queue
= DEFAULT_BATCH_QUEUE
;
939 timer
= parsetime(argc
, argv
);
945 struct tm
*tm
= localtime(&timer
);
946 fprintf(stderr
, "%s\n", asctime(tm
));
949 writefile(timer
, queue
);
953 panic("internal error");