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