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