xref: /freebsd/usr.sbin/cron/crontab/crontab.c (revision e93f27e3aeb7c0778012b7732bc6376e20f80427)
1 /* Copyright 1988,1990,1993,1994 by Paul Vixie
2  * All rights reserved
3  *
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
11  * user.
12  *
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
17  */
18 
19 #if !defined(lint) && !defined(LINT)
20 static const char rcsid[] =
21   "$FreeBSD$";
22 #endif
23 
24 /* crontab - install and manage per-user crontab files
25  * vix 02may87 [RCS has the rest of the log]
26  * vix 26jan87 [original]
27  */
28 
29 #define	MAIN_PROGRAM
30 
31 #include <sys/param.h>
32 #include "cron.h"
33 #include <errno.h>
34 #include <fcntl.h>
35 #include <md5.h>
36 #include <paths.h>
37 #include <sys/file.h>
38 #include <sys/stat.h>
39 #ifdef USE_UTIMES
40 # include <sys/time.h>
41 #else
42 # include <time.h>
43 # include <utime.h>
44 #endif
45 #if defined(POSIX)
46 # include <locale.h>
47 #endif
48 
49 #define MD5_SIZE 33
50 #define NHEADER_LINES 3
51 
52 
53 enum opt_t	{ opt_unknown, opt_list, opt_delete, opt_edit, opt_replace };
54 
55 #if DEBUGGING
56 static char	*Options[] = { "???", "list", "delete", "edit", "replace" };
57 #endif
58 
59 
60 static	PID_T		Pid;
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;
66 static	int		fflag;
67 static	struct passwd	*pw;
68 static	void		list_cmd(void),
69 			delete_cmd(void),
70 			edit_cmd(void),
71 			poke_daemon(void),
72 			check_error(char *),
73 			parse_args(int c, char *v[]);
74 static	int		replace_cmd(void);
75 
76 
77 static void
78 usage(char *msg)
79 {
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 }");
84 	exit(ERROR_EXIT);
85 }
86 
87 
88 int
89 main(int argc, char *argv[])
90 {
91 	int	exitstatus;
92 
93 	Pid = getpid();
94 	ProgramName = argv[0];
95 
96 #if defined(POSIX)
97 	setlocale(LC_ALL, "");
98 #endif
99 
100 #if defined(BSD)
101 	setlinebuf(stderr);
102 #endif
103 	parse_args(argc, argv);		/* sets many globals, opens a file */
104 	set_cron_uid();
105 	set_cron_cwd();
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");
109 		exit(ERROR_EXIT);
110 	}
111 	exitstatus = OK_EXIT;
112 	switch (Option) {
113 	case opt_list:		list_cmd();
114 				break;
115 	case opt_delete:	delete_cmd();
116 				break;
117 	case opt_edit:		edit_cmd();
118 				break;
119 	case opt_replace:	if (replace_cmd() < 0)
120 					exitstatus = ERROR_EXIT;
121 				break;
122 	case opt_unknown:
123 				break;
124 	}
125 	exit(exitstatus);
126 	/*NOTREACHED*/
127 }
128 
129 
130 static void
131 parse_args(int argc, char *argv[])
132 {
133 	int		argch;
134 	char		resolved_path[PATH_MAX];
135 
136 	if (!(pw = getpwuid(getuid())))
137 		errx(ERROR_EXIT, "your UID isn't in the passwd file, bailing out");
138 	bzero(pw->pw_passwd, strlen(pw->pw_passwd));
139 	(void) strncpy(User, pw->pw_name, (sizeof User)-1);
140 	User[(sizeof User)-1] = '\0';
141 	strcpy(RealUser, User);
142 	Filename[0] = '\0';
143 	Option = opt_unknown;
144 	while ((argch = getopt(argc, argv, "u:lerx:f")) != -1) {
145 		switch (argch) {
146 		case 'x':
147 			if (!set_debug_flags(optarg))
148 				usage("bad debug option");
149 			break;
150 		case 'u':
151 			if (getuid() != ROOT_UID)
152 				errx(ERROR_EXIT, "must be privileged to use -u");
153 			if (!(pw = getpwnam(optarg)))
154 				errx(ERROR_EXIT, "user `%s' unknown", optarg);
155 			bzero(pw->pw_passwd, strlen(pw->pw_passwd));
156 			(void) strncpy(User, pw->pw_name, (sizeof User)-1);
157 			User[(sizeof User)-1] = '\0';
158 			break;
159 		case 'l':
160 			if (Option != opt_unknown)
161 				usage("only one operation permitted");
162 			Option = opt_list;
163 			break;
164 		case 'r':
165 			if (Option != opt_unknown)
166 				usage("only one operation permitted");
167 			Option = opt_delete;
168 			break;
169 		case 'e':
170 			if (Option != opt_unknown)
171 				usage("only one operation permitted");
172 			Option = opt_edit;
173 			break;
174 		case 'f':
175 			fflag = 1;
176 			break;
177 		default:
178 			usage("unrecognized option");
179 		}
180 	}
181 
182 	endpwent();
183 
184 	if (Option != opt_unknown) {
185 		if (argv[optind] != NULL) {
186 			usage("no arguments permitted after this option");
187 		}
188 	} else {
189 		if (argv[optind] != NULL) {
190 			Option = opt_replace;
191 			(void) strncpy (Filename, argv[optind], (sizeof Filename)-1);
192 			Filename[(sizeof Filename)-1] = '\0';
193 
194 		} else {
195 			usage("file name must be specified for replace");
196 		}
197 	}
198 
199 	if (Option == opt_replace) {
200 		/* relinquish the setuid status of the binary during
201 		 * the open, lest nonroot users read files they should
202 		 * not be able to read.  we can't use access() here
203 		 * since there's a race condition.  thanks go out to
204 		 * Arnt Gulbrandsen <agulbra@pvv.unit.no> for spotting
205 		 * the race.
206 		 */
207 
208 		if (swap_uids() < OK)
209 			err(ERROR_EXIT, "swapping uids");
210 
211 		/* we have to open the file here because we're going to
212 		 * chdir(2) into /var/cron before we get around to
213 		 * reading the file.
214 		 */
215 		if (!strcmp(Filename, "-")) {
216 			NewCrontab = stdin;
217 		} else if (realpath(Filename, resolved_path) != NULL &&
218 		    !strcmp(resolved_path, SYSCRONTAB)) {
219 			err(ERROR_EXIT, SYSCRONTAB " must be edited manually");
220 		} else {
221 			if (!(NewCrontab = fopen(Filename, "r")))
222 				err(ERROR_EXIT, "%s", Filename);
223 		}
224 		if (swap_uids_back() < OK)
225 			err(ERROR_EXIT, "swapping uids back");
226 	}
227 
228 	Debug(DMISC, ("user=%s, file=%s, option=%s\n",
229 		      User, Filename, Options[(int)Option]))
230 }
231 
232 static void
233 copy_file(FILE *in, FILE *out) {
234 	int	x, ch;
235 
236 	Set_LineNum(1)
237 	/* ignore the top few comments since we probably put them there.
238 	 */
239 	for (x = 0;  x < NHEADER_LINES;  x++) {
240 		ch = get_char(in);
241 		if (EOF == ch)
242 			break;
243 		if ('#' != ch) {
244 			putc(ch, out);
245 			break;
246 		}
247 		while (EOF != (ch = get_char(in)))
248 			if (ch == '\n')
249 				break;
250 		if (EOF == ch)
251 			break;
252 	}
253 
254 	/* copy the rest of the crontab (if any) to the output file.
255 	 */
256 	if (EOF != ch)
257 		while (EOF != (ch = get_char(in)))
258 			putc(ch, out);
259 }
260 
261 static void
262 list_cmd(void)
263 {
264 	char	n[MAX_FNAME];
265 	FILE	*f;
266 
267 	log_it(RealUser, Pid, "LIST", User);
268 	(void) snprintf(n, sizeof(n), CRON_TAB(User));
269 	if (!(f = fopen(n, "r"))) {
270 		if (errno == ENOENT)
271 			errx(ERROR_EXIT, "no crontab for %s", User);
272 		else
273 			err(ERROR_EXIT, "%s", n);
274 	}
275 
276 	/* file is open. copy to stdout, close.
277 	 */
278 	copy_file(f, stdout);
279 	fclose(f);
280 }
281 
282 
283 static void
284 delete_cmd(void)
285 {
286 	char	n[MAX_FNAME];
287 	int ch, first;
288 
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)
293 			ch = getchar();
294 		if (first != 'y' && first != 'Y')
295 			return;
296 	}
297 
298 	log_it(RealUser, Pid, "DELETE", User);
299 	(void) snprintf(n, sizeof(n), CRON_TAB(User));
300 	if (unlink(n)) {
301 		if (errno == ENOENT)
302 			errx(ERROR_EXIT, "no crontab for %s", User);
303 		else
304 			err(ERROR_EXIT, "%s", n);
305 	}
306 	poke_daemon();
307 }
308 
309 
310 static void
311 check_error(char *msg)
312 {
313 	CheckErrorCount++;
314 	fprintf(stderr, "\"%s\":%d: %s\n", Filename, LineNumber-1, msg);
315 }
316 
317 
318 static void
319 edit_cmd(void)
320 {
321 	char		n[MAX_FNAME], q[MAX_TEMPSTR], *editor;
322 	FILE		*f;
323 	int		t;
324 	struct stat	statbuf, fsbuf;
325 	WAIT_T		waiter;
326 	PID_T		pid, xpid;
327 	mode_t		um;
328 	int		syntax_error = 0;
329 	char		orig_md5[MD5_SIZE];
330 	char		new_md5[MD5_SIZE];
331 
332 	log_it(RealUser, Pid, "BEGIN EDIT", User);
333 	(void) snprintf(n, sizeof(n), CRON_TAB(User));
334 	if (!(f = fopen(n, "r"))) {
335 		if (errno != ENOENT)
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);
340 	}
341 
342 	um = umask(077);
343 	(void) snprintf(Filename, sizeof(Filename), "/tmp/crontab.XXXXXXXXXX");
344 	if ((t = mkstemp(Filename)) == -1) {
345 		warn("%s", Filename);
346 		(void) umask(um);
347 		goto fatal;
348 	}
349 	(void) umask(um);
350 #ifdef HAS_FCHOWN
351 	if (fchown(t, getuid(), getgid()) < 0) {
352 #else
353 	if (chown(Filename, getuid(), getgid()) < 0) {
354 #endif
355 		warn("fchown");
356 		goto fatal;
357 	}
358 	if (!(NewCrontab = fdopen(t, "r+"))) {
359 		warn("fdopen");
360 		goto fatal;
361 	}
362 
363 	copy_file(f, NewCrontab);
364 	fclose(f);
365 	if (fflush(NewCrontab))
366 		err(ERROR_EXIT, "%s", Filename);
367 	if (fstat(t, &fsbuf) < 0) {
368 		warn("unable to fstat temp file");
369 		goto fatal;
370 	}
371  again:
372 	if (swap_uids() < OK)
373 		err(ERROR_EXIT, "swapping uids");
374 	if (stat(Filename, &statbuf) < 0) {
375 		warn("stat");
376  fatal:		unlink(Filename);
377 		exit(ERROR_EXIT);
378 	}
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) {
384 		warn("MD5");
385 		goto fatal;
386 	}
387 
388 	if ((!(editor = getenv("VISUAL")))
389 	 && (!(editor = getenv("EDITOR")))
390 	    ) {
391 		editor = EDITOR;
392 	}
393 
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.
400 	 */
401 
402 	switch (pid = fork()) {
403 	case -1:
404 		warn("fork");
405 		goto fatal;
406 	case 0:
407 		/* child */
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);
416 		/*NOTREACHED*/
417 	default:
418 		/* parent */
419 		break;
420 	}
421 
422 	/* parent */
423 	{
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]);
432 	}
433 	if (xpid != pid) {
434 		warnx("wrong PID (%d != %d) from \"%s\"", xpid, pid, editor);
435 		goto fatal;
436 	}
437 	if (WIFEXITED(waiter) && WEXITSTATUS(waiter)) {
438 		warnx("\"%s\" exited with status %d", editor, WEXITSTATUS(waiter));
439 		goto fatal;
440 	}
441 	if (WIFSIGNALED(waiter)) {
442 		warnx("\"%s\" killed; signal %d (%score dumped)",
443 			editor, WTERMSIG(waiter), WCOREDUMP(waiter) ?"" :"no ");
444 		goto fatal;
445 	}
446 	if (swap_uids() < OK)
447 		err(ERROR_EXIT, "swapping uids");
448 	if (stat(Filename, &statbuf) < 0) {
449 		warn("stat");
450 		goto fatal;
451 	}
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) {
455 		warn("MD5");
456 		goto fatal;
457 	}
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");
462 		goto remove;
463 	}
464 	warnx("installing new crontab");
465 	switch (replace_cmd()) {
466 	case 0:			/* Success */
467 		break;
468 	case -1:		/* Syntax error */
469 		for (;;) {
470 			printf("Do you want to retry the same edit? ");
471 			fflush(stdout);
472 			q[0] = '\0';
473 			(void) fgets(q, sizeof q, stdin);
474 			switch (islower(q[0]) ? q[0] : tolower(q[0])) {
475 			case 'y':
476 				syntax_error = 1;
477 				goto again;
478 			case 'n':
479 				goto abandon;
480 			default:
481 				fprintf(stderr, "Enter Y or N\n");
482 			}
483 		}
484 		/*NOTREACHED*/
485 	case -2:		/* Install error */
486 	abandon:
487 		warnx("edits left in %s", Filename);
488 		goto done;
489 	default:
490 		warnx("panic: bad switch() in replace_cmd()");
491 		goto fatal;
492 	}
493  remove:
494 	unlink(Filename);
495  done:
496 	log_it(RealUser, Pid, "END EDIT", User);
497 }
498 
499 
500 /* returns	0	on success
501  *		-1	on syntax error
502  *		-2	on install error
503  */
504 static int
505 replace_cmd(void)
506 {
507 	char	n[MAX_FNAME], envstr[MAX_ENVSTR], tn[MAX_FNAME];
508 	FILE	*tmp;
509 	int	ch, eof;
510 	entry	*e;
511 	time_t	now = time(NULL);
512 	char	**envp = env_init();
513 
514 	if (envp == NULL) {
515 		warnx("cannot allocate memory");
516 		return (-2);
517 	}
518 
519 	(void) snprintf(n, sizeof(n), "tmp.%d", Pid);
520 	(void) snprintf(tn, sizeof(tn), CRON_TAB(n));
521 
522 	if (!(tmp = fopen(tn, "w+"))) {
523 		warn("%s", tn);
524 		return (-2);
525 	}
526 
527 	/* write a signature at the top of the file.
528 	 *
529 	 * VERY IMPORTANT: make sure NHEADER_LINES agrees with this code.
530 	 */
531 	fprintf(tmp, "# DO NOT EDIT THIS FILE - edit the master and reinstall.\n");
532 	fprintf(tmp, "# (%s installed on %-24.24s)\n", Filename, ctime(&now));
533 	fprintf(tmp, "# (Cron version -- %s)\n", rcsid);
534 
535 	/* copy the crontab to the tmp
536 	 */
537 	rewind(NewCrontab);
538 	Set_LineNum(1)
539 	while (EOF != (ch = get_char(NewCrontab)))
540 		putc(ch, tmp);
541 	ftruncate(fileno(tmp), ftello(tmp));
542 	fflush(tmp);  rewind(tmp);
543 
544 	if (ferror(tmp)) {
545 		warnx("error while writing new crontab to %s", tn);
546 		fclose(tmp);  unlink(tn);
547 		return (-2);
548 	}
549 
550 	/* check the syntax of the file being installed.
551 	 */
552 
553 	/* BUG: was reporting errors after the EOF if there were any errors
554 	 * in the file proper -- kludged it by stopping after first error.
555 	 *		vix 31mar87
556 	 */
557 	Set_LineNum(1 - NHEADER_LINES)
558 	CheckErrorCount = 0;  eof = FALSE;
559 	while (!CheckErrorCount && !eof) {
560 		switch (load_env(envstr, tmp)) {
561 		case ERR:
562 			eof = TRUE;
563 			break;
564 		case FALSE:
565 			e = load_entry(tmp, check_error, pw, envp);
566 			if (e)
567 				free_entry(e);
568 			break;
569 		case TRUE:
570 			break;
571 		}
572 	}
573 
574 	if (CheckErrorCount != 0) {
575 		warnx("errors in crontab file, can't install");
576 		fclose(tmp);  unlink(tn);
577 		return (-1);
578 	}
579 
580 #ifdef HAS_FCHOWN
581 	if (fchown(fileno(tmp), ROOT_UID, -1) < OK)
582 #else
583 	if (chown(tn, ROOT_UID, -1) < OK)
584 #endif
585 	{
586 		warn("chown");
587 		fclose(tmp);  unlink(tn);
588 		return (-2);
589 	}
590 
591 #ifdef HAS_FCHMOD
592 	if (fchmod(fileno(tmp), 0600) < OK)
593 #else
594 	if (chmod(tn, 0600) < OK)
595 #endif
596 	{
597 		warn("chown");
598 		fclose(tmp);  unlink(tn);
599 		return (-2);
600 	}
601 
602 	if (fclose(tmp) == EOF) {
603 		warn("fclose");
604 		unlink(tn);
605 		return (-2);
606 	}
607 
608 	(void) snprintf(n, sizeof(n), CRON_TAB(User));
609 	if (rename(tn, n)) {
610 		warn("error renaming %s to %s", tn, n);
611 		unlink(tn);
612 		return (-2);
613 	}
614 
615 	log_it(RealUser, Pid, "REPLACE", User);
616 
617 	/*
618 	 * Creating the 'tn' temp file has already updated the
619 	 * modification time of the spool directory.  Sleep for a
620 	 * second to ensure that poke_daemon() sets a later
621 	 * modification time.  Otherwise, this can race with the cron
622 	 * daemon scanning for updated crontabs.
623 	 */
624 	sleep(1);
625 
626 	poke_daemon();
627 
628 	return (0);
629 }
630 
631 
632 static void
633 poke_daemon(void)
634 {
635 #ifdef USE_UTIMES
636 	struct timeval tvs[2];
637 
638 	(void)gettimeofday(&tvs[0], NULL);
639 	tvs[1] = tvs[0];
640 	if (utimes(SPOOL_DIR, tvs) < OK) {
641 		warn("can't update mtime on spooldir %s", SPOOL_DIR);
642 		return;
643 	}
644 #else
645 	if (utime(SPOOL_DIR, NULL) < OK) {
646 		warn("can't update mtime on spooldir %s", SPOOL_DIR);
647 		return;
648 	}
649 #endif /*USE_UTIMES*/
650 }
651