]> git.netwichtig.de Git - user/henk/code/snooze.git/blob - snooze.c
Print duration and day of week with -n
[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,
5  * Christian Neukirchen <chneukirchen@gmail.com>
6  * has waived all copyright and related or neighboring rights to this work.
7  * http://creativecommons.org/publicdomain/zero/1.0/
8  */
9
10 /*
11 ##% gcc -Os -Wall -g -o $STEM $FILE -Wextra -Wwrite-strings
12 */
13
14 #include <sys/stat.h>
15 #include <sys/types.h>
16
17 #include <ctype.h>
18 #include <errno.h>
19 #include <signal.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <time.h>
24 #include <unistd.h>
25
26 #ifdef __linux__
27 #include <sys/auxv.h>
28 #endif
29
30 static long slack = 60;
31 #define SLEEP_PHASE 300
32 static int nflag, vflag;
33
34 static int timewait = -1;
35 static int randdelay = 0;
36 static char *timefile;
37
38 static sig_atomic_t alarm_rang = 0;
39
40 static void
41 wakeup(int sig)
42 {
43         (void)sig;
44         alarm_rang = 1;
45 }
46
47 static long
48 parse_int(char **s, size_t minn, size_t maxn)
49 {
50         long n;
51         char *end;
52
53         errno = 0;
54         n = strtol(*s, &end, 10);
55         if (errno) {
56                 perror("strtol");
57                 exit(1);
58         }
59         if (n < (long)minn || n >= (long)maxn) {
60                 fprintf(stderr, "number outside %zd <= n < %zd\n", minn, maxn);
61                 exit(1);
62         }
63         *s = end;
64         return n;
65 }
66
67 static long
68 parse_dur(char *s)
69 {
70         long n;
71         char *end;
72
73         errno = 0;
74         n = strtol(s, &end, 10);
75         if (errno) {
76                 perror("strtol");
77                 exit(1);
78         }
79         if (n < 0) {
80                 fprintf(stderr, "negative duration\n");
81                 exit(1);
82         }
83         switch (*end) {
84         case 'm': n *= 60; break;
85         case 'h': n *= 60*60; break;
86         case 'd': n *= 24*60*60; break;
87         case 0: break;
88         default:
89                 fprintf(stderr, "junk after duration: %s\n", end);
90                 exit(1);
91         }
92         return n;
93 }
94
95 static int
96 parse(char *expr, char *buf, long bufsiz, int offset)
97 {
98         char *s;
99         long i, n = 0, n0 = 0;
100
101         memset(buf, ' ', bufsiz);
102
103         s = expr;
104         while (*s) {
105                 switch (*s) {
106                 case '0': case '1': case '2': case '3': case '4':
107                 case '5': case '6': case '7': case '8': case '9':
108                         n = parse_int(&s, -offset, bufsiz);
109                         buf[n+offset] = '*';
110                         break;
111                 case '-':
112                         n0 = n;
113                         s++;
114                         n = parse_int(&s, -offset, bufsiz);
115                         for (i = n0; i <= n; i++)
116                                 buf[i+offset] = '*';
117                         break;
118                 case '/':
119                         s++;
120                         n0 = n;
121                         n = parse_int(&s, -offset, bufsiz);
122                         if (n == 0)  // / = *
123                                 n = 1;
124                         for (i = n0; i < bufsiz; i += n)
125                                 buf[i+offset] = '*';
126                         break;
127                 case ',':
128                         s++;
129                         n = 0;
130                         break;
131                 case '*':
132                         s++;
133                         n = 0;
134                         for (i = 0; i < bufsiz; i++)
135                                 buf[i+offset] = '*';
136                         break;
137                 default:
138                         fprintf(stderr, "can't parse: %s %s\n", expr, s);
139                         exit(1);
140                 }
141         }
142
143         return 0;
144 }
145
146 char weekday[8] = {0};
147 char dayofmonth[31] = {0};
148 char month[12] = {0};
149 char dayofyear[366] = {0};
150 char weekofyear[53] = {0};
151 char hour[24] = {0};
152 char minute[60] = {0};
153 char second[61] = {0};
154
155 int
156 isoweek(struct tm *tm)
157 {
158         /* ugh, but easier than the correct formula... */
159         char weekstr[3];
160         char *w = weekstr;
161         strftime(weekstr, sizeof weekstr, "%V", tm);
162         return parse_int(&w, 1, 54);
163 }
164
165 time_t
166 find_next(time_t from)
167 {
168         time_t t;
169         struct tm *tm;
170
171         t = from;
172         tm = localtime(&t);
173
174 next_day:
175         while (!(weekday[tm->tm_wday] == '*'
176             && dayofmonth[tm->tm_mday-1] == '*'
177             && month[tm->tm_mon] == '*'
178             && weekofyear[isoweek(tm)] == '*'
179             && dayofyear[tm->tm_yday] == '*')) {
180                 if (month[tm->tm_mon] != '*') {
181                         // if month is not good, step month
182                         tm->tm_mon++;
183                         tm->tm_mday = 1;
184                 } else {
185                         tm->tm_mday++;
186                 }
187
188                 tm->tm_sec = 0;
189                 tm->tm_min = 0;
190                 tm->tm_hour = 0;
191
192                 t = mktime(tm);
193                 if (t > from+(365*24*60*60))  // no result within a year
194                         return -1;
195         }
196
197         int y = tm->tm_yday;  // save yday
198
199         while (!(hour[tm->tm_hour] == '*'
200             && minute[tm->tm_min] == '*'
201             && second[tm->tm_sec] == '*')) {
202                 if (hour[tm->tm_hour] != '*') {
203                         tm->tm_hour++;
204                         tm->tm_min = 0;
205                         tm->tm_sec = 0;
206                 } else if (minute[tm->tm_min] != '*') {
207                         tm->tm_min++;
208                         tm->tm_sec = 0;
209                 } else {
210                         tm->tm_sec++;
211                 }
212                 t = mktime(tm);
213                 if (tm->tm_yday != y)  // hit a different day, retry...
214                         goto next_day;
215         }
216             
217         return t;
218 }
219
220 static char isobuf[25];
221 char *
222 isotime(const struct tm *tm)
223 {
224         strftime(isobuf, sizeof isobuf, "%FT%T%z", tm);
225         return isobuf;
226 }
227
228 int main(int argc, char *argv[])
229 {
230         int c;
231         time_t t;
232         time_t now = time(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;
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                         if (t > 0) {
322                                 char weekstr[4];
323                                 struct tm *tm = localtime(&t);
324                                 strftime(weekstr, sizeof weekstr, "%a", tm);
325                                 printf("%s %s %2ldd%3ldh%3ldm%3lds\n",
326                                     isotime(tm),
327                                     weekstr,
328                                     ((t - now) / (60*60*24)),
329                                     ((t - now) / (60*60)) % 24,
330                                     ((t - now) / 60) % 60,
331                                     (t - now) % 60);
332                         }
333                         t = find_next(t + 1);
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                 t = mktime(tm);
352                 if (t <= now) {
353                         if (now - t <= slack)  // still about time
354                                 break;
355                         else {  // reschedule to next event
356                                 if (vflag)
357                                         printf("Missed execution at %s\n", isobuf);
358                                 t = find_next(now + 1);
359                                 tm = localtime(&t);
360                                 if (vflag)
361                                         printf("Snoozing until %s\n", isotime(tm));
362                         }
363                 } else {
364                         // do some sleeping, but not more than SLEEP_PHASE
365                         struct timespec ts;
366                         ts.tv_nsec = 0;
367                         ts.tv_sec = t - now > SLEEP_PHASE ? SLEEP_PHASE : t - now;
368                         nanosleep(&ts, 0);
369                         // we just iterate again when this exits early
370                 }
371         }
372
373         // no command to run, the outside script can go on
374         if (argc == optind)
375                 return 0;
376
377         if (vflag) {
378                 now = time(0);
379                 tm = localtime(&now);
380                 printf("Starting execution at %s\n", isotime(tm));
381         }
382
383         execvp(argv[optind], argv+optind);
384         perror("execvp");
385         return 255;
386 }