xref: /freebsd/usr.sbin/cron/crontab/crontab.c (revision 0de89efe5c443f213c7ea28773ef2dc6cf3af2ed)
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 	"$Id: crontab.c,v 1.10 1997/03/31 05:09:58 imp Exp $";
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 
252 	log_it(RealUser, Pid, "DELETE", User);
253 	(void) sprintf(n, CRON_TAB(User));
254 	if (unlink(n)) {
255 		if (errno == ENOENT)
256 			errx(ERROR_EXIT, "no crontab for %s", User);
257 		else
258 			err(ERROR_EXIT, "%s", n);
259 	}
260 	poke_daemon();
261 }
262 
263 
264 static void
265 check_error(msg)
266 	char	*msg;
267 {
268 	CheckErrorCount++;
269 	fprintf(stderr, "\"%s\":%d: %s\n", Filename, LineNumber-1, msg);
270 }
271 
272 
273 static void
274 edit_cmd() {
275 	char		n[MAX_FNAME], q[MAX_TEMPSTR], *editor;
276 	FILE		*f;
277 	int		ch, t, x;
278 	struct stat	statbuf;
279 	time_t		mtime;
280 	WAIT_T		waiter;
281 	PID_T		pid, xpid;
282 	mode_t		um;
283 
284 	log_it(RealUser, Pid, "BEGIN EDIT", User);
285 	(void) sprintf(n, CRON_TAB(User));
286 	if (!(f = fopen(n, "r"))) {
287 		if (errno != ENOENT)
288 			err(ERROR_EXIT, "%s", n);
289 		warnx("no crontab for %s - using an empty one", User);
290 		if (!(f = fopen("/dev/null", "r")))
291 			err(ERROR_EXIT, "/dev/null");
292 	}
293 
294 	um = umask(077);
295 	(void) sprintf(Filename, "/tmp/crontab.XXXXXXXXXX");
296 	if ((t = mkstemp(Filename)) == -1) {
297 		warn("%s", Filename);
298 		(void) umask(um);
299 		goto fatal;
300 	}
301 	(void) umask(um);
302 #ifdef HAS_FCHOWN
303 	if (fchown(t, getuid(), getgid()) < 0) {
304 #else
305 	if (chown(Filename, getuid(), getgid()) < 0) {
306 #endif
307 		warn("fchown");
308 		goto fatal;
309 	}
310 	if (!(NewCrontab = fdopen(t, "w"))) {
311 		warn("fdopen");
312 		goto fatal;
313 	}
314 
315 	Set_LineNum(1)
316 
317 	/* ignore the top few comments since we probably put them there.
318 	 */
319 	for (x = 0;  x < NHEADER_LINES;  x++) {
320 		ch = get_char(f);
321 		if (EOF == ch)
322 			break;
323 		if ('#' != ch) {
324 			putc(ch, NewCrontab);
325 			break;
326 		}
327 		while (EOF != (ch = get_char(f)))
328 			if (ch == '\n')
329 				break;
330 		if (EOF == ch)
331 			break;
332 	}
333 
334 	/* copy the rest of the crontab (if any) to the temp file.
335 	 */
336 	if (EOF != ch)
337 		while (EOF != (ch = get_char(f)))
338 			putc(ch, NewCrontab);
339 	fclose(f);
340 	if (fclose(NewCrontab))
341 		err(ERROR_EXIT, "%s", Filename);
342  again:
343 	if (stat(Filename, &statbuf) < 0) {
344 		warn("stat");
345  fatal:		unlink(Filename);
346 		exit(ERROR_EXIT);
347 	}
348 	mtime = statbuf.st_mtime;
349 
350 	if ((!(editor = getenv("VISUAL")))
351 	 && (!(editor = getenv("EDITOR")))
352 	    ) {
353 		editor = EDITOR;
354 	}
355 
356 	/* we still have the file open.  editors will generally rewrite the
357 	 * original file rather than renaming/unlinking it and starting a
358 	 * new one; even backup files are supposed to be made by copying
359 	 * rather than by renaming.  if some editor does not support this,
360 	 * then don't use it.  the security problems are more severe if we
361 	 * close and reopen the file around the edit.
362 	 */
363 
364 	switch (pid = fork()) {
365 	case -1:
366 		warn("fork");
367 		goto fatal;
368 	case 0:
369 		/* child */
370 		if (setuid(getuid()) < 0)
371 			err(ERROR_EXIT, "setuid(getuid())");
372 		if (chdir("/tmp") < 0)
373 			err(ERROR_EXIT, "chdir(/tmp)");
374 		if (strlen(editor) + strlen(Filename) + 2 >= MAX_TEMPSTR)
375 			errx(ERROR_EXIT, "editor or filename too long");
376 		execlp(editor, editor, Filename, NULL);
377 		err(ERROR_EXIT, "%s", editor);
378 		/*NOTREACHED*/
379 	default:
380 		/* parent */
381 		break;
382 	}
383 
384 	/* parent */
385 	{
386 	void (*f[4])();
387 	f[0] = signal(SIGHUP, SIG_IGN);
388 	f[1] = signal(SIGINT, SIG_IGN);
389 	f[2] = signal(SIGTERM, SIG_IGN);
390 	xpid = wait(&waiter);
391 	signal(SIGHUP, f[0]);
392 	signal(SIGINT, f[1]);
393 	signal(SIGTERM, f[2]);
394 	}
395 	if (xpid != pid) {
396 		warnx("wrong PID (%d != %d) from \"%s\"", xpid, pid, editor);
397 		goto fatal;
398 	}
399 	if (WIFEXITED(waiter) && WEXITSTATUS(waiter)) {
400 		warnx("\"%s\" exited with status %d", editor, WEXITSTATUS(waiter));
401 		goto fatal;
402 	}
403 	if (WIFSIGNALED(waiter)) {
404 		warnx("\"%s\" killed; signal %d (%score dumped)",
405 			editor, WTERMSIG(waiter), WCOREDUMP(waiter) ?"" :"no ");
406 		goto fatal;
407 	}
408 	if (stat(Filename, &statbuf) < 0) {
409 		warn("stat");
410 		goto fatal;
411 	}
412 	if (mtime == statbuf.st_mtime) {
413 		warnx("no changes made to crontab");
414 		goto remove;
415 	}
416 	warnx("installing new crontab");
417 	if (!(NewCrontab = fopen(Filename, "r"))) {
418 		warn("%s", Filename);
419 		goto fatal;
420 	}
421 	switch (replace_cmd()) {
422 	case 0:
423 		break;
424 	case -1:
425 		for (;;) {
426 			printf("Do you want to retry the same edit? ");
427 			fflush(stdout);
428 			q[0] = '\0';
429 			(void) fgets(q, sizeof q, stdin);
430 			switch (islower(q[0]) ? q[0] : tolower(q[0])) {
431 			case 'y':
432 				goto again;
433 			case 'n':
434 				goto abandon;
435 			default:
436 				fprintf(stderr, "Enter Y or N\n");
437 			}
438 		}
439 		/*NOTREACHED*/
440 	case -2:
441 	abandon:
442 		warnx("edits left in %s", Filename);
443 		goto done;
444 	default:
445 		warnx("panic: bad switch() in replace_cmd()");
446 		goto fatal;
447 	}
448  remove:
449 	unlink(Filename);
450  done:
451 	log_it(RealUser, Pid, "END EDIT", User);
452 }
453 
454 
455 /* returns	0	on success
456  *		-1	on syntax error
457  *		-2	on install error
458  */
459 static int
460 replace_cmd() {
461 	char	n[MAX_FNAME], envstr[MAX_ENVSTR], tn[MAX_FNAME];
462 	FILE	*tmp;
463 	int	ch, eof;
464 	entry	*e;
465 	time_t	now = time(NULL);
466 	char	**envp = env_init();
467 
468 	if (envp == NULL) {
469 		warnx("cannot allocate memory");
470 		return (-2);
471 	}
472 
473 	(void) sprintf(n, "tmp.%d", Pid);
474 	(void) sprintf(tn, CRON_TAB(n));
475 	if (!(tmp = fopen(tn, "w+"))) {
476 		warn("%s", tn);
477 		return (-2);
478 	}
479 
480 	/* write a signature at the top of the file.
481 	 *
482 	 * VERY IMPORTANT: make sure NHEADER_LINES agrees with this code.
483 	 */
484 	fprintf(tmp, "# DO NOT EDIT THIS FILE - edit the master and reinstall.\n");
485 	fprintf(tmp, "# (%s installed on %-24.24s)\n", Filename, ctime(&now));
486 	fprintf(tmp, "# (Cron version -- %s)\n", rcsid);
487 
488 	/* copy the crontab to the tmp
489 	 */
490 	Set_LineNum(1)
491 	while (EOF != (ch = get_char(NewCrontab)))
492 		putc(ch, tmp);
493 	fclose(NewCrontab);
494 	ftruncate(fileno(tmp), ftell(tmp));
495 	fflush(tmp);  rewind(tmp);
496 
497 	if (ferror(tmp)) {
498 		warnx("error while writing new crontab to %s", tn);
499 		fclose(tmp);  unlink(tn);
500 		return (-2);
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 			eof = TRUE;
516 			break;
517 		case FALSE:
518 			e = load_entry(tmp, check_error, pw, envp);
519 			if (e)
520 				free(e);
521 			break;
522 		case TRUE:
523 			break;
524 		}
525 	}
526 
527 	if (CheckErrorCount != 0) {
528 		warnx("errors in crontab file, can't install");
529 		fclose(tmp);  unlink(tn);
530 		return (-1);
531 	}
532 
533 #ifdef HAS_FCHOWN
534 	if (fchown(fileno(tmp), ROOT_UID, -1) < OK)
535 #else
536 	if (chown(tn, ROOT_UID, -1) < OK)
537 #endif
538 	{
539 		warn("chown");
540 		fclose(tmp);  unlink(tn);
541 		return (-2);
542 	}
543 
544 #ifdef HAS_FCHMOD
545 	if (fchmod(fileno(tmp), 0600) < OK)
546 #else
547 	if (chmod(tn, 0600) < OK)
548 #endif
549 	{
550 		warn("chown");
551 		fclose(tmp);  unlink(tn);
552 		return (-2);
553 	}
554 
555 	if (fclose(tmp) == EOF) {
556 		warn("fclose");
557 		unlink(tn);
558 		return (-2);
559 	}
560 
561 	(void) sprintf(n, CRON_TAB(User));
562 	if (rename(tn, n)) {
563 		warn("error renaming %s to %s", tn, n);
564 		unlink(tn);
565 		return (-2);
566 	}
567 	log_it(RealUser, Pid, "REPLACE", User);
568 
569 	poke_daemon();
570 
571 	return (0);
572 }
573 
574 
575 static void
576 poke_daemon() {
577 #ifdef USE_UTIMES
578 	struct timeval tvs[2];
579 	struct timezone tz;
580 
581 	(void) gettimeofday(&tvs[0], &tz);
582 	tvs[1] = tvs[0];
583 	if (utimes(SPOOL_DIR, tvs) < OK) {
584 		warn("can't update mtime on spooldir %s", SPOOL_DIR);
585 		return;
586 	}
587 #else
588 	if (utime(SPOOL_DIR, NULL) < OK) {
589 		warn("can't update mtime on spooldir %s", SPOOL_DIR);
590 		return;
591 	}
592 #endif /*USE_UTIMES*/
593 }
594