/
collect-client.c
2461 lines (1915 loc) · 90.5 KB
/
collect-client.c
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
/*
collect-client - a client for ISPApp
Copyright 2022 Andrew Hodel
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
// required for basic wss support
#include <fcntl.h>
#include <pthread.h>
#include <signal.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "mbedtls/base64.h"
#include "mbedtls/certs.h"
#include "mbedtls/ctr_drbg.h"
#include "mbedtls/debug.h"
#include "mbedtls/entropy.h"
#include "mbedtls/error.h"
#include "mbedtls/net_sockets.h"
#include "mbedtls/sha1.h"
#include "mbedtls/ssl.h"
// required for collector data
#include <arpa/inet.h>
#include <errno.h>
#include <ifaddrs.h>
#include <json-c/json.h>
#include <limits.h>
#include <linux/if_link.h>
#include <linux/kernel.h>
#include <linux/reboot.h>
#include <linux/sysinfo.h>
#include <mntent.h>
#include <net/if.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/ip_icmp.h>
#include <sys/ioctl.h>
#include <sys/reboot.h>
#include <sys/socket.h>
#include <sys/statvfs.h>
#include <sys/types.h>
#include <sys/utsname.h>
#include <sys/wait.h>
#include <time.h>
#define _XOPEN_SOURCE 700
#include <linux/genetlink.h>
#include <linux/nl80211.h>
#include <netlink/cache.h>
#include <netlink/genl/ctrl.h> // genl_ctrl_resolve
#include <netlink/genl/family.h>
#include <netlink/genl/genl.h> // genl_connect, genlmsg_put
#include <netlink/netlink.h>
#include <netlink/route/link.h>
#if !defined(MBEDTLS_CONFIG_FILE)
#include "mbedtls/config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#define mbedtls_time time
#define mbedtls_time_t time_t
#define mbedtls_fprintf fprintf
#define mbedtls_printf printf
#define mbedtls_exit exit
#define MBEDTLS_EXIT_SUCCESS EXIT_SUCCESS
#define MBEDTLS_EXIT_FAILURE EXIT_FAILURE
#endif /* MBEDTLS_PLATFORM_C */
// the level of debug logs you require. Its values can be between 0 and 5, where 5 is the most logs
#define DEBUG_LEVEL 1
// setup the ssl object outside main so it can be accessed by threads
mbedtls_ssl_context ssl;
mbedtls_net_context server_fd;
mbedtls_entropy_context entropy;
mbedtls_ctr_drbg_context ctr_drbg;
mbedtls_ssl_config conf;
mbedtls_x509_crt cacert;
pthread_t thread_id = 0;
pthread_t ping_thread_id = 0;
char *ping_json_string;
int send_loop_errors = 0;
int force_reconnect_from_send_loop = 0;
int update_wait;
int collector_wait = 0;
int send_col_data = 1;
int listener_update_interval_seconds = 60;
int listener_outage_interval_seconds = 300;
time_t last_response;
char *root_address;
char *root_port;
char root_update_delay;
char *root_wlan_if;
char *root_collect_key;
char *root_client_info = "collect-client-3.06";
char *root_hardware_make;
char *root_hardware_model;
char *root_hardware_model_number;
char *root_hardware_cpu_info;
char *root_hardware_serial;
char *root_os_build_date;
char *root_fw;
char root_mac[18];
char *root_cert_path;
char *root_config_file;
int wss_recv = -1;
int send_config_request = 1;
int64_t last_config_change_ts_ms = -1;
uint64_t connection_failures = 0;
int timeout_cmd_detected = 1;
char **ping_addresses;
int num_ping_hosts = 0;
// each label of a domain (parts separated by .) can be 63 characters max, the whole domain can be 253 character long at maximum
// there are 4 double (64 bit) values and an integer plus the json object keys
// the range of the whole part of the number in IEEE 754 is (−9,007,199,254,740,992 to 9,007,199,254,740,992) 16 characters in a string
// if you only fill the fraction part of a double and leave the whole at zero, a double can have a very long string representation
// you can use scientific notation (counting the number of leading zeros) to make a short string representation
// 2 x 10^-1074 is 1074 digits
// you could make many leading zeros and a few significant digits in the fraction part
// the maximum value of the whole part must be allowed
// the decimal point must be allowed
// the understanding that the fraction part can have a large number of leading zeros and few significant digits is crucial in understanding
// that storing values as strings must support scientific notation
// with regards to precision, always include the number of leading or trailing zeros (per IBM)
// allowing consideration of only printing strings with a precision of 10
// 16 whole part digits, 1 decimal point, 10 fraction part digits
// total 27 characters
// if the measuring equipment was precise enough to maintain an accuracy that required 5000 leading zeros, you would expect a string length of that
// but considering that the string can send scientific notation, and that double IEEE 754 type data can use some of the whole part bits to represent a longer fraction part
// and that storing a very precise number that is less than 1 is important
//
// a string length of 500 is capable for each double
// 253 domain length
// 2000 (4) doubles
// 16 (1) uint64
// 20 json formatting
int ping_host_json_data_length = 253 + 2000 + 16 + 20;
char *escape_string_for_json(char *str) {
// allocate the length of str
char *nstr = calloc(strlen(str) + 1, sizeof(char));
// loop through each character
long unsigned int c = 0;
long unsigned int d = 0;
while (c < strlen(str)) {
// printf("character: %c\n", str[c]);
// json needs everything from '\x00' to '\x1f' escaped
if (str[c] == '"' || str[c] == '\\' || ('\x00' <= str[c] && str[c] <= '\x1f')) {
// printf("\tescaping %c\n", str[c]);
// add the escape character to nstr
nstr[d] = '\\';
// increment d to account for the extra space
d++;
// allocate that space in the nstr pointer
nstr = realloc(nstr, d);
// add the character
nstr[d] = str[c];
} else {
// add the character to nstr
nstr[d] = str[c];
}
c++;
d++;
}
// add the \0 at the end
nstr[d] = '\0';
return nstr;
}
static int get_mac(char *ifname, char *mac) {
// printf("getting mac for %s\n", ifname);
struct ifreq s;
int fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
strcpy(s.ifr_name, ifname);
if (0 == ioctl(fd, SIOCGIFHWADDR, &s)) {
sprintf(mac, "%02x:%02x:%02x:%02x:%02x:%02x", (unsigned char)s.ifr_addr.sa_data[0], (unsigned char)s.ifr_addr.sa_data[1], (unsigned char)s.ifr_addr.sa_data[2], (unsigned char)s.ifr_addr.sa_data[3], (unsigned char)s.ifr_addr.sa_data[4], (unsigned char)s.ifr_addr.sa_data[5]);
return 1;
}
return -1;
}
int l_strcpy(char *dest, char *src, int start, int end) {
// returns number of characters copied
int c = 0;
int d = 0;
while (c < strlen(src)) {
if (c > end && end > 0) {
break;
}
if (c > start) {
dest[d] = src[c];
d++;
}
c++;
}
dest[d] = '\0';
return d;
}
#define BYTE_TO_BINARY_PATTERN "%c%c%c%c%c%c%c%c"
#define BYTE_TO_BINARY(byte) (byte & 0x80 ? '1' : '0'), (byte & 0x40 ? '1' : '0'), (byte & 0x20 ? '1' : '0'), (byte & 0x10 ? '1' : '0'), (byte & 0x08 ? '1' : '0'), (byte & 0x04 ? '1' : '0'), (byte & 0x02 ? '1' : '0'), (byte & 0x01 ? '1' : '0')
int wss_frame_encode_message(char *output_buf, int type, char *buf) {
// returns the message length
if (sizeof(buf) > UINT64_MAX) {
// this message is too long to encode, this library does not currently support sending messages that require multiple frames
printf("message is too long to encode into a WebSocket frame.\n");
return -1;
}
// the first byte of the frame, bits 1-8
// bit 1 = FIN (1 indicates last message in a series)
// bit 2 = RSV1 (NA)
// bit 3 = RSV2 (NA)
// bit 4 = RSV3 (NA)
// bits 5-8 = opcode (0x0 continuation, 0x1 text, 0x2 binary)
// decimal 129 is FIN=1 OPCODE=0x1
output_buf[0] = 129;
// printf("bits in first byte: "BYTE_TO_BINARY_PATTERN"\n", BYTE_TO_BINARY((unsigned char) output_buf[0]));
// the second byte of the frame
// bit 1 = MASK (1 indicates message is XOR encoded, messages from the client must be masked)
// bit 2-8 = payload length (read bits 2-8 as an unsigned int up to 125, if == 126 read the next 16 bits as unsigned int, if == 127 read the next 64 bits as unsigned int)
// set bit 1 to 1 (that is also decimal 1)
output_buf[1] = 128; // or output_buf[1] |= (unsigned char) 1 << 7;
// the third and fourth byte of the frame if payload length <= UINT16_MAX
// payload length == 126, will set payload length
// read 16 bits (bytes 3, 4) as unsigned int
// the 3rd, 4th, 5th, 6th, 7th, 8th, 9th, 10th byte of the frame if payload length <= UINT64_MAX
// payload length == 127, will set payload length
// read 64 bits (bytes 3, 4, 5, 6, 7, 8, 9, 10) as unsigned int
// printf("encoding message with length: %llu\n", strlen(buf));
// the masking key starts at byte 2
// if the payload is <= UINT16_MAX then it starts at byte 4
// if the payload is <= UINT64_MAX then it starts at byte 10
unsigned int start_masking_key = 2;
// basically
// 125 = 01111101
// 126 = 01111110
// 127 = 01111111
// 128 = 10000000
if (strlen(buf) <= 125) {
// set bits 2-8 from byte 2 with the length
output_buf[1] = (unsigned char)strlen(buf);
} else if (strlen(buf) <= UINT16_MAX) {
// set payload len to 126, saying use 16 bits for the payload length
output_buf[1] = 126;
// set bytes 3-4 (2 bytes) as a UINT16 with the length
unsigned int l = (unsigned int)strlen(buf);
output_buf[2] = (char)((l >> 8) & 0xFF);
output_buf[3] = (char)((l & 0xFF));
start_masking_key = 4;
} else {
// set payload len to 127, saying use 64 bits for the payload length
output_buf[1] = 127;
// set bytes 3-10 (8 bytes) as a UINT64 with the length
unsigned long long int l = (unsigned long long int)strlen(buf);
output_buf[2] = (char)((l >> 56) & 0xFF);
output_buf[3] = (char)((l >> 48) & 0xFF);
output_buf[4] = (char)((l >> 40) & 0xFF);
output_buf[5] = (char)((l >> 32) & 0xFF);
output_buf[6] = (char)((l >> 24) & 0xFF);
output_buf[7] = (char)((l >> 16) & 0xFF);
output_buf[8] = (char)((l >> 8) & 0xFF);
output_buf[9] = (char)((l & 0xFF));
start_masking_key = 10;
}
// set the first bit to 1 again to enable MASK
output_buf[1] |= (unsigned char)1 << 7;
// printf("bits in 2nd byte: "BYTE_TO_BINARY_PATTERN"\n", BYTE_TO_BINARY((unsigned char) output_buf[1]));
// next 4 bytes starting with start_masking_key
// the masking key (if MASK == 1)
// var DECODED = "";
// for (var i = 0; i < ENCODED.length; i++) {
// DECODED[i] = ENCODED[i] ^ MASK[i % 4];
//}
// generate 4 random bytes
char *randomBytes = calloc(4, sizeof(char));
int rngfd = open("/dev/urandom", O_RDONLY);
if (rngfd < 0) {
// error opening /dev/urandom
printf("error opening /dev/urandom!\n");
free(randomBytes);
return -1;
} else {
ssize_t result = read(rngfd, randomBytes, 4);
if (result < 0) {
// error getting data from /dev/urandom
printf("error getting data from /dev/urandom.\n");
free(randomBytes);
close(rngfd);
return -1;
}
output_buf[start_masking_key] = randomBytes[0];
output_buf[start_masking_key + 1] = randomBytes[1];
output_buf[start_masking_key + 2] = randomBytes[2];
output_buf[start_masking_key + 3] = randomBytes[3];
}
// payload bytes
// the payload data encoded with the masking key
int c = 0;
// printf("string to send:\n");
while (c < strlen(buf)) {
output_buf[start_masking_key + 4 + c] = randomBytes[c % 4] ^ buf[c];
// printf("%c", buf[c], (unsigned char) buf[c]);
c++;
}
// printf("\n\n");
free(randomBytes);
close(rngfd);
return start_masking_key + 4 + c;
}
int get_wan(char *wan_ip) {
FILE *f;
char line[100], *p, *c;
f = fopen("/proc/net/route", "r");
while (fgets(line, 100, f)) {
p = strtok(line, "\t");
c = strtok(NULL, "\t");
if (p != NULL && c != NULL) {
if (strcmp(c, "00000000") == 0) {
// printf("Default interface is : %s \n", p);
break;
}
}
}
fclose(f);
// which family do we require , AF_INET or AF_INET6
int fm = AF_INET;
struct ifaddrs *ifaddr, *ifa;
int family, s;
char host[NI_MAXHOST];
if (getifaddrs(&ifaddr) == -1) {
perror("getifaddrs");
return -1;
}
for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
if (ifa->ifa_addr == NULL) {
continue;
}
family = ifa->ifa_addr->sa_family;
if (strcmp(ifa->ifa_name, p) == 0) {
if (family == fm) {
s = getnameinfo(ifa->ifa_addr, (family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6), host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
if (s != 0) {
printf("getnameinfo() failed: %s\n", gai_strerror(s));
return -1;
}
// printf("address: %s", host);
strcpy(wan_ip, host);
}
// printf("\n");
}
}
freeifaddrs(ifaddr);
return 0;
}
char *dns_lookup(char *addr_host, struct sockaddr_in *addr_con) {
// printf("\nResolving DNS..\n");
char *ip = (char *)malloc(NI_MAXHOST * sizeof(char));
struct hostent *host_entity;
if ((host_entity = gethostbyname(addr_host)) == NULL) {
// No ip found for hostname
free(ip);
return NULL;
}
// filling up address structure
strcpy(ip, inet_ntoa(*(struct in_addr *)host_entity->h_addr));
(*addr_con).sin_family = host_entity->h_addrtype;
(*addr_con).sin_port = htons(0);
(*addr_con).sin_addr.s_addr = *(long *)host_entity->h_addr;
// printf("dns result for %s: %s\n", addr_host, host_entity->h_addr);
// printf("%s resolved address: %s\n", addr_host, ip);
return ip;
}
unsigned short ping_checksum(void *b, int len) {
unsigned short *buf = b;
unsigned int sum = 0;
unsigned short result;
for (sum = 0; len > 1; len -= 2) sum += *buf++;
if (len == 1) sum += *(unsigned char *)buf;
sum = (sum >> 16) + (sum & 0xFFFF);
sum += (sum >> 16);
result = ~sum;
return result;
}
// ping packet size
#define PING_PKT_S 64
// ping packet structure
struct ping_pkt {
struct icmphdr hdr;
char msg[PING_PKT_S - sizeof(struct icmphdr)];
};
struct ping_response {
char host[255];
double avgRtt;
double minRtt;
double maxRtt;
int loss;
};
void send_ping(struct sockaddr_in *ping_addr, char *ping_dom, char *ping_ip, char *hostname_str, struct ping_response *pr) {
// ttl_val is the max number of hops
int ttl_val = 64;
int msg_count = 0;
int i;
int addr_len;
int flag = 1;
int msg_received_count = 0;
struct ping_pkt pckt;
struct sockaddr_in r_addr;
struct timespec time_start, time_end;
double rtt_msec = 0;
struct timeval tv_out;
tv_out.tv_sec = 2;
tv_out.tv_usec = 0;
pr->avgRtt = -1;
pr->minRtt = 0.0;
pr->maxRtt = 0.0;
pr->loss = 0;
// send icmp packets
int sent = 0;
while (sent < 5) {
//printf("ping opening socket to '%s' IP: %s\n", pr->host, ping_ip);
int sockfd;
// root access required to do this
sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
if (sockfd < 0) {
printf("ping socket file descriptor not received!! Got %i\n", sockfd);
return;
} else {
//printf("ping socket file descriptor %d received\n", sockfd);
}
// set the socket options
if (setsockopt(sockfd, SOL_IP, IP_TTL, &ttl_val, sizeof(ttl_val)) != 0) {
printf("ping, setting socket options to TTL failed!\n");
close(sockfd);
return;
} else {
//printf("ping socket set to TTL..\n");
}
// setting timeout of recv setting
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char *)&tv_out, sizeof tv_out);
// flag is whether packet was sent or not
flag = 1;
// filling packet
bzero(&pckt, sizeof(pckt));
pckt.hdr.type = ICMP_ECHO;
pckt.hdr.un.echo.id = getpid();
for (i = 0; i < sizeof(pckt.msg) - 1; i++) {
pckt.msg[i] = i + '0';
}
pckt.msg[i] = 0;
pckt.hdr.un.echo.sequence = msg_count++;
pckt.hdr.checksum = ping_checksum(&pckt, sizeof(pckt));
// send packet
clock_gettime(CLOCK_MONOTONIC, &time_start);
if (sendto(sockfd, &pckt, sizeof(pckt), 0, (struct sockaddr *)ping_addr, sizeof(*ping_addr)) <= 0) {
printf("ping, packet send failure.\n");
flag = 0;
}
// receive packet
addr_len = sizeof(r_addr);
if (recvfrom(sockfd, &pckt, sizeof(pckt), 0, (struct sockaddr *)&r_addr, (socklen_t *)&addr_len) <= 0 && msg_count > 1) {
//printf("ping packet receive failed.\n");
} else {
clock_gettime(CLOCK_MONOTONIC, &time_end);
double timeElapsed = ((double)(time_end.tv_nsec - time_start.tv_nsec)) / 1000000.0;
rtt_msec = (double)(time_end.tv_sec - time_start.tv_sec) * 1000.0 + timeElapsed;
// if packet was not sent, don't receive
if (flag) {
if (pckt.hdr.type == 69) {
//printf("ping: %d bytes from %s (h: %s) (%s) msg_seq=%d ttl=%d rtt = %lf ms\n", PING_PKT_S, ping_dom, hostname_str, ping_ip, msg_count, ttl_val, rtt_msec);
// if there was a successful response, set avgRtt to 0 so the average can be calculated correctly
if (pr->avgRtt == -1) {
pr->avgRtt = 0;
}
// calculate the ping results
pr->avgRtt += rtt_msec;
//printf("avgRtt=%lf\n", pr->avgRtt);
if (pr->minRtt == 0.0 || pr->minRtt > rtt_msec) {
pr->minRtt = rtt_msec;
}
if (pr->maxRtt == 0.0 || pr->maxRtt < rtt_msec) {
pr->maxRtt = rtt_msec;
}
msg_received_count++;
}
else
{
//printf("ping error. Packet received with invalid ICMP type %d code %d\n", pckt.hdr.type, pckt.hdr.code);
}
}
}
sent++;
close(sockfd);
}
// loss is an integer between 0 and 100 that represents percentage
pr->loss = 100 - ((msg_received_count / sent) * 100);
if (msg_received_count > 0) {
// calculate the average from all the ping responses
pr->avgRtt = pr->avgRtt / msg_received_count;
}
//printf("ping avgRtt: %lf, msg_received_count: %i, sent: %i\n", pr->avgRtt, msg_received_count, sent);
}
typedef struct {
int id;
struct nl_sock *socket;
struct nl_cb *cb1, *cb2;
int result1, result2;
} Netlink;
json_object *wap_json;
// surely one device doesn't have more than 100 interfaces, haha
unsigned long wifi_index_count = 0;
unsigned long all_wifi_indexes[100];
static struct nla_policy stats_policy[NL80211_STA_INFO_MAX + 1] = {
[NL80211_STA_INFO_INACTIVE_TIME] = {.type = NLA_U32}, [NL80211_STA_INFO_RX_BYTES] = {.type = NLA_U32}, [NL80211_STA_INFO_TX_BYTES] = {.type = NLA_U32}, [NL80211_STA_INFO_RX_PACKETS] = {.type = NLA_U32}, [NL80211_STA_INFO_TX_PACKETS] = {.type = NLA_U32}, [NL80211_STA_INFO_SIGNAL] = {.type = NLA_U8}, [NL80211_STA_INFO_TX_BITRATE] = {.type = NLA_NESTED}, [NL80211_STA_INFO_LLID] = {.type = NLA_U16}, [NL80211_STA_INFO_PLID] = {.type = NLA_U16}, [NL80211_STA_INFO_PLINK_STATE] = {.type = NLA_U8},
};
static struct nla_policy rate_policy[NL80211_RATE_INFO_MAX + 1] = {
[NL80211_RATE_INFO_BITRATE] = {.type = NLA_U16},
[NL80211_RATE_INFO_MCS] = {.type = NLA_U8},
[NL80211_RATE_INFO_40_MHZ_WIDTH] = {.type = NLA_FLAG},
[NL80211_RATE_INFO_SHORT_GI] = {.type = NLA_FLAG},
};
static int initNl80211(Netlink *nl);
static int finish_handler(struct nl_msg *msg, void *arg);
static int getWifiName_callback(struct nl_msg *msg, void *arg);
static int getWifiInfo_callback(struct nl_msg *msg, void *arg);
static int getWifiStatus(Netlink *nl);
static int initNl80211(Netlink *nl) {
nl->socket = nl_socket_alloc();
if (!nl->socket) {
fprintf(stderr, "Failed to allocate netlink socket.\n");
return -ENOMEM;
}
nl_socket_set_buffer_size(nl->socket, 8192, 8192);
if (genl_connect(nl->socket)) {
fprintf(stderr, "Failed to connect to netlink socket.\n");
nl_close(nl->socket);
nl_socket_free(nl->socket);
return -ENOLINK;
}
nl->id = genl_ctrl_resolve(nl->socket, "nl80211");
if (nl->id < 0) {
//fprintf(stderr, "Nl80211 interface not found.\n");
nl_close(nl->socket);
nl_socket_free(nl->socket);
return -ENOENT;
}
nl->cb1 = nl_cb_alloc(NL_CB_DEFAULT);
nl->cb2 = nl_cb_alloc(NL_CB_DEFAULT);
if ((!nl->cb1) || (!nl->cb2)) {
fprintf(stderr, "Failed to allocate netlink callback.\n");
nl_close(nl->socket);
nl_socket_free(nl->socket);
return ENOMEM;
}
// the last argument was a Wifi struct, it just passes that to the
// callback so it's not needed
nl_cb_set(nl->cb1, NL_CB_VALID, NL_CB_CUSTOM, getWifiName_callback, 0);
nl_cb_set(nl->cb1, NL_CB_FINISH, NL_CB_CUSTOM, finish_handler, &(nl->result1));
nl_cb_set(nl->cb2, NL_CB_VALID, NL_CB_CUSTOM, getWifiInfo_callback, 0);
nl_cb_set(nl->cb2, NL_CB_FINISH, NL_CB_CUSTOM, finish_handler, &(nl->result2));
return nl->id;
}
static int finish_handler(struct nl_msg *msg, void *arg) {
int *ret = arg;
*ret = 0;
return NL_SKIP;
}
void mac_addr_n2a(char *mac_addr, unsigned char *arg) {
int i, l;
l = 0;
for (i = 0; i < 6; i++) {
if (i == 0) {
sprintf(mac_addr + l, "%02x", arg[i]);
l += 2;
} else {
sprintf(mac_addr + l, ":%02x", arg[i]);
l += 3;
}
}
}
static int getWifiName_callback(struct nl_msg *msg, void *arg) {
// all the data arrives in msg
struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
struct nlattr *tb_msg[NL80211_ATTR_MAX + 1];
// printf("getWifiName_callback()\n");
// it can be dumped to the screen with nl_msg_dump
// nl_msg_dump(msg, stdout);
// parse the data into tb_msg: a struct nlattr
nla_parse(tb_msg, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0), genlmsg_attrlen(gnlh, 0), NULL);
if (tb_msg[NL80211_ATTR_IFNAME]) {
// nla_get_string(tb_msg[NL80211_ATTR_IFNAME]));
}
if (tb_msg[NL80211_ATTR_IFINDEX]) {
// nla_get_u32(tb_msg[NL80211_ATTR_IFINDEX]);
}
// this happens for each local (to the device) interface
char dev[20];
if_indextoname(nla_get_u32(tb_msg[NL80211_ATTR_IFINDEX]), dev);
// printf("interface %s with index: %lu\n", dev, (unsigned long) nla_get_u32(tb_msg[NL80211_ATTR_IFINDEX]));
// add interface to wap_json
json_object *iface = json_object_new_object();
json_object_object_add(iface, "interface", json_object_new_string(dev));
json_object *stations = json_object_new_array();
json_object_object_add(iface, "stations", stations);
json_object_array_add(wap_json, iface);
all_wifi_indexes[wifi_index_count] = nla_get_u32(tb_msg[NL80211_ATTR_IFINDEX]);
wifi_index_count++;
// this means this msg is done
return NL_SKIP;
}
static int getWifiInfo_callback(struct nl_msg *msg, void *arg) {
struct nlattr *tb[NL80211_ATTR_MAX + 1];
struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
struct nlattr *sinfo[NL80211_STA_INFO_MAX + 1];
struct nlattr *rinfo[NL80211_RATE_INFO_MAX + 1];
// printf("getWifiInfo_callback()\n");
// nl_msg_dump(msg, stdout);
// parse the msg to tb
nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0), genlmsg_attrlen(gnlh, 0), NULL);
if (!tb[NL80211_ATTR_STA_INFO]) {
fprintf(stderr, "sta stats missing!\n");
return NL_SKIP;
}
// this
if (nla_parse_nested(sinfo, NL80211_STA_INFO_MAX, tb[NL80211_ATTR_STA_INFO], stats_policy)) {
fprintf(stderr, "failed to parse nested attributes!\n");
return NL_SKIP;
}
if (sinfo[NL80211_STA_INFO_SIGNAL]) {
// (int8_t) nla_get_u8(sinfo[NL80211_STA_INFO_SIGNAL]);
}
if (sinfo[NL80211_STA_INFO_TX_BITRATE]) {
if (nla_parse_nested(rinfo, NL80211_RATE_INFO_MAX, sinfo[NL80211_STA_INFO_TX_BITRATE], rate_policy)) {
fprintf(stderr, "failed to parse nested rate attributes!\n");
} else {
if (rinfo[NL80211_RATE_INFO_BITRATE]) {
// nla_get_u16(rinfo[NL80211_RATE_INFO_BITRATE]);
}
}
}
// this happens for each connected station on this interface
// and this callback function is called synchronously for each
// interface
char mac_addr[20], dev[20];
mac_addr_n2a(mac_addr, nla_data(tb[NL80211_ATTR_MAC]));
if_indextoname(nla_get_u32(tb[NL80211_ATTR_IFINDEX]), dev);
// cast this as int8_t to get normal dBm values
int8_t wlsignal = (int8_t)nla_get_u8(sinfo[NL80211_STA_INFO_SIGNAL_AVG]);
// printf("Station %s (on %s): %u\n", mac_addr, dev, wlsignal);
// add station to wap_json
// first loop through wap_json and find the object that has interface set to dev
int arraylen = json_object_array_length(wap_json);
// printf("wap array length: %i\n", arraylen);
int c = 0;
while (c < arraylen) {
json_object *ele = json_object_array_get_idx(wap_json, c);
json_object *interface;
json_object_object_get_ex(ele, "interface", &interface);
if (strcmp(json_object_get_string(interface), dev) == 0) {
// this ele object will contain all the stations for dev
// get the current array of stations from ele
json_object *stations;
json_object_object_get_ex(ele, "stations", &stations);
// create a new station object
json_object *station = json_object_new_object();
// add the mac address
json_object_object_add(station, "mac", json_object_new_string(mac_addr));
// add the rssi
json_object_object_add(station, "rssi", json_object_new_int(wlsignal));
// add the tx and rx bytes
json_object_object_add(station, "sentBytes", json_object_new_int64(nla_get_u64(sinfo[NL80211_STA_INFO_TX_BYTES64])));
json_object_object_add(station, "recBytes", json_object_new_int64(nla_get_u64(sinfo[NL80211_STA_INFO_RX_BYTES64])));
// append this station to the existing stations
json_object_array_add(stations, station);
// printf("adding station: %s\n\t\t RSSI: %d\n", json_object_to_json_string(station), wlsignal);
}
c++;
}
// printf("wap_json after adding station: %s\n", json_object_to_json_string(wap_json));
return NL_SKIP;
}
static int getWifiStatus(Netlink *nl) {
nl->result1 = 1;
struct nl_msg *msg1 = nlmsg_alloc();
if (!msg1) {
fprintf(stderr, "Failed to allocate netlink message.\n");
return -2;
}
// this gets all interfaces
genlmsg_put(msg1, NL_AUTO_PORT, NL_AUTO_SEQ, nl->id, 0, NLM_F_DUMP, NL80211_CMD_GET_INTERFACE, 0);
nl_send_auto(nl->socket, msg1);
while (nl->result1 > 0) {
nl_recvmsgs(nl->socket, nl->cb1);
}
nlmsg_free(msg1);
// get the interface index of each wifi interface
unsigned long c = 0;
while (c < wifi_index_count) {
nl->result2 = 1;
// printf("running GET_STATION for interface with index: %lu\n", all_wifi_indexes[c]);
struct nl_msg *msg2 = nlmsg_alloc();
if (!msg2) {
fprintf(stderr, "Failed to allocate netlink message.\n");
return -2;
}
// this should be run for each interface
genlmsg_put(msg2, NL_AUTO_PORT, NL_AUTO_SEQ, nl->id, 0, NLM_F_DUMP, NL80211_CMD_GET_STATION, 0);
// here set the index for each interface and the stations will be
// returned in the second callback
// all these callbacks are blocking and sequential of course, what
// a joy to know javascript as well
nla_put_u32(msg2, NL80211_ATTR_IFINDEX, all_wifi_indexes[c]);
nl_send_auto(nl->socket, msg2);
while (nl->result2 > 0) {
nl_recvmsgs(nl->socket, nl->cb2);
}
nlmsg_free(msg2);
c++;
}
return 0;
}
void wsocket_kill() {
// notify the peer that the connection is being closed
printf("mbedtls_()\n");
mbedtls_ssl_close_notify(&ssl);
printf("wsocket_kill() finished\n");
}
void *pingLoop() {
sprintf(ping_json_string, "%s", "[]");
while (1) {
// ping hosts
//printf("PING LOOP\n");
// stores the json string of the ping collector
char *temp_string = calloc(ping_host_json_data_length * num_ping_hosts, sizeof(char));
sprintf(temp_string, "%s", "[");
int c = 0;
int valid_response_count = 0;
//printf("number of ping hosts: %d\n", num_ping_hosts);
while (c < num_ping_hosts + 1) {
char *ip_addr;
struct sockaddr_in addr_con;
struct ping_response pr;
if (c == num_ping_hosts) {
// last iteration, ping the instance
sprintf(pr.host, "%s", root_address);
} else {
// ping host in ping_addresses
sprintf(pr.host, "%s", ping_addresses[c]);
}
//printf("pinging %s 5 times.\n", pr.host);
ip_addr = dns_lookup(pr.host, &addr_con);
if (ip_addr == NULL) {
printf("ping collector, DNS lookup failed with: %s\n", pr.host);
} else {
//printf("\nopening socket to '%s' IP: %s\n", pr.host, ip_addr);
// send pings
send_ping(&addr_con, pr.host, ip_addr, pr.host, &pr);
//printf("ping result for host: %s, avgRtt: %lf\n", pr.host, pr.avgRtt);
char *temp_ping_host_string = calloc(ping_host_json_data_length, sizeof(char));
sprintf(temp_ping_host_string, "{\"host\": \"%s\", \"avgRtt\": %lf, \"minRtt\": %lf, \"maxRtt\": %lf, \"loss\": %d}", pr.host, pr.avgRtt, pr.minRtt, pr.maxRtt, pr.loss);
if (valid_response_count == 0) {
// add without ", " at the start
} else {
strcat(temp_string, ", ");
}
strcat(temp_string, temp_ping_host_string);
free(temp_ping_host_string);
free(ip_addr);
valid_response_count = 1;
}
c++;
}
// copy temp_string to ping_json_string
strcat(temp_string, "]");
memcpy(ping_json_string, temp_string, ping_host_json_data_length * num_ping_hosts);
free(temp_string);
// pingLoop() sleep
while (1) {
if (collector_wait == 0) {