]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.sbin/cron/cron/cron.c
This commit was generated by cvs2svn to compensate for changes in r131823,
[FreeBSD/FreeBSD.git] / usr.sbin / cron / cron / cron.c
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  */
17
18 #if !defined(lint) && !defined(LINT)
19 static const char rcsid[] =
20   "$FreeBSD$";
21 #endif
22
23 #define MAIN_PROGRAM
24
25
26 #include "cron.h"
27 #include <sys/signal.h>
28 #if SYS_TIME_H
29 # include <sys/time.h>
30 #else
31 # include <time.h>
32 #endif
33
34
35 static  void    usage __P((void)),
36                 run_reboot_jobs __P((cron_db *)),
37                 cron_tick __P((cron_db *)),
38                 cron_sync __P((void)),
39                 cron_sleep __P((cron_db *)),
40                 cron_clean __P((cron_db *)),
41 #ifdef USE_SIGCHLD
42                 sigchld_handler __P((int)),
43 #endif
44                 sighup_handler __P((int)),
45                 parse_args __P((int c, char *v[]));
46
47 static time_t   last_time = 0;
48 static int      dst_enabled = 0;
49
50 static void
51 usage() {
52     char **dflags;
53
54         fprintf(stderr, "usage: cron [-j jitter] [-J rootjitter] "
55                         "[-s] [-o] [-x debugflag[,...]]\n");
56         fprintf(stderr, "\ndebugflags: ");
57
58         for(dflags = DebugFlagNames; *dflags; dflags++) {
59                 fprintf(stderr, "%s ", *dflags);
60         }
61         fprintf(stderr, "\n");
62
63         exit(ERROR_EXIT);
64 }
65
66
67 int
68 main(argc, argv)
69         int     argc;
70         char    *argv[];
71 {
72         cron_db database;
73
74         ProgramName = argv[0];
75
76 #if defined(BSD)
77         setlinebuf(stdout);
78         setlinebuf(stderr);
79 #endif
80
81         parse_args(argc, argv);
82
83 #ifdef USE_SIGCHLD
84         (void) signal(SIGCHLD, sigchld_handler);
85 #else
86         (void) signal(SIGCLD, SIG_IGN);
87 #endif
88         (void) signal(SIGHUP, sighup_handler);
89
90         acquire_daemonlock(0);
91         set_cron_uid();
92         set_cron_cwd();
93
94 #if defined(POSIX)
95         setenv("PATH", _PATH_DEFPATH, 1);
96 #endif
97
98         /* if there are no debug flags turned on, fork as a daemon should.
99          */
100 # if DEBUGGING
101         if (DebugFlags) {
102 # else
103         if (0) {
104 # endif
105                 (void) fprintf(stderr, "[%d] cron started\n", getpid());
106         } else {
107                 if (daemon(1, 0) == -1) {
108                         log_it("CRON",getpid(),"DEATH","can't become daemon");
109                         exit(0);
110                 }
111         }
112
113         acquire_daemonlock(0);
114         database.head = NULL;
115         database.tail = NULL;
116         database.mtime = (time_t) 0;
117         load_database(&database);
118         run_reboot_jobs(&database);
119         cron_sync();
120         while (TRUE) {
121 # if DEBUGGING
122             /* if (!(DebugFlags & DTEST)) */
123 # endif /*DEBUGGING*/
124                         cron_sleep(&database);
125
126                 load_database(&database);
127
128                 /* do this iteration
129                  */
130                 cron_tick(&database);
131
132                 /* sleep 1 minute
133                  */
134                 TargetTime += 60;
135         }
136 }
137
138
139 static void
140 run_reboot_jobs(db)
141         cron_db *db;
142 {
143         register user           *u;
144         register entry          *e;
145
146         for (u = db->head;  u != NULL;  u = u->next) {
147                 for (e = u->crontab;  e != NULL;  e = e->next) {
148                         if (e->flags & WHEN_REBOOT) {
149                                 job_add(e, u);
150                         }
151                 }
152         }
153         (void) job_runqueue();
154 }
155
156
157 static void
158 cron_tick(db)
159         cron_db *db;
160 {
161         static struct tm        lasttm;
162         static time_t   diff = 0, /* time difference in seconds from the last offset change */
163                 difflimit = 0; /* end point for the time zone correction */
164         struct tm       otztm; /* time in the old time zone */
165         int             otzminute, otzhour, otzdom, otzmonth, otzdow;
166         register struct tm      *tm = localtime(&TargetTime);
167         register int            minute, hour, dom, month, dow;
168         register user           *u;
169         register entry          *e;
170
171         /* make 0-based values out of these so we can use them as indicies
172          */
173         minute = tm->tm_min -FIRST_MINUTE;
174         hour = tm->tm_hour -FIRST_HOUR;
175         dom = tm->tm_mday -FIRST_DOM;
176         month = tm->tm_mon +1 /* 0..11 -> 1..12 */ -FIRST_MONTH;
177         dow = tm->tm_wday -FIRST_DOW;
178
179         Debug(DSCH, ("[%d] tick(%d,%d,%d,%d,%d)\n",
180                 getpid(), minute, hour, dom, month, dow))
181
182         if (dst_enabled && last_time != 0 
183         && TargetTime > last_time /* exclude stepping back */
184         && tm->tm_gmtoff != lasttm.tm_gmtoff ) {
185
186                 diff = tm->tm_gmtoff - lasttm.tm_gmtoff;
187
188                 if ( diff > 0 ) { /* ST->DST */
189                         /* mark jobs for an earlier run */
190                         difflimit = TargetTime + diff;
191                         for (u = db->head;  u != NULL;  u = u->next) {
192                                 for (e = u->crontab;  e != NULL;  e = e->next) {
193                                         e->flags &= ~NOT_UNTIL;
194                                         if ( e->lastrun >= TargetTime )
195                                                 e->lastrun = 0;
196                                         /* not include the ends of hourly ranges */
197                                         if ( e->lastrun < TargetTime - 3600 )
198                                                 e->flags |= RUN_AT;
199                                         else
200                                                 e->flags &= ~RUN_AT;
201                                 }
202                         }
203                 } else { /* diff < 0 : DST->ST */
204                         /* mark jobs for skipping */
205                         difflimit = TargetTime - diff;
206                         for (u = db->head;  u != NULL;  u = u->next) {
207                                 for (e = u->crontab;  e != NULL;  e = e->next) {
208                                         e->flags |= NOT_UNTIL;
209                                         e->flags &= ~RUN_AT;
210                                 }
211                         }
212                 }
213         }
214
215         if (diff != 0) {
216                 /* if the time was reset of the end of special zone is reached */
217                 if (last_time == 0 || TargetTime >= difflimit) {
218                         /* disable the TZ switch checks */
219                         diff = 0;
220                         difflimit = 0;
221                         for (u = db->head;  u != NULL;  u = u->next) {
222                                 for (e = u->crontab;  e != NULL;  e = e->next) {
223                                         e->flags &= ~(RUN_AT|NOT_UNTIL);
224                                 }
225                         }
226                 } else {
227                         /* get the time in the old time zone */
228                         time_t difftime = TargetTime + tm->tm_gmtoff - diff;
229                         gmtime_r(&difftime, &otztm);
230
231                         /* make 0-based values out of these so we can use them as indicies
232                          */
233                         otzminute = otztm.tm_min -FIRST_MINUTE;
234                         otzhour = otztm.tm_hour -FIRST_HOUR;
235                         otzdom = otztm.tm_mday -FIRST_DOM;
236                         otzmonth = otztm.tm_mon +1 /* 0..11 -> 1..12 */ -FIRST_MONTH;
237                         otzdow = otztm.tm_wday -FIRST_DOW;
238                 }
239         }
240
241         /* the dom/dow situation is odd.  '* * 1,15 * Sun' will run on the
242          * first and fifteenth AND every Sunday;  '* * * * Sun' will run *only*
243          * on Sundays;  '* * 1,15 * *' will run *only* the 1st and 15th.  this
244          * is why we keep 'e->dow_star' and 'e->dom_star'.  yes, it's bizarre.
245          * like many bizarre things, it's the standard.
246          */
247         for (u = db->head;  u != NULL;  u = u->next) {
248                 for (e = u->crontab;  e != NULL;  e = e->next) {
249                         Debug(DSCH|DEXT, ("user [%s:%d:%d:...] cmd=\"%s\"\n",
250                                           env_get("LOGNAME", e->envp),
251                                           e->uid, e->gid, e->cmd))
252
253                         if ( diff != 0 && (e->flags & (RUN_AT|NOT_UNTIL)) ) {
254                                 if (bit_test(e->minute, otzminute)
255                                  && bit_test(e->hour, otzhour)
256                                  && bit_test(e->month, otzmonth)
257                                  && ( ((e->flags & DOM_STAR) || (e->flags & DOW_STAR))
258                                           ? (bit_test(e->dow,otzdow) && bit_test(e->dom,otzdom))
259                                           : (bit_test(e->dow,otzdow) || bit_test(e->dom,otzdom))
260                                         )
261                                    ) {
262                                         if ( e->flags & RUN_AT ) {
263                                                 e->flags &= ~RUN_AT;
264                                                 e->lastrun = TargetTime;
265                                                 job_add(e, u);
266                                                 continue;
267                                         } else 
268                                                 e->flags &= ~NOT_UNTIL;
269                                 } else if ( e->flags & NOT_UNTIL )
270                                         continue;
271                         }
272
273                         if (bit_test(e->minute, minute)
274                          && bit_test(e->hour, hour)
275                          && bit_test(e->month, month)
276                          && ( ((e->flags & DOM_STAR) || (e->flags & DOW_STAR))
277                               ? (bit_test(e->dow,dow) && bit_test(e->dom,dom))
278                               : (bit_test(e->dow,dow) || bit_test(e->dom,dom))
279                             )
280                            ) {
281                                 e->flags &= ~RUN_AT;
282                                 e->lastrun = TargetTime;
283                                 job_add(e, u);
284                         }
285                 }
286         }
287
288         last_time = TargetTime;
289         lasttm = *tm;
290 }
291
292
293 /* the task here is to figure out how long it's going to be until :00 of the
294  * following minute and initialize TargetTime to this value.  TargetTime
295  * will subsequently slide 60 seconds at a time, with correction applied
296  * implicitly in cron_sleep().  it would be nice to let cron execute in
297  * the "current minute" before going to sleep, but by restarting cron you
298  * could then get it to execute a given minute's jobs more than once.
299  * instead we have the chance of missing a minute's jobs completely, but
300  * that's something sysadmin's know to expect what with crashing computers..
301  */
302 static void
303 cron_sync() {
304         register struct tm      *tm;
305
306         TargetTime = time((time_t*)0);
307         tm = localtime(&TargetTime);
308         TargetTime += (60 - tm->tm_sec);
309 }
310
311
312 static void
313 cron_sleep(db)
314         cron_db *db;
315 {
316         int     seconds_to_wait = 0;
317
318         /*
319          * Loop until we reach the top of the next minute, sleep when possible.
320          */
321
322         for (;;) {
323                 seconds_to_wait = (int) (TargetTime - time((time_t*)0));
324
325                 /*
326                  * If the seconds_to_wait value is insane, jump the cron
327                  */
328
329                 if (seconds_to_wait < -600 || seconds_to_wait > 600) {
330                         cron_clean(db);
331                         cron_sync();
332                         continue;
333                 }
334
335                 Debug(DSCH, ("[%d] TargetTime=%ld, sec-to-wait=%d\n",
336                         getpid(), (long)TargetTime, seconds_to_wait))
337
338                 /*
339                  * If we've run out of wait time or there are no jobs left
340                  * to run, break
341                  */
342
343                 if (seconds_to_wait <= 0)
344                         break;
345                 if (job_runqueue() == 0) {
346                         Debug(DSCH, ("[%d] sleeping for %d seconds\n",
347                                 getpid(), seconds_to_wait))
348
349                         sleep(seconds_to_wait);
350                 }
351         }
352 }
353
354
355 /* if the time was changed abruptly, clear the flags related
356  * to the daylight time switch handling to avoid strange effects
357  */
358
359 static void
360 cron_clean(db)
361         cron_db *db;
362 {
363         user            *u;
364         entry           *e;
365
366         last_time = 0;
367
368         for (u = db->head;  u != NULL;  u = u->next) {
369                 for (e = u->crontab;  e != NULL;  e = e->next) {
370                         e->flags &= ~(RUN_AT|NOT_UNTIL);
371                 }
372         }
373 }
374
375 #ifdef USE_SIGCHLD
376 static void
377 sigchld_handler(x) {
378         WAIT_T          waiter;
379         PID_T           pid;
380
381         for (;;) {
382 #ifdef POSIX
383                 pid = waitpid(-1, &waiter, WNOHANG);
384 #else
385                 pid = wait3(&waiter, WNOHANG, (struct rusage *)0);
386 #endif
387                 switch (pid) {
388                 case -1:
389                         Debug(DPROC,
390                                 ("[%d] sigchld...no children\n", getpid()))
391                         return;
392                 case 0:
393                         Debug(DPROC,
394                                 ("[%d] sigchld...no dead kids\n", getpid()))
395                         return;
396                 default:
397                         Debug(DPROC,
398                                 ("[%d] sigchld...pid #%d died, stat=%d\n",
399                                 getpid(), pid, WEXITSTATUS(waiter)))
400                 }
401         }
402 }
403 #endif /*USE_SIGCHLD*/
404
405
406 static void
407 sighup_handler(x) {
408         log_close();
409 }
410
411
412 static void
413 parse_args(argc, argv)
414         int     argc;
415         char    *argv[];
416 {
417         int     argch;
418         char    *endp;
419
420         while ((argch = getopt(argc, argv, "j:J:osx:")) != -1) {
421                 switch (argch) {
422                 case 'j':
423                         Jitter = strtoul(optarg, &endp, 10);
424                         if (*optarg == '\0' || *endp != '\0' || Jitter > 60)
425                                 errx(ERROR_EXIT,
426                                      "bad value for jitter: %s", optarg);
427                         break;
428                 case 'J':
429                         RootJitter = strtoul(optarg, &endp, 10);
430                         if (*optarg == '\0' || *endp != '\0' || RootJitter > 60)
431                                 errx(ERROR_EXIT,
432                                      "bad value for root jitter: %s", optarg);
433                         break;
434                 case 'o':
435                         dst_enabled = 0;
436                         break;
437                 case 's':
438                         dst_enabled = 1;
439                         break;
440                 case 'x':
441                         if (!set_debug_flags(optarg))
442                                 usage();
443                         break;
444                 default:
445                         usage();
446                 }
447         }
448 }
449