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