-
Notifications
You must be signed in to change notification settings - Fork 12
/
client.c
3152 lines (2610 loc) · 78.7 KB
/
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
/*
* Copyright (C) 2010 Miroslav Lichvar <[email protected]>
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#define _GNU_SOURCE
/* avoid redirection in glibc headers */
#define adjtimex adjtimex_off
#include <sys/timex.h>
#undef adjtimex
#define fopen fopen_off
#include <stdio.h>
#undef fopen
#include <sys/utsname.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/timerfd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sysmacros.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <time.h>
#include <dlfcn.h>
#include <fcntl.h>
#include <sys/un.h>
#include <unistd.h>
#include <assert.h>
#include <stddef.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <netdb.h>
#include <pwd.h>
#include <stdarg.h>
#include <signal.h>
#include <ifaddrs.h>
#include <linux/types.h>
#include <linux/ethtool.h>
#include <linux/limits.h>
#include <linux/pps.h>
#include <linux/rtc.h>
#include <linux/sockios.h>
#ifdef SO_TIMESTAMPING
#include <linux/ptp_clock.h>
#include <linux/net_tstamp.h>
#endif
#include "protocol.h"
#include "client_fuzz.c"
/* first node in first subnet is 192.168.123.1 */
#define BASE_ADDR 0xc0a87b00
#define NETMASK 0xffffff00
#define NODE_ADDR(subnet, node) (BASE_ADDR + 0x100 * (subnet) + (node) + 1)
#define BROADCAST_ADDR(subnet) (NODE_ADDR(subnet, 0) | 0xff)
#define NODE_FROM_ADDR(addr) (((addr) & ~NETMASK) - 1)
#define SUBNET_FROM_ADDR(addr) ((((addr) & NETMASK) - BASE_ADDR) / 0x100)
#define PTP_PRIMARY_MCAST_ADDR 0xe0000181 /* 224.0.1.129 */
#define PTP_PDELAY_MCAST_ADDR 0xe000006b /* 224.0.0.107 */
#define REFCLK_FD 1000
#define REFCLK_ID ((clockid_t)(((unsigned int)~REFCLK_FD << 3) | 3))
#define REFCLK_PHC_INDEX 0
#define SYSCLK_FD 1001
#define SYSCLK_CLOCKID ((clockid_t)(((unsigned int)~SYSCLK_FD << 3) | 3))
#define SYSCLK_PHC_INDEX 1
#define PPS_FD 1002
#define RTC_FD 1003
#define URANDOM_FD 1010
#define MAX_SOCKETS 20
#define BASE_SOCKET_FD 100
#define BASE_SOCKET_DEFAULT_PORT 60000
#define MAX_TIMERS 80
#define BASE_TIMER_ID 0xC1230123
#define BASE_TIMER_FD 200
#define URANDOM_FILE (void *)0xD1230123
#if !defined(__GLIBC_PREREQ) || __GLIBC_PREREQ(2, 33)
#define HAVE_STAT
#endif
static FILE *(*_fopen)(const char *path, const char *mode);
static FILE *(*_fdopen)(int fd, const char *mode);
static size_t (*_fread)(void *ptr, size_t size, size_t nmemb, FILE *stream);
static int (*_fileno)(FILE *stream);
static int (*_fclose)(FILE *fp);
static int (*_fcntl)(int fd, int cmd, ...);
#ifdef HAVE_STAT
static int (*_fstat)(int fd, struct stat *statbuf);
static int (*_stat)(const char *pathname, struct stat *statbuf);
#else
static int (*_fxstat)(int ver, int fd, struct stat *statbuf);
static int (*_xstat)(int ver, const char *pathname, struct stat *statbuf);
#endif
static char *(*_realpath)(const char *path, char *resolved_path);
static int (*_open)(const char *pathname, int flags, ...);
static ssize_t (*_read)(int fd, void *buf, size_t count);
static int (*_close)(int fd);
static int (*_socket)(int domain, int type, int protocol);
static int (*_connect)(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
static ssize_t (*_recvmsg)(int sockfd, struct msghdr *msg, int flags);
static ssize_t (*_send)(int sockfd, const void *buf, size_t len, int flags);
static int (*_usleep)(useconds_t usec);
static void (*_srandom)(unsigned int seed);
static int (*_shmget)(key_t key, size_t size, int shmflg);
static void *(*_shmat)(int shmid, const void *shmaddr, int shmflg);
static unsigned int node;
static int initializing = 0;
static int initialized_symbols = 0;
static int initialized = 0;
static int clknetsim_fd;
static int precision_hack = 1;
static unsigned int random_seed = 0;
static int recv_multiply = 1;
static int timestamping = 1;
static double phc_delay = 0.0;
static double phc_jitter = 0.0;
static double phc_jitter_asym = 0.0;
static int phc_jitter_off = 0;
static int phc_jitter_on = 1;
static int phc_swap = 0;
/* Ethernet speed in Mb/s */
static int link_speed = 100000;
static double rtc_offset = 0.0;
static int rtc_timerfd = 0;
enum {
IFACE_UNIX,
IFACE_LO,
IFACE_ALL,
IFACE_ETH0,
};
struct message {
char data[MAX_PACKET_SIZE];
unsigned int len;
unsigned int subnet;
unsigned int to_from;
unsigned int port;
};
struct socket {
int used;
int domain;
int type;
int port;
int iface;
int remote_node;
int remote_port;
int listening;
int connected;
int broadcast;
int pkt_info;
int time_stamping;
struct message last_ts_msg;
struct message buffer;
};
static struct socket sockets[MAX_SOCKETS];
static int subnets;
static int unix_subnet = -1;
static double real_time = 0.0;
static double monotonic_time = 0.0;
static double network_time = 0.0;
static double freq_error = 0.0;
static int local_time_valid = 0;
static time_t system_time_offset = 1262304000; /* 2010-01-01 0:00 UTC */
#define TIMER_TYPE_SIGNAL 1
#define TIMER_TYPE_FD 2
struct timer {
int used;
int armed;
int type;
int fd_flags;
uint64_t expired;
clockid_t clock_id;
double timeout;
double interval;
};
static struct timer timers[MAX_TIMERS];
static timer_t itimer_real_id;
#define SHM_KEY 0x4e545030
#define SHM_REFCLOCKS 4
static struct shmTime {
int mode;
int count;
time_t clockTimeStampSec;
int clockTimeStampUSec;
time_t receiveTimeStampSec;
int receiveTimeStampUSec;
int leap;
int precision;
int nsamples;
int valid;
int clockTimeStampNSec;
int receiveTimeStampNSec;
int dummy[8];
} shm_time[SHM_REFCLOCKS];
static int shm_refclocks = 0;
static double shm_refclock_time = 0.0;
static struct Reply_getrefoffsets refclock_offsets;
static int refclock_offsets_used = 0;
static int pps_fds = 0;
static FILE *pcap = NULL;
static void write_pcap_header(void);
static void make_request(int request_id, const void *request_data, int reqlen, void *reply, int replylen);
static void init_symbols(void) {
if (initialized_symbols)
return;
_fopen = (FILE *(*)(const char *path, const char *mode))dlsym(RTLD_NEXT, "fopen");
_fdopen = (FILE *(*)(int fd, const char *mode))dlsym(RTLD_NEXT, "fdopen");
_fread = (size_t (*)(void *ptr, size_t size, size_t nmemb, FILE *stream))dlsym(RTLD_NEXT, "fread");
_fileno = (int (*)(FILE *stream))dlsym(RTLD_NEXT, "fileno");
_fclose = (int (*)(FILE *fp))dlsym(RTLD_NEXT, "fclose");
_fcntl = (int (*)(int fd, int cmd, ...))dlsym(RTLD_NEXT, "fcntl");
#ifdef HAVE_STAT
#if defined(__USE_TIME_BITS64) && __USE_TIME_BITS64 && __TIMESIZE == 32
_fstat = (int (*)(int fd, struct stat *statbuf))dlsym(RTLD_NEXT, "__fstat64_time64");
_stat = (int (*)(const char *pathname, struct stat *statbuf))dlsym(RTLD_NEXT, "__stat64_time64");
#else
_fstat = (int (*)(int fd, struct stat *statbuf))dlsym(RTLD_NEXT, "fstat");
_stat = (int (*)(const char *pathname, struct stat *statbuf))dlsym(RTLD_NEXT, "stat");
#endif
#else
_fxstat = (int (*)(int ver, int fd, struct stat *statbuf))dlsym(RTLD_NEXT, "__fxstat");
_xstat = (int (*)(int ver, const char *pathname, struct stat *statbuf))dlsym(RTLD_NEXT, "__xstat");
#endif
_realpath = (char *(*)(const char *path, char *resolved_path))dlsym(RTLD_NEXT, "realpath");
_open = (int (*)(const char *pathname, int flags, ...))dlsym(RTLD_NEXT, "open");
_read = (ssize_t (*)(int fd, void *buf, size_t count))dlsym(RTLD_NEXT, "read");
_close = (int (*)(int fd))dlsym(RTLD_NEXT, "close");
_socket = (int (*)(int domain, int type, int protocol))dlsym(RTLD_NEXT, "socket");
_connect = (int (*)(int sockfd, const struct sockaddr *addr, socklen_t addrlen))dlsym(RTLD_NEXT, "connect");
_recvmsg = (ssize_t (*)(int sockfd, struct msghdr *msg, int flags))dlsym(RTLD_NEXT, "recvmsg");
_send = (ssize_t (*)(int sockfd, const void *buf, size_t len, int flags))dlsym(RTLD_NEXT, "send");
_usleep = (int (*)(useconds_t usec))dlsym(RTLD_NEXT, "usleep");
_srandom = (void (*)(unsigned int seed))dlsym(RTLD_NEXT, "srandom");
_shmget = (int (*)(key_t key, size_t size, int shmflg))dlsym(RTLD_NEXT, "shmget");
_shmat = (void *(*)(int shmid, const void *shmaddr, int shmflg))dlsym(RTLD_NEXT, "shmat");
initialized_symbols = 1;
}
__attribute__((constructor))
static void init(void) {
unsigned int connect_retries = 100; /* 10 seconds */
struct sockaddr_un s = {AF_UNIX, "clknetsim.sock"};
struct Request_register req;
struct Reply_register rep;
const char *env;
char command[64];
FILE *f;
if (initializing || initialized)
return;
initializing = 1;
init_symbols();
env = getenv("CLKNETSIM_START_DATE");
if (env)
system_time_offset = atoll(env);
env = getenv("CLKNETSIM_RANDOM_SEED");
if (env)
random_seed = atoi(env);
env = getenv("CLKNETSIM_RECV_MULTIPLY");
if (env)
recv_multiply = atoi(env);
env = getenv("CLKNETSIM_TIMESTAMPING");
if (env)
timestamping = atoi(env);
env = getenv("CLKNETSIM_LINK_SPEED");
if (env)
link_speed = atoi(env);
env = getenv("CLKNETSIM_PHC_DELAY");
if (env)
phc_delay = atof(env);
env = getenv("CLKNETSIM_PHC_JITTER");
if (env)
phc_jitter = atof(env);
env = getenv("CLKNETSIM_PHC_JITTER_ASYM");
if (env)
phc_jitter_asym = atof(env);
env = getenv("CLKNETSIM_PHC_JITTER_OFF");
if (env)
phc_jitter_off = atoi(env);
env = getenv("CLKNETSIM_PHC_JITTER_ON");
if (env)
phc_jitter_on = atoi(env);
env = getenv("CLKNETSIM_PHC_SWAP");
if (env)
phc_swap = atoi(env);
env = getenv("CLKNETSIM_RTC_OFFSET");
if (env)
rtc_offset = atof(env);
f = _fopen("/proc/self/comm", "r");
if (f) {
command[0] = '\0';
if (!fgets(command, sizeof (command), f))
;
fclose(f);
if (strncmp(command, "valgrind", 8) == 0 ||
strncmp(command, "strace", 6) == 0) {
/* don't connect to the server */
initialized = 1;
return;
}
}
env = getenv("CLKNETSIM_PCAP_DUMP");
if (env) {
pcap = _fopen(env, "w");
write_pcap_header();
}
if (fuzz_init()) {
node = 0;
subnets = 2;
unix_subnet = 1;
initialized = 1;
return;
}
env = getenv("CLKNETSIM_NODE");
if (!env) {
fprintf(stderr, "clknetsim: CLKNETSIM_NODE variable not set.\n");
exit(1);
}
node = atoi(env) - 1;
env = getenv("CLKNETSIM_UNIX_SUBNET");
if (env)
unix_subnet = atoi(env) - 1;
env = getenv("CLKNETSIM_SOCKET");
if (env)
snprintf(s.sun_path, sizeof (s.sun_path), "%s", env);
env = getenv("CLKNETSIM_CONNECT_TIMEOUT");
if (env)
connect_retries = 10 * atoi(env);
clknetsim_fd = _socket(AF_UNIX, SOCK_SEQPACKET, 0);
assert(clknetsim_fd >= 0);
while (_connect(clknetsim_fd, (struct sockaddr *)&s, sizeof (s)) < 0) {
if (!--connect_retries) {
fprintf(stderr, "clknetsim: could not connect to server.\n");
exit(1);
}
_usleep(100000);
}
/* this requires the node variable to be already set */
srandom(0);
initializing = 0;
initialized = 1;
req.node = node;
make_request(REQ_REGISTER, &req, sizeof (req), &rep, sizeof (rep));
subnets = rep.subnets;
}
__attribute__((destructor))
static void fini(void) {
if (initialized)
make_request(REQ_DEREGISTER, NULL, 0, NULL, 0);
if (pcap)
fclose(pcap);
}
static void make_request(int request_id, const void *request_data, int reqlen, void *reply, int replylen) {
struct Request_packet request;
int sent, received = 0;
init();
if (fuzz_mode) {
fuzz_process_request(request_id, request_data, reply, replylen);
return;
}
request.header.request = request_id;
request.header._pad = 0;
assert(offsetof(struct Request_packet, data) + reqlen <= sizeof (request));
if (request_data)
memcpy(&request.data, request_data, reqlen);
reqlen += offsetof(struct Request_packet, data);
if ((sent = _send(clknetsim_fd, &request, reqlen, 0)) <= 0 ||
(reply && (received = recv(clknetsim_fd, reply, replylen, 0)) <= 0)) {
fprintf(stderr, "clknetsim: server connection closed.\n");
initialized = 0;
exit(1);
}
assert(sent == reqlen);
if (!reply)
return;
/* check reply length */
switch (request_id) {
case REQ_RECV:
/* reply with variable length */
assert(received >= offsetof(struct Reply_recv, data));
assert(offsetof(struct Reply_recv, data) +
((struct Reply_recv *)reply)->len <= received);
break;
case REQ_GETREFOFFSETS:
/* reply with variable length */
assert(received >= offsetof(struct Reply_getrefoffsets, offsets));
assert(offsetof(struct Reply_getrefoffsets, offsets) +
(sizeof ((struct Reply_getrefoffsets *)reply)->offsets[0]) *
((struct Reply_getrefoffsets *)reply)->size == received);
break;
default:
assert(received == replylen);
}
}
static void fetch_time(void) {
struct Reply_gettime r;
if (!local_time_valid) {
make_request(REQ_GETTIME, NULL, 0, &r, sizeof (r));
real_time = r.real_time;
monotonic_time = r.monotonic_time;
network_time = r.network_time;
freq_error = r.freq_error;
local_time_valid = 1;
}
}
static double get_real_time(void) {
fetch_time();
return real_time;
}
static double get_monotonic_time(void) {
fetch_time();
return monotonic_time;
}
static double get_refclock_offset(void) {
if (refclock_offsets_used >= refclock_offsets.size) {
make_request(REQ_GETREFOFFSETS, NULL, 0, &refclock_offsets, sizeof (refclock_offsets));
assert(refclock_offsets.size > 0);
refclock_offsets_used = 0;
}
return refclock_offsets.offsets[refclock_offsets_used++];
}
static double get_refclock_time(void) {
fetch_time();
return network_time - get_refclock_offset();
}
static double get_rtc_time(void) {
return get_monotonic_time() + rtc_offset;
}
static void settime(double time) {
struct Request_settime req;
req.time = time;
make_request(REQ_SETTIME, &req, sizeof (req), NULL, 0);
local_time_valid = 0;
}
static void fill_refclock_sample(void) {
struct Reply_getrefsample r;
double clock_time, receive_time, round_corr;
int i;
if (shm_refclocks == 0 && pps_fds == 0)
return;
make_request(REQ_GETREFSAMPLE, NULL, 0, &r, sizeof (r));
if (r.time == shm_refclock_time || !r.valid)
return;
shm_refclock_time = r.time;
for (i = 0; i < shm_refclocks; i++) {
if (shm_refclocks == 1) {
clock_time = r.time - r.offset;
receive_time = r.time;
} else {
clock_time = get_refclock_time();
receive_time = get_real_time();
}
round_corr = (clock_time * 1e6 - floor(clock_time * 1e6) + 0.5) / 1e6;
clock_time -= round_corr;
receive_time -= round_corr;
shm_time[i].count++;
shm_time[i].clockTimeStampSec = floor(clock_time);
shm_time[i].clockTimeStampUSec = (clock_time - shm_time[i].clockTimeStampSec) * 1e6;
shm_time[i].clockTimeStampNSec = (clock_time - shm_time[i].clockTimeStampSec) * 1e9;
shm_time[i].clockTimeStampSec += system_time_offset;
shm_time[i].receiveTimeStampSec = floor(receive_time);
shm_time[i].receiveTimeStampUSec = (receive_time - shm_time[i].receiveTimeStampSec) * 1e6;
shm_time[i].receiveTimeStampNSec = (receive_time - shm_time[i].receiveTimeStampSec) * 1e9;
shm_time[i].receiveTimeStampSec += system_time_offset;
shm_time[i].leap = 0;
shm_time[i].valid = 1;
}
}
static int socket_in_subnet(int socket, int subnet) {
switch (sockets[socket].iface) {
case IFACE_LO:
return 0;
case IFACE_UNIX:
return subnet == unix_subnet;
case IFACE_ALL:
return subnet != unix_subnet;
default:
return sockets[socket].iface - IFACE_ETH0 == subnet &&
subnet != unix_subnet;
}
}
static void get_target(int socket, uint32_t addr, unsigned int *subnet, unsigned int *node) {
if (addr == PTP_PRIMARY_MCAST_ADDR || addr == PTP_PDELAY_MCAST_ADDR) {
assert(sockets[socket].iface >= IFACE_ETH0);
*subnet = sockets[socket].iface - IFACE_ETH0;
*node = -1; /* multicast as broadcast */
} else {
*subnet = SUBNET_FROM_ADDR(addr);
if (fuzz_mode && (*subnet >= subnets || *subnet == unix_subnet))
*subnet = 0;
assert(*subnet >= 0 && *subnet < subnets);
assert(socket_in_subnet(socket, *subnet));
if (addr == BROADCAST_ADDR(*subnet))
*node = -1; /* broadcast */
else
*node = NODE_FROM_ADDR(addr);
}
}
static int get_network_from_iface(const char *iface) {
if (strncmp(iface, "eth", 3))
return -1;
return atoi(iface + 3);
}
static int get_free_socket(void) {
int i;
for (i = 0; i < MAX_SOCKETS; i++) {
if (!sockets[i].used)
return i;
}
return -1;
}
static int get_socket_from_fd(int fd) {
int s = fd - BASE_SOCKET_FD;
if (s >= 0 && s < MAX_SOCKETS && sockets[s].used)
return s;
return -1;
}
static int get_socket_fd(int s) {
return s + BASE_SOCKET_FD;
}
static int find_recv_socket(struct Reply_select *rep) {
int i, s = -1;
for (i = 0; i < MAX_SOCKETS; i++) {
if (!sockets[i].used)
continue;
if (rep == NULL)
return i;
if (!socket_in_subnet(i, rep->subnet) ||
(rep->dst_port && sockets[i].port != rep->dst_port) ||
(sockets[i].remote_node >= 0 && sockets[i].remote_node != rep->from) ||
(sockets[i].remote_port >= 0 && sockets[i].remote_port != rep->src_port))
continue;
switch (rep->type) {
case MSG_TYPE_NO_MSG:
break;
case MSG_TYPE_UDP_DATA:
if (sockets[i].type != SOCK_DGRAM)
continue;
break;
case MSG_TYPE_TCP_CONNECT:
if (sockets[i].type != SOCK_STREAM || sockets[i].connected)
continue;
break;
case MSG_TYPE_TCP_DATA:
case MSG_TYPE_TCP_DISCONNECT:
if (sockets[i].type != SOCK_STREAM ||
sockets[i].listening || !sockets[i].connected)
continue;
break;
default:
assert(0);
}
if (s < 0 || sockets[s].iface < sockets[i].iface ||
(rep->ret == REPLY_SELECT_BROADCAST && sockets[i].broadcast) ||
(rep->ret != REPLY_SELECT_BROADCAST && sockets[s].broadcast &&
!sockets[i].broadcast))
s = i;
}
return s;
}
static void send_msg_to_peer(int s, int type) {
struct Request_send req;
assert(sockets[s].domain == AF_INET);
assert(sockets[s].type == SOCK_STREAM);
if (sockets[s].remote_node == -1)
return;
req.type = type;
req.subnet = sockets[s].iface - IFACE_ETH0;
req.to = sockets[s].remote_node;
req.src_port = sockets[s].port;
req.dst_port = sockets[s].remote_port;
req.len = 0;
make_request(REQ_SEND, &req, offsetof(struct Request_send, data), NULL, 0);
}
static int get_free_timer(void) {
int i;
for (i = 0; i < MAX_TIMERS; i++) {
if (!timers[i].used)
return i;
}
return -1;
}
static timer_t get_timerid(int timer) {
return (timer_t)((long)timer + BASE_TIMER_ID);
}
static int get_timer_from_id(timer_t timerid) {
int t = (long)timerid - BASE_TIMER_ID;
if (t >= 0 && t < MAX_TIMERS && timers[t].used)
return t;
return -1;
}
static int get_timerfd(int timer) {
return timer + BASE_TIMER_FD;
}
static int get_timer_from_fd(int fd) {
int t = fd - BASE_TIMER_FD;
if (t >= 0 && t < MAX_TIMERS && timers[t].used)
return t;
return -1;
}
static int get_first_timer(fd_set *timerfds) {
int i, r = -1;
for (i = 0; i < MAX_TIMERS; i++) {
if (!timers[i].used || !timers[i].armed)
continue;
if (timers[i].type == TIMER_TYPE_FD &&
!(timerfds && FD_ISSET(get_timerfd(i), timerfds)))
continue;
if (r < 0 || timers[r].timeout > timers[i].timeout)
r = i;
}
return r;
}
static void rearm_timer(int timer)
{
assert(timers[timer].armed);
if (timers[timer].interval > 0.0)
timers[timer].timeout += timers[timer].interval;
else
timers[timer].armed = 0;
timers[timer].expired++;
}
static void time_to_timeval(double d, struct timeval *tv) {
tv->tv_sec = floor(d);
tv->tv_usec = (d - tv->tv_sec) * 1e6;
}
static void time_to_timespec(double d, struct timespec *tp) {
tp->tv_sec = floor(d);
tp->tv_nsec = (d - tp->tv_sec) * 1e9;
}
static double timeval_to_time(const struct timeval *tv, time_t offset) {
return tv->tv_sec + offset + tv->tv_usec / 1e6;
}
static double timespec_to_time(const struct timespec *tp, time_t offset) {
return tp->tv_sec + offset + tp->tv_nsec / 1e9;
}
static void normalize_timespec(struct timespec *tp) {
while (tp->tv_nsec >= 1000000000) {
tp->tv_nsec -= 1000000000;
tp->tv_sec++;
}
while (tp->tv_nsec < 0) {
tp->tv_nsec += 1000000000;
tp->tv_sec--;
}
}
static void add_to_timespec(struct timespec *tp, double offset) {
tp->tv_sec += floor(offset);
tp->tv_nsec += (offset - floor(offset)) * 1e9;
normalize_timespec(tp);
}
static double get_random_double(void) {
return (double)random() / ((1U << 31) - 1);
}
static double get_phc_delay(int dir) {
static unsigned int count = 0;
double L, p, delay = 0.0;
int k, lambda = 5;
/* Poisson with uniform steps */
if (phc_jitter > 0.0 && count >= phc_jitter_off) {
for (L = exp(-lambda), p = 1.0, k = 0; k < 100 && p > L; k++)
p *= get_random_double();
delay += (k + get_random_double()) / (lambda + 0.5) *
phc_jitter * (0.5 + dir * phc_jitter_asym);
}
count++;
if (count >= phc_jitter_on + phc_jitter_off)
count = 0;
return (delay + phc_delay / 2.0) * (freq_error + 1.0);
}
static int generate_eth_frame(unsigned int type, unsigned int subnet, unsigned int from,
unsigned int to, unsigned int src_port, unsigned int dst_port,
char *data, unsigned int data_len, char *frame, unsigned int buf_len) {
uint16_t port1, port2, ip_len, udp_len;
uint32_t addr1, addr2;
assert(type == SOCK_DGRAM || type == SOCK_STREAM);
if ((type == SOCK_DGRAM && data_len + 42 > buf_len) ||
(type == SOCK_STREAM && data_len + 54 > buf_len))
return 0;
addr1 = htonl(NODE_ADDR(subnet, from));
addr2 = htonl(NODE_ADDR(subnet, to));
port1 = htons(src_port);
port2 = htons(dst_port);
memset(frame, 0, buf_len);
frame[12] = 0x08;
frame[14] = 0x45;
memcpy(frame + 26, &addr1, sizeof (addr1));
memcpy(frame + 30, &addr2, sizeof (addr2));
memcpy(frame + 34, &port1, sizeof (port1));
memcpy(frame + 36, &port2, sizeof (port2));
if (type == SOCK_DGRAM) {
ip_len = htons(data_len + 28);
udp_len = htons(data_len + 8);
memcpy(frame + 16, &ip_len, sizeof (ip_len));
frame[23] = 17;
memcpy(frame + 38, &udp_len, sizeof (udp_len));
memcpy(frame + 42, data, data_len);
return data_len + 42;
} else {
ip_len = htons(data_len + 40);
memcpy(frame + 16, &ip_len, sizeof (ip_len));
frame[23] = 6;
frame[46] = 5 << 4;
memcpy(frame + 54, data, data_len);
return data_len + 54;
}
}
static void write_pcap_header(void) {
/* Big-endian nanosecond pcap with DLT_EN10MB */
const char header[] = "\xa1\xb2\x3c\x4d\x00\x02\x00\x04\x00\x00\x00\x00"
"\x00\x00\x00\x00\x00\x00\xff\xff\x00\x00\x00\x01";
if (!pcap)
return;
if (fwrite(header, sizeof (header) - 1, 1, pcap) != 1)
return;
}
static void write_pcap_packet(unsigned int type, unsigned int subnet, unsigned int from, unsigned int to,
unsigned int src_port, unsigned int dst_port, char *data, unsigned int len) {
char frame[64 + MAX_PACKET_SIZE];
unsigned int frame_len;
struct timespec ts;
uint32_t v;
if (!pcap)
return;
clock_gettime(CLOCK_REALTIME, &ts);
frame_len = generate_eth_frame(type, subnet, from, to, src_port, dst_port,
data, len, frame, sizeof (frame));
v = htonl(ts.tv_sec);
if (fwrite(&v, sizeof (v), 1, pcap) != 1)
return;
v = htonl(ts.tv_nsec);
if (fwrite(&v, sizeof (v), 1, pcap) != 1)
return;
v = htonl(frame_len);
if (fwrite(&v, sizeof (v), 1, pcap) != 1 || fwrite(&v, sizeof (v), 1, pcap) != 1)
return;
if (fwrite(frame, frame_len, 1, pcap) != 1)
return;
}
int gettimeofday(struct timeval *tv,
#if !defined(__GLIBC_PREREQ) || __GLIBC_PREREQ(2, 31) || defined(GETTIMEOFDAY_VOID)
void *tz
#else
struct timezone *tz
#endif
) {
double time;
time = get_real_time() + 0.5e-6;
time_to_timeval(time, tv);
tv->tv_sec += system_time_offset;
/* old chrony clock precision routine hack */
if (precision_hack)
tv->tv_usec += random() % 2;
return 0;
}
int clock_gettime(clockid_t which_clock, struct timespec *tp) {
double time;
/* try to allow reading of the clock from other constructors, but
prevent a recursive call (e.g. due to a special memory allocator) */
init();
if (!initialized) {
errno = EINVAL;
return -1;
}
switch (which_clock) {
case CLOCK_REALTIME:
case CLOCK_REALTIME_COARSE:
case SYSCLK_CLOCKID:
time = get_real_time();
break;
case CLOCK_MONOTONIC:
case CLOCK_MONOTONIC_COARSE:
time = get_monotonic_time();
break;
case REFCLK_ID:
time = get_refclock_time();
break;
default:
assert(0);
}
time += 0.5e-9;
time_to_timespec(time, tp);
if (which_clock != CLOCK_MONOTONIC && which_clock != CLOCK_MONOTONIC_COARSE)
tp->tv_sec += system_time_offset;
/* chrony and ntpd clock precision routine hack */
if (precision_hack) {
static int x = 0;
tp->tv_nsec += x++ * 101;
}
return 0;
}
time_t time(time_t *t) {
time_t time;
time = floor(get_real_time());
time += system_time_offset;
if (t)
*t = time;
return time;
}
int settimeofday(const struct timeval *tv, const struct timezone *tz) {
struct timespec ts;
assert(tv);
ts.tv_sec = tv->tv_sec;
ts.tv_nsec = 1000 * tv->tv_usec;
return clock_settime(CLOCK_REALTIME, &ts);
}
int clock_settime(clockid_t which_clock, const struct timespec *tp) {
assert(tp && which_clock == CLOCK_REALTIME);
if (tp->tv_sec < 0 || tp->tv_sec > ((1LLU << 63) / 1000000000)) {
errno = EINVAL;
return -1;
}
settime(timespec_to_time(tp, -system_time_offset));
return 0;
}