crontab.c revision 135165
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)
20static const char rcsid[] =
21  "$FreeBSD: head/usr.sbin/cron/crontab/crontab.c 135165 2004-09-13 18:39:04Z dds $";
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 "cron.h"
32#include <errno.h>
33#include <fcntl.h>
34#include <paths.h>
35#include <sys/file.h>
36#include <sys/stat.h>
37#ifdef USE_UTIMES
38# include <sys/time.h>
39#else
40# include <time.h>
41# include <utime.h>
42#endif
43#if defined(POSIX)
44# include <locale.h>
45#endif
46
47
48#define NHEADER_LINES 3
49
50
51enum opt_t	{ opt_unknown, opt_list, opt_delete, opt_edit, opt_replace };
52
53#if DEBUGGING
54static char	*Options[] = { "???", "list", "delete", "edit", "replace" };
55#endif
56
57
58static	PID_T		Pid;
59static	char		User[MAX_UNAME], RealUser[MAX_UNAME];
60static	char		Filename[MAX_FNAME];
61static	FILE		*NewCrontab;
62static	int		CheckErrorCount;
63static	enum opt_t	Option;
64static	struct passwd	*pw;
65static	void		list_cmd __P((void)),
66			delete_cmd __P((void)),
67			edit_cmd __P((void)),
68			poke_daemon __P((void)),
69			check_error __P((char *)),
70			parse_args __P((int c, char *v[]));
71static	int		replace_cmd __P((void));
72
73
74static void
75usage(msg)
76	char *msg;
77{
78	fprintf(stderr, "crontab: usage error: %s\n", msg);
79	fprintf(stderr, "%s\n%s\n",
80		"usage: crontab [-u user] file",
81		"       crontab [-u user] { -e | -l | -r }");
82	exit(ERROR_EXIT);
83}
84
85
86int
87main(argc, argv)
88	int	argc;
89	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
130static void
131parse_args(argc, argv)
132	int	argc;
133	char	*argv[];
134{
135	int		argch;
136
137	if (!(pw = getpwuid(getuid())))
138		errx(ERROR_EXIT, "your UID isn't in the passwd file, bailing out");
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:")) != -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			(void) strncpy(User, pw->pw_name, (sizeof User)-1);
156			User[(sizeof User)-1] = '\0';
157			break;
158		case 'l':
159			if (Option != opt_unknown)
160				usage("only one operation permitted");
161			Option = opt_list;
162			break;
163		case 'r':
164			if (Option != opt_unknown)
165				usage("only one operation permitted");
166			Option = opt_delete;
167			break;
168		case 'e':
169			if (Option != opt_unknown)
170				usage("only one operation permitted");
171			Option = opt_edit;
172			break;
173		default:
174			usage("unrecognized option");
175		}
176	}
177
178	endpwent();
179
180	if (Option != opt_unknown) {
181		if (argv[optind] != NULL) {
182			usage("no arguments permitted after this option");
183		}
184	} else {
185		if (argv[optind] != NULL) {
186			Option = opt_replace;
187			(void) strncpy (Filename, argv[optind], (sizeof Filename)-1);
188			Filename[(sizeof Filename)-1] = '\0';
189
190		} else {
191			usage("file name must be specified for replace");
192		}
193	}
194
195	if (Option == opt_replace) {
196		/* we have to open the file here because we're going to
197		 * chdir(2) into /var/cron before we get around to
198		 * reading the file.
199		 */
200		if (!strcmp(Filename, "-")) {
201			NewCrontab = stdin;
202		} else {
203			/* relinquish the setuid status of the binary during
204			 * the open, lest nonroot users read files they should
205			 * not be able to read.  we can't use access() here
206			 * since there's a race condition.  thanks go out to
207			 * Arnt Gulbrandsen <agulbra@pvv.unit.no> for spotting
208			 * the race.
209			 */
210
211			if (swap_uids() < OK)
212				err(ERROR_EXIT, "swapping uids");
213			if (!(NewCrontab = fopen(Filename, "r")))
214				err(ERROR_EXIT, "%s", Filename);
215			if (swap_uids() < OK)
216				err(ERROR_EXIT, "swapping uids back");
217		}
218	}
219
220	Debug(DMISC, ("user=%s, file=%s, option=%s\n",
221		      User, Filename, Options[(int)Option]))
222}
223
224
225static void
226list_cmd() {
227	char	n[MAX_FNAME];
228	FILE	*f;
229	int	ch, x;
230
231	log_it(RealUser, Pid, "LIST", User);
232	(void) sprintf(n, CRON_TAB(User));
233	if (!(f = fopen(n, "r"))) {
234		if (errno == ENOENT)
235			errx(ERROR_EXIT, "no crontab for %s", User);
236		else
237			err(ERROR_EXIT, "%s", n);
238	}
239
240	/* file is open. copy to stdout, close.
241	 */
242	Set_LineNum(1)
243
244	/* ignore the top few comments since we probably put them there.
245	 */
246	for (x = 0;  x < NHEADER_LINES;  x++) {
247		ch = get_char(f);
248		if (EOF == ch)
249			break;
250		if ('#' != ch) {
251			putchar(ch);
252			break;
253		}
254		while (EOF != (ch = get_char(f)))
255			if (ch == '\n')
256				break;
257		if (EOF == ch)
258			break;
259	}
260
261	while (EOF != (ch = get_char(f)))
262		putchar(ch);
263	fclose(f);
264}
265
266
267static void
268delete_cmd() {
269	char	n[MAX_FNAME];
270	int ch, first;
271
272	if (isatty(STDIN_FILENO)) {
273		(void)fprintf(stderr, "remove crontab for %s? ", User);
274		first = ch = getchar();
275		while (ch != '\n' && ch != EOF)
276			ch = getchar();
277		if (first != 'y' && first != 'Y')
278			return;
279	}
280
281	log_it(RealUser, Pid, "DELETE", User);
282	(void) sprintf(n, CRON_TAB(User));
283	if (unlink(n)) {
284		if (errno == ENOENT)
285			errx(ERROR_EXIT, "no crontab for %s", User);
286		else
287			err(ERROR_EXIT, "%s", n);
288	}
289	poke_daemon();
290}
291
292
293static void
294check_error(msg)
295	char	*msg;
296{
297	CheckErrorCount++;
298	fprintf(stderr, "\"%s\":%d: %s\n", Filename, LineNumber-1, msg);
299}
300
301
302static void
303edit_cmd() {
304	char		n[MAX_FNAME], q[MAX_TEMPSTR], *editor;
305	FILE		*f;
306	int		ch, t, x;
307	struct stat	statbuf, fsbuf;
308	time_t		mtime;
309	WAIT_T		waiter;
310	PID_T		pid, xpid;
311	mode_t		um;
312	int		syntax_error = 0;
313
314	log_it(RealUser, Pid, "BEGIN EDIT", User);
315	(void) sprintf(n, CRON_TAB(User));
316	if (!(f = fopen(n, "r"))) {
317		if (errno != ENOENT)
318			err(ERROR_EXIT, "%s", n);
319		warnx("no crontab for %s - using an empty one", User);
320		if (!(f = fopen(_PATH_DEVNULL, "r")))
321			err(ERROR_EXIT, _PATH_DEVNULL);
322	}
323
324	um = umask(077);
325	(void) sprintf(Filename, "/tmp/crontab.XXXXXXXXXX");
326	if ((t = mkstemp(Filename)) == -1) {
327		warn("%s", Filename);
328		(void) umask(um);
329		goto fatal;
330	}
331	(void) umask(um);
332#ifdef HAS_FCHOWN
333	if (fchown(t, getuid(), getgid()) < 0) {
334#else
335	if (chown(Filename, getuid(), getgid()) < 0) {
336#endif
337		warn("fchown");
338		goto fatal;
339	}
340	if (!(NewCrontab = fdopen(t, "r+"))) {
341		warn("fdopen");
342		goto fatal;
343	}
344
345	Set_LineNum(1)
346
347	/* ignore the top few comments since we probably put them there.
348	 */
349	for (x = 0;  x < NHEADER_LINES;  x++) {
350		ch = get_char(f);
351		if (EOF == ch)
352			break;
353		if ('#' != ch) {
354			putc(ch, NewCrontab);
355			break;
356		}
357		while (EOF != (ch = get_char(f)))
358			if (ch == '\n')
359				break;
360		if (EOF == ch)
361			break;
362	}
363
364	/* copy the rest of the crontab (if any) to the temp file.
365	 */
366	if (EOF != ch)
367		while (EOF != (ch = get_char(f)))
368			putc(ch, NewCrontab);
369	fclose(f);
370	if (fflush(NewCrontab))
371		err(ERROR_EXIT, "%s", Filename);
372	if (fstat(t, &fsbuf) < 0) {
373		warn("unable to fstat temp file");
374		goto fatal;
375	}
376 again:
377	if (stat(Filename, &statbuf) < 0) {
378		warn("stat");
379 fatal:		unlink(Filename);
380		exit(ERROR_EXIT);
381	}
382	if (statbuf.st_dev != fsbuf.st_dev || statbuf.st_ino != fsbuf.st_ino)
383		errx(ERROR_EXIT, "temp file must be edited in place");
384	mtime = statbuf.st_mtime;
385
386	if ((!(editor = getenv("VISUAL")))
387	 && (!(editor = getenv("EDITOR")))
388	    ) {
389		editor = EDITOR;
390	}
391
392	/* we still have the file open.  editors will generally rewrite the
393	 * original file rather than renaming/unlinking it and starting a
394	 * new one; even backup files are supposed to be made by copying
395	 * rather than by renaming.  if some editor does not support this,
396	 * then don't use it.  the security problems are more severe if we
397	 * close and reopen the file around the edit.
398	 */
399
400	switch (pid = fork()) {
401	case -1:
402		warn("fork");
403		goto fatal;
404	case 0:
405		/* child */
406		if (setuid(getuid()) < 0)
407			err(ERROR_EXIT, "setuid(getuid())");
408		if (chdir("/tmp") < 0)
409			err(ERROR_EXIT, "chdir(/tmp)");
410		if (strlen(editor) + strlen(Filename) + 2 >= MAX_TEMPSTR)
411			errx(ERROR_EXIT, "editor or filename too long");
412		execlp(editor, editor, Filename, (char *)NULL);
413		err(ERROR_EXIT, "%s", editor);
414		/*NOTREACHED*/
415	default:
416		/* parent */
417		break;
418	}
419
420	/* parent */
421	{
422	void (*f[4])();
423	f[0] = signal(SIGHUP, SIG_IGN);
424	f[1] = signal(SIGINT, SIG_IGN);
425	f[2] = signal(SIGTERM, SIG_IGN);
426	xpid = wait(&waiter);
427	signal(SIGHUP, f[0]);
428	signal(SIGINT, f[1]);
429	signal(SIGTERM, f[2]);
430	}
431	if (xpid != pid) {
432		warnx("wrong PID (%d != %d) from \"%s\"", xpid, pid, editor);
433		goto fatal;
434	}
435	if (WIFEXITED(waiter) && WEXITSTATUS(waiter)) {
436		warnx("\"%s\" exited with status %d", editor, WEXITSTATUS(waiter));
437		goto fatal;
438	}
439	if (WIFSIGNALED(waiter)) {
440		warnx("\"%s\" killed; signal %d (%score dumped)",
441			editor, WTERMSIG(waiter), WCOREDUMP(waiter) ?"" :"no ");
442		goto fatal;
443	}
444	if (stat(Filename, &statbuf) < 0) {
445		warn("stat");
446		goto fatal;
447	}
448	if (statbuf.st_dev != fsbuf.st_dev || statbuf.st_ino != fsbuf.st_ino)
449		errx(ERROR_EXIT, "temp file must be edited in place");
450	if (mtime == statbuf.st_mtime && !syntax_error) {
451		warnx("no changes made to crontab");
452		goto remove;
453	}
454	warnx("installing new crontab");
455	switch (replace_cmd()) {
456	case 0:			/* Success */
457		break;
458	case -1:		/* Syntax error */
459		for (;;) {
460			printf("Do you want to retry the same edit? ");
461			fflush(stdout);
462			q[0] = '\0';
463			(void) fgets(q, sizeof q, stdin);
464			switch (islower(q[0]) ? q[0] : tolower(q[0])) {
465			case 'y':
466				syntax_error = 1;
467				goto again;
468			case 'n':
469				goto abandon;
470			default:
471				fprintf(stderr, "Enter Y or N\n");
472			}
473		}
474		/*NOTREACHED*/
475	case -2:		/* Install error */
476	abandon:
477		warnx("edits left in %s", Filename);
478		goto done;
479	default:
480		warnx("panic: bad switch() in replace_cmd()");
481		goto fatal;
482	}
483 remove:
484	unlink(Filename);
485 done:
486	log_it(RealUser, Pid, "END EDIT", User);
487}
488
489
490/* returns	0	on success
491 *		-1	on syntax error
492 *		-2	on install error
493 */
494static int
495replace_cmd() {
496	char	n[MAX_FNAME], envstr[MAX_ENVSTR], tn[MAX_FNAME];
497	FILE	*tmp;
498	int	ch, eof;
499	entry	*e;
500	time_t	now = time(NULL);
501	char	**envp = env_init();
502
503	if (envp == NULL) {
504		warnx("cannot allocate memory");
505		return (-2);
506	}
507
508	(void) sprintf(n, "tmp.%d", Pid);
509	(void) sprintf(tn, CRON_TAB(n));
510	if (!(tmp = fopen(tn, "w+"))) {
511		warn("%s", tn);
512		return (-2);
513	}
514
515	/* write a signature at the top of the file.
516	 *
517	 * VERY IMPORTANT: make sure NHEADER_LINES agrees with this code.
518	 */
519	fprintf(tmp, "# DO NOT EDIT THIS FILE - edit the master and reinstall.\n");
520	fprintf(tmp, "# (%s installed on %-24.24s)\n", Filename, ctime(&now));
521	fprintf(tmp, "# (Cron version -- %s)\n", rcsid);
522
523	/* copy the crontab to the tmp
524	 */
525	rewind(NewCrontab);
526	Set_LineNum(1)
527	while (EOF != (ch = get_char(NewCrontab)))
528		putc(ch, tmp);
529	ftruncate(fileno(tmp), ftell(tmp));
530	fflush(tmp);  rewind(tmp);
531
532	if (ferror(tmp)) {
533		warnx("error while writing new crontab to %s", tn);
534		fclose(tmp);  unlink(tn);
535		return (-2);
536	}
537
538	/* check the syntax of the file being installed.
539	 */
540
541	/* BUG: was reporting errors after the EOF if there were any errors
542	 * in the file proper -- kludged it by stopping after first error.
543	 *		vix 31mar87
544	 */
545	Set_LineNum(1 - NHEADER_LINES)
546	CheckErrorCount = 0;  eof = FALSE;
547	while (!CheckErrorCount && !eof) {
548		switch (load_env(envstr, tmp)) {
549		case ERR:
550			eof = TRUE;
551			break;
552		case FALSE:
553			e = load_entry(tmp, check_error, pw, envp);
554			if (e)
555				free(e);
556			break;
557		case TRUE:
558			break;
559		}
560	}
561
562	if (CheckErrorCount != 0) {
563		warnx("errors in crontab file, can't install");
564		fclose(tmp);  unlink(tn);
565		return (-1);
566	}
567
568#ifdef HAS_FCHOWN
569	if (fchown(fileno(tmp), ROOT_UID, -1) < OK)
570#else
571	if (chown(tn, ROOT_UID, -1) < OK)
572#endif
573	{
574		warn("chown");
575		fclose(tmp);  unlink(tn);
576		return (-2);
577	}
578
579#ifdef HAS_FCHMOD
580	if (fchmod(fileno(tmp), 0600) < OK)
581#else
582	if (chmod(tn, 0600) < OK)
583#endif
584	{
585		warn("chown");
586		fclose(tmp);  unlink(tn);
587		return (-2);
588	}
589
590	if (fclose(tmp) == EOF) {
591		warn("fclose");
592		unlink(tn);
593		return (-2);
594	}
595
596	(void) sprintf(n, CRON_TAB(User));
597	if (rename(tn, n)) {
598		warn("error renaming %s to %s", tn, n);
599		unlink(tn);
600		return (-2);
601	}
602	log_it(RealUser, Pid, "REPLACE", User);
603
604	poke_daemon();
605
606	return (0);
607}
608
609
610static void
611poke_daemon() {
612#ifdef USE_UTIMES
613	struct timeval tvs[2];
614	struct timezone tz;
615
616	(void) gettimeofday(&tvs[0], &tz);
617	tvs[1] = tvs[0];
618	if (utimes(SPOOL_DIR, tvs) < OK) {
619		warn("can't update mtime on spooldir %s", SPOOL_DIR);
620		return;
621	}
622#else
623	if (utime(SPOOL_DIR, NULL) < OK) {
624		warn("can't update mtime on spooldir %s", SPOOL_DIR);
625		return;
626	}
627#endif /*USE_UTIMES*/
628}
629