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