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