]>
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
;
234 (void) setlocale(LC_TIME
, "");
237 /* Install the signal handler for SIGINT; terminate after removing the
238 * spool file if necessary
240 act
.sa_handler
= sigc
;
241 sigemptyset(&(act
.sa_mask
));
244 sigaction(SIGINT
, &act
, NULL
);
246 ppos
= atfile
+ strlen(ATJOB_DIR
);
248 /* Loop over all possible file names for running something at this
249 * particular time, see if a file is there; the first empty slot at any
250 * particular time is used. Lock the file LFILE first to make sure
251 * we're alone when doing this.
256 if ((lockdes
= open(LFILE
, O_WRONLY
| O_CREAT
, S_IWUSR
| S_IRUSR
)) < 0)
257 perr("cannot open lockfile " LFILE
);
259 lock
.l_type
= F_WRLCK
; lock
.l_whence
= SEEK_SET
; lock
.l_start
= 0;
262 act
.sa_handler
= alarmc
;
263 sigemptyset(&(act
.sa_mask
));
266 /* Set an alarm so a timeout occurs after ALARMC seconds, in case
267 * something is seriously broken.
269 sigaction(SIGALRM
, &act
, NULL
);
271 fcntl(lockdes
, F_SETLKW
, &lock
);
274 if ((jobno
= nextjob()) == EOF
)
275 perr("cannot generate job number");
277 sprintf(ppos
, "%c%5lx%8lx", queue
,
278 jobno
, (unsigned long) (runtimer
/60));
280 for(ap
=ppos
; *ap
!= '\0'; ap
++)
284 if (stat(atfile
, &statbuf
) != 0)
286 perr("cannot access " ATJOB_DIR
);
288 /* Create the file. The x bit is only going to be set after it has
289 * been completely written out, to make sure it is not executed in the
290 * meantime. To make sure they do not get deleted, turn off their r
291 * bit. Yes, this is a kluge.
293 cmask
= umask(S_IRUSR
| S_IWUSR
| S_IXUSR
);
294 if ((fdes
= creat(atfile
, O_WRONLY
)) == -1)
295 perr("cannot create atjob file");
297 if ((fd2
= dup(fdes
)) <0)
298 perr("error in dup() of job file");
300 if(fchown(fd2
, real_uid
, real_gid
) != 0)
301 perr("cannot give away file");
305 /* We no longer need suid root; now we just need to be able to write
306 * to the directory, if necessary.
309 REDUCE_PRIV(DAEMON_UID
, DAEMON_GID
)
311 /* We've successfully created the file; let's set the flag so it
312 * gets removed in case of an interrupt or error.
316 /* Now we can release the lock, so other people can access it
318 lock
.l_type
= F_UNLCK
; lock
.l_whence
= SEEK_SET
; lock
.l_start
= 0;
320 fcntl(lockdes
, F_SETLKW
, &lock
);
323 if((fp
= fdopen(fdes
, "w")) == NULL
)
324 panic("cannot reopen atjob file");
326 /* Get the userid to mail to, first by trying getlogin(),
327 * then from LOGNAME, finally from getpwuid().
329 mailname
= getlogin();
330 if (mailname
== NULL
)
331 mailname
= getenv("LOGNAME");
333 if ((mailname
== NULL
) || (mailname
[0] == '\0')
334 || (strlen(mailname
) >= MAXLOGNAME
) || (getpwnam(mailname
)==NULL
))
336 pass_entry
= getpwuid(real_uid
);
337 if (pass_entry
!= NULL
)
338 mailname
= pass_entry
->pw_name
;
341 if (atinput
!= (char *) NULL
)
343 fpin
= freopen(atinput
, "r", stdin
);
345 perr("cannot open input file");
347 fprintf(fp
, "#!/bin/sh\n# atrun uid=%ld gid=%ld\n# mail %.*s %d\n",
348 (long) real_uid
, (long) real_gid
, MAXLOGNAME
- 1, mailname
,
351 /* Write out the umask at the time of invocation
353 fprintf(fp
, "umask %lo\n", (unsigned long) cmask
);
355 /* Write out the environment. Anything that may look like a
356 * special character to the shell is quoted, except for \n, which is
357 * done with a pair of "'s. Don't export the no_export list (such
358 * as TERM or DISPLAY) because we don't want these.
360 for (atenv
= environ
; *atenv
!= NULL
; atenv
++)
365 eqp
= strchr(*atenv
, '=');
371 for (i
=0; i
<sizeof(no_export
)/sizeof(no_export
[0]); i
++)
374 && (strncmp(*atenv
, no_export
[i
],
375 (size_t) (eqp
-*atenv
)) != 0);
382 fwrite(*atenv
, sizeof(char), eqp
-*atenv
, fp
);
383 for(ap
= eqp
;*ap
!= '\0'; ap
++)
386 fprintf(fp
, "\"\n\"");
391 case '%': case '/': case '{': case '[':
392 case ']': case '=': case '}': case '@':
393 case '+': case '#': case ',': case '.':
394 case ':': case '-': case '_':
404 fputs("; export ", fp
);
405 fwrite(*atenv
, sizeof(char), eqp
-*atenv
-1, fp
);
410 /* Cd to the directory at the time and write out all the
411 * commands the user supplies from stdin.
414 for (ap
= cwdname(); *ap
!= '\0'; ap
++)
417 fprintf(fp
, "\"\n\"");
420 if (*ap
!= '/' && !isalnum(*ap
))
426 /* Test cd's exit status: die if the original directory has been
427 * removed, become unreadable or whatever
429 fprintf(fp
, " || {\n\t echo 'Execution directory "
430 "inaccessible' >&2\n\t exit 1\n}\n");
432 while((ch
= getchar()) != EOF
)
437 panic("output error");
440 panic("input error");
444 /* Set the x bit so that we're ready to start executing
447 if (fchmod(fd2
, S_IRUSR
| S_IWUSR
| S_IXUSR
) < 0)
448 perr("cannot give away file");
451 if (posixly_correct
) {
453 char timestr
[TIMESIZE
];
454 runtime
= *localtime(&runtimer
);
455 strftime(timestr
, TIMESIZE
, "%a %b %e %T %Y", &runtime
);
456 fprintf(stderr
, "job %ld at %s\n", jobno
, timestr
);
458 fprintf(stderr
, "Job %ld will be executed using /bin/sh\n", jobno
);
462 in_job_list(long job
, long *joblist
, int len
)
466 for (i
= 0; i
< len
; i
++)
467 if (job
== joblist
[i
])
474 list_one_job(char *name
, long *joblist
, int len
, int *first
)
482 char timestr
[TIMESIZE
];
484 if (stat(name
, &buf
) != 0)
485 perr("cannot stat in " ATJOB_DIR
);
487 /* See it's a regular file and has its x bit turned on and
490 if (!S_ISREG(buf
.st_mode
)
491 || ((buf
.st_uid
!= real_uid
) && ! (real_uid
== 0))
492 || !(S_IXUSR
& buf
.st_mode
|| atverify
))
495 if(sscanf(name
, "%c%5lx%8lx", &queue
, &jobno
, &ctm
)!=3)
498 /* If jobs are given, only list those jobs */
499 if (joblist
&& !in_job_list(jobno
, joblist
, len
))
502 if (atqueue
&& (queue
!= atqueue
))
505 runtimer
= 60*(time_t) ctm
;
506 runtime
= *localtime(&runtimer
);
507 strftime(timestr
, TIMESIZE
, "%a %b %e %T %Y", &runtime
);
509 if (!posixly_correct
)
510 printf("Date\t\t\t\tOwner\t\tQueue\tJob#\n");
514 printf("%ld\t%s\n", jobno
, timestr
);
516 struct passwd
*pw
= getpwuid(buf
.st_uid
);
518 printf("%s\t%s\t%c%s\t%s\n",
520 pw
? pw
->pw_name
: "???",
522 (S_IXUSR
& buf
.st_mode
) ? "":"(done)",
528 list_jobs(long *joblist
, int len
)
530 /* List all a user's jobs in the queue, by looping through ATJOB_DIR,
531 * or everybody's if we are root
534 struct dirent
*dirent
;
538 (void) setlocale(LC_TIME
, "");
543 if (chdir(ATJOB_DIR
) != 0)
544 perr("cannot change to " ATJOB_DIR
);
546 if (joblist
) { /* Force order to match POSIX */
551 sprintf(jobglob
, "?%05lx*", joblist
[0]);
553 glob(jobglob
, GLOB_DOOFFS
, NULL
, &g
);
554 for (i
= 1; i
< len
; i
++) {
555 sprintf(jobglob
, "?%05lx*", joblist
[i
]);
556 glob(jobglob
, GLOB_DOOFFS
| GLOB_APPEND
, NULL
, &g
);
558 for (i
= 0; i
< g
.gl_pathc
; i
++) {
559 list_one_job(g
.gl_pathv
[i
], joblist
, len
, &first
);
563 if ((spool
= opendir(".")) == NULL
)
564 perr("cannot open " ATJOB_DIR
);
566 /* Loop over every file in the directory
568 while((dirent
= readdir(spool
)) != NULL
) {
569 list_one_job(dirent
->d_name
, joblist
, len
, &first
);
577 process_jobs(int argc
, char **argv
, int what
)
579 /* Delete every argument (job - ID) given
584 struct dirent
*dirent
;
591 if (chdir(ATJOB_DIR
) != 0)
592 perr("cannot change to " ATJOB_DIR
);
594 if ((spool
= opendir(".")) == NULL
)
595 perr("cannot open " ATJOB_DIR
);
599 /* Loop over every file in the directory
601 while((dirent
= readdir(spool
)) != NULL
) {
604 if (stat(dirent
->d_name
, &buf
) != 0)
605 perr("cannot stat in " ATJOB_DIR
);
608 if(sscanf(dirent
->d_name
, "%c%5lx%8lx", &queue
, &jobno
, &ctm
)!=3)
611 for (i
=optind
; i
< argc
; i
++) {
612 if (atoi(argv
[i
]) == jobno
|| strcmp(argv
[i
], dirent
->d_name
)==0) {
613 if ((buf
.st_uid
!= real_uid
) && !(real_uid
== 0))
614 errx(EXIT_FAILURE
, "%s: not owner", argv
[i
]);
620 if (unlink(dirent
->d_name
) != 0)
621 perr(dirent
->d_name
);
634 fp
= fopen(dirent
->d_name
,"r");
639 perr("cannot open file");
641 while((ch
= getc(fp
)) != EOF
) {
648 errx(EXIT_FAILURE
, "internal error, process_jobs = %d",
656 #define ATOI2(ar) ((ar)[0] - '0') * 10 + ((ar)[1] - '0'); (ar) += 2;
659 ttime(const char *arg
)
662 * This is pretty much a copy of stime_arg1() from touch.c. I changed
663 * the return value and the argument list because it's more convenient
664 * (IMO) to do everything in one place. - Joe Halpin
666 struct timeval tv
[2];
672 if (gettimeofday(&tv
[0], NULL
))
673 panic("Cannot get current time");
675 /* Start with the current time. */
677 if ((t
= localtime(&now
)) == NULL
)
679 /* [[CC]YY]MMDDhhmm[.SS] */
680 if ((p
= strchr(arg
, '.')) == NULL
)
681 t
->tm_sec
= 0; /* Seconds defaults to 0. */
683 if (strlen(p
+ 1) != 2)
686 t
->tm_sec
= ATOI2(p
);
690 switch(strlen(arg
)) {
691 case 12: /* CCYYMMDDhhmm */
692 t
->tm_year
= ATOI2(arg
);
696 case 10: /* YYMMDDhhmm */
698 yearset
= ATOI2(arg
);
699 t
->tm_year
+= yearset
;
701 yearset
= ATOI2(arg
);
702 t
->tm_year
= yearset
+ 2000;
704 t
->tm_year
-= 1900; /* Convert to UNIX time. */
706 case 8: /* MMDDhhmm */
707 t
->tm_mon
= ATOI2(arg
);
708 --t
->tm_mon
; /* Convert from 01-12 to 00-11 */
709 t
->tm_mday
= ATOI2(arg
);
710 t
->tm_hour
= ATOI2(arg
);
711 t
->tm_min
= ATOI2(arg
);
717 t
->tm_isdst
= -1; /* Figure out DST. */
718 tv
[0].tv_sec
= tv
[1].tv_sec
= mktime(t
);
719 if (tv
[0].tv_sec
!= -1)
724 "out of range or illegal time specification: [[CC]YY]MMDDhhmm[.SS]");
728 get_job_list(int argc
, char *argv
[], int *joblen
)
737 if ((joblist
= malloc(len
* sizeof(*joblist
))) == NULL
)
738 panic("out of memory");
740 for (i
= 0; i
< argc
; i
++) {
742 if ((joblist
[i
] = strtol(argv
[i
], &ep
, 10)) < 0 ||
743 ep
== argv
[i
] || *ep
!= '\0' || errno
)
744 panic("invalid job number");
753 main(int argc
, char **argv
)
756 char queue
= DEFAULT_AT_QUEUE
;
760 int program
= AT
; /* our default program */
761 const char *options
= "q:f:t:rmvldbc"; /* default options for at */
766 posixly_correct
= COMPAT_MODE("bin/at", "Unix2003");
772 /* Eat any leading paths
774 if ((pgm
= strrchr(argv
[0], '/')) == NULL
)
781 /* find out what this program is supposed to do
783 if (strcmp(pgm
, "atq") == 0) {
787 else if (strcmp(pgm
, "atrm") == 0) {
791 else if (strcmp(pgm
, "batch") == 0) {
796 /* process whatever options we can process
799 while ((c
=getopt(argc
, argv
, options
)) != -1)
801 case 'v': /* verify time settings */
805 case 'm': /* send mail when job is complete */
813 case 'q': /* specify queue */
814 if (strlen(optarg
) > 1)
817 atqueue
= queue
= *optarg
;
818 if (!(islower(queue
)||isupper(queue
)))
825 warnx("-d is deprecated; use -r instead");
826 /* fall through to 'r' */
839 timer
= ttime(optarg
);
867 /* end of options eating
870 /* select our program
872 if(!check_permission())
873 errx(EXIT_FAILURE
, "you do not have permission to use this program");
877 REDUCE_PRIV(DAEMON_UID
, DAEMON_GID
)
880 joblist
= get_job_list(argc
- optind
, argv
+ optind
, &joblen
);
881 list_jobs(joblist
, joblen
);
886 REDUCE_PRIV(DAEMON_UID
, DAEMON_GID
)
888 process_jobs(argc
, argv
, ATRM
);
893 process_jobs(argc
, argv
, CAT
);
898 * If timer is > -1, then the user gave the time with -t. In that
899 * case, it's already been set. If not, set it now.
902 timer
= parsetime(argc
, argv
);
906 struct tm
*tm
= localtime(&timer
);
907 fprintf(stderr
, "%s\n", asctime(tm
));
909 writefile(timer
, queue
);
914 queue
= toupper(queue
);
916 queue
= DEFAULT_BATCH_QUEUE
;
919 timer
= parsetime(argc
, argv
);
925 struct tm
*tm
= localtime(&timer
);
926 fprintf(stderr
, "%s\n", asctime(tm
));
929 writefile(timer
, queue
);
933 panic("internal error");