crontab.c revision 135174
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 135174 2004-09-13 21:04:30Z 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
224static void
225copy_file(FILE *in, FILE *out) {
226	int	x, ch;
227
228	Set_LineNum(1)
229	/* ignore the top few comments since we probably put them there.
230	 */
231	for (x = 0;  x < NHEADER_LINES;  x++) {
232		ch = get_char(in);
233		if (EOF == ch)
234			break;
235		if ('#' != ch) {
236			putc(ch, out);
237			break;
238		}
239		while (EOF != (ch = get_char(in)))
240			if (ch == '\n')
241				break;
242		if (EOF == ch)
243			break;
244	}
245
246	/* copy the rest of the crontab (if any) to the output file.
247	 */
248	if (EOF != ch)
249		while (EOF != (ch = get_char(in)))
250			putc(ch, out);
251}
252
253static void
254list_cmd() {
255	char	n[MAX_FNAME];
256	FILE	*f;
257
258	log_it(RealUser, Pid, "LIST", User);
259	(void) sprintf(n, CRON_TAB(User));
260	if (!(f = fopen(n, "r"))) {
261		if (errno == ENOENT)
262			errx(ERROR_EXIT, "no crontab for %s", User);
263		else
264			err(ERROR_EXIT, "%s", n);
265	}
266
267	/* file is open. copy to stdout, close.
268	 */
269	copy_file(f, stdout);
270	fclose(f);
271}
272
273
274static void
275delete_cmd() {
276	char	n[MAX_FNAME];
277	int ch, first;
278
279	if (isatty(STDIN_FILENO)) {
280		(void)fprintf(stderr, "remove crontab for %s? ", User);
281		first = ch = getchar();
282		while (ch != '\n' && ch != EOF)
283			ch = getchar();
284		if (first != 'y' && first != 'Y')
285			return;
286	}
287
288	log_it(RealUser, Pid, "DELETE", User);
289	(void) sprintf(n, CRON_TAB(User));
290	if (unlink(n)) {
291		if (errno == ENOENT)
292			errx(ERROR_EXIT, "no crontab for %s", User);
293		else
294			err(ERROR_EXIT, "%s", n);
295	}
296	poke_daemon();
297}
298
299
300static void
301check_error(msg)
302	char	*msg;
303{
304	CheckErrorCount++;
305	fprintf(stderr, "\"%s\":%d: %s\n", Filename, LineNumber-1, msg);
306}
307
308
309static void
310edit_cmd() {
311	char		n[MAX_FNAME], q[MAX_TEMPSTR], *editor;
312	FILE		*f;
313	int		t;
314	struct stat	statbuf, fsbuf;
315	time_t		mtime;
316	WAIT_T		waiter;
317	PID_T		pid, xpid;
318	mode_t		um;
319	int		syntax_error = 0;
320
321	log_it(RealUser, Pid, "BEGIN EDIT", User);
322	(void) sprintf(n, CRON_TAB(User));
323	if (!(f = fopen(n, "r"))) {
324		if (errno != ENOENT)
325			err(ERROR_EXIT, "%s", n);
326		warnx("no crontab for %s - using an empty one", User);
327		if (!(f = fopen(_PATH_DEVNULL, "r")))
328			err(ERROR_EXIT, _PATH_DEVNULL);
329	}
330
331	um = umask(077);
332	(void) sprintf(Filename, "/tmp/crontab.XXXXXXXXXX");
333	if ((t = mkstemp(Filename)) == -1) {
334		warn("%s", Filename);
335		(void) umask(um);
336		goto fatal;
337	}
338	(void) umask(um);
339#ifdef HAS_FCHOWN
340	if (fchown(t, getuid(), getgid()) < 0) {
341#else
342	if (chown(Filename, getuid(), getgid()) < 0) {
343#endif
344		warn("fchown");
345		goto fatal;
346	}
347	if (!(NewCrontab = fdopen(t, "r+"))) {
348		warn("fdopen");
349		goto fatal;
350	}
351
352	copy_file(f, NewCrontab);
353	fclose(f);
354	if (fflush(NewCrontab))
355		err(ERROR_EXIT, "%s", Filename);
356	if (fstat(t, &fsbuf) < 0) {
357		warn("unable to fstat temp file");
358		goto fatal;
359	}
360 again:
361	if (stat(Filename, &statbuf) < 0) {
362		warn("stat");
363 fatal:		unlink(Filename);
364		exit(ERROR_EXIT);
365	}
366	if (statbuf.st_dev != fsbuf.st_dev || statbuf.st_ino != fsbuf.st_ino)
367		errx(ERROR_EXIT, "temp file must be edited in place");
368	mtime = statbuf.st_mtime;
369
370	if ((!(editor = getenv("VISUAL")))
371	 && (!(editor = getenv("EDITOR")))
372	    ) {
373		editor = EDITOR;
374	}
375
376	/* we still have the file open.  editors will generally rewrite the
377	 * original file rather than renaming/unlinking it and starting a
378	 * new one; even backup files are supposed to be made by copying
379	 * rather than by renaming.  if some editor does not support this,
380	 * then don't use it.  the security problems are more severe if we
381	 * close and reopen the file around the edit.
382	 */
383
384	switch (pid = fork()) {
385	case -1:
386		warn("fork");
387		goto fatal;
388	case 0:
389		/* child */
390		if (setuid(getuid()) < 0)
391			err(ERROR_EXIT, "setuid(getuid())");
392		if (chdir("/tmp") < 0)
393			err(ERROR_EXIT, "chdir(/tmp)");
394		if (strlen(editor) + strlen(Filename) + 2 >= MAX_TEMPSTR)
395			errx(ERROR_EXIT, "editor or filename too long");
396		execlp(editor, editor, Filename, (char *)NULL);
397		err(ERROR_EXIT, "%s", editor);
398		/*NOTREACHED*/
399	default:
400		/* parent */
401		break;
402	}
403
404	/* parent */
405	{
406	void (*f[4])();
407	f[0] = signal(SIGHUP, SIG_IGN);
408	f[1] = signal(SIGINT, SIG_IGN);
409	f[2] = signal(SIGTERM, SIG_IGN);
410	xpid = wait(&waiter);
411	signal(SIGHUP, f[0]);
412	signal(SIGINT, f[1]);
413	signal(SIGTERM, f[2]);
414	}
415	if (xpid != pid) {
416		warnx("wrong PID (%d != %d) from \"%s\"", xpid, pid, editor);
417		goto fatal;
418	}
419	if (WIFEXITED(waiter) && WEXITSTATUS(waiter)) {
420		warnx("\"%s\" exited with status %d", editor, WEXITSTATUS(waiter));
421		goto fatal;
422	}
423	if (WIFSIGNALED(waiter)) {
424		warnx("\"%s\" killed; signal %d (%score dumped)",
425			editor, WTERMSIG(waiter), WCOREDUMP(waiter) ?"" :"no ");
426		goto fatal;
427	}
428	if (stat(Filename, &statbuf) < 0) {
429		warn("stat");
430		goto fatal;
431	}
432	if (statbuf.st_dev != fsbuf.st_dev || statbuf.st_ino != fsbuf.st_ino)
433		errx(ERROR_EXIT, "temp file must be edited in place");
434	if (mtime == statbuf.st_mtime && !syntax_error) {
435		warnx("no changes made to crontab");
436		goto remove;
437	}
438	warnx("installing new crontab");
439	switch (replace_cmd()) {
440	case 0:			/* Success */
441		break;
442	case -1:		/* Syntax error */
443		for (;;) {
444			printf("Do you want to retry the same edit? ");
445			fflush(stdout);
446			q[0] = '\0';
447			(void) fgets(q, sizeof q, stdin);
448			switch (islower(q[0]) ? q[0] : tolower(q[0])) {
449			case 'y':
450				syntax_error = 1;
451				goto again;
452			case 'n':
453				goto abandon;
454			default:
455				fprintf(stderr, "Enter Y or N\n");
456			}
457		}
458		/*NOTREACHED*/
459	case -2:		/* Install error */
460	abandon:
461		warnx("edits left in %s", Filename);
462		goto done;
463	default:
464		warnx("panic: bad switch() in replace_cmd()");
465		goto fatal;
466	}
467 remove:
468	unlink(Filename);
469 done:
470	log_it(RealUser, Pid, "END EDIT", User);
471}
472
473
474/* returns	0	on success
475 *		-1	on syntax error
476 *		-2	on install error
477 */
478static int
479replace_cmd() {
480	char	n[MAX_FNAME], envstr[MAX_ENVSTR], tn[MAX_FNAME];
481	FILE	*tmp;
482	int	ch, eof;
483	entry	*e;
484	time_t	now = time(NULL);
485	char	**envp = env_init();
486
487	if (envp == NULL) {
488		warnx("cannot allocate memory");
489		return (-2);
490	}
491
492	(void) sprintf(n, "tmp.%d", Pid);
493	(void) sprintf(tn, CRON_TAB(n));
494	if (!(tmp = fopen(tn, "w+"))) {
495		warn("%s", tn);
496		return (-2);
497	}
498
499	/* write a signature at the top of the file.
500	 *
501	 * VERY IMPORTANT: make sure NHEADER_LINES agrees with this code.
502	 */
503	fprintf(tmp, "# DO NOT EDIT THIS FILE - edit the master and reinstall.\n");
504	fprintf(tmp, "# (%s installed on %-24.24s)\n", Filename, ctime(&now));
505	fprintf(tmp, "# (Cron version -- %s)\n", rcsid);
506
507	/* copy the crontab to the tmp
508	 */
509	rewind(NewCrontab);
510	Set_LineNum(1)
511	while (EOF != (ch = get_char(NewCrontab)))
512		putc(ch, tmp);
513	ftruncate(fileno(tmp), ftell(tmp));
514	fflush(tmp);  rewind(tmp);
515
516	if (ferror(tmp)) {
517		warnx("error while writing new crontab to %s", tn);
518		fclose(tmp);  unlink(tn);
519		return (-2);
520	}
521
522	/* check the syntax of the file being installed.
523	 */
524
525	/* BUG: was reporting errors after the EOF if there were any errors
526	 * in the file proper -- kludged it by stopping after first error.
527	 *		vix 31mar87
528	 */
529	Set_LineNum(1 - NHEADER_LINES)
530	CheckErrorCount = 0;  eof = FALSE;
531	while (!CheckErrorCount && !eof) {
532		switch (load_env(envstr, tmp)) {
533		case ERR:
534			eof = TRUE;
535			break;
536		case FALSE:
537			e = load_entry(tmp, check_error, pw, envp);
538			if (e)
539				free(e);
540			break;
541		case TRUE:
542			break;
543		}
544	}
545
546	if (CheckErrorCount != 0) {
547		warnx("errors in crontab file, can't install");
548		fclose(tmp);  unlink(tn);
549		return (-1);
550	}
551
552#ifdef HAS_FCHOWN
553	if (fchown(fileno(tmp), ROOT_UID, -1) < OK)
554#else
555	if (chown(tn, ROOT_UID, -1) < OK)
556#endif
557	{
558		warn("chown");
559		fclose(tmp);  unlink(tn);
560		return (-2);
561	}
562
563#ifdef HAS_FCHMOD
564	if (fchmod(fileno(tmp), 0600) < OK)
565#else
566	if (chmod(tn, 0600) < OK)
567#endif
568	{
569		warn("chown");
570		fclose(tmp);  unlink(tn);
571		return (-2);
572	}
573
574	if (fclose(tmp) == EOF) {
575		warn("fclose");
576		unlink(tn);
577		return (-2);
578	}
579
580	(void) sprintf(n, CRON_TAB(User));
581	if (rename(tn, n)) {
582		warn("error renaming %s to %s", tn, n);
583		unlink(tn);
584		return (-2);
585	}
586	log_it(RealUser, Pid, "REPLACE", User);
587
588	poke_daemon();
589
590	return (0);
591}
592
593
594static void
595poke_daemon() {
596#ifdef USE_UTIMES
597	struct timeval tvs[2];
598	struct timezone tz;
599
600	(void) gettimeofday(&tvs[0], &tz);
601	tvs[1] = tvs[0];
602	if (utimes(SPOOL_DIR, tvs) < OK) {
603		warn("can't update mtime on spooldir %s", SPOOL_DIR);
604		return;
605	}
606#else
607	if (utime(SPOOL_DIR, NULL) < OK) {
608		warn("can't update mtime on spooldir %s", SPOOL_DIR);
609		return;
610	}
611#endif /*USE_UTIMES*/
612}
613