crontab.c revision 184779
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 184779 2008-11-09 06:44:53Z matteo $";
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 <md5.h>
35#include <paths.h>
36#include <sys/file.h>
37#include <sys/stat.h>
38#ifdef USE_UTIMES
39# include <sys/time.h>
40#else
41# include <time.h>
42# include <utime.h>
43#endif
44#if defined(POSIX)
45# include <locale.h>
46#endif
47
48#define MD5_SIZE 33
49#define NHEADER_LINES 3
50
51
52enum opt_t	{ opt_unknown, opt_list, opt_delete, opt_edit, opt_replace };
53
54#if DEBUGGING
55static char	*Options[] = { "???", "list", "delete", "edit", "replace" };
56#endif
57
58
59static	PID_T		Pid;
60static	char		User[MAX_UNAME], RealUser[MAX_UNAME];
61static	char		Filename[MAX_FNAME];
62static	FILE		*NewCrontab;
63static	int		CheckErrorCount;
64static	enum opt_t	Option;
65static	struct passwd	*pw;
66static	void		list_cmd(void),
67			delete_cmd(void),
68			edit_cmd(void),
69			poke_daemon(void),
70			check_error(char *),
71			parse_args(int c, char *v[]);
72static	int		replace_cmd(void);
73
74
75static void
76usage(msg)
77	char *msg;
78{
79	fprintf(stderr, "crontab: usage error: %s\n", msg);
80	fprintf(stderr, "%s\n%s\n",
81		"usage: crontab [-u user] file",
82		"       crontab [-u user] { -e | -l | -r }");
83	exit(ERROR_EXIT);
84}
85
86
87int
88main(argc, argv)
89	int	argc;
90	char	*argv[];
91{
92	int	exitstatus;
93
94	Pid = getpid();
95	ProgramName = argv[0];
96
97#if defined(POSIX)
98	setlocale(LC_ALL, "");
99#endif
100
101#if defined(BSD)
102	setlinebuf(stderr);
103#endif
104	parse_args(argc, argv);		/* sets many globals, opens a file */
105	set_cron_uid();
106	set_cron_cwd();
107	if (!allowed(User)) {
108		warnx("you (%s) are not allowed to use this program", User);
109		log_it(RealUser, Pid, "AUTH", "crontab command not allowed");
110		exit(ERROR_EXIT);
111	}
112	exitstatus = OK_EXIT;
113	switch (Option) {
114	case opt_list:		list_cmd();
115				break;
116	case opt_delete:	delete_cmd();
117				break;
118	case opt_edit:		edit_cmd();
119				break;
120	case opt_replace:	if (replace_cmd() < 0)
121					exitstatus = ERROR_EXIT;
122				break;
123	case opt_unknown:
124				break;
125	}
126	exit(exitstatus);
127	/*NOTREACHED*/
128}
129
130
131static void
132parse_args(argc, argv)
133	int	argc;
134	char	*argv[];
135{
136	int		argch;
137	char		resolved_path[PATH_MAX];
138
139	if (!(pw = getpwuid(getuid())))
140		errx(ERROR_EXIT, "your UID isn't in the passwd file, bailing out");
141	bzero(pw->pw_passwd, strlen(pw->pw_passwd));
142	(void) strncpy(User, pw->pw_name, (sizeof User)-1);
143	User[(sizeof User)-1] = '\0';
144	strcpy(RealUser, User);
145	Filename[0] = '\0';
146	Option = opt_unknown;
147	while ((argch = getopt(argc, argv, "u:lerx:")) != -1) {
148		switch (argch) {
149		case 'x':
150			if (!set_debug_flags(optarg))
151				usage("bad debug option");
152			break;
153		case 'u':
154			if (getuid() != ROOT_UID)
155				errx(ERROR_EXIT, "must be privileged to use -u");
156			if (!(pw = getpwnam(optarg)))
157				errx(ERROR_EXIT, "user `%s' unknown", optarg);
158			bzero(pw->pw_passwd, strlen(pw->pw_passwd));
159			(void) strncpy(User, pw->pw_name, (sizeof User)-1);
160			User[(sizeof User)-1] = '\0';
161			break;
162		case 'l':
163			if (Option != opt_unknown)
164				usage("only one operation permitted");
165			Option = opt_list;
166			break;
167		case 'r':
168			if (Option != opt_unknown)
169				usage("only one operation permitted");
170			Option = opt_delete;
171			break;
172		case 'e':
173			if (Option != opt_unknown)
174				usage("only one operation permitted");
175			Option = opt_edit;
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		/* we have to open the file here because we're going to
201		 * chdir(2) into /var/cron before we get around to
202		 * reading the file.
203		 */
204		if (!strcmp(Filename, "-")) {
205			NewCrontab = stdin;
206		} else if (realpath(Filename, resolved_path) != NULL &&
207		    !strcmp(resolved_path, SYSCRONTAB)) {
208			err(ERROR_EXIT, SYSCRONTAB " must be edited manually");
209		} else {
210			/* relinquish the setuid status of the binary during
211			 * the open, lest nonroot users read files they should
212			 * not be able to read.  we can't use access() here
213			 * since there's a race condition.  thanks go out to
214			 * Arnt Gulbrandsen <agulbra@pvv.unit.no> for spotting
215			 * the race.
216			 */
217
218			if (swap_uids() < OK)
219				err(ERROR_EXIT, "swapping uids");
220			if (!(NewCrontab = fopen(Filename, "r")))
221				err(ERROR_EXIT, "%s", Filename);
222			if (swap_uids() < OK)
223				err(ERROR_EXIT, "swapping uids back");
224		}
225	}
226
227	Debug(DMISC, ("user=%s, file=%s, option=%s\n",
228		      User, Filename, Options[(int)Option]))
229}
230
231static void
232copy_file(FILE *in, FILE *out) {
233	int	x, ch;
234
235	Set_LineNum(1)
236	/* ignore the top few comments since we probably put them there.
237	 */
238	for (x = 0;  x < NHEADER_LINES;  x++) {
239		ch = get_char(in);
240		if (EOF == ch)
241			break;
242		if ('#' != ch) {
243			putc(ch, out);
244			break;
245		}
246		while (EOF != (ch = get_char(in)))
247			if (ch == '\n')
248				break;
249		if (EOF == ch)
250			break;
251	}
252
253	/* copy the rest of the crontab (if any) to the output file.
254	 */
255	if (EOF != ch)
256		while (EOF != (ch = get_char(in)))
257			putc(ch, out);
258}
259
260static void
261list_cmd() {
262	char	n[MAX_FNAME];
263	FILE	*f;
264
265	log_it(RealUser, Pid, "LIST", User);
266	(void) snprintf(n, sizeof(n), CRON_TAB(User));
267	if (!(f = fopen(n, "r"))) {
268		if (errno == ENOENT)
269			errx(ERROR_EXIT, "no crontab for %s", User);
270		else
271			err(ERROR_EXIT, "%s", n);
272	}
273
274	/* file is open. copy to stdout, close.
275	 */
276	copy_file(f, stdout);
277	fclose(f);
278}
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