Xinqi Bao's Git

Added \n to all error messages.
[slstatus.git] / slstatus.c
1 /* See LICENSE file for copyright and license details. */
2
3 /* global libraries */
4 #include <alsa/asoundlib.h>
5 #include <arpa/inet.h>
6 #include <fcntl.h>
7 #include <ifaddrs.h>
8 #include <limits.h>
9 #include <linux/wireless.h>
10 #include <locale.h>
11 #include <netdb.h>
12 #include <pwd.h>
13 #include <stdarg.h>
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <string.h>
17 #include <sys/ioctl.h>
18 #include <sys/stat.h>
19 #include <sys/statvfs.h>
20 #include <sys/socket.h>
21 #include <sys/types.h>
22 #include <time.h>
23 #include <unistd.h>
24 #include <X11/Xlib.h>
25
26 /* local headers */
27 #include "slstatus.h"
28 #include "config.h"
29
30 /* set statusbar */
31 void
32 setstatus(const char *str)
33 {
34 /* set WM_NAME via X11 */
35 XStoreName(dpy, DefaultRootWindow(dpy), str);
36 XSync(dpy, False);
37 }
38
39 /* smprintf function */
40 char *
41 smprintf(const char *fmt, ...)
42 {
43 va_list fmtargs;
44 char *ret = NULL;
45
46 va_start(fmtargs, fmt);
47 if (vasprintf(&ret, fmt, fmtargs) < 0) {
48 return NULL;
49 }
50 va_end(fmtargs);
51
52 return ret;
53 }
54
55 /* battery percentage */
56 char *
57 battery_perc(const char *battery)
58 {
59 int now, full, perc;
60 char batterynowfile[64] = "";
61 char batteryfullfile[64] = "";
62 FILE *fp;
63
64 /* generate battery nowfile path */
65 strcat(batterynowfile, batterypath);
66 strcat(batterynowfile, battery);
67 strcat(batterynowfile, "/");
68 strcat(batterynowfile, batterynow);
69
70 /* generate battery fullfile path */
71 strcat(batteryfullfile, batterypath);
72 strcat(batteryfullfile, battery);
73 strcat(batteryfullfile, "/");
74 strcat(batteryfullfile, batteryfull);
75
76 /* open battery now file */
77 if (!(fp = fopen(batterynowfile, "r"))) {
78 fprintf(stderr, "Error opening battery file: %s.\n", batterynowfile);
79 return smprintf("n/a");
80 }
81
82 /* read value */
83 fscanf(fp, "%i", &now);
84
85 /* close battery now file */
86 fclose(fp);
87
88 /* open battery full file */
89 if (!(fp = fopen(batteryfullfile, "r"))) {
90 fprintf(stderr, "Error opening battery file.\n");
91 return smprintf("n/a");
92 }
93
94 /* read value */
95 fscanf(fp, "%i", &full);
96
97 /* close battery full file */
98 fclose(fp);
99
100 /* calculate percent */
101 perc = now / (full / 100);
102
103 /* return perc as string */
104 return smprintf("%d%%", perc);
105 }
106
107 /* cpu percentage */
108 char *
109 cpu_perc(const char *null)
110 {
111 int perc;
112 long double a[4], b[4];
113 FILE *fp;
114
115 /* open stat file */
116 if (!(fp = fopen("/proc/stat","r"))) {
117 fprintf(stderr, "Error opening stat file.\n");
118 return smprintf("n/a");
119 }
120
121 /* read values */
122 fscanf(fp, "%*s %Lf %Lf %Lf %Lf", &a[0], &a[1], &a[2], &a[3]);
123
124 /* close stat file */
125 fclose(fp);
126
127 /* wait a second (for avg values) */
128 sleep(1);
129
130 /* open stat file */
131 if (!(fp = fopen("/proc/stat","r"))) {
132 fprintf(stderr, "Error opening stat file.\n");
133 return smprintf("n/a");
134 }
135
136 /* read values */
137 fscanf(fp, "%*s %Lf %Lf %Lf %Lf", &b[0], &b[1], &b[2], &b[3]);
138
139 /* close stat file */
140 fclose(fp);
141
142 /* calculate avg in this second */
143 perc = 100 * ((b[0]+b[1]+b[2]) - (a[0]+a[1]+a[2])) / ((b[0]+b[1]+b[2]+b[3]) - (a[0]+a[1]+a[2]+a[3]));
144
145 /* return perc as string */
146 return smprintf("%d%%", perc);
147 }
148
149 /* date and time */
150 char *
151 datetime(const char *timeformat)
152 {
153 time_t tm;
154 size_t bufsize = 64;
155 char *buf = malloc(bufsize);
156 if (buf == NULL) {
157 fprintf(stderr, "Failed to get date/time.\n");
158 return smprintf("n/a");
159 }
160
161 /* get time in format */
162 time(&tm);
163 setlocale(LC_TIME, "");
164 if (!strftime(buf, bufsize, timeformat, localtime(&tm))) {
165 setlocale(LC_TIME, "C");
166 free(buf);
167 fprintf(stderr, "Strftime failed.\n");
168 return smprintf("n/a");
169 }
170
171 setlocale(LC_TIME, "C");
172 /* return time */
173 char *ret = smprintf("%s", buf);
174 free(buf);
175 return ret;
176 }
177
178 /* disk free */
179 char *
180 disk_free(const char *mountpoint)
181 {
182 struct statvfs fs;
183
184 /* try to open mountpoint */
185 if (statvfs(mountpoint, &fs) < 0) {
186 fprintf(stderr, "Could not get filesystem info.\n");
187 return smprintf("n/a");
188 }
189
190 /* return free */
191 return smprintf("%f", (float)fs.f_bsize * (float)fs.f_bfree / 1024 / 1024 / 1024);
192 }
193
194 /* disk usage percentage */
195 char *
196 disk_perc(const char *mountpoint)
197 {
198 int perc = 0;
199 struct statvfs fs;
200
201 /* try to open mountpoint */
202 if (statvfs(mountpoint, &fs) < 0) {
203 fprintf(stderr, "Could not get filesystem info.\n");
204 return smprintf("n/a");
205 }
206
207 /* calculate percent */
208 perc = 100 * (1.0f - ((float)fs.f_bfree / (float)fs.f_blocks));
209
210 /* return perc */
211 return smprintf("%d%%", perc);
212 }
213
214 /* disk total */
215 char *
216 disk_total(const char *mountpoint)
217 {
218 struct statvfs fs;
219
220 /* try to open mountpoint */
221 if (statvfs(mountpoint, &fs) < 0) {
222 fprintf(stderr, "Could not get filesystem info.\n");
223 return smprintf("n/a");
224 }
225
226 /* return total */
227 return smprintf("%f", (float)fs.f_bsize * (float)fs.f_blocks / 1024 / 1024 / 1024);
228 }
229
230 /* disk used */
231 char *
232 disk_used(const char *mountpoint)
233 {
234 struct statvfs fs;
235
236 /* try to open mountpoint */
237 if (statvfs(mountpoint, &fs) < 0) {
238 fprintf(stderr, "Could not get filesystem info.\n");
239 return smprintf("n/a");
240 }
241
242 /* return used */
243 return smprintf("%f", (float)fs.f_bsize * ((float)fs.f_blocks - (float)fs.f_bfree) / 1024 / 1024 / 1024);
244 }
245
246 /* entropy available */
247 char *
248 entropy(const char *null)
249 {
250 int entropy = 0;
251 FILE *fp;
252
253 /* open entropy file */
254 if (!(fp = fopen("/proc/sys/kernel/random/entropy_avail", "r"))) {
255 fprintf(stderr, "Could not open entropy file.\n");
256 return smprintf("n/a");
257 }
258
259 /* extract entropy */
260 fscanf(fp, "%d", &entropy);
261
262 /* close entropy file */
263 fclose(fp);
264
265 /* return entropy */
266 return smprintf("%d", entropy);
267 }
268
269 /* gid */
270 char *
271 gid(const char *null)
272 {
273 gid_t gid;
274
275 if ((gid = getgid()) < 0) {
276 fprintf(stderr, "Could no get gid.\n");
277 return smprintf("n/a");
278 } else {
279 return smprintf("%d", gid);
280 }
281
282 return smprintf("n/a");
283 }
284
285 /* hostname */
286 char *
287 hostname(const char *null)
288 {
289 char hostname[HOST_NAME_MAX];
290 FILE *fp;
291
292 /* open hostname file */
293 if (!(fp = fopen("/proc/sys/kernel/hostname", "r"))) {
294 fprintf(stderr, "Could not open hostname file.\n");
295 return smprintf("n/a");
296 }
297
298 /* extract hostname */
299 fscanf(fp, "%s\n", hostname);
300
301 /* close hostname file */
302 fclose(fp);
303
304 /* return entropy */
305 return smprintf("%s", hostname);
306 }
307
308 /* ip address */
309 char *
310 ip(const char *interface)
311 {
312 struct ifaddrs *ifaddr, *ifa;
313 int s;
314 char host[NI_MAXHOST];
315
316 /* check if getting ip address works */
317 if (getifaddrs(&ifaddr) == -1) {
318 fprintf(stderr, "Error getting IP address.\n");
319 return smprintf("n/a");
320 }
321
322 /* get the ip address */
323 for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
324 if (ifa->ifa_addr == NULL) {
325 continue;
326 }
327
328 s = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in), host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
329
330 if ((strcmp(ifa->ifa_name, interface) == 0) && (ifa->ifa_addr->sa_family == AF_INET)) {
331 if (s != 0) {
332 fprintf(stderr, "Error getting IP address.\n");
333 return smprintf("n/a");
334 }
335 return smprintf("%s", host);
336 }
337 }
338
339 /* free the address */
340 freeifaddrs(ifaddr);
341
342 /* return n/a if nothing works */
343 return smprintf("n/a");
344 }
345
346 /* ram free */
347 char *
348 ram_free(const char *null)
349 {
350 long free;
351 FILE *fp;
352
353 /* open meminfo file */
354 if (!(fp = fopen("/proc/meminfo", "r"))) {
355 fprintf(stderr, "Error opening meminfo file.\n");
356 return smprintf("n/a");
357 }
358
359 /* read the values */
360 fscanf(fp, "MemFree: %ld kB\n", &free);
361
362 /* close meminfo file */
363 fclose(fp);
364
365 /* return free ram as string */
366 return smprintf("%f", (float)free / 1024 / 1024);
367 }
368
369 /* ram percentage */
370 char *
371 ram_perc(const char *null)
372 {
373 int perc;
374 long total, free, buffers, cached;
375 FILE *fp;
376
377 /* open meminfo file */
378 if (!(fp = fopen("/proc/meminfo", "r"))) {
379 fprintf(stderr, "Error opening meminfo file.\n");
380 return smprintf("n/a");
381 }
382
383 /* read the values */
384 fscanf(fp, "MemTotal: %ld kB\n", &total);
385 fscanf(fp, "MemFree: %ld kB\n", &free);
386 fscanf(fp, "MemAvailable: %ld kB\nBuffers: %ld kB\n", &buffers, &buffers);
387 fscanf(fp, "Cached: %ld kB\n", &cached);
388
389 /* close meminfo file */
390 fclose(fp);
391
392 /* calculate percentage */
393 perc = 100 * ((total - free) - (buffers + cached)) / total;
394
395 /* return perc as string */
396 return smprintf("%d%%", perc);
397 }
398
399 /* ram total */
400 char *
401 ram_total(const char *null)
402 {
403 long total;
404 FILE *fp;
405
406 /* open meminfo file */
407 if (!(fp = fopen("/proc/meminfo", "r"))) {
408 fprintf(stderr, "Error opening meminfo file.\n");
409 return smprintf("n/a");
410 }
411
412 /* read the values */
413 fscanf(fp, "MemTotal: %ld kB\n", &total);
414
415 /* close meminfo file */
416 fclose(fp);
417
418 /* return total ram as string */
419 return smprintf("%f", (float)total / 1024 / 1024);
420 }
421
422 /* ram used */
423 char *
424 ram_used(const char *null)
425 {
426 long free, total, buffers, cached, used;
427 FILE *fp;
428
429 /* open meminfo file */
430 if (!(fp = fopen("/proc/meminfo", "r"))) {
431 fprintf(stderr, "Error opening meminfo file.\n");
432 return smprintf("n/a");
433 }
434
435 /* read the values */
436 fscanf(fp, "MemTotal: %ld kB\n", &total);
437 fscanf(fp, "MemFree: %ld kB\n", &free);
438 fscanf(fp, "MemAvailable: %ld kB\nBuffers: %ld kB\n", &buffers, &buffers);
439 fscanf(fp, "Cached: %ld kB\n", &cached);
440
441 /* close meminfo file */
442 fclose(fp);
443
444 /* calculate used */
445 used = total - free - buffers - cached;
446
447 /* return used ram as string */
448 return smprintf("%f", (float)used / 1024 / 1024);
449 }
450
451 /* custom shell command */
452 char *
453 run_command(const char* command)
454 {
455 int good;
456 FILE *fp;
457 char buffer[64];
458
459 /* try to open the command output */
460 if (!(fp = popen(command, "r"))) {
461 fprintf(stderr, "Could not get command output for: %s.\n", command);
462 return smprintf("n/a");
463 }
464
465 /* get command output text, save it to buffer */
466 fgets(buffer, sizeof(buffer) - 1, fp);
467
468 /* close it again */
469 pclose(fp);
470
471 /* add nullchar at the end */
472 for (int i = 0 ; i != sizeof(buffer); i++) {
473 if (buffer[i] == '\0') {
474 good = 1;
475 break;
476 }
477 }
478 if (good) {
479 buffer[strlen(buffer) - 1] = '\0';
480 }
481
482 /* return the output */
483 return smprintf("%s", buffer);
484 }
485
486 /* temperature */
487 char *
488 temp(const char *file)
489 {
490 int temperature;
491 FILE *fp;
492
493 /* open temperature file */
494 if (!(fp = fopen(file, "r"))) {
495 fprintf(stderr, "Could not open temperature file.\n");
496 return smprintf("n/a");
497 }
498
499 /* extract temperature */
500 fscanf(fp, "%d", &temperature);
501
502 /* close temperature file */
503 fclose(fp);
504
505 /* return temperature in degrees */
506 return smprintf("%d°C", temperature / 1000);
507 }
508
509 /* username */
510 char *
511 username(const char *null)
512 {
513 register struct passwd *pw;
514 register uid_t uid;
515
516 /* get the values */
517 uid = geteuid();
518 pw = getpwuid(uid);
519
520 /* if it worked, return */
521 if (pw) {
522 return smprintf("%s", pw->pw_name);
523 } else {
524 fprintf(stderr, "Could not get username.\n");
525 return smprintf("n/a");
526 }
527
528 return smprintf("n/a");
529 }
530
531 /* uid */
532 char *
533 uid(const char *null)
534 {
535 register uid_t uid;
536
537 /* get the values */
538 uid = geteuid();
539
540 /* if it worked, return */
541 if (uid) {
542 return smprintf("%d", uid);
543 } else {
544 fprintf(stderr, "Could not get uid.\n");
545 return smprintf("n/a");
546 }
547
548 return smprintf("n/a");
549 }
550
551
552 /* alsa volume percentage */
553 char *
554 vol_perc(const char *soundcard)
555 {
556 int mute = 0;
557 long vol = 0, max = 0, min = 0;
558 snd_mixer_t *handle;
559 snd_mixer_elem_t *pcm_mixer, *mas_mixer;
560 snd_mixer_selem_id_t *vol_info, *mute_info;
561
562 /* open everything */
563 snd_mixer_open(&handle, 0);
564 snd_mixer_attach(handle, soundcard);
565 snd_mixer_selem_register(handle, NULL, NULL);
566 snd_mixer_load(handle);
567
568 /* prepare everything */
569 snd_mixer_selem_id_malloc(&vol_info);
570 snd_mixer_selem_id_malloc(&mute_info);
571 /* check */
572 if (vol_info == NULL || mute_info == NULL) {
573 fprintf(stderr, "Could not get alsa volume.\n");
574 return smprintf("n/a");
575 }
576 snd_mixer_selem_id_set_name(vol_info, channel);
577 snd_mixer_selem_id_set_name(mute_info, channel);
578 pcm_mixer = snd_mixer_find_selem(handle, vol_info);
579 mas_mixer = snd_mixer_find_selem(handle, mute_info);
580
581 /* get the info */
582 snd_mixer_selem_get_playback_volume_range((snd_mixer_elem_t *)pcm_mixer, &min, &max);
583 snd_mixer_selem_get_playback_volume((snd_mixer_elem_t *)pcm_mixer, SND_MIXER_SCHN_MONO, &vol);
584 snd_mixer_selem_get_playback_switch(mas_mixer, SND_MIXER_SCHN_MONO, &mute);
585
586 /* clean up */
587 if (vol_info) {
588 snd_mixer_selem_id_free(vol_info);
589 }
590 if (mute_info) {
591 snd_mixer_selem_id_free(mute_info);
592 }
593 if (handle) {
594 snd_mixer_close(handle);
595 }
596
597 /* return the string (mute) */
598 if (!mute) {
599 return smprintf("mute");
600 } else {
601 return smprintf("%d%%", (vol * 100) / max);
602 }
603 }
604
605 /* wifi percentage */
606 char *
607 wifi_perc(const char *wificard)
608 {
609 int bufsize = 255;
610 int strength;
611 char buf[bufsize];
612 char *datastart;
613 char path[64];
614 char status[5];
615 char needle[sizeof wificard + 1];
616 FILE *fp;
617
618 /* generate the path name */
619 memset(path, 0, sizeof path);
620 strcat(path, "/sys/class/net/");
621 strcat(path, wificard);
622 strcat(path, "/operstate");
623
624 /* open wifi file */
625 if(!(fp = fopen(path, "r"))) {
626 fprintf(stderr, "Error opening wifi operstate file.\n");
627 return smprintf("n/a");
628 }
629
630 /* read the status */
631 fgets(status, 5, fp);
632
633 /* close wifi file */
634 fclose(fp);
635
636 /* check if interface down */
637 if(strcmp(status, "up\n") != 0) {
638 return smprintf("n/a");
639 }
640
641 /* open wifi file */
642 if (!(fp = fopen("/proc/net/wireless", "r"))) {
643 fprintf(stderr, "Error opening wireless file.\n");
644 return smprintf("n/a");
645 }
646
647 /* extract the signal strength */
648 strcpy(needle, wificard);
649 strcat(needle, ":");
650 fgets(buf, bufsize, fp);
651 fgets(buf, bufsize, fp);
652 fgets(buf, bufsize, fp);
653 if ((datastart = strstr(buf, needle)) != NULL) {
654 datastart = strstr(buf, ":");
655 sscanf(datastart + 1, " %*d %d %*d %*d %*d %*d %*d %*d %*d %*d", &strength);
656 }
657
658 /* close wifi file */
659 fclose(fp);
660
661 /* return strength in percent */
662 return smprintf("%d%%", strength);
663 }
664
665 /* wifi essid */
666 char *
667 wifi_essid(const char *wificard)
668 {
669 char id[IW_ESSID_MAX_SIZE+1];
670 int sockfd;
671 struct iwreq wreq;
672
673 /* prepare */
674 memset(&wreq, 0, sizeof(struct iwreq));
675 wreq.u.essid.length = IW_ESSID_MAX_SIZE+1;
676
677 /* set the interface */
678 sprintf(wreq.ifr_name, wificard);
679
680 /* check */
681 if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
682 fprintf(stderr, "Cannot open socket for interface: %s\n", wificard);
683 return smprintf("n/a");
684 }
685 wreq.u.essid.pointer = id;
686 if (ioctl(sockfd,SIOCGIWESSID, &wreq) == -1) {
687 fprintf(stderr, "Get ESSID ioctl failed for interface %s\n", wificard);
688 return smprintf("n/a");
689 }
690
691 /* return the essid */
692 if (strcmp((char *)wreq.u.essid.pointer, "") == 0) {
693 return smprintf("n/a");
694 } else {
695 return smprintf("%s", (char *)wreq.u.essid.pointer);
696 }
697 }
698
699 /* main function */
700 int
701 main(void)
702 {
703 char status_string[1024];
704 struct arg argument;
705
706 /* try to open display */
707 if (!(dpy = XOpenDisplay(0x0))) {
708 fprintf(stderr, "Cannot open display!\n");
709 exit(1);
710 }
711
712 /* return status every interval */
713 for (;;) {
714 /* clear the string */
715 memset(status_string, 0, sizeof(status_string));
716
717 /* generate status_string */
718 for (size_t i = 0; i < sizeof(args) / sizeof(args[0]); ++i) {
719 argument = args[i];
720 char *res = argument.func(argument.args);
721 char *element = smprintf(argument.format, res);
722 if (element == NULL) {
723 element = smprintf("n/a");
724 fprintf(stderr, "Failed to format output.\n");
725 }
726 strcat(status_string, element);
727 free(res);
728 free(element);
729 }
730
731 /* return the statusbar */
732 setstatus(status_string);
733
734 /* wait, "update_interval - 1" because of get_cpu_usage() which uses 1 second */
735 sleep(update_interval -1);
736 }
737
738 /* close display */
739 XCloseDisplay(dpy);
740
741 /* exit successfully */
742 return 0;
743 }