]> git.netwichtig.de Git - user/henk/code/snooze.git/blob - snooze.c
3811977decfc404ba31144ecacf5c9ccf0a167ed
[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[31] = {0};
144 char month[12] = {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 (!(weekday[tm->tm_wday] == '*'
172             && dayofmonth[tm->tm_mday-1] == '*'
173             && month[tm->tm_mon] == '*'
174             && weekofyear[isoweek(tm)-1] == '*'
175             && dayofyear[tm->tm_yday] == '*')) {
176                 if (month[tm->tm_mon] != '*') {
177                         // if month is not good, step month
178                         tm->tm_mon++;
179                         tm->tm_mday = 1;
180                 } else {
181                         tm->tm_mday++;
182                 }
183
184                 tm->tm_sec = 0;
185                 tm->tm_min = 0;
186                 tm->tm_hour = 0;
187
188                 t = mktime(tm);
189                 if (t > from+(366*24*60*60))  // no result within a year
190                         return -1;
191         }
192
193         int y = tm->tm_yday;  // save yday
194
195         while (!(hour[tm->tm_hour] == '*'
196             && minute[tm->tm_min] == '*'
197             && second[tm->tm_sec] == '*')) {
198                 if (hour[tm->tm_hour] != '*') {
199                         tm->tm_hour++;
200                         tm->tm_min = 0;
201                         tm->tm_sec = 0;
202                 } else if (minute[tm->tm_min] != '*') {
203                         tm->tm_min++;
204                         tm->tm_sec = 0;
205                 } else {
206                         tm->tm_sec++;
207                 }
208                 t = mktime(tm);
209                 if (tm->tm_yday != y)  // hit a different day, retry...
210                         goto next_day;
211         }
212             
213         return t;
214 }
215
216 static char isobuf[25];
217 char *
218 isotime(const struct tm *tm)
219 {
220         strftime(isobuf, sizeof isobuf, "%FT%T%z", tm);
221         return isobuf;
222 }
223
224 int main(int argc, char *argv[])
225 {
226         int c;
227         time_t t;
228         time_t now = time(0);
229         time_t last = 0;
230
231         /* default: every day at 00:00:00 */
232         memset(weekday, '*', sizeof weekday);
233         memset(dayofmonth, '*', sizeof dayofmonth);
234         memset(month, '*', sizeof month);
235         memset(dayofyear, '*', sizeof dayofyear);
236         memset(weekofyear, '*', sizeof weekofyear);
237         hour[0] = '*';
238         minute[0] = '*';
239         second[0] = '*';
240
241         while ((c = getopt(argc, argv, "+D:W:H:M:S:T:R:d:m:ns:t:vw:")) != -1)
242                 switch(c) {
243                 case 'D': parse(optarg, dayofyear, sizeof dayofyear, -1); break;
244                 case 'W': parse(optarg, weekofyear, sizeof weekofyear, -1); break;
245                 case 'H': parse(optarg, hour, sizeof hour, 0); break;
246                 case 'M': parse(optarg, minute, sizeof minute, 0); break;
247                 case 'S': parse(optarg, second, sizeof second, 0); break;
248                 case 'd': parse(optarg, dayofmonth, sizeof dayofmonth, -1); break;
249                 case 'm': parse(optarg, month, sizeof month, -1); break;
250                 case 'w': parse(optarg, weekday, sizeof weekday, 0);
251                         // special case: sunday is both 0 and 7.
252                         if (weekday[7] == '*') 
253                                 weekday[0] = '*';
254                         break;
255                 case 'n': nflag++; break;
256                 case 'v': vflag++; break;
257                 case 's': slack = parse_dur(optarg); break;
258                 case 'T': timewait = parse_dur(optarg); break;
259                 case 't': timefile = optarg; break;
260                 case 'R': randdelay = parse_dur(optarg); break;
261                 default:
262                         fprintf(stderr, "Usage: %s [-nv] [-t timefile] [-T timewait] [-R randdelay] [-s slack]\n"
263                             "  [-d mday] [-m mon] [-w wday] [-D yday] [-W yweek] [-H hour] [-M min] [-S sec] COMMAND...\n"
264                             "Timespec: exact: 1,3,5\n"
265                             "          range: 1-7\n"
266                             "          every n-th: /10\n", argv[0]);
267                         exit(2);
268                 }
269
270         time_t start = now + 1;
271
272         if (timefile) {
273                 struct stat st;
274                 if (stat(timefile, &st) < 0) {
275                         if (errno != ENOENT)
276                                 perror("stat");
277                         t = start - slack - 1 - timewait;
278                 } else {
279                         t = st.st_mtime + 1;
280                 }
281                 if (timewait == -1) {
282                         while (t < start - slack)
283                                 t = find_next(t + 1);
284                         start = t;
285                 } else {
286                         if (t + timewait > start)
287                                 start = st.st_mtime + timewait;
288                 }
289         }
290
291         if (randdelay) {
292                 long delay;
293 #ifdef __linux__
294                 long rnd = getauxval(AT_RANDOM);
295                 if (rnd > 0)
296                         delay = rnd % randdelay;
297                 else
298 #endif
299                 {
300                         srand48(getpid() ^ start);
301                         delay = lrand48() % randdelay;
302                 }
303                 if (vflag)
304                         printf("randomly delaying by %lds.\n", delay);
305                 start += delay;
306         }
307
308         t = find_next(start);
309         if (t < 0) {
310                 fprintf(stderr, "no satisfying date found within a year.\n");
311                 exit(2);
312         }
313
314         if (nflag) {
315                 /* dry-run, just output the next 5 dates. */
316                 int i;
317                 for (i = 0; i < 5; i++) {
318                         char weekstr[4];
319                         struct tm *tm = localtime(&t);
320                         strftime(weekstr, sizeof weekstr, "%a", tm);
321                         printf("%s %s %2ldd%3ldh%3ldm%3lds\n",
322                             isotime(tm),
323                             weekstr,
324                             ((t - now) / (60*60*24)),
325                             ((t - now) / (60*60)) % 24,
326                             ((t - now) / 60) % 60,
327                             (t - now) % 60);
328                         t = find_next(t + 1);
329                         if (t < 0) {
330                                 fprintf(stderr,
331                                     "no satisfying date found within a year.\n");
332                                 exit(2);
333                         }
334                 }
335                 exit(0);
336         }
337
338         struct tm *tm = localtime(&t);
339         if (vflag)
340                 printf("Snoozing until %s\n", isotime(tm));
341
342         // setup SIGALRM handler to force early execution
343         struct sigaction sa;
344         sa.sa_handler = &wakeup;
345         sa.sa_flags = SA_RESTART;
346         sigfillset(&sa.sa_mask);
347         sigaction(SIGALRM, &sa, NULL);  // XXX error handling
348
349         while (!alarm_rang) {
350                 now = time(0);
351                 if (now < last) {
352                         t = find_next(now);
353                         if (vflag)
354                                 printf("Time moved backwards, rescheduled for %s\n", isotime(tm));
355                 }
356                 t = mktime(tm);
357                 if (t <= now) {
358                         if (now - t <= slack)  // still about time
359                                 break;
360                         else {  // reschedule to next event
361                                 if (vflag)
362                                         printf("Missed execution at %s\n", isobuf);
363                                 t = find_next(now + 1);
364                                 tm = localtime(&t);
365                                 if (vflag)
366                                         printf("Snoozing until %s\n", isotime(tm));
367                         }
368                 } else {
369                         // do some sleeping, but not more than SLEEP_PHASE
370                         struct timespec ts;
371                         ts.tv_nsec = 0;
372                         ts.tv_sec = t - now > SLEEP_PHASE ? SLEEP_PHASE : t - now;
373                         last = now;
374                         nanosleep(&ts, 0);
375                         // we just iterate again when this exits early
376                 }
377         }
378
379         // no command to run, the outside script can go on
380         if (argc == optind)
381                 return 0;
382
383         if (vflag) {
384                 now = time(0);
385                 tm = localtime(&now);
386                 printf("Starting execution at %s\n", isotime(tm));
387         }
388
389         execvp(argv[optind], argv+optind);
390         perror("execvp");
391         return 255;
392 }