]> git.sur5r.net Git - i3/i3status/blob - i3status.c
debian: revert packaging to produce only one package, but with both binaries
[i3/i3status] / i3status.c
1 /*
2  * vim:ts=8:expandtab
3  *
4  * i3status – Generates a status line for dzen2 or wmii
5  *
6  *
7  * Copyright © 2008-2009 Michael Stapelberg and contributors
8  * Copyright © 2009 Thorsten Toepper <atsutane at freethoughts dot de>
9  * All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without modification,
12  * are permitted provided that the following conditions are met:
13  *
14  * * Redistributions of source code must retain the above copyright notice, this
15  *   list of conditions and the following disclaimer.
16  *
17  * * Redistributions in binary form must reproduce the above copyright notice, this
18  *   list of conditions and the following disclaimer in the documentation and/or other
19  *   materials provided with the distribution.
20  *
21  * * Neither the name of Michael Stapelberg nor the names of contributors
22  *   may be used to endorse or promote products derived from this software without
23  *   specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
26  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
27  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
28  * SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
30  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
31  * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
32  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
34  * DAMAGE.
35  *
36  */
37 #include <sys/types.h>
38 #include <sys/stat.h>
39 #include <fcntl.h>
40 #include <string.h>
41 #include <stdio.h>
42 #include <time.h>
43 #include <stdbool.h>
44 #include <stdarg.h>
45 #include <unistd.h>
46 #include <stdlib.h>
47 #include <limits.h>
48 #include <ctype.h>
49 #include <net/if.h>
50 #include <sys/ioctl.h>
51 #include <sys/socket.h>
52 #include <netinet/in.h>
53 #include <arpa/inet.h>
54 #include <glob.h>
55 #include <dirent.h>
56 #include <getopt.h>
57 #include <signal.h>
58
59 #include "queue.h"
60
61 #ifdef LINUX
62 #include <linux/ethtool.h>
63 #include <linux/sockios.h>
64 #else
65 /* TODO: correctly check for *BSD */
66 #include <sys/param.h>
67 #include <sys/sysctl.h>
68 #include <sys/resource.h>
69 #endif
70
71 #include "i3status.h"
72
73 #define BAR "^fg(#333333)^p(5;-2)^ro(2)^p()^fg()^p(5)"
74
75 struct battery {
76         char *path;
77         /* Use last full capacity instead of design capacity */
78         bool use_last_full;
79         SIMPLEQ_ENTRY(battery) batteries;
80 };
81
82 SIMPLEQ_HEAD(battery_head, battery) batteries;
83
84 /* socket file descriptor for general purposes */
85 static int general_socket;
86
87 static const char *wlan_interface;
88 static const char *eth_interface;
89 static char *wmii_path;
90 static const char *time_format;
91 static bool use_colors;
92 static bool get_ethspeed;
93 static bool get_cpu_temperature;
94 static char *thermal_zone;
95 static const char *wmii_normcolors = "#222222 #333333";
96 static char order[MAX_ORDER][2];
97 static const char **run_watches;
98 static unsigned int num_run_watches;
99 static unsigned int interval = 1;
100
101 static int max(int a, int b) {
102         return (a > b ? a : b);
103 }
104
105 /*
106  * This function just concats two strings in place, it should only be used
107  * for concatting order to the name of a file or concatting color codes.
108  * Otherwise, the buffer size would have to be increased.
109  *
110  */
111 static char *concat(const char *str1, const char *str2) {
112         static char concatbuf[32];
113         (void)snprintf(concatbuf, sizeof(concatbuf), "%s%s", str1, str2);
114         return concatbuf;
115 }
116
117 /*
118  * Returns the correct color format for dzen (^fg(color)) or wmii (color <normcolors>)
119  *
120  */
121 static char *color(const char *colorstr) {
122         static char colorbuf[32];
123 #ifdef DZEN
124         (void)snprintf(colorbuf, sizeof(colorbuf), "^fg(%s)", colorstr);
125 #else
126         (void)snprintf(colorbuf, sizeof(colorbuf), "%s %s ", colorstr, wmii_normcolors);
127 #endif
128         return colorbuf;
129 }
130
131 /*
132  * Cleans wmii's /rbar directory by deleting all regular files
133  *
134  */
135 static void cleanup_rbar_dir() {
136 #ifdef DZEN
137         return;
138 #endif
139         struct dirent *ent;
140         DIR *dir;
141         char pathbuf[strlen(wmii_path)+256+1];
142
143         if ((dir = opendir(wmii_path)) == NULL)
144                 exit(EXIT_FAILURE);
145
146         while ((ent = readdir(dir)) != NULL) {
147                 if (ent->d_type == DT_REG) {
148                         (void)snprintf(pathbuf, sizeof(pathbuf), "%s%s", wmii_path, ent->d_name);
149                         if (unlink(pathbuf) == -1)
150                                 exit(EXIT_FAILURE);
151                 }
152         }
153
154         (void)closedir(dir);
155 }
156
157 /*
158  * Creates the specified file in wmii's /rbar directory with
159  * correct modes and initializes colors if colormode is enabled
160  *
161  */
162 static void create_file(const char *name) {
163 #ifdef DZEN
164         return;
165 #endif
166         char pathbuf[strlen(wmii_path)+256+1];
167         int fd;
168         int flags = O_CREAT | O_WRONLY;
169         struct stat statbuf;
170
171         (void)snprintf(pathbuf, sizeof(pathbuf), "%s%s", wmii_path, name);
172
173         /* Overwrite file's contents if it exists */
174         if (stat(pathbuf, &statbuf) >= 0)
175                 flags |= O_TRUNC;
176
177         if ((fd = open(pathbuf, flags, S_IRUSR | S_IWUSR)) < 0)
178                 exit(EXIT_FAILURE);
179         if (use_colors) {
180                 char *tmp = color("#888888");
181                 if (write(fd, tmp, strlen(tmp)) != (ssize_t)strlen(tmp))
182                         exit(EXIT_FAILURE);
183         }
184         (void)close(fd);
185 }
186
187 /*
188  * Waits until wmii_path/rbar exists (= the filesystem gets mounted),
189  * cleans up all files and creates the needed files
190  *
191  */
192 static void setup(void) {
193         unsigned int i;
194         char pathbuf[512];
195
196 #ifndef DZEN
197         struct stat statbuf;
198         /* Wait until wmii_path/rbar exists */
199         for (; stat(wmii_path, &statbuf) < 0; sleep(interval));
200 #endif
201
202         cleanup_rbar_dir();
203         if (wlan_interface)
204                 create_file(concat(order[ORDER_WLAN],"wlan"));
205         if (eth_interface)
206                 create_file(concat(order[ORDER_ETH],"eth"));
207         if (get_cpu_temperature)
208                 create_file(concat(order[ORDER_CPU_TEMPERATURE], "cpu_temperature"));
209         create_file(concat(order[ORDER_LOAD],"load"));
210         if (time_format)
211                 create_file(concat(order[ORDER_TIME],"time"));
212         for (i = 0; i < num_run_watches; i += 2) {
213                 snprintf(pathbuf, sizeof(pathbuf), "%s%s", order[ORDER_RUN], run_watches[i]);
214                 create_file(pathbuf);
215         }
216 }
217
218 /*
219  * Writes the given message in the corresponding file in wmii's /rbar directory
220  *
221  */
222 static void write_to_statusbar(const char *name, const char *message, bool final_entry) {
223 #ifdef DZEN
224         if (final_entry) {
225                 if (printf("%s^p(6)\n", message) < 0) {
226                         perror("printf");
227                         exit(1);
228                 }
229
230                 fflush(stdout);
231                 return;
232         }
233         if (printf("%s" BAR, message) < 0) {
234                 perror("printf");
235                 exit(1);
236         }
237         return;
238 #endif
239
240         char pathbuf[strlen(wmii_path)+256+1];
241         int fd;
242
243         (void)snprintf(pathbuf, sizeof(pathbuf), "%s%s", wmii_path, name);
244         if ((fd = open(pathbuf, O_RDWR)) == -1) {
245                 /* Try to re-setup stuff and just continue */
246                 setup();
247                 return;
248         }
249         if (write(fd, message, strlen(message)) != (ssize_t)strlen(message))
250                 exit(EXIT_FAILURE);
251         (void)close(fd);
252 }
253
254 /*
255  * Writes an errormessage to statusbar
256  *
257  */
258 static void write_error_to_statusbar(const char *message) {
259         cleanup_rbar_dir();
260         create_file("error");
261         write_to_statusbar("error", message, true);
262 }
263
264 /*
265  * Write errormessage to statusbar and exit
266  *
267  */
268 void die(const char *fmt, ...) {
269         char buffer[512];
270         va_list ap;
271         va_start(ap, fmt);
272         (void)vsnprintf(buffer, sizeof(buffer), fmt, ap);
273         va_end(ap);
274
275         if (wmii_path != NULL)
276                 write_error_to_statusbar(buffer);
277         else
278                 fprintf(stderr, "%s", buffer);
279         exit(EXIT_FAILURE);
280 }
281
282 /*
283  * Skip the given character for exactly 'amount' times, returns
284  * a pointer to the first non-'character' character in 'input'.
285  *
286  */
287 static char *skip_character(char *input, char character, int amount) {
288         char *walk;
289         size_t len = strlen(input);
290         int blanks = 0;
291
292         for (walk = input; ((size_t)(walk - input) < len) && (blanks < amount); walk++)
293                 if (*walk == character)
294                         blanks++;
295
296         return (walk == input ? walk : walk-1);
297 }
298
299 /*
300  * Get battery information from /sys. Note that it uses the design capacity to
301  * calculate the percentage, not the last full capacity, so you can see how
302  * worn off your battery is.
303  *
304  */
305 static char *get_battery_info(struct battery *bat) {
306         char buf[1024];
307         static char part[512];
308         char *walk, *last;
309         int fd;
310         int full_design = -1,
311             remaining = -1,
312             present_rate = -1;
313         charging_status_t status = CS_DISCHARGING;
314
315         if ((fd = open(bat->path, O_RDONLY)) == -1)
316                 return "No battery found";
317
318         memset(part, 0, sizeof(part));
319         (void)read(fd, buf, sizeof(buf));
320         for (walk = buf, last = buf; (walk-buf) < 1024; walk++) {
321                 if (*walk == '\n') {
322                         last = walk+1;
323                         continue;
324                 }
325
326                 if (*walk != '=')
327                         continue;
328
329                 if (BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_NOW") ||
330                     BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_NOW"))
331                         remaining = atoi(walk+1);
332                 else if (BEGINS_WITH(last, "POWER_SUPPLY_CURRENT_NOW"))
333                         present_rate = atoi(walk+1);
334                 else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Charging"))
335                         status = CS_CHARGING;
336                 else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Full"))
337                         status = CS_FULL;
338                 else {
339                         /* The only thing left is the full capacity */
340                         if (bat->use_last_full) {
341                                 if (!BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_FULL") &&
342                                     !BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_FULL"))
343                                         continue;
344                         } else {
345                                 if (!BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_FULL_DESIGN") &&
346                                     !BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_FULL_DESIGN"))
347                                         continue;
348                         }
349
350                         full_design = atoi(walk+1);
351                 }
352         }
353         (void)close(fd);
354
355         if ((full_design == 1) || (remaining == -1))
356                 return part;
357
358         if (present_rate > 0) {
359                 float remaining_time;
360                 int seconds, hours, minutes;
361                 if (status == CS_CHARGING)
362                         remaining_time = ((float)full_design - (float)remaining) / (float)present_rate;
363                 else if (status == CS_DISCHARGING)
364                         remaining_time = ((float)remaining / (float)present_rate);
365                 else remaining_time = 0;
366
367                 seconds = (int)(remaining_time * 3600.0);
368                 hours = seconds / 3600;
369                 seconds -= (hours * 3600);
370                 minutes = seconds / 60;
371                 seconds -= (minutes * 60);
372
373                 (void)snprintf(part, sizeof(part), "%s %.02f%% %02d:%02d:%02d",
374                         (status == CS_CHARGING ? "CHR" :
375                          (status == CS_DISCHARGING ? "BAT" : "FULL")),
376                         (((float)remaining / (float)full_design) * 100),
377                         max(hours, 0), max(minutes, 0), max(seconds, 0));
378         } else {
379                 (void)snprintf(part, sizeof(part), "%s %.02f%%",
380                         (status == CS_CHARGING ? "CHR" :
381                          (status == CS_DISCHARGING ? "BAT" : "FULL")),
382                         (((float)remaining / (float)full_design) * 100));
383         }
384         return part;
385 }
386
387 /*
388  * Return the IP address for the given interface or "no IP" if the
389  * interface is up and running but hasn't got an IP address yet
390  *
391  */
392 static const char *get_ip_address(const char *interface) {
393         static char part[512];
394         struct ifreq ifr;
395         struct sockaddr_in addr;
396         socklen_t len = sizeof(struct sockaddr_in);
397         memset(part, 0, sizeof(part));
398
399         /* First check if the interface is running */
400         (void)strcpy(ifr.ifr_name, interface);
401         if (ioctl(general_socket, SIOCGIFFLAGS, &ifr) < 0 ||
402             !(ifr.ifr_flags & IFF_RUNNING))
403                 return NULL;
404
405         /* Interface is up, get the IP address */
406         (void)strcpy(ifr.ifr_name, interface);
407         ifr.ifr_addr.sa_family = AF_INET;
408         if (ioctl(general_socket, SIOCGIFADDR, &ifr) < 0)
409                 return "no IP";
410
411         memcpy(&addr, &ifr.ifr_addr, len);
412         (void)inet_ntop(AF_INET, &addr.sin_addr.s_addr, part, len);
413         if (strlen(part) == 0)
414                 (void)snprintf(part, sizeof(part), "no IP");
415
416         return part;
417 }
418
419 /*
420  * Just parses /proc/net/wireless looking for lines beginning with
421  * wlan_interface, extracting the quality of the link and adding the
422  * current IP address of wlan_interface.
423  *
424  */
425 static char *get_wireless_info() {
426         char buf[1024];
427         static char part[512];
428         char *interfaces;
429         int fd;
430         memset(buf, 0, sizeof(buf));
431         memset(part, 0, sizeof(part));
432
433         if ((fd = open("/proc/net/wireless", O_RDONLY)) == -1)
434                 die("Could not open /proc/net/wireless\n");
435         (void)read(fd, buf, sizeof(buf));
436         (void)close(fd);
437
438         interfaces = skip_character(buf, '\n', 1) + 1;
439         while ((interfaces = skip_character(interfaces, '\n', 1)+1) < buf+strlen(buf)) {
440                 while (isspace((int)*interfaces))
441                         interfaces++;
442                 if (!BEGINS_WITH(interfaces, wlan_interface))
443                         continue;
444                 int quality;
445                 if (sscanf(interfaces, "%*[^:]: 0000 %d", &quality) != 1)
446                         continue;
447                 if ((quality == UCHAR_MAX) || (quality == 0)) {
448                         if (use_colors)
449                                 (void)snprintf(part, sizeof(part), "%sW: down", color("#FF0000"));
450                         else (void)snprintf(part, sizeof(part), "W: down");
451                 } else (void)snprintf(part, sizeof(part), "%sW: (%03d%%) %s",
452                                 color("#00FF00"), quality, get_ip_address(wlan_interface));
453                 return part;
454         }
455
456         return part;
457 }
458
459 /*
460  * Combines ethernet IP addresses and speed (if requested) for displaying
461  *
462  */
463 static char *get_eth_info() {
464         static char part[512];
465         const char *ip_address = get_ip_address(eth_interface);
466         int ethspeed = 0;
467
468         if (get_ethspeed) {
469 #ifdef LINUX
470                 /* This code path requires root privileges */
471                 struct ifreq ifr;
472                 struct ethtool_cmd ecmd;
473
474                 ecmd.cmd = ETHTOOL_GSET;
475                 (void)memset(&ifr, 0, sizeof(ifr));
476                 ifr.ifr_data = (caddr_t)&ecmd;
477                 (void)strcpy(ifr.ifr_name, eth_interface);
478                 if (ioctl(general_socket, SIOCETHTOOL, &ifr) == 0)
479                         ethspeed = (ecmd.speed == USHRT_MAX ? 0 : ecmd.speed);
480                 else get_ethspeed = false;
481 #endif
482         }
483
484         if (ip_address == NULL)
485                 (void)snprintf(part, sizeof(part), "E: down");
486         else {
487                 if (get_ethspeed)
488                         (void)snprintf(part, sizeof(part), "E: %s (%d Mbit/s)", ip_address, ethspeed);
489                 else (void)snprintf(part, sizeof(part), "E: %s", ip_address);
490         }
491
492         return part;
493 }
494
495 /*
496  * Reads the CPU temperature from /sys/class/thermal/thermal_zone0/temp and
497  * returns the temperature in degree celcius.
498  *
499  */
500 static char *get_cpu_temperature_info() {
501         static char part[16];
502         char buf[16];
503         int temp;
504         int fd;
505
506         memset(buf, 0, sizeof(buf));
507         memset(part, 0, sizeof(part));
508
509         if ((fd = open(thermal_zone, O_RDONLY)) == -1)
510                 die("Could not open %s\n", thermal_zone);
511         (void)read(fd, buf, sizeof(buf));
512         (void)close(fd);
513
514         if (sscanf(buf, "%d", &temp) != 1)
515                 (void)snprintf(part, sizeof(part), "T: ? C");
516         else
517                 (void)snprintf(part, sizeof(part), "T: %d C", (temp/1000));
518
519         return part;
520 }
521
522 /*
523  * Checks if the PID in path is still valid by checking:
524  *  (Linux) if /proc/<pid> exists
525  *  (NetBSD) if sysctl returns process infos for this pid
526  *
527  */
528 static bool process_runs(const char *path) {
529         char pidbuf[16];
530         static glob_t globbuf;
531         int fd;
532         memset(pidbuf, 0, sizeof(pidbuf));
533
534         if (glob(path, GLOB_NOCHECK | GLOB_TILDE, NULL, &globbuf) < 0)
535                 die("glob() failed\n");
536         fd = open((globbuf.gl_pathc > 0 ? globbuf.gl_pathv[0] : path), O_RDONLY);
537         globfree(&globbuf);
538         if (fd < 0)
539                 return false;
540         (void)read(fd, pidbuf, sizeof(pidbuf));
541         (void)close(fd);
542
543 #ifdef LINUX
544         struct stat statbuf;
545         char procbuf[512];
546         (void)snprintf(procbuf, sizeof(procbuf), "/proc/%ld", strtol(pidbuf, NULL, 10));
547         return (stat(procbuf, &statbuf) >= 0);
548 #else
549         /* TODO: correctly check for NetBSD. Evaluate if this runs on OpenBSD/FreeBSD */
550         struct kinfo_proc info;
551         size_t length = sizeof(struct kinfo_proc);
552         int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, strtol(pidbuf, NULL, 10) };
553         if (sysctl(mib, 4, &info, &length, NULL, 0) < 0)
554                 return false;
555         return (length != 0);
556 #endif
557 }
558
559 /*
560  * Reads the configuration from the given file
561  *
562  */
563 static int load_configuration(const char *configfile) {
564         #define OPT(x) else if (strcasecmp(dest_name, x) == 0)
565
566         /* check if the file exists */
567         struct stat buf;
568         if (stat(configfile, &buf) < 0)
569                 return -1;
570
571         int result = 0;
572         FILE *handle = fopen(configfile, "r");
573         if (handle == NULL)
574                 die("Could not open configfile\n");
575         char dest_name[512], dest_value[512], whole_buffer[1026];
576
577         while (!feof(handle)) {
578                 char *ret;
579                 if ((ret = fgets(whole_buffer, 1024, handle)) == whole_buffer) {
580                         /* sscanf implicitly strips whitespace */
581                         if (sscanf(whole_buffer, "%s %[^\n]", dest_name, dest_value) < 1)
582                                 continue;
583                 } else if (ret != NULL)
584                         die("Could not read line in configuration file\n");
585
586                 /* skip comments and empty lines */
587                 if (dest_name[0] == '#' || strlen(dest_name) < 3)
588                         continue;
589
590                 OPT("wlan")
591                         wlan_interface = strdup(dest_value);
592                 OPT("eth")
593                         eth_interface = strdup(dest_value);
594                 OPT("time_format")
595                         time_format = strdup(dest_value);
596                 OPT("battery") {
597                         struct battery *new = calloc(1, sizeof(struct battery));
598                         if (new == NULL)
599                                 die("Could not allocate memory\n");
600                         if (asprintf(&(new->path), "/sys/class/power_supply/BAT%d/uevent", atoi(dest_value)) == -1)
601                                 die("Could not build battery path\n");
602
603                         /* check if flags were specified for this battery */
604                         if (strstr(dest_value, ",") != NULL) {
605                                 char *flags = strstr(dest_value, ",");
606                                 flags++;
607                                 if (*flags == 'f')
608                                         new->use_last_full = true;
609                         }
610                         SIMPLEQ_INSERT_TAIL(&batteries, new, batteries);
611                 } OPT("color")
612                         use_colors = true;
613                 OPT("get_ethspeed")
614                         get_ethspeed = true;
615                 OPT("get_cpu_temperature") {
616                         get_cpu_temperature = true;
617                         if (strlen(dest_value) > 0) {
618                                 if (asprintf(&thermal_zone, "/sys/class/thermal/thermal_zone%d/temp", atoi(dest_value)) == -1)
619                                         die("Could not build thermal_zone path\n");
620                         } else {
621                                  if (asprintf(&thermal_zone, "/sys/class/thermal/thermal_zone0/temp") == -1)
622                                         die("Could not build thermal_zone path\n");
623                         }
624                 } OPT("normcolors")
625                         wmii_normcolors = strdup(dest_value);
626                 OPT("interval")
627                         interval = atoi(dest_value);
628                 OPT("wmii_path")
629                 {
630 #ifndef DZEN
631                         static glob_t globbuf;
632                         struct stat stbuf;
633                         if (glob(dest_value, GLOB_NOCHECK | GLOB_TILDE, NULL, &globbuf) < 0)
634                                 die("glob() failed\n");
635                         wmii_path = strdup(globbuf.gl_pathc > 0 ? globbuf.gl_pathv[0] : dest_value);
636                         globfree(&globbuf);
637
638                         if ((stat(wmii_path, &stbuf)) == -1) {
639                                 fprintf(stderr, "Warning: wmii_path contains an invalid path\n");
640                                 free(wmii_path);
641                                 wmii_path = strdup(dest_value);
642                         }
643                         if (wmii_path[strlen(wmii_path)-1] != '/')
644                                 die("wmii_path is not terminated by /\n");
645 #endif
646                 }
647                 OPT("run_watch")
648                 {
649                         char *name = strdup(dest_value);
650                         char *path = name;
651                         while (*path != ' ')
652                                 path++;
653                         *(path++) = '\0';
654                         num_run_watches += 2;
655                         run_watches = realloc(run_watches, sizeof(char*) * num_run_watches);
656                         run_watches[num_run_watches-2] = name;
657                         run_watches[num_run_watches-1] = path;
658                 }
659                 OPT("order")
660                 {
661                         #define SET_ORDER(opt, idx) { if (strcasecmp(token, opt) == 0) sprintf(order[idx], "%d", c++); }
662                         char *walk, *token;
663                         int c = 0;
664                         walk = token = dest_value;
665                         while (*walk != '\0') {
666                                 while ((*walk != ',') && (*walk != '\0'))
667                                         walk++;
668                                 *(walk++) = '\0';
669                                 SET_ORDER("run", ORDER_RUN);
670                                 SET_ORDER("wlan", ORDER_WLAN);
671                                 SET_ORDER("eth", ORDER_ETH);
672                                 SET_ORDER("battery", ORDER_BATTERY);
673                                 SET_ORDER("cpu_temperature", ORDER_CPU_TEMPERATURE);
674                                 SET_ORDER("load", ORDER_LOAD);
675                                 SET_ORDER("time", ORDER_TIME);
676                                 token = walk;
677                                 while (isspace((int)(*token)))
678                                         token++;
679                         }
680                 }
681                 else
682                 {
683                         result = -2;
684                         die("Unknown configfile option: %s\n", dest_name);
685                 }
686         }
687         fclose(handle);
688
689 #ifndef DZEN
690         if (wmii_path == NULL)
691                 exit(EXIT_FAILURE);
692 #endif
693
694         return result;
695 }
696
697 /*
698  * Exit upon SIGPIPE because when we have nowhere to write to, gathering
699  * system information is pointless.
700  *
701  */
702 void sigpipe(int signum) {
703         fprintf(stderr, "Received SIGPIPE, exiting\n");
704         exit(1);
705 }
706
707 int main(int argc, char *argv[]) {
708         char part[512],
709              pathbuf[512];
710         unsigned int i;
711
712         char *configfile = PREFIX "/etc/i3status.conf";
713         int o, option_index = 0;
714         struct option long_options[] = {
715                 {"config", required_argument, 0, 'c'},
716                 {"help", no_argument, 0, 'h'},
717                 {0, 0, 0, 0}
718         };
719
720         struct sigaction action;
721         memset(&action, 0, sizeof(struct sigaction));
722         action.sa_handler = sigpipe;
723         sigaction(SIGPIPE, &action, NULL);
724
725         SIMPLEQ_INIT(&batteries);
726
727         while ((o = getopt_long(argc, argv, "c:h", long_options, &option_index)) != -1)
728                 if ((char)o == 'c')
729                         configfile = optarg;
730                 else if ((char)o == 'h') {
731                         printf("i3status (c) 2008-2009 Michael Stapelberg\n"
732                                 "Syntax: %s [-c <configfile>]\n", argv[0]);
733                         return 0;
734                 }
735
736         if (load_configuration(configfile) < 0)
737                 return EXIT_FAILURE;
738
739         setup();
740
741         if ((general_socket = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
742                 die("Could not create socket\n");
743
744         while (1) {
745                 for (i = 0; i < num_run_watches; i += 2) {
746                         bool running = process_runs(run_watches[i+1]);
747                         if (use_colors)
748                                 snprintf(part, sizeof(part), "%s%s: %s",
749                                         (running ? color("#00FF00") : color("#FF0000")),
750                                         run_watches[i],
751                                         (running ? "yes" : "no"));
752                         else snprintf(part, sizeof(part), "%s: %s", run_watches[i], (running ? "yes" : "no"));
753                         snprintf(pathbuf, sizeof(pathbuf), "%s%s", order[ORDER_RUN], run_watches[i]);
754                         write_to_statusbar(pathbuf, part, false);
755                 }
756
757                 if (wlan_interface)
758                         write_to_statusbar(concat(order[ORDER_WLAN], "wlan"), get_wireless_info(), false);
759                 if (eth_interface)
760                         write_to_statusbar(concat(order[ORDER_ETH], "eth"), get_eth_info(), false);
761                 struct battery *current_battery;
762                 SIMPLEQ_FOREACH(current_battery, &batteries, batteries) {
763                         write_to_statusbar(concat(order[ORDER_BATTERY], "battery"), get_battery_info(current_battery), false);
764                 }
765                 if (get_cpu_temperature)
766                         write_to_statusbar(concat(order[ORDER_CPU_TEMPERATURE], "cpu_temperature"), get_cpu_temperature_info(), false);
767
768                 /* Get load */
769 #ifdef LINUX
770                 int load_avg;
771                 if ((load_avg = open("/proc/loadavg", O_RDONLY)) == -1)
772                         die("Could not open /proc/loadavg\n");
773                 (void)read(load_avg, part, sizeof(part));
774                 (void)close(load_avg);
775                 *skip_character(part, ' ', 3) = '\0';
776 #else
777                 /* TODO: correctly check for NetBSD, check if it works the same on *BSD */
778                 struct loadavg load;
779                 size_t length = sizeof(struct loadavg);
780                 int mib[2] = { CTL_VM, VM_LOADAVG };
781                 if (sysctl(mib, 2, &load, &length, NULL, 0) < 0)
782                         die("Could not sysctl({ CTL_VM, VM_LOADAVG })\n");
783                 double scale = load.fscale;
784                 (void)snprintf(part, sizeof(part), "%.02f %.02f %.02f",
785                                 (double)load.ldavg[0] / scale,
786                                 (double)load.ldavg[1] / scale,
787                                 (double)load.ldavg[2] / scale);
788 #endif
789                 write_to_statusbar(concat(order[ORDER_LOAD], "load"), part, !time_format);
790
791                 if (time_format) {
792                         /* Get date & time */
793                         time_t current_time = time(NULL);
794                         struct tm *current_tm = localtime(&current_time);
795                         (void)strftime(part, sizeof(part), time_format, current_tm);
796                         write_to_statusbar(concat(order[ORDER_TIME], "time"), part, true);
797                 }
798
799                 sleep(interval);
800         }
801 }