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