4 * i3status – Generates a status line for dzen2 or wmii
7 * Copyright © 2008-2009 Michael Stapelberg and contributors
8 * Copyright © 2009 Thorsten Toepper <atsutane at freethoughts dot de>
11 * Redistribution and use in source and binary forms, with or without modification,
12 * are permitted provided that the following conditions are met:
14 * * Redistributions of source code must retain the above copyright notice, this
15 * list of conditions and the following disclaimer.
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.
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.
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
37 #include <sys/types.h>
50 #include <sys/ioctl.h>
51 #include <sys/socket.h>
52 #include <netinet/in.h>
53 #include <arpa/inet.h>
62 #include <linux/ethtool.h>
63 #include <linux/sockios.h>
65 /* TODO: correctly check for *BSD */
66 #include <sys/param.h>
67 #include <sys/sysctl.h>
68 #include <sys/resource.h>
73 #define BAR "^fg(#333333)^p(5;-2)^ro(2)^p()^fg()^p(5)"
77 /* Use last full capacity instead of design capacity */
79 SIMPLEQ_ENTRY(battery) batteries;
82 SIMPLEQ_HEAD(battery_head, battery) batteries;
84 /* socket file descriptor for general purposes */
85 static int general_socket;
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;
101 static int max(int a, int b) {
102 return (a > b ? a : b);
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.
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);
118 * Returns the correct color format for dzen (^fg(color)) or wmii (color <normcolors>)
121 static char *color(const char *colorstr) {
122 static char colorbuf[32];
124 (void)snprintf(colorbuf, sizeof(colorbuf), "^fg(%s)", colorstr);
126 (void)snprintf(colorbuf, sizeof(colorbuf), "%s %s ", colorstr, wmii_normcolors);
132 * Cleans wmii's /rbar directory by deleting all regular files
135 static void cleanup_rbar_dir() {
141 char pathbuf[strlen(wmii_path)+256+1];
143 if ((dir = opendir(wmii_path)) == NULL)
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)
158 * Creates the specified file in wmii's /rbar directory with
159 * correct modes and initializes colors if colormode is enabled
162 static void create_file(const char *name) {
166 char pathbuf[strlen(wmii_path)+256+1];
168 int flags = O_CREAT | O_WRONLY;
171 (void)snprintf(pathbuf, sizeof(pathbuf), "%s%s", wmii_path, name);
173 /* Overwrite file's contents if it exists */
174 if (stat(pathbuf, &statbuf) >= 0)
177 if ((fd = open(pathbuf, flags, S_IRUSR | S_IWUSR)) < 0)
180 char *tmp = color("#888888");
181 if (write(fd, tmp, strlen(tmp)) != (ssize_t)strlen(tmp))
188 * Waits until wmii_path/rbar exists (= the filesystem gets mounted),
189 * cleans up all files and creates the needed files
192 static void setup(void) {
198 /* Wait until wmii_path/rbar exists */
199 for (; stat(wmii_path, &statbuf) < 0; sleep(interval));
204 create_file(concat(order[ORDER_WLAN],"wlan"));
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"));
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);
219 * Writes the given message in the corresponding file in wmii's /rbar directory
222 static void write_to_statusbar(const char *name, const char *message, bool final_entry) {
225 if (printf("%s^p(6)\n", message) < 0) {
233 if (printf("%s" BAR, message) < 0) {
240 char pathbuf[strlen(wmii_path)+256+1];
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 */
249 if (write(fd, message, strlen(message)) != (ssize_t)strlen(message))
255 * Writes an errormessage to statusbar
258 static void write_error_to_statusbar(const char *message) {
260 create_file("error");
261 write_to_statusbar("error", message, true);
265 * Write errormessage to statusbar and exit
268 void die(const char *fmt, ...) {
272 (void)vsnprintf(buffer, sizeof(buffer), fmt, ap);
275 if (wmii_path != NULL)
276 write_error_to_statusbar(buffer);
278 fprintf(stderr, "%s", buffer);
283 * Skip the given character for exactly 'amount' times, returns
284 * a pointer to the first non-'character' character in 'input'.
287 static char *skip_character(char *input, char character, int amount) {
289 size_t len = strlen(input);
292 for (walk = input; ((size_t)(walk - input) < len) && (blanks < amount); walk++)
293 if (*walk == character)
296 return (walk == input ? walk : walk-1);
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.
305 static char *get_battery_info(struct battery *bat) {
307 static char part[512];
310 int full_design = -1,
313 charging_status_t status = CS_DISCHARGING;
315 if ((fd = open(bat->path, O_RDONLY)) == -1)
316 return "No battery found";
318 memset(part, 0, sizeof(part));
319 (void)read(fd, buf, sizeof(buf));
320 for (walk = buf, last = buf; (walk-buf) < 1024; walk++) {
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"))
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"))
345 if (!BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_FULL_DESIGN") &&
346 !BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_FULL_DESIGN"))
350 full_design = atoi(walk+1);
355 if ((full_design == 1) || (remaining == -1))
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;
367 seconds = (int)(remaining_time * 3600.0);
368 hours = seconds / 3600;
369 seconds -= (hours * 3600);
370 minutes = seconds / 60;
371 seconds -= (minutes * 60);
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));
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));
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
392 static const char *get_ip_address(const char *interface) {
393 static char part[512];
395 struct sockaddr_in addr;
396 socklen_t len = sizeof(struct sockaddr_in);
397 memset(part, 0, sizeof(part));
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))
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)
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");
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.
425 static char *get_wireless_info() {
427 static char part[512];
430 memset(buf, 0, sizeof(buf));
431 memset(part, 0, sizeof(part));
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));
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))
442 if (!BEGINS_WITH(interfaces, wlan_interface))
445 if (sscanf(interfaces, "%*[^:]: 0000 %d", &quality) != 1)
447 if ((quality == UCHAR_MAX) || (quality == 0)) {
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));
460 * Combines ethernet IP addresses and speed (if requested) for displaying
463 static char *get_eth_info() {
464 static char part[512];
465 const char *ip_address = get_ip_address(eth_interface);
470 /* This code path requires root privileges */
472 struct ethtool_cmd ecmd;
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;
484 if (ip_address == NULL)
485 (void)snprintf(part, sizeof(part), "E: down");
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);
496 * Reads the CPU temperature from /sys/class/thermal/thermal_zone0/temp and
497 * returns the temperature in degree celcius.
500 static char *get_cpu_temperature_info() {
501 static char part[16];
506 memset(buf, 0, sizeof(buf));
507 memset(part, 0, sizeof(part));
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));
514 if (sscanf(buf, "%d", &temp) != 1)
515 (void)snprintf(part, sizeof(part), "T: ? C");
517 (void)snprintf(part, sizeof(part), "T: %d C", (temp/1000));
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
528 static bool process_runs(const char *path) {
530 static glob_t globbuf;
532 memset(pidbuf, 0, sizeof(pidbuf));
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);
540 (void)read(fd, pidbuf, sizeof(pidbuf));
546 (void)snprintf(procbuf, sizeof(procbuf), "/proc/%ld", strtol(pidbuf, NULL, 10));
547 return (stat(procbuf, &statbuf) >= 0);
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)
555 return (length != 0);
560 * Reads the configuration from the given file
563 static int load_configuration(const char *configfile) {
564 #define OPT(x) else if (strcasecmp(dest_name, x) == 0)
566 /* check if the file exists */
568 if (stat(configfile, &buf) < 0)
572 FILE *handle = fopen(configfile, "r");
574 die("Could not open configfile\n");
575 char dest_name[512], dest_value[512], whole_buffer[1026];
577 while (!feof(handle)) {
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)
583 } else if (ret != NULL)
584 die("Could not read line in configuration file\n");
586 /* skip comments and empty lines */
587 if (dest_name[0] == '#' || strlen(dest_name) < 3)
591 wlan_interface = strdup(dest_value);
593 eth_interface = strdup(dest_value);
595 time_format = strdup(dest_value);
597 struct battery *new = calloc(1, sizeof(struct battery));
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");
603 /* check if flags were specified for this battery */
604 if (strstr(dest_value, ",") != NULL) {
605 char *flags = strstr(dest_value, ",");
608 new->use_last_full = true;
610 SIMPLEQ_INSERT_TAIL(&batteries, new, batteries);
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");
621 if (asprintf(&thermal_zone, "/sys/class/thermal/thermal_zone0/temp") == -1)
622 die("Could not build thermal_zone path\n");
625 wmii_normcolors = strdup(dest_value);
627 interval = atoi(dest_value);
631 static glob_t globbuf;
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);
638 if ((stat(wmii_path, &stbuf)) == -1) {
639 fprintf(stderr, "Warning: wmii_path contains an invalid path\n");
641 wmii_path = strdup(dest_value);
643 if (wmii_path[strlen(wmii_path)-1] != '/')
644 die("wmii_path is not terminated by /\n");
649 char *name = strdup(dest_value);
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;
661 #define SET_ORDER(opt, idx) { if (strcasecmp(token, opt) == 0) sprintf(order[idx], "%d", c++); }
664 walk = token = dest_value;
665 while (*walk != '\0') {
666 while ((*walk != ',') && (*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);
677 while (isspace((int)(*token)))
684 die("Unknown configfile option: %s\n", dest_name);
690 if (wmii_path == NULL)
698 * Exit upon SIGPIPE because when we have nowhere to write to, gathering
699 * system information is pointless.
702 void sigpipe(int signum) {
703 fprintf(stderr, "Received SIGPIPE, exiting\n");
707 int main(int argc, char *argv[]) {
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'},
720 struct sigaction action;
721 memset(&action, 0, sizeof(struct sigaction));
722 action.sa_handler = sigpipe;
723 sigaction(SIGPIPE, &action, NULL);
725 SIMPLEQ_INIT(&batteries);
727 while ((o = getopt_long(argc, argv, "c:h", long_options, &option_index)) != -1)
730 else if ((char)o == 'h') {
731 printf("i3status (c) 2008-2009 Michael Stapelberg\n"
732 "Syntax: %s [-c <configfile>]\n", argv[0]);
736 if (load_configuration(configfile) < 0)
741 if ((general_socket = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
742 die("Could not create socket\n");
745 for (i = 0; i < num_run_watches; i += 2) {
746 bool running = process_runs(run_watches[i+1]);
748 snprintf(part, sizeof(part), "%s%s: %s",
749 (running ? color("#00FF00") : color("#FF0000")),
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);
758 write_to_statusbar(concat(order[ORDER_WLAN], "wlan"), get_wireless_info(), false);
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);
765 if (get_cpu_temperature)
766 write_to_statusbar(concat(order[ORDER_CPU_TEMPERATURE], "cpu_temperature"), get_cpu_temperature_info(), false);
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';
777 /* TODO: correctly check for NetBSD, check if it works the same on *BSD */
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);
789 write_to_statusbar(concat(order[ORDER_LOAD], "load"), part, !time_format);
792 /* Get date & time */
793 time_t current_time = time(NULL);
794 struct tm *current_tm = localtime(¤t_time);
795 (void)strftime(part, sizeof(part), time_format, current_tm);
796 write_to_statusbar(concat(order[ORDER_TIME], "time"), part, true);