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