Use braces in elses which follow multi-statement ifs
[khatus.git] / x5 / khatus.c
1 #include <sys/select.h>
2 #include <sys/stat.h>
3
4 #include <assert.h>
5 #include <ctype.h>
6 #include <errno.h>
7 #include <fcntl.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <time.h>
12 #include <unistd.h>
13
14 #include <X11/Xlib.h>
15
16 #include "bsdtimespec.h"
17
18 #define debug(args...) if (cfg->log_level >= Debug) {fprintf(stderr, "[debug] " args); fflush(stderr);}
19 #define info( args...) if (cfg->log_level >= Info ) {fprintf(stderr, "[info] " args); fflush(stderr);}
20 #define error(args...) if (cfg->log_level >= Error) {fprintf(stderr, "[error] " args); fflush(stderr);}
21 #define fatal(args...) {fprintf(stderr, "[fatal] " args); exit(EXIT_FAILURE);}
22 #define usage(args...) {print_usage(); fatal("[usage] " args);}
23
24 #define ERRMSG "ERROR"
25
26 static const char errmsg[] = ERRMSG;
27 static const int errlen = sizeof(ERRMSG) - 1;
28
29 char *argv0;
30
31 typedef enum LogLevel {
32 Nothing,
33 Error,
34 Info,
35 Debug
36 } LogLevel;
37
38 /* TODO: Convert fifo list to fifo array. */
39 typedef struct Fifo Fifo;
40 struct Fifo {
41 char *name;
42 int fd;
43 int width;
44 int last_read;
45 int ttl;
46 int pos; /* Position on the output buffer. */
47 Fifo *next;
48 };
49
50 typedef struct Config Config;
51 struct Config {
52 int interval;
53 char * separator;
54 Fifo * fifos;
55 int fifo_count;
56 int total_width;
57 int output_to_x_root_window;
58 LogLevel log_level;
59 } defaults = {
60 .interval = 1,
61 .separator = "|",
62 .fifos = NULL,
63 .fifo_count = 0,
64 .total_width = 0,
65 .output_to_x_root_window = 0,
66 .log_level = Info,
67 };
68
69 void
70 fifo_print_one(Fifo *f, Config *cfg)
71 {
72 info("Fifo "
73 "{"
74 " name = %s,"
75 " fd = %d,"
76 " width = %d,"
77 " last_read = %d,"
78 " ttl = %d,"
79 " pos = %d,"
80 " next = %p,"
81 " }\n",
82 f->name,
83 f->fd,
84 f->width,
85 f->last_read,
86 f->ttl,
87 f->pos,
88 f->next
89 );
90 }
91
92 void
93 fifo_print_all(Fifo *head, Config *cfg)
94 {
95 for (Fifo *f = head; f; f = f->next) {
96 fifo_print_one(f, cfg);
97 }
98 }
99
100 void
101 config_print(Config *cfg)
102 {
103 info(
104 "Config "
105 "{"
106 " interval = %d,"
107 " separator = %s,"
108 " fifo_count = %d,"
109 " total_width = %d,"
110 " log_level = %d,"
111 " fifos = ..."
112 " }\n",
113 cfg->interval,
114 cfg->separator,
115 cfg->fifo_count,
116 cfg->total_width,
117 cfg->log_level
118 );
119 fifo_print_all(cfg->fifos, cfg);
120 }
121
122 int
123 is_pos_num(char *s)
124 {
125 while (*s != '\0')
126 if (!isdigit(*(s++)))
127 return 0;
128 return 1;
129 }
130
131 void
132 print_usage()
133 {
134 assert(argv0);
135 fprintf(
136 stderr,
137 "\n"
138 "Usage: %s [OPTION ...] SPEC [SPEC ...]\n"
139 "\n"
140 " SPEC = FILE_PATH DATA_WIDTH DATA_TTL\n"
141 " FILE_PATH = string\n"
142 " DATA_WIDTH = int (* (positive) number of characters *)\n"
143 " DATA_TTL = int (* (positive) number of seconds *)\n"
144 " OPTION = -i INTERVAL\n"
145 " | -s SEPARATOR\n"
146 " | -x (* Output to X root window *)\n"
147 " | -l LOG_LEVEL\n"
148 " SEPARATOR = string\n"
149 " INTERVAL = int (* (positive) number of seconds *)\n"
150 " LOG_LEVEL = int (* %d through %d *)\n"
151 "\n",
152 argv0,
153 Nothing,
154 Debug
155 );
156 fprintf(
157 stderr,
158 "Example: %s -i 1 /dev/shm/khatus/khatus_sensor_x 4 10\n"
159 "\n",
160 argv0
161 );
162 }
163
164 void opts_parse_any(Config *, int, char *[], int); /* For mutually-recursive calls. */
165
166 void
167 parse_opts_opt_i(Config *cfg, int argc, char *argv[], int i)
168 {
169 char *param;
170
171 if (i >= argc)
172 usage("Option -i parameter is missing.\n");
173 param = argv[i++];
174 if (!is_pos_num(param))
175 usage("Option -i parameter is invalid: \"%s\"\n", param);
176 cfg->interval = atoi(param);
177 opts_parse_any(cfg, argc, argv, i);
178 }
179
180 void
181 parse_opts_opt_s(Config *cfg, int argc, char *argv[], int i)
182 {
183 if (i >= argc)
184 usage("Option -s parameter is missing.\n");
185 cfg->separator = calloc((strlen(argv[i]) + 1), sizeof(char));
186 strcpy(cfg->separator, argv[i]);
187 opts_parse_any(cfg, argc, argv, ++i);
188 }
189
190 void
191 parse_opts_opt_l(Config *cfg, int argc, char *argv[], int i)
192 {
193 char *param;
194 int log_level;
195
196 if (i >= argc)
197 usage("Option -l parameter is missing.\n");
198 param = argv[i++];
199 if (!is_pos_num(param))
200 usage("Option -l parameter is invalid: \"%s\"\n", param);
201 log_level = atoi(param);
202 if (log_level > Debug)
203 usage("Option -l value (%d) exceeds maximum (%d)\n", log_level, Debug);
204 cfg->log_level = log_level;
205 opts_parse_any(cfg, argc, argv, i);
206 }
207
208 void
209 parse_opts_opt(Config *cfg, int argc, char *argv[], int i)
210 {
211 switch (argv[i][1]) {
212 case 'i':
213 /* TODO: Generic set_int */
214 parse_opts_opt_i(cfg, argc, argv, ++i);
215 break;
216 case 's':
217 /* TODO: Generic set_str */
218 parse_opts_opt_s(cfg, argc, argv, ++i);
219 break;
220 case 'x':
221 cfg->output_to_x_root_window = 1;
222 opts_parse_any(cfg, argc, argv, ++i);
223 break;
224 case 'l':
225 /* TODO: Generic set_int */
226 parse_opts_opt_l(cfg, argc, argv, ++i);
227 break;
228 default :
229 usage("Option \"%s\" is invalid\n", argv[i]);
230 }
231 }
232
233 void
234 parse_opts_spec(Config *cfg, int argc, char *argv[], int i)
235 {
236 if ((i + 3) > argc)
237 usage("[spec] Parameter(s) missing for fifo \"%s\".\n", argv[i]);
238
239 char *n = argv[i++];
240 char *w = argv[i++];
241 char *t = argv[i++];
242
243 if (!is_pos_num(w))
244 usage("[spec] Invalid width: \"%s\", for fifo \"%s\"\n", w, n);
245 if (!is_pos_num(t))
246 usage("[spec] Invalid TTL: \"%s\", for fifo \"%s\"\n", t, n);
247 Fifo *f = calloc(1, sizeof(struct Fifo));
248 if (f) {
249 f->name = n;
250 f->fd = -1;
251 f->width = atoi(w);
252 f->ttl = atoi(t);
253 f->last_read = 0;
254 f->pos = cfg->total_width;
255 f->next = cfg->fifos;
256
257 cfg->fifos = f;
258 cfg->total_width += f->width;
259 cfg->fifo_count++;
260 } else {
261 fatal("[memory] Allocation failure.");
262 }
263 opts_parse_any(cfg, argc, argv, i);
264 }
265
266 void
267 opts_parse_any(Config *cfg, int argc, char *argv[], int i)
268 {
269 if (i < argc) {
270 switch (argv[i][0]) {
271 case '-':
272 parse_opts_opt(cfg, argc, argv, i);
273 break;
274 default :
275 parse_opts_spec(cfg, argc, argv, i);
276 }
277 }
278 }
279
280 void
281 opts_parse(Config *cfg, int argc, char *argv[])
282 {
283 opts_parse_any(cfg, argc, argv, 1);
284
285 Fifo *last = cfg->fifos;
286 cfg->fifos = NULL;
287 for (Fifo *f = last; f; ) {
288 Fifo *next = f->next;
289 f->next = cfg->fifos;
290 cfg->fifos = f;
291 f = next;
292 }
293 }
294
295 void
296 fifo_read_error(Fifo *f, char *buf)
297 {
298 char *b;
299 int i;
300
301 b = buf + f->pos;
302 /* Copy as much of the error message as possible.
303 * EXCLUDING the reminating \0. */
304 for (i = 0; i < errlen && i < f->width; i++)
305 b[i] = errmsg[i];
306 /* Any remaining slots: */
307 for (; i < f->width; i++)
308 b[i] = '_';
309 }
310
311 void
312 fifo_read_one(Fifo *f, char *buf, Config *cfg)
313 {
314 ssize_t current;
315 ssize_t total;
316 char *b;
317 char c;
318
319 current = 0;
320 total = 0;
321 c = '\0';
322 b = buf + f->pos;
323 while ((current = read(f->fd, &c, 1)) && c != '\n' && c != '\0' && total++ < f->width)
324 *b++ = c;
325 if (current == -1) {
326 error("Failed to read: \"%s\". Error: %s\n", f->name, strerror(errno));
327 fifo_read_error(f, buf);
328 } else {
329 while (total++ < f->width)
330 *b++ = ' ';
331 }
332 /* TODO Record timestamp read */
333 close(f->fd);
334 f->fd = -1;
335 }
336
337 void
338 fifo_read_all(Config *cfg, char *buf)
339 {
340 fd_set fds;
341 int maxfd = -1;
342 int ready;
343 struct stat st;
344
345 FD_ZERO(&fds);
346 for (Fifo *f = cfg->fifos; f; f = f->next) {
347 /* TODO: Create the FIFO if it doesn't already exist. */
348 if (lstat(f->name, &st) < 0) {
349 error("Cannot stat \"%s\". Error: %s\n", f->name, strerror(errno));
350 fifo_read_error(f, buf);
351 continue;
352 }
353 if (!(st.st_mode & S_IFIFO)) {
354 error("\"%s\" is not a FIFO\n", f->name);
355 fifo_read_error(f, buf);
356 continue;
357 }
358 debug("opening: %s\n", f->name);
359 if (f->fd < 0)
360 f->fd = open(f->name, O_RDONLY | O_NONBLOCK);
361 if (f->fd == -1) {
362 /* TODO: Consider backing off retries for failed fifos. */
363 error("Failed to open \"%s\"\n", f->name);
364 fifo_read_error(f, buf);
365 continue;
366 }
367 if (f->fd > maxfd)
368 maxfd = f->fd;
369 FD_SET(f->fd, &fds);
370 }
371 debug("selecting...\n");
372 ready = select(maxfd + 1, &fds, NULL, NULL, NULL);
373 debug("ready: %d\n", ready);
374 assert(ready != 0);
375 if (ready < 0)
376 fatal("%s", strerror(errno));
377 for (Fifo *f = cfg->fifos; f; f = f->next) {
378 if (FD_ISSET(f->fd, &fds)) {
379 debug("reading: %s\n", f->name);
380 fifo_read_one(f, buf, cfg);
381 }
382 }
383 }
384
385 void
386 snooze(struct timespec *t, Config *cfg)
387 {
388 struct timespec remainder;
389 int result;
390
391 result = nanosleep(t, &remainder);
392
393 if (result < 0) {
394 if (errno == EINTR) {
395 info(
396 "nanosleep interrupted. Remainder: "
397 "{ tv_sec = %ld, tv_nsec = %ld }",
398 remainder.tv_sec, remainder.tv_nsec);
399 /* No big deal if we occasionally sleep less,
400 * so not attempting to correct after an interruption.
401 */
402 } else {
403 fatal("nanosleep: %s\n", strerror(errno));
404 }
405 }
406 }
407
408 int
409 main(int argc, char *argv[])
410 {
411 int width = 0;
412 int nfifos = 0;
413 int seplen = 0;
414 int prefix = 0;
415 int errors = 0;
416 char *buf;
417 Config cfg0 = defaults;
418 Config *cfg = &cfg0;
419 Display *display = NULL;
420 struct stat st;
421 struct timespec
422 t0, /* time stamp. before reading fifos */
423 t1, /* time stamp. after reading fifos */
424 ti, /* time interval desired (t1 - t0) */
425 td, /* time interval measured (t1 - t0) */
426 tc; /* time interval correction (ti - td) when td < ti */
427
428 argv0 = argv[0];
429
430 opts_parse(cfg, argc, argv);
431 debug("argv0 = %s\n", argv0);
432 config_print(cfg);
433
434 /* TODO: Support interval < 1. i.e. implement timespec_of_float */
435 ti.tv_sec = cfg->interval;
436 ti.tv_nsec = 0;
437
438 if (cfg->fifos == NULL)
439 usage("No fifo specs were given!\n");
440
441 /* 1st pass to check file existence and type */
442 for (Fifo *f = cfg->fifos; f; f = f->next) {
443 if (lstat(f->name, &st) < 0) {
444 error("Cannot stat \"%s\". Error: %s\n", f->name, strerror(errno));
445 errors++;
446 continue;
447 }
448 if (!(st.st_mode & S_IFIFO)) {
449 error("\"%s\" is not a FIFO\n", f->name);
450 errors++;
451 continue;
452 }
453 }
454 if (errors)
455 fatal("Encountered errors with the given file paths. See log.\n");
456
457 width = cfg->total_width;
458 seplen = strlen(cfg->separator);
459
460 /* 2nd pass to make space for separators */
461 for (Fifo *f = cfg->fifos; f; f = f->next) {
462 f->pos += prefix;
463 prefix += seplen;
464 nfifos++;
465 }
466 width += (seplen * (nfifos - 1));
467 buf = calloc(1, width + 1);
468 if (buf == NULL)
469 fatal("[memory] Failed to allocate buffer of %d bytes", width);
470 memset(buf, ' ', width);
471 buf[width] = '\0';
472 /* 3rd pass to set the separators */
473 for (Fifo *f = cfg->fifos; f; f = f->next) {
474 if (f->pos) { /* Skip the first, left-most */
475 /* Copying only seplen ensures we omit the '\0' byte. */
476 strncpy(buf + (f->pos - seplen), cfg->separator, seplen);
477 }
478 }
479
480 if (cfg->output_to_x_root_window && !(display = XOpenDisplay(NULL)))
481 fatal("XOpenDisplay failed with: %p\n", display);
482 /* TODO: Handle signals */
483 for (;;) {
484 clock_gettime(CLOCK_MONOTONIC, &t0); // FIXME: check errors
485 /* TODO: Cache expiration. i.e. use the TTL */
486 /* TODO: How to trigger TTL check? On select? Alarm signal? */
487 /* TODO: Set timeout on fifo_read_all based on diff of last time of
488 * fifo_read_all and desired time of next TTL check.
489 */
490 /* TODO: How long to wait on IO? Max TTL? */
491 fifo_read_all(cfg, buf);
492 if (cfg->output_to_x_root_window) {
493 if (XStoreName(display, DefaultRootWindow(display), buf) < 0)
494 fatal("XStoreName failed.\n");
495 XFlush(display);
496 } else {
497 puts(buf);
498 fflush(stdout);
499 }
500 clock_gettime(CLOCK_MONOTONIC, &t1); // FIXME: check errors
501 timespecsub(&t1, &t0, &td);
502 debug("td {tv_sec = %ld, tv_nsec = %ld}\n", td.tv_sec, td.tv_nsec);
503 if (timespeccmp(&td, &ti, <)) {
504 /* Pushback on data producers by refusing to read the
505 * pipe more frequently than the interval.
506 */
507 timespecsub(&ti, &td, &tc);
508 debug("snooze YES\n");
509 snooze(&tc, cfg);
510 } else {
511 debug("snooze NO\n");
512 }
513 }
514
515 return EXIT_SUCCESS;
516 }
This page took 0.093796 seconds and 4 git commands to generate.