]> git.sur5r.net Git - i3/i3status/blob - i3status.c
i3status - More temperature related fixes for OpenBSD, and a general feature
[i3/i3status] / i3status.c
1 /*
2  * vim:ts=8:expandtab
3  *
4  * i3status – Generates a status line for dzen2 or xmobar
5  *
6  * Copyright © 2008-2012 Michael Stapelberg and contributors
7  * Copyright © 2009 Thorsten Toepper <atsutane at freethoughts dot de>
8  * Copyright © 2010 Axel Wagner <mail at merovius dot de>
9  * Copyright © 2010 Fernando Tarlá Cardoso Lemos <fernandotcl at gmail dot com>
10  *
11  * See file LICENSE for license information.
12  *
13  */
14 #include <string.h>
15 #include <stdio.h>
16 #include <stdbool.h>
17 #include <unistd.h>
18 #include <stdlib.h>
19 #include <sys/socket.h>
20 #include <netinet/in.h>
21 #include <getopt.h>
22 #include <signal.h>
23 #include <confuse.h>
24 #include <glob.h>
25 #include <sys/stat.h>
26 #include <sys/types.h>
27 #include <time.h>
28 #include <sys/time.h>
29 #include <locale.h>
30
31 #include <yajl/yajl_gen.h>
32 #include <yajl/yajl_version.h>
33
34 #include "i3status.h"
35
36 #define exit_if_null(pointer, ...) { if (pointer == NULL) die(__VA_ARGS__); }
37
38 /* socket file descriptor for general purposes */
39 int general_socket;
40
41 cfg_t *cfg, *cfg_general;
42
43 /*
44  * Exit upon SIGPIPE because when we have nowhere to write to, gathering
45  * system information is pointless.
46  *
47  */
48 void sigpipe(int signum) {
49         fprintf(stderr, "Received SIGPIPE, exiting\n");
50         exit(1);
51 }
52
53 /*
54  * Checks if the given path exists by calling stat().
55  *
56  */
57 static bool path_exists(const char *path) {
58         struct stat buf;
59         return (stat(path, &buf) == 0);
60 }
61
62 static void *scalloc(size_t size) {
63         void *result = calloc(size, 1);
64         exit_if_null(result, "Error: out of memory (calloc(%zd))\n", size);
65         return result;
66 }
67
68 static char *sstrdup(const char *str) {
69         char *result = strdup(str);
70         exit_if_null(result, "Error: out of memory (strdup())\n");
71         return result;
72 }
73
74
75 /*
76  * Validates a color in "#RRGGBB" format
77  *
78  */
79 static int valid_color(const char *value)
80 {
81         if (strlen(value) != 7) return 0;
82         if (value[0] != '#') return 0;
83         for (int i = 1; i < 7; ++i) {
84                 if (value[i] >= '0' && value[i] <= '9') continue;
85                 if (value[i] >= 'a' && value[i] <= 'f') continue;
86                 if (value[i] >= 'A' && value[i] <= 'F') continue;
87                 return 0;
88         }
89         return 1;
90 }
91
92 /*
93  * This function resolves ~ in pathnames.
94  * It may resolve wildcards in the first part of the path, but if no match
95  * or multiple matches are found, it just returns a copy of path as given.
96  *
97  */
98 static char *resolve_tilde(const char *path) {
99         static glob_t globbuf;
100         char *head, *tail, *result = NULL;
101
102         tail = strchr(path, '/');
103         head = strndup(path, tail ? (size_t)(tail - path) : strlen(path));
104
105         int res = glob(head, GLOB_TILDE, NULL, &globbuf);
106         free(head);
107         /* no match, or many wildcard matches are bad */
108         if (res == GLOB_NOMATCH || globbuf.gl_pathc != 1)
109                 result = sstrdup(path);
110         else if (res != 0) {
111                 die("glob() failed");
112         } else {
113                 head = globbuf.gl_pathv[0];
114                 result = scalloc(strlen(head) + (tail ? strlen(tail) : 0) + 1);
115                 strncpy(result, head, strlen(head));
116                 if (tail)
117                         strncat(result, tail, strlen(tail));
118         }
119         globfree(&globbuf);
120
121         return result;
122 }
123
124 static char *get_config_path(void) {
125         char *xdg_config_home, *xdg_config_dirs, *config_path;
126
127         /* 1: check the traditional path under the home directory */
128         config_path = resolve_tilde("~/.i3status.conf");
129         if (path_exists(config_path))
130                 return config_path;
131
132         /* 2: check for $XDG_CONFIG_HOME/i3status/config */
133         if ((xdg_config_home = getenv("XDG_CONFIG_HOME")) == NULL)
134                 xdg_config_home = "~/.config";
135
136         xdg_config_home = resolve_tilde(xdg_config_home);
137         if (asprintf(&config_path, "%s/i3status/config", xdg_config_home) == -1)
138                 die("asprintf() failed");
139         free(xdg_config_home);
140
141         if (path_exists(config_path))
142                 return config_path;
143         free(config_path);
144
145         /* 3: check the traditional path under /etc */
146         config_path = SYSCONFDIR "/i3status.conf";
147         if (path_exists(config_path))
148             return sstrdup(config_path);
149
150         /* 4: check for $XDG_CONFIG_DIRS/i3status/config */
151         if ((xdg_config_dirs = getenv("XDG_CONFIG_DIRS")) == NULL)
152                 xdg_config_dirs = "/etc/xdg";
153
154         char *buf = strdup(xdg_config_dirs);
155         char *tok = strtok(buf, ":");
156         while (tok != NULL) {
157                 tok = resolve_tilde(tok);
158                 if (asprintf(&config_path, "%s/i3status/config", tok) == -1)
159                         die("asprintf() failed");
160                 free(tok);
161                 if (path_exists(config_path)) {
162                         free(buf);
163                         return config_path;
164                 }
165                 free(config_path);
166                 tok = strtok(NULL, ":");
167         }
168         free(buf);
169
170         die("Unable to find the configuration file (looked at "
171                 "~/.i3status.conf, $XDG_CONFIG_HOME/i3status/config, "
172                 "/etc/i3status.conf and $XDG_CONFIG_DIRS/i3status/config)");
173         return NULL;
174 }
175
176 int main(int argc, char *argv[]) {
177         unsigned int j;
178
179         cfg_opt_t general_opts[] = {
180                 CFG_STR("output_format", "auto", CFGF_NONE),
181                 CFG_BOOL("colors", 1, CFGF_NONE),
182                 CFG_STR("color_good", "#00FF00", CFGF_NONE),
183                 CFG_STR("color_degraded", "#FFFF00", CFGF_NONE),
184                 CFG_STR("color_bad", "#FF0000", CFGF_NONE),
185                 CFG_STR("color_separator", "#333333", CFGF_NONE),
186                 CFG_INT("interval", 1, CFGF_NONE),
187                 CFG_END()
188         };
189
190         cfg_opt_t run_watch_opts[] = {
191                 CFG_STR("pidfile", NULL, CFGF_NONE),
192                 CFG_STR("format", "%title: %status", CFGF_NONE),
193                 CFG_END()
194         };
195
196         cfg_opt_t wireless_opts[] = {
197                 CFG_STR("format_up", "W: (%quality at %essid, %bitrate) %ip", CFGF_NONE),
198                 CFG_STR("format_down", "W: down", CFGF_NONE),
199                 CFG_END()
200         };
201
202         cfg_opt_t ethernet_opts[] = {
203                 CFG_STR("format_up", "E: %ip (%speed)", CFGF_NONE),
204                 CFG_STR("format_down", "E: down", CFGF_NONE),
205                 CFG_END()
206         };
207
208         cfg_opt_t ipv6_opts[] = {
209                 CFG_STR("format_up", "%ip", CFGF_NONE),
210                 CFG_STR("format_down", "no IPv6", CFGF_NONE),
211                 CFG_END()
212         };
213
214         cfg_opt_t battery_opts[] = {
215                 CFG_STR("format", "%status %percentage %remaining", CFGF_NONE),
216                 CFG_STR("path", "/sys/class/power_supply/BAT%d/uevent", CFGF_NONE),
217                 CFG_INT("low_threshold", 30, CFGF_NONE),
218                 CFG_STR("threshold_type", "time", CFGF_NONE),
219                 CFG_BOOL("last_full_capacity", false, CFGF_NONE),
220                 CFG_END()
221         };
222
223         cfg_opt_t time_opts[] = {
224                 CFG_STR("format", "%d.%m.%Y %H:%M:%S", CFGF_NONE),
225                 CFG_END()
226         };
227
228         cfg_opt_t ddate_opts[] = {
229                 CFG_STR("format", "%{%a, %b %d%}, %Y%N - %H", CFGF_NONE),
230                 CFG_END()
231         };
232
233         cfg_opt_t load_opts[] = {
234                 CFG_STR("format", "%1min %5min %15min", CFGF_NONE),
235                 CFG_END()
236         };
237
238         cfg_opt_t usage_opts[] = {
239                 CFG_STR("format", "%usage", CFGF_NONE),
240                 CFG_END()
241         };
242
243         cfg_opt_t temp_opts[] = {
244                 CFG_STR("format", "%degrees C", CFGF_NONE),
245                 CFG_STR("path", NULL, CFGF_NONE),
246                 CFG_INT("max_threshold", 75, CFGF_NONE),
247                 CFG_END()
248         };
249
250         cfg_opt_t disk_opts[] = {
251                 CFG_STR("format", "%free", CFGF_NONE),
252                 CFG_END()
253         };
254
255         cfg_opt_t volume_opts[] = {
256                 CFG_STR("format", "♪: %volume", CFGF_NONE),
257                 CFG_STR("device", "default", CFGF_NONE),
258                 CFG_STR("mixer", "Master", CFGF_NONE),
259                 CFG_INT("mixer_idx", 0, CFGF_NONE),
260                 CFG_END()
261         };
262
263         cfg_opt_t opts[] = {
264                 CFG_STR_LIST("order", "{}", CFGF_NONE),
265                 CFG_SEC("general", general_opts, CFGF_NONE),
266                 CFG_SEC("run_watch", run_watch_opts, CFGF_TITLE | CFGF_MULTI),
267                 CFG_SEC("wireless", wireless_opts, CFGF_TITLE | CFGF_MULTI),
268                 CFG_SEC("ethernet", ethernet_opts, CFGF_TITLE | CFGF_MULTI),
269                 CFG_SEC("battery", battery_opts, CFGF_TITLE | CFGF_MULTI),
270                 CFG_SEC("cpu_temperature", temp_opts, CFGF_TITLE | CFGF_MULTI),
271                 CFG_SEC("disk", disk_opts, CFGF_TITLE | CFGF_MULTI),
272                 CFG_SEC("volume", volume_opts, CFGF_TITLE | CFGF_MULTI),
273                 CFG_SEC("ipv6", ipv6_opts, CFGF_NONE),
274                 CFG_SEC("time", time_opts, CFGF_NONE),
275                 CFG_SEC("ddate", ddate_opts, CFGF_NONE),
276                 CFG_SEC("load", load_opts, CFGF_NONE),
277                 CFG_SEC("cpu_usage", usage_opts, CFGF_NONE),
278                 CFG_END()
279         };
280
281         char *configfile = NULL;
282         int o, option_index = 0;
283         struct option long_options[] = {
284                 {"config", required_argument, 0, 'c'},
285                 {"help", no_argument, 0, 'h'},
286                 {"version", no_argument, 0, 'v'},
287                 {0, 0, 0, 0}
288         };
289
290         struct sigaction action;
291         memset(&action, 0, sizeof(struct sigaction));
292         action.sa_handler = sigpipe;
293         sigaction(SIGPIPE, &action, NULL);
294
295         if (setlocale(LC_ALL, "") == NULL)
296                 die("Could not set locale. Please make sure all your LC_* / LANG settings are correct.");
297
298         while ((o = getopt_long(argc, argv, "c:hv", long_options, &option_index)) != -1)
299                 if ((char)o == 'c')
300                         configfile = optarg;
301                 else if ((char)o == 'h') {
302                         printf("i3status " VERSION " © 2008-2012 Michael Stapelberg and contributors\n"
303                                 "Syntax: %s [-c <configfile>] [-h] [-v]\n", argv[0]);
304                         return 0;
305                 } else if ((char)o == 'v') {
306                         printf("i3status " VERSION " © 2008-2012 Michael Stapelberg and contributors\n");
307                         return 0;
308                 }
309
310
311         if (configfile == NULL)
312                 configfile = get_config_path();
313
314         cfg = cfg_init(opts, CFGF_NOCASE);
315         if (cfg_parse(cfg, configfile) == CFG_PARSE_ERROR)
316                 return EXIT_FAILURE;
317
318         if (cfg_size(cfg, "order") == 0)
319                 die("Your 'order' array is empty. Please fix your config.\n");
320
321         cfg_general = cfg_getsec(cfg, "general");
322         if (cfg_general == NULL)
323                 die("Could not get section \"general\"\n");
324
325         char *output_str = cfg_getstr(cfg_general, "output_format");
326         if (strcasecmp(output_str, "auto") == 0) {
327                 fprintf(stderr, "i3status: trying to auto-detect output_format setting\n");
328                 output_str = auto_detect_format();
329                 if (!output_str) {
330                         output_str = "none";
331                         fprintf(stderr, "i3status: falling back to \"none\"\n");
332                 } else {
333                         fprintf(stderr, "i3status: auto-detected \"%s\"\n", output_str);
334                 }
335         }
336
337         if (strcasecmp(output_str, "dzen2") == 0)
338                 output_format = O_DZEN2;
339         else if (strcasecmp(output_str, "xmobar") == 0)
340                 output_format = O_XMOBAR;
341         else if (strcasecmp(output_str, "i3bar") == 0)
342                 output_format = O_I3BAR;
343         else if (strcasecmp(output_str, "none") == 0)
344                 output_format = O_NONE;
345         else die("Unknown output format: \"%s\"\n", output_str);
346
347         if (!valid_color(cfg_getstr(cfg_general, "color_good"))
348                         || !valid_color(cfg_getstr(cfg_general, "color_degraded"))
349                         || !valid_color(cfg_getstr(cfg_general, "color_bad"))
350                         || !valid_color(cfg_getstr(cfg_general, "color_separator")))
351                die("Bad color format");
352
353 #if YAJL_MAJOR >= 2
354         yajl_gen json_gen = yajl_gen_alloc(NULL);
355 #else
356         yajl_gen json_gen = yajl_gen_alloc(NULL, NULL);
357 #endif
358
359         if (output_format == O_I3BAR) {
360                 /* Initialize the i3bar protocol. See i3/docs/i3bar-protocol
361                  * for details. */
362                 printf("{\"version\":1}\n[\n");
363                 fflush(stdout);
364                 yajl_gen_array_open(json_gen);
365                 yajl_gen_clear(json_gen);
366         }
367
368         if ((general_socket = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
369                 die("Could not create socket\n");
370
371         int interval = cfg_getint(cfg_general, "interval");
372
373         /* One memory page which each plugin can use to buffer output.
374          * Even though it’s unclean, we just assume that the user will not
375          * specify a format string which expands to something longer than 4096
376          * bytes — given that the output of i3status is used to display
377          * information on screen, more than 1024 characters for the full line
378          * (!), not individual plugins, seem very unlikely. */
379         char buffer[4096];
380
381         struct tm tm;
382         while (1) {
383                 struct timeval tv;
384                 gettimeofday(&tv, NULL);
385                 time_t current_time = tv.tv_sec;
386                 struct tm *current_tm = NULL;
387                 if (current_time != (time_t) -1) {
388                         localtime_r(&current_time, &tm);
389                         current_tm = &tm;
390                 }
391                 if (output_format == O_I3BAR)
392                         yajl_gen_array_open(json_gen);
393                 for (j = 0; j < cfg_size(cfg, "order"); j++) {
394                         if (j > 0)
395                                 print_seperator();
396
397                         const char *current = cfg_getnstr(cfg, "order", j);
398
399                         CASE_SEC("ipv6") {
400                                 SEC_OPEN_MAP("ipv6");
401                                 print_ipv6_info(json_gen, buffer, cfg_getstr(sec, "format_up"), cfg_getstr(sec, "format_down"));
402                                 SEC_CLOSE_MAP;
403                         }
404
405                         CASE_SEC_TITLE("wireless") {
406                                 SEC_OPEN_MAP("wireless");
407                                 print_wireless_info(json_gen, buffer, title, cfg_getstr(sec, "format_up"), cfg_getstr(sec, "format_down"));
408                                 SEC_CLOSE_MAP;
409                         }
410
411                         CASE_SEC_TITLE("ethernet") {
412                                 SEC_OPEN_MAP("ethernet");
413                                 print_eth_info(json_gen, buffer, title, cfg_getstr(sec, "format_up"), cfg_getstr(sec, "format_down"));
414                                 SEC_CLOSE_MAP;
415                         }
416
417                         CASE_SEC_TITLE("battery") {
418                                 SEC_OPEN_MAP("battery");
419                                 print_battery_info(json_gen, buffer, atoi(title), cfg_getstr(sec, "path"), cfg_getstr(sec, "format"), cfg_getint(sec, "low_threshold"), cfg_getstr(sec, "threshold_type"), cfg_getbool(sec, "last_full_capacity"));
420                                 SEC_CLOSE_MAP;
421                         }
422
423                         CASE_SEC_TITLE("run_watch") {
424                                 SEC_OPEN_MAP("run_watch");
425                                 print_run_watch(json_gen, buffer, title, cfg_getstr(sec, "pidfile"), cfg_getstr(sec, "format"));
426                                 SEC_CLOSE_MAP;
427                         }
428
429                         CASE_SEC_TITLE("disk") {
430                                 SEC_OPEN_MAP("disk_info");
431                                 print_disk_info(json_gen, buffer, title, cfg_getstr(sec, "format"));
432                                 SEC_CLOSE_MAP;
433                         }
434
435                         CASE_SEC("load") {
436                                 SEC_OPEN_MAP("load");
437                                 print_load(json_gen, buffer, cfg_getstr(sec, "format"));
438                                 SEC_CLOSE_MAP;
439                         }
440
441                         CASE_SEC("time") {
442                                 SEC_OPEN_MAP("time");
443                                 print_time(json_gen, buffer, cfg_getstr(sec, "format"), current_tm);
444                                 SEC_CLOSE_MAP;
445                         }
446
447                         CASE_SEC("ddate") {
448                                 SEC_OPEN_MAP("ddate");
449                                 print_ddate(json_gen, buffer, cfg_getstr(sec, "format"), current_tm);
450                                 SEC_CLOSE_MAP;
451                         }
452
453                         CASE_SEC_TITLE("volume") {
454                                 SEC_OPEN_MAP("volume");
455                                 print_volume(json_gen, buffer, cfg_getstr(sec, "format"),
456                                              cfg_getstr(sec, "device"),
457                                              cfg_getstr(sec, "mixer"),
458                                              cfg_getint(sec, "mixer_idx"));
459                                 SEC_CLOSE_MAP;
460                         }
461
462                         CASE_SEC_TITLE("cpu_temperature") {
463                                 SEC_OPEN_MAP("cpu_temperature");
464                                 print_cpu_temperature_info(json_gen, buffer, atoi(title), cfg_getstr(sec, "path"), cfg_getstr(sec, "format"), cfg_getint(sec, "max_threshold"));
465                                 SEC_CLOSE_MAP;
466                         }
467
468                         CASE_SEC("cpu_usage") {
469                                 SEC_OPEN_MAP("cpu_usage");
470                                 print_cpu_usage(json_gen, buffer, cfg_getstr(sec, "format"));
471                                 SEC_CLOSE_MAP;
472                         }
473                 }
474                 if (output_format == O_I3BAR) {
475                         yajl_gen_array_close(json_gen);
476                         const unsigned char *buf;
477 #if YAJL_MAJOR >= 2
478                         size_t len;
479 #else
480                         unsigned int len;
481 #endif
482                         yajl_gen_get_buf(json_gen, &buf, &len);
483                         write(STDOUT_FILENO, buf, len);
484                         yajl_gen_clear(json_gen);
485                 }
486
487                 printf("\n");
488                 fflush(stdout);
489
490                 /* To provide updates on every full second (as good as possible)
491                  * we don’t use sleep(interval) but we sleep until the next
492                  * second (with microsecond precision) plus (interval-1)
493                  * seconds. */
494                 struct timeval current_timeval;
495                 gettimeofday(&current_timeval, NULL);
496                 struct timespec ts = {interval - 1, (10e5 - current_timeval.tv_usec) * 1000};
497                 nanosleep(&ts, NULL);
498         }
499 }