crontab.c revision 184779
1231200Smm/* Copyright 1988,1990,1993,1994 by Paul Vixie
2231200Smm * All rights reserved
3231200Smm *
4231200Smm * Distribute freely, except: don't remove my name from the source or
5231200Smm * documentation (don't take credit for my work), mark your changes (don't
6231200Smm * get me blamed for your possible bugs), don't alter or remove this
7231200Smm * notice.  May be sold if buildable source is provided to buyer.  No
8231200Smm * warrantee of any kind, express or implied, is included with this
9231200Smm * software; use at your own risk, responsibility for damages (if any) to
10231200Smm * anyone resulting from the use of this software rests entirely with the
11231200Smm * user.
12231200Smm *
13231200Smm * Send bug reports, bug fixes, enhancements, requests, flames, etc., and
14231200Smm * I'll try to keep a version up to date.  I can be reached as follows:
15231200Smm * Paul Vixie          <paul@vix.com>          uunet!decwrl!vixie!paul
16231200Smm * From Id: crontab.c,v 2.13 1994/01/17 03:20:37 vixie Exp
17231200Smm */
18231200Smm
19231200Smm#if !defined(lint) && !defined(LINT)
20231200Smmstatic const char rcsid[] =
21231200Smm  "$FreeBSD: head/usr.sbin/cron/crontab/crontab.c 184779 2008-11-09 06:44:53Z matteo $";
22231200Smm#endif
23231200Smm
24231200Smm/* crontab - install and manage per-user crontab files
25231200Smm * vix 02may87 [RCS has the rest of the log]
26231200Smm * vix 26jan87 [original]
27231200Smm */
28231200Smm
29231200Smm#define	MAIN_PROGRAM
30231200Smm
31231200Smm#include "cron.h"
32231200Smm#include <errno.h>
33231200Smm#include <fcntl.h>
34231200Smm#include <md5.h>
35231200Smm#include <paths.h>
36231200Smm#include <sys/file.h>
37231200Smm#include <sys/stat.h>
38231200Smm#ifdef USE_UTIMES
39231200Smm# include <sys/time.h>
40231200Smm#else
41231200Smm# include <time.h>
42231200Smm# include <utime.h>
43231200Smm#endif
44231200Smm#if defined(POSIX)
45231200Smm# include <locale.h>
46231200Smm#endif
47231200Smm
48231200Smm#define MD5_SIZE 33
49231200Smm#define NHEADER_LINES 3
50231200Smm
51231200Smm
52231200Smmenum opt_t	{ opt_unknown, opt_list, opt_delete, opt_edit, opt_replace };
53231200Smm
54231200Smm#if DEBUGGING
55231200Smmstatic char	*Options[] = { "???", "list", "delete", "edit", "replace" };
56231200Smm#endif
57231200Smm
58231200Smm
59231200Smmstatic	PID_T		Pid;
60231200Smmstatic	char		User[MAX_UNAME], RealUser[MAX_UNAME];
61231200Smmstatic	char		Filename[MAX_FNAME];
62231200Smmstatic	FILE		*NewCrontab;
63231200Smmstatic	int		CheckErrorCount;
64231200Smmstatic	enum opt_t	Option;
65231200Smmstatic	struct passwd	*pw;
66231200Smmstatic	void		list_cmd(void),
67231200Smm			delete_cmd(void),
68231200Smm			edit_cmd(void),
69231200Smm			poke_daemon(void),
70231200Smm			check_error(char *),
71231200Smm			parse_args(int c, char *v[]);
72231200Smmstatic	int		replace_cmd(void);
73231200Smm
74231200Smm
75231200Smmstatic void
76231200Smmusage(msg)
77231200Smm	char *msg;
78231200Smm{
79231200Smm	fprintf(stderr, "crontab: usage error: %s\n", msg);
80231200Smm	fprintf(stderr, "%s\n%s\n",
81231200Smm		"usage: crontab [-u user] file",
82231200Smm		"       crontab [-u user] { -e | -l | -r }");
83231200Smm	exit(ERROR_EXIT);
84231200Smm}
85231200Smm
86231200Smm
87231200Smmint
88231200Smmmain(argc, argv)
89231200Smm	int	argc;
90231200Smm	char	*argv[];
91231200Smm{
92231200Smm	int	exitstatus;
93231200Smm
94231200Smm	Pid = getpid();
95231200Smm	ProgramName = argv[0];
96231200Smm
97231200Smm#if defined(POSIX)
98231200Smm	setlocale(LC_ALL, "");
99231200Smm#endif
100231200Smm
101231200Smm#if defined(BSD)
102231200Smm	setlinebuf(stderr);
103231200Smm#endif
104231200Smm	parse_args(argc, argv);		/* sets many globals, opens a file */
105231200Smm	set_cron_uid();
106231200Smm	set_cron_cwd();
107231200Smm	if (!allowed(User)) {
108231200Smm		warnx("you (%s) are not allowed to use this program", User);
109231200Smm		log_it(RealUser, Pid, "AUTH", "crontab command not allowed");
110231200Smm		exit(ERROR_EXIT);
111231200Smm	}
112231200Smm	exitstatus = OK_EXIT;
113231200Smm	switch (Option) {
114231200Smm	case opt_list:		list_cmd();
115231200Smm				break;
116231200Smm	case opt_delete:	delete_cmd();
117231200Smm				break;
118231200Smm	case opt_edit:		edit_cmd();
119231200Smm				break;
120231200Smm	case opt_replace:	if (replace_cmd() < 0)
121231200Smm					exitstatus = ERROR_EXIT;
122231200Smm				break;
123231200Smm	case opt_unknown:
124231200Smm				break;
125231200Smm	}
126231200Smm	exit(exitstatus);
127231200Smm	/*NOTREACHED*/
128231200Smm}
129231200Smm
130231200Smm
131231200Smmstatic void
132231200Smmparse_args(argc, argv)
133231200Smm	int	argc;
134231200Smm	char	*argv[];
135231200Smm{
136231200Smm	int		argch;
137231200Smm	char		resolved_path[PATH_MAX];
138231200Smm
139231200Smm	if (!(pw = getpwuid(getuid())))
140231200Smm		errx(ERROR_EXIT, "your UID isn't in the passwd file, bailing out");
141231200Smm	bzero(pw->pw_passwd, strlen(pw->pw_passwd));
142231200Smm	(void) strncpy(User, pw->pw_name, (sizeof User)-1);
143231200Smm	User[(sizeof User)-1] = '\0';
144231200Smm	strcpy(RealUser, User);
145231200Smm	Filename[0] = '\0';
146231200Smm	Option = opt_unknown;
147231200Smm	while ((argch = getopt(argc, argv, "u:lerx:")) != -1) {
148231200Smm		switch (argch) {
149231200Smm		case 'x':
150231200Smm			if (!set_debug_flags(optarg))
151231200Smm				usage("bad debug option");
152231200Smm			break;
153231200Smm		case 'u':
154231200Smm			if (getuid() != ROOT_UID)
155231200Smm				errx(ERROR_EXIT, "must be privileged to use -u");
156231200Smm			if (!(pw = getpwnam(optarg)))
157231200Smm				errx(ERROR_EXIT, "user `%s' unknown", optarg);
158231200Smm			bzero(pw->pw_passwd, strlen(pw->pw_passwd));
159231200Smm			(void) strncpy(User, pw->pw_name, (sizeof User)-1);
160231200Smm			User[(sizeof User)-1] = '\0';
161231200Smm			break;
162231200Smm		case 'l':
163231200Smm			if (Option != opt_unknown)
164231200Smm				usage("only one operation permitted");
165231200Smm			Option = opt_list;
166231200Smm			break;
167231200Smm		case 'r':
168231200Smm			if (Option != opt_unknown)
169231200Smm				usage("only one operation permitted");
170231200Smm			Option = opt_delete;
171231200Smm			break;
172231200Smm		case 'e':
173231200Smm			if (Option != opt_unknown)
174231200Smm				usage("only one operation permitted");
175231200Smm			Option = opt_edit;
176231200Smm			break;
177231200Smm		default:
178231200Smm			usage("unrecognized option");
179231200Smm		}
180231200Smm	}
181231200Smm
182231200Smm	endpwent();
183231200Smm
184231200Smm	if (Option != opt_unknown) {
185231200Smm		if (argv[optind] != NULL) {
186231200Smm			usage("no arguments permitted after this option");
187231200Smm		}
188231200Smm	} else {
189231200Smm		if (argv[optind] != NULL) {
190231200Smm			Option = opt_replace;
191231200Smm			(void) strncpy (Filename, argv[optind], (sizeof Filename)-1);
192231200Smm			Filename[(sizeof Filename)-1] = '\0';
193231200Smm
194231200Smm		} else {
195231200Smm			usage("file name must be specified for replace");
196231200Smm		}
197231200Smm	}
198231200Smm
199231200Smm	if (Option == opt_replace) {
200231200Smm		/* we have to open the file here because we're going to
201231200Smm		 * chdir(2) into /var/cron before we get around to
202231200Smm		 * reading the file.
203231200Smm		 */
204231200Smm		if (!strcmp(Filename, "-")) {
205231200Smm			NewCrontab = stdin;
206231200Smm		} else if (realpath(Filename, resolved_path) != NULL &&
207231200Smm		    !strcmp(resolved_path, SYSCRONTAB)) {
208231200Smm			err(ERROR_EXIT, SYSCRONTAB " must be edited manually");
209231200Smm		} else {
210231200Smm			/* relinquish the setuid status of the binary during
211231200Smm			 * the open, lest nonroot users read files they should
212231200Smm			 * not be able to read.  we can't use access() here
213231200Smm			 * since there's a race condition.  thanks go out to
214231200Smm			 * Arnt Gulbrandsen <agulbra@pvv.unit.no> for spotting
215231200Smm			 * the race.
216231200Smm			 */
217231200Smm
218231200Smm			if (swap_uids() < OK)
219231200Smm				err(ERROR_EXIT, "swapping uids");
220231200Smm			if (!(NewCrontab = fopen(Filename, "r")))
221231200Smm				err(ERROR_EXIT, "%s", Filename);
222231200Smm			if (swap_uids() < OK)
223231200Smm				err(ERROR_EXIT, "swapping uids back");
224231200Smm		}
225231200Smm	}
226231200Smm
227231200Smm	Debug(DMISC, ("user=%s, file=%s, option=%s\n",
228231200Smm		      User, Filename, Options[(int)Option]))
229231200Smm}
230231200Smm
231231200Smmstatic void
232231200Smmcopy_file(FILE *in, FILE *out) {
233231200Smm	int	x, ch;
234231200Smm
235231200Smm	Set_LineNum(1)
236231200Smm	/* ignore the top few comments since we probably put them there.
237231200Smm	 */
238231200Smm	for (x = 0;  x < NHEADER_LINES;  x++) {
239231200Smm		ch = get_char(in);
240231200Smm		if (EOF == ch)
241231200Smm			break;
242231200Smm		if ('#' != ch) {
243231200Smm			putc(ch, out);
244231200Smm			break;
245231200Smm		}
246231200Smm		while (EOF != (ch = get_char(in)))
247231200Smm			if (ch == '\n')
248231200Smm				break;
249231200Smm		if (EOF == ch)
250248616Smm			break;
251231200Smm	}
252231200Smm
253231200Smm	/* copy the rest of the crontab (if any) to the output file.
254231200Smm	 */
255231200Smm	if (EOF != ch)
256231200Smm		while (EOF != (ch = get_char(in)))
257231200Smm			putc(ch, out);
258231200Smm}
259231200Smm
260231200Smmstatic void
261231200Smmlist_cmd() {
262231200Smm	char	n[MAX_FNAME];
263231200Smm	FILE	*f;
264231200Smm
265231200Smm	log_it(RealUser, Pid, "LIST", User);
266231200Smm	(void) snprintf(n, sizeof(n), CRON_TAB(User));
267231200Smm	if (!(f = fopen(n, "r"))) {
268231200Smm		if (errno == ENOENT)
269231200Smm			errx(ERROR_EXIT, "no crontab for %s", User);
270231200Smm		else
271231200Smm			err(ERROR_EXIT, "%s", n);
272231200Smm	}
273231200Smm
274231200Smm	/* file is open. copy to stdout, close.
275231200Smm	 */
276231200Smm	copy_file(f, stdout);
277231200Smm	fclose(f);
278231200Smm}
279
280
281static void
282delete_cmd() {
283	char	n[MAX_FNAME];
284	int ch, first;
285
286	if (isatty(STDIN_FILENO)) {
287		(void)fprintf(stderr, "remove crontab for %s? ", User);
288		first = ch = getchar();
289		while (ch != '\n' && ch != EOF)
290			ch = getchar();
291		if (first != 'y' && first != 'Y')
292			return;
293	}
294
295	log_it(RealUser, Pid, "DELETE", User);
296	(void) snprintf(n, sizeof(n), CRON_TAB(User));
297	if (unlink(n)) {
298		if (errno == ENOENT)
299			errx(ERROR_EXIT, "no crontab for %s", User);
300		else
301			err(ERROR_EXIT, "%s", n);
302	}
303	poke_daemon();
304}
305
306
307static void
308check_error(msg)
309	char	*msg;
310{
311	CheckErrorCount++;
312	fprintf(stderr, "\"%s\":%d: %s\n", Filename, LineNumber-1, msg);
313}
314
315
316static void
317edit_cmd() {
318	char		n[MAX_FNAME], q[MAX_TEMPSTR], *editor;
319	FILE		*f;
320	int		t;
321	struct stat	statbuf, fsbuf;
322	WAIT_T		waiter;
323	PID_T		pid, xpid;
324	mode_t		um;
325	int		syntax_error = 0;
326	char		orig_md5[MD5_SIZE];
327	char		new_md5[MD5_SIZE];
328
329	log_it(RealUser, Pid, "BEGIN EDIT", User);
330	(void) snprintf(n, sizeof(n), CRON_TAB(User));
331	if (!(f = fopen(n, "r"))) {
332		if (errno != ENOENT)
333			err(ERROR_EXIT, "%s", n);
334		warnx("no crontab for %s - using an empty one", User);
335		if (!(f = fopen(_PATH_DEVNULL, "r")))
336			err(ERROR_EXIT, _PATH_DEVNULL);
337	}
338
339	um = umask(077);
340	(void) snprintf(Filename, sizeof(Filename), "/tmp/crontab.XXXXXXXXXX");
341	if ((t = mkstemp(Filename)) == -1) {
342		warn("%s", Filename);
343		(void) umask(um);
344		goto fatal;
345	}
346	(void) umask(um);
347#ifdef HAS_FCHOWN
348	if (fchown(t, getuid(), getgid()) < 0) {
349#else
350	if (chown(Filename, getuid(), getgid()) < 0) {
351#endif
352		warn("fchown");
353		goto fatal;
354	}
355	if (!(NewCrontab = fdopen(t, "r+"))) {
356		warn("fdopen");
357		goto fatal;
358	}
359
360	copy_file(f, NewCrontab);
361	fclose(f);
362	if (fflush(NewCrontab))
363		err(ERROR_EXIT, "%s", Filename);
364	if (fstat(t, &fsbuf) < 0) {
365		warn("unable to fstat temp file");
366		goto fatal;
367	}
368 again:
369	if (stat(Filename, &statbuf) < 0) {
370		warn("stat");
371 fatal:		unlink(Filename);
372		exit(ERROR_EXIT);
373	}
374	if (statbuf.st_dev != fsbuf.st_dev || statbuf.st_ino != fsbuf.st_ino)
375		errx(ERROR_EXIT, "temp file must be edited in place");
376	if (MD5File(Filename, orig_md5) == NULL) {
377		warn("MD5");
378		goto fatal;
379	}
380
381	if ((!(editor = getenv("VISUAL")))
382	 && (!(editor = getenv("EDITOR")))
383	    ) {
384		editor = EDITOR;
385	}
386
387	/* we still have the file open.  editors will generally rewrite the
388	 * original file rather than renaming/unlinking it and starting a
389	 * new one; even backup files are supposed to be made by copying
390	 * rather than by renaming.  if some editor does not support this,
391	 * then don't use it.  the security problems are more severe if we
392	 * close and reopen the file around the edit.
393	 */
394
395	switch (pid = fork()) {
396	case -1:
397		warn("fork");
398		goto fatal;
399	case 0:
400		/* child */
401		if (setuid(getuid()) < 0)
402			err(ERROR_EXIT, "setuid(getuid())");
403		if (chdir("/tmp") < 0)
404			err(ERROR_EXIT, "chdir(/tmp)");
405		if (strlen(editor) + strlen(Filename) + 2 >= MAX_TEMPSTR)
406			errx(ERROR_EXIT, "editor or filename too long");
407		execlp(editor, editor, Filename, (char *)NULL);
408		err(ERROR_EXIT, "%s", editor);
409		/*NOTREACHED*/
410	default:
411		/* parent */
412		break;
413	}
414
415	/* parent */
416	{
417	void (*f[4])();
418	f[0] = signal(SIGHUP, SIG_IGN);
419	f[1] = signal(SIGINT, SIG_IGN);
420	f[2] = signal(SIGTERM, SIG_IGN);
421	xpid = wait(&waiter);
422	signal(SIGHUP, f[0]);
423	signal(SIGINT, f[1]);
424	signal(SIGTERM, f[2]);
425	}
426	if (xpid != pid) {
427		warnx("wrong PID (%d != %d) from \"%s\"", xpid, pid, editor);
428		goto fatal;
429	}
430	if (WIFEXITED(waiter) && WEXITSTATUS(waiter)) {
431		warnx("\"%s\" exited with status %d", editor, WEXITSTATUS(waiter));
432		goto fatal;
433	}
434	if (WIFSIGNALED(waiter)) {
435		warnx("\"%s\" killed; signal %d (%score dumped)",
436			editor, WTERMSIG(waiter), WCOREDUMP(waiter) ?"" :"no ");
437		goto fatal;
438	}
439	if (stat(Filename, &statbuf) < 0) {
440		warn("stat");
441		goto fatal;
442	}
443	if (statbuf.st_dev != fsbuf.st_dev || statbuf.st_ino != fsbuf.st_ino)
444		errx(ERROR_EXIT, "temp file must be edited in place");
445	if (MD5File(Filename, new_md5) == NULL) {
446		warn("MD5");
447		goto fatal;
448	}
449	if (strcmp(orig_md5, new_md5) == 0 && !syntax_error) {
450		warnx("no changes made to crontab");
451		goto remove;
452	}
453	warnx("installing new crontab");
454	switch (replace_cmd()) {
455	case 0:			/* Success */
456		break;
457	case -1:		/* Syntax error */
458		for (;;) {
459			printf("Do you want to retry the same edit? ");
460			fflush(stdout);
461			q[0] = '\0';
462			(void) fgets(q, sizeof q, stdin);
463			switch (islower(q[0]) ? q[0] : tolower(q[0])) {
464			case 'y':
465				syntax_error = 1;
466				goto again;
467			case 'n':
468				goto abandon;
469			default:
470				fprintf(stderr, "Enter Y or N\n");
471			}
472		}
473		/*NOTREACHED*/
474	case -2:		/* Install error */
475	abandon:
476		warnx("edits left in %s", Filename);
477		goto done;
478	default:
479		warnx("panic: bad switch() in replace_cmd()");
480		goto fatal;
481	}
482 remove:
483	unlink(Filename);
484 done:
485	log_it(RealUser, Pid, "END EDIT", User);
486}
487
488
489/* returns	0	on success
490 *		-1	on syntax error
491 *		-2	on install error
492 */
493static int
494replace_cmd() {
495	char	n[MAX_FNAME], envstr[MAX_ENVSTR], tn[MAX_FNAME];
496	FILE	*tmp;
497	int	ch, eof;
498	entry	*e;
499	time_t	now = time(NULL);
500	char	**envp = env_init();
501
502	if (envp == NULL) {
503		warnx("cannot allocate memory");
504		return (-2);
505	}
506
507	(void) snprintf(n, sizeof(n), "tmp.%d", Pid);
508	(void) snprintf(tn, sizeof(n), CRON_TAB(n));
509	if (!(tmp = fopen(tn, "w+"))) {
510		warn("%s", tn);
511		return (-2);
512	}
513
514	/* write a signature at the top of the file.
515	 *
516	 * VERY IMPORTANT: make sure NHEADER_LINES agrees with this code.
517	 */
518	fprintf(tmp, "# DO NOT EDIT THIS FILE - edit the master and reinstall.\n");
519	fprintf(tmp, "# (%s installed on %-24.24s)\n", Filename, ctime(&now));
520	fprintf(tmp, "# (Cron version -- %s)\n", rcsid);
521
522	/* copy the crontab to the tmp
523	 */
524	rewind(NewCrontab);
525	Set_LineNum(1)
526	while (EOF != (ch = get_char(NewCrontab)))
527		putc(ch, tmp);
528	ftruncate(fileno(tmp), ftell(tmp));
529	fflush(tmp);  rewind(tmp);
530
531	if (ferror(tmp)) {
532		warnx("error while writing new crontab to %s", tn);
533		fclose(tmp);  unlink(tn);
534		return (-2);
535	}
536
537	/* check the syntax of the file being installed.
538	 */
539
540	/* BUG: was reporting errors after the EOF if there were any errors
541	 * in the file proper -- kludged it by stopping after first error.
542	 *		vix 31mar87
543	 */
544	Set_LineNum(1 - NHEADER_LINES)
545	CheckErrorCount = 0;  eof = FALSE;
546	while (!CheckErrorCount && !eof) {
547		switch (load_env(envstr, tmp)) {
548		case ERR:
549			eof = TRUE;
550			break;
551		case FALSE:
552			e = load_entry(tmp, check_error, pw, envp);
553			if (e)
554				free(e);
555			break;
556		case TRUE:
557			break;
558		}
559	}
560
561	if (CheckErrorCount != 0) {
562		warnx("errors in crontab file, can't install");
563		fclose(tmp);  unlink(tn);
564		return (-1);
565	}
566
567#ifdef HAS_FCHOWN
568	if (fchown(fileno(tmp), ROOT_UID, -1) < OK)
569#else
570	if (chown(tn, ROOT_UID, -1) < OK)
571#endif
572	{
573		warn("chown");
574		fclose(tmp);  unlink(tn);
575		return (-2);
576	}
577
578#ifdef HAS_FCHMOD
579	if (fchmod(fileno(tmp), 0600) < OK)
580#else
581	if (chmod(tn, 0600) < OK)
582#endif
583	{
584		warn("chown");
585		fclose(tmp);  unlink(tn);
586		return (-2);
587	}
588
589	if (fclose(tmp) == EOF) {
590		warn("fclose");
591		unlink(tn);
592		return (-2);
593	}
594
595	(void) snprintf(n, sizeof(n), CRON_TAB(User));
596	if (rename(tn, n)) {
597		warn("error renaming %s to %s", tn, n);
598		unlink(tn);
599		return (-2);
600	}
601	log_it(RealUser, Pid, "REPLACE", User);
602
603	poke_daemon();
604
605	return (0);
606}
607
608
609static void
610poke_daemon() {
611#ifdef USE_UTIMES
612	struct timeval tvs[2];
613	struct timezone tz;
614
615	(void) gettimeofday(&tvs[0], &tz);
616	tvs[1] = tvs[0];
617	if (utimes(SPOOL_DIR, tvs) < OK) {
618		warn("can't update mtime on spooldir %s", SPOOL_DIR);
619		return;
620	}
621#else
622	if (utime(SPOOL_DIR, NULL) < OK) {
623		warn("can't update mtime on spooldir %s", SPOOL_DIR);
624		return;
625	}
626#endif /*USE_UTIMES*/
627}
628