]> git.sur5r.net Git - i3/i3status/blob - wmiistatus.c
afd3965938b465d7e40a6e622e729e57e0e9d63e
[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 <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         int flags = O_CREAT | O_WRONLY;
106         struct stat statbuf;
107
108         (void)snprintf(pathbuf, sizeof(pathbuf), "%s%s", wmii_path, name);
109
110         /* Overwrite file's contents if it exists */
111         if (stat(pathbuf, &statbuf) >= 0)
112                 flags |= O_TRUNC;
113
114         if ((fd = open(pathbuf, flags, S_IRUSR | S_IWUSR)) < 0)
115                 exit(EXIT_FAILURE);
116         if (use_colors) {
117                 char *tmp = concat("#888888 ", wmii_normcolors);
118                 if (write(fd, tmp, strlen(tmp)) != (ssize_t)strlen(tmp))
119                         exit(EXIT_FAILURE);
120         }
121         (void)close(fd);
122 }
123
124 /*
125  * Waits until wmii_path/rbar exists (= the filesystem gets mounted),
126  * cleans up all files and creates the needed files
127  *
128  */
129 static void setup(void) {
130         unsigned int i;
131         struct stat statbuf;
132         char pathbuf[512];
133
134         /* Wait until wmii_path/rbar exists */
135         for (; stat(wmii_path, &statbuf) < 0; sleep(interval));
136
137         cleanup_rbar_dir();
138         if (wlan_interface)
139                 create_file(concat(order[ORDER_WLAN],"wlan"));
140         if (eth_interface)
141                 create_file(concat(order[ORDER_ETH],"eth"));
142         if (battery_path)
143                 create_file(concat(order[ORDER_BATTERY],"battery"));
144         create_file(concat(order[ORDER_LOAD],"load"));
145         if (time_format)
146                 create_file(concat(order[ORDER_TIME],"time"));
147         for (i = 0; i < num_run_watches; i += 2) {
148                 snprintf(pathbuf, sizeof(pathbuf), "%s%s", order[ORDER_RUN], run_watches[i]);
149                 create_file(pathbuf);
150         }
151
152 }
153
154 /*
155  * Writes the given message in the corresponding file in wmii's /rbar directory
156  *
157  */
158 static void write_to_statusbar(const char *name, const char *message) {
159         char pathbuf[strlen(wmii_path)+256+1];
160         int fd;
161
162         (void)snprintf(pathbuf, sizeof(pathbuf), "%s%s", wmii_path, name);
163         if ((fd = open(pathbuf, O_RDWR)) == -1) {
164                 /* Try to re-setup stuff and just continue */
165                 setup();
166                 return;
167         }
168         if (write(fd, message, strlen(message)) != (ssize_t)strlen(message))
169                 exit(EXIT_FAILURE);
170         (void)close(fd);
171 }
172
173 /*
174  * Writes an errormessage to statusbar
175  *
176  */
177 static void write_error_to_statusbar(const char *message) {
178         cleanup_rbar_dir();
179         create_file("error");
180         write_to_statusbar("error", message);
181 }
182
183 /*
184  * Write errormessage to statusbar and exit
185  *
186  */
187 void die(const char *fmt, ...) {
188         char buffer[512];
189         va_list ap;
190         va_start(ap, fmt);
191         (void)vsnprintf(buffer, sizeof(buffer), fmt, ap);
192         va_end(ap);
193
194         if (wmii_path != NULL)
195                 write_error_to_statusbar(buffer);
196         exit(EXIT_FAILURE);
197 }
198
199 /*
200  * Skip the given character for maximum 'amount' times, returns
201  * a pointer to the first non-'character' character in 'input'.
202  *
203  */
204 static char *skip_character(char *input, char character, int amount) {
205         char *walk;
206         size_t len = strlen(input);
207         int blanks = 0;
208
209         for (walk = input; ((size_t)(walk - input) < len) && (blanks < amount); walk++)
210                 if (*walk == character)
211                         blanks++;
212
213         return (walk == input ? walk : walk-1);
214 }
215
216 /*
217  * Get battery information from /sys. Note that it uses the design capacity to
218  * calculate the percentage, not the last full capacity, so you can see how
219  * worn off your battery is.
220  *
221  */
222 static char *get_battery_info() {
223         char buf[1024];
224         static char part[512];
225         char *walk, *last;
226         int fd;
227         int full_design = -1,
228             remaining = -1,
229             present_rate = -1;
230         charging_status_t status = CS_DISCHARGING;
231
232         if ((fd = open(battery_path, O_RDONLY)) == -1)
233                 return "No battery found";
234
235         memset(part, 0, sizeof(part));
236         (void)read(fd, buf, sizeof(buf));
237         for (walk = buf, last = buf; (walk-buf) < 1024; walk++)
238                 if (*walk == '=') {
239                         if (BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_FULL_DESIGN") ||
240                             BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_FULL_DESIGN"))
241                                 full_design = atoi(walk+1);
242                         else if (BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_NOW") ||
243                                  BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_NOW"))
244                                 remaining = atoi(walk+1);
245                         else if (BEGINS_WITH(last, "POWER_SUPPLY_CURRENT_NOW"))
246                                 present_rate = atoi(walk+1);
247                         else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Charging"))
248                                 status = CS_CHARGING;
249                         else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Full"))
250                                 status = CS_FULL;
251                 } else if (*walk == '\n')
252                         last = walk+1;
253         (void)close(fd);
254
255         if ((full_design != -1) && (remaining != -1) && (present_rate != -1)) {
256                 float remaining_time, perc;
257                 int seconds, hours, minutes;
258                 if (status == CS_CHARGING)
259                         remaining_time = ((float)full_design - (float)remaining) / (float)present_rate;
260                 else if (status == CS_DISCHARGING)
261                         remaining_time = ((float)remaining / (float)present_rate);
262                 else {
263                         (void)snprintf(part, sizeof(part), "FULL");
264                         return part;
265                 }
266                 perc = ((float)remaining / (float)full_design);
267
268                 seconds = (int)(remaining_time * 3600.0);
269                 hours = seconds / 3600;
270                 seconds -= (hours * 3600);
271                 minutes = seconds / 60;
272                 seconds -= (minutes * 60);
273
274                 (void)snprintf(part, sizeof(part), "%s %.02f%% %02d:%02d:%02d",
275                         (status == CS_CHARGING? "CHR" : "BAT"),
276                         (perc * 100), hours, minutes, seconds);
277         }
278         return part;
279 }
280
281 /*
282  * Just parses /proc/net/wireless
283  *
284  */
285 static char *get_wireless_info() {
286         char buf[1024];
287         static char part[512];
288         char *interfaces;
289         int fd;
290         memset(buf, 0, sizeof(buf));
291         memset(part, 0, sizeof(part));
292
293         if ((fd = open("/proc/net/wireless", O_RDONLY)) == -1)
294                 die("Could not open /proc/net/wireless");
295         (void)read(fd, buf, sizeof(buf));
296         (void)close(fd);
297
298         interfaces = skip_character(buf, '\n', 2) + 1;
299         while (interfaces < buf+strlen(buf)) {
300                 while (isspace((int)*interfaces))
301                         interfaces++;
302                 if (strncmp(interfaces, wlan_interface, strlen(wlan_interface)) == 0) {
303                         int quality;
304                         /* Skip status field (0000) */
305                         interfaces += strlen(wlan_interface) + 2;
306                         interfaces = skip_character(interfaces, ' ', 1);
307                         while (isspace((int)*interfaces))
308                                 interfaces++;
309                         quality = atoi(interfaces);
310                         /* For some reason, I get 255 sometimes */
311                         if ((quality == 255) || (quality == 0)) {
312                         if (use_colors)
313                                 (void)snprintf(part, sizeof(part), "%s%s", concat("#FF0000 ", wmii_normcolors), " W: down");
314                         else (void)snprintf(part, sizeof(part), "W: down");
315
316                         } else {
317                                 const char *ip_address;
318                                 (void)snprintf(part, sizeof(part), "W: (%03d%%) ", quality);
319                                 ip_address = get_ip_address(wlan_interface);
320                                 strcpy(part+strlen(part), ip_address);
321                         }
322
323                         return part;
324                 }
325                 interfaces = skip_character(interfaces, '\n', 1) + 1;
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         int fd;
340         memset(part, 0, sizeof(part));
341
342         if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
343                 die("Could not create socket");
344
345         strcpy(ifr.ifr_name, interface);
346         if (ioctl(fd, SIOCGIFFLAGS, &ifr) < 0)
347                 die("Could not get interface flags (SIOCGIFFLAGS)");
348
349         if (!(ifr.ifr_flags & IFF_UP) ||
350             !(ifr.ifr_flags & IFF_RUNNING)) {
351                 close(fd);
352                 return NULL;
353         }
354
355         (void)strcpy(ifr.ifr_name, interface);
356         ifr.ifr_addr.sa_family = AF_INET;
357         if (ioctl(fd, SIOCGIFADDR, &ifr) == 0) {
358                 struct sockaddr_in addr;
359                 memcpy(&addr, &ifr.ifr_addr, sizeof(struct sockaddr_in));
360                 (void)inet_ntop(AF_INET, &addr.sin_addr.s_addr, part, (socklen_t)sizeof(struct sockaddr_in));
361                 if (strlen(part) == 0)
362                         snprintf(part, sizeof(part), "no IP");
363         }
364
365         (void)close(fd);
366         return part;
367 }
368
369 /*
370  * Combines ethernet IP addresses and speed (if requested) for displaying
371  *
372  */
373 static char *get_eth_info() {
374         static char part[512];
375         const char *ip_address = get_ip_address(eth_interface);
376         int ethspeed = 0;
377
378         if (get_ethspeed) {
379                 /* This code path requires root privileges */
380                 struct ifreq ifr;
381                 struct ethtool_cmd ecmd;
382                 int fd, err;
383
384                 if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
385                         write_error_to_statusbar("Could not open socket");
386
387                 ecmd.cmd = ETHTOOL_GSET;
388                 (void)memset(&ifr, 0, sizeof(ifr));
389                 ifr.ifr_data = (caddr_t)&ecmd;
390                 (void)strcpy(ifr.ifr_name, eth_interface);
391                 if ((err = ioctl(fd, SIOCETHTOOL, &ifr)) == 0)
392                         ethspeed = (ecmd.speed == 65535 ? 0 : ecmd.speed);
393                 else get_ethspeed = false;
394
395                 (void)close(fd);
396         }
397
398         if (ip_address == NULL)
399                 (void)snprintf(part, sizeof(part), "E: down");
400         else {
401                 if (get_ethspeed)
402                         (void)snprintf(part, sizeof(part), "E: %s (%d Mbit/s)", ip_address, ethspeed);
403                 else (void)snprintf(part, sizeof(part), "E: %s", ip_address);
404         }
405
406         return part;
407 }
408
409 /*
410  * Checks if the PID in path is still valid by checking if /proc/<pid> exists
411  *
412  */
413 static bool process_runs(const char *path) {
414         char pidbuf[512],
415              procbuf[512],
416              *walk;
417         ssize_t n;
418         static glob_t globbuf;
419         struct stat statbuf;
420         const char *real_path;
421         int fd;
422
423         if (glob(path, GLOB_NOCHECK | GLOB_TILDE, NULL, &globbuf) < 0)
424                 die("glob() failed");
425         real_path = (globbuf.gl_pathc > 0 ? globbuf.gl_pathv[0] : path);
426         fd = open(real_path, O_RDONLY);
427         globfree(&globbuf);
428         if (fd < 0)
429                 return false;
430         if ((n = read(fd, pidbuf, sizeof(pidbuf))) > 0)
431                 pidbuf[n] = '\0';
432         (void)close(fd);
433         for (walk = pidbuf; *walk != '\0'; walk++)
434                 if (!isdigit((int)(*walk))) {
435                         *walk = '\0';
436                         break;
437                 }
438         (void)snprintf(procbuf, sizeof(procbuf), "/proc/%s", pidbuf);
439         return (stat(procbuf, &statbuf) >= 0);
440 }
441
442 int main(int argc, char *argv[]) {
443         char part[512],
444              pathbuf[512],
445              *end;
446         unsigned int i;
447         int load_avg;
448
449         char *configfile = PREFIX "/etc/wmiistatus.conf";
450         int o, option_index = 0;
451         struct option long_options[] = {
452                 {"config", required_argument, 0, 'c'},
453                 {0, 0, 0, 0}
454         };
455
456         while ((o = getopt_long(argc, argv, "c:", long_options, &option_index)) != -1)
457                 if ((char)o == 'c')
458                         configfile = optarg;
459
460         if (load_configuration(configfile) < 0)
461                 return EXIT_FAILURE;
462
463         setup();
464
465         while (1) {
466                 for (i = 0; i < num_run_watches; i += 2) {
467                         bool running = process_runs(run_watches[i+1]);
468                         if (use_colors)
469                                 snprintf(part, sizeof(part), "%s %s: %s",
470                                         (running ?
471                                                 concat("#00FF00 ", wmii_normcolors) :
472                                                 concat("#FF0000 ", wmii_normcolors)),
473                                         run_watches[i],
474                                         (running ? "yes" : "no"));
475                         else snprintf(part, sizeof(part), "%s: %s", run_watches[i], (running ? "yes" : "no"));
476                         snprintf(pathbuf, sizeof(pathbuf), "%s%s", order[ORDER_RUN], run_watches[i]);
477                         write_to_statusbar(pathbuf, part);
478                 }
479
480                 if (wlan_interface)
481                         write_to_statusbar(concat(order[ORDER_WLAN], "wlan"), get_wireless_info());
482                 if (eth_interface)
483                         write_to_statusbar(concat(order[ORDER_ETH], "eth"), get_eth_info());
484                 if (battery_path)
485                         write_to_statusbar(concat(order[ORDER_BATTERY], "battery"), get_battery_info());
486
487                 /* Get load */
488                 if ((load_avg = open("/proc/loadavg", O_RDONLY)) == -1)
489                         die("Could not open /proc/loadavg");
490                 (void)read(load_avg, part, sizeof(part));
491                 (void)close(load_avg);
492                 end = skip_character(part, ' ', 3);
493                 *end = '\0';
494                 write_to_statusbar(concat(order[ORDER_LOAD], "load"), part);
495
496                 if (time_format) {
497                         /* Get date & time */
498                         time_t current_time = time(NULL);
499                         struct tm *current_tm = localtime(&current_time);
500                         (void)strftime(part, sizeof(part), time_format, current_tm);
501                         write_to_statusbar(concat(order[ORDER_TIME], "time"), part);
502                 }
503
504                 sleep(interval);
505         }
506 }