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