-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.c
More file actions
2796 lines (2542 loc) · 89.3 KB
/
Copy pathmain.c
File metadata and controls
2796 lines (2542 loc) · 89.3 KB
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
/*
* socketdaemon/main.c
*
* Unix Domain Socket daemon for Enigma2 / OpenATV.
* Listens on /var/run/daemon.socket (AF_UNIX SOCK_STREAM).
*
* Protocol (null-terminated strings):
* Client sends: "<COMMAND>[,<data>]\0"
* Daemon replies: "RC:<exitcode>" (0 = success, 127 = unknown command)
*
* Supported commands:
* RESTART,<service> → /etc/init.d/<service> restart
* START,<service> → /etc/init.d/<service> start
* STOP,<service> → /etc/init.d/<service> stop
* SWITCH_SOFTCAM,<name> → stop + re-link + start softcam
* SWITCH_CARDSERVER,<name> → stop + re-link + start cardserver
* NETRESTART → netrestarter restart all
* NETRESTART,<iface> → netrestarter restart <iface>
* (iface: eth0, wlan0, wlan1, …)
* PING,<iface>,<host> → one ICMP echo bound to <iface>, 2s timeout
* (exitcode 0 = reply received, 1 = no reply)
* RESOLVE,<host> → resolve <host> via getaddrinfo (AF_INET)
* (exitcode 0 = resolved, 1 = failed)
* NETSCAN,<cidr>,<port>[,<port>...]
* → active TCP connect-scan of <cidr> (max /24,
* i.e. up to 256 host addresses) against the
* given ports, writes /var/run/netscan
* (exitcode 0 = scan completed, 1 = bad params).
* Blocks the caller for the scan's duration
* (bounded, see NETSCAN block below) - same
* blocking-per-command model as PING above.
*
* In addition to on-demand NETSCAN, the daemon runs its own unattended
* discovery scan once at startup (SMB/NFS ports 445+2049 against the
* default-route interface's subnet), after waiting for that interface to
* have a usable IPv4 address - see nm_run_autoscan().
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/un.h>
#include <sys/ioctl.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <net/if.h>
#include <ifaddrs.h>
#include <netdb.h>
#include <linux/ethtool.h>
#include <linux/sockios.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <linux/if_addr.h>
#include <pthread.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <stdarg.h>
#include <signal.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <poll.h>
#define CMD_SOCKET_NAME "/var/run/daemon.socket"
#define CMD_START "START"
#define CMD_STOP "STOP"
#define CMD_RESTART "RESTART"
#define CMD_SWITCH_CAM "SWITCH_SOFTCAM"
#define CMD_SWITCH_CARDSERVER "SWITCH_CARDSERVER"
#define CMD_NETRESTART "NETRESTART"
#define NETRESTARTER_SH "/etc/init.d/netrestarter"
#define NET_SOCKET_NAME "/var/run/daemon_net.socket"
#define NETLINK_KOBJECT_UEVENT 15
#define CMD_IFUP "IFUP"
#define CMD_IFDOWN "IFDOWN"
#define CMD_WLANUP "WLANUP"
#define CMD_WLANDOWN "WLANDOWN"
#define WLANACTIVATOR_SH "/etc/init.d/wlanactivator"
#define CMD_PING "PING"
#define CMD_RESOLVE "RESOLVE"
#define CMD_NETSCAN "NETSCAN"
/* network monitor */
#define NETINFO_PATH "/var/run/netinfo"
#define NETINFO_TMP "/var/run/netinfo.tmp"
/* Safety fallback interval – only fires if kernel emits no events (e.g.
* DHCP renewal on kernel 3.14 does not generate RTMGRP_IPV4_IFADDR).
* select() is blocking, so this costs zero CPU while waiting. */
#define POLL_INTERVAL_SEC 120
#define NETMON_BUF_SIZE 8192
/*
* Minimal wireless ioctl definitions – avoids linux/wireless.h header
* conflicts with net/if.h on older glibc/kernel header combinations.
*/
#ifndef SIOCGIWNAME
#define SIOCGIWNAME 0x8B01
#endif
#ifndef SIOCGIWFREQ
#define SIOCGIWFREQ 0x8B05
#endif
#ifndef SIOCGIWSTATS
#define SIOCGIWSTATS 0x8B0F
#endif
#ifndef SIOCGIWAP
#define SIOCGIWAP 0x8B15
#endif
#ifndef SIOCGIWESSID
#define SIOCGIWESSID 0x8B1B
#endif
#ifndef SIOCGIWRATE
#define SIOCGIWRATE 0x8B21
#endif
#define NM_IW_ESSID_MAX 32
#define NM_IW_QUAL_DBM 0x08
struct nm_iw_quality { uint8_t qual, level, noise, updated; };
struct nm_iw_stats { uint16_t status; struct nm_iw_quality qual; };
struct nm_iw_point { void *pointer; uint16_t length, flags; };
union nm_iwreq_data {
char name[IFNAMSIZ];
struct nm_iw_point essid;
struct { void *pointer; uint16_t length, flags; } data;
struct { uint16_t sa_family; uint8_t sa_data[14]; } ap_addr; /* SIOCGIWAP */
struct { int32_t m; int16_t e; uint8_t i; uint8_t flags; } freq; /* SIOCGIWFREQ */
struct { int32_t value; uint8_t fixed; uint8_t disabled; uint16_t flags; } param; /* SIOCGIWRATE */
};
struct nm_iwreq { char iw_ifname[IFNAMSIZ]; union nm_iwreq_data u; };
/*
* Minimal Generic Netlink / nl80211 definitions – hand-rolled like the
* wireless-extension ioctls above, to avoid depending on linux/nl80211.h
* and linux/genetlink.h, which aren't guaranteed present/consistent across
* the many cross-compilation kernel header sets this daemon is built with.
*/
#define NM_NETLINK_GENERIC 16
#define NM_GENL_ID_CTRL 0x10
#define NM_CTRL_CMD_GETFAMILY 3
#define NM_CTRL_ATTR_FAMILY_ID 1
#define NM_CTRL_ATTR_FAMILY_NAME 2
#define NM_NL80211_CMD_GET_STATION 17
#define NM_NL80211_ATTR_IFINDEX 3
#define NM_NL80211_ATTR_MAC 6
#define NM_NL80211_ATTR_STA_INFO 21
#define NM_NL80211_STA_INFO_TX_BITRATE 8
#define NM_NL80211_RATE_INFO_BITRATE 1
#define NM_NL80211_RATE_INFO_BITRATE32 5
struct nm_genlmsghdr { uint8_t cmd, version; uint16_t reserved; };
static int verbose = 0;
static volatile sig_atomic_t running = 1;
static pthread_t g_monitor_tid;
static int g_stop_pipe[2] = {-1, -1};
/* Serializes access to the netscan machinery's static scan/DNS-cache
* buffers (see NETSCAN block below) between two independent callers that
* run on different threads: CMD_NETSCAN (processMessage(), on the main
* accept-loop thread) and nm_run_autoscan() (on its own thread, spawned
* once by monitor_thread() at startup). */
static pthread_mutex_t g_netscan_mutex = PTHREAD_MUTEX_INITIALIZER;
int processMessage(char *inData);
static void *monitor_thread(void *arg);
static void *nm_autoscan_thread(void *arg);
static FILE *log_stream;
static void handle_signal(int sig)
{
(void)sig;
running = 0;
/* wake monitor thread out of select() immediately */
if (g_stop_pipe[1] >= 0) {
char b = 0;
(void)write(g_stop_pipe[1], &b, 1);
}
}
void LOG(const char *format, ...)
{
char buf[2048];
char timebuf[50];
va_list other_args;
time_t t;
struct tm *tm;
va_start(other_args, format);
vsnprintf(buf, sizeof(buf), format, other_args);
va_end(other_args);
time(&t);
tm = gmtime(&t);
if (tm)
{
strftime(timebuf, sizeof(timebuf), "%Y-%m-%dT%H:%M:%SZ", tm);
fprintf(log_stream, "[%s] %s", timebuf, buf);
}
else
{
fprintf(log_stream, "%s", buf);
}
fflush(log_stream);
}
/* ============================================================
* Network monitor helpers
* ============================================================ */
/* VPN tunnels (WireGuard, OpenVPN tun/tap, PPP) show up as regular
* point-to-point interfaces in /proc/net/dev; tell them apart from
* physical links via IFF_POINTOPOINT plus the usual name prefixes. */
static int nm_is_vpn(short flags, const char *iface)
{
if (flags & IFF_POINTOPOINT)
return 1;
return !strncmp(iface, "wg", 2) || !strncmp(iface, "tun", 3) ||
!strncmp(iface, "tap", 3) || !strncmp(iface, "ppp", 3) ||
!strncmp(iface, "zt", 2);
}
static int nm_is_wireless(int sock, const char *iface)
{
struct nm_iwreq wrq;
memset(&wrq, 0, sizeof(wrq));
strncpy(wrq.iw_ifname, iface, IFNAMSIZ - 1);
return ioctl(sock, SIOCGIWNAME, &wrq) >= 0;
}
static int nm_get_link(int sock, const char *iface)
{
struct ifreq ifr;
struct ethtool_value ev;
memset(&ifr, 0, sizeof(ifr));
memset(&ev, 0, sizeof(ev));
strncpy(ifr.ifr_name, iface, IFNAMSIZ - 1);
ev.cmd = ETHTOOL_GLINK;
ifr.ifr_data = (void *)&ev;
if (ioctl(sock, SIOCETHTOOL, &ifr) < 0)
return -1;
return (int)ev.data;
}
static const char *nm_port_str(uint8_t port)
{
switch (port) {
case 0x00: return "TP";
case 0x01: return "AUI";
case 0x02: return "MII";
case 0x03: return "FIBRE";
case 0x04: return "BNC";
case 0x05: return "DA";
default: return NULL;
}
}
static void nm_get_eth_info(int sock, const char *iface,
int *speed, int *duplex,
int *port, int *xcvr, int *autoneg,
uint32_t *supported)
{
struct ifreq ifr;
struct ethtool_cmd ecmd;
*speed = -1;
*duplex = -1;
*port = -1;
*xcvr = -1;
*autoneg = -1;
*supported = 0;
memset(&ifr, 0, sizeof(ifr));
memset(&ecmd, 0, sizeof(ecmd));
strncpy(ifr.ifr_name, iface, IFNAMSIZ - 1);
ecmd.cmd = ETHTOOL_GSET;
ifr.ifr_data = (void *)&ecmd;
if (ioctl(sock, SIOCETHTOOL, &ifr) < 0)
return;
*speed = (int)ethtool_cmd_speed(&ecmd);
*duplex = (int)ecmd.duplex; /* 0=half, 1=full */
*port = (int)ecmd.port;
*xcvr = (int)ecmd.transceiver;
*autoneg = (int)ecmd.autoneg; /* 0=off, 1=on */
*supported = ecmd.supported; /* SUPPORTED_* bitmask */
}
static void nm_get_wlan_ssid(int sock, const char *iface, char *out, size_t outsz)
{
struct nm_iwreq wrq;
out[0] = '\0';
memset(&wrq, 0, sizeof(wrq));
strncpy(wrq.iw_ifname, iface, IFNAMSIZ - 1);
wrq.u.essid.pointer = out;
wrq.u.essid.length = (uint16_t)(outsz - 1);
wrq.u.essid.flags = 0;
if (ioctl(sock, SIOCGIWESSID, &wrq) >= 0) {
size_t len = wrq.u.essid.length < outsz - 1 ? wrq.u.essid.length : outsz - 1;
out[len] = '\0';
} else {
out[0] = '\0';
}
}
static int nm_get_wlan_signal(int sock, const char *iface)
{
struct nm_iwreq wrq;
struct nm_iw_stats stats;
memset(&wrq, 0, sizeof(wrq));
memset(&stats, 0, sizeof(stats));
strncpy(wrq.iw_ifname, iface, IFNAMSIZ - 1);
wrq.u.data.pointer = &stats;
wrq.u.data.length = sizeof(stats);
wrq.u.data.flags = 1;
if (ioctl(sock, SIOCGIWSTATS, &wrq) < 0)
return 0;
if (stats.qual.updated & NM_IW_QUAL_DBM)
return (int)(int8_t)stats.qual.level;
/* raw hardware value: >63 is typically unsigned dBm offset */
return stats.qual.level > 63 ? (int)stats.qual.level - 256 : (int)stats.qual.level;
}
/* BSSID (AP MAC) via SIOCGIWAP; returns 1 on success */
static int nm_get_wlan_bssid(int sock, const char *iface, char *out, size_t outsz)
{
struct nm_iwreq wrq;
memset(&wrq, 0, sizeof(wrq));
strncpy(wrq.iw_ifname, iface, IFNAMSIZ - 1);
if (ioctl(sock, SIOCGIWAP, &wrq) < 0)
return 0;
const uint8_t *b = wrq.u.ap_addr.sa_data;
/* all-zero or ff:ff:ff:ff:ff:ff = not associated */
int allzero = 1, allff = 1;
for (int i = 0; i < 6; i++) {
if (b[i] != 0x00) allzero = 0;
if (b[i] != 0xff) allff = 0;
}
if (allzero || allff)
return 0;
snprintf(out, outsz, "%02x:%02x:%02x:%02x:%02x:%02x",
b[0], b[1], b[2], b[3], b[4], b[5]);
return 1;
}
/* Frequency in MHz via SIOCGIWFREQ; returns 0 when not available */
static int nm_get_wlan_freq_mhz(int sock, const char *iface)
{
struct nm_iwreq wrq;
memset(&wrq, 0, sizeof(wrq));
strncpy(wrq.iw_ifname, iface, IFNAMSIZ - 1);
if (ioctl(sock, SIOCGIWFREQ, &wrq) < 0)
return 0;
int32_t m = wrq.u.freq.m;
int16_t e = wrq.u.freq.e;
if (m <= 0 || e < 0)
return 0; /* channel index or invalid */
/* convert m * 10^e Hz → MHz */
while (e > 6) { m *= 10; e--; }
while (e < 6) { m /= 10; e++; }
return (int)m;
}
/* Appends one netlink attribute (type+len+data, 4-byte aligned) to buf at
* off; returns the new offset. Reuses struct rtattr / RTA_* macros from
* linux/rtnetlink.h - identical binary layout to generic-netlink's nlattr. */
static size_t nm_nl_put(void *buf, size_t off, unsigned short type, const void *data, size_t len)
{
struct rtattr *rta = (struct rtattr *)((char *)buf + off);
rta->rta_type = type;
rta->rta_len = RTA_LENGTH(len);
memcpy(RTA_DATA(rta), data, len);
return off + RTA_ALIGN(rta->rta_len);
}
/* Resolves the nl80211 generic-netlink family id once; cached for the
* process lifetime. Returns -1 if generic netlink / nl80211 is unavailable. */
static int nm_nl80211_family_id(void)
{
static int cached = -2; /* -2 = not yet resolved */
if (cached != -2)
return cached;
cached = -1;
int sock = socket(AF_NETLINK, SOCK_RAW, NM_NETLINK_GENERIC);
if (sock < 0)
return cached;
uint8_t txbuf[64];
memset(txbuf, 0, sizeof(txbuf));
struct nlmsghdr *nlh = (struct nlmsghdr *)txbuf;
struct nm_genlmsghdr *genl = (struct nm_genlmsghdr *)NLMSG_DATA(nlh);
genl->cmd = NM_CTRL_CMD_GETFAMILY;
size_t off = NLMSG_ALIGN(sizeof(*nlh)) + sizeof(*genl);
off = nm_nl_put(txbuf, off, NM_CTRL_ATTR_FAMILY_NAME, "nl80211", 8);
nlh->nlmsg_len = (uint32_t)off;
nlh->nlmsg_type = NM_GENL_ID_CTRL;
nlh->nlmsg_flags = NLM_F_REQUEST;
nlh->nlmsg_seq = 1;
if (send(sock, txbuf, off, 0) < 0) {
close(sock);
return cached;
}
/* nl80211's CTRL_ATTR_OPS list alone runs into several KB on modern
* kernels; a too-small buffer here silently truncates the reply and
* makes NLMSG_OK() reject it (nlmsg_len then exceeds the bytes we
* actually received), so family resolution always failed. */
uint8_t rxbuf[8192];
ssize_t len = recv(sock, rxbuf, sizeof(rxbuf), 0);
close(sock);
if (len < (ssize_t)sizeof(struct nlmsghdr))
return cached;
struct nlmsghdr *rnlh = (struct nlmsghdr *)rxbuf;
if (!NLMSG_OK(rnlh, (size_t)len) || rnlh->nlmsg_type == NLMSG_ERROR)
return cached;
struct rtattr *rta = (struct rtattr *)((char *)NLMSG_DATA(rnlh) + sizeof(struct nm_genlmsghdr));
int rtl = (int)(rnlh->nlmsg_len - NLMSG_ALIGN(sizeof(*rnlh)) - sizeof(struct nm_genlmsghdr));
for (; RTA_OK(rta, rtl); rta = RTA_NEXT(rta, rtl)) {
if (rta->rta_type == NM_CTRL_ATTR_FAMILY_ID) {
cached = *(uint16_t *)RTA_DATA(rta);
break;
}
}
return cached;
}
/* Current TX bitrate in bps via nl80211 GET_STATION; returns 0 when
* unavailable. Used as a fallback for SIOCGIWRATE (see below), which some
* 802.11n USB dongles (e.g. rt2800usb / RT2870-RT3070) get stuck reporting
* a stale legacy OFDM floor rate once running at real HT rates. */
static int nm_get_wlan_bitrate_nl80211(const char *iface, const uint8_t mac[6])
{
int family = nm_nl80211_family_id();
if (family < 0)
return 0;
unsigned int ifindex = if_nametoindex(iface);
if (!ifindex)
return 0;
int sock = socket(AF_NETLINK, SOCK_RAW, NM_NETLINK_GENERIC);
if (sock < 0)
return 0;
uint8_t txbuf[128];
memset(txbuf, 0, sizeof(txbuf));
struct nlmsghdr *nlh = (struct nlmsghdr *)txbuf;
struct nm_genlmsghdr *genl = (struct nm_genlmsghdr *)NLMSG_DATA(nlh);
genl->cmd = NM_NL80211_CMD_GET_STATION;
size_t off = NLMSG_ALIGN(sizeof(*nlh)) + sizeof(*genl);
uint32_t ifidx32 = ifindex;
off = nm_nl_put(txbuf, off, NM_NL80211_ATTR_IFINDEX, &ifidx32, sizeof(ifidx32));
off = nm_nl_put(txbuf, off, NM_NL80211_ATTR_MAC, mac, 6);
nlh->nlmsg_len = (uint32_t)off;
nlh->nlmsg_type = (uint16_t)family;
nlh->nlmsg_flags = NLM_F_REQUEST;
nlh->nlmsg_seq = 1;
if (send(sock, txbuf, off, 0) < 0) {
close(sock);
return 0;
}
uint8_t rxbuf[2048];
ssize_t len = recv(sock, rxbuf, sizeof(rxbuf), 0);
close(sock);
if (len < (ssize_t)sizeof(struct nlmsghdr))
return 0;
struct nlmsghdr *rnlh = (struct nlmsghdr *)rxbuf;
if (!NLMSG_OK(rnlh, (size_t)len) || rnlh->nlmsg_type == NLMSG_ERROR)
return 0;
struct rtattr *rta = (struct rtattr *)((char *)NLMSG_DATA(rnlh) + sizeof(struct nm_genlmsghdr));
int rtl = (int)(rnlh->nlmsg_len - NLMSG_ALIGN(sizeof(*rnlh)) - sizeof(struct nm_genlmsghdr));
int bps = 0;
for (; RTA_OK(rta, rtl); rta = RTA_NEXT(rta, rtl)) {
if (rta->rta_type != NM_NL80211_ATTR_STA_INFO)
continue;
struct rtattr *sinfo = (struct rtattr *)RTA_DATA(rta);
int sinfo_len = (int)RTA_PAYLOAD(rta);
for (; RTA_OK(sinfo, sinfo_len); sinfo = RTA_NEXT(sinfo, sinfo_len)) {
if (sinfo->rta_type != NM_NL80211_STA_INFO_TX_BITRATE)
continue;
struct rtattr *rinfo = (struct rtattr *)RTA_DATA(sinfo);
int rinfo_len = (int)RTA_PAYLOAD(sinfo);
for (; RTA_OK(rinfo, rinfo_len); rinfo = RTA_NEXT(rinfo, rinfo_len)) {
/* both units are 100 kbit/s */
if (rinfo->rta_type == NM_NL80211_RATE_INFO_BITRATE32)
bps = (int)(*(uint32_t *)RTA_DATA(rinfo) * 100000u);
else if (rinfo->rta_type == NM_NL80211_RATE_INFO_BITRATE && bps == 0)
bps = (int)(*(uint16_t *)RTA_DATA(rinfo) * 100000u);
}
}
}
return bps;
}
/* TX bitrate in bps via SIOCGIWRATE; returns 0 when not available.
* Corrected with nl80211 GET_STATION when that reports a higher rate -
* mac80211's WEXT compat layer can't represent HT/VHT rates and some
* drivers just leave the field at a legacy floor instead of the real link
* speed (see above), and that wrong value isn't reliably bounded by the
* 802.11a/g 54 Mb/s ceiling on every driver, so nl80211 is always consulted
* rather than only below some ioctl-value threshold. */
static int nm_get_wlan_bitrate(int sock, const char *iface)
{
struct nm_iwreq wrq;
memset(&wrq, 0, sizeof(wrq));
strncpy(wrq.iw_ifname, iface, IFNAMSIZ - 1);
int bps = 0;
if (ioctl(sock, SIOCGIWRATE, &wrq) >= 0 && wrq.u.param.value > 0)
bps = (int)wrq.u.param.value;
char bssidbuf[18];
if (nm_get_wlan_bssid(sock, iface, bssidbuf, sizeof(bssidbuf))) {
uint8_t mac[6];
if (sscanf(bssidbuf, "%2hhx:%2hhx:%2hhx:%2hhx:%2hhx:%2hhx",
&mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5]) == 6) {
int nl_bps = nm_get_wlan_bitrate_nl80211(iface, mac);
if (nl_bps > bps)
bps = nl_bps;
}
}
return bps;
}
/* Channel number from frequency in MHz */
static int nm_freq_to_channel(int mhz)
{
if (mhz == 2484) return 14;
if (mhz >= 2412 && mhz <= 2472) return (mhz - 2407) / 5;
if (mhz >= 5180 && mhz <= 5980) return (mhz - 5000) / 5;
if (mhz >= 5955 && mhz <= 7115) return (mhz - 5950) / 5;
return 0;
}
/* Policy-routing table multihome setups keep per-adapter default routes in
* (one entry per adapter, each with its own metric); see nm_scan_default_routes(). */
#define NM_MULTIHOME_RT_TABLE 201
#define NM_MAX_DEFAULT_ROUTES 16
struct nm_default_route {
unsigned int ifindex;
struct in_addr gw;
unsigned int metric;
int table;
};
/* Every interface's own default route (gateway + metric), plus which
* interface currently owns the system's single active default gateway,
* found via one NETLINK_ROUTE RTM_GETROUTE dump.
*
* Multihome setups keep one default route per interface in
* NM_MULTIHOME_RT_TABLE, all of them present at the same time (so switching
* is just a metric/ip-rule change) but only the one with the lowest metric
* is actually used for outbound traffic. For a given interface, its
* NM_MULTIHOME_RT_TABLE entry is authoritative when present; interfaces
* without one (single-adapter, non-multihome devices) fall back to whatever
* table their default route lives in (normally main). The winner is picked
* the same way, but across interfaces: lowest metric among
* NM_MULTIHOME_RT_TABLE entries if any exist, else lowest metric overall.
*
* Fills routes[] (up to max entries, one per interface that has a default
* route) and returns the entry count. *out_winner_ifindex is set to the
* winning interface's index, or 0 if no default route was found at all. */
static int nm_scan_default_routes(struct nm_default_route *routes, int max, unsigned int *out_winner_ifindex)
{
int count = 0;
*out_winner_ifindex = 0;
int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
if (sock < 0) return 0;
struct {
struct nlmsghdr nlh;
struct rtmsg rtm;
} req;
memset(&req, 0, sizeof(req));
req.nlh.nlmsg_len = sizeof(req);
req.nlh.nlmsg_type = RTM_GETROUTE;
req.nlh.nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP;
req.nlh.nlmsg_seq = 1;
req.rtm.rtm_family = AF_INET;
if (send(sock, &req, req.nlh.nlmsg_len, 0) < 0) { close(sock); return 0; }
int done = 0;
char buf[8192];
while (!done) {
ssize_t len = recv(sock, buf, sizeof(buf), 0);
if (len <= 0) break;
struct nlmsghdr *nlh = (struct nlmsghdr *)buf;
for (; NLMSG_OK(nlh, (size_t)len); nlh = NLMSG_NEXT(nlh, len)) {
if (nlh->nlmsg_type == NLMSG_DONE || nlh->nlmsg_type == NLMSG_ERROR) {
done = 1;
break;
}
if (nlh->nlmsg_type != RTM_NEWROUTE) continue;
struct rtmsg *rtm = (struct rtmsg *)NLMSG_DATA(nlh);
if (rtm->rtm_dst_len != 0) continue; /* default route only */
struct rtattr *rta = RTM_RTA(rtm);
int rtl = (int)RTM_PAYLOAD(nlh);
unsigned int oif = 0, metric = 0;
struct in_addr gw = { 0 };
int haveGw = 0;
for (; RTA_OK(rta, rtl); rta = RTA_NEXT(rta, rtl)) {
switch (rta->rta_type) {
case RTA_OIF: oif = *(unsigned int *)RTA_DATA(rta); break;
case RTA_GATEWAY: gw = *(struct in_addr *)RTA_DATA(rta); haveGw = 1; break;
case RTA_PRIORITY: metric = *(unsigned int *)RTA_DATA(rta); break;
}
}
if (!haveGw || !oif) continue;
/* keep, per interface, its NM_MULTIHOME_RT_TABLE entry if there is
* one, else the first entry seen for it */
struct nm_default_route *existing = NULL;
for (int i = 0; i < count; i++) {
if (routes[i].ifindex == oif) { existing = &routes[i]; break; }
}
if (existing) {
if (rtm->rtm_table == NM_MULTIHOME_RT_TABLE)
*existing = (struct nm_default_route){ oif, gw, metric, rtm->rtm_table };
} else if (count < max) {
routes[count++] = (struct nm_default_route){ oif, gw, metric, rtm->rtm_table };
}
}
}
close(sock);
/* winner: lowest metric among NM_MULTIHOME_RT_TABLE entries if any exist,
* else lowest metric overall */
int anyMultihome = 0;
for (int i = 0; i < count; i++)
if (routes[i].table == NM_MULTIHOME_RT_TABLE) { anyMultihome = 1; break; }
int winner = -1;
for (int i = 0; i < count; i++) {
if (anyMultihome && routes[i].table != NM_MULTIHOME_RT_TABLE) continue;
if (winner < 0 || routes[i].metric < routes[winner].metric)
winner = i;
}
if (winner >= 0) *out_winner_ifindex = routes[winner].ifindex;
return count;
}
/* IPv6 addresses from /proc/net/if_inet6 as a JSON array.
* out is set to "" when no addresses are found. */
/* IPv6 scope byte from /proc/net/if_inet6 -> human label, matches ifconfig's "Scope:" */
static const char *nm_ipv6_scope_str(int scope)
{
switch (scope) {
case 0x00: return "global";
case 0x10: return "host";
case 0x20: return "link";
case 0x40: return "site";
case 0x80: return "compat";
default: return "other";
}
}
static void nm_get_ipv6(const char *iface, char *out, size_t outsz)
{
out[0] = '\0';
FILE *f = fopen("/proc/net/if_inet6", "r");
if (!f) return;
char line[256];
int count = 0;
size_t off = 1; /* reserve space for opening '[' */
out[0] = '[';
while (fgets(line, sizeof(line), f)) {
char hex[33], name[IFNAMSIZ];
int idx, plen, scope, flags;
if (sscanf(line, "%32s %x %x %x %x %15s",
hex, &idx, &plen, &scope, &flags, name) != 6)
continue;
if (strcmp(name, iface) != 0) continue;
struct in6_addr a;
for (int i = 0; i < 16; i++) {
char b[3] = { hex[i * 2], hex[i * 2 + 1], '\0' };
a.s6_addr[i] = (uint8_t)strtoul(b, NULL, 16);
}
char astr[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, &a, astr, sizeof(astr));
int n = snprintf(out + off, outsz - off,
"%s{\"addr\":\"%s\",\"prefix\":%d,\"scope\":\"%s\"}",
count ? "," : "", astr, plen, nm_ipv6_scope_str(scope));
if (n > 0) off += n;
count++;
}
fclose(f);
if (count == 0) { out[0] = '\0'; return; }
if (off < outsz) out[off++] = ']';
out[off < outsz ? off : outsz - 1] = '\0';
}
/* WoL capability bitmask via ETHTOOL_GWOL; returns 0 if not supported/available */
static uint32_t nm_get_wol_supported(int sock, const char *iface)
{
struct ifreq ifr;
struct ethtool_wolinfo wol;
memset(&ifr, 0, sizeof(ifr));
memset(&wol, 0, sizeof(wol));
strncpy(ifr.ifr_name, iface, IFNAMSIZ - 1);
wol.cmd = ETHTOOL_GWOL;
ifr.ifr_data = (void *)&wol;
if (ioctl(sock, SIOCETHTOOL, &ifr) < 0)
return 0;
return wol.supported;
}
/* Kernel module name from /sys/class/net/<iface>/device/driver[/module] symlink */
static void nm_get_driver(const char *iface, char *buf, size_t bufsz)
{
char path[256];
char link[256];
ssize_t n;
const char *slash;
buf[0] = '\0';
snprintf(path, sizeof(path), "/sys/class/net/%s/device/driver/module", iface);
n = readlink(path, link, sizeof(link) - 1);
if (n <= 0) {
snprintf(path, sizeof(path), "/sys/class/net/%s/device/driver", iface);
n = readlink(path, link, sizeof(link) - 1);
}
if (n > 0) {
link[n] = '\0';
slash = strrchr(link, '/');
strncpy(buf, slash ? slash + 1 : link, bufsz - 1);
buf[bufsz - 1] = '\0';
}
}
/* Hardware ID: "VVVV:DDDD" (hex, no 0x prefix).
* Tries PCI /sys/.../vendor+device first, then USB idVendor/idProduct. */
static void nm_get_hw_id(const char *iface, char *buf, size_t bufsz)
{
char path[256];
char tmp[16];
FILE *f;
char vendor[16] = {}, device[16] = {};
buf[0] = '\0';
/* PCI */
snprintf(path, sizeof(path), "/sys/class/net/%s/device/vendor", iface);
f = fopen(path, "r");
if (f) {
if (fgets(vendor, sizeof(vendor), f))
vendor[strcspn(vendor, "\n\r")] = '\0';
fclose(f);
}
snprintf(path, sizeof(path), "/sys/class/net/%s/device/device", iface);
f = fopen(path, "r");
if (f) {
if (fgets(device, sizeof(device), f))
device[strcspn(device, "\n\r")] = '\0';
fclose(f);
}
if (vendor[0] && device[0]) {
const char *v = strncmp(vendor, "0x", 2) == 0 ? vendor + 2 : vendor;
const char *d = strncmp(device, "0x", 2) == 0 ? device + 2 : device;
snprintf(buf, bufsz, "%s:%s", v, d);
return;
}
/* USB: parent device has idVendor/idProduct */
snprintf(path, sizeof(path), "/sys/class/net/%s/device/../idVendor", iface);
f = fopen(path, "r");
if (f) {
if (fgets(tmp, sizeof(tmp), f)) {
tmp[strcspn(tmp, "\n\r")] = '\0';
strncpy(vendor, tmp, sizeof(vendor) - 1);
}
fclose(f);
}
snprintf(path, sizeof(path), "/sys/class/net/%s/device/../idProduct", iface);
f = fopen(path, "r");
if (f) {
if (fgets(tmp, sizeof(tmp), f)) {
tmp[strcspn(tmp, "\n\r")] = '\0';
strncpy(device, tmp, sizeof(device) - 1);
}
fclose(f);
}
if (vendor[0] && device[0])
snprintf(buf, bufsz, "%s:%s", vendor, device);
}
/* Physical bus the device hangs off ("usb", "pci", "platform", "sdio", ...)
* from /sys/class/net/<iface>/device/subsystem symlink target. */
static void nm_get_bus(const char *iface, char *buf, size_t bufsz)
{
char path[256];
char link[256];
ssize_t n;
const char *slash;
buf[0] = '\0';
snprintf(path, sizeof(path), "/sys/class/net/%s/device/subsystem", iface);
n = readlink(path, link, sizeof(link) - 1);
if (n <= 0)
return;
link[n] = '\0';
slash = strrchr(link, '/');
strncpy(buf, slash ? slash + 1 : link, bufsz - 1);
buf[bufsz - 1] = '\0';
}
/* Lines carrying these keys change on every scan (byte counters, timestamp)
* and must not affect change detection, or every poll would look "changed". */
static int nm_line_is_volatile(const char *line, size_t len)
{
static const char *const keys[] = { "\"rx_bytes\"", "\"tx_bytes\"", "\"updated\"", "\"bitrate_bps\"" };
for (size_t k = 0; k < sizeof(keys) / sizeof(keys[0]); k++) {
size_t klen = strlen(keys[k]);
for (size_t i = 0; i + klen <= len; i++) {
if (memcmp(line + i, keys[k], klen) == 0)
return 1;
}
}
return 0;
}
/* djb2 hash over buf, skipping volatile lines, to detect real state changes
* across polls without being tripped up by ever-changing traffic counters. */
static unsigned long nm_content_hash(const char *s)
{
unsigned long hash = 5381;
const char *p = s;
while (*p) {
const char *nl = strchr(p, '\n');
size_t len = nl ? (size_t)(nl - p) : strlen(p);
if (!nm_line_is_volatile(p, len)) {
hash = hash * 33 + len;
for (size_t i = 0; i < len; i++)
hash = hash * 33 + (unsigned char)p[i];
}
if (!nl)
break;
p = nl + 1;
}
return hash;
}
/* Returns 1 if the gathered state differs from the previous scan (ignoring
* byte counters / timestamp), 0 otherwise. /var/run/netinfo is refreshed
* either way so counters stay current for anyone reading the file directly.
* Pass force=1 to always report "changed" (e.g. on client connect or a real
* netlink/uevent event), bypassing the hash comparison. */
static int nm_gather_and_write(int force)
{
static char buf[NETMON_BUF_SIZE];
static unsigned long lastHash;
static int haveHash;
int off = 0;
FILE *pf, *out;
int sock;
time_t t;
struct tm *tm_val;
char timebuf[32];
char ipbuf[INET_ADDRSTRLEN];
char macbuf[18];
char ssid[NM_IW_ESSID_MAX + 1];
char driverbuf[64];
char hwidbuf[32];
char busbuf[16];
struct ifreq ifr;
char line[256];
int first = 1;
time(&t);
tm_val = gmtime(&t);
if (tm_val)
strftime(timebuf, sizeof(timebuf), "%Y-%m-%dT%H:%M:%SZ", tm_val);
else
strncpy(timebuf, "1970-01-01T00:00:00Z", sizeof(timebuf) - 1);
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0) {
LOG("netmon: socket: %s\n", strerror(errno));
return 0;
}
pf = fopen("/proc/net/dev", "r");
if (!pf) {
LOG("netmon: cannot open /proc/net/dev: %s\n", strerror(errno));
close(sock);
return 0;
}
/* every interface's own default route (gw + metric) is reported below;
* the interface that owns the system's single active default gateway
* additionally gets "defgw": 1 (see nm_scan_default_routes()) */
struct nm_default_route defRoutes[NM_MAX_DEFAULT_ROUTES];
unsigned int defGwWinnerIfindex = 0;
int defRouteCount = nm_scan_default_routes(defRoutes, NM_MAX_DEFAULT_ROUTES, &defGwWinnerIfindex);
/* skip two header lines */
if (!fgets(line, sizeof(line), pf) || !fgets(line, sizeof(line), pf)) {
fclose(pf); close(sock); return 0;
}
off += snprintf(buf + off, sizeof(buf) - off,
"{\n \"updated\": \"%s\",\n \"interfaces\": {\n", timebuf);
while (fgets(line, sizeof(line), pf) && off < (int)sizeof(buf) - 300) {
char *colon = strchr(line, ':');
if (!colon) continue;
*colon = '\0';
char *iface = line;
while (*iface == ' ' || *iface == '\t') iface++;
if (strcmp(iface, "lo") == 0) continue;
/* /proc/net/dev counters: rx_bytes is field 1, tx_bytes is field 9 */
unsigned long long rxBytes = 0, txBytes = 0;
sscanf(colon + 1, "%llu %*u %*u %*u %*u %*u %*u %*u %llu", &rxBytes, &txBytes);
int wireless = nm_is_wireless(sock, iface);
/* interface flags */
memset(&ifr, 0, sizeof(ifr));
strncpy(ifr.ifr_name, iface, IFNAMSIZ - 1);
int if_up = 0, if_running = 0, if_flags = 0;
if (ioctl(sock, SIOCGIFFLAGS, &ifr) >= 0) {
if_flags = ifr.ifr_flags;
if_up = (ifr.ifr_flags & IFF_UP) != 0;
if_running = (ifr.ifr_flags & IFF_RUNNING) != 0;
}
int vpn = !wireless && nm_is_vpn((short)if_flags, iface);
/* MAC */
macbuf[0] = '\0';
memset(&ifr, 0, sizeof(ifr));
strncpy(ifr.ifr_name, iface, IFNAMSIZ - 1);
if (ioctl(sock, SIOCGIFHWADDR, &ifr) >= 0) {
unsigned char *m = (unsigned char *)ifr.ifr_hwaddr.sa_data;
snprintf(macbuf, sizeof(macbuf), "%02x:%02x:%02x:%02x:%02x:%02x",
m[0], m[1], m[2], m[3], m[4], m[5]);
}
/* MTU */
int mtu = -1;
memset(&ifr, 0, sizeof(ifr));
strncpy(ifr.ifr_name, iface, IFNAMSIZ - 1);
if (ioctl(sock, SIOCGIFMTU, &ifr) >= 0)
mtu = ifr.ifr_mtu;
/* IPv4 address + prefix + mask + broadcast + gateway */
ipbuf[0] = '\0';
char maskbuf[INET_ADDRSTRLEN] = {};
char brdbuf[INET_ADDRSTRLEN] = {};
char gwbuf[INET_ADDRSTRLEN] = {};
unsigned int gwMetric = 0;
int haveGwMetric = 0;
int isDefGw = 0;
int prefix = -1;
memset(&ifr, 0, sizeof(ifr));
strncpy(ifr.ifr_name, iface, IFNAMSIZ - 1);
if (ioctl(sock, SIOCGIFADDR, &ifr) >= 0) {
inet_ntop(AF_INET,
&((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr,
ipbuf, sizeof(ipbuf));
memset(&ifr, 0, sizeof(ifr));
strncpy(ifr.ifr_name, iface, IFNAMSIZ - 1);
if (ioctl(sock, SIOCGIFNETMASK, &ifr) >= 0) {
struct in_addr *nm_addr = &((struct sockaddr_in *)&ifr.ifr_netmask)->sin_addr;
inet_ntop(AF_INET, nm_addr, maskbuf, sizeof(maskbuf));
prefix = __builtin_popcount(ntohl(nm_addr->s_addr));
}
memset(&ifr, 0, sizeof(ifr));
strncpy(ifr.ifr_name, iface, IFNAMSIZ - 1);
if (ioctl(sock, SIOCGIFBRDADDR, &ifr) >= 0) {
inet_ntop(AF_INET,
&((struct sockaddr_in *)&ifr.ifr_broadaddr)->sin_addr,
brdbuf, sizeof(brdbuf));