]> git.sur5r.net Git - i3/i3status/blob - i3status.c
Merge pull request #17 from chrko/format_down
[i3/i3status] / i3status.c
1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * i3status – Generates a status line for dzen2 or xmobar
5  *
6  * Copyright © 2008-2012 Michael Stapelberg and contributors
7  * Copyright © 2009 Thorsten Toepper <atsutane at freethoughts dot de>
8  * Copyright © 2010 Axel Wagner <mail at merovius dot de>
9  * Copyright © 2010 Fernando Tarlá Cardoso Lemos <fernandotcl at gmail dot com>
10  *
11  * See file LICENSE for license information.
12  *
13  */
14 #include <limits.h>
15 #include <string.h>
16 #include <stdio.h>
17 #include <stdbool.h>
18 #include <unistd.h>
19 #include <stdlib.h>
20 #include <sys/socket.h>
21 #include <netinet/in.h>
22 #include <getopt.h>
23 #include <signal.h>
24 #include <confuse.h>
25 #include <glob.h>
26 #include <sys/stat.h>
27 #include <sys/types.h>
28 #include <time.h>
29 #include <sys/time.h>
30 #include <locale.h>
31
32 #include <yajl/yajl_gen.h>
33 #include <yajl/yajl_version.h>
34
35 #include "i3status.h"
36
37 #define exit_if_null(pointer, ...) \
38     {                              \
39         if (pointer == NULL)       \
40             die(__VA_ARGS__);      \
41     }
42
43 #define CFG_CUSTOM_ALIGN_OPT \
44     CFG_STR_CB("align", NULL, CFGF_NONE, parse_align)
45
46 #define CFG_COLOR_OPTS(good, degraded, bad)             \
47     CFG_STR("color_good", good, CFGF_NONE),             \
48         CFG_STR("color_degraded", degraded, CFGF_NONE), \
49         CFG_STR("color_bad", bad, CFGF_NONE)
50
51 #define CFG_CUSTOM_COLOR_OPTS CFG_COLOR_OPTS(NULL, NULL, NULL)
52
53 #define CFG_CUSTOM_MIN_WIDTH_OPT \
54     CFG_PTR_CB("min_width", NULL, CFGF_NONE, parse_min_width, free)
55
56 /* socket file descriptor for general purposes */
57 int general_socket;
58
59 static bool exit_upon_signal = false;
60
61 cfg_t *cfg, *cfg_general, *cfg_section;
62
63 void **cur_instance;
64
65 /*
66  * Set the exit_upon_signal flag, because one cannot do anything in a safe
67  * manner in a signal handler (e.g. fprintf, which we really want to do for
68  * debugging purposes), see
69  * https://www.securecoding.cert.org/confluence/display/seccode/SIG30-C.+Call+only+asynchronous-safe+functions+within+signal+handlers
70  *
71  */
72 void fatalsig(int signum) {
73     exit_upon_signal = true;
74 }
75
76 /*
77  * Do nothing upon SIGUSR1. Running this signal handler will nevertheless
78  * interrupt nanosleep() so that i3status immediately generates new output.
79  *
80  */
81 void sigusr1(int signum) {
82 }
83
84 /*
85  * Checks if the given path exists by calling stat().
86  *
87  */
88 static bool path_exists(const char *path) {
89     struct stat buf;
90     return (stat(path, &buf) == 0);
91 }
92
93 static void *scalloc(size_t size) {
94     void *result = calloc(size, 1);
95     exit_if_null(result, "Error: out of memory (calloc(%zd))\n", size);
96     return result;
97 }
98
99 static char *sstrdup(const char *str) {
100     char *result = strdup(str);
101     exit_if_null(result, "Error: out of memory (strdup())\n");
102     return result;
103 }
104
105 /*
106  * Parses the "align" module option (to validate input).
107  */
108 static int parse_align(cfg_t *context, cfg_opt_t *option, const char *value, void *result) {
109     if (strcasecmp(value, "left") != 0 && strcasecmp(value, "right") != 0 && strcasecmp(value, "center") != 0)
110         die("Invalid alignment attribute found in section %s, line %d: \"%s\"\n"
111             "Valid attributes are: left, center, right\n",
112             context->name, context->line, value);
113
114     const char **cresult = result;
115     *cresult = value;
116
117     return 0;
118 }
119
120 /*
121  * Parses the "min_width" module option whose value can either be a string or an integer.
122  */
123 static int parse_min_width(cfg_t *context, cfg_opt_t *option, const char *value, void *result) {
124     char *end;
125     long num = strtol(value, &end, 10);
126
127     if (num < 0)
128         die("Invalid min_width attribute found in section %s, line %d: %d\n"
129             "Expected positive integer or string\n",
130             context->name, context->line, num);
131     else if (num == LONG_MIN || num == LONG_MAX || (end && *end != '\0'))
132         num = 0;
133
134     if (strlen(value) == 0)
135         die("Empty min_width attribute found in section %s, line %d\n"
136             "Expected positive integer or non-empty string\n",
137             context->name, context->line);
138
139     if (strcmp(value, "0") == 0)
140         die("Invalid min_width attribute found in section %s, line %d: \"%s\"\n"
141             "Expected positive integer or string\n",
142             context->name, context->line, value);
143
144     struct min_width *parsed = scalloc(sizeof(struct min_width));
145     parsed->num = num;
146
147     /* num is preferred, but if it’s 0 (i.e. not valid), store and use
148      * the raw string value */
149     if (num == 0)
150         parsed->str = sstrdup(value);
151
152     struct min_width **cresult = result;
153     *cresult = parsed;
154
155     return 0;
156 }
157
158 /*
159  * Validates a color in "#RRGGBB" format
160  *
161  */
162 static int valid_color(const char *value) {
163     if (strlen(value) != 7)
164         return 0;
165     if (value[0] != '#')
166         return 0;
167     for (int i = 1; i < 7; ++i) {
168         if (value[i] >= '0' && value[i] <= '9')
169             continue;
170         if (value[i] >= 'a' && value[i] <= 'f')
171             continue;
172         if (value[i] >= 'A' && value[i] <= 'F')
173             continue;
174         return 0;
175     }
176     return 1;
177 }
178
179 /*
180  * This function resolves ~ in pathnames.
181  * It may resolve wildcards in the first part of the path, but if no match
182  * or multiple matches are found, it just returns a copy of path as given.
183  *
184  */
185 static char *resolve_tilde(const char *path) {
186     static glob_t globbuf;
187     char *head, *tail, *result = NULL;
188
189     tail = strchr(path, '/');
190     head = strndup(path, tail ? (size_t)(tail - path) : strlen(path));
191
192     int res = glob(head, GLOB_TILDE, NULL, &globbuf);
193     free(head);
194     /* no match, or many wildcard matches are bad */
195     if (res == GLOB_NOMATCH || globbuf.gl_pathc != 1)
196         result = sstrdup(path);
197     else if (res != 0) {
198         die("glob() failed");
199     } else {
200         head = globbuf.gl_pathv[0];
201         result = scalloc(strlen(head) + (tail ? strlen(tail) : 0) + 1);
202         strncpy(result, head, strlen(head));
203         if (tail)
204             strncat(result, tail, strlen(tail));
205     }
206     globfree(&globbuf);
207
208     return result;
209 }
210
211 static char *get_config_path(void) {
212     char *xdg_config_home, *xdg_config_dirs, *config_path;
213
214     /* 1: check the traditional path under the home directory */
215     config_path = resolve_tilde("~/.i3status.conf");
216     if (path_exists(config_path))
217         return config_path;
218
219     /* 2: check for $XDG_CONFIG_HOME/i3status/config */
220     if ((xdg_config_home = getenv("XDG_CONFIG_HOME")) == NULL)
221         xdg_config_home = "~/.config";
222
223     xdg_config_home = resolve_tilde(xdg_config_home);
224     if (asprintf(&config_path, "%s/i3status/config", xdg_config_home) == -1)
225         die("asprintf() failed");
226     free(xdg_config_home);
227
228     if (path_exists(config_path))
229         return config_path;
230     free(config_path);
231
232     /* 3: check the traditional path under /etc */
233     config_path = SYSCONFDIR "/i3status.conf";
234     if (path_exists(config_path))
235         return sstrdup(config_path);
236
237     /* 4: check for $XDG_CONFIG_DIRS/i3status/config */
238     if ((xdg_config_dirs = getenv("XDG_CONFIG_DIRS")) == NULL)
239         xdg_config_dirs = "/etc/xdg";
240
241     char *buf = strdup(xdg_config_dirs);
242     char *tok = strtok(buf, ":");
243     while (tok != NULL) {
244         tok = resolve_tilde(tok);
245         if (asprintf(&config_path, "%s/i3status/config", tok) == -1)
246             die("asprintf() failed");
247         free(tok);
248         if (path_exists(config_path)) {
249             free(buf);
250             return config_path;
251         }
252         free(config_path);
253         tok = strtok(NULL, ":");
254     }
255     free(buf);
256
257     die("Unable to find the configuration file (looked at "
258         "~/.i3status.conf, $XDG_CONFIG_HOME/i3status/config, "
259         "/etc/i3status.conf and $XDG_CONFIG_DIRS/i3status/config)");
260     return NULL;
261 }
262
263 /*
264  * Returns the default separator to use if no custom separator has been specified.
265  */
266 static char *get_default_separator() {
267     if (output_format == O_DZEN2)
268         return "^p(5;-2)^ro(2)^p()^p(5)";
269     if (output_format == O_I3BAR)
270         // anything besides the empty string indicates that the default separator should be used
271         return "default";
272     return " | ";
273 }
274
275 int main(int argc, char *argv[]) {
276     unsigned int j;
277
278     cfg_opt_t general_opts[] = {
279         CFG_STR("output_format", "auto", CFGF_NONE),
280         CFG_BOOL("colors", 1, CFGF_NONE),
281         CFG_STR("separator", "default", CFGF_NONE),
282         CFG_STR("color_separator", "#333333", CFGF_NONE),
283         CFG_INT("interval", 1, CFGF_NONE),
284         CFG_COLOR_OPTS("#00FF00", "#FFFF00", "#FF0000"),
285         CFG_END()};
286
287     cfg_opt_t run_watch_opts[] = {
288         CFG_STR("pidfile", NULL, CFGF_NONE),
289         CFG_STR("format", "%title: %status", CFGF_NONE),
290         CFG_STR("format_down", NULL, CFGF_NONE),
291         CFG_CUSTOM_ALIGN_OPT,
292         CFG_CUSTOM_COLOR_OPTS,
293         CFG_CUSTOM_MIN_WIDTH_OPT,
294         CFG_END()};
295
296     cfg_opt_t path_exists_opts[] = {
297         CFG_STR("path", NULL, CFGF_NONE),
298         CFG_STR("format", "%title: %status", CFGF_NONE),
299         CFG_STR("format_down", NULL, CFGF_NONE),
300         CFG_CUSTOM_ALIGN_OPT,
301         CFG_CUSTOM_COLOR_OPTS,
302         CFG_CUSTOM_MIN_WIDTH_OPT,
303         CFG_END()};
304
305     cfg_opt_t wireless_opts[] = {
306         CFG_STR("format_up", "W: (%quality at %essid, %bitrate) %ip", CFGF_NONE),
307         CFG_STR("format_down", "W: down", CFGF_NONE),
308         CFG_CUSTOM_ALIGN_OPT,
309         CFG_CUSTOM_COLOR_OPTS,
310         CFG_CUSTOM_MIN_WIDTH_OPT,
311         CFG_END()};
312
313     cfg_opt_t ethernet_opts[] = {
314         CFG_STR("format_up", "E: %ip (%speed)", CFGF_NONE),
315         CFG_STR("format_down", "E: down", CFGF_NONE),
316         CFG_CUSTOM_ALIGN_OPT,
317         CFG_CUSTOM_COLOR_OPTS,
318         CFG_CUSTOM_MIN_WIDTH_OPT,
319         CFG_END()};
320
321     cfg_opt_t ipv6_opts[] = {
322         CFG_STR("format_up", "%ip", CFGF_NONE),
323         CFG_STR("format_down", "no IPv6", CFGF_NONE),
324         CFG_CUSTOM_ALIGN_OPT,
325         CFG_CUSTOM_COLOR_OPTS,
326         CFG_CUSTOM_MIN_WIDTH_OPT,
327         CFG_END()};
328
329     cfg_opt_t battery_opts[] = {
330         CFG_STR("format", "%status %percentage %remaining", CFGF_NONE),
331         CFG_STR("format_down", "No battery", CFGF_NONE),
332         CFG_STR("status_chr", "CHR", CFGF_NONE),
333         CFG_STR("status_bat", "BAT", CFGF_NONE),
334         CFG_STR("status_full", "FULL", CFGF_NONE),
335         CFG_STR("path", "/sys/class/power_supply/BAT%d/uevent", CFGF_NONE),
336         CFG_INT("low_threshold", 30, CFGF_NONE),
337         CFG_STR("threshold_type", "time", CFGF_NONE),
338         CFG_BOOL("last_full_capacity", false, CFGF_NONE),
339         CFG_BOOL("integer_battery_capacity", false, CFGF_NONE),
340         CFG_BOOL("hide_seconds", false, CFGF_NONE),
341         CFG_CUSTOM_ALIGN_OPT,
342         CFG_CUSTOM_COLOR_OPTS,
343         CFG_CUSTOM_MIN_WIDTH_OPT,
344         CFG_END()};
345
346     cfg_opt_t time_opts[] = {
347         CFG_STR("format", "%Y-%m-%d %H:%M:%S", CFGF_NONE),
348         CFG_CUSTOM_ALIGN_OPT,
349         CFG_CUSTOM_MIN_WIDTH_OPT,
350         CFG_END()};
351
352     cfg_opt_t tztime_opts[] = {
353         CFG_STR("format", "%Y-%m-%d %H:%M:%S %Z", CFGF_NONE),
354         CFG_STR("timezone", "", CFGF_NONE),
355         CFG_CUSTOM_ALIGN_OPT,
356         CFG_CUSTOM_MIN_WIDTH_OPT,
357         CFG_END()};
358
359     cfg_opt_t ddate_opts[] = {
360         CFG_STR("format", "%{%a, %b %d%}, %Y%N - %H", CFGF_NONE),
361         CFG_CUSTOM_ALIGN_OPT,
362         CFG_CUSTOM_MIN_WIDTH_OPT,
363         CFG_END()};
364
365     cfg_opt_t load_opts[] = {
366         CFG_STR("format", "%1min %5min %15min", CFGF_NONE),
367         CFG_FLOAT("max_threshold", 5, CFGF_NONE),
368         CFG_CUSTOM_ALIGN_OPT,
369         CFG_CUSTOM_COLOR_OPTS,
370         CFG_CUSTOM_MIN_WIDTH_OPT,
371         CFG_END()};
372
373     cfg_opt_t usage_opts[] = {
374         CFG_STR("format", "%usage", CFGF_NONE),
375         CFG_CUSTOM_ALIGN_OPT,
376         CFG_CUSTOM_MIN_WIDTH_OPT,
377         CFG_END()};
378
379     cfg_opt_t temp_opts[] = {
380         CFG_STR("format", "%degrees C", CFGF_NONE),
381         CFG_STR("path", NULL, CFGF_NONE),
382         CFG_INT("max_threshold", 75, CFGF_NONE),
383         CFG_CUSTOM_ALIGN_OPT,
384         CFG_CUSTOM_COLOR_OPTS,
385         CFG_CUSTOM_MIN_WIDTH_OPT,
386         CFG_END()};
387
388     cfg_opt_t disk_opts[] = {
389         CFG_STR("format", "%free", CFGF_NONE),
390         CFG_STR("format_not_mounted", NULL, CFGF_NONE),
391         CFG_STR("prefix_type", "binary", CFGF_NONE),
392         CFG_STR("threshold_type", "percentage_avail", CFGF_NONE),
393         CFG_FLOAT("low_threshold", 0, CFGF_NONE),
394         CFG_CUSTOM_ALIGN_OPT,
395         CFG_CUSTOM_COLOR_OPTS,
396         CFG_CUSTOM_MIN_WIDTH_OPT,
397         CFG_END()};
398
399     cfg_opt_t volume_opts[] = {
400         CFG_STR("format", "♪: %volume", CFGF_NONE),
401         CFG_STR("format_muted", "♪: 0%%", CFGF_NONE),
402         CFG_STR("device", "default", CFGF_NONE),
403         CFG_STR("mixer", "Master", CFGF_NONE),
404         CFG_INT("mixer_idx", 0, CFGF_NONE),
405         CFG_CUSTOM_ALIGN_OPT,
406         CFG_CUSTOM_COLOR_OPTS,
407         CFG_CUSTOM_MIN_WIDTH_OPT,
408         CFG_END()};
409
410     cfg_opt_t opts[] = {
411         CFG_STR_LIST("order", "{}", CFGF_NONE),
412         CFG_SEC("general", general_opts, CFGF_NONE),
413         CFG_SEC("run_watch", run_watch_opts, CFGF_TITLE | CFGF_MULTI),
414         CFG_SEC("path_exists", path_exists_opts, CFGF_TITLE | CFGF_MULTI),
415         CFG_SEC("wireless", wireless_opts, CFGF_TITLE | CFGF_MULTI),
416         CFG_SEC("ethernet", ethernet_opts, CFGF_TITLE | CFGF_MULTI),
417         CFG_SEC("battery", battery_opts, CFGF_TITLE | CFGF_MULTI),
418         CFG_SEC("cpu_temperature", temp_opts, CFGF_TITLE | CFGF_MULTI),
419         CFG_SEC("disk", disk_opts, CFGF_TITLE | CFGF_MULTI),
420         CFG_SEC("volume", volume_opts, CFGF_TITLE | CFGF_MULTI),
421         CFG_SEC("ipv6", ipv6_opts, CFGF_NONE),
422         CFG_SEC("time", time_opts, CFGF_NONE),
423         CFG_SEC("tztime", tztime_opts, CFGF_TITLE | CFGF_MULTI),
424         CFG_SEC("ddate", ddate_opts, CFGF_NONE),
425         CFG_SEC("load", load_opts, CFGF_NONE),
426         CFG_SEC("cpu_usage", usage_opts, CFGF_NONE),
427         CFG_END()};
428
429     char *configfile = NULL;
430     int o, option_index = 0;
431     struct option long_options[] = {
432         {"config", required_argument, 0, 'c'},
433         {"help", no_argument, 0, 'h'},
434         {"version", no_argument, 0, 'v'},
435         {0, 0, 0, 0}};
436
437     struct sigaction action;
438     memset(&action, 0, sizeof(struct sigaction));
439     action.sa_handler = fatalsig;
440
441     /* Exit upon SIGPIPE because when we have nowhere to write to, gathering system
442      * information is pointless. Also exit explicitly on SIGTERM and SIGINT because
443      * only this will trigger a reset of the cursor in the terminal output-format.
444      */
445     sigaction(SIGPIPE, &action, NULL);
446     sigaction(SIGTERM, &action, NULL);
447     sigaction(SIGINT, &action, NULL);
448
449     memset(&action, 0, sizeof(struct sigaction));
450     action.sa_handler = sigusr1;
451     sigaction(SIGUSR1, &action, NULL);
452
453     if (setlocale(LC_ALL, "") == NULL)
454         die("Could not set locale. Please make sure all your LC_* / LANG settings are correct.");
455
456     while ((o = getopt_long(argc, argv, "c:hv", long_options, &option_index)) != -1)
457         if ((char)o == 'c')
458             configfile = optarg;
459         else if ((char)o == 'h') {
460             printf("i3status " VERSION " © 2008-2012 Michael Stapelberg and contributors\n"
461                    "Syntax: %s [-c <configfile>] [-h] [-v]\n",
462                    argv[0]);
463             return 0;
464         } else if ((char)o == 'v') {
465             printf("i3status " VERSION " © 2008-2012 Michael Stapelberg and contributors\n");
466             return 0;
467         }
468
469     if (configfile == NULL)
470         configfile = get_config_path();
471
472     cfg = cfg_init(opts, CFGF_NOCASE);
473     if (cfg_parse(cfg, configfile) == CFG_PARSE_ERROR)
474         return EXIT_FAILURE;
475
476     if (cfg_size(cfg, "order") == 0)
477         die("Your 'order' array is empty. Please fix your config.\n");
478
479     cfg_general = cfg_getsec(cfg, "general");
480     if (cfg_general == NULL)
481         die("Could not get section \"general\"\n");
482
483     char *output_str = cfg_getstr(cfg_general, "output_format");
484     if (strcasecmp(output_str, "auto") == 0) {
485         fprintf(stderr, "i3status: trying to auto-detect output_format setting\n");
486         output_str = auto_detect_format();
487         if (!output_str) {
488             output_str = "none";
489             fprintf(stderr, "i3status: falling back to \"none\"\n");
490         } else {
491             fprintf(stderr, "i3status: auto-detected \"%s\"\n", output_str);
492         }
493     }
494
495     if (strcasecmp(output_str, "dzen2") == 0)
496         output_format = O_DZEN2;
497     else if (strcasecmp(output_str, "xmobar") == 0)
498         output_format = O_XMOBAR;
499     else if (strcasecmp(output_str, "i3bar") == 0)
500         output_format = O_I3BAR;
501     else if (strcasecmp(output_str, "term") == 0)
502         output_format = O_TERM;
503     else if (strcasecmp(output_str, "none") == 0)
504         output_format = O_NONE;
505     else
506         die("Unknown output format: \"%s\"\n", output_str);
507
508     const char *separator = cfg_getstr(cfg_general, "separator");
509
510     // if no custom separator has been provided, use the default one
511     if (strcasecmp(separator, "default") == 0)
512         separator = get_default_separator();
513
514     if (!valid_color(cfg_getstr(cfg_general, "color_good")) || !valid_color(cfg_getstr(cfg_general, "color_degraded")) || !valid_color(cfg_getstr(cfg_general, "color_bad")) || !valid_color(cfg_getstr(cfg_general, "color_separator")))
515         die("Bad color format");
516
517 #if YAJL_MAJOR >= 2
518     yajl_gen json_gen = yajl_gen_alloc(NULL);
519 #else
520     yajl_gen json_gen = yajl_gen_alloc(NULL, NULL);
521 #endif
522
523     if (output_format == O_I3BAR) {
524         /* Initialize the i3bar protocol. See i3/docs/i3bar-protocol
525          * for details. */
526         printf("{\"version\":1}\n[\n");
527         fflush(stdout);
528         yajl_gen_array_open(json_gen);
529         yajl_gen_clear(json_gen);
530     }
531     if (output_format == O_TERM) {
532         /* Save the cursor-position and hide the cursor */
533         printf("\033[s\033[?25l");
534         /* Undo at exit */
535         atexit(&reset_cursor);
536     }
537
538     if ((general_socket = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
539         die("Could not create socket\n");
540
541     int interval = cfg_getint(cfg_general, "interval");
542
543     /* One memory page which each plugin can use to buffer output.
544      * Even though it’s unclean, we just assume that the user will not
545      * specify a format string which expands to something longer than 4096
546      * bytes — given that the output of i3status is used to display
547      * information on screen, more than 1024 characters for the full line
548      * (!), not individual plugins, seem very unlikely. */
549     char buffer[4096];
550
551     void **per_instance = calloc(cfg_size(cfg, "order"), sizeof(*per_instance));
552
553     while (1) {
554         if (exit_upon_signal) {
555             fprintf(stderr, "Exiting due to signal.\n");
556             exit(1);
557         }
558         struct timeval tv;
559         gettimeofday(&tv, NULL);
560         if (output_format == O_I3BAR)
561             yajl_gen_array_open(json_gen);
562         else if (output_format == O_TERM)
563             /* Restore the cursor-position, clear line */
564             printf("\033[u\033[K");
565         for (j = 0; j < cfg_size(cfg, "order"); j++) {
566             cur_instance = per_instance + j;
567             if (j > 0)
568                 print_separator(separator);
569
570             const char *current = cfg_getnstr(cfg, "order", j);
571
572             CASE_SEC("ipv6") {
573                 SEC_OPEN_MAP("ipv6");
574                 print_ipv6_info(json_gen, buffer, cfg_getstr(sec, "format_up"), cfg_getstr(sec, "format_down"));
575                 SEC_CLOSE_MAP;
576             }
577
578             CASE_SEC_TITLE("wireless") {
579                 SEC_OPEN_MAP("wireless");
580                 const char *interface = NULL;
581                 if (strcasecmp(title, "_first_") == 0)
582                     interface = first_eth_interface(NET_TYPE_WIRELESS);
583                 if (interface == NULL)
584                     interface = title;
585                 print_wireless_info(json_gen, buffer, interface, cfg_getstr(sec, "format_up"), cfg_getstr(sec, "format_down"));
586                 SEC_CLOSE_MAP;
587             }
588
589             CASE_SEC_TITLE("ethernet") {
590                 SEC_OPEN_MAP("ethernet");
591                 const char *interface = NULL;
592                 if (strcasecmp(title, "_first_") == 0)
593                     interface = first_eth_interface(NET_TYPE_ETHERNET);
594                 if (interface == NULL)
595                     interface = title;
596                 print_eth_info(json_gen, buffer, interface, cfg_getstr(sec, "format_up"), cfg_getstr(sec, "format_down"));
597                 SEC_CLOSE_MAP;
598             }
599
600             CASE_SEC_TITLE("battery") {
601                 SEC_OPEN_MAP("battery");
602                 print_battery_info(json_gen, buffer, atoi(title), cfg_getstr(sec, "path"), cfg_getstr(sec, "format"), cfg_getstr(sec, "format_down"), cfg_getstr(sec, "status_chr"), cfg_getstr(sec, "status_bat"), cfg_getstr(sec, "status_full"), cfg_getint(sec, "low_threshold"), cfg_getstr(sec, "threshold_type"), cfg_getbool(sec, "last_full_capacity"), cfg_getbool(sec, "integer_battery_capacity"), cfg_getbool(sec, "hide_seconds"));
603                 SEC_CLOSE_MAP;
604             }
605
606             CASE_SEC_TITLE("run_watch") {
607                 SEC_OPEN_MAP("run_watch");
608                 print_run_watch(json_gen, buffer, title, cfg_getstr(sec, "pidfile"), cfg_getstr(sec, "format"), cfg_getstr(sec, "format_down"));
609                 SEC_CLOSE_MAP;
610             }
611
612             CASE_SEC_TITLE("path_exists") {
613                 SEC_OPEN_MAP("path_exists");
614                 print_path_exists(json_gen, buffer, title, cfg_getstr(sec, "path"), cfg_getstr(sec, "format"), cfg_getstr(sec, "format_down"));
615                 SEC_CLOSE_MAP;
616             }
617
618             CASE_SEC_TITLE("disk") {
619                 SEC_OPEN_MAP("disk_info");
620                 print_disk_info(json_gen, buffer, title, cfg_getstr(sec, "format"), cfg_getstr(sec, "format_not_mounted"), cfg_getstr(sec, "prefix_type"), cfg_getstr(sec, "threshold_type"), cfg_getfloat(sec, "low_threshold"));
621                 SEC_CLOSE_MAP;
622             }
623
624             CASE_SEC("load") {
625                 SEC_OPEN_MAP("load");
626                 print_load(json_gen, buffer, cfg_getstr(sec, "format"), cfg_getfloat(sec, "max_threshold"));
627                 SEC_CLOSE_MAP;
628             }
629
630             CASE_SEC("time") {
631                 SEC_OPEN_MAP("time");
632                 print_time(json_gen, buffer, NULL, cfg_getstr(sec, "format"), NULL, tv.tv_sec);
633                 SEC_CLOSE_MAP;
634             }
635
636             CASE_SEC_TITLE("tztime") {
637                 SEC_OPEN_MAP("tztime");
638                 print_time(json_gen, buffer, title, cfg_getstr(sec, "format"), cfg_getstr(sec, "timezone"), tv.tv_sec);
639                 SEC_CLOSE_MAP;
640             }
641
642             CASE_SEC("ddate") {
643                 SEC_OPEN_MAP("ddate");
644                 print_ddate(json_gen, buffer, cfg_getstr(sec, "format"), tv.tv_sec);
645                 SEC_CLOSE_MAP;
646             }
647
648             CASE_SEC_TITLE("volume") {
649                 SEC_OPEN_MAP("volume");
650                 print_volume(json_gen, buffer, cfg_getstr(sec, "format"),
651                              cfg_getstr(sec, "format_muted"),
652                              cfg_getstr(sec, "device"),
653                              cfg_getstr(sec, "mixer"),
654                              cfg_getint(sec, "mixer_idx"));
655                 SEC_CLOSE_MAP;
656             }
657
658             CASE_SEC_TITLE("cpu_temperature") {
659                 SEC_OPEN_MAP("cpu_temperature");
660                 print_cpu_temperature_info(json_gen, buffer, atoi(title), cfg_getstr(sec, "path"), cfg_getstr(sec, "format"), cfg_getint(sec, "max_threshold"));
661                 SEC_CLOSE_MAP;
662             }
663
664             CASE_SEC("cpu_usage") {
665                 SEC_OPEN_MAP("cpu_usage");
666                 print_cpu_usage(json_gen, buffer, cfg_getstr(sec, "format"));
667                 SEC_CLOSE_MAP;
668             }
669         }
670         if (output_format == O_I3BAR) {
671             yajl_gen_array_close(json_gen);
672             const unsigned char *buf;
673 #if YAJL_MAJOR >= 2
674             size_t len;
675 #else
676             unsigned int len;
677 #endif
678             yajl_gen_get_buf(json_gen, &buf, &len);
679             write(STDOUT_FILENO, buf, len);
680             yajl_gen_clear(json_gen);
681         }
682
683         printf("\n");
684         fflush(stdout);
685
686         /* To provide updates on every full second (as good as possible)
687          * we don’t use sleep(interval) but we sleep until the next
688          * second (with microsecond precision) plus (interval-1)
689          * seconds. We also align to 60 seconds modulo interval such
690          * that we start with :00 on every new minute. */
691         struct timeval current_timeval;
692         gettimeofday(&current_timeval, NULL);
693         struct timespec ts = {interval - 1 - (current_timeval.tv_sec % interval), (10e5 - current_timeval.tv_usec) * 1000};
694         nanosleep(&ts, NULL);
695     }
696 }