]> git.sur5r.net Git - i3/i3status/blob - wmiistatus.c
Add code for getting process status (running/not) and load on NetBSD
[i3/i3status] / wmiistatus.c
1 /*
2  * Generates a status line for use with wmii or other minimal window managers
3  *
4  *
5  * Copyright (c) 2008-2009 Michael Stapelberg and contributors
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without modification,
9  * are permitted provided that the following conditions are met:
10  *
11  * * Redistributions of source code must retain the above copyright notice, this
12  *   list of conditions and the following disclaimer.
13  *
14  * * Redistributions in binary form must reproduce the above copyright notice, this
15  *   list of conditions and the following disclaimer in the documentation and/or other
16  *   materials provided with the distribution.
17  *
18  * * Neither the name of Michael Stapelberg nor the names of contributors
19  *   may be used to endorse or promote products derived from this software without
20  *   specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
23  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
24  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
25  * SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
27  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
28  * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
30  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
31  * DAMAGE.
32  *
33  */
34 #include <sys/types.h>
35 #include <sys/stat.h>
36 #include <fcntl.h>
37 #include <string.h>
38 #include <stdio.h>
39 #include <time.h>
40 #include <stdbool.h>
41 #include <stdarg.h>
42 #include <unistd.h>
43 #include <stdlib.h>
44 #include <limits.h>
45 #include <ctype.h>
46 #include <net/if.h>
47 #include <sys/ioctl.h>
48 #include <sys/socket.h>
49 #include <netinet/in.h>
50 #include <arpa/inet.h>
51 #include <glob.h>
52 #include <dirent.h>
53 #include <getopt.h>
54
55 #ifdef LINUX
56 #include <linux/ethtool.h>
57 #include <linux/sockios.h>
58 #else
59 /* TODO: correctly check for *BSD */
60 #include <sys/param.h>
61 #include <sys/sysctl.h>
62 #include <sys/resource.h>
63 #endif
64
65 #define _IS_WMIISTATUS_C
66 #include "wmiistatus.h"
67 #undef _IS_WMIISTATUS_C
68 #include "config.h"
69
70 /* socket file descriptor for general purposes */
71 static int general_socket;
72
73 /*
74  * This function just concats two strings in place, it should only be used
75  * for concatting order to the name of a file or concatting color codes.
76  * Otherwise, the buffer size would have to be increased.
77  *
78  */
79 static char *concat(const char *str1, const char *str2) {
80         static char concatbuf[32];
81         (void)snprintf(concatbuf, sizeof(concatbuf), "%s%s", str1, str2);
82         return concatbuf;
83 }
84
85 /*
86  * Cleans wmii's /rbar directory by deleting all regular files
87  *
88  */
89 static void cleanup_rbar_dir() {
90         struct dirent *ent;
91         DIR *dir;
92         char pathbuf[strlen(wmii_path)+256+1];
93
94         if ((dir = opendir(wmii_path)) == NULL)
95                 exit(EXIT_FAILURE);
96
97         while ((ent = readdir(dir)) != NULL) {
98                 if (ent->d_type == DT_REG) {
99                         (void)snprintf(pathbuf, sizeof(pathbuf), "%s%s", wmii_path, ent->d_name);
100                         if (unlink(pathbuf) == -1)
101                                 exit(EXIT_FAILURE);
102                 }
103         }
104
105         (void)closedir(dir);
106 }
107
108 /*
109  * Creates the specified file in wmii's /rbar directory with
110  * correct modes and initializes colors if colormode is enabled
111  *
112  */
113 static void create_file(const char *name) {
114         char pathbuf[strlen(wmii_path)+256+1];
115         int fd;
116         int flags = O_CREAT | O_WRONLY;
117         struct stat statbuf;
118
119         (void)snprintf(pathbuf, sizeof(pathbuf), "%s%s", wmii_path, name);
120
121         /* Overwrite file's contents if it exists */
122         if (stat(pathbuf, &statbuf) >= 0)
123                 flags |= O_TRUNC;
124
125         if ((fd = open(pathbuf, flags, S_IRUSR | S_IWUSR)) < 0)
126                 exit(EXIT_FAILURE);
127         if (use_colors) {
128                 char *tmp = concat("#888888 ", wmii_normcolors);
129                 if (write(fd, tmp, strlen(tmp)) != (ssize_t)strlen(tmp))
130                         exit(EXIT_FAILURE);
131         }
132         (void)close(fd);
133 }
134
135 /*
136  * Waits until wmii_path/rbar exists (= the filesystem gets mounted),
137  * cleans up all files and creates the needed files
138  *
139  */
140 static void setup(void) {
141         unsigned int i;
142         struct stat statbuf;
143         char pathbuf[512];
144
145         /* Wait until wmii_path/rbar exists */
146         for (; stat(wmii_path, &statbuf) < 0; sleep(interval));
147
148         cleanup_rbar_dir();
149         if (wlan_interface)
150                 create_file(concat(order[ORDER_WLAN],"wlan"));
151         if (eth_interface)
152                 create_file(concat(order[ORDER_ETH],"eth"));
153         if (battery_path)
154                 create_file(concat(order[ORDER_BATTERY],"battery"));
155         create_file(concat(order[ORDER_LOAD],"load"));
156         if (time_format)
157                 create_file(concat(order[ORDER_TIME],"time"));
158         for (i = 0; i < num_run_watches; i += 2) {
159                 snprintf(pathbuf, sizeof(pathbuf), "%s%s", order[ORDER_RUN], run_watches[i]);
160                 create_file(pathbuf);
161         }
162 }
163
164 /*
165  * Writes the given message in the corresponding file in wmii's /rbar directory
166  *
167  */
168 static void write_to_statusbar(const char *name, const char *message) {
169         char pathbuf[strlen(wmii_path)+256+1];
170         int fd;
171
172         (void)snprintf(pathbuf, sizeof(pathbuf), "%s%s", wmii_path, name);
173         if ((fd = open(pathbuf, O_RDWR)) == -1) {
174                 /* Try to re-setup stuff and just continue */
175                 setup();
176                 return;
177         }
178         if (write(fd, message, strlen(message)) != (ssize_t)strlen(message))
179                 exit(EXIT_FAILURE);
180         (void)close(fd);
181 }
182
183 /*
184  * Writes an errormessage to statusbar
185  *
186  */
187 static void write_error_to_statusbar(const char *message) {
188         cleanup_rbar_dir();
189         create_file("error");
190         write_to_statusbar("error", message);
191 }
192
193 /*
194  * Write errormessage to statusbar and exit
195  *
196  */
197 void die(const char *fmt, ...) {
198         if (wmii_path != NULL) {
199                 char buffer[512];
200                 va_list ap;
201                 va_start(ap, fmt);
202                 (void)vsnprintf(buffer, sizeof(buffer), fmt, ap);
203                 va_end(ap);
204
205                 write_error_to_statusbar(buffer);
206         }
207         exit(EXIT_FAILURE);
208 }
209
210 /*
211  * Skip the given character for exactly 'amount' times, returns
212  * a pointer to the first non-'character' character in 'input'.
213  *
214  */
215 static char *skip_character(char *input, char character, int amount) {
216         char *walk;
217         size_t len = strlen(input);
218         int blanks = 0;
219
220         for (walk = input; ((size_t)(walk - input) < len) && (blanks < amount); walk++)
221                 if (*walk == character)
222                         blanks++;
223
224         return (walk == input ? walk : walk-1);
225 }
226
227 /*
228  * Get battery information from /sys. Note that it uses the design capacity to
229  * calculate the percentage, not the last full capacity, so you can see how
230  * worn off your battery is.
231  *
232  */
233 static char *get_battery_info() {
234         char buf[1024];
235         static char part[512];
236         char *walk, *last;
237         int fd;
238         int full_design = -1,
239             remaining = -1,
240             present_rate = -1;
241         charging_status_t status = CS_DISCHARGING;
242
243         if ((fd = open(battery_path, O_RDONLY)) == -1)
244                 return "No battery found";
245
246         memset(part, 0, sizeof(part));
247         (void)read(fd, buf, sizeof(buf));
248         for (walk = buf, last = buf; (walk-buf) < 1024; walk++)
249                 if (*walk == '=') {
250                         if (BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_FULL_DESIGN") ||
251                             BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_FULL_DESIGN"))
252                                 full_design = atoi(walk+1);
253                         else if (BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_NOW") ||
254                                  BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_NOW"))
255                                 remaining = atoi(walk+1);
256                         else if (BEGINS_WITH(last, "POWER_SUPPLY_CURRENT_NOW"))
257                                 present_rate = atoi(walk+1);
258                         else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Charging"))
259                                 status = CS_CHARGING;
260                         else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Full"))
261                                 status = CS_FULL;
262                 } else if (*walk == '\n')
263                         last = walk+1;
264         (void)close(fd);
265
266         if ((full_design != -1) && (remaining != -1) && (present_rate != -1)) {
267                 float remaining_time;
268                 int seconds, hours, minutes;
269                 if (status == CS_CHARGING)
270                         remaining_time = ((float)full_design - (float)remaining) / (float)present_rate;
271                 else if (status == CS_DISCHARGING)
272                         remaining_time = ((float)remaining / (float)present_rate);
273                 else remaining_time = 0;
274
275                 seconds = (int)(remaining_time * 3600.0);
276                 hours = seconds / 3600;
277                 seconds -= (hours * 3600);
278                 minutes = seconds / 60;
279                 seconds -= (minutes * 60);
280
281                 (void)snprintf(part, sizeof(part), "%s %.02f%% %02d:%02d:%02d",
282                         (status == CS_CHARGING ? "CHR" :
283                          (status == CS_DISCHARGING ? "BAT" : "FULL")),
284                         (((float)remaining / (float)full_design) * 100),
285                         hours, minutes, seconds);
286         }
287         return part;
288 }
289
290 /*
291  * Just parses /proc/net/wireless looking for lines beginning with
292  * wlan_interface, extracting the quality of the link and adding the
293  * current IP address of wlan_interface.
294  *
295  */
296 static char *get_wireless_info() {
297         char buf[1024];
298         static char part[512];
299         char *interfaces;
300         int fd;
301         memset(buf, 0, sizeof(buf));
302         memset(part, 0, sizeof(part));
303
304         if ((fd = open("/proc/net/wireless", O_RDONLY)) == -1)
305                 die("Could not open /proc/net/wireless\n");
306         (void)read(fd, buf, sizeof(buf));
307         (void)close(fd);
308
309         interfaces = skip_character(buf, '\n', 1) + 1;
310         while ((interfaces = skip_character(interfaces, '\n', 1)+1) < buf+strlen(buf)) {
311                 while (isspace((int)*interfaces))
312                         interfaces++;
313                 if (!BEGINS_WITH(interfaces, wlan_interface))
314                         continue;
315                 int quality;
316                 if (sscanf(interfaces, "%*[^:]: 0000 %d", &quality) != 1)
317                         continue;
318                 if ((quality == UCHAR_MAX) || (quality == 0)) {
319                         if (use_colors)
320                                 (void)snprintf(part, sizeof(part), "%s%s",
321                                         concat("#FF0000 ", wmii_normcolors), " W: down");
322                         else (void)snprintf(part, sizeof(part), "W: down");
323                 } else (void)snprintf(part, sizeof(part), "W: (%03d%%) %s",
324                                 quality, get_ip_address(wlan_interface));
325                 return part;
326         }
327
328         return part;
329 }
330
331 /*
332  * Return the IP address for the given interface or "no IP" if the
333  * interface is up and running but hasn't got an IP address yet
334  *
335  */
336 static const char *get_ip_address(const char *interface) {
337         static char part[512];
338         struct ifreq ifr;
339         struct sockaddr_in addr;
340         socklen_t len = sizeof(struct sockaddr_in);
341         memset(part, 0, sizeof(part));
342
343         (void)strcpy(ifr.ifr_name, interface);
344         ifr.ifr_addr.sa_family = AF_INET;
345         if (ioctl(general_socket, SIOCGIFADDR, &ifr) < 0)
346                 return NULL;
347
348         memcpy(&addr, &ifr.ifr_addr, len);
349         (void)inet_ntop(AF_INET, &addr.sin_addr.s_addr, part, len);
350         if (strlen(part) == 0)
351                 (void)snprintf(part, sizeof(part), "no IP");
352
353         return part;
354 }
355
356 /*
357  * Combines ethernet IP addresses and speed (if requested) for displaying
358  *
359  */
360 static char *get_eth_info() {
361         static char part[512];
362         const char *ip_address = get_ip_address(eth_interface);
363         int ethspeed = 0;
364
365         if (get_ethspeed) {
366 #ifdef LINUX
367                 /* This code path requires root privileges */
368                 struct ifreq ifr;
369                 struct ethtool_cmd ecmd;
370
371                 ecmd.cmd = ETHTOOL_GSET;
372                 (void)memset(&ifr, 0, sizeof(ifr));
373                 ifr.ifr_data = (caddr_t)&ecmd;
374                 (void)strcpy(ifr.ifr_name, eth_interface);
375                 if (ioctl(general_socket, SIOCETHTOOL, &ifr) == 0)
376                         ethspeed = (ecmd.speed == USHRT_MAX ? 0 : ecmd.speed);
377                 else get_ethspeed = false;
378 #endif
379         }
380
381         if (ip_address == NULL)
382                 (void)snprintf(part, sizeof(part), "E: down");
383         else {
384                 if (get_ethspeed)
385                         (void)snprintf(part, sizeof(part), "E: %s (%d Mbit/s)", ip_address, ethspeed);
386                 else (void)snprintf(part, sizeof(part), "E: %s", ip_address);
387         }
388
389         return part;
390 }
391
392 /*
393  * Checks if the PID in path is still valid by checking if /proc/<pid> exists
394  *
395  */
396 static bool process_runs(const char *path) {
397         char pidbuf[512],
398              procbuf[512];
399         static glob_t globbuf;
400         struct stat statbuf;
401         int fd;
402         memset(pidbuf, 0, sizeof(pidbuf));
403
404         if (glob(path, GLOB_NOCHECK | GLOB_TILDE, NULL, &globbuf) < 0)
405                 die("glob() failed\n");
406         fd = open((globbuf.gl_pathc > 0 ? globbuf.gl_pathv[0] : path), O_RDONLY);
407         globfree(&globbuf);
408         if (fd < 0)
409                 return false;
410         (void)read(fd, pidbuf, sizeof(pidbuf));
411         (void)close(fd);
412
413 #ifdef LINUX
414         (void)snprintf(procbuf, sizeof(procbuf), "/proc/%ld", strtol(pidbuf, NULL, 10));
415         return (stat(procbuf, &statbuf) >= 0);
416 #else
417         /* TODO: correctly check for NetBSD. Evaluate if this runs on OpenBSD/FreeBSD */
418         struct kinfo_proc info;
419         size_t length = sizeof(struct kinfo_proc);
420         int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, strtol(pidbuf, NULL, 10) };
421         if (sysctl(mib, 4, &info, &length, NULL, 0) < 0)
422                 return false;
423         return (length != 0);
424 #endif
425 }
426
427 int main(int argc, char *argv[]) {
428         char part[512],
429              pathbuf[512];
430         unsigned int i;
431         int load_avg;
432
433         char *configfile = PREFIX "/etc/wmiistatus.conf";
434         int o, option_index = 0;
435         struct option long_options[] = {
436                 {"config", required_argument, 0, 'c'},
437                 {"help", no_argument, 0, 'h'},
438                 {0, 0, 0, 0}
439         };
440
441         while ((o = getopt_long(argc, argv, "c:h", long_options, &option_index)) != -1)
442                 if ((char)o == 'c')
443                         configfile = optarg;
444                 else if ((char)o == 'h') {
445                         printf("wmiistatus (c) 2008-2009 Michael Stapelberg\n"
446                                 "Syntax: %s [-c <configfile>]\n", argv[0]);
447                         return 0;
448                 }
449
450         if (load_configuration(configfile) < 0)
451                 return EXIT_FAILURE;
452
453         setup();
454
455         if ((general_socket = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
456                 die("Could not create socket\n");
457
458         while (1) {
459                 for (i = 0; i < num_run_watches; i += 2) {
460                         bool running = process_runs(run_watches[i+1]);
461                         if (use_colors)
462                                 snprintf(part, sizeof(part), "%s %s: %s",
463                                         (running ?
464                                                 concat("#00FF00 ", wmii_normcolors) :
465                                                 concat("#FF0000 ", wmii_normcolors)),
466                                         run_watches[i],
467                                         (running ? "yes" : "no"));
468                         else snprintf(part, sizeof(part), "%s: %s", run_watches[i], (running ? "yes" : "no"));
469                         snprintf(pathbuf, sizeof(pathbuf), "%s%s", order[ORDER_RUN], run_watches[i]);
470                         write_to_statusbar(pathbuf, part);
471                 }
472
473                 if (wlan_interface)
474                         write_to_statusbar(concat(order[ORDER_WLAN], "wlan"), get_wireless_info());
475                 if (eth_interface)
476                         write_to_statusbar(concat(order[ORDER_ETH], "eth"), get_eth_info());
477                 if (battery_path)
478                         write_to_statusbar(concat(order[ORDER_BATTERY], "battery"), get_battery_info());
479
480                 /* Get load */
481 #ifdef LINUX
482                 if ((load_avg = open("/proc/loadavg", O_RDONLY)) == -1)
483                         die("Could not open /proc/loadavg\n");
484                 (void)read(load_avg, part, sizeof(part));
485                 (void)close(load_avg);
486                 *skip_character(part, ' ', 3) = '\0';
487 #else
488                 /* TODO: correctly check for NetBSD, check if it works the same on *BSD */
489                 struct loadavg load;
490                 size_t length = sizeof(struct loadavg);
491                 int mib[2] = { CTL_VM, VM_LOADAVG };
492                 if (sysctl(mib, 2, &load, &length, NULL, 0) < 0)
493                         die("Could not sysctl({ CTL_VM, VM_LOADAVG })\n");
494                 double scale = load.fscale;
495                 (void)snprintf(part, sizeof(part), "%.02f %.02f %.02f",
496                                 (double)load.ldavg[0] / scale,
497                                 (double)load.ldavg[1] / scale,
498                                 (double)load.ldavg[2] / scale);
499 #endif
500                 write_to_statusbar(concat(order[ORDER_LOAD], "load"), part);
501
502                 if (time_format) {
503                         /* Get date & time */
504                         time_t current_time = time(NULL);
505                         struct tm *current_tm = localtime(&current_time);
506                         (void)strftime(part, sizeof(part), time_format, current_tm);
507                         write_to_statusbar(concat(order[ORDER_TIME], "time"), part);
508                 }
509
510                 sleep(interval);
511         }
512 }