]> git.sur5r.net Git - i3/i3status/blob - wmiistatus.c
Add support for differently named uevent data and hint for 9pnet_fd
[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 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 <ctype.h>
45 #include <net/if.h>
46 #include <sys/ioctl.h>
47 #include <sys/socket.h>
48 #include <netinet/in.h>
49 #include <arpa/inet.h>
50 #include <glob.h>
51 #include <dirent.h>
52 #include <getopt.h>
53 #include <linux/ethtool.h>
54 #include <linux/sockios.h>
55
56
57 #define _IS_WMIISTATUS_C
58 #include "wmiistatus.h"
59 #undef _IS_WMIISTATUS_C
60 #include "config.h"
61
62 /*
63  * This function just concats two strings in place, it should only be used
64  * for concatting order to the name of a file or concatting color codes.
65  * Otherwise, the buffer size would have to be increased.
66  *
67  */
68 static char *concat(const char *str1, const char *str2) {
69         static char concatbuf[32];
70         (void)snprintf(concatbuf, sizeof(concatbuf), "%s%s", str1, str2);
71         return concatbuf;
72 }
73
74 /*
75  * Cleans wmii's /rbar directory by deleting all regular files
76  *
77  */
78 static void cleanup_rbar_dir() {
79         struct dirent *ent;
80         DIR *dir;
81         char pathbuf[strlen(wmii_path)+256+1];
82
83         if ((dir = opendir(wmii_path)) == NULL)
84                 exit(EXIT_FAILURE);
85
86         while ((ent = readdir(dir)) != NULL) {
87                 if (ent->d_type == DT_REG) {
88                         (void)snprintf(pathbuf, sizeof(pathbuf), "%s%s", wmii_path, ent->d_name);
89                         if (unlink(pathbuf) == -1)
90                                 exit(EXIT_FAILURE);
91                 }
92         }
93
94         (void)closedir(dir);
95 }
96
97 /*
98  * Creates the specified file in wmii's /rbar directory with
99  * correct modes and initializes colors if colormode is enabled
100  * '
101  */
102 static void create_file(const char *name) {
103         char pathbuf[strlen(wmii_path)+256+1];
104         int fd;
105
106         (void)snprintf(pathbuf, sizeof(pathbuf), "%s%s", wmii_path, name);
107         if ((fd = open(pathbuf, O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR)) < 0)
108                 exit(EXIT_FAILURE);
109         if (use_colors) {
110                 char *tmp = concat("#888888 ", wmii_normcolors);
111                 if (write(fd, tmp, strlen(tmp)) != (ssize_t)strlen(tmp))
112                         exit(EXIT_FAILURE);
113         }
114         (void)close(fd);
115 }
116
117 /*
118  * Writes the given message in the corresponding file in wmii's /rbar directory
119  *
120  */
121 static void write_to_statusbar(const char *name, const char *message) {
122         char pathbuf[strlen(wmii_path)+256+1];
123         int fd;
124
125         (void)snprintf(pathbuf, sizeof(pathbuf), "%s%s", wmii_path, name);
126         if ((fd = open(pathbuf, O_RDWR)) == -1)
127                 exit(EXIT_FAILURE);
128         if (write(fd, message, strlen(message)) != (ssize_t)strlen(message))
129                 exit(EXIT_FAILURE);
130         (void)close(fd);
131 }
132
133 /*
134  * Writes an errormessage to statusbar
135  *
136  */
137 static void write_error_to_statusbar(const char *message) {
138         cleanup_rbar_dir();
139         create_file("error");
140         write_to_statusbar("error", message);
141 }
142
143 /*
144  * Write errormessage to statusbar and exit
145  *
146  */
147 void die(const char *fmt, ...) {
148         char buffer[512];
149         va_list ap;
150         va_start(ap, fmt);
151         (void)vsnprintf(buffer, sizeof(buffer), fmt, ap);
152         va_end(ap);
153
154         write_error_to_statusbar(buffer);
155         exit(EXIT_FAILURE);
156 }
157
158 static char *skip_character(char *input, char character, int amount) {
159         char *walk;
160         size_t len = strlen(input);
161         int blanks = 0;
162
163         for (walk = input; ((size_t)(walk - input) < len) && (blanks < amount); walk++)
164                 if (*walk == character)
165                         blanks++;
166
167         return (walk == input ? walk : walk-1);
168 }
169
170 /*
171  * Get battery information from /sys. Note that it uses the design capacity to calculate the percentage,
172  * not the full capacity.
173  *
174  */
175 static char *get_battery_info() {
176         char buf[1024];
177         static char part[512];
178         char *walk, *last;
179         int fd;
180         int full_design = -1,
181             remaining = -1,
182             present_rate = -1;
183         charging_status_t status = CS_DISCHARGING;
184
185         if ((fd = open(battery_path, O_RDONLY)) == -1)
186                 die("Could not open %s", battery_path);
187
188         memset(part, 0, sizeof(part));
189         (void)read(fd, buf, sizeof(buf));
190         for (walk = buf, last = buf; (walk-buf) < 1024; walk++)
191                 if (*walk == '=') {
192                         if (BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_FULL_DESIGN") ||
193                             BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_FULL_DESIGN"))
194                                 full_design = atoi(walk+1);
195                         else if (BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_NOW") ||
196                                  BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_NOW"))
197                                 remaining = atoi(walk+1);
198                         else if (BEGINS_WITH(last, "POWER_SUPPLY_CURRENT_NOW"))
199                                 present_rate = atoi(walk+1);
200                         else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Charging"))
201                                 status = CS_CHARGING;
202                         else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Full"))
203                                 status = CS_FULL;
204                 } else if (*walk == '\n')
205                         last = walk+1;
206         (void)close(fd);
207
208         if ((full_design != -1) && (remaining != -1) && (present_rate != -1)) {
209                 float remaining_time, perc;
210                 int seconds, hours, minutes;
211                 if (status == CS_CHARGING)
212                         remaining_time = ((float)full_design - (float)remaining) / (float)present_rate;
213                 else if (status == CS_DISCHARGING)
214                         remaining_time = ((float)remaining / (float)present_rate);
215                 else {
216                         (void)snprintf(part, sizeof(part), "FULL");
217                         return part;
218                 }
219                 perc = ((float)remaining / (float)full_design);
220
221                 seconds = (int)(remaining_time * 3600.0);
222                 hours = seconds / 3600;
223                 seconds -= (hours * 3600);
224                 minutes = seconds / 60;
225                 seconds -= (minutes * 60);
226
227                 (void)snprintf(part, sizeof(part), "%s %.02f%% %02d:%02d:%02d",
228                         (status == CS_CHARGING? "CHR" : "BAT"),
229                         (perc * 100), hours, minutes, seconds);
230         }
231         return part;
232 }
233
234 /*
235  * Just parses /proc/net/wireless
236  *
237  */
238 static char *get_wireless_info() {
239         char buf[1024];
240         static char part[512];
241         char *interfaces;
242         int fd;
243         memset(buf, 0, sizeof(buf));
244         memset(part, 0, sizeof(part));
245
246         if ((fd = open("/proc/net/wireless", O_RDONLY)) == -1)
247                 die("Could not open /proc/net/wireless");
248         (void)read(fd, buf, sizeof(buf));
249         (void)close(fd);
250
251         interfaces = skip_character(buf, '\n', 2) + 1;
252         while (interfaces < buf+strlen(buf)) {
253                 while (isspace((int)*interfaces))
254                         interfaces++;
255                 if (strncmp(interfaces, wlan_interface, strlen(wlan_interface)) == 0) {
256                         int quality;
257                         /* Skip status field (0000) */
258                         interfaces += strlen(wlan_interface) + 2;
259                         interfaces = skip_character(interfaces, ' ', 1);
260                         while (isspace((int)*interfaces))
261                                 interfaces++;
262                         quality = atoi(interfaces);
263                         /* For some reason, I get 255 sometimes */
264                         if ((quality == 255) || (quality == 0)) {
265                         if (use_colors)
266                                 (void)snprintf(part, sizeof(part), "%s%s", concat("#FF0000 ", wmii_normcolors), " W: down");
267                         else (void)snprintf(part, sizeof(part), "W: down");
268
269                         } else {
270                                 const char *ip_address;
271                                 (void)snprintf(part, sizeof(part), "W: (%02d%%) ", quality);
272                                 ip_address = get_ip_address(wlan_interface);
273                                 strcpy(part+strlen(part), ip_address);
274                         }
275
276                         return part;
277                 }
278                 interfaces = skip_character(interfaces, '\n', 1) + 1;
279         }
280
281         return part;
282 }
283
284 static const char *get_ip_address(const char *interface) {
285         static char part[512];
286         struct ifreq ifr;
287         int fd;
288         memset(part, 0, sizeof(part));
289
290         fd = socket(AF_INET, SOCK_DGRAM, 0);
291
292         strcpy(ifr.ifr_name, interface);
293         if (ioctl(fd, SIOCGIFFLAGS, &ifr) < 0)
294                 die("Could not get interface flags (SIOCGIFFLAGS)");
295
296         if (!(ifr.ifr_flags & IFF_UP) ||
297             !(ifr.ifr_flags & IFF_RUNNING)) {
298                 close(fd);
299                 return NULL;
300         }
301
302         strcpy(ifr.ifr_name, interface);
303         ifr.ifr_addr.sa_family = AF_INET;
304         if (ioctl(fd, SIOCGIFADDR, &ifr) == 0) {
305                 struct sockaddr_in addr;
306                 memcpy(&addr, &ifr.ifr_addr, sizeof(struct sockaddr_in));
307                 (void)inet_ntop(AF_INET, &addr.sin_addr.s_addr, part, (socklen_t)sizeof(struct sockaddr_in));
308                 if (strlen(part) == 0)
309                         snprintf(part, sizeof(part), "no IP");
310         }
311
312         (void)close(fd);
313         return part;
314 }
315
316 static char *get_eth_info() {
317         static char part[512];
318         const char *ip_address = get_ip_address(eth_interface);
319         int ethspeed = 0;
320
321         if (get_ethspeed) {
322                 struct ifreq ifr;
323                 struct ethtool_cmd ecmd;
324                 int fd, err;
325
326                 if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
327                         write_error_to_statusbar("Could not open socket");
328
329                 ecmd.cmd = ETHTOOL_GSET;
330                 (void)memset(&ifr, 0, sizeof(ifr));
331                 ifr.ifr_data = (caddr_t)&ecmd;
332                 (void)strcpy(ifr.ifr_name, eth_interface);
333                 if ((err = ioctl(fd, SIOCETHTOOL, &ifr)) == 0)
334                         ethspeed = ecmd.speed;
335                 else write_error_to_statusbar("Could not get interface speed. Insufficient privileges?");
336
337                 (void)close(fd);
338         }
339
340         if (ip_address == NULL)
341                 (void)snprintf(part, sizeof(part), "E: down");
342         else {
343                 if (get_ethspeed)
344                         (void)snprintf(part, sizeof(part), "E: %s (%d Mbit/s)", ip_address, ethspeed);
345                 else (void)snprintf(part, sizeof(part), "E: %s", ip_address);
346         }
347
348         return part;
349 }
350
351 /*
352  * Checks if the PID in path is still valid by checking if /proc/<pid> exists
353  *
354  */
355 static bool process_runs(const char *path) {
356         char pidbuf[512],
357              procbuf[512],
358              *walk;
359         ssize_t n;
360         static glob_t globbuf;
361         struct stat statbuf;
362         const char *real_path;
363         int fd;
364
365         if (glob(path, GLOB_NOCHECK | GLOB_TILDE, NULL, &globbuf) < 0)
366                 die("glob() failed");
367         real_path = (globbuf.gl_pathc > 0 ? globbuf.gl_pathv[0] : path);
368         fd = open(real_path, O_RDONLY);
369         globfree(&globbuf);
370         if (fd < 0)
371                 return false;
372         if ((n = read(fd, pidbuf, sizeof(pidbuf))) > 0)
373                 pidbuf[n] = '\0';
374         (void)close(fd);
375         for (walk = pidbuf; *walk != '\0'; walk++)
376                 if (!isdigit((int)(*walk))) {
377                         *walk = '\0';
378                         break;
379                 }
380         (void)snprintf(procbuf, sizeof(procbuf), "/proc/%s", pidbuf);
381         return (stat(procbuf, &statbuf) >= 0);
382 }
383
384 int main(int argc, char *argv[]) {
385         char part[512],
386              pathbuf[512],
387              *end;
388         unsigned int i;
389         int load_avg;
390
391         char *configfile = PREFIX "/etc/wmiistatus.conf";
392         int o, option_index = 0;
393         struct option long_options[] = {
394                 {"config", required_argument, 0, 'c'},
395                 {0, 0, 0, 0}
396         };
397
398         while ((o = getopt_long(argc, argv, "c:", long_options, &option_index)) != -1)
399                 if ((char)o == 'c')
400                         configfile = optarg;
401
402         load_configuration(configfile);
403         cleanup_rbar_dir();
404         if (wlan_interface)
405                 create_file(concat(order[ORDER_WLAN],"wlan"));
406         if (eth_interface)
407                 create_file(concat(order[ORDER_ETH],"eth"));
408         if (battery_path)
409                 create_file(concat(order[ORDER_BATTERY],"battery"));
410         create_file(concat(order[ORDER_LOAD],"load"));
411         if (time_format)
412                 create_file(concat(order[ORDER_TIME],"time"));
413         for (i = 0; i < num_run_watches; i += 2) {
414                 snprintf(pathbuf, sizeof(pathbuf), "%s%s", order[ORDER_RUN], run_watches[i]);
415                 create_file(pathbuf);
416         }
417
418         while (1) {
419                 for (i = 0; i < num_run_watches; i += 2) {
420                         bool running = process_runs(run_watches[i+1]);
421                         if (use_colors)
422                                 snprintf(part, sizeof(part), "%s %s: %s",
423                                         (running ?
424                                                 concat("#00FF00 ", wmii_normcolors) :
425                                                 concat("#FF0000 ", wmii_normcolors)),
426                                         run_watches[i],
427                                         (running ? "yes" : "no"));
428                         else snprintf(part, sizeof(part), "%s: %s", run_watches[i], (running ? "yes" : "no"));
429                         snprintf(pathbuf, sizeof(pathbuf), "%s%s", order[ORDER_RUN], run_watches[i]);
430                         write_to_statusbar(pathbuf, part);
431                 }
432
433                 if (wlan_interface)
434                         write_to_statusbar(concat(order[ORDER_WLAN], "wlan"), get_wireless_info());
435                 if (eth_interface)
436                         write_to_statusbar(concat(order[ORDER_ETH], "eth"), get_eth_info());
437                 if (battery_path)
438                         write_to_statusbar(concat(order[ORDER_BATTERY], "battery"), get_battery_info());
439
440                 /* Get load */
441                 if ((load_avg = open("/proc/loadavg", O_RDONLY)) == -1)
442                         die("Could not open /proc/loadavg");
443                 (void)read(load_avg, part, sizeof(part));
444                 (void)close(load_avg);
445                 end = skip_character(part, ' ', 3);
446                 *end = '\0';
447                 write_to_statusbar(concat(order[ORDER_LOAD], "load"), part);
448
449                 if (time_format) {
450                         /* Get date & time */
451                         time_t current_time = time(NULL);
452                         struct tm *current_tm = localtime(&current_time);
453                         (void)strftime(part, sizeof(part), time_format, current_tm);
454                         write_to_statusbar(concat(order[ORDER_TIME], "time"), part);
455                 }
456
457                 sleep(interval);
458         }
459 }