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