/
linux.cc
3083 lines (2642 loc) · 90.7 KB
/
linux.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
*
* Conky, a system monitor, based on torsmo
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2007 Toni Spets
* Copyright (c) 2005-2019 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "linux.h"
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <limits.h>
#include <sys/stat.h>
#include <sys/sysinfo.h>
#include <sys/types.h>
#include <clocale>
#include "common.h"
#include "conky.h"
#include "diskio.h"
#include "logging.h"
#include "net_stat.h"
#include "proc.h"
#include "temphelper.h"
#ifndef HAVE_CLOCK_GETTIME
#include <sys/time.h>
#endif
#include <fcntl.h>
#include <unistd.h>
// #include <assert.h>
#include <time.h>
#include <unordered_map>
#include "setting.hh"
#include "top.h"
#include <arpa/inet.h>
#include <linux/sockios.h>
#include <net/if.h>
#include <netinet/in.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#ifdef _NET_IF_H
#define _LINUX_IF_H
#endif
#include <linux/route.h>
#include <linux/version.h>
#include <math.h>
#include <pthread.h>
#include <atomic>
#include <mutex>
/* The following ifdefs were adapted from gkrellm */
#include <linux/major.h>
#if !defined(MD_MAJOR)
#define MD_MAJOR 9
#endif
#if !defined(LVM_BLK_MAJOR)
#define LVM_BLK_MAJOR 58
#endif
#if !defined(NBD_MAJOR)
#define NBD_MAJOR 43
#endif
#if !defined(DM_MAJOR)
#define DM_MAJOR 253
#endif
#ifdef BUILD_WLAN
#include <iwlib.h>
#endif
struct sysfs {
int fd;
int arg;
char devtype[256];
char type[64];
float factor, offset;
};
/* To be used inside upspeed/f downspeed/f as ${gw_iface} variable */
char e_iface[50];
/* To use ${iface X} where X is a number and will
* return the current X NIC name */
static const unsigned int iface_len = 64U;
char interfaces_arr[MAX_NET_INTERFACES][iface_len] = {""};
#define SHORTSTAT_TEMPL "%*s %llu %llu %llu"
#define LONGSTAT_TEMPL "%*s %llu %llu %llu "
static conky::simple_config_setting<bool> top_cpu_separate("top_cpu_separate",
false, true);
/* This flag tells the linux routines to use the /proc system where possible,
* even if other api's are available, e.g. sysinfo() or getloadavg().
* the reason for this is to allow for /proc-based distributed monitoring.
* using a flag in this manner creates less confusing code. */
static int prefer_proc = 0;
/* To tell 'print_sysfs_sensor' whether to print the temperature
* in int or float */
static const char *temp2 = "empty";
void prepare_update(void) {}
int update_uptime(void) {
#ifdef HAVE_SYSINFO
if (!prefer_proc) {
struct sysinfo s_info;
sysinfo(&s_info);
info.uptime = (double)s_info.uptime;
} else
#endif
{
static int reported = 0;
FILE *fp;
if (!(fp = open_file("/proc/uptime", &reported))) {
info.uptime = 0.0;
return 0;
}
if (fscanf(fp, "%lf", &info.uptime) <= 0) info.uptime = 0;
fclose(fp);
}
return 0;
}
int check_mount(struct text_object *obj) {
int ret = 0;
FILE *mtab;
if (!obj->data.s) return 0;
if ((mtab = fopen("/proc/mounts", "r"))) {
char buf1[256], buf2[129];
while (fgets(buf1, 256, mtab)) {
sscanf(buf1, "%*s %128s", buf2);
if (!strcmp(obj->data.s, buf2)) {
ret = 1;
break;
}
}
fclose(mtab);
} else {
NORM_ERR("Could not open mtab");
}
return ret;
}
/* these things are also in sysinfo except Buffers:
* (that's why I'm reading them from proc) */
int update_meminfo(void) {
FILE *meminfo_fp;
static int reported = 0;
/* unsigned int a; */
char buf[256];
/* With multi-threading, calculations that require
* multple steps to reach a final result can cause havok
* if the intermediary calculations are directly assigned to the
* information struct (they may be read by other functions in the meantime).
* These variables keep the calculations local to the function and finish off
* the function by assigning the results to the information struct */
unsigned long long shmem = 0, sreclaimable = 0, curmem = 0, curbufmem = 0,
cureasyfree = 0, memavail = 0;
info.memmax = info.memdirty = info.swap = info.swapfree = info.swapmax =
info.memwithbuffers = info.buffers = info.cached = info.memfree =
info.memeasyfree = 0;
if (!(meminfo_fp = open_file("/proc/meminfo", &reported))) { return 0; }
while (!feof(meminfo_fp)) {
if (fgets(buf, 255, meminfo_fp) == nullptr) { break; }
if (strncmp(buf, "MemTotal:", 9) == 0) {
sscanf(buf, "%*s %llu", &info.memmax);
} else if (strncmp(buf, "MemFree:", 8) == 0) {
sscanf(buf, "%*s %llu", &info.memfree);
} else if (strncmp(buf, "SwapTotal:", 10) == 0) {
sscanf(buf, "%*s %llu", &info.swapmax);
} else if (strncmp(buf, "SwapFree:", 9) == 0) {
sscanf(buf, "%*s %llu", &info.swapfree);
} else if (strncmp(buf, "Buffers:", 8) == 0) {
sscanf(buf, "%*s %llu", &info.buffers);
} else if (strncmp(buf, "Cached:", 7) == 0) {
sscanf(buf, "%*s %llu", &info.cached);
} else if (strncmp(buf, "Dirty:", 6) == 0) {
sscanf(buf, "%*s %llu", &info.memdirty);
} else if (strncmp(buf, "MemAvailable:", 13) == 0) {
sscanf(buf, "%*s %llu", &memavail);
} else if (strncmp(buf, "Shmem:", 6) == 0) {
sscanf(buf, "%*s %llu", &shmem);
} else if (strncmp(buf, "SReclaimable:", 13) == 0) {
sscanf(buf, "%*s %llu", &sreclaimable);
}
}
curmem = info.memwithbuffers = info.memmax - info.memfree;
cureasyfree = info.memfree;
info.swap = info.swapmax - info.swapfree;
/* Reclaimable memory: does not include shared memory, which is part of cached
but unreclaimable. Includes the reclaimable part of the Slab cache though.
Note: when shared memory is swapped out, shmem decreases and swapfree
decreases - we want this.
*/
curbufmem = (info.cached - shmem) + info.buffers + sreclaimable;
/* Calculate the memory usage.
*
* The Linux Kernel introduced a new field for memory available,
* when possible, use that.
* https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773
*/
if (no_buffers.get(*state)) {
#if LINUX_VERSION_CODE <= KERNEL_VERSION(3, 14, 0)
/* Now ('info.mem' - 'info.bufmem') is the *really used* (aka unreclaimable)
memory. When this value reaches the size of the physical RAM, and swap is
full or non-present, OOM happens. Therefore this is the value users want
to monitor, regarding their RAM.
*/
curmem -= curbufmem;
cureasyfree += curbufmem;
#else
curmem = info.memmax - memavail;
cureasyfree += curbufmem;
#endif
}
/* Now that we know that every calculation is finished we can wrap up
* by assigning the values to the information structure */
info.mem = curmem;
info.bufmem = curbufmem;
info.memeasyfree = cureasyfree;
fclose(meminfo_fp);
return 0;
}
void print_laptop_mode(struct text_object *obj, char *p,
unsigned int p_max_size) {
FILE *fp;
int val = -1;
(void)obj;
if ((fp = fopen("/proc/sys/vm/laptop_mode", "r")) != nullptr) {
if (fscanf(fp, "%d\n", &val) <= 0) val = 0;
fclose(fp);
}
snprintf(p, p_max_size, "%d", val);
}
/* my system says:
* # cat /sys/block/sda/queue/scheduler
* noop [anticipatory] cfq
*/
void print_ioscheduler(struct text_object *obj, char *p,
unsigned int p_max_size) {
FILE *fp;
char buf[128];
if (!obj->data.s) goto out_fail;
snprintf(buf, 127, "/sys/block/%s/queue/scheduler", obj->data.s);
if ((fp = fopen(buf, "r")) == nullptr) goto out_fail;
while (fscanf(fp, "%127s", buf) == 1) {
if (buf[0] == '[') {
buf[strlen(buf) - 1] = '\0';
snprintf(p, p_max_size, "%s", buf + 1);
fclose(fp);
return;
}
}
fclose(fp);
out_fail:
snprintf(p, p_max_size, "%s", "n/a");
return;
}
class gw_info_s {
public:
gw_info_s() : iface(nullptr), ip(nullptr), count(0) {}
char *iface;
char *ip;
std::atomic<int> count;
std::mutex mutex;
void reset() {
std::lock_guard<std::mutex> lock(mutex);
free_and_zero(iface);
free_and_zero(ip);
}
};
static gw_info_s gw_info;
char *save_set_string(char *x, char *y) {
if (x != nullptr && strcmp((char *)x, (char *)y)) {
free_and_zero(x);
x = strndup("multiple", text_buffer_size.get(*state));
} else if (x == nullptr && y != nullptr) {
x = strndup(y, text_buffer_size.get(*state));
}
return x;
}
void update_gateway_info_failure(const char *reason) {
if (reason != nullptr) { perror(reason); }
// 2 pointers to 1 location causes a crash when we try to free them both
std::unique_lock<std::mutex> lock(gw_info.mutex);
free_and_zero(gw_info.iface);
free_and_zero(gw_info.ip);
gw_info.iface = strndup("failed", text_buffer_size.get(*state));
gw_info.ip = strndup("failed", text_buffer_size.get(*state));
}
/* Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT */
#define RT_ENTRY_FORMAT "%63s %lx %lx %x %*d %*d %*d %lx %*d %*d %*d\n"
FILE *check_procroute() {
FILE *fp;
if ((fp = fopen("/proc/net/route", "r")) == nullptr) {
update_gateway_info_failure("fopen()");
return nullptr;
}
/* skip over the table header line, which is always present */
if (fscanf(fp, "%*[^\n]\n") < 0) {
fclose(fp);
return nullptr;
}
return fp;
}
int update_gateway_info2(void) {
FILE *fp;
char iface[iface_len];
unsigned long dest;
unsigned long gate;
unsigned long mask;
unsigned int flags;
unsigned int x = 1;
unsigned int z = 1;
int strcmpreturn;
if ((fp = check_procroute()) != nullptr) {
while (!feof(fp)) {
strcmpreturn = 1;
if (fscanf(fp, RT_ENTRY_FORMAT, iface, &dest, &gate, &flags, &mask) !=
5) {
update_gateway_info_failure("fscanf()");
break;
}
if (!(dest || mask) && ((flags & RTF_GATEWAY) || !gate)) {
snprintf(e_iface, 49, "%s", iface);
}
if (1U == x) {
snprintf(interfaces_arr[x++], iface_len - 1, "%s", iface);
continue;
} else if (0 == strcmp(iface, interfaces_arr[x - 1])) {
continue;
}
for (z = 1; z < iface_len - 1 && strcmpreturn == 1; z++) {
strcmpreturn = strcmp(iface, interfaces_arr[z]);
}
if (strcmpreturn == 1) {
snprintf(interfaces_arr[x++], iface_len - 1, "%s", iface);
}
}
fclose(fp);
}
return 0;
}
int update_gateway_info(void) {
FILE *fp;
struct in_addr ina;
char iface[iface_len];
unsigned long dest, gate, mask;
unsigned int flags;
gw_info.reset();
gw_info.count = 0;
if ((fp = check_procroute()) != nullptr) {
while (!feof(fp)) {
if (fscanf(fp, RT_ENTRY_FORMAT, iface, &dest, &gate, &flags, &mask) !=
5) {
update_gateway_info_failure("fscanf()");
break;
}
if (!(dest || mask) && ((flags & RTF_GATEWAY) || !gate)) {
gw_info.count++;
snprintf(e_iface, 49, "%s", iface);
std::unique_lock<std::mutex> lock(gw_info.mutex);
gw_info.iface = save_set_string(gw_info.iface, iface);
ina.s_addr = gate;
gw_info.ip = save_set_string(gw_info.ip, inet_ntoa(ina));
}
}
fclose(fp);
}
return 0;
}
void free_gateway_info(struct text_object *obj) {
(void)obj;
gw_info.reset();
}
int gateway_exists(struct text_object *obj) {
(void)obj;
return !!gw_info.count;
}
void print_gateway_iface(struct text_object *obj, char *p,
unsigned int p_max_size) {
(void)obj;
std::lock_guard<std::mutex> lock(gw_info.mutex);
snprintf(p, p_max_size, "%s", gw_info.iface);
}
void print_gateway_iface2(struct text_object *obj, char *p,
unsigned int p_max_size) {
long int z = 0;
unsigned int x = 1;
unsigned int found = 0;
char buf[iface_len * iface_len] = {""};
char *buf_ptr = buf;
if (0 == strcmp(obj->data.s, "")) {
for (; x < iface_len - 1; x++) {
if (0 == strcmp("", interfaces_arr[x])) { break; }
buf_ptr += snprintf(buf_ptr, iface_len - 1, "%s, ", interfaces_arr[x]);
found = 1;
}
if (1 == found) {
--buf_ptr;
*(--buf_ptr) = '\0';
}
snprintf(p, p_max_size, "%s", buf);
return;
}
z = strtol(obj->data.s, (char **)NULL, 10);
if ((iface_len - 1) > z) { snprintf(p, p_max_size, "%s", interfaces_arr[z]); }
}
void print_gateway_ip(struct text_object *obj, char *p,
unsigned int p_max_size) {
(void)obj;
std::lock_guard<std::mutex> lock(gw_info.mutex);
snprintf(p, p_max_size, "%s", gw_info.ip);
}
void update_net_interfaces(FILE *net_dev_fp, bool is_first_update,
double time_between_updates) {
/* read each interface */
#ifdef BUILD_WLAN
// wireless info variables
struct wireless_info *winfo;
struct iwreq wrq;
#endif
for (int i = 0; i < MAX_NET_INTERFACES; i++) {
struct net_stat *ns;
char *s, *p;
long long r, t, last_recv, last_trans;
/* quit only after all non-header lines from /proc/net/dev parsed */
// FIXME: arbitrary size chosen to keep code simple.
char buf[256];
if (fgets(buf, 255, net_dev_fp) == nullptr) { break; }
p = buf;
/* change char * p to first non-space character, which is the beginning
* of the interface name */
while (*p != '\0' && isspace((unsigned char)*p)) { p++; }
s = p;
/* increment p until the end of the interface name has been reached */
while (*p != '\0' && *p != ':') { p++; }
if (*p == '\0') { continue; }
/* replace ':' with '\0' in output of /proc/net/dev */
*p = '\0';
p++;
/* get pointer to interface statistics with the interface name in s */
ns = get_net_stat(s, nullptr, NULL);
ns->up = 1;
memset(&(ns->addr.sa_data), 0, 14);
memset(ns->addrs, 0,
17 * MAX_NET_INTERFACES +
1); /* Up to 17 chars per ip, max MAX_NET_INTERFACES interfaces.
Nasty memory usage... */
/* bytes packets errs drop fifo frame compressed multicast|bytes ... */
sscanf(p, "%lld %*d %*d %*d %*d %*d %*d %*d %lld",
&r, &t);
/* if the interface is parsed the first time, then set recv and trans
* to currently received, meaning the change in network traffic is 0 */
if (ns->last_read_recv == -1) {
ns->recv = r;
is_first_update = true;
ns->last_read_recv = r;
}
if (ns->last_read_trans == -1) {
ns->trans = t;
is_first_update = true;
ns->last_read_trans = t;
}
/* move current traffic statistic to last thereby obsoleting the
* current statistic */
last_recv = ns->recv;
last_trans = ns->trans;
/* If recv or trans is less than last time, an overflow happened.
* In that case set the last traffic to the current one, don't set
* it to 0, else a spike in the download and upload speed will occur! */
if (r < ns->last_read_recv) {
last_recv = r;
} else {
ns->recv += (r - ns->last_read_recv);
}
ns->last_read_recv = r;
if (t < ns->last_read_trans) {
last_trans = t;
} else {
ns->trans += (t - ns->last_read_trans);
}
ns->last_read_trans = t;
/*** ip addr patch ***/
int file_descriptor = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
struct ifconf conf;
conf.ifc_buf = (char *)malloc(sizeof(struct ifreq) * MAX_NET_INTERFACES);
conf.ifc_len = sizeof(struct ifreq) * MAX_NET_INTERFACES;
memset(conf.ifc_buf, 0, conf.ifc_len);
ioctl(file_descriptor, SIOCGIFCONF, &conf);
for (unsigned int k = 0; k < conf.ifc_len / sizeof(struct ifreq); k++) {
struct net_stat *ns2;
if (!(((struct ifreq *)conf.ifc_buf) + k)) break;
ns2 = get_net_stat(((struct ifreq *)conf.ifc_buf)[k].ifr_ifrn.ifrn_name,
nullptr, NULL);
ns2->addr = ((struct ifreq *)conf.ifc_buf)[k].ifr_ifru.ifru_addr;
char temp_addr[18];
sprintf(temp_addr, "%u.%u.%u.%u, ", ns2->addr.sa_data[2] & 255,
ns2->addr.sa_data[3] & 255, ns2->addr.sa_data[4] & 255,
ns2->addr.sa_data[5] & 255);
if (nullptr == strstr(ns2->addrs, temp_addr))
strncpy(ns2->addrs + strlen(ns2->addrs), temp_addr, 17);
}
close(file_descriptor);
free(conf.ifc_buf);
/*** end ip addr patch ***/
if (!is_first_update) {
/* calculate instantaneous speeds */
ns->net_rec[0] = (ns->recv - last_recv) / time_between_updates;
ns->net_trans[0] = (ns->trans - last_trans) / time_between_updates;
}
unsigned int curtmp1 = 0;
unsigned int curtmp2 = 0;
/* get an average over the last speed samples */
int samples = net_avg_samples.get(*state);
/* is OpenMP actually useful here? How large is samples? > 1000 ? */
#ifdef HAVE_OPENMP
#pragma omp parallel for reduction(+ : curtmp1, curtmp2) schedule(dynamic, 10)
#endif /* HAVE_OPENMP */
for (int j = 0; j < samples; j++) {
curtmp1 = curtmp1 + ns->net_rec[j];
curtmp2 = curtmp2 + ns->net_trans[j];
}
ns->recv_speed = curtmp1 / (double)samples;
ns->trans_speed = curtmp2 / (double)samples;
if (samples > 1) {
#ifdef HAVE_OPENMP
#pragma omp parallel for schedule(dynamic, 10)
#endif /* HAVE_OPENMP */
for (int j = samples; j > 1; j--) {
ns->net_rec[j - 1] = ns->net_rec[j - 2];
ns->net_trans[j - 1] = ns->net_trans[j - 2];
}
}
#ifdef BUILD_WLAN
/* update wireless info */
winfo = (struct wireless_info *)malloc(sizeof(struct wireless_info));
memset(winfo, 0, sizeof(struct wireless_info));
int skfd = iw_sockets_open();
if (iw_get_basic_config(skfd, s, &(winfo->b)) > -1) {
// set present winfo variables
if (iw_get_range_info(skfd, s, &(winfo->range)) >= 0) {
winfo->has_range = 1;
}
if (iw_get_stats(skfd, s, &(winfo->stats), &winfo->range,
winfo->has_range) >= 0) {
winfo->has_stats = 1;
}
if (iw_get_ext(skfd, s, SIOCGIWAP, &wrq) >= 0) {
winfo->has_ap_addr = 1;
memcpy(&(winfo->ap_addr), &(wrq.u.ap_addr), sizeof(sockaddr));
}
// get bitrate
if (iw_get_ext(skfd, s, SIOCGIWRATE, &wrq) >= 0) {
memcpy(&(winfo->bitrate), &(wrq.u.bitrate), sizeof(iwparam));
iw_print_bitrate(ns->bitrate, 16, winfo->bitrate.value);
}
// get link quality
if (winfo->has_range && winfo->has_stats) {
bool has_qual_level = (winfo->stats.qual.level != 0) ||
(winfo->stats.qual.updated & IW_QUAL_DBM);
if (has_qual_level &&
!(winfo->stats.qual.updated & IW_QUAL_QUAL_INVALID)) {
ns->link_qual = winfo->stats.qual.qual;
if (winfo->range.max_qual.qual > 0) {
ns->link_qual_max = winfo->range.max_qual.qual;
}
}
}
// get ap mac
if (winfo->has_ap_addr) { iw_sawap_ntop(&winfo->ap_addr, ns->ap); }
// get essid
if (winfo->b.has_essid) {
if (winfo->b.essid_on) {
snprintf(ns->essid, 34, "%s", winfo->b.essid);
} else {
snprintf(ns->essid, 34, "%s", "off/any");
}
}
// get channel and freq
if (winfo->b.has_freq) {
if (winfo->has_range == 1) {
ns->channel = iw_freq_to_channel(winfo->b.freq, &(winfo->range));
iw_print_freq_value(ns->freq, 16, winfo->b.freq);
} else {
ns->channel = 0;
ns->freq[0] = 0;
}
}
snprintf(ns->mode, 16, "%s", iw_operation_mode[winfo->b.mode]);
}
iw_sockets_close(skfd);
free(winfo);
#endif
}
}
void update_ipv6_net_stats() {
FILE *file;
char v6addr[33];
char devname[21];
unsigned int netmask, scope;
struct net_stat *ns;
struct v6addr *lastv6;
// remove the old v6 addresses otherwise they are listed multiple times
for (unsigned int i = 0; i < MAX_NET_INTERFACES; i++) {
ns = &netstats[i];
while (ns->v6addrs != nullptr) {
lastv6 = ns->v6addrs;
ns->v6addrs = ns->v6addrs->next;
free(lastv6);
}
}
if ((file = fopen(PROCDIR "/net/if_inet6", "r")) == nullptr) { return; }
while (fscanf(file, "%32s %*02x %02x %02x %*02x %20s\n", v6addr, &netmask,
&scope, devname) != EOF) {
ns = get_net_stat(devname, nullptr, NULL);
if (ns->v6addrs == nullptr) {
lastv6 = (struct v6addr *)malloc(sizeof(struct v6addr));
ns->v6addrs = lastv6;
} else {
lastv6 = ns->v6addrs;
while (lastv6->next) lastv6 = lastv6->next;
lastv6->next = (struct v6addr *)malloc(sizeof(struct v6addr));
lastv6 = lastv6->next;
}
for (int i = 0; i < 16; i++)
sscanf(v6addr + 2 * i, "%2hhx", &(lastv6->addr.s6_addr[i]));
lastv6->netmask = netmask;
switch (scope) {
case 0: // global
lastv6->scope = 'G';
break;
case 16: // host-local
lastv6->scope = 'H';
break;
case 32: // link-local
lastv6->scope = 'L';
break;
case 64: // site-local
lastv6->scope = 'S';
break;
case 128: // compat
lastv6->scope = 'C';
break;
default:
lastv6->scope = '?';
}
lastv6->next = nullptr;
}
fclose(file);
}
/**
* Parses information from /proc/net/dev and stores them in ???
*
* For the output format of /proc/net/dev @see http://linux.die.net/man/5/proc
*
* @return always returns 0. May change in the future, e.g. returning non zero
* if some error happened
**/
int update_net_stats(void) {
update_gateway_info();
update_gateway_info2();
FILE *net_dev_fp;
static int reported = 0;
/* variable to notify the parts averaging the download speed, that this
* is the first call ever to this function. This variable can't be used
* to decide if this is the first time an interface was parsed as there
* are many interfaces, which can be activated and deactivated at arbitrary
* times */
static bool is_first_update = true;
// FIXME: arbitrary size chosen to keep code simple.
char buf[256];
double time_between_updates;
/* get delta */
time_between_updates = current_update_time - last_update_time;
if (time_between_updates <= 0.0001) { return 0; }
/* open file /proc/net/dev. If not something went wrong, clear all
* network statistics */
if (!(net_dev_fp = open_file("/proc/net/dev", &reported))) {
clear_net_stats();
return 0;
}
/* ignore first two header lines in file /proc/net/dev. If somethings
* goes wrong, e.g. end of file reached, quit.
* (Why isn't clear_net_stats called for this case ??? */
char *one = fgets(buf, 255, net_dev_fp);
char *two = fgets(buf, 255, net_dev_fp);
if (!one || /* garbage */
!two) { /* garbage (field names) */
fclose(net_dev_fp);
return 0;
}
update_net_interfaces(net_dev_fp, is_first_update, time_between_updates);
#ifdef BUILD_IPV6
update_ipv6_net_stats();
#endif /* BUILD_IPV6 */
is_first_update = false;
fclose(net_dev_fp);
return 0;
}
int result;
int update_total_processes(void) {
DIR *dir;
struct dirent *entry;
int ignore1;
char ignore2;
info.procs = 0;
dir = opendir("/proc");
if (dir) {
while ((entry = readdir(dir))) {
if (sscanf(entry->d_name, "%d%c", &ignore1, &ignore2) == 1) {
info.procs++;
}
}
closedir(dir);
}
return 0;
}
int update_threads(void) {
#ifdef HAVE_SYSINFO
if (!prefer_proc) {
struct sysinfo s_info;
sysinfo(&s_info);
info.threads = s_info.procs;
} else
#endif
{
static int reported = 0;
FILE *fp;
if (!(fp = open_file("/proc/loadavg", &reported))) {
info.threads = 0;
return 0;
}
if (fscanf(fp, "%*f %*f %*f %*d/%hu", &info.threads) <= 0) info.threads = 0;
fclose(fp);
}
return 0;
}
#define CPU_SAMPLE_COUNT 15
struct cpu_info {
unsigned long long cpu_user;
unsigned long long cpu_system;
unsigned long long cpu_nice;
unsigned long long cpu_idle;
unsigned long long cpu_iowait;
unsigned long long cpu_irq;
unsigned long long cpu_softirq;
unsigned long long cpu_steal;
unsigned long long cpu_total;
unsigned long long cpu_active_total;
unsigned long long cpu_last_total;
unsigned long long cpu_last_active_total;
double cpu_val[CPU_SAMPLE_COUNT];
};
static short cpu_setup = 0;
/* Determine if this kernel gives us "extended" statistics information in
* /proc/stat.
* Kernels around 2.5 and earlier only reported user, system, nice, and
* idle values in proc stat.
* Kernels around 2.6 and greater report these PLUS iowait, irq, softirq,
* and steal */
void determine_longstat(char *buf) {
unsigned long long iowait = 0;
KFLAG_SETOFF(KFLAG_IS_LONGSTAT);
/* scanf will either return -1 or 1 because there is only 1 assignment */
if (sscanf(buf, "%*s %*d %*d %*d %*d %llu", &iowait) > 0) {
KFLAG_SETON(KFLAG_IS_LONGSTAT);
}
}
void determine_longstat_file(void) {
#define MAX_PROCSTAT_LINELEN 255
FILE *stat_fp;
static int reported = 0;
char buf[MAX_PROCSTAT_LINELEN + 1];
if (!(stat_fp = open_file("/proc/stat", &reported))) return;
while (!feof(stat_fp) &&
fgets(buf, MAX_PROCSTAT_LINELEN, stat_fp) != nullptr) {
if (strncmp(buf, "cpu", 3) == 0) {
determine_longstat(buf);
break;
}
}
fclose(stat_fp);
}
void get_cpu_count(void) {
FILE *stat_fp;
static int reported = 0;
char buf[256];
char *str1, *str2, *token, *subtoken;
char *saveptr1, *saveptr2;
int subtoken1 = -1;
int subtoken2 = -1;
if (info.cpu_usage) { return; }
if (!(stat_fp = open_file("/sys/devices/system/cpu/present", &reported))) {
return;
}
info.cpu_count = 0;
while (!feof(stat_fp)) {
if (fgets(buf, 255, stat_fp) == nullptr) { break; }
// Do some parsing here to handle skipped cpu numbers. For example,
// for an AMD FX(tm)-6350 Six-Core Processor /sys/.../present reports
// "0,3-7". I assume that chip is really an 8-core die with two cores
// disabled... Presumably you could also get "0,3-4,6", and other
// combos too...
for (str1 = buf;; str1 = nullptr) {
token = strtok_r(str1, ",", &saveptr1);
if (token == nullptr) break;
++info.cpu_count;
subtoken1 = -1;
subtoken2 = -1;
for (str2 = token;; str2 = nullptr) {
subtoken = strtok_r(str2, "-", &saveptr2);
if (subtoken == nullptr) break;
if (subtoken1 < 0)
subtoken1 = atoi(subtoken);
else
subtoken2 = atoi(subtoken);
}
if (subtoken2 > 0) info.cpu_count += subtoken2 - subtoken1;
}
}
info.cpu_usage = (float *)malloc((info.cpu_count + 1) * sizeof(float));
fclose(stat_fp);
}
#define TMPL_LONGSTAT "%*s %llu %llu %llu %llu %llu %llu %llu %llu"
#define TMPL_SHORTSTAT "%*s %llu %llu %llu %llu"
int update_stat(void) {
FILE *stat_fp;
static int reported = 0;
struct cpu_info *cpu = nullptr;
char buf[256];
int i;
unsigned int idx;
double curtmp;
const char *stat_template = nullptr;
unsigned int malloc_cpu_size = 0;
extern void *global_cpu;
static pthread_mutex_t last_stat_update_mutex = PTHREAD_MUTEX_INITIALIZER;
static double last_stat_update = 0.0;
float cur_total = 0.0;
/* since we use wrappers for this function, the update machinery
* can't eliminate double invocations of this function. Check for
* them here, otherwise cpu_usage counters are freaking out. */
pthread_mutex_lock(&last_stat_update_mutex);
if (last_stat_update == current_update_time) {
pthread_mutex_unlock(&last_stat_update_mutex);
return 0;
}
last_stat_update = current_update_time;
pthread_mutex_unlock(&last_stat_update_mutex);
/* add check for !info.cpu_usage since that mem is freed on a SIGUSR1 */
if (!cpu_setup || !info.cpu_usage) {
get_cpu_count();
cpu_setup = 1;
}
if (!stat_template) {
stat_template =