]> git.sur5r.net Git - i3/i3status/blob - wmiistatus.c
Beautify the code for getting ip address/ethernet speed, only use one static socket
[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-2009 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 /* socket file descriptor for general purposes */
63 static int general_socket;
64
65 /*
66  * This function just concats two strings in place, it should only be used
67  * for concatting order to the name of a file or concatting color codes.
68  * Otherwise, the buffer size would have to be increased.
69  *
70  */
71 static char *concat(const char *str1, const char *str2) {
72         static char concatbuf[32];
73         (void)snprintf(concatbuf, sizeof(concatbuf), "%s%s", str1, str2);
74         return concatbuf;
75 }
76
77 /*
78  * Cleans wmii's /rbar directory by deleting all regular files
79  *
80  */
81 static void cleanup_rbar_dir() {
82         struct dirent *ent;
83         DIR *dir;
84         char pathbuf[strlen(wmii_path)+256+1];
85
86         if ((dir = opendir(wmii_path)) == NULL)
87                 exit(EXIT_FAILURE);
88
89         while ((ent = readdir(dir)) != NULL) {
90                 if (ent->d_type == DT_REG) {
91                         (void)snprintf(pathbuf, sizeof(pathbuf), "%s%s", wmii_path, ent->d_name);
92                         if (unlink(pathbuf) == -1)
93                                 exit(EXIT_FAILURE);
94                 }
95         }
96
97         (void)closedir(dir);
98 }
99
100 /*
101  * Creates the specified file in wmii's /rbar directory with
102  * correct modes and initializes colors if colormode is enabled
103  * '
104  */
105 static void create_file(const char *name) {
106         char pathbuf[strlen(wmii_path)+256+1];
107         int fd;
108         int flags = O_CREAT | O_WRONLY;
109         struct stat statbuf;
110
111         (void)snprintf(pathbuf, sizeof(pathbuf), "%s%s", wmii_path, name);
112
113         /* Overwrite file's contents if it exists */
114         if (stat(pathbuf, &statbuf) >= 0)
115                 flags |= O_TRUNC;
116
117         if ((fd = open(pathbuf, flags, S_IRUSR | S_IWUSR)) < 0)
118                 exit(EXIT_FAILURE);
119         if (use_colors) {
120                 char *tmp = concat("#888888 ", wmii_normcolors);
121                 if (write(fd, tmp, strlen(tmp)) != (ssize_t)strlen(tmp))
122                         exit(EXIT_FAILURE);
123         }
124         (void)close(fd);
125 }
126
127 /*
128  * Waits until wmii_path/rbar exists (= the filesystem gets mounted),
129  * cleans up all files and creates the needed files
130  *
131  */
132 static void setup(void) {
133         unsigned int i;
134         struct stat statbuf;
135         char pathbuf[512];
136
137         /* Wait until wmii_path/rbar exists */
138         for (; stat(wmii_path, &statbuf) < 0; sleep(interval));
139
140         cleanup_rbar_dir();
141         if (wlan_interface)
142                 create_file(concat(order[ORDER_WLAN],"wlan"));
143         if (eth_interface)
144                 create_file(concat(order[ORDER_ETH],"eth"));
145         if (battery_path)
146                 create_file(concat(order[ORDER_BATTERY],"battery"));
147         create_file(concat(order[ORDER_LOAD],"load"));
148         if (time_format)
149                 create_file(concat(order[ORDER_TIME],"time"));
150         for (i = 0; i < num_run_watches; i += 2) {
151                 snprintf(pathbuf, sizeof(pathbuf), "%s%s", order[ORDER_RUN], run_watches[i]);
152                 create_file(pathbuf);
153         }
154
155 }
156
157 /*
158  * Writes the given message in the corresponding file in wmii's /rbar directory
159  *
160  */
161 static void write_to_statusbar(const char *name, const char *message) {
162         char pathbuf[strlen(wmii_path)+256+1];
163         int fd;
164
165         (void)snprintf(pathbuf, sizeof(pathbuf), "%s%s", wmii_path, name);
166         if ((fd = open(pathbuf, O_RDWR)) == -1) {
167                 /* Try to re-setup stuff and just continue */
168                 setup();
169                 return;
170         }
171         if (write(fd, message, strlen(message)) != (ssize_t)strlen(message))
172                 exit(EXIT_FAILURE);
173         (void)close(fd);
174 }
175
176 /*
177  * Writes an errormessage to statusbar
178  *
179  */
180 static void write_error_to_statusbar(const char *message) {
181         cleanup_rbar_dir();
182         create_file("error");
183         write_to_statusbar("error", message);
184 }
185
186 /*
187  * Write errormessage to statusbar and exit
188  *
189  */
190 void die(const char *fmt, ...) {
191         char buffer[512];
192         va_list ap;
193         va_start(ap, fmt);
194         (void)vsnprintf(buffer, sizeof(buffer), fmt, ap);
195         va_end(ap);
196
197         if (wmii_path != NULL)
198                 write_error_to_statusbar(buffer);
199         exit(EXIT_FAILURE);
200 }
201
202 /*
203  * Skip the given character for maximum 'amount' times, returns
204  * a pointer to the first non-'character' character in 'input'.
205  *
206  */
207 static char *skip_character(char *input, char character, int amount) {
208         char *walk;
209         size_t len = strlen(input);
210         int blanks = 0;
211
212         for (walk = input; ((size_t)(walk - input) < len) && (blanks < amount); walk++)
213                 if (*walk == character)
214                         blanks++;
215
216         return (walk == input ? walk : walk-1);
217 }
218
219 /*
220  * Get battery information from /sys. Note that it uses the design capacity to
221  * calculate the percentage, not the last full capacity, so you can see how
222  * worn off your battery is.
223  *
224  */
225 static char *get_battery_info() {
226         char buf[1024];
227         static char part[512];
228         char *walk, *last;
229         int fd;
230         int full_design = -1,
231             remaining = -1,
232             present_rate = -1;
233         charging_status_t status = CS_DISCHARGING;
234
235         if ((fd = open(battery_path, O_RDONLY)) == -1)
236                 return "No battery found";
237
238         memset(part, 0, sizeof(part));
239         (void)read(fd, buf, sizeof(buf));
240         for (walk = buf, last = buf; (walk-buf) < 1024; walk++)
241                 if (*walk == '=') {
242                         if (BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_FULL_DESIGN") ||
243                             BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_FULL_DESIGN"))
244                                 full_design = atoi(walk+1);
245                         else if (BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_NOW") ||
246                                  BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_NOW"))
247                                 remaining = atoi(walk+1);
248                         else if (BEGINS_WITH(last, "POWER_SUPPLY_CURRENT_NOW"))
249                                 present_rate = atoi(walk+1);
250                         else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Charging"))
251                                 status = CS_CHARGING;
252                         else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Full"))
253                                 status = CS_FULL;
254                 } else if (*walk == '\n')
255                         last = walk+1;
256         (void)close(fd);
257
258         if ((full_design != -1) && (remaining != -1) && (present_rate != -1)) {
259                 float remaining_time, perc;
260                 int seconds, hours, minutes;
261                 if (status == CS_CHARGING)
262                         remaining_time = ((float)full_design - (float)remaining) / (float)present_rate;
263                 else if (status == CS_DISCHARGING)
264                         remaining_time = ((float)remaining / (float)present_rate);
265                 else {
266                         (void)snprintf(part, sizeof(part), "FULL");
267                         return part;
268                 }
269                 perc = ((float)remaining / (float)full_design);
270
271                 seconds = (int)(remaining_time * 3600.0);
272                 hours = seconds / 3600;
273                 seconds -= (hours * 3600);
274                 minutes = seconds / 60;
275                 seconds -= (minutes * 60);
276
277                 (void)snprintf(part, sizeof(part), "%s %.02f%% %02d:%02d:%02d",
278                         (status == CS_CHARGING? "CHR" : "BAT"),
279                         (perc * 100), hours, minutes, seconds);
280         }
281         return part;
282 }
283
284 /*
285  * Just parses /proc/net/wireless
286  *
287  */
288 static char *get_wireless_info() {
289         char buf[1024];
290         static char part[512];
291         char *interfaces;
292         int fd;
293         memset(buf, 0, sizeof(buf));
294         memset(part, 0, sizeof(part));
295
296         if ((fd = open("/proc/net/wireless", O_RDONLY)) == -1)
297                 die("Could not open /proc/net/wireless");
298         (void)read(fd, buf, sizeof(buf));
299         (void)close(fd);
300
301         interfaces = skip_character(buf, '\n', 2) + 1;
302         while (interfaces < buf+strlen(buf)) {
303                 while (isspace((int)*interfaces))
304                         interfaces++;
305                 if (strncmp(interfaces, wlan_interface, strlen(wlan_interface)) == 0) {
306                         int quality;
307                         /* Skip status field (0000) */
308                         interfaces += strlen(wlan_interface) + 2;
309                         interfaces = skip_character(interfaces, ' ', 1);
310                         while (isspace((int)*interfaces))
311                                 interfaces++;
312                         quality = atoi(interfaces);
313                         /* For some reason, I get 255 sometimes */
314                         if ((quality == 255) || (quality == 0)) {
315                         if (use_colors)
316                                 (void)snprintf(part, sizeof(part), "%s%s", concat("#FF0000 ", wmii_normcolors), " W: down");
317                         else (void)snprintf(part, sizeof(part), "W: down");
318
319                         } else {
320                                 const char *ip_address;
321                                 (void)snprintf(part, sizeof(part), "W: (%03d%%) ", quality);
322                                 ip_address = get_ip_address(wlan_interface);
323                                 strcpy(part+strlen(part), ip_address);
324                         }
325
326                         return part;
327                 }
328                 interfaces = skip_character(interfaces, '\n', 1) + 1;
329         }
330
331         return part;
332 }
333
334 /*
335  * Return the IP address for the given interface or "no IP" if the
336  * interface is up and running but hasn't got an IP address yet
337  *
338  */
339 static const char *get_ip_address(const char *interface) {
340         static char part[512];
341         struct ifreq ifr;
342         struct sockaddr_in addr;
343         socklen_t len = sizeof(struct sockaddr_in);
344         memset(part, 0, sizeof(part));
345
346         (void)strcpy(ifr.ifr_name, interface);
347         ifr.ifr_addr.sa_family = AF_INET;
348         if (ioctl(general_socket, SIOCGIFADDR, &ifr) < 0)
349                 return NULL;
350
351         memcpy(&addr, &ifr.ifr_addr, len);
352         (void)inet_ntop(AF_INET, &addr.sin_addr.s_addr, part, len);
353         if (strlen(part) == 0)
354                 (void)snprintf(part, sizeof(part), "no IP");
355
356         return part;
357 }
358
359 /*
360  * Combines ethernet IP addresses and speed (if requested) for displaying
361  *
362  */
363 static char *get_eth_info() {
364         static char part[512];
365         const char *ip_address = get_ip_address(eth_interface);
366         int ethspeed = 0;
367
368         if (get_ethspeed) {
369                 /* This code path requires root privileges */
370                 struct ifreq ifr;
371                 struct ethtool_cmd ecmd;
372                 int err;
373
374                 ecmd.cmd = ETHTOOL_GSET;
375                 (void)memset(&ifr, 0, sizeof(ifr));
376                 ifr.ifr_data = (caddr_t)&ecmd;
377                 (void)strcpy(ifr.ifr_name, eth_interface);
378                 if ((err = ioctl(general_socket, SIOCETHTOOL, &ifr)) == 0)
379                         ethspeed = (ecmd.speed == 65535 ? 0 : ecmd.speed);
380                 else get_ethspeed = false;
381         }
382
383         if (ip_address == NULL)
384                 (void)snprintf(part, sizeof(part), "E: down");
385         else {
386                 if (get_ethspeed)
387                         (void)snprintf(part, sizeof(part), "E: %s (%d Mbit/s)", ip_address, ethspeed);
388                 else (void)snprintf(part, sizeof(part), "E: %s", ip_address);
389         }
390
391         return part;
392 }
393
394 /*
395  * Checks if the PID in path is still valid by checking if /proc/<pid> exists
396  *
397  */
398 static bool process_runs(const char *path) {
399         char pidbuf[512],
400              procbuf[512],
401              *walk;
402         ssize_t n;
403         static glob_t globbuf;
404         struct stat statbuf;
405         const char *real_path;
406         int fd;
407
408         if (glob(path, GLOB_NOCHECK | GLOB_TILDE, NULL, &globbuf) < 0)
409                 die("glob() failed");
410         real_path = (globbuf.gl_pathc > 0 ? globbuf.gl_pathv[0] : path);
411         fd = open(real_path, O_RDONLY);
412         globfree(&globbuf);
413         if (fd < 0)
414                 return false;
415         if ((n = read(fd, pidbuf, sizeof(pidbuf))) > 0)
416                 pidbuf[n] = '\0';
417         (void)close(fd);
418         for (walk = pidbuf; *walk != '\0'; walk++)
419                 if (!isdigit((int)(*walk))) {
420                         *walk = '\0';
421                         break;
422                 }
423         (void)snprintf(procbuf, sizeof(procbuf), "/proc/%s", pidbuf);
424         return (stat(procbuf, &statbuf) >= 0);
425 }
426
427 int main(int argc, char *argv[]) {
428         char part[512],
429              pathbuf[512],
430              *end;
431         unsigned int i;
432         int load_avg;
433
434         char *configfile = PREFIX "/etc/wmiistatus.conf";
435         int o, option_index = 0;
436         struct option long_options[] = {
437                 {"config", required_argument, 0, 'c'},
438                 {0, 0, 0, 0}
439         };
440
441         while ((o = getopt_long(argc, argv, "c:", long_options, &option_index)) != -1)
442                 if ((char)o == 'c')
443                         configfile = optarg;
444
445         if (load_configuration(configfile) < 0)
446                 return EXIT_FAILURE;
447
448         setup();
449
450         if ((general_socket = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
451                 die("Could not create socket");
452
453         while (1) {
454                 for (i = 0; i < num_run_watches; i += 2) {
455                         bool running = process_runs(run_watches[i+1]);
456                         if (use_colors)
457                                 snprintf(part, sizeof(part), "%s %s: %s",
458                                         (running ?
459                                                 concat("#00FF00 ", wmii_normcolors) :
460                                                 concat("#FF0000 ", wmii_normcolors)),
461                                         run_watches[i],
462                                         (running ? "yes" : "no"));
463                         else snprintf(part, sizeof(part), "%s: %s", run_watches[i], (running ? "yes" : "no"));
464                         snprintf(pathbuf, sizeof(pathbuf), "%s%s", order[ORDER_RUN], run_watches[i]);
465                         write_to_statusbar(pathbuf, part);
466                 }
467
468                 if (wlan_interface)
469                         write_to_statusbar(concat(order[ORDER_WLAN], "wlan"), get_wireless_info());
470                 if (eth_interface)
471                         write_to_statusbar(concat(order[ORDER_ETH], "eth"), get_eth_info());
472                 if (battery_path)
473                         write_to_statusbar(concat(order[ORDER_BATTERY], "battery"), get_battery_info());
474
475                 /* Get load */
476                 if ((load_avg = open("/proc/loadavg", O_RDONLY)) == -1)
477                         die("Could not open /proc/loadavg");
478                 (void)read(load_avg, part, sizeof(part));
479                 (void)close(load_avg);
480                 end = skip_character(part, ' ', 3);
481                 *end = '\0';
482                 write_to_statusbar(concat(order[ORDER_LOAD], "load"), part);
483
484                 if (time_format) {
485                         /* Get date & time */
486                         time_t current_time = time(NULL);
487                         struct tm *current_tm = localtime(&current_time);
488                         (void)strftime(part, sizeof(part), time_format, current_tm);
489                         write_to_statusbar(concat(order[ORDER_TIME], "time"), part);
490                 }
491
492                 sleep(interval);
493         }
494 }