xref: /openbsd-src/usr.sbin/cron/crontab.c (revision 5054e3e78af0749a9bb00ba9a024b3ee2d90290f)
1 /*	$OpenBSD: crontab.c,v 1.58 2009/10/27 23:52:16 deraadt Exp $	*/
2 
3 /* Copyright 1988,1990,1993,1994 by Paul Vixie
4  * All rights reserved
5  */
6 
7 /*
8  * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
9  * Copyright (c) 1997,2000 by Internet Software Consortium, Inc.
10  *
11  * Permission to use, copy, modify, and distribute this software for any
12  * purpose with or without fee is hereby granted, provided that the above
13  * copyright notice and this permission notice appear in all copies.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES
16  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
17  * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR
18  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
19  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
20  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
21  * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
22  */
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 #include <err.h>
30 
31 #define	MAIN_PROGRAM
32 
33 #include "cron.h"
34 
35 #define NHEADER_LINES 3
36 
37 enum opt_t	{ opt_unknown, opt_list, opt_delete, opt_edit, opt_replace };
38 
39 #if DEBUGGING
40 static char	*Options[] = { "???", "list", "delete", "edit", "replace" };
41 static char	*getoptargs = "u:lerx:";
42 #else
43 static char	*getoptargs = "u:ler";
44 #endif
45 
46 static	PID_T		Pid;
47 static	char		User[MAX_UNAME], RealUser[MAX_UNAME];
48 static	char		Filename[MAX_FNAME], TempFilename[MAX_FNAME];
49 static	FILE		*NewCrontab;
50 static	int		CheckErrorCount;
51 static	enum opt_t	Option;
52 static	struct passwd	*pw;
53 int			editit(const char *);
54 static	void		list_cmd(void),
55 			delete_cmd(void),
56 			edit_cmd(void),
57 			check_error(const char *),
58 			parse_args(int c, char *v[]),
59 			die(int);
60 static	int		replace_cmd(void);
61 static	int		ignore_comments(FILE *);
62 
63 static void
64 usage(const char *msg) {
65 	fprintf(stderr, "%s: usage error: %s\n", ProgramName, msg);
66 	fprintf(stderr, "usage: %s [-u user] file\n", ProgramName);
67 	fprintf(stderr, "       %s [-e | -l | -r] [-u user]\n", ProgramName);
68 	fprintf(stderr,
69 	    "\t\t(default operation is replace, per 1003.2)\n"
70 	    "\t-e\t(edit user's crontab)\n"
71 	    "\t-l\t(list user's crontab)\n"
72 	    "\t-r\t(delete user's crontab)\n");
73 	exit(ERROR_EXIT);
74 }
75 
76 int
77 main(int argc, char *argv[]) {
78 	int exitstatus;
79 
80 	Pid = getpid();
81 	ProgramName = argv[0];
82 
83 	setlocale(LC_ALL, "");
84 
85 #if defined(BSD)
86 	setlinebuf(stderr);
87 #endif
88 	parse_args(argc, argv);		/* sets many globals, opens a file */
89 	set_cron_cwd();
90 	if (!allowed(RealUser, CRON_ALLOW, CRON_DENY)) {
91 		fprintf(stderr,
92 			"You (%s) are not allowed to use this program (%s)\n",
93 			User, ProgramName);
94 		fprintf(stderr, "See crontab(1) for more information\n");
95 		log_it(RealUser, Pid, "AUTH", "crontab command not allowed");
96 		exit(ERROR_EXIT);
97 	}
98 	exitstatus = OK_EXIT;
99 	switch (Option) {
100 	case opt_list:
101 		list_cmd();
102 		break;
103 	case opt_delete:
104 		delete_cmd();
105 		break;
106 	case opt_edit:
107 		edit_cmd();
108 		break;
109 	case opt_replace:
110 		if (replace_cmd() < 0)
111 			exitstatus = ERROR_EXIT;
112 		break;
113 	default:
114 		exitstatus = ERROR_EXIT;
115 		break;
116 	}
117 	exit(exitstatus);
118 	/*NOTREACHED*/
119 }
120 
121 static void
122 parse_args(int argc, char *argv[]) {
123 	int argch;
124 
125 	if (!(pw = getpwuid(getuid()))) {
126 		fprintf(stderr, "%s: your UID isn't in the passwd file.\n",
127 			ProgramName);
128 		fprintf(stderr, "bailing out.\n");
129 		exit(ERROR_EXIT);
130 	}
131 	if (strlen(pw->pw_name) >= sizeof User) {
132 		fprintf(stderr, "username too long\n");
133 		exit(ERROR_EXIT);
134 	}
135 	strlcpy(User, pw->pw_name, sizeof(User));
136 	strlcpy(RealUser, User, sizeof(RealUser));
137 	Filename[0] = '\0';
138 	Option = opt_unknown;
139 	while (-1 != (argch = getopt(argc, argv, getoptargs))) {
140 		switch (argch) {
141 #if DEBUGGING
142 		case 'x':
143 			if (!set_debug_flags(optarg))
144 				usage("bad debug option");
145 			break;
146 #endif
147 		case 'u':
148 			if (MY_UID(pw) != ROOT_UID) {
149 				fprintf(stderr,
150 					"must be privileged to use -u\n");
151 				exit(ERROR_EXIT);
152 			}
153 			if (!(pw = getpwnam(optarg))) {
154 				fprintf(stderr, "%s:  user `%s' unknown\n",
155 					ProgramName, optarg);
156 				exit(ERROR_EXIT);
157 			}
158 			if (strlcpy(User, optarg, sizeof User) >= sizeof User)
159 				usage("username too long");
160 			break;
161 		case 'l':
162 			if (Option != opt_unknown)
163 				usage("only one operation permitted");
164 			Option = opt_list;
165 			break;
166 		case 'r':
167 			if (Option != opt_unknown)
168 				usage("only one operation permitted");
169 			Option = opt_delete;
170 			break;
171 		case 'e':
172 			if (Option != opt_unknown)
173 				usage("only one operation permitted");
174 			Option = opt_edit;
175 			break;
176 		default:
177 			usage("unrecognized option");
178 		}
179 	}
180 
181 	endpwent();
182 
183 	if (Option != opt_unknown) {
184 		if (argv[optind] != NULL)
185 			usage("no arguments permitted after this option");
186 	} else {
187 		if (argv[optind] != NULL) {
188 			Option = opt_replace;
189 			if (strlcpy(Filename, argv[optind], sizeof Filename)
190 			    >= sizeof Filename)
191 				usage("filename too long");
192 		} else
193 			usage("file name must be specified for replace");
194 	}
195 
196 	if (Option == opt_replace) {
197 		/* we have to open the file here because we're going to
198 		 * chdir(2) into /var/cron before we get around to
199 		 * reading the file.
200 		 */
201 		if (!strcmp(Filename, "-"))
202 			NewCrontab = stdin;
203 		else {
204 			/* relinquish the setgid status of the binary during
205 			 * the open, lest nonroot users read files they should
206 			 * not be able to read.  we can't use access() here
207 			 * since there's a race condition.  thanks go out to
208 			 * Arnt Gulbrandsen <agulbra@pvv.unit.no> for spotting
209 			 * the race.
210 			 */
211 
212 			if (swap_gids() < OK) {
213 				perror("swapping gids");
214 				exit(ERROR_EXIT);
215 			}
216 			if (!(NewCrontab = fopen(Filename, "r"))) {
217 				perror(Filename);
218 				exit(ERROR_EXIT);
219 			}
220 			if (swap_gids_back() < OK) {
221 				perror("swapping gids back");
222 				exit(ERROR_EXIT);
223 			}
224 		}
225 	}
226 
227 	Debug(DMISC, ("user=%s, file=%s, option=%s\n",
228 		      User, Filename, Options[(int)Option]))
229 }
230 
231 static void
232 list_cmd(void) {
233 	char n[MAX_FNAME];
234 	FILE *f;
235 	int ch;
236 
237 	log_it(RealUser, Pid, "LIST", User);
238 	if (snprintf(n, sizeof n, "%s/%s", SPOOL_DIR, User) >= sizeof(n)) {
239 		fprintf(stderr, "path too long\n");
240 		exit(ERROR_EXIT);
241 	}
242 	if (!(f = fopen(n, "r"))) {
243 		if (errno == ENOENT)
244 			fprintf(stderr, "no crontab for %s\n", User);
245 		else
246 			perror(n);
247 		exit(ERROR_EXIT);
248 	}
249 
250 	/* file is open. copy to stdout, close.
251 	 */
252 	Set_LineNum(1)
253 
254 	/* ignore the top few comments since we probably put them there.
255 	 */
256 	ch = ignore_comments(f);
257 
258 	while (EOF != (ch = get_char(f)))
259 		putchar(ch);
260 	fclose(f);
261 }
262 
263 static void
264 delete_cmd(void) {
265 	char n[MAX_FNAME];
266 
267 	log_it(RealUser, Pid, "DELETE", User);
268 	if (snprintf(n, sizeof n, "%s/%s", SPOOL_DIR, User) >= sizeof(n)) {
269 		fprintf(stderr, "path too long\n");
270 		exit(ERROR_EXIT);
271 	}
272 	if (unlink(n) != 0) {
273 		if (errno == ENOENT)
274 			fprintf(stderr, "no crontab for %s\n", User);
275 		else
276 			perror(n);
277 		exit(ERROR_EXIT);
278 	}
279 	poke_daemon(SPOOL_DIR, RELOAD_CRON);
280 }
281 
282 static void
283 check_error(const char *msg) {
284 	CheckErrorCount++;
285 	fprintf(stderr, "\"%s\":%d: %s\n", Filename, LineNumber-1, msg);
286 }
287 
288 static void
289 edit_cmd(void) {
290 	char n[MAX_FNAME], q[MAX_TEMPSTR];
291 	FILE *f;
292 	int ch, t;
293 	struct stat statbuf, xstatbuf;
294 	struct timespec mtimespec;
295 	struct timeval tv[2];
296 
297 	log_it(RealUser, Pid, "BEGIN EDIT", User);
298 	if (snprintf(n, sizeof n, "%s/%s", SPOOL_DIR, User) >= sizeof(n)) {
299 		fprintf(stderr, "path too long\n");
300 		exit(ERROR_EXIT);
301 	}
302 	if (!(f = fopen(n, "r"))) {
303 		if (errno != ENOENT) {
304 			perror(n);
305 			exit(ERROR_EXIT);
306 		}
307 		fprintf(stderr, "no crontab for %s - using an empty one\n",
308 			User);
309 		if (!(f = fopen(_PATH_DEVNULL, "r"))) {
310 			perror(_PATH_DEVNULL);
311 			exit(ERROR_EXIT);
312 		}
313 	}
314 
315 	if (fstat(fileno(f), &statbuf) < 0) {
316 		perror("fstat");
317 		goto fatal;
318 	}
319 	/*
320 	 * Note that timespec has higher precision than timeval so we
321 	 * store mtimespec using timeval precision so we can compare later.
322 	 */
323 	TIMESPEC_TO_TIMEVAL(&tv[0], &statbuf.st_atimespec);
324 	TIMESPEC_TO_TIMEVAL(&tv[1], &statbuf.st_mtimespec);
325 	TIMEVAL_TO_TIMESPEC(&tv[1], &mtimespec);
326 
327 	/* Turn off signals. */
328 	(void)signal(SIGHUP, SIG_IGN);
329 	(void)signal(SIGINT, SIG_IGN);
330 	(void)signal(SIGQUIT, SIG_IGN);
331 
332 	if (snprintf(Filename, sizeof Filename, "%scrontab.XXXXXXXXXX",
333 	    _PATH_TMP) >= sizeof(Filename)) {
334 		fprintf(stderr, "path too long\n");
335 		goto fatal;
336 	}
337 	if (-1 == (t = mkstemp(Filename))) {
338 		perror(Filename);
339 		goto fatal;
340 	}
341 	if (!(NewCrontab = fdopen(t, "r+"))) {
342 		perror("fdopen");
343 		goto fatal;
344 	}
345 
346 	Set_LineNum(1)
347 
348 	/* ignore the top few comments since we probably put them there.
349 	 */
350 	ch = ignore_comments(f);
351 
352 	/* copy the rest of the crontab (if any) to the temp file.
353 	 */
354 	if (EOF != ch)
355 		while (EOF != (ch = get_char(f)))
356 			putc(ch, NewCrontab);
357 	fclose(f);
358 	if (fflush(NewCrontab) < OK) {
359 		perror(Filename);
360 		exit(ERROR_EXIT);
361 	}
362 	(void)futimes(t, tv);
363  again:
364 	rewind(NewCrontab);
365 	if (ferror(NewCrontab)) {
366 		fprintf(stderr, "%s: error while writing new crontab to %s\n",
367 			ProgramName, Filename);
368  fatal:
369 		unlink(Filename);
370 		exit(ERROR_EXIT);
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 	if (editit(Filename) == -1) {
381 		warn("error starting editor");
382 		goto fatal;
383 	}
384 
385 	if (fstat(t, &statbuf) < 0) {
386 		perror("fstat");
387 		goto fatal;
388 	}
389 	if (timespeccmp(&mtimespec, &statbuf.st_mtimespec, -) == 0) {
390 		if (lstat(Filename, &xstatbuf) == 0 &&
391 		    statbuf.st_ino != xstatbuf.st_ino) {
392 			fprintf(stderr, "%s: crontab temp file moved, editor "
393 			   "may create backup files improperly\n", ProgramName);
394 		}
395 		fprintf(stderr, "%s: no changes made to crontab\n",
396 			ProgramName);
397 		goto remove;
398 	}
399 	fprintf(stderr, "%s: installing new crontab\n", ProgramName);
400 	switch (replace_cmd()) {
401 	case 0:
402 		break;
403 	case -1:
404 		for (;;) {
405 			printf("Do you want to retry the same edit? ");
406 			fflush(stdout);
407 			q[0] = '\0';
408 			if (fgets(q, sizeof q, stdin) == NULL) {
409 				putchar('\n');
410 				goto abandon;
411 			}
412 			switch (q[0]) {
413 			case 'y':
414 			case 'Y':
415 				goto again;
416 			case 'n':
417 			case 'N':
418 				goto abandon;
419 			default:
420 				fprintf(stderr, "Enter Y or N\n");
421 			}
422 		}
423 		/*NOTREACHED*/
424 	case -2:
425 	abandon:
426 		fprintf(stderr, "%s: edits left in %s\n",
427 			ProgramName, Filename);
428 		goto done;
429 	default:
430 		fprintf(stderr, "%s: panic: bad switch() in replace_cmd()\n",
431 			ProgramName);
432 		goto fatal;
433 	}
434  remove:
435 	unlink(Filename);
436  done:
437 	log_it(RealUser, Pid, "END EDIT", User);
438 }
439 
440 /* returns	0	on success
441  *		-1	on syntax error
442  *		-2	on install error
443  */
444 static int
445 replace_cmd(void) {
446 	char n[MAX_FNAME], envstr[MAX_ENVSTR];
447 	FILE *tmp;
448 	int ch, eof, fd;
449 	int error = 0;
450 	entry *e;
451 	time_t now = time(NULL);
452 	char **envp = env_init();
453 
454 	if (envp == NULL) {
455 		fprintf(stderr, "%s: Cannot allocate memory.\n", ProgramName);
456 		return (-2);
457 	}
458 	if (snprintf(TempFilename, sizeof TempFilename, "%s/tmp.XXXXXXXXX",
459 	    SPOOL_DIR) >= sizeof(TempFilename)) {
460 		TempFilename[0] = '\0';
461 		fprintf(stderr, "path too long\n");
462 		return (-2);
463 	}
464 	if ((fd = mkstemp(TempFilename)) == -1 || !(tmp = fdopen(fd, "w+"))) {
465 		perror(TempFilename);
466 		if (fd != -1) {
467 			close(fd);
468 			unlink(TempFilename);
469 		}
470 		TempFilename[0] = '\0';
471 		return (-2);
472 	}
473 
474 	(void) signal(SIGHUP, die);
475 	(void) signal(SIGINT, die);
476 	(void) signal(SIGQUIT, die);
477 
478 	/* write a signature at the top of the file.
479 	 *
480 	 * VERY IMPORTANT: make sure NHEADER_LINES agrees with this code.
481 	 */
482 	fprintf(tmp, "# DO NOT EDIT THIS FILE - edit the master and reinstall.\n");
483 	fprintf(tmp, "# (%s installed on %-24.24s)\n", Filename, ctime(&now));
484 	fprintf(tmp, "# (Cron version %s)\n", CRON_VERSION);
485 
486 	/* copy the crontab to the tmp
487 	 */
488 	rewind(NewCrontab);
489 	Set_LineNum(1)
490 	while (EOF != (ch = get_char(NewCrontab)))
491 		putc(ch, tmp);
492 	ftruncate(fileno(tmp), ftello(tmp));	/* XXX redundant with "w+"? */
493 	fflush(tmp);  rewind(tmp);
494 
495 	if (ferror(tmp)) {
496 		fprintf(stderr, "%s: error while writing new crontab to %s\n",
497 			ProgramName, TempFilename);
498 		fclose(tmp);
499 		error = -2;
500 		goto done;
501 	}
502 
503 	/* check the syntax of the file being installed.
504 	 */
505 
506 	/* BUG: was reporting errors after the EOF if there were any errors
507 	 * in the file proper -- kludged it by stopping after first error.
508 	 *		vix 31mar87
509 	 */
510 	Set_LineNum(1 - NHEADER_LINES)
511 	CheckErrorCount = 0;  eof = FALSE;
512 	while (!CheckErrorCount && !eof) {
513 		switch (load_env(envstr, tmp)) {
514 		case ERR:
515 			/* check for data before the EOF */
516 			if (envstr[0] != '\0') {
517 				Set_LineNum(LineNumber + 1);
518 				check_error("premature EOF");
519 			}
520 			eof = TRUE;
521 			break;
522 		case FALSE:
523 			e = load_entry(tmp, check_error, pw, envp);
524 			if (e)
525 				free(e);
526 			break;
527 		case TRUE:
528 			break;
529 		}
530 	}
531 
532 	if (CheckErrorCount != 0) {
533 		fprintf(stderr, "errors in crontab file, can't install.\n");
534 		fclose(tmp);
535 		error = -1;
536 		goto done;
537 	}
538 
539 #ifdef HAVE_FCHOWN
540 	if (fchown(fileno(tmp), pw->pw_uid, -1) < OK) {
541 		perror("fchown");
542 		fclose(tmp);
543 		error = -2;
544 		goto done;
545 	}
546 #else
547 	if (chown(TempFilename, pw->pw_uid, -1) < OK) {
548 		perror("chown");
549 		fclose(tmp);
550 		error = -2;
551 		goto done;
552 	}
553 #endif
554 
555 	if (fclose(tmp) == EOF) {
556 		perror("fclose");
557 		error = -2;
558 		goto done;
559 	}
560 
561 	if (snprintf(n, sizeof n, "%s/%s", SPOOL_DIR, User) >= sizeof(n)) {
562 		fprintf(stderr, "path too long\n");
563 		error = -2;
564 		goto done;
565 	}
566 	if (rename(TempFilename, n)) {
567 		fprintf(stderr, "%s: error renaming %s to %s\n",
568 			ProgramName, TempFilename, n);
569 		perror("rename");
570 		error = -2;
571 		goto done;
572 	}
573 	TempFilename[0] = '\0';
574 	log_it(RealUser, Pid, "REPLACE", User);
575 
576 	poke_daemon(SPOOL_DIR, RELOAD_CRON);
577 
578 done:
579 	(void) signal(SIGHUP, SIG_DFL);
580 	(void) signal(SIGINT, SIG_DFL);
581 	(void) signal(SIGQUIT, SIG_DFL);
582 	if (TempFilename[0]) {
583 		(void) unlink(TempFilename);
584 		TempFilename[0] = '\0';
585 	}
586 	return (error);
587 }
588 
589 /*
590  * Execute an editor on the specified pathname, which is interpreted
591  * from the shell.  This means flags may be included.
592  *
593  * Returns -1 on error, or the exit value on success.
594  */
595 int
596 editit(const char *pathname)
597 {
598 	char *argp[] = {"sh", "-c", NULL, NULL}, *ed, *p;
599 	sig_t sighup, sigint, sigquit, sigchld;
600 	pid_t pid;
601 	int saved_errno, st, ret = -1;
602 
603 	ed = getenv("VISUAL");
604 	if (ed == NULL || ed[0] == '\0')
605 		ed = getenv("EDITOR");
606 	if (ed == NULL || ed[0] == '\0')
607 		ed = _PATH_VI;
608 	if (asprintf(&p, "%s %s", ed, pathname) == -1)
609 		return (-1);
610 	argp[2] = p;
611 
612 	sighup = signal(SIGHUP, SIG_IGN);
613 	sigint = signal(SIGINT, SIG_IGN);
614 	sigquit = signal(SIGQUIT, SIG_IGN);
615 	sigchld = signal(SIGCHLD, SIG_DFL);
616 	if ((pid = fork()) == -1)
617 		goto fail;
618 	if (pid == 0) {
619 		setgid(getgid());
620 		setuid(getuid());
621 		execv(_PATH_BSHELL, argp);
622 		_exit(127);
623 	}
624 	while (waitpid(pid, &st, 0) == -1)
625 		if (errno != EINTR)
626 			goto fail;
627 	if (!WIFEXITED(st))
628 		errno = EINTR;
629 	else
630 		ret = WEXITSTATUS(st);
631 
632  fail:
633 	saved_errno = errno;
634 	(void)signal(SIGHUP, sighup);
635 	(void)signal(SIGINT, sigint);
636 	(void)signal(SIGQUIT, sigquit);
637 	(void)signal(SIGCHLD, sigchld);
638 	free(p);
639 	errno = saved_errno;
640 	return (ret);
641 }
642 
643 static void
644 die(int x) {
645 	if (TempFilename[0])
646 		(void) unlink(TempFilename);
647 	_exit(ERROR_EXIT);
648 }
649 
650 static int
651 ignore_comments(FILE *f) {
652 	int ch, x;
653 
654 	x = 0;
655 	while (EOF != (ch = get_char(f))) {
656 		if ('#' != ch) {
657 			putc(ch, NewCrontab);
658 			break;
659 		}
660 		while (EOF != (ch = get_char(f)))
661 			if (ch == '\n')
662 				break;
663 		if (++x >= NHEADER_LINES)
664 			break;
665 	}
666 
667 	return ch;
668 }
669