]> git.netwichtig.de Git - user/henk/code/snooze.git/blob - snooze.c
more off-by-ones :(
[user/henk/code/snooze.git] / snooze.c
1 /*
2  * snooze - run a command at a particular time
3  *
4  * To the extent possible under law, Leah Neukirchen <leah@vuxu.org>
5  * has waived all copyright and related or neighboring rights to this work.
6  * http://creativecommons.org/publicdomain/zero/1.0/
7  */
8
9 #include <sys/stat.h>
10 #include <sys/types.h>
11
12 #include <ctype.h>
13 #include <errno.h>
14 #include <signal.h>
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #include <time.h>
19 #include <unistd.h>
20
21 #ifdef __linux__
22 #include <sys/auxv.h>
23 #endif
24
25 static long slack = 60;
26 #define SLEEP_PHASE 300
27 static int nflag, vflag;
28
29 static int timewait = -1;
30 static int randdelay = 0;
31 static char *timefile;
32
33 static sig_atomic_t alarm_rang = 0;
34
35 static void
36 wakeup(int sig)
37 {
38         (void)sig;
39         alarm_rang = 1;
40 }
41
42 static long
43 parse_int(char **s, size_t minn, size_t maxn)
44 {
45         long n;
46         char *end;
47
48         errno = 0;
49         n = strtol(*s, &end, 10);
50         if (errno) {
51                 perror("strtol");
52                 exit(1);
53         }
54         if (n < (long)minn || n >= (long)maxn) {
55                 fprintf(stderr, "number outside %zd <= n < %zd\n", minn, maxn);
56                 exit(1);
57         }
58         *s = end;
59         return n;
60 }
61
62 static long
63 parse_dur(char *s)
64 {
65         long n;
66         char *end;
67
68         errno = 0;
69         n = strtol(s, &end, 10);
70         if (errno) {
71                 perror("strtol");
72                 exit(1);
73         }
74         if (n < 0) {
75                 fprintf(stderr, "negative duration\n");
76                 exit(1);
77         }
78         switch (*end) {
79         case 'm': n *= 60; break;
80         case 'h': n *= 60*60; break;
81         case 'd': n *= 24*60*60; break;
82         case 0: break;
83         default:
84                 fprintf(stderr, "junk after duration: %s\n", end);
85                 exit(1);
86         }
87         return n;
88 }
89
90 static int
91 parse(char *expr, char *buf, long bufsiz, int offset)
92 {
93         char *s;
94         long i, n = 0, n0 = 0;
95
96         memset(buf, ' ', bufsiz);
97
98         s = expr;
99         while (*s) {
100                 switch (*s) {
101                 case '0': case '1': case '2': case '3': case '4':
102                 case '5': case '6': case '7': case '8': case '9':
103                         n = parse_int(&s, -offset, bufsiz);
104                         buf[n+offset] = '*';
105                         break;
106                 case '-':
107                         n0 = n;
108                         s++;
109                         n = parse_int(&s, -offset, bufsiz);
110                         for (i = n0; i <= n; i++)
111                                 buf[i+offset] = '*';
112                         break;
113                 case '/':
114                         s++;
115                         n0 = n;
116                         if (*s)
117                                 n = parse_int(&s, -offset, bufsiz);
118                         if (n == 0)  // / = *
119                                 n = 1;
120                         for (i = n0; i < bufsiz; i += n)
121                                 buf[i+offset] = '*';
122                         break;
123                 case ',':
124                         s++;
125                         n = 0;
126                         break;
127                 case '*':
128                         s++;
129                         n = 0;
130                         for (i = 0; i < bufsiz; i++)
131                                 buf[i+offset] = '*';
132                         break;
133                 default:
134                         fprintf(stderr, "can't parse: %s %s\n", expr, s);
135                         exit(1);
136                 }
137         }
138
139         return 0;
140 }
141
142 char weekday[8] = {0};
143 char dayofmonth[32] = {0};
144 char month[13] = {0};
145 char dayofyear[367] = {0};
146 char weekofyear[54] = {0};
147 char hour[24] = {0};
148 char minute[60] = {0};
149 char second[61] = {0};
150
151 int
152 isoweek(struct tm *tm)
153 {
154         /* ugh, but easier than the correct formula... */
155         char weekstr[3];
156         char *w = weekstr;
157         strftime(weekstr, sizeof weekstr, "%V", tm);
158         return parse_int(&w, 1, 54);
159 }
160
161 time_t
162 find_next(time_t from)
163 {
164         time_t t;
165         struct tm *tm;
166
167         t = from;
168         tm = localtime(&t);
169
170 next_day:
171         while (!(
172             weekday[tm->tm_wday] == '*' &&
173             dayofmonth[tm->tm_mday-1] == '*' &&
174             month[tm->tm_mon] == '*' &&
175             weekofyear[isoweek(tm)-1] == '*' &&
176             dayofyear[tm->tm_yday] == '*')) {
177                 if (month[tm->tm_mon] != '*') {
178                         // if month is not good, step month
179                         tm->tm_mon++;
180                         tm->tm_mday = 1;
181                 } else {
182                         tm->tm_mday++;
183                 }
184
185                 tm->tm_sec = 0;
186                 tm->tm_min = 0;
187                 tm->tm_hour = 0;
188
189                 t = mktime(tm);
190                 if (t > from+(366*24*60*60))  // no result within a year
191                         return -1;
192         }
193
194         int y = tm->tm_yday;  // save yday
195
196         while (!(
197             hour[tm->tm_hour] == '*' &&
198             minute[tm->tm_min] == '*' &&
199             second[tm->tm_sec] == '*')) {
200                 if (hour[tm->tm_hour] != '*') {
201                         tm->tm_hour++;
202                         tm->tm_min = 0;
203                         tm->tm_sec = 0;
204                 } else if (minute[tm->tm_min] != '*') {
205                         tm->tm_min++;
206                         tm->tm_sec = 0;
207                 } else {
208                         tm->tm_sec++;
209                 }
210                 t = mktime(tm);
211                 if (tm->tm_yday != y)  // hit a different day, retry...
212                         goto next_day;
213         }
214
215         return t;
216 }
217
218 static char isobuf[25];
219 char *
220 isotime(const struct tm *tm)
221 {
222         strftime(isobuf, sizeof isobuf, "%FT%T%z", tm);
223         return isobuf;
224 }
225
226 int
227 main(int argc, char *argv[])
228 {
229         int c;
230         time_t t;
231         time_t now = time(0);
232         time_t last = 0;
233
234         /* default: every day at 00:00:00 */
235         memset(weekday, '*', sizeof weekday);
236         memset(dayofmonth, '*', sizeof dayofmonth);
237         memset(month, '*', sizeof month);
238         memset(dayofyear, '*', sizeof dayofyear);
239         memset(weekofyear, '*', sizeof weekofyear);
240         hour[0] = '*';
241         minute[0] = '*';
242         second[0] = '*';
243
244         while ((c = getopt(argc, argv, "+D:W:H:M:S:T:R:d:m:ns:t:vw:")) != -1)
245                 switch (c) {
246                 case 'D': parse(optarg, dayofyear, sizeof dayofyear, -1); break;
247                 case 'W': parse(optarg, weekofyear, sizeof weekofyear, -1); break;
248                 case 'H': parse(optarg, hour, sizeof hour, 0); break;
249                 case 'M': parse(optarg, minute, sizeof minute, 0); break;
250                 case 'S': parse(optarg, second, sizeof second, 0); break;
251                 case 'd': parse(optarg, dayofmonth, sizeof dayofmonth, -1); break;
252                 case 'm': parse(optarg, month, sizeof month, -1); break;
253                 case 'w': parse(optarg, weekday, sizeof weekday, 0);
254                         // special case: sunday is both 0 and 7.
255                         if (weekday[7] == '*')
256                                 weekday[0] = '*';
257                         break;
258                 case 'n': nflag++; break;
259                 case 'v': vflag++; break;
260                 case 's': slack = parse_dur(optarg); break;
261                 case 'T': timewait = parse_dur(optarg); break;
262                 case 't': timefile = optarg; break;
263                 case 'R': randdelay = parse_dur(optarg); break;
264                 default:
265                         fprintf(stderr, "Usage: %s [-nv] [-t timefile] [-T timewait] [-R randdelay] [-s slack]\n"
266                             "  [-d mday] [-m mon] [-w wday] [-D yday] [-W yweek] [-H hour] [-M min] [-S sec] COMMAND...\n"
267                             "Timespec: exact: 1,3,5\n"
268                             "          range: 1-7\n"
269                             "          every n-th: /10\n", argv[0]);
270                         exit(2);
271                 }
272
273         time_t start = now + 1;
274
275         if (timefile) {
276                 struct stat st;
277                 if (stat(timefile, &st) < 0) {
278                         if (errno != ENOENT)
279                                 perror("stat");
280                         t = start - slack - 1 - timewait;
281                 } else {
282                         t = st.st_mtime + 1;
283                 }
284                 if (timewait == -1) {
285                         while (t < start - slack)
286                                 t = find_next(t + 1);
287                         start = t;
288                 } else {
289                         if (t + timewait > start)
290                                 start = st.st_mtime + timewait;
291                 }
292         }
293
294         if (randdelay) {
295                 long delay;
296 #ifdef __linux__
297                 long rnd = getauxval(AT_RANDOM);
298                 if (rnd > 0)
299                         delay = rnd % randdelay;
300                 else
301 #endif
302                 {
303                         srand48(getpid() ^ start);
304                         delay = lrand48() % randdelay;
305                 }
306                 if (vflag)
307                         printf("randomly delaying by %lds.\n", delay);
308                 start += delay;
309         }
310
311         t = find_next(start);
312         if (t < 0) {
313                 fprintf(stderr, "no satisfying date found within a year.\n");
314                 exit(2);
315         }
316
317         if (nflag) {
318                 /* dry-run, just output the next 5 dates. */
319                 int i;
320                 for (i = 0; i < 5; i++) {
321                         char weekstr[4];
322                         struct tm *tm = localtime(&t);
323                         strftime(weekstr, sizeof weekstr, "%a", tm);
324                         printf("%s %s %2ldd%3ldh%3ldm%3lds\n",
325                             isotime(tm),
326                             weekstr,
327                             ((t - now) / (60*60*24)),
328                             ((t - now) / (60*60)) % 24,
329                             ((t - now) / 60) % 60,
330                             (t - now) % 60);
331                         t = find_next(t + 1);
332                         if (t < 0) {
333                                 fprintf(stderr,
334                                     "no satisfying date found within a year.\n");
335                                 exit(2);
336                         }
337                 }
338                 exit(0);
339         }
340
341         struct tm *tm = localtime(&t);
342         if (vflag)
343                 printf("Snoozing until %s\n", isotime(tm));
344
345         // setup SIGALRM handler to force early execution
346         struct sigaction sa;
347         sa.sa_handler = &wakeup;
348         sa.sa_flags = SA_RESTART;
349         sigfillset(&sa.sa_mask);
350         sigaction(SIGALRM, &sa, NULL);  // XXX error handling
351
352         while (!alarm_rang) {
353                 now = time(0);
354                 if (now < last) {
355                         t = find_next(now);
356                         if (vflag)
357                                 printf("Time moved backwards, rescheduled for %s\n", isotime(tm));
358                 }
359                 t = mktime(tm);
360                 if (t <= now) {
361                         if (now - t <= slack)  // still about time
362                                 break;
363                         else {  // reschedule to next event
364                                 if (vflag)
365                                         printf("Missed execution at %s\n", isobuf);
366                                 t = find_next(now + 1);
367                                 tm = localtime(&t);
368                                 if (vflag)
369                                         printf("Snoozing until %s\n", isotime(tm));
370                         }
371                 } else {
372                         // do some sleeping, but not more than SLEEP_PHASE
373                         struct timespec ts;
374                         ts.tv_nsec = 0;
375                         ts.tv_sec = t - now > SLEEP_PHASE ? SLEEP_PHASE : t - now;
376                         last = now;
377                         nanosleep(&ts, 0);
378                         // we just iterate again when this exits early
379                 }
380         }
381
382         // no command to run, the outside script can go on
383         if (argc == optind)
384                 return 0;
385
386         if (vflag) {
387                 now = time(0);
388                 tm = localtime(&now);
389                 printf("Starting execution at %s\n", isotime(tm));
390         }
391
392         execvp(argv[optind], argv+optind);
393         perror("execvp");
394         return 255;
395 }