]> git.sur5r.net Git - i3/i3status/blobdiff - wmiistatus.c
Add code for getting process status (running/not) and load on NetBSD
[i3/i3status] / wmiistatus.c
index 48c504c7219016569e4103266c51f486d3021c28..5c6630201d993683b66eb12b0178ded18f807c60 100644 (file)
@@ -2,7 +2,7 @@
  * Generates a status line for use with wmii or other minimal window managers
  *
  *
- * Copyright (c) 2008 Michael Stapelberg and contributors
+ * Copyright (c) 2008-2009 Michael Stapelberg and contributors
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without modification,
@@ -41,6 +41,7 @@
 #include <stdarg.h>
 #include <unistd.h>
 #include <stdlib.h>
+#include <limits.h>
 #include <ctype.h>
 #include <net/if.h>
 #include <sys/ioctl.h>
 #include <glob.h>
 #include <dirent.h>
 #include <getopt.h>
+
+#ifdef LINUX
 #include <linux/ethtool.h>
 #include <linux/sockios.h>
-
+#else
+/* TODO: correctly check for *BSD */
+#include <sys/param.h>
+#include <sys/sysctl.h>
+#include <sys/resource.h>
+#endif
 
 #define _IS_WMIISTATUS_C
 #include "wmiistatus.h"
 #undef _IS_WMIISTATUS_C
 #include "config.h"
 
