Xinqi Bao's Git

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