-
Notifications
You must be signed in to change notification settings - Fork 14
/
udpst_data.c
2682 lines (2548 loc) · 117 KB
/
udpst_data.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) 2020, Broadband Forum
* Copyright (c) 2020, AT&T Communications
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
* UDP Speed Test - udpst_data.c
*
* This file manages the sending and servicing of both load and status PDUs. It
* handles traffic data collection, sending rate adjustments, and any output
* messaging of test status and results.
*
* Author Date Comments
* -------------------- ---------- ----------------------------------
* Len Ciavattone 01/16/2019 Created
* Len Ciavattone 10/18/2019 Add param for load sample period
* Len Ciavattone 11/04/2019 Add minimum delays to summary
* Len Ciavattone 06/16/2020 Add dual-stack (IPv6) support
* Len Ciavattone 07/02/2020 Added (HMAC-SHA256) authentication
* Len Ciavattone 08/04/2020 Rearranged source files
* Len Ciavattone 09/03/2020 Added __linux__ conditionals
* Len Ciavattone 09/05/2020 Allow socket_error() & receive_trunc()
* to be redefined externally
* Len Ciavattone 09/18/2020 Use usec instead of ms for delta time
* values (new protocol version required)
* Len Ciavattone 10/09/2020 Add support for bimodal maxima (and
* include sub-interval count in output)
* Len Ciavattone 11/10/2020 Add option to ignore OoO/Dup
* Daniel Egger 02/22/2021 Add sendmsg support
* Len Ciavattone 10/13/2021 Refresh with clang-format
* Add TR-181 fields & sub-int. in JSON
* Add JSON bimodal output
* Add JSON error support to send_proc()
* Add interface traffic rate support
* Len Ciavattone 12/08/2021 Add starting sending rate
* Len Ciavattone 12/17/2021 Add payload randomization
* Len Ciavattone 12/24/2021 Handle interface byte counter wrap
* Len Ciavattone 01/08/2022 Check burstsize >1 if forcing to 1
* Len Ciavattone 02/02/2022 Add rate adj. algo. selection
* Al Morton 04/12/2022 Type C algoithm, Multiply and Retry
* Len Ciavattone 12/26/2022 Add random payload size support
* Len Ciavattone 12/29/2022 Add single test option on server
* Len Ciavattone 01/14/2023 Add multi-connection support
* Len Ciavattone 03/22/2023 Add GSO and GRO optimizations
* Len Ciavattone 03/25/2023 GRO replaced w/recvmmsg+truncation
* Len Ciavattone 04/04/2023 Add optional rate limiting
* Len Ciavattone 05/24/2023 Add data output (export) capability
* Len Ciavattone 10/01/2023 Updated ErrorStatus values
* Len Ciavattone 12/08/2023 Always handle intf counters as 64-bit
* Len Ciavattone 02/23/2024 Add status feedback loss to export
* Len Ciavattone 04/12/2024 Enhanced data PDU integrity checks
* Len Ciavattone 06/24/2024 Add interface Mbps to export
*
*/
#define UDPST_DATA
#ifdef __linux__
#define _GNU_SOURCE
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <limits.h>
#include <fcntl.h>
#include <time.h>
#include <math.h>
#include <unistd.h>
#include <net/if.h>
#include <arpa/inet.h>
#include <netinet/ip.h> // For GSO support
#include <netinet/udp.h> // For GSO support
#ifdef AUTH_KEY_ENABLE
#include <openssl/hmac.h>
#include <openssl/x509.h>
#endif
#else
#include "../udpst_data_alt1.h"
#endif
//
#include "cJSON.h"
#include "udpst_common.h"
#include "udpst_protocol.h"
#include "udpst.h"
#include "udpst_data.h"
#ifndef __linux__
#include "../udpst_data_alt2.h"
#endif
//----------------------------------------------------------------------------
//
// Internal function prototypes
//
int send_loadpdu(int, int);
int adjust_sending_rate(int);
int output_currate(int);
int output_maxrate(int);
double get_rate(int, struct subIntStats *, int);
#ifdef __linux__
int socket_error(int, int, char *);
int receive_trunc(int, int, int);
#endif
void sis_copy(struct subIntStats *, struct subIntStats *, BOOL);
void output_warning(int, int);
double upd_intf_stats(BOOL);
void output_minimum(int);
void output_debug(int);
BOOL verify_datapdu(int, struct loadHdr *, struct statusHdr *);
//----------------------------------------------------------------------------
//
// External data
//
extern int errConn, monConn, aggConn;
extern char scratch[STRING_SIZE];
extern struct configuration conf;
extern struct repository repo;
extern struct connection *conn;
//
extern cJSON *json_top, *json_output, *json_siArray;
extern char json_errbuf[STRING_SIZE], json_errbuf2[STRING_SIZE];
//----------------------------------------------------------------------------
//
// Global data
//
#define LOSSRATIO_TEXT "LossRatio: %.2E, "
#define DELIVERED_TEXT "Delivered(%%): %6.2f, "
#define SUMMARY_TEXT "Loss/OoO/Dup: %u/%u/%u, OWDVar(ms): %u/%u/%u, RTTVar(ms): %u-%u, Mbps(L3/IP): %.2f%s\n"
#define MINIMUM_TEXT "Minimum One-Way Delay(ms): %d [w/clock diff], Round-Trip Time(ms): %u"
#define MINIMUM_FINAL MINIMUM_TEXT ", Active Connections: %d\n"
#define DEBUG_STATS "[Loss/OoO/Dup: %u/%u/%u, OWDVar(ms): %u/%u/%u, RTTVar(ms): %d]"
#define CLIENT_DEBUG "[%d]DEBUG Status Feedback " DEBUG_STATS " Mbps(L3/IP): %.2f\n"
#define SERVER_DEBUG "[%d]DEBUG Rate Adjustment " DEBUG_STATS " SRIndex: %d\n"
static char scratch2[STRING_SIZE + 32]; // Allow for log file timestamp prefix
static int mmsgDataSize[RECVMMSG_SIZE]; // Received data size of each message
//----------------------------------------------------------------------------
// Function definitions
//----------------------------------------------------------------------------
//
// Populate the static part of the our message header
//
static void _populate_header(struct loadHdr *lHdr, struct connection *c, unsigned int rttRespDelay) {
lHdr->loadId = htons(LOAD_ID);
lHdr->testAction = (uint8_t) c->testAction;
lHdr->rxStopped = (uint8_t) c->rxStoppedLoc;
// lpduSeqNo populated by the send function
// udpPayload populated by the send function
lHdr->spduSeqErr = htons((uint16_t) c->spduSeqErr);
lHdr->spduTime_sec = htonl((uint32_t) c->spduTime.tv_sec);
lHdr->spduTime_nsec = htonl((uint32_t) c->spduTime.tv_nsec);
lHdr->lpduTime_sec = htonl((uint32_t) repo.systemClock.tv_sec);
lHdr->lpduTime_nsec = htonl((uint32_t) repo.systemClock.tv_nsec);
lHdr->rttRespDelay = htons((uint16_t) rttRespDelay);
lHdr->checkSum = 0; // Updated in send function if needed
}
//
// Randomize payload of datagram (via single call of random())
//
static void _randomize_payload(char *buffer, unsigned int length) {
register long int rvar = random(); // Obtain random value (0 - RAND_MAX)
register long int *b, *rd = (long int *) repo.randData;
register unsigned int len = length, i;
#if LONG_MAX > 2147483647L
rvar |= rvar << 32; // Copy value to upper half when using 64 bits
#endif
//
// Randomize initial bytes while aligning buffer on long int boundary
//
i = 0;
while (len && (unsigned long int) buffer % sizeof(long int)) {
*buffer++ = (char) (rvar >> i++); // Keep it very simple
len--;
}
//
// Randomize majority as long int values using randomized seed data
//
b = (long int *) buffer;
while (len > sizeof(long int)) {
*b++ = rvar ^ *rd++; // Also simple (but more efficient)
len -= sizeof(long int);
}
buffer = (char *) b;
//
// Randomize any remaining bytes
//
i = 8; // Something different than initial bytes
while (len) {
*buffer++ = (char) (rvar >> i++); // Back to very simple
len--;
}
}
#if defined(HAVE_SENDMMSG)
#if defined(HAVE_GSO)
//
// Send a burst of messages using GSO (Generic Segmentation Offload)
//
static void _sendmmsg_gso(int connindex, int totalburst, int burstsize, unsigned int payload, unsigned int addon) {
register struct connection *c = &conn[connindex];
char *sndbuf, *nextsndbuf, cmsgbuf[GSO_CMSG_SIZE * MMSG_SEGMENTS] = {0};
unsigned int uvar, rttrd = 0, totalsize;
int i, j, var;
struct cmsghdr *cmsg;
struct mmsghdr mmsg[MMSG_SEGMENTS];
struct iovec iov[MMSG_SEGMENTS];
struct timespec tspecvar;
//
// Calculate RTT response delay
//
if (tspecisset(&c->pduRxTime)) {
tspecminus(&repo.systemClock, &c->pduRxTime, &tspecvar);
rttrd = (unsigned int) tspecmsec(&tspecvar);
}
//
// Prepare send structures
//
memset(mmsg, 0, sizeof(mmsg));
if (c->randPayload) {
sndbuf = repo.sndBufRand;
} else {
sndbuf = repo.sndBuffer;
}
j = 0; // Message count
cmsg = (struct cmsghdr *) cmsgbuf;
while (totalburst > 0) {
//
// Fill send buffer until GSO limit or burst completion
//
totalsize = 0;
nextsndbuf = sndbuf;
for (i = 0; i < totalburst; i++) {
if (i < burstsize)
uvar = payload;
else
uvar = addon;
//
// Check for GSO limits
//
if (i >= UDP_MAX_SEGMENTS) // Segment limit
break;
if (totalsize + uvar > IP_MAXPACKET) // Size limit
break;
//
// Build load PDU (including corresponding control message on first one)
//
struct loadHdr *lHdr = (struct loadHdr *) nextsndbuf;
_populate_header(lHdr, c, rttrd);
lHdr->lpduSeqNo = htonl((uint32_t) ++c->lpduSeqNo);
lHdr->udpPayload = htons((uint16_t) uvar);
#ifdef ADD_HEADER_CSUM
if (c->protocolVer >= CHECKSUM_PVER)
lHdr->checkSum = checksum(lHdr, sizeof(struct loadHdr));
#endif
if (c->randPayload) {
_randomize_payload((char *) lHdr + sizeof(struct loadHdr), uvar - sizeof(struct loadHdr));
}
if (i == 0) {
cmsg->cmsg_len = GSO_CMSG_LEN;
cmsg->cmsg_level = SOL_UDP;
cmsg->cmsg_type = UDP_SEGMENT;
*((uint16_t *) CMSG_DATA(cmsg)) = (uint16_t) uvar;
}
totalsize += uvar;
nextsndbuf += payload;
}
totalburst -= i;
if (burstsize > 0)
burstsize -= i;
//
// Setup message structure for buffer
//
iov[j].iov_base = (void *) sndbuf;
iov[j].iov_len = (size_t) totalsize;
mmsg[j].msg_hdr.msg_iov = &iov[j];
mmsg[j].msg_hdr.msg_iovlen = 1;
mmsg[j].msg_hdr.msg_control = cmsg;
mmsg[j].msg_hdr.msg_controllen = GSO_CMSG_SIZE;
j++;
//
// Advance to next send buffer
//
sndbuf += DEF_BUFFER_SIZE;
cmsg = (struct cmsghdr *) ((char *) cmsg + GSO_CMSG_SIZE);
}
//
// Send complete burst with single system call
//
// NOTE: Certain error conditions are expected when overloading an interface
//
var = sendmmsg(c->fd, mmsg, j, 0);
if (var == -1 && errno == EINVAL) { // Flag GSO incompatibility
var = sprintf(scratch, "ERROR: GSO incompatible with IP fragmentation (disable jumbo sizes or increase MTU)\n");
send_proc(errConn, scratch, var);
tspeccpy(&c->endTime, &repo.systemClock); // End testing
return;
}
if (!conf.errSuppress) {
if (var < 0) {
//
// An error of EAGAIN (Resource temporarily unavailable) indicates the send buffer is full
//
if ((var = socket_error(connindex, errno, "SENDMMSG+GSO")) > 0)
send_proc(errConn, scratch, var);
} else if (var < j) {
//
// Not all messages sent indicates the send buffer is full
//
var = sprintf(scratch, "[%d]SENDMMSG+GSO INCOMPLETE: Only %d out of %d sent\n", connindex, var, j);
send_proc(errConn, scratch, var);
}
}
}
#else
//
// Send a burst of messages using the Linux 3.0+ only sendmmsg syscall
//
static void _sendmmsg_burst(int connindex, int totalburst, int burstsize, unsigned int payload, unsigned int addon) {
register struct connection *c = &conn[connindex];
static struct mmsghdr mmsg[MAX_BURST_SIZE]; // Static array
static struct iovec iov[MAX_BURST_SIZE]; // Static array
unsigned int uvar, rttrd = 0;
char *nextsndbuf;
int i, var;
struct timespec tspecvar;
//
// Calculate RTT response delay
//
if (tspecisset(&c->pduRxTime)) {
tspecminus(&repo.systemClock, &c->pduRxTime, &tspecvar);
rttrd = (unsigned int) tspecmsec(&tspecvar);
}
//
// Prepare send structures
//
memset(mmsg, 0, totalburst * sizeof(struct mmsghdr));
if (c->randPayload) {
nextsndbuf = repo.sndBufRand;
} else {
nextsndbuf = repo.sndBuffer;
}
for (i = 0; i < totalburst; i++) {
struct loadHdr *lHdr = (struct loadHdr *) nextsndbuf;
_populate_header(lHdr, c, rttrd);
lHdr->lpduSeqNo = htonl((uint32_t) ++c->lpduSeqNo);
if (i < burstsize)
uvar = payload;
else
uvar = addon;
lHdr->udpPayload = htons((uint16_t) uvar);
#ifdef ADD_HEADER_CSUM
if (c->protocolVer >= CHECKSUM_PVER)
lHdr->checkSum = checksum(lHdr, sizeof(struct loadHdr));
#endif
if (c->randPayload) {
_randomize_payload((char *) lHdr + sizeof(struct loadHdr), uvar - sizeof(struct loadHdr));
}
//
// Setup corresponding message structure
//
iov[i].iov_base = (void *) lHdr;
iov[i].iov_len = (size_t) uvar;
mmsg[i].msg_hdr.msg_iov = &iov[i];
mmsg[i].msg_hdr.msg_iovlen = 1;
nextsndbuf += payload;
}
//
// Send complete burst with single system call
//
// NOTE: Certain error conditions are expected when overloading an interface
//
var = sendmmsg(c->fd, mmsg, totalburst, 0);
if (!conf.errSuppress) {
if (var < 0) {
//
// An error of EAGAIN (Resource temporarily unavailable) indicates the send buffer is full
//
if ((var = socket_error(connindex, errno, "SENDMMSG")) > 0)
send_proc(errConn, scratch, var);
} else if (var < totalburst) {
//
// Not all messages sent indicates the send buffer is full
//
var = sprintf(scratch, "[%d]SENDMMSG INCOMPLETE: Only %d out of %d sent\n", connindex, var, totalburst);
send_proc(errConn, scratch, var);
}
}
}
#endif // HAVE_GSO
#else
//
// Send a burst of messages using the slower but more widely available sendmsg syscall
//
static void _sendmsg_burst(int connindex, int totalburst, int burstsize, unsigned int payload, unsigned int addon) {
register struct connection *c = &conn[connindex];
struct msghdr msg;
struct iovec iov;
unsigned int uvar, rttrd = 0;
int i;
struct loadHdr *lHdr;
struct timespec tspecvar;
//
// Calculate RTT response delay
//
if (tspecisset(&c->pduRxTime)) {
tspecminus(&repo.systemClock, &c->pduRxTime, &tspecvar);
rttrd = (unsigned int) tspecmsec(&tspecvar);
}
//
// Prepare send structures
//
memset((void *) &msg, 0, sizeof(struct msghdr));
if (c->randPayload) {
lHdr = (struct loadHdr *) repo.sndBufRand;
} else {
lHdr = (struct loadHdr *) repo.sndBuffer;
}
_populate_header(lHdr, c, rttrd);
for (i = 0; i < totalburst; i++) {
int var;
lHdr->lpduSeqNo = htonl((uint32_t) ++c->lpduSeqNo);
if (i < burstsize)
uvar = payload;
else
uvar = addon;
lHdr->udpPayload = htons((uint16_t) uvar);
#ifdef ADD_HEADER_CSUM
lHdr->checkSum = 0; // Zero on each pass because _populate_header() is only called once
if (c->protocolVer >= CHECKSUM_PVER)
lHdr->checkSum = checksum(lHdr, sizeof(struct loadHdr));
#endif
if (c->randPayload) {
_randomize_payload((char *) lHdr + sizeof(struct loadHdr), uvar - sizeof(struct loadHdr));
}
//
// Setup corresponding message structure
//
iov.iov_base = (void *) lHdr;
iov.iov_len = (size_t) uvar;
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
//
// Send a single message of our burst with a system call
//
// NOTE: Certain error conditions are expected when overloading an interface
//
var = sendmsg(c->fd, &msg, 0);
if (!conf.errSuppress) {
if (var < 0) {
//
// An error of EAGAIN (Resource temporarily unavailable) indicates the send buffer is full
//
if ((var = socket_error(connindex, errno, "SENDMSG")) > 0)
send_proc(errConn, scratch, var);
}
}
}
}
#endif // HAVE_SENDMMSG
//
// Send load PDUs via periodic timers for transmitters 1 & 2
//
int send1_loadpdu(int connindex) {
return send_loadpdu(connindex, 1);
}
int send2_loadpdu(int connindex) {
return send_loadpdu(connindex, 2);
}
int send_loadpdu(int connindex, int transmitter) {
register struct connection *c = &conn[connindex];
int var, burstsize, totalburst, txintpri, txintalt;
unsigned int payload, addon;
BOOL randpayload;
struct timespec tspecvar, *tspecpri, *tspecalt;
struct sendingRate *sr;
//
// Select sending rate source
//
if (repo.isServer) {
sr = &repo.sendingRates[c->srIndex]; // Local table if server
} else {
sr = &c->srStruct; // Server specified values if client
}
//
// Select transmitter specifics
//
randpayload = FALSE;
if (transmitter == 1) {
payload = (unsigned int) (sr->udpPayload1 & ~SRATE_RAND_BIT);
if (sr->udpPayload1 & SRATE_RAND_BIT)
randpayload = TRUE;
burstsize = (int) sr->burstSize1;
addon = 0;
} else {
payload = (unsigned int) (sr->udpPayload2 & ~SRATE_RAND_BIT);
if (sr->udpPayload2 & SRATE_RAND_BIT)
randpayload = TRUE;
burstsize = (int) sr->burstSize2;
addon = (unsigned int) (sr->udpAddon2 & ~SRATE_RAND_BIT);
}
//
// If IPv6 reduce payload to maintain L3 packet sizes
//
if (c->ipProtocol == IPPROTO_IPV6) {
if (payload >= MIN_PAYLOAD_SIZE)
payload -= IPV6_ADDSIZE;
if (addon >= MIN_PAYLOAD_SIZE)
addon -= IPV6_ADDSIZE;
}
//
// If designated as random, use stored size as max when calculating size
//
var = MIN_PAYLOAD_SIZE;
if (c->ipProtocol == IPPROTO_IPV6) {
var -= IPV6_ADDSIZE;
}
if (payload > 0 && randpayload) {
payload = getuniform(var, payload);
}
if (addon > 0 && (sr->udpAddon2 & SRATE_RAND_BIT)) {
addon = getuniform(var, addon);
}
//
// Handle test stop in progress
//
if (c->testAction != TEST_ACT_TEST) {
if (burstsize > 1)
burstsize = 1; // Reduce load w/min burst size
if (repo.isServer) {
if (conf.verbose && c->testAction == TEST_ACT_STOP1) {
int var = sprintf(scratch, "[%d]Sending test stop\n", connindex);
send_proc(monConn, scratch, var);
}
c->testAction = TEST_ACT_STOP2; // Second phase of test stop
} else {
//
// The PDU sent in this pass will confirm the test stop back to the server,
// schedule an immediate/subsequent test end
//
tspeccpy(&c->endTime, &repo.systemClock);
}
if (repo.endTimeStatus > STATUS_WARNMAX) // Declare success, but retain warnings
repo.endTimeStatus = STATUS_SUCCESS; // ErrorStatus
}
//
// Process timers 1 & 2 as primary or alternate
//
if (transmitter == 1) {
txintpri = (int) sr->txInterval1;
txintalt = (int) sr->txInterval2;
tspecpri = &c->timer1Thresh;
tspecalt = &c->timer2Thresh;
} else {
txintpri = (int) sr->txInterval2;
txintalt = (int) sr->txInterval1;
tspecpri = &c->timer2Thresh;
tspecalt = &c->timer1Thresh;
}
//
// Reset or clear primary timer (this one)
//
if (txintpri > 0) {
tspecvar.tv_sec = 0;
tspecvar.tv_nsec = (long) ((txintpri - SEND_TIMER_ADJ) * NSECINUSEC);
tspecplus(&repo.systemClock, &tspecvar, tspecpri);
} else {
tspecclear(tspecpri);
}
//
// Set or clear alternate timer (the other one)
//
if (!tspecisset(tspecalt) && txintalt > 0) {
tspecvar.tv_sec = 0;
tspecvar.tv_nsec = (long) ((txintalt - SEND_TIMER_ADJ) * NSECINUSEC);
tspecplus(&repo.systemClock, &tspecvar, tspecalt);
} else if (tspecisset(tspecalt) && txintalt == 0) {
tspecclear(tspecalt);
}
//
// Initialize interface stats on first PDU if sysfs FD is valid
//
if (repo.intfFD >= 0 && !tspecisset(&repo.intfTime)) {
upd_intf_stats(TRUE);
}
//
// Check for burst size of zero
//
if (burstsize == 0 && addon == 0) {
return 0; // Nothing to do until next call
}
//
// If receive traffic stopped, set indicator to inform peer and generate warning (else clear indicator)
//
if (tspecisset(&c->pduRxTime)) {
tspecminus(&repo.systemClock, &c->pduRxTime, &tspecvar);
if (tspecvar.tv_sec >= WARNING_NOTRAFFIC) {
c->rxStoppedLoc = TRUE;
tspecclear(&c->pduRxTime); // Clear PDU receive time to maintain indicator until traffic resumes
if (c->warningCount < WARNING_MSG_LIMIT) {
c->warningCount++;
output_warning(connindex, WARN_LOC_STOPPED);
}
} else {
c->rxStoppedLoc = FALSE;
}
}
//
// Build complete burst of datagrams and message structures
//
totalburst = burstsize;
if (addon > 0)
totalburst++;
#if defined(HAVE_SENDMMSG)
#if defined(HAVE_GSO)
_sendmmsg_gso(connindex, totalburst, burstsize, payload, addon);
#else
_sendmmsg_burst(connindex, totalburst, burstsize, payload, addon);
#endif // HAVE_GSO
#else
_sendmsg_burst(connindex, totalburst, burstsize, payload, addon);
#endif // HAVE_SENDMMSG
return 0;
}
//----------------------------------------------------------------------------
//
// Service incoming load PDUs
//
int service_loadpdu(int connindex) {
register struct connection *c = &conn[connindex];
int i, delta, var;
BOOL bvar, firstpdu = FALSE;
unsigned int uvar, seqno, rttrd, payload;
struct loadHdr *lHdr = (struct loadHdr *) repo.rcvDataPtr;
struct timespec tspecvar, tspecdelta;
char *nulloutput = ",,,,,\n";
//
// Verify PDU
//
if (!verify_datapdu(connindex, lHdr, NULL)) {
return 0; // Ignore bad PDU
}
//
// Handle test stop in progress, else extend test (reset watchdog)
//
if (c->testAction != TEST_ACT_TEST || lHdr->testAction != TEST_ACT_TEST) {
if (repo.isServer) {
//
// If client is confirming stop, end test
//
if (lHdr->testAction != TEST_ACT_TEST) {
tspeccpy(&c->endTime, &repo.systemClock);
return 0;
}
} else {
//
// On first pass, finalize testing
//
if (c->testAction == TEST_ACT_TEST) {
if (conf.verbose) {
var = sprintf(scratch, "[%d]Test stop received\n", connindex);
send_proc(monConn, scratch, var);
}
c->testAction = (int) lHdr->testAction;
}
return 0;
}
} else {
tspecvar.tv_sec = TIMEOUT_NOTRAFFIC;
tspecvar.tv_nsec = 0;
tspecplus(&repo.systemClock, &tspecvar, &c->endTime);
}
//
// Save receive time for this PDU
//
tspeccpy(&c->pduRxTime, &repo.systemClock);
//
// Generate warning if peer indicates receive traffic has stopped
//
if ((bvar = (BOOL) lHdr->rxStopped) != c->rxStoppedRem) {
c->rxStoppedRem = bvar; // Save value if changed
if (c->rxStoppedRem) { // Only warn if state indicates true
if (c->warningCount < WARNING_MSG_LIMIT) {
c->warningCount++;
output_warning(connindex, WARN_REM_STOPPED);
}
}
}
//
// Update traffic stats (use size specified in PDU, actual receive may have been truncated)
//
payload = (unsigned int) ntohs(lHdr->udpPayload);
c->sisAct.rxDatagrams++;
c->sisAct.rxBytes += (uint64_t) payload;
c->tiRxDatagrams++;
c->tiRxBytes += payload;
//
// Check sequence number for loss, also reordering/duplication (end processing if so)
//
if (c->lpduSeqNo == 0)
firstpdu = TRUE;
var = 0; // Used below for history buffer processing
seqno = (unsigned int) ntohl(lHdr->lpduSeqNo);
if (seqno >= c->lpduSeqNo + 1) {
//
// Sequence number greater than or equal to expected
//
if (seqno > c->lpduSeqNo + 1) {
uvar = seqno - c->lpduSeqNo - 1; // Calculate loss
c->seqErrLoss += uvar;
c->sisAct.seqErrLoss += (uint32_t) uvar;
}
c->lpduSeqNo = seqno; // Update for next expected
} else {
//
// Sequence number less than expected, check history buffer
//
for (i = 0; i < LPDU_HISTORY_SIZE; i++) {
if (seqno == c->lpduHistBuf[i])
break;
}
if (i < LPDU_HISTORY_SIZE) {
//
// Sequence number in history buffer, increment duplicate count
//
c->seqErrDup++;
c->sisAct.seqErrDup++;
var = 2; // Skip history buffer insertion as well as subsequent processing
} else {
//
// Sequence number NOT in history buffer, increment out-of-order count
//
c->seqErrOoo++;
c->sisAct.seqErrOoo++;
var = 1; // Skip subsequent processing
//
// Correct previous loss count that resulted from this "late" datagram
//
// NOTE: If this datagram arrives after either of these have been cleared (because they were just sent
// in a status feedback message), the previous trial or sub-interval will still show the loss.
//
if (c->seqErrLoss > 0)
c->seqErrLoss--;
if (c->sisAct.seqErrLoss > 0)
c->sisAct.seqErrLoss--;
}
}
if (var < 2) {
c->lpduHistBuf[c->lpduHistIdx] = seqno; // Save sequence number in history buffer
++c->lpduHistIdx; // Advance history buffer index
c->lpduHistIdx &= LPDU_HISTORY_MASK; // Maintain index limit
}
//
// Calculate one-way clock delta (used again further down)
//
tspecvar.tv_sec = (time_t) ntohl(lHdr->lpduTime_sec);
tspecvar.tv_nsec = (long) ntohl(lHdr->lpduTime_nsec);
tspecminus(&repo.systemClock, &tspecvar, &tspecdelta);
delta = (int) tspecmsec(&tspecdelta);
if (c->outputFPtr != NULL) { // Start output data with one-way values
fprintf(c->outputFPtr, "%u,%u,%ld.%06ld,%ld.%06ld,%d,%.2f", seqno, payload, (long) tspecvar.tv_sec,
tspecvar.tv_nsec / NSECINUSEC, (long) repo.systemClock.tv_sec, repo.systemClock.tv_nsec / NSECINUSEC, delta,
repo.intfMbps);
}
if (var > 0) {
if (c->outputFPtr != NULL) { // Finalize output data with null entries
fputs(nulloutput, c->outputFPtr);
}
return 0; // No further processing for non-increasing sequence numbers
}
//
// If an updated value is detected (because another status PDU was sent),
// calculate round-trip time from the last status PDU sent until this load PDU
//
tspecvar.tv_sec = (time_t) ntohl(lHdr->spduTime_sec);
tspecvar.tv_nsec = (long) ntohl(lHdr->spduTime_nsec);
if (tspecvar.tv_nsec != c->spduTime.tv_nsec || tspecvar.tv_sec != c->spduTime.tv_sec) {
tspecminus(&repo.systemClock, &tspecvar, &tspecdelta);
uvar = (unsigned int) tspecmsec(&tspecdelta);
//
// Adjust RTT based on delay between when status PDU was received and load PDU sent
//
if ((rttrd = (unsigned int) ntohs(lHdr->rttRespDelay)) <= uvar) {
uvar -= rttrd;
} else if (rttrd == uvar + 1) { // Allow for rounding adjustment on either end
uvar = 0;
}
//
// Generate warning if peer indicates status message sequence errors
//
c->spduSeqErr = (int) ntohs(lHdr->spduSeqErr);
if (c->spduSeqErr > 0) { // Only warn if count indicates loss
if (c->warningCount < WARNING_MSG_LIMIT) {
c->warningCount++;
output_warning(connindex, WARN_REM_STATUS);
}
}
if (c->outputFPtr != NULL) { // Finalize output data with RTT values
fprintf(c->outputFPtr, ",%ld.%06ld,%ld.%06ld,%u,%u,%d\n", (long) tspecvar.tv_sec,
tspecvar.tv_nsec / NSECINUSEC, (long) repo.systemClock.tv_sec,
repo.systemClock.tv_nsec / NSECINUSEC, rttrd, uvar, c->spduSeqErr);
}
//
// Check for new minimum
//
if (uvar < c->rttMinimum) {
c->rttMinimum = uvar;
c->delayMinUpd = TRUE;
}
//
// Update RTT variation for trial interval and RTT variation range for sub-interval
//
c->rttSample = uvar - c->rttMinimum;
if (c->rttSample < (unsigned int) c->sisAct.rttMinimum)
c->sisAct.rttMinimum = (uint32_t) c->rttSample;
if (c->rttSample > (unsigned int) c->sisAct.rttMaximum)
c->sisAct.rttMaximum = (uint32_t) c->rttSample;
tspeccpy(&c->spduTime, &tspecvar); // Save to detect updated value
} else {
if (c->outputFPtr != NULL) { // Finalize output data with null entries
fputs(nulloutput, c->outputFPtr);
}
}
//
// Process one-way clock delta (calculated above) and delay variation for this load PDU
//
if (firstpdu) {
c->clockDeltaMin = delta;
c->delayMinUpd = TRUE;
} else {
//
// Check for new minimum
//
if (delta < c->clockDeltaMin) {
c->clockDeltaMin = delta;
c->delayMinUpd = TRUE;
}
uvar = (unsigned int) (delta - c->clockDeltaMin);
//
// Update one-way delay variation stats for trial interval
//
if (uvar < c->delayVarMin)
c->delayVarMin = uvar;
if (uvar > c->delayVarMax)
c->delayVarMax = uvar;
c->delayVarSum += uvar;
c->delayVarCnt++;
//
// Update one-way delay variation stats for sub-interval
//
if (uvar < (unsigned int) c->sisAct.delayVarMin)
c->sisAct.delayVarMin = (uint32_t) uvar;
if (uvar > (unsigned int) c->sisAct.delayVarMax)
c->sisAct.delayVarMax = (uint32_t) uvar;
c->sisAct.delayVarSum += (uint32_t) uvar;
c->sisAct.delayVarCnt++;
}
return 0;
}
//----------------------------------------------------------------------------
//
// Send status PDUs via periodic timer
//
int send_statuspdu(int connindex) {
register struct connection *c = &conn[connindex];
int var;
struct timespec tspecvar;
struct sendingRate *sr;
struct statusHdr *sHdr = (struct statusHdr *) repo.defBuffer;
//
// Check for test stop in progress, else reset status send timer
//
if (c->testAction != TEST_ACT_TEST) {
tspecclear(&c->timer1Thresh); // Stop subsequent status messages
if (repo.isServer) {
if (conf.verbose && c->testAction == TEST_ACT_STOP1) {
var = sprintf(scratch, "[%d]Sending test stop\n", connindex);
send_proc(monConn, scratch, var);
}
c->testAction = TEST_ACT_STOP2; // Second phase of test stop
} else {
//
// The PDU sent in this pass will confirm the test stop back to the server,
// schedule an immediate/subsequent test end
//
tspeccpy(&c->endTime, &repo.systemClock);
}
if (repo.endTimeStatus > STATUS_WARNMAX) // Declare success, but retain warnings
repo.endTimeStatus = STATUS_SUCCESS; // ErrorStatus
} else {
tspecvar.tv_sec = 0;
tspecvar.tv_nsec = (long) (c->trialInt * NSECINMSEC);
tspecplus(&repo.systemClock, &tspecvar, &c->timer1Thresh);
//
// Only continue if some data has been received (initial load PDUs could still be in transit)
//
if (c->lpduSeqNo == 0) {
if (c->infoCount < INFO_MSG_LIMIT && conf.verbose) {
c->infoCount++;
var = sprintf(scratch, "[%d]INFO: Skipping status transmission, awaiting initial load PDUs...\n",
connindex);
send_proc(monConn, scratch, var);
}
return 0;
}
//
// If server, adjust sending rate based on our receive traffic conditions
//
if (repo.isServer) {
adjust_sending_rate(connindex);
}
}
//
// If receive traffic stopped, set indicator to inform peer and generate warning (else clear indicator)
//
if (tspecisset(&c->pduRxTime)) {
tspecminus(&repo.systemClock, &c->pduRxTime, &tspecvar);
if (tspecvar.tv_sec >= WARNING_NOTRAFFIC) {
c->rxStoppedLoc = TRUE;
tspecclear(&c->pduRxTime); // Clear PDU receive time to maintain indicator until traffic resumes
if (c->warningCount < WARNING_MSG_LIMIT) {
c->warningCount++;
output_warning(connindex, WARN_LOC_STOPPED);
}
} else {
c->rxStoppedLoc = FALSE;
}
}