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