1 /* Copyright 1988,1990,1993,1994 by Paul Vixie
4 * Distribute freely, except: don't remove my name from the source or
5 * documentation (don't take credit for my work), mark your changes (don't
6 * get me blamed for your possible bugs), don't alter or remove this
7 * notice. May be sold if buildable source is provided to buyer. No
8 * warrantee of any kind, express or implied, is included with this
9 * software; use at your own risk, responsibility for damages (if any) to
10 * anyone resulting from the use of this software rests entirely with the
13 * Send bug reports, bug fixes, enhancements, requests, flames, etc., and
14 * I'll try to keep a version up to date. I can be reached as follows:
15 * Paul Vixie <paul@vix.com> uunet!decwrl!vixie!paul
16 * From Id: crontab.c,v 2.13 1994/01/17 03:20:37 vixie Exp
19 #if !defined(lint) && !defined(LINT)
20 static const char rcsid[] =
24 /* crontab - install and manage per-user crontab files
25 * vix 02may87 [RCS has the rest of the log]
26 * vix 26jan87 [original]
31 #include <sys/param.h>
40 # include <sys/time.h>
50 #define NHEADER_LINES 3
53 enum opt_t { opt_unknown, opt_list, opt_delete, opt_edit, opt_replace };
56 static char *Options[] = { "???", "list", "delete", "edit", "replace" };
61 static char User[MAXLOGNAME], RealUser[MAXLOGNAME];
62 static char Filename[MAX_FNAME];
63 static FILE *NewCrontab;
64 static int CheckErrorCount;
65 static enum opt_t Option;
67 static struct passwd *pw;
68 static void list_cmd(void),
73 parse_args(int c, char *v[]);
74 static int replace_cmd(void);
80 fprintf(stderr, "crontab: usage error: %s\n", msg);
81 fprintf(stderr, "%s\n%s\n",
82 "usage: crontab [-u user] file",
83 " crontab [-u user] { -l | -r [-f] | -e }");
89 main(int argc, char *argv[])
94 ProgramName = argv[0];
97 setlocale(LC_ALL, "");
103 parse_args(argc, argv); /* sets many globals, opens a file */
106 if (!allowed(User)) {
107 warnx("you (%s) are not allowed to use this program", User);
108 log_it(RealUser, Pid, "AUTH", "crontab command not allowed");
111 exitstatus = OK_EXIT;
113 case opt_list: list_cmd();
115 case opt_delete: delete_cmd();
117 case opt_edit: edit_cmd();
119 case opt_replace: if (replace_cmd() < 0)
120 exitstatus = ERROR_EXIT;
131 parse_args(argc, argv)
136 char resolved_path[PATH_MAX];
138 if (!(pw = getpwuid(getuid())))
139 errx(ERROR_EXIT, "your UID isn't in the passwd file, bailing out");
140 bzero(pw->pw_passwd, strlen(pw->pw_passwd));
141 (void) strncpy(User, pw->pw_name, (sizeof User)-1);
142 User[(sizeof User)-1] = '\0';
143 strcpy(RealUser, User);
145 Option = opt_unknown;
146 while ((argch = getopt(argc, argv, "u:lerx:f")) != -1) {
149 if (!set_debug_flags(optarg))
150 usage("bad debug option");
153 if (getuid() != ROOT_UID)
154 errx(ERROR_EXIT, "must be privileged to use -u");
155 if (!(pw = getpwnam(optarg)))
156 errx(ERROR_EXIT, "user `%s' unknown", optarg);
157 bzero(pw->pw_passwd, strlen(pw->pw_passwd));
158 (void) strncpy(User, pw->pw_name, (sizeof User)-1);
159 User[(sizeof User)-1] = '\0';
162 if (Option != opt_unknown)
163 usage("only one operation permitted");
167 if (Option != opt_unknown)
168 usage("only one operation permitted");
172 if (Option != opt_unknown)
173 usage("only one operation permitted");
180 usage("unrecognized option");
186 if (Option != opt_unknown) {
187 if (argv[optind] != NULL) {
188 usage("no arguments permitted after this option");
191 if (argv[optind] != NULL) {
192 Option = opt_replace;
193 (void) strncpy (Filename, argv[optind], (sizeof Filename)-1);
194 Filename[(sizeof Filename)-1] = '\0';
197 usage("file name must be specified for replace");
201 if (Option == opt_replace) {
202 /* relinquish the setuid status of the binary during
203 * the open, lest nonroot users read files they should
204 * not be able to read. we can't use access() here
205 * since there's a race condition. thanks go out to
206 * Arnt Gulbrandsen <agulbra@pvv.unit.no> for spotting
210 if (swap_uids() < OK)
211 err(ERROR_EXIT, "swapping uids");
213 /* we have to open the file here because we're going to
214 * chdir(2) into /var/cron before we get around to
217 if (!strcmp(Filename, "-")) {
219 } else if (realpath(Filename, resolved_path) != NULL &&
220 !strcmp(resolved_path, SYSCRONTAB)) {
221 err(ERROR_EXIT, SYSCRONTAB " must be edited manually");
223 if (!(NewCrontab = fopen(Filename, "r")))
224 err(ERROR_EXIT, "%s", Filename);
226 if (swap_uids_back() < OK)
227 err(ERROR_EXIT, "swapping uids back");
230 Debug(DMISC, ("user=%s, file=%s, option=%s\n",
231 User, Filename, Options[(int)Option]))
235 copy_file(FILE *in, FILE *out) {
239 /* ignore the top few comments since we probably put them there.
241 for (x = 0; x < NHEADER_LINES; x++) {
249 while (EOF != (ch = get_char(in)))
256 /* copy the rest of the crontab (if any) to the output file.
259 while (EOF != (ch = get_char(in)))
268 log_it(RealUser, Pid, "LIST", User);
269 (void) snprintf(n, sizeof(n), CRON_TAB(User));
270 if (!(f = fopen(n, "r"))) {
272 errx(ERROR_EXIT, "no crontab for %s", User);
274 err(ERROR_EXIT, "%s", n);
277 /* file is open. copy to stdout, close.
279 copy_file(f, stdout);
289 if (!fflag && isatty(STDIN_FILENO)) {
290 (void)fprintf(stderr, "remove crontab for %s? ", User);
291 first = ch = getchar();
292 while (ch != '\n' && ch != EOF)
294 if (first != 'y' && first != 'Y')
298 log_it(RealUser, Pid, "DELETE", User);
299 (void) snprintf(n, sizeof(n), CRON_TAB(User));
302 errx(ERROR_EXIT, "no crontab for %s", User);
304 err(ERROR_EXIT, "%s", n);
315 fprintf(stderr, "\"%s\":%d: %s\n", Filename, LineNumber-1, msg);
321 char n[MAX_FNAME], q[MAX_TEMPSTR], *editor;
324 struct stat statbuf, fsbuf;
328 int syntax_error = 0;
329 char orig_md5[MD5_SIZE];
330 char new_md5[MD5_SIZE];
332 log_it(RealUser, Pid, "BEGIN EDIT", User);
333 (void) snprintf(n, sizeof(n), CRON_TAB(User));
334 if (!(f = fopen(n, "r"))) {
336 err(ERROR_EXIT, "%s", n);
337 warnx("no crontab for %s - using an empty one", User);
338 if (!(f = fopen(_PATH_DEVNULL, "r")))
339 err(ERROR_EXIT, _PATH_DEVNULL);
343 (void) snprintf(Filename, sizeof(Filename), "/tmp/crontab.XXXXXXXXXX");
344 if ((t = mkstemp(Filename)) == -1) {
345 warn("%s", Filename);
351 if (fchown(t, getuid(), getgid()) < 0) {
353 if (chown(Filename, getuid(), getgid()) < 0) {
358 if (!(NewCrontab = fdopen(t, "r+"))) {
363 copy_file(f, NewCrontab);
365 if (fflush(NewCrontab))
366 err(ERROR_EXIT, "%s", Filename);
367 if (fstat(t, &fsbuf) < 0) {
368 warn("unable to fstat temp file");
372 if (swap_uids() < OK)
373 err(ERROR_EXIT, "swapping uids");
374 if (stat(Filename, &statbuf) < 0) {
376 fatal: unlink(Filename);
379 if (swap_uids_back() < OK)
380 err(ERROR_EXIT, "swapping uids back");
381 if (statbuf.st_dev != fsbuf.st_dev || statbuf.st_ino != fsbuf.st_ino)
382 errx(ERROR_EXIT, "temp file must be edited in place");
383 if (MD5File(Filename, orig_md5) == NULL) {
388 if ((!(editor = getenv("VISUAL")))
389 && (!(editor = getenv("EDITOR")))
394 /* we still have the file open. editors will generally rewrite the
395 * original file rather than renaming/unlinking it and starting a
396 * new one; even backup files are supposed to be made by copying
397 * rather than by renaming. if some editor does not support this,
398 * then don't use it. the security problems are more severe if we
399 * close and reopen the file around the edit.
402 switch (pid = fork()) {
408 if (setuid(getuid()) < 0)
409 err(ERROR_EXIT, "setuid(getuid())");
410 if (chdir("/tmp") < 0)
411 err(ERROR_EXIT, "chdir(/tmp)");
412 if (strlen(editor) + strlen(Filename) + 2 >= MAX_TEMPSTR)
413 errx(ERROR_EXIT, "editor or filename too long");
414 execlp(editor, editor, Filename, (char *)NULL);
415 err(ERROR_EXIT, "%s", editor);
424 void (*sig[3])(int signal);
425 sig[0] = signal(SIGHUP, SIG_IGN);
426 sig[1] = signal(SIGINT, SIG_IGN);
427 sig[2] = signal(SIGTERM, SIG_IGN);
428 xpid = wait(&waiter);
429 signal(SIGHUP, sig[0]);
430 signal(SIGINT, sig[1]);
431 signal(SIGTERM, sig[2]);
434 warnx("wrong PID (%d != %d) from \"%s\"", xpid, pid, editor);
437 if (WIFEXITED(waiter) && WEXITSTATUS(waiter)) {
438 warnx("\"%s\" exited with status %d", editor, WEXITSTATUS(waiter));
441 if (WIFSIGNALED(waiter)) {
442 warnx("\"%s\" killed; signal %d (%score dumped)",
443 editor, WTERMSIG(waiter), WCOREDUMP(waiter) ?"" :"no ");
446 if (swap_uids() < OK)
447 err(ERROR_EXIT, "swapping uids");
448 if (stat(Filename, &statbuf) < 0) {
452 if (statbuf.st_dev != fsbuf.st_dev || statbuf.st_ino != fsbuf.st_ino)
453 errx(ERROR_EXIT, "temp file must be edited in place");
454 if (MD5File(Filename, new_md5) == NULL) {
458 if (swap_uids_back() < OK)
459 err(ERROR_EXIT, "swapping uids back");
460 if (strcmp(orig_md5, new_md5) == 0 && !syntax_error) {
461 warnx("no changes made to crontab");
464 warnx("installing new crontab");
465 switch (replace_cmd()) {
466 case 0: /* Success */
468 case -1: /* Syntax error */
470 printf("Do you want to retry the same edit? ");
473 (void) fgets(q, sizeof q, stdin);
474 switch (islower(q[0]) ? q[0] : tolower(q[0])) {
481 fprintf(stderr, "Enter Y or N\n");
485 case -2: /* Install error */
487 warnx("edits left in %s", Filename);
490 warnx("panic: bad switch() in replace_cmd()");
496 log_it(RealUser, Pid, "END EDIT", User);
500 /* returns 0 on success
502 * -2 on install error
506 char n[MAX_FNAME], envstr[MAX_ENVSTR], tn[MAX_FNAME];
510 time_t now = time(NULL);
511 char **envp = env_init();
514 warnx("cannot allocate memory");
518 (void) snprintf(n, sizeof(n), "tmp.%d", Pid);
519 (void) snprintf(tn, sizeof(tn), CRON_TAB(n));
521 if (!(tmp = fopen(tn, "w+"))) {
526 /* write a signature at the top of the file.
528 * VERY IMPORTANT: make sure NHEADER_LINES agrees with this code.
530 fprintf(tmp, "# DO NOT EDIT THIS FILE - edit the master and reinstall.\n");
531 fprintf(tmp, "# (%s installed on %-24.24s)\n", Filename, ctime(&now));
532 fprintf(tmp, "# (Cron version -- %s)\n", rcsid);
534 /* copy the crontab to the tmp
538 while (EOF != (ch = get_char(NewCrontab)))
540 ftruncate(fileno(tmp), ftello(tmp));
541 fflush(tmp); rewind(tmp);
544 warnx("error while writing new crontab to %s", tn);
545 fclose(tmp); unlink(tn);
549 /* check the syntax of the file being installed.
552 /* BUG: was reporting errors after the EOF if there were any errors
553 * in the file proper -- kludged it by stopping after first error.
556 Set_LineNum(1 - NHEADER_LINES)
557 CheckErrorCount = 0; eof = FALSE;
558 while (!CheckErrorCount && !eof) {
559 switch (load_env(envstr, tmp)) {
564 e = load_entry(tmp, check_error, pw, envp);
573 if (CheckErrorCount != 0) {
574 warnx("errors in crontab file, can't install");
575 fclose(tmp); unlink(tn);
580 if (fchown(fileno(tmp), ROOT_UID, -1) < OK)
582 if (chown(tn, ROOT_UID, -1) < OK)
586 fclose(tmp); unlink(tn);
591 if (fchmod(fileno(tmp), 0600) < OK)
593 if (chmod(tn, 0600) < OK)
597 fclose(tmp); unlink(tn);
601 if (fclose(tmp) == EOF) {
607 (void) snprintf(n, sizeof(n), CRON_TAB(User));
609 warn("error renaming %s to %s", tn, n);
614 log_it(RealUser, Pid, "REPLACE", User);
617 * Creating the 'tn' temp file has already updated the
618 * modification time of the spool directory. Sleep for a
619 * second to ensure that poke_daemon() sets a later
620 * modification time. Otherwise, this can race with the cron
621 * daemon scanning for updated crontabs.
634 struct timeval tvs[2];
636 (void)gettimeofday(&tvs[0], NULL);
638 if (utimes(SPOOL_DIR, tvs) < OK) {
639 warn("can't update mtime on spooldir %s", SPOOL_DIR);
643 if (utime(SPOOL_DIR, NULL) < OK) {
644 warn("can't update mtime on spooldir %s", SPOOL_DIR);
647 #endif /*USE_UTIMES*/