]> git.saurik.com Git - apple/system_cmds.git/blob - at.tproj/at.c
f52e36e6ffe224c22ad82032677eccc55d65f122
[apple/system_cmds.git] / at.tproj / at.c
1 /*
2 * Copyright (c) 1999 Apple Computer, Inc. All rights reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * Copyright (c) 1999-2003 Apple Computer, Inc. All Rights Reserved.
7 *
8 * This file contains Original Code and/or Modifications of Original Code
9 * as defined in and that are subject to the Apple Public Source License
10 * Version 2.0 (the 'License'). You may not use this file except in
11 * compliance with the License. Please obtain a copy of the License at
12 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * file.
14 *
15 * The Original Code and all software distributed under the License are
16 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
17 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
18 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
20 * Please see the License for the specific language governing rights and
21 * limitations under the License.
22 *
23 * @APPLE_LICENSE_HEADER_END@
24 */
25 /*
26 * at.c : Put file into atrun queue
27 * Copyright (C) 1993 Thomas Koenig
28 *
29 * Atrun & Atq modifications
30 * Copyright (C) 1993 David Parsons
31 * All rights reserved.
32 *
33 * Redistribution and use in source and binary forms, with or without
34 * modification, are permitted provided that the following conditions
35 * are met:
36 * 1. Redistributions of source code must retain the above copyright
37 * notice, this list of conditions and the following disclaimer.
38 * 2. The name of the author(s) may not be used to endorse or promote
39 * products derived from this software without specific prior written
40 * permission.
41 *
42 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
43 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
44 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
45 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
46 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
47 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
48 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
49 * THEORY OF LIABILITY, WETHER IN CONTRACT, STRICT LIABILITY, OR TORT
50 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
51 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
52 */
53
54 #define _USE_BSD 1
55
56 /* System Headers */
57 #include <sys/types.h>
58 #include <sys/stat.h>
59 #include <sys/wait.h>
60 #include <ctype.h>
61 #include <dirent.h>
62 #include <errno.h>
63 #include <fcntl.h>
64 #include <pwd.h>
65 #include <signal.h>
66 #include <stddef.h>
67 #include <stdio.h>
68 #include <stdlib.h>
69 #include <string.h>
70 #include <time.h>
71 #include <unistd.h>
72
73 /* Local headers */
74 #include "at.h"
75 #include "panic.h"
76 #include "parsetime.h"
77 #include "pathnames.h"
78 #define MAIN
79 #include "privs.h"
80 #include "perm.h"
81
82 /* Macros */
83 #define ALARMC 10 /* Number of seconds to wait for timeout */
84
85 #define SIZE 255
86 #define TIMESIZE 50
87
88 /* File scope variables */
89 static char rcsid[] = "$Id: at.c,v 1.2 2003/10/15 22:48:12 lindak Exp $";
90 char *no_export[] =
91 {
92 "TERM", "TERMCAP", "DISPLAY", "_"
93 };
94 static send_mail = 0;
95
96 /* External variables */
97 extern char **environ;
98 int fcreated;
99 char *namep;
100 char atfile[FILENAME_MAX];
101
102 char *atinput = (char *) 0; /* where to get input from */
103 char atqueue = 0; /* which queue to examine for jobs (atq) */
104 char atverify = 0; /* verify time instead of queuing job */
105
106 /* Function declarations */
107 static void sigc __P((int signo));
108 static void alarmc __P((int signo));
109 static char *cwdname __P((void));
110 static void writefile __P((time_t runtimer, char queue));
111 static void list_jobs __P((void));
112
113 /* Signal catching functions */
114
115 static void
116 sigc(signo)
117 int signo;
118 {
119 /* If the user presses ^C, remove the spool file and exit
120 */
121 if (fcreated) {
122 PRIV_START
123 unlink(atfile);
124 PRIV_END
125 }
126
127 exit(EXIT_FAILURE);
128 }
129
130 static void
131 alarmc(signo)
132 int signo;
133 {
134 /* Time out after some seconds
135 */
136 panic("File locking timed out");
137 }
138
139 /* Local functions */
140
141 static char *
142 cwdname()
143 {
144 /* Read in the current directory; the name will be overwritten on
145 * subsequent calls.
146 */
147 static char *ptr = NULL;
148 static size_t size = SIZE;
149
150 if (ptr == NULL)
151 ptr = (char *) malloc(size);
152
153 while (1) {
154 if (ptr == NULL)
155 panic("Out of memory");
156
157 if (getcwd(ptr, size - 1) != NULL)
158 return ptr;
159
160 if (errno != ERANGE)
161 perr("Cannot get directory");
162
163 free(ptr);
164 size += SIZE;
165 ptr = (char *) malloc(size);
166 }
167 }
168
169 static void
170 writefile(runtimer, queue)
171 time_t runtimer;
172 char queue;
173 {
174 /*
175 * This does most of the work if at or batch are invoked for
176 * writing a job.
177 */
178 int i;
179 char *ap, *ppos, *mailname;
180 struct passwd *pass_entry;
181 struct stat statbuf;
182 int fdes, lockdes, fd2;
183 FILE *fp, *fpin;
184 struct sigaction act;
185 char **atenv;
186 int ch;
187 mode_t cmask;
188 struct flock lock;
189
190 /*
191 * Install the signal handler for SIGINT; terminate after removing the
192 * spool file if necessary
193 */
194 act.sa_handler = sigc;
195 sigemptyset(&(act.sa_mask));
196 act.sa_flags = 0;
197
198 sigaction(SIGINT, &act, NULL);
199
200 (void)strlcpy(atfile, _PATH_ATJOBS, sizeof atfile);
201 ppos = atfile + strlen(_PATH_ATJOBS);
202
203 /*
204 * Loop over all possible file names for running something at this
205 * particular time, see if a file is there; the first empty slot at
206 * any particular time is used. Lock the file _PATH_LOCKFILE first
207 * to make sure we're alone when doing this.
208 */
209
210 PRIV_START
211
212 if ((lockdes = open(_PATH_LOCKFILE, O_WRONLY | O_CREAT, 0600)) < 0)
213 perr2("Cannot open lockfile ", _PATH_LOCKFILE);
214
215 lock.l_type = F_WRLCK;
216 lock.l_whence = SEEK_SET;
217 lock.l_start = 0;
218 lock.l_len = 0;
219
220 act.sa_handler = alarmc;
221 sigemptyset(&(act.sa_mask));
222 act.sa_flags = 0;
223
224 /*
225 * Set an alarm so a timeout occurs after ALARMC seconds, in case
226 * something is seriously broken.
227 */
228 sigaction(SIGALRM, &act, NULL);
229 alarm(ALARMC);
230 fcntl(lockdes, F_SETLKW, &lock);
231 alarm(0);
232
233 for (i = 0; i < AT_MAXJOBS; i++) {
234 sprintf(ppos, "%c%8lx.%3x", queue,
235 (unsigned long) (runtimer / 60), i);
236 for (ap = ppos; *ap != '\0'; ap++)
237 if (*ap == ' ')
238 *ap = '0';
239
240 if (stat(atfile, &statbuf) != 0) {
241 if (errno == ENOENT)
242 break;
243 else
244 perr2("Cannot access ", _PATH_ATJOBS);
245 }
246 } /* for */
247
248 if (i >= AT_MAXJOBS)
249 panic("Too many jobs already");
250
251 /*
252 * Create the file. The x bit is only going to be set after it has
253 * been completely written out, to make sure it is not executed in
254 * the meantime. To make sure they do not get deleted, turn off
255 * their r bit. Yes, this is a kluge.
256 */
257 cmask = umask(S_IRUSR | S_IWUSR | S_IXUSR);
258 if ((fdes = creat(atfile, O_WRONLY)) == -1)
259 perr("Cannot create atjob file");
260
261 if ((fd2 = dup(fdes)) < 0)
262 perr("Error in dup() of job file");
263
264 if (fchown(fd2, real_uid, -1) != 0)
265 perr("Cannot give away file");
266
267 PRIV_END
268
269 /*
270 * We no longer need suid root; now we just need to be able to
271 * write to the directory, if necessary.
272 */
273
274 REDUCE_PRIV(0);
275
276 /*
277 * We've successfully created the file; let's set the flag so it
278 * gets removed in case of an interrupt or error.
279 */
280 fcreated = 1;
281
282 /* Now we can release the lock, so other people can access it */
283 lock.l_type = F_UNLCK;
284 lock.l_whence = SEEK_SET;
285 lock.l_start = 0;
286 lock.l_len = 0;
287 fcntl(lockdes, F_SETLKW, &lock);
288 close(lockdes);
289
290 if ((fp = fdopen(fdes, "w")) == NULL)
291 panic("Cannot reopen atjob file");
292
293 /*
294 * Get the userid to mail to, first by trying getlogin(), which
295 * reads /etc/utmp, then from LOGNAME, finally from getpwuid().
296 */
297 mailname = getlogin();
298 if (mailname == NULL)
299 mailname = getenv("LOGNAME");
300
301 if ((mailname == NULL) || (mailname[0] == '\0')
302 || (strlen(mailname) > 8)) {
303 pass_entry = getpwuid(getuid());
304 if (pass_entry != NULL)
305 mailname = pass_entry->pw_name;
306 }
307
308 if (atinput != (char *) NULL) {
309 fpin = freopen(atinput, "r", stdin);
310 if (fpin == NULL)
311 perr("Cannot open input file");
312 }
313 fprintf(fp, "#! /bin/sh\n# mail %8s %d\n", mailname, send_mail);
314
315 /* Write out the umask at the time of invocation */
316 fprintf(fp, "umask %lo\n", (unsigned long) cmask);
317
318 /*
319 * Write out the environment. Anything that may look like a special
320 * character to the shell is quoted, except for \n, which is done
321 * with a pair of "'s. Dont't export the no_export list (such as
322 * TERM or DISPLAY) because we don't want these.
323 */
324 for (atenv = environ; *atenv != NULL; atenv++) {
325 int export = 1;
326 char *eqp;
327
328 eqp = strchr(*atenv, '=');
329 if (ap == NULL)
330 eqp = *atenv;
331 else {
332 int i;
333
334 for (i = 0;i < sizeof(no_export) /
335 sizeof(no_export[0]); i++) {
336 export = export
337 && (strncmp(*atenv, no_export[i],
338 (size_t) (eqp - *atenv)) != 0);
339 }
340 eqp++;
341 }
342
343 if (export) {
344 fwrite(*atenv, sizeof(char), eqp - *atenv, fp);
345 for (ap = eqp; *ap != '\0'; ap++) {
346 if (*ap == '\n')
347 fprintf(fp, "\"\n\"");
348 else {
349 if (!isalnum(*ap))
350 fputc('\\', fp);
351
352 fputc(*ap, fp);
353 }
354 }
355 fputs("; export ", fp);
356 fwrite(*atenv, sizeof(char), eqp - *atenv - 1, fp);
357 fputc('\n', fp);
358
359 }
360 }
361 /*
362 * Cd to the directory at the time and write out all the commands
363 * the user supplies from stdin.
364 */
365 fprintf(fp, "cd %s\n", cwdname());
366
367 while ((ch = getchar()) != EOF)
368 fputc(ch, fp);
369
370 fprintf(fp, "\n");
371 if (ferror(fp))
372 panic("Output error");
373
374 if (ferror(stdin))
375 panic("Input error");
376
377 fclose(fp);
378
379 /*
380 * Set the x bit so that we're ready to start executing
381 */
382 if (fchmod(fd2, S_IRUSR | S_IWUSR | S_IXUSR) < 0)
383 perr("Cannot give away file");
384
385 close(fd2);
386 fprintf(stderr, "Job %s will be executed using /bin/sh\n", ppos);
387 }
388
389 static void
390 list_jobs()
391 {
392 /*
393 * List all a user's jobs in the queue, by looping through
394 * _PATH_ATJOBS, or everybody's if we are root
395 */
396 struct passwd *pw;
397 DIR *spool;
398 struct dirent *dirent;
399 struct stat buf;
400 struct tm runtime;
401 unsigned long ctm;
402 char queue;
403 time_t runtimer;
404 char timestr[TIMESIZE];
405 int first = 1;
406
407 PRIV_START
408
409 if (chdir(_PATH_ATJOBS) != 0)
410 perr2("Cannot change to ", _PATH_ATJOBS);
411
412 if ((spool = opendir(".")) == NULL)
413 perr2("Cannot open ", _PATH_ATJOBS);
414
415 /* Loop over every file in the directory */
416 while ((dirent = readdir(spool)) != NULL) {
417 if (stat(dirent->d_name, &buf) != 0)
418 perr2("Cannot stat in ", _PATH_ATJOBS);
419
420 /*
421 * See it's a regular file and has its x bit turned on and
422 * is the user's
423 */
424 if (!S_ISREG(buf.st_mode)
425 || ((buf.st_uid != real_uid) && !(real_uid == 0))
426 || !(S_IXUSR & buf.st_mode || atverify))
427 continue;
428
429 if (sscanf(dirent->d_name, "%c%8lx", &queue, &ctm) != 2)
430 continue;
431
432 if (atqueue && (queue != atqueue))
433 continue;
434
435 runtimer = 60 * (time_t) ctm;
436 runtime = *localtime(&runtimer);
437 strftime(timestr, TIMESIZE, "%X %x", &runtime);
438 if (first) {
439 printf("Date\t\t\tOwner\tQueue\tJob#\n");
440 first = 0;
441 }
442 pw = getpwuid(buf.st_uid);
443
444 printf("%s\t%s\t%c%s\t%s\n",
445 timestr,
446 pw ? pw->pw_name : "???",
447 queue,
448 (S_IXUSR & buf.st_mode) ? "" : "(done)",
449 dirent->d_name);
450 }
451 PRIV_END
452 }
453
454 static void
455 delete_jobs(argc, argv)
456 int argc;
457 char **argv;
458 {
459 /* Delete every argument (job - ID) given */
460 int i;
461 struct stat buf;
462
463 PRIV_START
464
465 if (chdir(_PATH_ATJOBS) != 0)
466 perr2("Cannot change to ", _PATH_ATJOBS);
467
468 for (i = optind; i < argc; i++) {
469 if (stat(argv[i], &buf) != 0)
470 perr(argv[i]);
471 if ((buf.st_uid != real_uid) && !(real_uid == 0)) {
472 fprintf(stderr, "%s: Not owner\n", argv[i]);
473 exit(EXIT_FAILURE);
474 }
475 if (unlink(argv[i]) != 0)
476 perr(argv[i]);
477 }
478 PRIV_END
479 } /* delete_jobs */
480
481 /* Global functions */
482
483 int
484 main(argc, argv)
485 int argc;
486 char **argv;
487 {
488 int c;
489 char queue = 'a';
490 char *pgm;
491
492 enum {
493 ATQ, ATRM, AT, BATCH
494 }; /* what program we want to run */
495 int program = AT; /* our default program */
496 char *options = "q:f:mv"; /* default options for at */
497 time_t timer;
498
499 RELINQUISH_PRIVS
500
501 /* Eat any leading paths */
502 if ((pgm = strrchr(argv[0], '/')) == NULL)
503 pgm = argv[0];
504 else
505 pgm++;
506
507 namep = pgm;
508
509 /* find out what this program is supposed to do */
510 if (strcmp(pgm, "atq") == 0) {
511 program = ATQ;
512 options = "q:v";
513 } else if (strcmp(pgm, "atrm") == 0) {
514 program = ATRM;
515 options = "";
516 } else if (strcmp(pgm, "batch") == 0) {
517 program = BATCH;
518 options = "f:mv";
519 }
520
521 /* process whatever options we can process */
522 opterr = 1;
523 while ((c = getopt(argc, argv, options)) != EOF)
524 switch (c) {
525 case 'v': /* verify time settings */
526 atverify = 1;
527 break;
528
529 case 'm': /* send mail when job is complete */
530 send_mail = 1;
531 break;
532
533 case 'f':
534 atinput = optarg;
535 break;
536
537 case 'q': /* specify queue */
538 if (strlen(optarg) > 1)
539 usage();
540
541 atqueue = queue = *optarg;
542 if ((!islower(queue)) || (queue > 'l'))
543 usage();
544 break;
545
546 default:
547 usage();
548 break;
549 }
550 /* end of options eating */
551
552 /* select our program */
553 if (!check_permission())
554 {
555 fprintf(stderr, "You do not have permission to use %s.\n",namep);
556 exit(EXIT_FAILURE);
557 }
558 switch (program) {
559 case ATQ:
560
561 REDUCE_PRIV(0);
562
563 list_jobs();
564 break;
565
566 case ATRM:
567
568 REDUCE_PRIV(0);
569
570 delete_jobs(argc, argv);
571 break;
572
573 case AT:
574 timer = parsetime(argc, argv);
575 if (atverify) {
576 struct tm *tm = localtime(&timer);
577
578 fprintf(stderr, "%s\n", asctime(tm));
579 }
580 writefile(timer, queue);
581 break;
582
583 case BATCH:
584 writefile(time(NULL), 'b');
585 break;
586
587 default:
588 panic("Internal error");
589 break;
590 }
591 exit(EXIT_SUCCESS);
592 }