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