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 if (printf("%s^p(6)\n", message) < 0) {
232 if (printf("%s" BAR, message) < 0) {
239 char pathbuf[strlen(wmii_path)+256+1];
242 (void)snprintf(pathbuf, sizeof(pathbuf), "%s%s", wmii_path, name);
243 if ((fd = open(pathbuf, O_RDWR)) == -1) {
244 /* Try to re-setup stuff and just continue */
248 if (write(fd, message, strlen(message)) != (ssize_t)strlen(message))
254 * Writes an errormessage to statusbar
257 static void write_error_to_statusbar(const char *message) {
259 create_file("error");
260 write_to_statusbar("error", message, true);
264 * Write errormessage to statusbar and exit
267 void die(const char *fmt, ...) {
271 (void)vsnprintf(buffer, sizeof(buffer), fmt, ap);
274 if (wmii_path != NULL)
275 write_error_to_statusbar(buffer);
277 fprintf(stderr, "%s", buffer);
282 * Skip the given character for exactly 'amount' times, returns
283 * a pointer to the first non-'character' character in 'input'.
286 static char *skip_character(char *input, char character, int amount) {
288 size_t len = strlen(input);
291 for (walk = input; ((size_t)(walk - input) < len) && (blanks < amount); walk++)
292 if (*walk == character)
295 return (walk == input ? walk : walk-1);
299 * Get battery information from /sys. Note that it uses the design capacity to
300 * calculate the percentage, not the last full capacity, so you can see how
301 * worn off your battery is.
304 static char *get_battery_info(struct battery *bat) {
306 static char part[512];
309 int full_design = -1,
312 charging_status_t status = CS_DISCHARGING;
314 if ((fd = open(bat->path, O_RDONLY)) == -1)
315 return "No battery found";
317 memset(part, 0, sizeof(part));
318 (void)read(fd, buf, sizeof(buf));
319 for (walk = buf, last = buf; (walk-buf) < 1024; walk++) {
328 if (BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_NOW") ||
329 BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_NOW"))
330 remaining = atoi(walk+1);
331 else if (BEGINS_WITH(last, "POWER_SUPPLY_CURRENT_NOW"))
332 present_rate = atoi(walk+1);
333 else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Charging"))
334 status = CS_CHARGING;
335 else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Full"))
338 /* The only thing left is the full capacity */
339 if (bat->use_last_full) {
340 if (!BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_FULL") &&
341 !BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_FULL"))
344 if (!BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_FULL_DESIGN") &&
345 !BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_FULL_DESIGN"))
349 full_design = atoi(walk+1);
354 if ((full_design == 1) || (remaining == -1))
357 if (present_rate > 0) {
358 float remaining_time;
359 int seconds, hours, minutes;
360 if (status == CS_CHARGING)
361 remaining_time = ((float)full_design - (float)remaining) / (float)present_rate;
362 else if (status == CS_DISCHARGING)
363 remaining_time = ((float)remaining / (float)present_rate);
364 else remaining_time = 0;
366 seconds = (int)(remaining_time * 3600.0);
367 hours = seconds / 3600;
368 seconds -= (hours * 3600);
369 minutes = seconds / 60;
370 seconds -= (minutes * 60);
372 (void)snprintf(part, sizeof(part), "%s %.02f%% %02d:%02d:%02d",
373 (status == CS_CHARGING ? "CHR" :
374 (status == CS_DISCHARGING ? "BAT" : "FULL")),
375 (((float)remaining / (float)full_design) * 100),
376 max(hours, 0), max(minutes, 0), max(seconds, 0));
378 (void)snprintf(part, sizeof(part), "%s %.02f%%",
379 (status == CS_CHARGING ? "CHR" :
380 (status == CS_DISCHARGING ? "BAT" : "FULL")),
381 (((float)remaining / (float)full_design) * 100));
387 * Return the IP address for the given interface or "no IP" if the
388 * interface is up and running but hasn't got an IP address yet
391 static const char *get_ip_address(const char *interface) {
392 static char part[512];
394 struct sockaddr_in addr;
395 socklen_t len = sizeof(struct sockaddr_in);
396 memset(part, 0, sizeof(part));
398 /* First check if the interface is running */
399 (void)strcpy(ifr.ifr_name, interface);
400 if (ioctl(general_socket, SIOCGIFFLAGS, &ifr) < 0 ||
401 !(ifr.ifr_flags & IFF_RUNNING))
404 /* Interface is up, get the IP address */
405 (void)strcpy(ifr.ifr_name, interface);
406 ifr.ifr_addr.sa_family = AF_INET;
407 if (ioctl(general_socket, SIOCGIFADDR, &ifr) < 0)
410 memcpy(&addr, &ifr.ifr_addr, len);
411 (void)inet_ntop(AF_INET, &addr.sin_addr.s_addr, part, len);
412 if (strlen(part) == 0)
413 (void)snprintf(part, sizeof(part), "no IP");
419 * Just parses /proc/net/wireless looking for lines beginning with
420 * wlan_interface, extracting the quality of the link and adding the
421 * current IP address of wlan_interface.
424 static char *get_wireless_info() {
426 static char part[512];
429 memset(buf, 0, sizeof(buf));
430 memset(part, 0, sizeof(part));
432 if ((fd = open("/proc/net/wireless", O_RDONLY)) == -1)
433 die("Could not open /proc/net/wireless\n");
434 (void)read(fd, buf, sizeof(buf));
437 interfaces = skip_character(buf, '\n', 1) + 1;
438 while ((interfaces = skip_character(interfaces, '\n', 1)+1) < buf+strlen(buf)) {
439 while (isspace((int)*interfaces))
441 if (!BEGINS_WITH(interfaces, wlan_interface))
444 if (sscanf(interfaces, "%*[^:]: 0000 %d", &quality) != 1)
446 if ((quality == UCHAR_MAX) || (quality == 0)) {
448 (void)snprintf(part, sizeof(part), "%sW: down", color("#FF0000"));
449 else (void)snprintf(part, sizeof(part), "W: down");
450 } else (void)snprintf(part, sizeof(part), "%sW: (%03d%%) %s",
451 color("#00FF00"), quality, get_ip_address(wlan_interface));
459 * Combines ethernet IP addresses and speed (if requested) for displaying
462 static char *get_eth_info() {
463 static char part[512];
464 const char *ip_address = get_ip_address(eth_interface);
469 /* This code path requires root privileges */
471 struct ethtool_cmd ecmd;
473 ecmd.cmd = ETHTOOL_GSET;
474 (void)memset(&ifr, 0, sizeof(ifr));
475 ifr.ifr_data = (caddr_t)&ecmd;
476 (void)strcpy(ifr.ifr_name, eth_interface);
477 if (ioctl(general_socket, SIOCETHTOOL, &ifr) == 0)
478 ethspeed = (ecmd.speed == USHRT_MAX ? 0 : ecmd.speed);
479 else get_ethspeed = false;
483 if (ip_address == NULL)
484 (void)snprintf(part, sizeof(part), "E: down");
487 (void)snprintf(part, sizeof(part), "E: %s (%d Mbit/s)", ip_address, ethspeed);
488 else (void)snprintf(part, sizeof(part), "E: %s", ip_address);
495 * Reads the CPU temperature from /sys/class/thermal/thermal_zone0/temp and
496 * returns the temperature in degree celcius.
499 static char *get_cpu_temperature_info() {
500 static char part[16];
505 memset(buf, 0, sizeof(buf));
506 memset(part, 0, sizeof(part));
508 if ((fd = open(thermal_zone, O_RDONLY)) == -1)
509 die("Could not open %s\n", thermal_zone);
510 (void)read(fd, buf, sizeof(buf));
513 if (sscanf(buf, "%d", &temp) != 1)
514 (void)snprintf(part, sizeof(part), "T: ? C");
516 (void)snprintf(part, sizeof(part), "T: %d C", (temp/1000));
522 * Checks if the PID in path is still valid by checking:
523 * (Linux) if /proc/<pid> exists
524 * (NetBSD) if sysctl returns process infos for this pid
527 static bool process_runs(const char *path) {
529 static glob_t globbuf;
531 memset(pidbuf, 0, sizeof(pidbuf));
533 if (glob(path, GLOB_NOCHECK | GLOB_TILDE, NULL, &globbuf) < 0)
534 die("glob() failed\n");
535 fd = open((globbuf.gl_pathc > 0 ? globbuf.gl_pathv[0] : path), O_RDONLY);
539 (void)read(fd, pidbuf, sizeof(pidbuf));
545 (void)snprintf(procbuf, sizeof(procbuf), "/proc/%ld", strtol(pidbuf, NULL, 10));
546 return (stat(procbuf, &statbuf) >= 0);
548 /* TODO: correctly check for NetBSD. Evaluate if this runs on OpenBSD/FreeBSD */
549 struct kinfo_proc info;
550 size_t length = sizeof(struct kinfo_proc);
551 int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, strtol(pidbuf, NULL, 10) };
552 if (sysctl(mib, 4, &info, &length, NULL, 0) < 0)
554 return (length != 0);
559 * Reads the configuration from the given file
562 static int load_configuration(const char *configfile) {
563 #define OPT(x) else if (strcasecmp(dest_name, x) == 0)
565 /* check if the file exists */
567 if (stat(configfile, &buf) < 0)
571 FILE *handle = fopen(configfile, "r");
573 die("Could not open configfile\n");
574 char dest_name[512], dest_value[512], whole_buffer[1026];
576 while (!feof(handle)) {
578 if ((ret = fgets(whole_buffer, 1024, handle)) == whole_buffer) {
579 /* sscanf implicitly strips whitespace */
580 if (sscanf(whole_buffer, "%s %[^\n]", dest_name, dest_value) < 1)
582 } else if (ret != NULL)
583 die("Could not read line in configuration file\n");
585 /* skip comments and empty lines */
586 if (dest_name[0] == '#' || strlen(dest_name) < 3)
590 wlan_interface = strdup(dest_value);
592 eth_interface = strdup(dest_value);
594 time_format = strdup(dest_value);
596 struct battery *new = calloc(1, sizeof(struct battery));
598 die("Could not allocate memory\n");
599 if (asprintf(&(new->path), "/sys/class/power_supply/BAT%d/uevent", atoi(dest_value)) == -1)
600 die("Could not build battery path\n");
602 /* check if flags were specified for this battery */
603 if (strstr(dest_value, ",") != NULL) {
604 char *flags = strstr(dest_value, ",");
607 new->use_last_full = true;
609 SIMPLEQ_INSERT_TAIL(&batteries, new, batteries);
614 OPT("get_cpu_temperature") {
615 get_cpu_temperature = true;
616 if (strlen(dest_value) > 0) {
617 if (asprintf(&thermal_zone, "/sys/class/thermal/thermal_zone%d/temp", atoi(dest_value)) == -1)
618 die("Could not build thermal_zone path\n");
620 if (asprintf(&thermal_zone, "/sys/class/thermal/thermal_zone0/temp") == -1)
621 die("Could not build thermal_zone path\n");
624 wmii_normcolors = strdup(dest_value);
626 interval = atoi(dest_value);
630 static glob_t globbuf;
632 if (glob(dest_value, GLOB_NOCHECK | GLOB_TILDE, NULL, &globbuf) < 0)
633 die("glob() failed\n");
634 wmii_path = strdup(globbuf.gl_pathc > 0 ? globbuf.gl_pathv[0] : dest_value);
637 if ((stat(wmii_path, &stbuf)) == -1) {
638 fprintf(stderr, "Warning: wmii_path contains an invalid path\n");
640 wmii_path = strdup(dest_value);
642 if (wmii_path[strlen(wmii_path)-1] != '/')
643 die("wmii_path is not terminated by /\n");
648 char *name = strdup(dest_value);
653 num_run_watches += 2;
654 run_watches = realloc(run_watches, sizeof(char*) * num_run_watches);
655 run_watches[num_run_watches-2] = name;
656 run_watches[num_run_watches-1] = path;
660 #define SET_ORDER(opt, idx) { if (strcasecmp(token, opt) == 0) sprintf(order[idx], "%d", c++); }
663 walk = token = dest_value;
664 while (*walk != '\0') {
665 while ((*walk != ',') && (*walk != '\0'))
668 SET_ORDER("run", ORDER_RUN);
669 SET_ORDER("wlan", ORDER_WLAN);
670 SET_ORDER("eth", ORDER_ETH);
671 SET_ORDER("battery", ORDER_BATTERY);
672 SET_ORDER("cpu_temperature", ORDER_CPU_TEMPERATURE);
673 SET_ORDER("load", ORDER_LOAD);
674 SET_ORDER("time", ORDER_TIME);
676 while (isspace((int)(*token)))
683 die("Unknown configfile option: %s\n", dest_name);
689 if (wmii_path == NULL)
696 int main(int argc, char *argv[]) {
701 char *configfile = PREFIX "/etc/i3status.conf";
702 int o, option_index = 0;
703 struct option long_options[] = {
704 {"config", required_argument, 0, 'c'},
705 {"help", no_argument, 0, 'h'},
709 SIMPLEQ_INIT(&batteries);
711 while ((o = getopt_long(argc, argv, "c:h", long_options, &option_index)) != -1)
714 else if ((char)o == 'h') {
715 printf("i3status (c) 2008-2009 Michael Stapelberg\n"
716 "Syntax: %s [-c <configfile>]\n", argv[0]);
720 if (load_configuration(configfile) < 0)
725 if ((general_socket = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
726 die("Could not create socket\n");
729 for (i = 0; i < num_run_watches; i += 2) {
730 bool running = process_runs(run_watches[i+1]);
732 snprintf(part, sizeof(part), "%s%s: %s",
733 (running ? color("#00FF00") : color("#FF0000")),
735 (running ? "yes" : "no"));
736 else snprintf(part, sizeof(part), "%s: %s", run_watches[i], (running ? "yes" : "no"));
737 snprintf(pathbuf, sizeof(pathbuf), "%s%s", order[ORDER_RUN], run_watches[i]);
738 write_to_statusbar(pathbuf, part, false);
742 write_to_statusbar(concat(order[ORDER_WLAN], "wlan"), get_wireless_info(), false);
744 write_to_statusbar(concat(order[ORDER_ETH], "eth"), get_eth_info(), false);
745 struct battery *current_battery;
746 SIMPLEQ_FOREACH(current_battery, &batteries, batteries) {
747 write_to_statusbar(concat(order[ORDER_BATTERY], "battery"), get_battery_info(current_battery), false);
749 if (get_cpu_temperature)
750 write_to_statusbar(concat(order[ORDER_CPU_TEMPERATURE], "cpu_temperature"), get_cpu_temperature_info(), false);
755 if ((load_avg = open("/proc/loadavg", O_RDONLY)) == -1)
756 die("Could not open /proc/loadavg\n");
757 (void)read(load_avg, part, sizeof(part));
758 (void)close(load_avg);
759 *skip_character(part, ' ', 3) = '\0';
761 /* TODO: correctly check for NetBSD, check if it works the same on *BSD */
763 size_t length = sizeof(struct loadavg);
764 int mib[2] = { CTL_VM, VM_LOADAVG };
765 if (sysctl(mib, 2, &load, &length, NULL, 0) < 0)
766 die("Could not sysctl({ CTL_VM, VM_LOADAVG })\n");
767 double scale = load.fscale;
768 (void)snprintf(part, sizeof(part), "%.02f %.02f %.02f",
769 (double)load.ldavg[0] / scale,
770 (double)load.ldavg[1] / scale,
771 (double)load.ldavg[2] / scale);
773 write_to_statusbar(concat(order[ORDER_LOAD], "load"), part, !time_format);
776 /* Get date & time */
777 time_t current_time = time(NULL);
778 struct tm *current_tm = localtime(¤t_time);
779 (void)strftime(part, sizeof(part), time_format, current_tm);
780 write_to_statusbar(concat(order[ORDER_TIME], "time"), part, true);