Xinqi Bao's Git

load avg
[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(unknowntext);
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(unknowntext);
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(unknowntext);
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(unknowntext);
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(unknowntext);
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(unknowntext);
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(unknowntext);
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(unknowntext);
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(unknowntext);
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(unknowntext);
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(unknowntext);
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(unknowntext);
278 } else {
279 return smprintf("%d", gid);
280 }
281
282 return smprintf(unknowntext);
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(unknowntext);
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(unknowntext);
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(unknowntext);
334 }
335 return smprintf("%s", host);
336 }
337 }
338
339 /* free the address */
340 freeifaddrs(ifaddr);
341
342 return smprintf(unknowntext);
343 }
344
345 /* load avg */
346 char *
347 load_avg(const char *null)
348 {
349 double avgs[3];
350
351 /* try to get load avg */
352 if (getloadavg(avgs, 3) < 0) {
353 fprintf(stderr, "Error getting load avg.\n");
354 return smprintf(unknowntext);
355 }
356
357 /* return it */
358 return smprintf("%.2f %.2f %.2f", avgs[0], avgs[1], avgs[2]);
359 }
360
361 /* ram free */
362 char *
363 ram_free(const char *null)
364 {
365 long free;
366 FILE *fp;
367
368 /* open meminfo file */
369 if (!(fp = fopen("/proc/meminfo", "r"))) {
370 fprintf(stderr, "Error opening meminfo file.\n");
371 return smprintf(unknowntext);
372 }
373
374 /* read the values */
375 fscanf(fp, "MemFree: %ld kB\n", &free);
376
377 /* close meminfo file */
378 fclose(fp);
379
380 /* return free ram as string */
381 return smprintf("%f", (float)free / 1024 / 1024);
382 }
383
384 /* ram percentage */
385 char *
386 ram_perc(const char *null)
387 {
388 int perc;
389 long total, free, buffers, cached;
390 FILE *fp;
391
392 /* open meminfo file */
393 if (!(fp = fopen("/proc/meminfo", "r"))) {
394 fprintf(stderr, "Error opening meminfo file.\n");
395 return smprintf(unknowntext);
396 }
397
398 /* read the values */
399 fscanf(fp, "MemTotal: %ld kB\n", &total);
400 fscanf(fp, "MemFree: %ld kB\n", &free);
401 fscanf(fp, "MemAvailable: %ld kB\nBuffers: %ld kB\n", &buffers, &buffers);
402 fscanf(fp, "Cached: %ld kB\n", &cached);
403
404 /* close meminfo file */
405 fclose(fp);
406
407 /* calculate percentage */
408 perc = 100 * ((total - free) - (buffers + cached)) / total;
409
410 /* return perc as string */
411 return smprintf("%d%%", perc);
412 }
413
414 /* ram total */
415 char *
416 ram_total(const char *null)
417 {
418 long total;
419 FILE *fp;
420
421 /* open meminfo file */
422 if (!(fp = fopen("/proc/meminfo", "r"))) {
423 fprintf(stderr, "Error opening meminfo file.\n");
424 return smprintf(unknowntext);
425 }
426
427 /* read the values */
428 fscanf(fp, "MemTotal: %ld kB\n", &total);
429
430 /* close meminfo file */
431 fclose(fp);
432
433 /* return total ram as string */
434 return smprintf("%f", (float)total / 1024 / 1024);
435 }
436
437 /* ram used */
438 char *
439 ram_used(const char *null)
440 {
441 long free, total, buffers, cached, used;
442 FILE *fp;
443
444 /* open meminfo file */
445 if (!(fp = fopen("/proc/meminfo", "r"))) {
446 fprintf(stderr, "Error opening meminfo file.\n");
447 return smprintf(unknowntext);
448 }
449
450 /* read the values */
451 fscanf(fp, "MemTotal: %ld kB\n", &total);
452 fscanf(fp, "MemFree: %ld kB\n", &free);
453 fscanf(fp, "MemAvailable: %ld kB\nBuffers: %ld kB\n", &buffers, &buffers);
454 fscanf(fp, "Cached: %ld kB\n", &cached);
455
456 /* close meminfo file */
457 fclose(fp);
458
459 /* calculate used */
460 used = total - free - buffers - cached;
461
462 /* return used ram as string */
463 return smprintf("%f", (float)used / 1024 / 1024);
464 }
465
466 /* custom shell command */
467 char *
468 run_command(const char* command)
469 {
470 int good;
471 FILE *fp;
472 char buffer[64];
473
474 /* try to open the command output */
475 if (!(fp = popen(command, "r"))) {
476 fprintf(stderr, "Could not get command output for: %s.\n", command);
477 return smprintf(unknowntext);
478 }
479
480 /* get command output text, save it to buffer */
481 fgets(buffer, sizeof(buffer) - 1, fp);
482
483 /* close it again */
484 pclose(fp);
485
486 /* add nullchar at the end */
487 for (int i = 0 ; i != sizeof(buffer); i++) {
488 if (buffer[i] == '\0') {
489 good = 1;
490 break;
491 }
492 }
493 if (good) {
494 buffer[strlen(buffer) - 1] = '\0';
495 }
496
497 /* return the output */
498 return smprintf("%s", buffer);
499 }
500
501 /* temperature */
502 char *
503 temp(const char *file)
504 {
505 int temperature;
506 FILE *fp;
507
508 /* open temperature file */
509 if (!(fp = fopen(file, "r"))) {
510 fprintf(stderr, "Could not open temperature file.\n");
511 return smprintf(unknowntext);
512 }
513
514 /* extract temperature */
515 fscanf(fp, "%d", &temperature);
516
517 /* close temperature file */
518 fclose(fp);
519
520 /* return temperature in degrees */
521 return smprintf("%d°C", temperature / 1000);
522 }
523
524 /* username */
525 char *
526 username(const char *null)
527 {
528 register struct passwd *pw;
529 register uid_t uid;
530
531 /* get the values */
532 uid = geteuid();
533 pw = getpwuid(uid);
534
535 /* if it worked, return */
536 if (pw) {
537 return smprintf("%s", pw->pw_name);
538 } else {
539 fprintf(stderr, "Could not get username.\n");
540 return smprintf(unknowntext);
541 }
542
543 return smprintf(unknowntext);
544 }
545
546 /* uid */
547 char *
548 uid(const char *null)
549 {
550 register uid_t uid;
551
552 /* get the values */
553 uid = geteuid();
554
555 /* if it worked, return */
556 if (uid) {
557 return smprintf("%d", uid);
558 } else {
559 fprintf(stderr, "Could not get uid.\n");
560 return smprintf(unknowntext);
561 }
562
563 return smprintf(unknowntext);
564 }
565
566
567 /* alsa volume percentage */
568 char *
569 vol_perc(const char *soundcard)
570 {
571 int mute = 0;
572 long vol = 0, max = 0, min = 0;
573 snd_mixer_t *handle;
574 snd_mixer_elem_t *pcm_mixer, *mas_mixer;
575 snd_mixer_selem_id_t *vol_info, *mute_info;
576
577 /* open everything */
578 snd_mixer_open(&handle, 0);
579 snd_mixer_attach(handle, soundcard);
580 snd_mixer_selem_register(handle, NULL, NULL);
581 snd_mixer_load(handle);
582
583 /* prepare everything */
584 snd_mixer_selem_id_malloc(&vol_info);
585 snd_mixer_selem_id_malloc(&mute_info);
586 /* check */
587 if (vol_info == NULL || mute_info == NULL) {
588 fprintf(stderr, "Could not get alsa volume.\n");
589 return smprintf(unknowntext);
590 }
591 snd_mixer_selem_id_set_name(vol_info, channel);
592 snd_mixer_selem_id_set_name(mute_info, channel);
593 pcm_mixer = snd_mixer_find_selem(handle, vol_info);
594 mas_mixer = snd_mixer_find_selem(handle, mute_info);
595
596 /* get the info */
597 snd_mixer_selem_get_playback_volume_range((snd_mixer_elem_t *)pcm_mixer, &min, &max);
598 snd_mixer_selem_get_playback_volume((snd_mixer_elem_t *)pcm_mixer, SND_MIXER_SCHN_MONO, &vol);
599 snd_mixer_selem_get_playback_switch(mas_mixer, SND_MIXER_SCHN_MONO, &mute);
600
601 /* clean up */
602 if (vol_info) {
603 snd_mixer_selem_id_free(vol_info);
604 }
605 if (mute_info) {
606 snd_mixer_selem_id_free(mute_info);
607 }
608 if (handle) {
609 snd_mixer_close(handle);
610 }
611
612 /* return the string (mute) */
613 if (!mute) {
614 return smprintf("mute");
615 } else {
616 return smprintf("%d%%", (vol * 100) / max);
617 }
618 }
619
620 /* wifi percentage */
621 char *
622 wifi_perc(const char *wificard)
623 {
624 int bufsize = 255;
625 int strength;
626 char buf[bufsize];
627 char *datastart;
628 char path[64];
629 char status[5];
630 char needle[sizeof wificard + 1];
631 FILE *fp;
632
633 /* generate the path name */
634 memset(path, 0, sizeof path);
635 strcat(path, "/sys/class/net/");
636 strcat(path, wificard);
637 strcat(path, "/operstate");
638
639 /* open wifi file */
640 if(!(fp = fopen(path, "r"))) {
641 fprintf(stderr, "Error opening wifi operstate file.\n");
642 return smprintf(unknowntext);
643 }
644
645 /* read the status */
646 fgets(status, 5, fp);
647
648 /* close wifi file */
649 fclose(fp);
650
651 /* check if interface down */
652 if(strcmp(status, "up\n") != 0) {
653 return smprintf(unknowntext);
654 }
655
656 /* open wifi file */
657 if (!(fp = fopen("/proc/net/wireless", "r"))) {
658 fprintf(stderr, "Error opening wireless file.\n");
659 return smprintf(unknowntext);
660 }
661
662 /* extract the signal strength */
663 strcpy(needle, wificard);
664 strcat(needle, ":");
665 fgets(buf, bufsize, fp);
666 fgets(buf, bufsize, fp);
667 fgets(buf, bufsize, fp);
668 if ((datastart = strstr(buf, needle)) != NULL) {
669 datastart = strstr(buf, ":");
670 sscanf(datastart + 1, " %*d %d %*d %*d %*d %*d %*d %*d %*d %*d", &strength);
671 }
672
673 /* close wifi file */
674 fclose(fp);
675
676 /* return strength in percent */
677 return smprintf("%d%%", strength);
678 }
679
680 /* wifi essid */
681 char *
682 wifi_essid(const char *wificard)
683 {
684 char id[IW_ESSID_MAX_SIZE+1];
685 int sockfd;
686 struct iwreq wreq;
687
688 /* prepare */
689 memset(&wreq, 0, sizeof(struct iwreq));
690 wreq.u.essid.length = IW_ESSID_MAX_SIZE+1;
691
692 /* set the interface */
693 sprintf(wreq.ifr_name, wificard);
694
695 /* check */
696 if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
697 fprintf(stderr, "Cannot open socket for interface: %s\n", wificard);
698 return smprintf(unknowntext);
699 }
700 wreq.u.essid.pointer = id;
701 if (ioctl(sockfd,SIOCGIWESSID, &wreq) == -1) {
702 fprintf(stderr, "Get ESSID ioctl failed for interface %s\n", wificard);
703 return smprintf(unknowntext);
704 }
705
706 /* return the essid */
707 if (strcmp((char *)wreq.u.essid.pointer, "") == 0) {
708 return smprintf(unknowntext);
709 } else {
710 return smprintf("%s", (char *)wreq.u.essid.pointer);
711 }
712 }
713
714 /* main function */
715 int
716 main(void)
717 {
718 char status_string[1024];
719 struct arg argument;
720
721 /* try to open display */
722 if (!(dpy = XOpenDisplay(0x0))) {
723 fprintf(stderr, "Cannot open display!\n");
724 exit(1);
725 }
726
727 /* return status every interval */
728 for (;;) {
729 /* clear the string */
730 memset(status_string, 0, sizeof(status_string));
731
732 /* generate status_string */
733 for (size_t i = 0; i < sizeof(args) / sizeof(args[0]); ++i) {
734 argument = args[i];
735 char *res = argument.func(argument.args);
736 char *element = smprintf(argument.format, res);
737 if (element == NULL) {
738 element = smprintf(unknowntext);
739 fprintf(stderr, "Failed to format output.\n");
740 }
741 strcat(status_string, element);
742 free(res);
743 free(element);
744 }
745
746 /* return the statusbar */
747 setstatus(status_string);
748
749 /* wait, "update_interval - 1" because of get_cpu_usage() which uses 1 second */
750 sleep(update_interval -1);
751 }
752
753 /* close display */
754 XCloseDisplay(dpy);
755
756 /* exit successfully */
757 return 0;
758 }