Put error msg in buffer instead of exiting on read errors
[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 <unistd.h>
12
13 #include <X11/Xlib.h>
14
15 #define debug(args...) {fprintf(stderr, "[debug] " args);}
16 #define info( args...) {fprintf(stderr, "[info] " args);}
17 #define error(args...) {fprintf(stderr, "[error] " args);}
18 #define fatal(args...) {fprintf(stderr, "[fatal] " args); exit(EXIT_FAILURE);}
19 #define usage(args...) {print_usage(); fatal("[usage] " args);}
20
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; /* Position on the output buffer. */
37 Fifo *next;
38 };
39
40 typedef struct Config Config;
41 struct Config {
42 int interval;
43 char * separator;
44 Fifo * fifos;
45 int fifo_count;
46 int total_width;
47 int output_to_x_root_window;
48 } defaults = {
49 .interval = 1,
50 .separator = "|",
51 .fifos = NULL,
52 .fifo_count = 0,
53 .total_width = 0,
54 .output_to_x_root_window = 0,
55 };
56
57 void
58 fifo_print_one(Fifo *f)
59 {
60 debug(
61 "Fifo "
62 "{"
63 " name = %s,"
64 " fd = %d,"
65 " width = %d,"
66 " last_read = %d,"
67 " ttl = %d,"
68 " pos = %d,"
69 " next = %p,"
70 " }\n",
71 f->name,
72 f->fd,
73 f->width,
74 f->last_read,
75 f->ttl,
76 f->pos,
77 f->next
78 );
79 }
80
81 void
82 fifo_print_all(Fifo *head)
83 {
84 for (Fifo *f = head; f; f = f->next) {
85 fifo_print_one(f);
86 }
87 }
88
89 void
90 config_print(Config *c)
91 {
92 debug(
93 "Config "
94 "{"
95 " interval = %d,"
96 " separator = %s,"
97 " fifo_count = %d,"
98 " total_width = %d,"
99 " fifos = ..."
100 " }\n",
101 c->interval,
102 c->separator,
103 c->fifo_count,
104 c->total_width
105 );
106 fifo_print_all(c->fifos);
107 }
108
109 int
110 is_pos_num(char *s)
111 {
112 while (*s != '\0')
113 if (!isdigit(*(s++)))
114 return 0;
115 return 1;
116 }
117
118 void
119 print_usage()
120 {
121 assert(argv0);
122 fprintf(
123 stderr,
124 "\n"
125 "Usage: %s [OPTION ...] SPEC [SPEC ...]\n"
126 "\n"
127 " SPEC = FILE_PATH DATA_WIDTH DATA_TTL\n"
128 " FILE_PATH = string\n"
129 " DATA_WIDTH = int (* (positive) number of characters *)\n"
130 " DATA_TTL = int (* (positive) number of seconds *)\n"
131 " OPTION = -i INTERVAL\n"
132 " | -s SEPARATOR\n"
133 " SEPARATOR = string\n"
134 " INTERVAL = int (* (positive) number of seconds *)\n"
135 "\n",
136 argv0
137 );
138 fprintf(
139 stderr,
140 "Example: %s -i 1 /dev/shm/khatus/khatus_sensor_x 4 10\n"
141 "\n",
142 argv0
143 );
144 }
145
146 void opts_parse_any(Config *, int, char *[], int); /* For mutually-recursive calls. */
147
148 void
149 parse_opts_opt_i(Config *cfg, int argc, char *argv[], int i)
150 {
151 if (i < argc) {
152 char *param = argv[i++];
153
154 if (is_pos_num(param)) {
155 cfg->interval = atoi(param);
156 opts_parse_any(cfg, argc, argv, i);
157 } else {
158 usage("Option -i parameter is invalid: \"%s\"\n", param);
159 }
160 } else {
161 usage("Option -i parameter is missing.\n");
162 }
163 }
164
165 void
166 parse_opts_opt_s(Config *cfg, int argc, char *argv[], int i)
167 {
168 if (i < argc) {
169 cfg->separator = calloc((strlen(argv[i]) + 1), sizeof(char));
170 strcpy(cfg->separator, argv[i]);
171 opts_parse_any(cfg, argc, argv, ++i);
172 } else {
173 usage("Option -s parameter is missing.\n");
174 }
175 }
176
177 void
178 parse_opts_opt(Config *cfg, int argc, char *argv[], int i)
179 {
180 switch (argv[i][1]) {
181 case 'i': parse_opts_opt_i(cfg, argc, argv, ++i); break; /* TODO: Generic set_int */
182 case 's': parse_opts_opt_s(cfg, argc, argv, ++i); break; /* TODO: Generic set_str */
183 case 'x': {
184 cfg->output_to_x_root_window = 1;
185 opts_parse_any(cfg, argc, argv, ++i);
186 break;
187 }
188 default : usage("Option \"%s\" is invalid\n", argv[i]);
189 }
190 }
191
192 void
193 parse_opts_spec(Config *cfg, int argc, char *argv[], int i)
194 {
195 if ((i + 3) > argc)
196 usage("[spec] Parameter(s) missing for fifo \"%s\".\n", argv[i]);
197
198 char *n = argv[i++];
199 char *w = argv[i++];
200 char *t = argv[i++];
201
202 if (!is_pos_num(w))
203 usage("[spec] Invalid width: \"%s\", for fifo \"%s\"\n", w, n);
204 if (!is_pos_num(t))
205 usage("[spec] Invalid TTL: \"%s\", for fifo \"%s\"\n", t, n);
206 Fifo *f = calloc(1, sizeof(struct Fifo));
207 if (f) {
208 f->name = n;
209 f->fd = -1;
210 f->width = atoi(w);
211 f->ttl = atoi(t);
212 f->last_read = 0;
213 f->pos = cfg->total_width;
214 f->next = cfg->fifos;
215
216 cfg->fifos = f;
217 cfg->total_width += f->width;
218 cfg->fifo_count++;
219 } else {
220 fatal("[memory] Allocation failure.");
221 }
222 opts_parse_any(cfg, argc, argv, i);
223 }
224
225 void
226 opts_parse_any(Config *cfg, int argc, char *argv[], int i)
227 {
228 if (i < argc) {
229 switch (argv[i][0]) {
230 case '-': parse_opts_opt(cfg, argc, argv, i); break;
231 default : parse_opts_spec(cfg, argc, argv, i);
232 }
233 }
234 }
235
236 void
237 opts_parse(Config *cfg, int argc, char *argv[])
238 {
239 opts_parse_any(cfg, argc, argv, 1);
240
241 Fifo *last = cfg->fifos;
242 cfg->fifos = NULL;
243 for (Fifo *f = last; f; ) {
244 Fifo *next = f->next;
245 f->next = cfg->fifos;
246 cfg->fifos = f;
247 f = next;
248 }
249 }
250
251 void
252 read_error(Fifo *f, char *buf)
253 {
254 char *b;
255 int i;
256
257 b = buf + f->pos;
258 /* Copy as much of the error message as possible.
259 * EXCLUDING the reminating \0. */
260 for (i = 0; i < errlen && i < f->width; i++)
261 b[i] = errmsg[i];
262 /* Any remaining slots: */
263 for (; i < f->width; i++)
264 b[i] = '_';
265 }
266
267 void
268 read_one(Fifo *f, char *buf)
269 {
270 ssize_t current;
271 ssize_t total;
272 char *b;
273 char c;
274
275 current = 0;
276 total = 0;
277 c = '\0';
278 b = buf + f->pos;
279 /* TODO: Could optimize here and only blank-out the remaining slots. */
280 memset(b, ' ', f->width);
281 while ((current = read(f->fd, &c, 1)) && c != '\n' && c != '\0' && total++ < f->width)
282 *b++ = c;
283 if (current == -1) {
284 error("Failed to read: \"%s\". Error: %s\n", f->name, strerror(errno));
285 read_error(f, buf);
286 }
287 /* TODO Record timestamp read */
288 close(f->fd);
289 f->fd = -1;
290 }
291
292 void
293 read_all(Config *cfg, char *buf)
294 {
295 fd_set fds;
296 int maxfd = -1;
297 int ready;
298 struct stat st;
299
300 FD_ZERO(&fds);
301 /* TODO: Check TTL */
302 for (Fifo *f = cfg->fifos; f; f = f->next) {
303 /* TODO: Create the FIFO if it doesn't already exist. */
304 if (lstat(f->name, &st) < 0) {
305 error("Cannot stat \"%s\". Error: %s\n", f->name, strerror(errno));
306 read_error(f, buf);
307 continue;
308 }
309 if (!(st.st_mode & S_IFIFO)) {
310 error("\"%s\" is not a FIFO\n", f->name);
311 read_error(f, buf);
312 continue;
313 }
314 debug("opening: %s\n", f->name);
315 if (f->fd < 0)
316 f->fd = open(f->name, O_RDONLY | O_NONBLOCK);
317 if (f->fd == -1) {
318 /* TODO: Consider backing off retries for failed fifos. */
319 error("Failed to open \"%s\"\n", f->name);
320 read_error(f, buf);
321 continue;
322 }
323 if (f->fd > maxfd)
324 maxfd = f->fd;
325 FD_SET(f->fd, &fds);
326 }
327 debug("selecting...\n");
328 ready = select(maxfd + 1, &fds, NULL, NULL, NULL);
329 debug("ready: %d\n", ready);
330 assert(ready != 0);
331 if (ready < 0)
332 fatal("%s", strerror(errno));
333 for (Fifo *f = cfg->fifos; f; f = f->next) {
334 if (FD_ISSET(f->fd, &fds)) {
335 debug("reading: %s\n", f->name);
336 read_one(f, buf);
337 }
338 }
339 }
340
341 int
342 main(int argc, char *argv[])
343 {
344 int width = 0;
345 int nfifos = 0;
346 int seplen = 0;
347 int prefix = 0;
348 int errors = 0;
349 char *buf;
350 Config cfg0 = defaults;
351 Config *cfg = &cfg0;
352 Display *display = NULL;
353 struct stat st;
354
355 argv0 = argv[0];
356
357 opts_parse(cfg, argc, argv);
358 debug("argv0 = %s\n", argv0);
359 config_print(cfg);
360 if (cfg->fifos == NULL)
361 usage("No fifo specs were given!\n");
362
363 /* 1st pass to check file existence and type */
364 for (Fifo *f = cfg->fifos; f; f = f->next) {
365 if (lstat(f->name, &st) < 0) {
366 error("Cannot stat \"%s\". Error: %s\n", f->name, strerror(errno));
367 errors++;
368 continue;
369 }
370 if (!(st.st_mode & S_IFIFO)) {
371 error("\"%s\" is not a FIFO\n", f->name);
372 errors++;
373 continue;
374 }
375 }
376 if (errors)
377 fatal("Encountered errors with the given file paths. See log.\n");
378
379 width = cfg->total_width;
380 seplen = strlen(cfg->separator);
381
382 /* 2nd pass to make space for separators */
383 for (Fifo *f = cfg->fifos; f; f = f->next) {
384 f->pos += prefix;
385 prefix += seplen;
386 nfifos++;
387 }
388 width += (seplen * (nfifos - 1));
389 buf = calloc(1, width + 1);
390 if (buf == NULL)
391 fatal("[memory] Failed to allocate buffer of %d bytes", width);
392 memset(buf, ' ', width);
393 buf[width] = '\0';
394 /* 3rd pass to set the separators */
395 for (Fifo *f = cfg->fifos; f; f = f->next) {
396 if (f->pos) { /* Skip the first, left-most */
397 /* Copying only seplen ensures we omit the '\0' byte. */
398 strncpy(buf + (f->pos - seplen), cfg->separator, seplen);
399 }
400 }
401
402 if (cfg->output_to_x_root_window && !(display = XOpenDisplay(NULL)))
403 fatal("XOpenDisplay failed with: %p\n", display);
404 /* TODO: nanosleep and nano time diff */
405 /* TODO: Handle signals */
406 for (;;) {
407 /* TODO: Check TTL and maybe blank-out */
408 /* TODO: How to trigger TTL check? On select? Alarm signal? */
409 /* TODO: Set timeout on read_all based on diff of last time of
410 * read_all and desired time of next TTL check.
411 * */
412 read_all(cfg, buf);
413 if (cfg->output_to_x_root_window) {
414 if (XStoreName(display, DefaultRootWindow(display), buf) < 0)
415 fatal("XStoreName failed.\n");
416 XFlush(display);
417 } else {
418 puts(buf);
419 fflush(stdout);
420 }
421 }
422
423 return EXIT_SUCCESS;
424 }
This page took 0.086368 seconds and 4 git commands to generate.