]> git.sur5r.net Git - i3/i3status/blob - wmiistatus.c
c47b5289e05c6b247e52cdb47e858b2790571f2e
[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
53 #include "wmiistatus.h"
54 #include "config.h"
55
56 static void cleanup_rbar_dir() {
57         struct dirent *ent;
58         DIR *dir;
59         char pathbuf[strlen(wmii_path)+256+1];
60
61         if ((dir = opendir(wmii_path)) == NULL)
62                 exit(-3);
63
64         while ((ent = readdir(dir)) != NULL) {
65                 if (ent->d_type == DT_REG) {
66                         sprintf(pathbuf, "%s%s", wmii_path, ent->d_name);
67                         unlink(pathbuf);
68                 }
69         }
70
71         closedir(dir);
72 }
73
74 static void create_file(const char *name) {
75         char pathbuf[strlen(wmii_path)+256+1];
76
77         sprintf(pathbuf, "%s%s", wmii_path, name);
78         int fd = creat(pathbuf, S_IRUSR | S_IWUSR);
79         if (fd < 0)
80                 exit(-4);
81         close(fd);
82 }
83
84 static void write_to_statusbar(const char *name, const char *message) {
85         char pathbuf[strlen(wmii_path)+256+1];
86
87         sprintf(pathbuf, "%s%s", wmii_path, name);
88         int fd = open(pathbuf, O_RDWR);
89         if (fd == -1)
90                 exit(-2);
91         write(fd, message, strlen(message));
92         close(fd);
93 }
94
95 static void write_error_to_statusbar(const char *message) {
96         cleanup_rbar_dir();
97         write_to_statusbar("error", message);
98 }
99
100 /*
101  * Write errormessage to statusbar and exit
102  *
103  */
104 static void die(const char *fmt, ...) {
105         char buffer[512];
106         va_list ap;
107         va_start(ap, fmt);
108         vsprintf(buffer, fmt, ap);
109         va_end(ap);
110
111         write_error_to_statusbar(buffer);
112         exit(-1);
113 }
114
115 static char *skip_character(char *input, char character, int amount) {
116         char *walk;
117         int len = strlen(input),
118             blanks = 0;
119
120         for (walk = input; ((walk - input) < len) && (blanks < amount); walk++)
121                 if (*walk == character)
122                         blanks++;
123
124         return (walk == input ? walk : walk-1);
125 }
126
127 /*
128  * Get battery information from /sys. Note that it uses the design capacity to calculate the percentage,
129  * not the full capacity.
130  *
131  */
132 static char *get_battery_info() {
133         char buf[1024];
134         static char part[512];
135         char *walk, *last = buf;
136         int fd = open(battery, O_RDONLY);
137         if (fd == -1)
138                 die("Could not open %s", battery);
139         int full_design = -1,
140             remaining = -1,
141             present_rate = -1;
142         charging_status_t status = CS_DISCHARGING;
143         memset(part, '\0', sizeof(part));
144         read(fd, buf, sizeof(buf));
145         for (walk = buf; (walk-buf) < 1024; walk++)
146                 if (*walk == '=') {
147                         if (BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_FULL_DESIGN"))
148                                 full_design = atoi(walk+1);
149                         else if (BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_NOW"))
150                                 remaining = atoi(walk+1);
151                         else if (BEGINS_WITH(last, "POWER_SUPPLY_CURRENT_NOW"))
152                                 present_rate = atoi(walk+1);
153                         else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Charging"))
154                                 status = CS_CHARGING;
155                         else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Full"))
156                                 status = CS_FULL;
157                 } else if (*walk == '\n')
158                         last = walk+1;
159         close(fd);
160
161         if ((full_design != -1) && (remaining != -1) && (present_rate != -1)) {
162                 float remaining_time, perc;
163                 if (status == CS_CHARGING)
164                         remaining_time = ((float)full_design - (float)remaining) / (float)present_rate;
165                 else if (status == CS_DISCHARGING)
166                         remaining_time = ((float)remaining / (float)present_rate);
167                 else {
168                         snprintf(part, sizeof(part), "FULL");
169                         return part;
170                 }
171                 perc = ((float)remaining / (float)full_design);
172
173                 int seconds = (int)(remaining_time * 3600.0);
174                 int hours = seconds / 3600;
175                 seconds -= (hours * 3600);
176                 int minutes = seconds / 60;
177                 seconds -= (minutes * 60);
178
179                 sprintf(part, "%s %.02f%% %02d:%02d:%02d", (status == CS_CHARGING? "CHR" : "BAT"),
180                         (perc * 100), hours, minutes, seconds);
181         }
182         return part;
183 }
184
185 /*
186  * Just parses /proc/net/wireless
187  *
188  */
189 static char *get_wireless_info() {
190         char buf[1024];
191         static char part[512];
192         char *interfaces;
193         memset(buf, '\0', sizeof(buf));
194         memset(part, '\0', sizeof(part));
195
196         int fd = open("/proc/net/wireless", O_RDONLY);
197         if (fd == -1)
198                 die("Could not open /proc/net/wireless");
199         read(fd, buf, sizeof(buf));
200         close(fd);
201
202         interfaces = skip_character(buf, '\n', 2) + 1;
203         while (interfaces < buf+strlen(buf)) {
204                 while (isspace((int)*interfaces))
205                         interfaces++;
206                 if (strncmp(interfaces, wlan_interface, strlen(wlan_interface)) == 0) {
207                         /* Skip status field (0000) */
208                         interfaces += strlen(wlan_interface) + 2;
209                         interfaces = skip_character(interfaces, ' ', 1);
210                         while (isspace((int)*interfaces))
211                                 interfaces++;
212                         int quality = atoi(interfaces);
213                         /* For some reason, I get 255 sometimes */
214                         if ((quality == 255) || (quality == 0))
215                                 snprintf(part, sizeof(part), "W: down");
216                         else {
217                                 snprintf(part, sizeof(part), "W: (%02d%%) ", quality);
218                                 char *ip_address = get_ip_address(wlan_interface);
219                                 strcpy(part+strlen(part), ip_address);
220                         }
221
222                         return part;
223                 }
224                 interfaces = skip_character(interfaces, '\n', 1) + 1;
225         }
226
227         return part;
228 }
229
230 static char *get_ip_address(const char *interface) {
231         static char part[512];
232         struct ifreq ifr;
233         memset(part, '\0', sizeof(part));
234
235         int fd = socket(AF_INET, SOCK_DGRAM, 0);
236
237         strcpy(ifr.ifr_name, interface);
238         if (ioctl(fd, SIOCGIFFLAGS, &ifr) < 0)
239                 die("Could not get interface flags (SIOCGIFFLAGS)");
240
241         if (!(ifr.ifr_flags & IFF_UP) ||
242             !(ifr.ifr_flags & IFF_RUNNING)) {
243                 close(fd);
244                 return NULL;
245         }
246
247         strcpy(ifr.ifr_name, interface);
248         ifr.ifr_addr.sa_family = AF_INET;
249         if (ioctl(fd, SIOCGIFADDR, &ifr) == 0) {
250                 struct sockaddr_in addr;
251                 memcpy(&addr, &ifr.ifr_addr, sizeof(struct sockaddr_in));
252                 inet_ntop(AF_INET, &addr.sin_addr.s_addr, part, sizeof(struct sockaddr_in));
253                 if (strlen(part) == 0)
254                         sprintf(part, "no IP");
255         }
256
257         close(fd);
258         return part;
259 }
260
261 static char *get_eth_info() {
262         static char part[512];
263         char *ip_address = get_ip_address(eth_interface);
264
265         if (ip_address == NULL)
266                 snprintf(part, sizeof(part), "E: down");
267         else snprintf(part, sizeof(part), "E: %s", ip_address);
268
269         return part;
270 }
271
272 /*
273  * Checks if the PID in path is still valid by checking if /proc/<pid> exists
274  *
275  */
276 static bool process_runs(const char *path) {
277         char pidbuf[512],
278              procbuf[512],
279              *walk;
280         int n;
281         static glob_t globbuf;
282         struct stat statbuf;
283
284         if (glob(path, GLOB_NOCHECK | GLOB_TILDE, NULL, &globbuf) < 0)
285                 die("glob() failed");
286         const char *real_path = (globbuf.gl_pathc > 0 ? globbuf.gl_pathv[0] : path);
287         int fd = open(real_path, O_RDONLY);
288         globfree(&globbuf);
289         if (fd < 0)
290                 return false;
291         n = read(fd, pidbuf, sizeof(pidbuf));
292         if (n > 0)
293                 pidbuf[n] = '\0';
294         close(fd);
295         for (walk = pidbuf; *walk != '\0'; walk++)
296                 if (!isdigit((int)(*walk))) {
297                         *walk = '\0';
298                         break;
299                 }
300         sprintf(procbuf, "/proc/%s", pidbuf);
301         return (stat(procbuf, &statbuf) >= 0);
302 }
303
304 int main(void) {
305         char part[512],
306              pathbuf[512],
307              *end;
308         unsigned int i;
309
310         cleanup_rbar_dir();
311         create_file(ORDER_WLAN "wlan");
312         create_file(ORDER_ETH "eth");
313         create_file(ORDER_BATTERY "battery");
314         create_file(ORDER_LOAD "load");
315         create_file(ORDER_TIME "time");
316         for (i = 0; i < sizeof(run_watches) / sizeof(char*); i += 2) {
317                 sprintf(pathbuf, "%s%s", ORDER_RUN, run_watches[i]);
318                 create_file(pathbuf);
319         }
320
321         while (1) {
322                 for (i = 0; i < sizeof(run_watches) / sizeof(char*); i += 2) {
323                         sprintf(part, "%s: %s", run_watches[i], (process_runs(run_watches[i+1]) ? "yes" : "no"));
324                         sprintf(pathbuf, "%s%s", ORDER_RUN, run_watches[i]);
325                         write_to_statusbar(pathbuf, part);
326                 }
327
328                 write_to_statusbar(ORDER_WLAN "wlan", get_wireless_info());
329                 write_to_statusbar(ORDER_ETH "eth", get_eth_info());
330                 write_to_statusbar(ORDER_BATTERY "battery", get_battery_info());
331
332                 /* Get load */
333                 int load_avg = open("/proc/loadavg", O_RDONLY);
334                 if (load_avg == -1)
335                         die("Could not open /proc/loadavg");
336                 read(load_avg, part, sizeof(part));
337                 close(load_avg);
338                 end = skip_character(part, ' ', 3);
339                 *end = '\0';
340                 write_to_statusbar(ORDER_LOAD "load", part);
341
342                 /* Get date & time */
343                 time_t current_time = time(NULL);
344                 struct tm *current_tm = localtime(&current_time);
345                 strftime(part, sizeof(part), time_format, current_tm);
346                 write_to_statusbar(ORDER_TIME "time", part);
347
348                 sleep(1);
349         }
350 }