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