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