xref: /openbsd/usr.sbin/cron/cron.c (revision b9a887b6)
1 /*	$OpenBSD: cron.c,v 1.46 2014/11/26 18:34:52 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 #define	MAIN_PROGRAM
25 
26 #include "cron.h"
27 
28 enum timejump { negative, small, medium, large };
29 
30 static	void	usage(void),
31 		run_reboot_jobs(cron_db *),
32 		find_jobs(time_t, cron_db *, int, int),
33 		set_time(int),
34 		cron_sleep(time_t),
35 		sigchld_handler(int),
36 		sighup_handler(int),
37 		sigchld_reaper(void),
38 		quit(int),
39 		parse_args(int c, char *v[]);
40 
41 static	volatile sig_atomic_t	got_sighup, got_sigchld;
42 static	time_t			timeRunning, virtualTime, clockTime;
43 static	int			cronSock;
44 static	long			GMToff;
45 static	cron_db			database;
46 static	at_db			at_database;
47 static	double			batch_maxload = BATCH_MAXLOAD;
48 
49 static void
50 usage(void) {
51 #if DEBUGGING
52 	const char **dflags;
53 #endif
54 
55 	fprintf(stderr, "usage: %s [-n] [-l load_avg] [-x [", ProgramName);
56 #if DEBUGGING
57 	for (dflags = DebugFlagNames; *dflags; dflags++)
58 		fprintf(stderr, "%s%s", *dflags, dflags[1] ? "," : "]");
59 #else
60 	fprintf(stderr, "debugging flags (none supported in this build)]");
61 #endif
62 	fprintf(stderr, "]\n");
63 	exit(EXIT_FAILURE);
64 }
65 
66 int
67 main(int argc, char *argv[]) {
68 	struct sigaction sact;
69 	int fd;
70 
71 	ProgramName = argv[0];
72 
73 	setlocale(LC_ALL, "");
74 
75 	setvbuf(stdout, NULL, _IOLBF, 0);
76 	setvbuf(stderr, NULL, _IOLBF, 0);
77 
78 	NoFork = 0;
79 	parse_args(argc, argv);
80 
81 	bzero((char *)&sact, sizeof sact);
82 	sigemptyset(&sact.sa_mask);
83 	sact.sa_flags = 0;
84 #ifdef SA_RESTART
85 	sact.sa_flags |= SA_RESTART;
86 #endif
87 	sact.sa_handler = sigchld_handler;
88 	(void) sigaction(SIGCHLD, &sact, NULL);
89 	sact.sa_handler = sighup_handler;
90 	(void) sigaction(SIGHUP, &sact, NULL);
91 	sact.sa_handler = quit;
92 	(void) sigaction(SIGINT, &sact, NULL);
93 	(void) sigaction(SIGTERM, &sact, NULL);
94 	sact.sa_handler = SIG_IGN;
95 	(void) sigaction(SIGPIPE, &sact, NULL);
96 
97 	acquire_daemonlock(0);
98 	set_cron_uid();
99 	set_cron_cwd();
100 
101 	if (putenv("PATH="_PATH_DEFPATH) < 0) {
102 		log_it("CRON", getpid(), "DEATH", "can't malloc");
103 		exit(EXIT_FAILURE);
104 	}
105 
106 	/* if there are no debug flags turned on, fork as a daemon should.
107 	 */
108 	if (DebugFlags) {
109 #if DEBUGGING
110 		(void) fprintf(stderr, "[%ld] cron started\n", (long)getpid());
111 #endif
112 	} else if (NoFork == 0) {
113 		switch (fork()) {
114 		case -1:
115 			log_it("CRON",getpid(),"DEATH","can't fork");
116 			exit(EXIT_FAILURE);
117 			break;
118 		case 0:
119 			/* child process */
120 			(void) setsid();
121 			if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) >= 0) {
122 				(void) dup2(fd, STDIN_FILENO);
123 				(void) dup2(fd, STDOUT_FILENO);
124 				(void) dup2(fd, STDERR_FILENO);
125 				if (fd != STDERR_FILENO)
126 					(void) close(fd);
127 			}
128 			log_it("CRON",getpid(),"STARTUP",CRON_VERSION);
129 			break;
130 		default:
131 			/* parent process should just die */
132 			_exit(EXIT_SUCCESS);
133 		}
134 	}
135 
136 	acquire_daemonlock(0);
137 	cronSock = open_socket();
138 	database.head = NULL;
139 	database.tail = NULL;
140 	database.mtime = (time_t) 0;
141 	load_database(&database);
142 	at_database.head = NULL;
143 	at_database.tail = NULL;
144 	at_database.mtime = (time_t) 0;
145 	scan_atjobs(&at_database, NULL);
146 	set_time(TRUE);
147 	run_reboot_jobs(&database);
148 	timeRunning = virtualTime = clockTime;
149 
150 	/*
151 	 * Too many clocks, not enough time (Al. Einstein)
152 	 * These clocks are in minutes since the epoch, adjusted for timezone.
153 	 * virtualTime: is the time it *would* be if we woke up
154 	 * promptly and nobody ever changed the clock. It is
155 	 * monotonically increasing... unless a timejump happens.
156 	 * At the top of the loop, all jobs for 'virtualTime' have run.
157 	 * timeRunning: is the time we last awakened.
158 	 * clockTime: is the time when set_time was last called.
159 	 */
160 	while (TRUE) {
161 		int timeDiff;
162 		enum timejump wakeupKind;
163 
164 		/* ... wait for the time (in minutes) to change ... */
165 		do {
166 			cron_sleep(timeRunning + 1);
167 			set_time(FALSE);
168 		} while (clockTime == timeRunning);
169 		timeRunning = clockTime;
170 
171 		/*
172 		 * Calculate how the current time differs from our virtual
173 		 * clock.  Classify the change into one of 4 cases.
174 		 */
175 		timeDiff = timeRunning - virtualTime;
176 
177 		/* shortcut for the most common case */
178 		if (timeDiff == 1) {
179 			virtualTime = timeRunning;
180 			find_jobs(virtualTime, &database, TRUE, TRUE);
181 		} else {
182 			if (timeDiff > (3*MINUTE_COUNT) ||
183 			    timeDiff < -(3*MINUTE_COUNT))
184 				wakeupKind = large;
185 			else if (timeDiff > 5)
186 				wakeupKind = medium;
187 			else if (timeDiff > 0)
188 				wakeupKind = small;
189 			else
190 				wakeupKind = negative;
191 
192 			switch (wakeupKind) {
193 			case small:
194 				/*
195 				 * case 1: timeDiff is a small positive number
196 				 * (wokeup late) run jobs for each virtual
197 				 * minute until caught up.
198 				 */
199 				Debug(DSCH, ("[%ld], normal case %d minutes to go\n",
200 				    (long)getpid(), timeDiff))
201 				do {
202 					if (job_runqueue())
203 						sleep(10);
204 					virtualTime++;
205 					find_jobs(virtualTime, &database,
206 					    TRUE, TRUE);
207 				} while (virtualTime < timeRunning);
208 				break;
209 
210 			case medium:
211 				/*
212 				 * case 2: timeDiff is a medium-sized positive
213 				 * number, for example because we went to DST
214 				 * run wildcard jobs once, then run any
215 				 * fixed-time jobs that would otherwise be
216 				 * skipped if we use up our minute (possible,
217 				 * if there are a lot of jobs to run) go
218 				 * around the loop again so that wildcard jobs
219 				 * have a chance to run, and we do our
220 				 * housekeeping.
221 				 */
222 				Debug(DSCH, ("[%ld], DST begins %d minutes to go\n",
223 				    (long)getpid(), timeDiff))
224 				/* run wildcard jobs for current minute */
225 				find_jobs(timeRunning, &database, TRUE, FALSE);
226 
227 				/* run fixed-time jobs for each minute missed */
228 				do {
229 					if (job_runqueue())
230 						sleep(10);
231 					virtualTime++;
232 					find_jobs(virtualTime, &database,
233 					    FALSE, TRUE);
234 					set_time(FALSE);
235 				} while (virtualTime< timeRunning &&
236 				    clockTime == timeRunning);
237 				break;
238 
239 			case negative:
240 				/*
241 				 * case 3: timeDiff is a small or medium-sized
242 				 * negative num, eg. because of DST ending.
243 				 * Just run the wildcard jobs. The fixed-time
244 				 * jobs probably have already run, and should
245 				 * not be repeated.  Virtual time does not
246 				 * change until we are caught up.
247 				 */
248 				Debug(DSCH, ("[%ld], DST ends %d minutes to go\n",
249 				    (long)getpid(), timeDiff))
250 				find_jobs(timeRunning, &database, TRUE, FALSE);
251 				break;
252 			default:
253 				/*
254 				 * other: time has changed a *lot*,
255 				 * jump virtual time, and run everything
256 				 */
257 				Debug(DSCH, ("[%ld], clock jumped\n",
258 				    (long)getpid()))
259 				virtualTime = timeRunning;
260 				find_jobs(timeRunning, &database, TRUE, TRUE);
261 			}
262 		}
263 
264 		/* Jobs to be run (if any) are loaded; clear the queue. */
265 		job_runqueue();
266 
267 		/* Run any jobs in the at queue. */
268 		atrun(&at_database, batch_maxload,
269 		    timeRunning * SECONDS_PER_MINUTE - GMToff);
270 
271 		/* Check to see if we received a signal while running jobs. */
272 		if (got_sighup) {
273 			got_sighup = 0;
274 			log_close();
275 		}
276 		if (got_sigchld) {
277 			got_sigchld = 0;
278 			sigchld_reaper();
279 		}
280 		load_database(&database);
281 		scan_atjobs(&at_database, NULL);
282 	}
283 }
284 
285 static void
286 run_reboot_jobs(cron_db *db) {
287 	user *u;
288 	entry *e;
289 
290 	for (u = db->head; u != NULL; u = u->next) {
291 		for (e = u->crontab; e != NULL; e = e->next) {
292 			if (e->flags & WHEN_REBOOT)
293 				job_add(e, u);
294 		}
295 	}
296 	(void) job_runqueue();
297 }
298 
299 static void
300 find_jobs(time_t vtime, cron_db *db, int doWild, int doNonWild) {
301 	time_t virtualSecond  = vtime * SECONDS_PER_MINUTE;
302 	struct tm *tm = gmtime(&virtualSecond);
303 	int minute, hour, dom, month, dow;
304 	user *u;
305 	entry *e;
306 
307 	/* make 0-based values out of these so we can use them as indices
308 	 */
309 	minute = tm->tm_min -FIRST_MINUTE;
310 	hour = tm->tm_hour -FIRST_HOUR;
311 	dom = tm->tm_mday -FIRST_DOM;
312 	month = tm->tm_mon +1 /* 0..11 -> 1..12 */ -FIRST_MONTH;
313 	dow = tm->tm_wday -FIRST_DOW;
314 
315 	Debug(DSCH, ("[%ld] tick(%d,%d,%d,%d,%d) %s %s\n",
316 		     (long)getpid(), minute, hour, dom, month, dow,
317 		     doWild?" ":"No wildcard",doNonWild?" ":"Wildcard only"))
318 
319 	/* the dom/dow situation is odd.  '* * 1,15 * Sun' will run on the
320 	 * first and fifteenth AND every Sunday;  '* * * * Sun' will run *only*
321 	 * on Sundays;  '* * 1,15 * *' will run *only* the 1st and 15th.  this
322 	 * is why we keep 'e->dow_star' and 'e->dom_star'.  yes, it's bizarre.
323 	 * like many bizarre things, it's the standard.
324 	 */
325 	for (u = db->head; u != NULL; u = u->next) {
326 		for (e = u->crontab; e != NULL; e = e->next) {
327 			Debug(DSCH|DEXT, ("user [%s:%lu:%lu:...] cmd=\"%s\"\n",
328 			    e->pwd->pw_name, (unsigned long)e->pwd->pw_uid,
329 			    (unsigned long)e->pwd->pw_gid, e->cmd))
330 			if (bit_test(e->minute, minute) &&
331 			    bit_test(e->hour, hour) &&
332 			    bit_test(e->month, month) &&
333 			    ( ((e->flags & DOM_STAR) || (e->flags & DOW_STAR))
334 			      ? (bit_test(e->dow,dow) && bit_test(e->dom,dom))
335 			      : (bit_test(e->dow,dow) || bit_test(e->dom,dom))
336 			    )
337 			   ) {
338 				if ((doNonWild &&
339 				    !(e->flags & (MIN_STAR|HR_STAR))) ||
340 				    (doWild && (e->flags & (MIN_STAR|HR_STAR))))
341 					job_add(e, u);
342 			}
343 		}
344 	}
345 }
346 
347 /*
348  * Set StartTime and clockTime to the current time.
349  * These are used for computing what time it really is right now.
350  * Note that clockTime is a unix wallclock time converted to minutes.
351  */
352 static void
353 set_time(int initialize) {
354 	struct tm tm;
355 	static int isdst;
356 
357 	StartTime = time(NULL);
358 
359 	/* We adjust the time to GMT so we can catch DST changes. */
360 	tm = *localtime(&StartTime);
361 	if (initialize || tm.tm_isdst != isdst) {
362 		isdst = tm.tm_isdst;
363 		GMToff = get_gmtoff(&StartTime, &tm);
364 		Debug(DSCH, ("[%ld] GMToff=%ld\n",
365 		    (long)getpid(), (long)GMToff))
366 	}
367 	clockTime = (StartTime + GMToff) / (time_t)SECONDS_PER_MINUTE;
368 }
369 
370 /*
371  * Try to just hit the next minute.
372  */
373 static void
374 cron_sleep(time_t target) {
375 	int fd, nfds;
376 	unsigned char poke;
377 	struct timeval t1, t2, tv;
378 	struct sockaddr_un s_un;
379 	socklen_t sunlen;
380 	static struct pollfd pfd[1];
381 
382 	gettimeofday(&t1, NULL);
383 	t1.tv_sec += GMToff;
384 	tv.tv_sec = (target * SECONDS_PER_MINUTE - t1.tv_sec) + 1;
385 	tv.tv_usec = 0;
386 
387 	pfd[0].fd = cronSock;
388 	pfd[0].events = POLLIN;
389 
390 	while (timerisset(&tv) && tv.tv_sec < 65) {
391 		Debug(DSCH, ("[%ld] Target time=%lld, sec-to-wait=%lld\n",
392 		    (long)getpid(), (long long)target*SECONDS_PER_MINUTE,
393 		    (long long)tv.tv_sec))
394 
395 		poke = RELOAD_CRON | RELOAD_AT;
396 
397 		/* Sleep until we time out, get a poke, or get a signal. */
398 		nfds = poll(pfd, 1, tv.tv_sec * 1000 + tv.tv_usec / 1000);
399 		if (nfds == 0)
400 			break;		/* timer expired */
401 		if (nfds == -1 && errno != EINTR)
402 			break;		/* an error occurred */
403 		if (nfds > 0) {
404 			Debug(DSCH, ("[%ld] Got a poke on the socket\n",
405 			    (long)getpid()))
406 			sunlen = sizeof(s_un);
407 			fd = accept(cronSock, (struct sockaddr *)&s_un, &sunlen);
408 			if (fd >= 0 && fcntl(fd, F_SETFL, O_NONBLOCK) == 0) {
409 				(void) read(fd, &poke, 1);
410 				close(fd);
411 				if (poke & RELOAD_CRON) {
412 					database.mtime = (time_t)0;
413 					load_database(&database);
414 				}
415 				if (poke & RELOAD_AT) {
416 					/*
417 					 * We run any pending at jobs right
418 					 * away so that "at now" really runs
419 					 * jobs immediately.
420 					 */
421 					gettimeofday(&t2, NULL);
422 					at_database.mtime = (time_t)0;
423 					if (scan_atjobs(&at_database, &t2))
424 						atrun(&at_database,
425 						    batch_maxload, t2.tv_sec);
426 				}
427 			}
428 		} else {
429 			/* Interrupted by a signal. */
430 			if (got_sighup) {
431 				got_sighup = 0;
432 				log_close();
433 			}
434 			if (got_sigchld) {
435 				got_sigchld = 0;
436 				sigchld_reaper();
437 			}
438 		}
439 
440 		/* Adjust tv and continue where we left off.  */
441 		gettimeofday(&t2, NULL);
442 		t2.tv_sec += GMToff;
443 		timersub(&t2, &t1, &t1);
444 		timersub(&tv, &t1, &tv);
445 		memcpy(&t1, &t2, sizeof(t1));
446 		if (tv.tv_sec < 0)
447 			tv.tv_sec = 0;
448 		if (tv.tv_usec < 0)
449 			tv.tv_usec = 0;
450 	}
451 }
452 
453 static void
454 sighup_handler(int x) {
455 	got_sighup = 1;
456 }
457 
458 static void
459 sigchld_handler(int x) {
460 	got_sigchld = 1;
461 }
462 
463 static void
464 quit(int x) {
465 	(void) unlink(_PATH_CRON_PID);
466 	_exit(0);
467 }
468 
469 static void
470 sigchld_reaper(void) {
471 	WAIT_T waiter;
472 	PID_T pid;
473 
474 	do {
475 		pid = waitpid(-1, &waiter, WNOHANG);
476 		switch (pid) {
477 		case -1:
478 			if (errno == EINTR)
479 				continue;
480 			Debug(DPROC,
481 			      ("[%ld] sigchld...no children\n",
482 			       (long)getpid()))
483 			break;
484 		case 0:
485 			Debug(DPROC,
486 			      ("[%ld] sigchld...no dead kids\n",
487 			       (long)getpid()))
488 			break;
489 		default:
490 			Debug(DPROC,
491 			      ("[%ld] sigchld...pid #%ld died, stat=%d\n",
492 			       (long)getpid(), (long)pid, WEXITSTATUS(waiter)))
493 			break;
494 		}
495 	} while (pid > 0);
496 }
497 
498 static void
499 parse_args(int argc, char *argv[]) {
500 	int argch;
501 	char *ep;
502 
503 	while (-1 != (argch = getopt(argc, argv, "l:nx:"))) {
504 		switch (argch) {
505 		case 'l':
506 			errno = 0;
507 			batch_maxload = strtod(optarg, &ep);
508 			if (*ep != '\0' || ep == optarg || errno == ERANGE ||
509 			    batch_maxload < 0) {
510 				fprintf(stderr, "Illegal load average: %s\n",
511 				    optarg);
512 				usage();
513 			}
514 			break;
515 		case 'n':
516 			NoFork = 1;
517 			break;
518 		case 'x':
519 			if (!set_debug_flags(optarg))
520 				usage();
521 			break;
522 		default:
523 			usage();
524 		}
525 	}
526 }
527