xref: /openbsd-src/usr.sbin/cron/crontab.c (revision daf88648c0e349d5c02e1504293082072c981640)
1 /*	$OpenBSD: crontab.c,v 1.49 2005/11/29 20:43:31 millert 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 static char const rcsid[] = "$OpenBSD: crontab.c,v 1.49 2005/11/29 20:43:31 millert Exp $";
25 
26 /* crontab - install and manage per-user crontab files
27  * vix 02may87 [RCS has the rest of the log]
28  * vix 26jan87 [original]
29  */
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 static	void		list_cmd(void),
54 			delete_cmd(void),
55 			edit_cmd(void),
56 			check_error(const char *),
57 			parse_args(int c, char *v[]),
58 			die(int);
59 static	int		replace_cmd(void);
60 
61 static void
62 usage(const char *msg) {
63 	fprintf(stderr, "%s: usage error: %s\n", ProgramName, msg);
64 	fprintf(stderr, "usage:\t%s [-u user] file\n", ProgramName);
65 	fprintf(stderr, "\t%s [-u user] [ -e | -l | -r ]\n", ProgramName);
66 	fprintf(stderr, "\t\t(default operation is replace, per 1003.2)\n");
67 	fprintf(stderr, "\t-e\t(edit user's crontab)\n");
68 	fprintf(stderr, "\t-l\t(list user's crontab)\n");
69 	fprintf(stderr, "\t-r\t(delete user's crontab)\n");
70 	exit(ERROR_EXIT);
71 }
72 
73 int
74 main(int argc, char *argv[]) {
75 	int exitstatus;
76 
77 	Pid = getpid();
78 	ProgramName = argv[0];
79 
80 	setlocale(LC_ALL, "");
81 
82 #if defined(BSD)
83 	setlinebuf(stderr);
84 #endif
85 	parse_args(argc, argv);		/* sets many globals, opens a file */
86 	set_cron_cwd();
87 	if (!allowed(RealUser, CRON_ALLOW, CRON_DENY)) {
88 		fprintf(stderr,
89 			"You (%s) are not allowed to use this program (%s)\n",
90 			User, ProgramName);
91 		fprintf(stderr, "See crontab(1) for more information\n");
92 		log_it(RealUser, Pid, "AUTH", "crontab command not allowed");
93 		exit(ERROR_EXIT);
94 	}
95 	exitstatus = OK_EXIT;
96 	switch (Option) {
97 	case opt_list:
98 		list_cmd();
99 		break;
100 	case opt_delete:
101 		delete_cmd();
102 		break;
103 	case opt_edit:
104 		edit_cmd();
105 		break;
106 	case opt_replace:
107 		if (replace_cmd() < 0)
108 			exitstatus = ERROR_EXIT;
109 		break;
110 	default:
111 		exitstatus = ERROR_EXIT;
112 		break;
113 	}
114 	exit(exitstatus);
115 	/*NOTREACHED*/
116 }
117 
118 static void
119 parse_args(int argc, char *argv[]) {
120 	int argch;
121 
122 	if (!(pw = getpwuid(getuid()))) {
123 		fprintf(stderr, "%s: your UID isn't in the passwd file.\n",
124 			ProgramName);
125 		fprintf(stderr, "bailing out.\n");
126 		exit(ERROR_EXIT);
127 	}
128 	if (strlen(pw->pw_name) >= sizeof User) {
129 		fprintf(stderr, "username too long\n");
130 		exit(ERROR_EXIT);
131 	}
132 	strlcpy(User, pw->pw_name, sizeof(User));
133 	strlcpy(RealUser, User, sizeof(RealUser));
134 	Filename[0] = '\0';
135 	Option = opt_unknown;
136 	while (-1 != (argch = getopt(argc, argv, getoptargs))) {
137 		switch (argch) {
138 #if DEBUGGING
139 		case 'x':
140 			if (!set_debug_flags(optarg))
141 				usage("bad debug option");
142 			break;
143 #endif
144 		case 'u':
145 			if (MY_UID(pw) != ROOT_UID) {
146 				fprintf(stderr,
147 					"must be privileged to use -u\n");
148 				exit(ERROR_EXIT);
149 			}
150 			if (!(pw = getpwnam(optarg))) {
151 				fprintf(stderr, "%s:  user `%s' unknown\n",
152 					ProgramName, optarg);
153 				exit(ERROR_EXIT);
154 			}
155 			if (strlcpy(User, optarg, sizeof User) >= sizeof User)
156 				usage("username too long");
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 	} else {
184 		if (argv[optind] != NULL) {
185 			Option = opt_replace;
186 			if (strlcpy(Filename, argv[optind], sizeof Filename)
187 			    >= sizeof Filename)
188 				usage("filename too long");
189 		} else
190 			usage("file name must be specified for replace");
191 	}
192 
193 	if (Option == opt_replace) {
194 		/* we have to open the file here because we're going to
195 		 * chdir(2) into /var/cron before we get around to
196 		 * reading the file.
197 		 */
198 		if (!strcmp(Filename, "-"))
199 			NewCrontab = stdin;
200 		else {
201 			/* relinquish the setgid status of the binary during
202 			 * the open, lest nonroot users read files they should
203 			 * not be able to read.  we can't use access() here
204 			 * since there's a race condition.  thanks go out to
205 			 * Arnt Gulbrandsen <agulbra@pvv.unit.no> for spotting
206 			 * the race.
207 			 */
208 
209 			if (swap_gids() < OK) {
210 				perror("swapping gids");
211 				exit(ERROR_EXIT);
212 			}
213 			if (!(NewCrontab = fopen(Filename, "r"))) {
214 				perror(Filename);
215 				exit(ERROR_EXIT);
216 			}
217 			if (swap_gids_back() < OK) {
218 				perror("swapping gids back");
219 				exit(ERROR_EXIT);
220 			}
221 		}
222 	}
223 
224 	Debug(DMISC, ("user=%s, file=%s, option=%s\n",
225 		      User, Filename, Options[(int)Option]))
226 }
227 
228 static void
229 list_cmd(void) {
230 	char n[MAX_FNAME];
231 	FILE *f;
232 	int ch;
233 
234 	log_it(RealUser, Pid, "LIST", User);
235 	if (snprintf(n, sizeof n, "%s/%s", SPOOL_DIR, User) >= sizeof(n)) {
236 		fprintf(stderr, "path too long\n");
237 		exit(ERROR_EXIT);
238 	}
239 	if (!(f = fopen(n, "r"))) {
240 		if (errno == ENOENT)
241 			fprintf(stderr, "no crontab for %s\n", User);
242 		else
243 			perror(n);
244 		exit(ERROR_EXIT);
245 	}
246 
247 	/* file is open. copy to stdout, close.
248 	 */
249 	Set_LineNum(1)
250 	while (EOF != (ch = get_char(f)))
251 		putchar(ch);
252 	fclose(f);
253 }
254 
255 static void
256 delete_cmd(void) {
257 	char n[MAX_FNAME];
258 
259 	log_it(RealUser, Pid, "DELETE", User);
260 	if (snprintf(n, sizeof n, "%s/%s", SPOOL_DIR, User) >= sizeof(n)) {
261 		fprintf(stderr, "path too long\n");
262 		exit(ERROR_EXIT);
263 	}
264 	if (unlink(n) != 0) {
265 		if (errno == ENOENT)
266 			fprintf(stderr, "no crontab for %s\n", User);
267 		else
268 			perror(n);
269 		exit(ERROR_EXIT);
270 	}
271 	poke_daemon(SPOOL_DIR, RELOAD_CRON);
272 }
273 
274 static void
275 check_error(const char *msg) {
276 	CheckErrorCount++;
277 	fprintf(stderr, "\"%s\":%d: %s\n", Filename, LineNumber-1, msg);
278 }
279 
280 static void
281 edit_cmd(void) {
282 	char n[MAX_FNAME], q[MAX_TEMPSTR], *editor;
283 	FILE *f;
284 	int ch, t, x;
285 	struct stat statbuf, xstatbuf;
286 	struct timespec mtimespec;
287 	struct timeval tv[2];
288 	WAIT_T waiter;
289 	PID_T pid, xpid;
290 
291 	log_it(RealUser, Pid, "BEGIN EDIT", User);
292 	if (snprintf(n, sizeof n, "%s/%s", SPOOL_DIR, User) >= sizeof(n)) {
293 		fprintf(stderr, "path too long\n");
294 		exit(ERROR_EXIT);
295 	}
296 	if (!(f = fopen(n, "r"))) {
297 		if (errno != ENOENT) {
298 			perror(n);
299 			exit(ERROR_EXIT);
300 		}
301 		fprintf(stderr, "no crontab for %s - using an empty one\n",
302 			User);
303 		if (!(f = fopen(_PATH_DEVNULL, "r"))) {
304 			perror(_PATH_DEVNULL);
305 			exit(ERROR_EXIT);
306 		}
307 	}
308 
309 	if (fstat(fileno(f), &statbuf) < 0) {
310 		perror("fstat");
311 		goto fatal;
312 	}
313 	memcpy(&mtimespec, &statbuf.st_mtimespec, sizeof(mtimespec));
314 	TIMESPEC_TO_TIMEVAL(&tv[0], &statbuf.st_atimespec);
315 	TIMESPEC_TO_TIMEVAL(&tv[1], &statbuf.st_mtimespec);
316 
317 	/* Turn off signals. */
318 	(void)signal(SIGHUP, SIG_IGN);
319 	(void)signal(SIGINT, SIG_IGN);
320 	(void)signal(SIGQUIT, SIG_IGN);
321 
322 	if (snprintf(Filename, sizeof Filename, "%s/crontab.XXXXXXXXXX",
323 	    _PATH_TMP) >= sizeof(Filename)) {
324 		fprintf(stderr, "path too long\n");
325 		goto fatal;
326 	}
327 	if (-1 == (t = mkstemp(Filename))) {
328 		perror(Filename);
329 		goto fatal;
330 	}
331 	if (!(NewCrontab = fdopen(t, "r+"))) {
332 		perror("fdopen");
333 		goto fatal;
334 	}
335 
336 	Set_LineNum(1)
337 
338 	/* ignore the top few comments since we probably put them there.
339 	 */
340 	x = 0;
341 	while (EOF != (ch = get_char(f))) {
342 		if ('#' != ch) {
343 			putc(ch, NewCrontab);
344 			break;
345 		}
346 		while (EOF != (ch = get_char(f)))
347 			if (ch == '\n')
348 				break;
349 		if (++x >= NHEADER_LINES)
350 			break;
351 	}
352 
353 	/* copy the rest of the crontab (if any) to the temp file.
354 	 */
355 	if (EOF != ch)
356 		while (EOF != (ch = get_char(f)))
357 			putc(ch, NewCrontab);
358 	fclose(f);
359 	if (fflush(NewCrontab) < OK) {
360 		perror(Filename);
361 		exit(ERROR_EXIT);
362 	}
363 	(void)futimes(t, tv);
364  again:
365 	rewind(NewCrontab);
366 	if (ferror(NewCrontab)) {
367 		fprintf(stderr, "%s: error while writing new crontab to %s\n",
368 			ProgramName, Filename);
369  fatal:
370 		unlink(Filename);
371 		exit(ERROR_EXIT);
372 	}
373 
374 	if (((editor = getenv("VISUAL")) == NULL || *editor == '\0') &&
375 	    ((editor = getenv("EDITOR")) == NULL || *editor == '\0')) {
376 		editor = EDITOR;
377 	}
378 
379 	/* we still have the file open.  editors will generally rewrite the
380 	 * original file rather than renaming/unlinking it and starting a
381 	 * new one; even backup files are supposed to be made by copying
382 	 * rather than by renaming.  if some editor does not support this,
383 	 * then don't use it.  the security problems are more severe if we
384 	 * close and reopen the file around the edit.
385 	 */
386 
387 	switch (pid = fork()) {
388 	case -1:
389 		perror("fork");
390 		goto fatal;
391 	case 0:
392 		/* child */
393 		if (setgid(MY_GID(pw)) < 0) {
394 			perror("setgid(getgid())");
395 			exit(ERROR_EXIT);
396 		}
397 		if (chdir(_PATH_TMP) < 0) {
398 			perror(_PATH_TMP);
399 			exit(ERROR_EXIT);
400 		}
401 		if (snprintf(q, sizeof q, "%s %s", editor, Filename) >= sizeof(q)) {
402 			fprintf(stderr, "%s: editor command line too long\n",
403 			    ProgramName);
404 			exit(ERROR_EXIT);
405 		}
406 		execlp(_PATH_BSHELL, _PATH_BSHELL, "-c", q, (char *)NULL);
407 		perror(editor);
408 		exit(ERROR_EXIT);
409 		/*NOTREACHED*/
410 	default:
411 		/* parent */
412 		break;
413 	}
414 
415 	/* parent */
416 	for (;;) {
417 		xpid = waitpid(pid, &waiter, WUNTRACED);
418 		if (xpid == -1) {
419 			if (errno != EINTR)
420 				fprintf(stderr, "%s: waitpid() failed waiting for PID %ld from \"%s\": %s\n",
421 					ProgramName, (long)pid, editor, strerror(errno));
422 		} else if (xpid != pid) {
423 			fprintf(stderr, "%s: wrong PID (%ld != %ld) from \"%s\"\n",
424 				ProgramName, (long)xpid, (long)pid, editor);
425 			goto fatal;
426 		} else if (WIFSTOPPED(waiter)) {
427 			kill(getpid(), WSTOPSIG(waiter));
428 		} else if (WIFEXITED(waiter) && WEXITSTATUS(waiter)) {
429 			fprintf(stderr, "%s: \"%s\" exited with status %d\n",
430 				ProgramName, editor, WEXITSTATUS(waiter));
431 			goto fatal;
432 		} else if (WIFSIGNALED(waiter)) {
433 			fprintf(stderr,
434 				"%s: \"%s\" killed; signal %d (%score dumped)\n",
435 				ProgramName, editor, WTERMSIG(waiter),
436 				WCOREDUMP(waiter) ?"" :"no ");
437 			goto fatal;
438 		} else
439 			break;
440 	}
441 	(void)signal(SIGHUP, SIG_DFL);
442 	(void)signal(SIGINT, SIG_DFL);
443 	(void)signal(SIGQUIT, SIG_DFL);
444 	if (fstat(t, &statbuf) < 0) {
445 		perror("fstat");
446 		goto fatal;
447 	}
448 	if (timespeccmp(&mtimespec, &statbuf.st_mtimespec, -) == 0) {
449 		if (lstat(Filename, &xstatbuf) == 0 &&
450 		    statbuf.st_ino != xstatbuf.st_ino) {
451 			fprintf(stderr, "%s: crontab temp file moved, editor "
452 			   "may create backup files improperly\n", ProgramName);
453 		}
454 		fprintf(stderr, "%s: no changes made to crontab\n",
455 			ProgramName);
456 		goto remove;
457 	}
458 	fprintf(stderr, "%s: installing new crontab\n", ProgramName);
459 	switch (replace_cmd()) {
460 	case 0:
461 		break;
462 	case -1:
463 		for (;;) {
464 			printf("Do you want to retry the same edit? ");
465 			fflush(stdout);
466 			q[0] = '\0';
467 			if (fgets(q, sizeof q, stdin) == NULL) {
468 				putchar('\n');
469 				goto abandon;
470 			}
471 			switch (q[0]) {
472 			case 'y':
473 			case 'Y':
474 				goto again;
475 			case 'n':
476 			case 'N':
477 				goto abandon;
478 			default:
479 				fprintf(stderr, "Enter Y or N\n");
480 			}
481 		}
482 		/*NOTREACHED*/
483 	case -2:
484 	abandon:
485 		fprintf(stderr, "%s: edits left in %s\n",
486 			ProgramName, Filename);
487 		goto done;
488 	default:
489 		fprintf(stderr, "%s: panic: bad switch() in replace_cmd()\n",
490 			ProgramName);
491 		goto fatal;
492 	}
493  remove:
494 	unlink(Filename);
495  done:
496 	log_it(RealUser, Pid, "END EDIT", User);
497 }
498 
499 /* returns	0	on success
500  *		-1	on syntax error
501  *		-2	on install error
502  */
503 static int
504 replace_cmd(void) {
505 	char n[MAX_FNAME], envstr[MAX_ENVSTR];
506 	FILE *tmp;
507 	int ch, eof, fd;
508 	int error = 0;
509 	entry *e;
510 	time_t now = time(NULL);
511 	char **envp = env_init();
512 
513 	if (envp == NULL) {
514 		fprintf(stderr, "%s: Cannot allocate memory.\n", ProgramName);
515 		return (-2);
516 	}
517 	if (snprintf(TempFilename, sizeof TempFilename, "%s/tmp.XXXXXXXXX",
518 	    SPOOL_DIR) >= sizeof(TempFilename)) {
519 		TempFilename[0] = '\0';
520 		fprintf(stderr, "path too long\n");
521 		return (-2);
522 	}
523 	if ((fd = mkstemp(TempFilename)) == -1 || !(tmp = fdopen(fd, "w+"))) {
524 		perror(TempFilename);
525 		if (fd != -1) {
526 			close(fd);
527 			unlink(TempFilename);
528 		}
529 		TempFilename[0] = '\0';
530 		return (-2);
531 	}
532 
533 	(void) signal(SIGHUP, die);
534 	(void) signal(SIGINT, die);
535 	(void) signal(SIGQUIT, die);
536 
537 	/* write a signature at the top of the file.
538 	 *
539 	 * VERY IMPORTANT: make sure NHEADER_LINES agrees with this code.
540 	 */
541 	fprintf(tmp, "# DO NOT EDIT THIS FILE - edit the master and reinstall.\n");
542 	fprintf(tmp, "# (%s installed on %-24.24s)\n", Filename, ctime(&now));
543 	fprintf(tmp, "# (Cron version %s -- %s)\n", CRON_VERSION, rcsid);
544 
545 	/* copy the crontab to the tmp
546 	 */
547 	rewind(NewCrontab);
548 	Set_LineNum(1)
549 	while (EOF != (ch = get_char(NewCrontab)))
550 		putc(ch, tmp);
551 	ftruncate(fileno(tmp), ftello(tmp));	/* XXX redundant with "w+"? */
552 	fflush(tmp);  rewind(tmp);
553 
554 	if (ferror(tmp)) {
555 		fprintf(stderr, "%s: error while writing new crontab to %s\n",
556 			ProgramName, TempFilename);
557 		fclose(tmp);
558 		error = -2;
559 		goto done;
560 	}
561 
562 	/* check the syntax of the file being installed.
563 	 */
564 
565 	/* BUG: was reporting errors after the EOF if there were any errors
566 	 * in the file proper -- kludged it by stopping after first error.
567 	 *		vix 31mar87
568 	 */
569 	Set_LineNum(1 - NHEADER_LINES)
570 	CheckErrorCount = 0;  eof = FALSE;
571 	while (!CheckErrorCount && !eof) {
572 		switch (load_env(envstr, tmp)) {
573 		case ERR:
574 			/* check for data before the EOF */
575 			if (envstr[0] != '\0') {
576 				Set_LineNum(LineNumber + 1);
577 				check_error("premature EOF");
578 			}
579 			eof = TRUE;
580 			break;
581 		case FALSE:
582 			e = load_entry(tmp, check_error, pw, envp);
583 			if (e)
584 				free(e);
585 			break;
586 		case TRUE:
587 			break;
588 		}
589 	}
590 
591 	if (CheckErrorCount != 0) {
592 		fprintf(stderr, "errors in crontab file, can't install.\n");
593 		fclose(tmp);
594 		error = -1;
595 		goto done;
596 	}
597 
598 #ifdef HAVE_FCHOWN
599 	if (fchown(fileno(tmp), pw->pw_uid, -1) < OK) {
600 		perror("fchown");
601 		fclose(tmp);
602 		error = -2;
603 		goto done;
604 	}
605 #else
606 	if (chown(TempFilename, pw->pw_uid, -1) < OK) {
607 		perror("chown");
608 		fclose(tmp);
609 		error = -2;
610 		goto done;
611 	}
612 #endif
613 
614 	if (fclose(tmp) == EOF) {
615 		perror("fclose");
616 		error = -2;
617 		goto done;
618 	}
619 
620 	if (snprintf(n, sizeof n, "%s/%s", SPOOL_DIR, User) >= sizeof(n)) {
621 		fprintf(stderr, "path too long\n");
622 		error = -2;
623 		goto done;
624 	}
625 	if (rename(TempFilename, n)) {
626 		fprintf(stderr, "%s: error renaming %s to %s\n",
627 			ProgramName, TempFilename, n);
628 		perror("rename");
629 		error = -2;
630 		goto done;
631 	}
632 	TempFilename[0] = '\0';
633 	log_it(RealUser, Pid, "REPLACE", User);
634 
635 	poke_daemon(SPOOL_DIR, RELOAD_CRON);
636 
637 done:
638 	(void) signal(SIGHUP, SIG_DFL);
639 	(void) signal(SIGINT, SIG_DFL);
640 	(void) signal(SIGQUIT, SIG_DFL);
641 	if (TempFilename[0]) {
642 		(void) unlink(TempFilename);
643 		TempFilename[0] = '\0';
644 	}
645 	return (error);
646 }
647 
648 static void
649 die(int x) {
650 	if (TempFilename[0])
651 		(void) unlink(TempFilename);
652 	_exit(ERROR_EXIT);
653 }
654