+/* socket file descriptor for general purposes */
+static int general_socket;
+
 /*
  * This function just concats two strings in place, it should only be used
  * for concatting order to the name of a file or concatting color codes.
@@ -97,14 +108,21 @@ static void cleanup_rbar_dir() {
 /*
  * Creates the specified file in wmii's /rbar directory with
  * correct modes and initializes colors if colormode is enabled
- * '
+ *
  */
 static void create_file(const char *name) {
        char pathbuf[strlen(wmii_path)+256+1];
        int fd;
+       int flags = O_CREAT | O_WRONLY;
+       struct stat statbuf;
 
        (void)snprintf(pathbuf, sizeof(pathbuf), "%s%s", wmii_path, name);
-       if ((fd = open(pathbuf, O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR)) < 0)
+
+       /* Overwrite file's contents if it exists */
+       if (stat(pathbuf, &statbuf) >= 0)
+               flags |= O_TRUNC;
+
+       if ((fd = open(pathbuf, flags, S_IRUSR | S_IWUSR)) < 0)
                exit(EXIT_FAILURE);
        if (use_colors) {
                char *tmp = concat("#888888 ", wmii_normcolors);
@@ -114,6 +132,11 @@ static void create_file(const char *name) {
        (void)close(fd);
 }
 
+/*
+ * Waits until wmii_path/rbar exists (= the filesystem gets mounted),
+ * cleans up all files and creates the needed files
+ *
+ */
 static void setup(void) {
        unsigned int i;
        struct stat statbuf;
@@ -136,7 +159,6 @@ static void setup(void) {
                snprintf(pathbuf, sizeof(pathbuf), "%s%s", order[ORDER_RUN], run_watches[i]);
                create_file(pathbuf);
        }
-
 }
 
 /*
@@ -173,17 +195,23 @@ static void write_error_to_statusbar(const char *message) {
  *
  */
 void die(const char *fmt, ...) {
-       char buffer[512];
-       va_list ap;
-       va_start(ap, fmt);
-       (void)vsnprintf(buffer, sizeof(buffer), fmt, ap);
-       va_end(ap);
+       if (wmii_path != NULL) {
+               char buffer[512];
+               va_list ap;
+               va_start(ap, fmt);
+               (void)vsnprintf(buffer, sizeof(buffer), fmt, ap);
+               va_end(ap);
 
-       if (wmii_path != NULL)
                write_error_to_statusbar(buffer);
+       }
        exit(EXIT_FAILURE);
 }
 
+/*
+ * Skip the given character for exactly 'amount' times, returns
+ * a pointer to the first non-'character' character in 'input'.
+ *
+ */
 static char *skip_character(char *input, char character, int amount) {
        char *walk;
        size_t len = strlen(input);
@@ -197,8 +225,9 @@ static char *skip_character(char *input, char character, int amount) {
 }
 
 /*
- * Get battery information from /sys. Note that it uses the design capacity to calculate the percentage,
- * not the full capacity.
+ * Get battery information from /sys. Note that it uses the design capacity to
+ * calculate the percentage, not the last full capacity, so you can see how
+ * worn off your battery is.
  *
  */
 static char *get_battery_info() {
@@ -212,7 +241,7 @@ static char *get_battery_info() {
        charging_status_t status = CS_DISCHARGING;
 
        if ((fd = open(battery_path, O_RDONLY)) == -1)
-               die("Could not open %s", battery_path);
+               return "No battery found";
 
        memset(part, 0, sizeof(part));
        (void)read(fd, buf, sizeof(buf));
@@ -235,17 +264,13 @@ static char *get_battery_info() {
        (void)close(fd);
 
        if ((full_design != -1) && (remaining != -1) && (present_rate != -1)) {
-               float remaining_time, perc;
+               float remaining_time;
                int seconds, hours, minutes;
                if (status == CS_CHARGING)
                        remaining_time = ((float)full_design - (float)remaining) / (float)present_rate;
                else if (status == CS_DISCHARGING)
                        remaining_time = ((float)remaining / (float)present_rate);
-               else {
-                       (void)snprintf(part, sizeof(part), "FULL");
-                       return part;
-               }
-               perc = ((float)remaining / (float)full_design);
+               else remaining_time = 0;
 
                seconds = (int)(remaining_time * 3600.0);
                hours = seconds / 3600;
@@ -254,14 +279,18 @@ static char *get_battery_info() {
                seconds -= (minutes * 60);
 
                (void)snprintf(part, sizeof(part), "%s %.02f%% %02d:%02d:%02d",
-                       (status == CS_CHARGING? "CHR" : "BAT"),
-                       (perc * 100), hours, minutes, seconds);
+                       (status == CS_CHARGING ? "CHR" :
+                        (status == CS_DISCHARGING ? "BAT" : "FULL")),
+                       (((float)remaining / (float)full_design) * 100),
+                       hours, minutes, seconds);
        }
        return part;
 }
 
 /*
- * Just parses /proc/net/wireless
+ * Just parses /proc/net/wireless looking for lines beginning with
+ * wlan_interface, extracting the quality of the link and adding the
+ * current IP address of wlan_interface.
  *
  */
 static char *get_wireless_info() {
@@ -273,97 +302,80 @@ static char *get_wireless_info() {
        memset(part, 0, sizeof(part));
 
        if ((fd = open("/proc/net/wireless", O_RDONLY)) == -1)
-               die("Could not open /proc/net/wireless");
+               die("Could not open /proc/net/wireless\n");
        (void)read(fd, buf, sizeof(buf));
        (void)close(fd);
 
-       interfaces = skip_character(buf, '\n', 2) + 1;
-       while (interfaces < buf+strlen(buf)) {
+       interfaces = skip_character(buf, '\n', 1) + 1;
+       while ((interfaces = skip_character(interfaces, '\n', 1)+1) < buf+strlen(buf)) {
                while (isspace((int)*interfaces))
                        interfaces++;
-               if (strncmp(interfaces, wlan_interface, strlen(wlan_interface)) == 0) {
-                       int quality;
-                       /* Skip status field (0000) */
-                       interfaces += strlen(wlan_interface) + 2;
-                       interfaces = skip_character(interfaces, ' ', 1);
-                       while (isspace((int)*interfaces))
-                               interfaces++;
-                       quality = atoi(interfaces);
-                       /* For some reason, I get 255 sometimes */
-                       if ((quality == 255) || (quality == 0)) {
+               if (!BEGINS_WITH(interfaces, wlan_interface))
+                       continue;
+               int quality;
+               if (sscanf(interfaces, "%*[^:]: 0000 %d", &quality) != 1)
+                       continue;
+               if ((quality == UCHAR_MAX) || (quality == 0)) {
                        if (use_colors)
-                               (void)snprintf(part, sizeof(part), "%s%s", concat("#FF0000 ", wmii_normcolors), " W: down");
+                               (void)snprintf(part, sizeof(part), "%s%s",
+                                       concat("#FF0000 ", wmii_normcolors), " W: down");
                        else (void)snprintf(part, sizeof(part), "W: down");
-
-                       } else {
-                               const char *ip_address;
-                               (void)snprintf(part, sizeof(part), "W: (%02d%%) ", quality);
-                               ip_address = get_ip_address(wlan_interface);
-                               strcpy(part+strlen(part), ip_address);
-                       }
-
-                       return part;
-               }
-               interfaces = skip_character(interfaces, '\n', 1) + 1;
+               } else (void)snprintf(part, sizeof(part), "W: (%03d%%) %s",
+                               quality, get_ip_address(wlan_interface));
+               return part;
        }
 
        return part;
 }
 
+/*
+ * Return the IP address for the given interface or "no IP" if the
+ * interface is up and running but hasn't got an IP address yet
+ *
+ */
 static const char *get_ip_address(const char *interface) {
        static char part[512];
        struct ifreq ifr;
-       int fd;
+       struct sockaddr_in addr;
+       socklen_t len = sizeof(struct sockaddr_in);
        memset(part, 0, sizeof(part));
 
-       fd = socket(AF_INET, SOCK_DGRAM, 0);
-
-       strcpy(ifr.ifr_name, interface);
-       if (ioctl(fd, SIOCGIFFLAGS, &ifr) < 0)
-               die("Could not get interface flags (SIOCGIFFLAGS)");
-
-       if (!(ifr.ifr_flags & IFF_UP) ||
-           !(ifr.ifr_flags & IFF_RUNNING)) {
-               close(fd);
+       (void)strcpy(ifr.ifr_name, interface);
+       ifr.ifr_addr.sa_family = AF_INET;
+       if (ioctl(general_socket, SIOCGIFADDR, &ifr) < 0)
                return NULL;
-       }
 
-       strcpy(ifr.ifr_name, interface);
-       ifr.ifr_addr.sa_family = AF_INET;
-       if (ioctl(fd, SIOCGIFADDR, &ifr) == 0) {
-               struct sockaddr_in addr;
-               memcpy(&addr, &ifr.ifr_addr, sizeof(struct sockaddr_in));
-               (void)inet_ntop(AF_INET, &addr.sin_addr.s_addr, part, (socklen_t)sizeof(struct sockaddr_in));
-               if (strlen(part) == 0)
-                       snprintf(part, sizeof(part), "no IP");
-       }
+       memcpy(&addr, &ifr.ifr_addr, len);
+       (void)inet_ntop(AF_INET, &addr.sin_addr.s_addr, part, len);
+       if (strlen(part) == 0)
+               (void)snprintf(part, sizeof(part), "no IP");
 
-       (void)close(fd);
        return part;
 }
 
+/*
+ * Combines ethernet IP addresses and speed (if requested) for displaying
+ *
+ */
 static char *get_eth_info() {
        static char part[512];
        const char *ip_address = get_ip_address(eth_interface);
        int ethspeed = 0;
 
        if (get_ethspeed) {
+#ifdef LINUX
+               /* This code path requires root privileges */
                struct ifreq ifr;
                struct ethtool_cmd ecmd;
-               int fd, err;
-
-               if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
-                       write_error_to_statusbar("Could not open socket");
 
                ecmd.cmd = ETHTOOL_GSET;
                (void)memset(&ifr, 0, sizeof(ifr));
                ifr.ifr_data = (caddr_t)&ecmd;
                (void)strcpy(ifr.ifr_name, eth_interface);
-               if ((err = ioctl(fd, SIOCETHTOOL, &ifr)) == 0)
-                       ethspeed = ecmd.speed;
-               else write_error_to_statusbar("Could not get interface speed. Insufficient privileges?");
-
-               (void)close(fd);
+               if (ioctl(general_socket, SIOCETHTOOL, &ifr) == 0)
+                       ethspeed = (ecmd.speed == USHRT_MAX ? 0 : ecmd.speed);
+               else get_ethspeed = false;
+#endif
        }
 
        if (ip_address == NULL)
@@ -383,37 +395,38 @@ static char *get_eth_info() {
  */
 static bool process_runs(const char *path) {
        char pidbuf[512],
-            procbuf[512],
-            *walk;
-       ssize_t n;
+            procbuf[512];
        static glob_t globbuf;
        struct stat statbuf;
-       const char *real_path;
        int fd;
+       memset(pidbuf, 0, sizeof(pidbuf));
 
        if (glob(path, GLOB_NOCHECK | GLOB_TILDE, NULL, &globbuf) < 0)
-               die("glob() failed");
-       real_path = (globbuf.gl_pathc > 0 ? globbuf.gl_pathv[0] : path);
-       fd = open(real_path, O_RDONLY);
+               die("glob() failed\n");
+       fd = open((globbuf.gl_pathc > 0 ? globbuf.gl_pathv[0] : path), O_RDONLY);
        globfree(&globbuf);
        if (fd < 0)
                return false;
-       if ((n = read(fd, pidbuf, sizeof(pidbuf))) > 0)
-               pidbuf[n] = '\0';
+       (void)read(fd, pidbuf, sizeof(pidbuf));
        (void)close(fd);
-       for (walk = pidbuf; *walk != '\0'; walk++)
-               if (!isdigit((int)(*walk))) {
-                       *walk = '\0';
-                       break;
-               }
-       (void)snprintf(procbuf, sizeof(procbuf), "/proc/%s", pidbuf);
+
+#ifdef LINUX
+       (void)snprintf(procbuf, sizeof(procbuf), "/proc/%ld", strtol(pidbuf, NULL, 10));
        return (stat(procbuf, &statbuf) >= 0);
+#else
+       /* TODO: correctly check for NetBSD. Evaluate if this runs on OpenBSD/FreeBSD */
+       struct kinfo_proc info;
+       size_t length = sizeof(struct kinfo_proc);
+       int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, strtol(pidbuf, NULL, 10) };
+       if (sysctl(mib, 4, &info, &length, NULL, 0) < 0)
+               return false;
+       return (length != 0);
+#endif
 }
 
 int main(int argc, char *argv[]) {
        char part[512],
-            pathbuf[512],
-            *end;
+            pathbuf[512];
        unsigned int i;
        int load_avg;
 
@@ -421,18 +434,27 @@ int main(int argc, char *argv[]) {
        int o, option_index = 0;
        struct option long_options[] = {
                {"config", required_argument, 0, 'c'},
+               {"help", no_argument, 0, 'h'},
                {0, 0, 0, 0}
        };
 
-       while ((o = getopt_long(argc, argv, "c:", long_options, &option_index)) != -1)
+       while ((o = getopt_long(argc, argv, "c:h", long_options, &option_index)) != -1)
                if ((char)o == 'c')
                        configfile = optarg;
+               else if ((char)o == 'h') {
+                       printf("wmiistatus (c) 2008-2009 Michael Stapelberg\n"
+                               "Syntax: %s [-c <configfile>]\n", argv[0]);
+                       return 0;
+               }
 
        if (load_configuration(configfile) < 0)
                return EXIT_FAILURE;
 
        setup();
 
+       if ((general_socket = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
+               die("Could not create socket\n");
+
        while (1) {
                for (i = 0; i < num_run_watches; i += 2) {
                        bool running = process_runs(run_watches[i+1]);
@@ -456,12 +478,25 @@ int main(int argc, char *argv[]) {
                        write_to_statusbar(concat(order[ORDER_BATTERY], "battery"), get_battery_info());
 
                /* Get load */
+#ifdef LINUX
                if ((load_avg = open("/proc/loadavg", O_RDONLY)) == -1)
-                       die("Could not open /proc/loadavg");
+                       die("Could not open /proc/loadavg\n");
                (void)read(load_avg, part, sizeof(part));
                (void)close(load_avg);
-               end = skip_character(part, ' ', 3);
-               *end = '\0';
+               *skip_character(part, ' ', 3) = '\0';
+#else
+               /* TODO: correctly check for NetBSD, check if it works the same on *BSD */
+               struct loadavg load;
+               size_t length = sizeof(struct loadavg);
+               int mib[2] = { CTL_VM, VM_LOADAVG };
+               if (sysctl(mib, 2, &load, &length, NULL, 0) < 0)
+                       die("Could not sysctl({ CTL_VM, VM_LOADAVG })\n");
+               double scale = load.fscale;
+               (void)snprintf(part, sizeof(part), "%.02f %.02f %.02f",
+                               (double)load.ldavg[0] / scale,
+                               (double)load.ldavg[1] / scale,
+                               (double)load.ldavg[2] / scale);
+#endif
                write_to_statusbar(concat(order[ORDER_LOAD], "load"), part);
 
                if (time_format) {