crontab.c revision 69793
11590Srgrimes/* Copyright 1988,1990,1993,1994 by Paul Vixie
21590Srgrimes * All rights reserved
31590Srgrimes *
41590Srgrimes * Distribute freely, except: don't remove my name from the source or
51590Srgrimes * documentation (don't take credit for my work), mark your changes (don't
61590Srgrimes * get me blamed for your possible bugs), don't alter or remove this
71590Srgrimes * notice.  May be sold if buildable source is provided to buyer.  No
81590Srgrimes * warrantee of any kind, express or implied, is included with this
91590Srgrimes * software; use at your own risk, responsibility for damages (if any) to
101590Srgrimes * anyone resulting from the use of this software rests entirely with the
111590Srgrimes * user.
121590Srgrimes *
131590Srgrimes * Send bug reports, bug fixes, enhancements, requests, flames, etc., and
141590Srgrimes * I'll try to keep a version up to date.  I can be reached as follows:
151590Srgrimes * Paul Vixie          <paul@vix.com>          uunet!decwrl!vixie!paul
161590Srgrimes * From Id: crontab.c,v 2.13 1994/01/17 03:20:37 vixie Exp
171590Srgrimes */
181590Srgrimes
191590Srgrimes#if !defined(lint) && !defined(LINT)
201590Srgrimesstatic const char rcsid[] =
211590Srgrimes  "$FreeBSD: head/usr.sbin/cron/crontab/crontab.c 69793 2000-12-09 09:35:55Z obrien $";
221590Srgrimes#endif
231590Srgrimes
241590Srgrimes/* crontab - install and manage per-user crontab files
251590Srgrimes * vix 02may87 [RCS has the rest of the log]
261590Srgrimes * vix 26jan87 [original]
271590Srgrimes */
281590Srgrimes
291590Srgrimes#define	MAIN_PROGRAM
301590Srgrimes
311590Srgrimes#include "cron.h"
321590Srgrimes#include <errno.h>
331590Srgrimes#include <fcntl.h>
341590Srgrimes#include <paths.h>
351590Srgrimes#include <sys/file.h>
361590Srgrimes#include <sys/stat.h>
371590Srgrimes#ifdef USE_UTIMES
3861575Sroberto# include <sys/time.h>
391590Srgrimes#else
4061575Sroberto# include <time.h>
4161575Sroberto# include <utime.h>
421590Srgrimes#endif
43116333Smarkm#if defined(POSIX)
4493604Sobrien# include <locale.h>
4593604Sobrien#endif
461590Srgrimes
471590Srgrimes
481590Srgrimes#define NHEADER_LINES 3
491590Srgrimes
501590Srgrimes
511590Srgrimesenum opt_t	{ opt_unknown, opt_list, opt_delete, opt_edit, opt_replace };
521590Srgrimes
531590Srgrimes#if DEBUGGING
541590Srgrimesstatic char	*Options[] = { "???", "list", "delete", "edit", "replace" };
551590Srgrimes#endif
561590Srgrimes
571590Srgrimes
588874Srgrimesstatic	PID_T		Pid;
591590Srgrimesstatic	char		User[MAX_UNAME], RealUser[MAX_UNAME];
601590Srgrimesstatic	char		Filename[MAX_FNAME];
611590Srgrimesstatic	FILE		*NewCrontab;
621590Srgrimesstatic	int		CheckErrorCount;
631590Srgrimesstatic	enum opt_t	Option;
64116333Smarkmstatic	struct passwd	*pw;
651590Srgrimesstatic	void		list_cmd __P((void)),
6691400Sdwmalone			delete_cmd __P((void)),
6791400Sdwmalone			edit_cmd __P((void)),
681590Srgrimes			poke_daemon __P((void)),
691590Srgrimes			check_error __P((char *)),
701590Srgrimes			parse_args __P((int c, char *v[]));
711590Srgrimesstatic	int		replace_cmd __P((void));
721590Srgrimes
731590Srgrimes
741590Srgrimesstatic void
751590Srgrimesusage(msg)
761590Srgrimes	char *msg;
771590Srgrimes{
781590Srgrimes	fprintf(stderr, "crontab: usage error: %s\n", msg);
791590Srgrimes	fprintf(stderr, "%s\n%s\n",
801590Srgrimes		"usage: crontab [-u user] file",
811590Srgrimes		"       crontab [-u user] { -e | -l | -r }");
821590Srgrimes	exit(ERROR_EXIT);
831590Srgrimes}
841590Srgrimes
851590Srgrimes
86144526Stjrint
87144526Stjrmain(argc, argv)
881590Srgrimes	int	argc;
891590Srgrimes	char	*argv[];
90116333Smarkm{
911590Srgrimes	int	exitstatus;
92144526Stjr
931590Srgrimes	Pid = getpid();
941590Srgrimes	ProgramName = argv[0];
951590Srgrimes
961590Srgrimes#if defined(POSIX)
971590Srgrimes	setlocale(LC_ALL, "");
981590Srgrimes#endif
991590Srgrimes
100144526Stjr#if defined(BSD)
101144526Stjr	setlinebuf(stderr);
102144526Stjr#endif
103144526Stjr	parse_args(argc, argv);		/* sets many globals, opens a file */
104144526Stjr	set_cron_uid();
1051590Srgrimes	set_cron_cwd();
1061590Srgrimes	if (!allowed(User)) {
1071590Srgrimes		warnx("you (%s) are not allowed to use this program", User);
108144526Stjr		log_it(RealUser, Pid, "AUTH", "crontab command not allowed");
1091590Srgrimes		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(0);
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;
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	while (EOF != (ch = get_char(f)))
244		putchar(ch);
245	fclose(f);
246}
247
248
249static void
250delete_cmd() {
251	char	n[MAX_FNAME];
252	int ch, first;
253
254	if (isatty(STDIN_FILENO)) {
255		(void)fprintf(stderr, "remove crontab for %s? ", User);
256		first = ch = getchar();
257		while (ch != '\n' && ch != EOF)
258			ch = getchar();
259		if (first != 'y' && first != 'Y')
260			return;
261	}
262
263	log_it(RealUser, Pid, "DELETE", User);
264	(void) sprintf(n, CRON_TAB(User));
265	if (unlink(n)) {
266		if (errno == ENOENT)
267			errx(ERROR_EXIT, "no crontab for %s", User);
268		else
269			err(ERROR_EXIT, "%s", n);
270	}
271	poke_daemon();
272}
273
274
275static void
276check_error(msg)
277	char	*msg;
278{
279	CheckErrorCount++;
280	fprintf(stderr, "\"%s\":%d: %s\n", Filename, LineNumber-1, msg);
281}
282
283
284static void
285edit_cmd() {
286	char		n[MAX_FNAME], q[MAX_TEMPSTR], *editor;
287	FILE		*f;
288	int		ch, t, x;
289	struct stat	statbuf, fsbuf;
290	time_t		mtime;
291	WAIT_T		waiter;
292	PID_T		pid, xpid;
293	mode_t		um;
294
295	log_it(RealUser, Pid, "BEGIN EDIT", User);
296	(void) sprintf(n, CRON_TAB(User));
297	if (!(f = fopen(n, "r"))) {
298		if (errno != ENOENT)
299			err(ERROR_EXIT, "%s", n);
300		warnx("no crontab for %s - using an empty one", User);
301		if (!(f = fopen(_PATH_DEVNULL, "r")))
302			err(ERROR_EXIT, _PATH_DEVNULL);
303	}
304
305	um = umask(077);
306	(void) sprintf(Filename, "/tmp/crontab.XXXXXXXXXX");
307	if ((t = mkstemp(Filename)) == -1) {
308		warn("%s", Filename);
309		(void) umask(um);
310		goto fatal;
311	}
312	(void) umask(um);
313#ifdef HAS_FCHOWN
314	if (fchown(t, getuid(), getgid()) < 0) {
315#else
316	if (chown(Filename, getuid(), getgid()) < 0) {
317#endif
318		warn("fchown");
319		goto fatal;
320	}
321	if (!(NewCrontab = fdopen(t, "r+"))) {
322		warn("fdopen");
323		goto fatal;
324	}
325
326	Set_LineNum(1)
327
328	/* ignore the top few comments since we probably put them there.
329	 */
330	for (x = 0;  x < NHEADER_LINES;  x++) {
331		ch = get_char(f);
332		if (EOF == ch)
333			break;
334		if ('#' != ch) {
335			putc(ch, NewCrontab);
336			break;
337		}
338		while (EOF != (ch = get_char(f)))
339			if (ch == '\n')
340				break;
341		if (EOF == ch)
342			break;
343	}
344
345	/* copy the rest of the crontab (if any) to the temp file.
346	 */
347	if (EOF != ch)
348		while (EOF != (ch = get_char(f)))
349			putc(ch, NewCrontab);
350	fclose(f);
351	if (fflush(NewCrontab))
352		err(ERROR_EXIT, "%s", Filename);
353	if (fstat(t, &fsbuf) < 0) {
354		warn("unable to fstat temp file");
355		goto fatal;
356	}
357 again:
358	if (stat(Filename, &statbuf) < 0) {
359		warn("stat");
360 fatal:		unlink(Filename);
361		exit(ERROR_EXIT);
362	}
363	if (statbuf.st_dev != fsbuf.st_dev || statbuf.st_ino != fsbuf.st_ino)
364		errx(ERROR_EXIT, "temp file must be edited in place");
365	mtime = statbuf.st_mtime;
366
367	if ((!(editor = getenv("VISUAL")))
368	 && (!(editor = getenv("EDITOR")))
369	    ) {
370		editor = EDITOR;
371	}
372
373	/* we still have the file open.  editors will generally rewrite the
374	 * original file rather than renaming/unlinking it and starting a
375	 * new one; even backup files are supposed to be made by copying
376	 * rather than by renaming.  if some editor does not support this,
377	 * then don't use it.  the security problems are more severe if we
378	 * close and reopen the file around the edit.
379	 */
380
381	switch (pid = fork()) {
382	case -1:
383		warn("fork");
384		goto fatal;
385	case 0:
386		/* child */
387		if (setuid(getuid()) < 0)
388			err(ERROR_EXIT, "setuid(getuid())");
389		if (chdir("/tmp") < 0)
390			err(ERROR_EXIT, "chdir(/tmp)");
391		if (strlen(editor) + strlen(Filename) + 2 >= MAX_TEMPSTR)
392			errx(ERROR_EXIT, "editor or filename too long");
393		execlp(editor, editor, Filename, NULL);
394		err(ERROR_EXIT, "%s", editor);
395		/*NOTREACHED*/
396	default:
397		/* parent */
398		break;
399	}
400
401	/* parent */
402	{
403	void (*f[4])();
404	f[0] = signal(SIGHUP, SIG_IGN);
405	f[1] = signal(SIGINT, SIG_IGN);
406	f[2] = signal(SIGTERM, SIG_IGN);
407	xpid = wait(&waiter);
408	signal(SIGHUP, f[0]);
409	signal(SIGINT, f[1]);
410	signal(SIGTERM, f[2]);
411	}
412	if (xpid != pid) {
413		warnx("wrong PID (%d != %d) from \"%s\"", xpid, pid, editor);
414		goto fatal;
415	}
416	if (WIFEXITED(waiter) && WEXITSTATUS(waiter)) {
417		warnx("\"%s\" exited with status %d", editor, WEXITSTATUS(waiter));
418		goto fatal;
419	}
420	if (WIFSIGNALED(waiter)) {
421		warnx("\"%s\" killed; signal %d (%score dumped)",
422			editor, WTERMSIG(waiter), WCOREDUMP(waiter) ?"" :"no ");
423		goto fatal;
424	}
425	if (stat(Filename, &statbuf) < 0) {
426		warn("stat");
427		goto fatal;
428	}
429	if (statbuf.st_dev != fsbuf.st_dev || statbuf.st_ino != fsbuf.st_ino)
430		errx(ERROR_EXIT, "temp file must be edited in place");
431	if (mtime == statbuf.st_mtime) {
432		warnx("no changes made to crontab");
433		goto remove;
434	}
435	warnx("installing new crontab");
436	switch (replace_cmd()) {
437	case 0:
438		break;
439	case -1:
440		for (;;) {
441			printf("Do you want to retry the same edit? ");
442			fflush(stdout);
443			q[0] = '\0';
444			(void) fgets(q, sizeof q, stdin);
445			switch (islower(q[0]) ? q[0] : tolower(q[0])) {
446			case 'y':
447				goto again;
448			case 'n':
449				goto abandon;
450			default:
451				fprintf(stderr, "Enter Y or N\n");
452			}
453		}
454		/*NOTREACHED*/
455	case -2:
456	abandon:
457		warnx("edits left in %s", Filename);
458		goto done;
459	default:
460		warnx("panic: bad switch() in replace_cmd()");
461		goto fatal;
462	}
463 remove:
464	unlink(Filename);
465 done:
466	log_it(RealUser, Pid, "END EDIT", User);
467}
468
469
470/* returns	0	on success
471 *		-1	on syntax error
472 *		-2	on install error
473 */
474static int
475replace_cmd() {
476	char	n[MAX_FNAME], envstr[MAX_ENVSTR], tn[MAX_FNAME];
477	FILE	*tmp;
478	int	ch, eof;
479	entry	*e;
480	time_t	now = time(NULL);
481	char	**envp = env_init();
482
483	if (envp == NULL) {
484		warnx("cannot allocate memory");
485		return (-2);
486	}
487
488	(void) sprintf(n, "tmp.%d", Pid);
489	(void) sprintf(tn, CRON_TAB(n));
490	if (!(tmp = fopen(tn, "w+"))) {
491		warn("%s", tn);
492		return (-2);
493	}
494
495	/* write a signature at the top of the file.
496	 *
497	 * VERY IMPORTANT: make sure NHEADER_LINES agrees with this code.
498	 */
499	fprintf(tmp, "# DO NOT EDIT THIS FILE - edit the master and reinstall.\n");
500	fprintf(tmp, "# (%s installed on %-24.24s)\n", Filename, ctime(&now));
501	fprintf(tmp, "# (Cron version -- %s)\n", rcsid);
502
503	/* copy the crontab to the tmp
504	 */
505	rewind(NewCrontab);
506	Set_LineNum(1)
507	while (EOF != (ch = get_char(NewCrontab)))
508		putc(ch, tmp);
509	ftruncate(fileno(tmp), ftell(tmp));
510	fflush(tmp);  rewind(tmp);
511
512	if (ferror(tmp)) {
513		warnx("error while writing new crontab to %s", tn);
514		fclose(tmp);  unlink(tn);
515		return (-2);
516	}
517
518	/* check the syntax of the file being installed.
519	 */
520
521	/* BUG: was reporting errors after the EOF if there were any errors
522	 * in the file proper -- kludged it by stopping after first error.
523	 *		vix 31mar87
524	 */
525	Set_LineNum(1 - NHEADER_LINES)
526	CheckErrorCount = 0;  eof = FALSE;
527	while (!CheckErrorCount && !eof) {
528		switch (load_env(envstr, tmp)) {
529		case ERR:
530			eof = TRUE;
531			break;
532		case FALSE:
533			e = load_entry(tmp, check_error, pw, envp);
534			if (e)
535				free(e);
536			break;
537		case TRUE:
538			break;
539		}
540	}
541
542	if (CheckErrorCount != 0) {
543		warnx("errors in crontab file, can't install");
544		fclose(tmp);  unlink(tn);
545		return (-1);
546	}
547
548#ifdef HAS_FCHOWN
549	if (fchown(fileno(tmp), ROOT_UID, -1) < OK)
550#else
551	if (chown(tn, ROOT_UID, -1) < OK)
552#endif
553	{
554		warn("chown");
555		fclose(tmp);  unlink(tn);
556		return (-2);
557	}
558
559#ifdef HAS_FCHMOD
560	if (fchmod(fileno(tmp), 0600) < OK)
561#else
562	if (chmod(tn, 0600) < OK)
563#endif
564	{
565		warn("chown");
566		fclose(tmp);  unlink(tn);
567		return (-2);
568	}
569
570	if (fclose(tmp) == EOF) {
571		warn("fclose");
572		unlink(tn);
573		return (-2);
574	}
575
576	(void) sprintf(n, CRON_TAB(User));
577	if (rename(tn, n)) {
578		warn("error renaming %s to %s", tn, n);
579		unlink(tn);
580		return (-2);
581	}
582	log_it(RealUser, Pid, "REPLACE", User);
583
584	poke_daemon();
585
586	return (0);
587}
588
589
590static void
591poke_daemon() {
592#ifdef USE_UTIMES
593	struct timeval tvs[2];
594	struct timezone tz;
595
596	(void) gettimeofday(&tvs[0], &tz);
597	tvs[1] = tvs[0];
598	if (utimes(SPOOL_DIR, tvs) < OK) {
599		warn("can't update mtime on spooldir %s", SPOOL_DIR);
600		return;
601	}
602#else
603	if (utime(SPOOL_DIR, NULL) < OK) {
604		warn("can't update mtime on spooldir %s", SPOOL_DIR);
605		return;
606	}
607#endif /*USE_UTIMES*/
608}
609