Xinqi Bao's Git

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