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>
61 #include <linux/ethtool.h>
62 #include <linux/sockios.h>
64 /* TODO: correctly check for *BSD */
65 #include <sys/param.h>
66 #include <sys/sysctl.h>
67 #include <sys/resource.h>
72 #define BAR "^fg(#333333)^p(5;-2)^ro(2)^p()^fg()^p(5)"
76 /* Use last full capacity instead of design capacity */
78 SIMPLEQ_ENTRY(battery) batteries;
81 SIMPLEQ_HEAD(battery_head, battery) batteries;
83 /* socket file descriptor for general purposes */
84 static int general_socket;
86 static const char *wlan_interface;
87 static const char *eth_interface;
88 static char *wmii_path;
89 static const char *time_format;
90 static bool use_colors;
91 static bool get_ethspeed;
92 static bool get_cpu_temperature;
93 static char *thermal_zone;
94 static const char *wmii_normcolors = "#222222 #333333";
95 static char order[MAX_ORDER][2];
96 static const char **run_watches;
97 static unsigned int num_run_watches;
98 static unsigned int interval = 1;
100 static int max(int a, int b) {
101 return (a > b ? a : b);
105 * This function just concats two strings in place, it should only be used
106 * for concatting order to the name of a file or concatting color codes.
107 * Otherwise, the buffer size would have to be increased.
110 static char *concat(const char *str1, const char *str2) {
111 static char concatbuf[32];
112 (void)snprintf(concatbuf, sizeof(concatbuf), "%s%s", str1, str2);
117 * Returns the correct color format for dzen (^fg(color)) or wmii (color <normcolors>)
120 static char *color(const char *colorstr) {
121 static char colorbuf[32];
123 (void)snprintf(colorbuf, sizeof(colorbuf), "^fg(%s)", colorstr);
125 (void)snprintf(colorbuf, sizeof(colorbuf), "%s %s ", colorstr, wmii_normcolors);
131 * Cleans wmii's /rbar directory by deleting all regular files
134 static void cleanup_rbar_dir() {
140 char pathbuf[strlen(wmii_path)+256+1];
142 if ((dir = opendir(wmii_path)) == NULL)
145 while ((ent = readdir(dir)) != NULL) {
146 if (ent->d_type == DT_REG) {
147 (void)snprintf(pathbuf, sizeof(pathbuf), "%s%s", wmii_path, ent->d_name);
148 if (unlink(pathbuf) == -1)
157 * Creates the specified file in wmii's /rbar directory with
158 * correct modes and initializes colors if colormode is enabled
161 static void create_file(const char *name) {
165 char pathbuf[strlen(wmii_path)+256+1];
167 int flags = O_CREAT | O_WRONLY;
170 (void)snprintf(pathbuf, sizeof(pathbuf), "%s%s", wmii_path, name);
172 /* Overwrite file's contents if it exists */
173 if (stat(pathbuf, &statbuf) >= 0)
176 if ((fd = open(pathbuf, flags, S_IRUSR | S_IWUSR)) < 0)
179 char *tmp = color("#888888");
180 if (write(fd, tmp, strlen(tmp)) != (ssize_t)strlen(tmp))
187 * Waits until wmii_path/rbar exists (= the filesystem gets mounted),
188 * cleans up all files and creates the needed files
191 static void setup(void) {
197 /* Wait until wmii_path/rbar exists */
198 for (; stat(wmii_path, &statbuf) < 0; sleep(interval));
203 create_file(concat(order[ORDER_WLAN],"wlan"));
205 create_file(concat(order[ORDER_ETH],"eth"));
206 if (get_cpu_temperature)
207 create_file(concat(order[ORDER_CPU_TEMPERATURE], "cpu_temperature"));
208 create_file(concat(order[ORDER_LOAD],"load"));
210 create_file(concat(order[ORDER_TIME],"time"));
211 for (i = 0; i < num_run_watches; i += 2) {
212 snprintf(pathbuf, sizeof(pathbuf), "%s%s", order[ORDER_RUN], run_watches[i]);
213 create_file(pathbuf);
218 * Writes the given message in the corresponding file in wmii's /rbar directory
221 static void write_to_statusbar(const char *name, const char *message, bool final_entry) {
224 (void)printf("%s^p(6)\n", message);
228 (void)printf("%s" BAR, message);
232 char pathbuf[strlen(wmii_path)+256+1];
235 (void)snprintf(pathbuf, sizeof(pathbuf), "%s%s", wmii_path, name);
236 if ((fd = open(pathbuf, O_RDWR)) == -1) {
237 /* Try to re-setup stuff and just continue */
241 if (write(fd, message, strlen(message)) != (ssize_t)strlen(message))
247 * Writes an errormessage to statusbar
250 static void write_error_to_statusbar(const char *message) {
252 create_file("error");
253 write_to_statusbar("error", message, true);
257 * Write errormessage to statusbar and exit
260 void die(const char *fmt, ...) {
264 (void)vsnprintf(buffer, sizeof(buffer), fmt, ap);
267 if (wmii_path != NULL)
268 write_error_to_statusbar(buffer);
270 fprintf(stderr, "%s", buffer);
275 * Skip the given character for exactly 'amount' times, returns
276 * a pointer to the first non-'character' character in 'input'.
279 static char *skip_character(char *input, char character, int amount) {
281 size_t len = strlen(input);
284 for (walk = input; ((size_t)(walk - input) < len) && (blanks < amount); walk++)
285 if (*walk == character)
288 return (walk == input ? walk : walk-1);
292 * Get battery information from /sys. Note that it uses the design capacity to
293 * calculate the percentage, not the last full capacity, so you can see how
294 * worn off your battery is.
297 static char *get_battery_info(struct battery *bat) {
299 static char part[512];
302 int full_design = -1,
305 charging_status_t status = CS_DISCHARGING;
307 if ((fd = open(bat->path, O_RDONLY)) == -1)
308 return "No battery found";
310 memset(part, 0, sizeof(part));
311 (void)read(fd, buf, sizeof(buf));
312 for (walk = buf, last = buf; (walk-buf) < 1024; walk++) {
321 if (BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_NOW") ||
322 BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_NOW"))
323 remaining = atoi(walk+1);
324 else if (BEGINS_WITH(last, "POWER_SUPPLY_CURRENT_NOW"))
325 present_rate = atoi(walk+1);
326 else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Charging"))
327 status = CS_CHARGING;
328 else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Full"))
331 /* The only thing left is the full capacity */
332 if (bat->use_last_full) {
333 if (!BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_FULL") &&
334 !BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_FULL"))
337 if (!BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_FULL_DESIGN") &&
338 !BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_FULL_DESIGN"))
342 full_design = atoi(walk+1);
347 if ((full_design == 1) || (remaining == -1))
350 if (present_rate > 0) {
351 float remaining_time;
352 int seconds, hours, minutes;
353 if (status == CS_CHARGING)
354 remaining_time = ((float)full_design - (float)remaining) / (float)present_rate;
355 else if (status == CS_DISCHARGING)
356 remaining_time = ((float)remaining / (float)present_rate);
357 else remaining_time = 0;
359 seconds = (int)(remaining_time * 3600.0);
360 hours = seconds / 3600;
361 seconds -= (hours * 3600);
362 minutes = seconds / 60;
363 seconds -= (minutes * 60);
365 (void)snprintf(part, sizeof(part), "%s %.02f%% %02d:%02d:%02d",
366 (status == CS_CHARGING ? "CHR" :
367 (status == CS_DISCHARGING ? "BAT" : "FULL")),
368 (((float)remaining / (float)full_design) * 100),
369 max(hours, 0), max(minutes, 0), max(seconds, 0));
371 (void)snprintf(part, sizeof(part), "%s %.02f%%",
372 (status == CS_CHARGING ? "CHR" :
373 (status == CS_DISCHARGING ? "BAT" : "FULL")),
374 (((float)remaining / (float)full_design) * 100));
380 * Return the IP address for the given interface or "no IP" if the
381 * interface is up and running but hasn't got an IP address yet
384 static const char *get_ip_address(const char *interface) {
385 static char part[512];
387 struct sockaddr_in addr;
388 socklen_t len = sizeof(struct sockaddr_in);
389 memset(part, 0, sizeof(part));
391 /* First check if the interface is running */
392 (void)strcpy(ifr.ifr_name, interface);
393 if (ioctl(general_socket, SIOCGIFFLAGS, &ifr) < 0 ||
394 !(ifr.ifr_flags & IFF_RUNNING))
397 /* Interface is up, get the IP address */
398 (void)strcpy(ifr.ifr_name, interface);
399 ifr.ifr_addr.sa_family = AF_INET;
400 if (ioctl(general_socket, SIOCGIFADDR, &ifr) < 0)
403 memcpy(&addr, &ifr.ifr_addr, len);
404 (void)inet_ntop(AF_INET, &addr.sin_addr.s_addr, part, len);
405 if (strlen(part) == 0)
406 (void)snprintf(part, sizeof(part), "no IP");
412 * Just parses /proc/net/wireless looking for lines beginning with
413 * wlan_interface, extracting the quality of the link and adding the
414 * current IP address of wlan_interface.
417 static char *get_wireless_info() {
419 static char part[512];
422 memset(buf, 0, sizeof(buf));
423 memset(part, 0, sizeof(part));
425 if ((fd = open("/proc/net/wireless", O_RDONLY)) == -1)
426 die("Could not open /proc/net/wireless\n");
427 (void)read(fd, buf, sizeof(buf));
430 interfaces = skip_character(buf, '\n', 1) + 1;
431 while ((interfaces = skip_character(interfaces, '\n', 1)+1) < buf+strlen(buf)) {
432 while (isspace((int)*interfaces))
434 if (!BEGINS_WITH(interfaces, wlan_interface))
437 if (sscanf(interfaces, "%*[^:]: 0000 %d", &quality) != 1)
439 if ((quality == UCHAR_MAX) || (quality == 0)) {
441 (void)snprintf(part, sizeof(part), "%sW: down", color("#FF0000"));
442 else (void)snprintf(part, sizeof(part), "W: down");
443 } else (void)snprintf(part, sizeof(part), "%sW: (%03d%%) %s",
444 color("#00FF00"), quality, get_ip_address(wlan_interface));
452 * Combines ethernet IP addresses and speed (if requested) for displaying
455 static char *get_eth_info() {
456 static char part[512];
457 const char *ip_address = get_ip_address(eth_interface);
462 /* This code path requires root privileges */
464 struct ethtool_cmd ecmd;
466 ecmd.cmd = ETHTOOL_GSET;
467 (void)memset(&ifr, 0, sizeof(ifr));
468 ifr.ifr_data = (caddr_t)&ecmd;
469 (void)strcpy(ifr.ifr_name, eth_interface);
470 if (ioctl(general_socket, SIOCETHTOOL, &ifr) == 0)
471 ethspeed = (ecmd.speed == USHRT_MAX ? 0 : ecmd.speed);
472 else get_ethspeed = false;
476 if (ip_address == NULL)
477 (void)snprintf(part, sizeof(part), "E: down");
480 (void)snprintf(part, sizeof(part), "E: %s (%d Mbit/s)", ip_address, ethspeed);
481 else (void)snprintf(part, sizeof(part), "E: %s", ip_address);
488 * Reads the CPU temperature from /sys/class/thermal/thermal_zone0/temp and
489 * returns the temperature in degree celcius.
492 static char *get_cpu_temperature_info() {
493 static char part[16];
498 memset(buf, 0, sizeof(buf));
499 memset(part, 0, sizeof(part));
501 if ((fd = open(thermal_zone, O_RDONLY)) == -1)
502 die("Could not open %s\n", thermal_zone);
503 (void)read(fd, buf, sizeof(buf));
506 if (sscanf(buf, "%d", &temp) != 1)
507 (void)snprintf(part, sizeof(part), "T: ? C");
509 (void)snprintf(part, sizeof(part), "T: %d C", (temp/1000));
515 * Checks if the PID in path is still valid by checking:
516 * (Linux) if /proc/<pid> exists
517 * (NetBSD) if sysctl returns process infos for this pid
520 static bool process_runs(const char *path) {
522 static glob_t globbuf;
524 memset(pidbuf, 0, sizeof(pidbuf));
526 if (glob(path, GLOB_NOCHECK | GLOB_TILDE, NULL, &globbuf) < 0)
527 die("glob() failed\n");
528 fd = open((globbuf.gl_pathc > 0 ? globbuf.gl_pathv[0] : path), O_RDONLY);
532 (void)read(fd, pidbuf, sizeof(pidbuf));
538 (void)snprintf(procbuf, sizeof(procbuf), "/proc/%ld", strtol(pidbuf, NULL, 10));
539 return (stat(procbuf, &statbuf) >= 0);
541 /* TODO: correctly check for NetBSD. Evaluate if this runs on OpenBSD/FreeBSD */
542 struct kinfo_proc info;
543 size_t length = sizeof(struct kinfo_proc);
544 int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, strtol(pidbuf, NULL, 10) };
545 if (sysctl(mib, 4, &info, &length, NULL, 0) < 0)
547 return (length != 0);
552 * Reads the configuration from the given file
555 static int load_configuration(const char *configfile) {
556 #define OPT(x) else if (strcasecmp(dest_name, x) == 0)
558 /* check if the file exists */
560 if (stat(configfile, &buf) < 0)
564 FILE *handle = fopen(configfile, "r");
566 die("Could not open configfile\n");
567 char dest_name[512], dest_value[512], whole_buffer[1026];
569 while (!feof(handle)) {
571 if ((ret = fgets(whole_buffer, 1024, handle)) == whole_buffer) {
572 /* sscanf implicitly strips whitespace */
573 if (sscanf(whole_buffer, "%s %[^\n]", dest_name, dest_value) < 1)
575 } else if (ret != NULL)
576 die("Could not read line in configuration file\n");
578 /* skip comments and empty lines */
579 if (dest_name[0] == '#' || strlen(dest_name) < 3)
583 wlan_interface = strdup(dest_value);
585 eth_interface = strdup(dest_value);
587 time_format = strdup(dest_value);
589 struct battery *new = calloc(1, sizeof(struct battery));
591 die("Could not allocate memory\n");
592 if (asprintf(&(new->path), "/sys/class/power_supply/BAT%d/uevent", atoi(dest_value)) == -1)
593 die("Could not build battery path\n");
595 /* check if flags were specified for this battery */
596 if (strstr(dest_value, ",") != NULL) {
597 char *flags = strstr(dest_value, ",");
600 new->use_last_full = true;
602 SIMPLEQ_INSERT_TAIL(&batteries, new, batteries);
607 OPT("get_cpu_temperature") {
608 get_cpu_temperature = true;
609 if (strlen(dest_value) > 0) {
610 if (asprintf(&thermal_zone, "/sys/class/thermal/thermal_zone%d/temp", atoi(dest_value)) == -1)
611 die("Could not build thermal_zone path\n");
613 if (asprintf(&thermal_zone, "/sys/class/thermal/thermal_zone0/temp") == -1)
614 die("Could not build thermal_zone path\n");
617 wmii_normcolors = strdup(dest_value);
619 interval = atoi(dest_value);
623 static glob_t globbuf;
625 if (glob(dest_value, GLOB_NOCHECK | GLOB_TILDE, NULL, &globbuf) < 0)
626 die("glob() failed\n");
627 wmii_path = strdup(globbuf.gl_pathc > 0 ? globbuf.gl_pathv[0] : dest_value);
630 if ((stat(wmii_path, &stbuf)) == -1) {
631 fprintf(stderr, "Warning: wmii_path contains an invalid path\n");
633 wmii_path = strdup(dest_value);
635 if (wmii_path[strlen(wmii_path)-1] != '/')
636 die("wmii_path is not terminated by /\n");
641 char *name = strdup(dest_value);
646 num_run_watches += 2;
647 run_watches = realloc(run_watches, sizeof(char*) * num_run_watches);
648 run_watches[num_run_watches-2] = name;
649 run_watches[num_run_watches-1] = path;
653 #define SET_ORDER(opt, idx) { if (strcasecmp(token, opt) == 0) sprintf(order[idx], "%d", c++); }
656 walk = token = dest_value;
657 while (*walk != '\0') {
658 while ((*walk != ',') && (*walk != '\0'))
661 SET_ORDER("run", ORDER_RUN);
662 SET_ORDER("wlan", ORDER_WLAN);
663 SET_ORDER("eth", ORDER_ETH);
664 SET_ORDER("battery", ORDER_BATTERY);
665 SET_ORDER("cpu_temperature", ORDER_CPU_TEMPERATURE);
666 SET_ORDER("load", ORDER_LOAD);
667 SET_ORDER("time", ORDER_TIME);
669 while (isspace((int)(*token)))
676 die("Unknown configfile option: %s\n", dest_name);
682 if (wmii_path == NULL)
689 int main(int argc, char *argv[]) {
694 char *configfile = PREFIX "/etc/i3status.conf";
695 int o, option_index = 0;
696 struct option long_options[] = {
697 {"config", required_argument, 0, 'c'},
698 {"help", no_argument, 0, 'h'},
702 SIMPLEQ_INIT(&batteries);
704 while ((o = getopt_long(argc, argv, "c:h", long_options, &option_index)) != -1)
707 else if ((char)o == 'h') {
708 printf("i3status (c) 2008-2009 Michael Stapelberg\n"
709 "Syntax: %s [-c <configfile>]\n", argv[0]);
713 if (load_configuration(configfile) < 0)
718 if ((general_socket = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
719 die("Could not create socket\n");
722 for (i = 0; i < num_run_watches; i += 2) {
723 bool running = process_runs(run_watches[i+1]);
725 snprintf(part, sizeof(part), "%s%s: %s",
726 (running ? color("#00FF00") : color("#FF0000")),
728 (running ? "yes" : "no"));
729 else snprintf(part, sizeof(part), "%s: %s", run_watches[i], (running ? "yes" : "no"));
730 snprintf(pathbuf, sizeof(pathbuf), "%s%s", order[ORDER_RUN], run_watches[i]);
731 write_to_statusbar(pathbuf, part, false);
735 write_to_statusbar(concat(order[ORDER_WLAN], "wlan"), get_wireless_info(), false);
737 write_to_statusbar(concat(order[ORDER_ETH], "eth"), get_eth_info(), false);
738 struct battery *current_battery;
739 SIMPLEQ_FOREACH(current_battery, &batteries, batteries) {
740 write_to_statusbar(concat(order[ORDER_BATTERY], "battery"), get_battery_info(current_battery), false);
742 if (get_cpu_temperature)
743 write_to_statusbar(concat(order[ORDER_CPU_TEMPERATURE], "cpu_temperature"), get_cpu_temperature_info(), false);
748 if ((load_avg = open("/proc/loadavg", O_RDONLY)) == -1)
749 die("Could not open /proc/loadavg\n");
750 (void)read(load_avg, part, sizeof(part));
751 (void)close(load_avg);
752 *skip_character(part, ' ', 3) = '\0';
754 /* TODO: correctly check for NetBSD, check if it works the same on *BSD */
756 size_t length = sizeof(struct loadavg);
757 int mib[2] = { CTL_VM, VM_LOADAVG };
758 if (sysctl(mib, 2, &load, &length, NULL, 0) < 0)
759 die("Could not sysctl({ CTL_VM, VM_LOADAVG })\n");
760 double scale = load.fscale;
761 (void)snprintf(part, sizeof(part), "%.02f %.02f %.02f",
762 (double)load.ldavg[0] / scale,
763 (double)load.ldavg[1] / scale,
764 (double)load.ldavg[2] / scale);
766 write_to_statusbar(concat(order[ORDER_LOAD], "load"), part, !time_format);
769 /* Get date & time */
770 time_t current_time = time(NULL);
771 struct tm *current_tm = localtime(¤t_time);
772 (void)strftime(part, sizeof(part), time_format, current_tm);
773 write_to_statusbar(concat(order[ORDER_TIME], "time"), part, true);