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