Xinqi Bao's Git

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