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