Xinqi Bao's Git

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