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