-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtrafficGen.cpp
2097 lines (1865 loc) · 80 KB
/
trafficGen.cpp
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
/****************************************************************************
* trafficGen.cpp *
****************************************************************************
* Copyright (C) 2013 Technische Universitaet Berlin *
* *
* Created on: Aug 30, 2013 *
* Authors: Konstantin Miller <[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 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************/
#include <sys/types.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/select.h>
#include <netinet/tcp.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>
#include <stdio.h>
#include <cstdlib>
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <getopt.h>
#include <cassert>
#include <pthread.h>
#ifndef __SENDER
# include <pcap.h>
#endif
#include <errno.h>
#include <ifaddrs.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <map>
#include <set>
#include <string>
#include <list>
#include <mutex>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <random>
#include <boost/circular_buffer.hpp>
using std::map;
using std::set;
using std::string;
using std::list;
using std::pair;
//#include "VectorList.h"
struct {
enum {UNDEF, SENDER, RECEIVER} senderReceiver = UNDEF;
bool ifActive = false;
uint16_t psvPort = 0;
string psvIp;
string actIp;
int64_t tcp_info_log_interval = 100000; // [us]
} global_info;
struct {
int fd = -1;
FILE* logFile = NULL;
struct tcp_info lastTcpInfo;
} tcp_logger_info;
struct {
FILE* f_sender_log = NULL;
bool hang_up = false;
bool permanent = false;
} sender_info;
struct
{
/* types */
enum RequestPatternType {DETERMINISTIC, NORMAL};
struct RequestPatternDeterministic {
int64_t on_duration;
int64_t off_duration;
};
struct RequestPatternNormal {
int64_t mean;
int64_t std;
int64_t min;
int64_t max;
int64_t tau; // segment duration, [ms]
};
/* request pattern stuff */
string request_pattern;
RequestPatternType request_pattern_type;
union {
RequestPatternDeterministic request_pattern_deterministic;
RequestPatternNormal request_pattern_normal;
};
string dev_name;
int64_t dev_wait_max = -1; // [us]
string dev_name_mon;
FILE* file_request_log;
int64_t request_sent = 0;
int64_t first_data_received = 0; // [us]
int64_t last_data_received = 0;
int64_t request_size = 0;
int64_t scheduled_on_duration = 0;
double max_thrpt = -1; // [bps]
int64_t max_thrpt_duration = -1; // [us]
} rcv_info;
struct rcv_log_info_t
{
//std::mutex mutex;
rcv_log_info_t(): pcap_tcp_data(65536), pcap_rdtap_data(65536) {}
#ifndef __SENDER
static const int pcap_snaplen = 96;
static const int radiotap_snaplen = 512;
pcap_t* pcap_tcp = NULL;
pcap_t* pcap_rdtap = NULL;
pcap_dumper_t* pcap_dumper_tcp = NULL;
pcap_dumper_t* pcap_dumper_rdtap = NULL;
#endif
struct pcap_element {
pcap_element(const struct pcap_pkthdr* _pkthdr, const u_char* _pktdata) {
pkthdr = *_pkthdr;
assert(pkthdr.caplen <= sizeof(pktdata));
std::memcpy(pktdata, _pktdata, pkthdr.caplen * sizeof(u_char));
}
struct pcap_pkthdr pkthdr;
u_char pktdata[(pcap_snaplen < radiotap_snaplen) ? radiotap_snaplen : pcap_snaplen];
};
boost::circular_buffer<pcap_element> pcap_tcp_data;
boost::circular_buffer<pcap_element> pcap_rdtap_data;
std::mutex pcap_tcp_data_mutex;
std::mutex pcap_rdtap_data_mutex;
//FILE* f = NULL;
//int64_t dt = 0; // [us]
//int64_t ts_first_packet = 0; // [us]
//int64_t tcp_ts_first_packet = 0; // [us]
//int64_t index = -1; // [us]
//int64_t num_bytes = 0;
//vector<int64_t> delay_vec; // [us]
//vector<int> missing_vec;
//int64_t off1;
//int64_t off2;
//void reset() {
// num_bytes = 0;
// delay_vec.resize(0);
// missing_vec.resize(0);
// off1 = 0;
// off2 = 0;
//}
} rcv_log_info;
#pragma pack(push, 1)
struct Rcv2Snd_Params {
uint8_t limitType = 0; // 0 for time, 1 for volume
uint32_t limitValue = 0; // if time: [ms], if volume: [byte]
uint8_t hang_up = 0; // 1 for disconnect after request completed, otherwise 0
};
#pragma pack(pop)
void printUsageAndExit(int line);
void parseInputArguments(int argc, char** argv);
void signalHandler(int sig);
void* runSender(void* args);
void* runReceiver(void* args);
void* runTcpStateLogger(void* args);
void* runSniffer(void* _args);
void* runRadiotap(void* _args);
int64_t now();
void recordTcpState(int fd, const char* reason, FILE* f);
void recordTcpState(FILE* f, const struct tcp_info& tcpInfo, const int64_t t, const char* reason);
string tcpState2String(int tcpState);
string tcpCAState2String(int tcpCAState);
//void rcv_log_output();
string getTimeString(int64_t t, bool showDate);
string get_dev_for_ip(string ip);
string get_ip_for_dev(string dev);
bool wait_for_dev(string dev, int64_t max_wait);
void parse_request_pattern(const char* request_pattern);
//void* run_flusher(void* _args);
char buf[1048576]; // for various string manipulations
const int sndbufsize = 1048576; // 8192;
//const int rcvbufsize = 2 * 1048576;
string config;
string traceDir(".");
int64_t Tmax = -1;
int64_t t_start_sender = 0;
int64_t t_start_receiver = 0;
bool terminate_tcp_logger = false;
bool globalTerminationFlag = false;
std::default_random_engine generator(std::chrono::system_clock::now().time_since_epoch().count());
int main(int argc, char** argv)
{
printf("Up and running...\n");
sprintf(buf, "main_enter %" PRId64 "\n", now());
config.append(buf);
parseInputArguments(argc, argv);
/* install signal handler */
struct sigaction sigAction;
sigAction.sa_handler = signalHandler;
sigemptyset(&sigAction.sa_mask);
sigAction.sa_flags = 0;
assert(0 == sigaction(SIGINT, &sigAction, NULL));
assert(0 == sigaction(SIGTERM, &sigAction, NULL));
assert(0 == sigaction(SIGALRM, &sigAction, NULL));
/* start flusher thread */
//pthread_t flusher_thread;
//assert(0 == pthread_create(&flusher_thread, NULL, &run_flusher, NULL));
if(global_info.senderReceiver == global_info.SENDER)
{
/* open log file */
char fn_sender_log[4096];
sprintf(fn_sender_log, "%s/sender_log_%016" PRId64 ".txt", traceDir.c_str(), now());
sender_info.f_sender_log = fopen(fn_sender_log, "w");
assert(sender_info.f_sender_log);
setlinebuf(sender_info.f_sender_log);
pthread_t senderThread;
while(!globalTerminationFlag) {
assert(0 == pthread_create(&senderThread, NULL, &runSender, NULL));
assert(0 == pthread_join(senderThread, NULL));
if(!sender_info.permanent) {
globalTerminationFlag = true;
printf("Terminating sender.\n");
}
}
/* close log file */
assert(0 == fclose(sender_info.f_sender_log));
}
else if(global_info.senderReceiver == global_info.RECEIVER)
{
pthread_t receiverThread;
assert(0 == pthread_create(&receiverThread, NULL, &runReceiver, NULL));
assert(0 == pthread_join(receiverThread, NULL));
}
else
{
abort();
}
/* wait for the flusher thread */
//assert(0 == pthread_join(flusher_thread, NULL));
sprintf(buf, "main_terminate %" PRId64 "\n", now());
config.append(buf);
/* write parameters to file */
if(global_info.senderReceiver == global_info.RECEIVER)
{
sprintf(buf, "%s/rcv_config_%016" PRId64 ".txt", traceDir.c_str(), t_start_receiver);
FILE* f = fopen(buf, "w");
fprintf(f, "%s", config.c_str());
fclose(f);
}
return 0;
}
void printUsageAndExit(int line)
{
printf("Error parsing command line arguments in line %d.\n", line);
printf("OPTIONS\n");
printf("\n");
printf("--role=( sender | receiver )\n");
printf(" Mandatory.\n");
printf("\n");
printf("--active\n");
printf(" Optional. If set, the peer actively connects to the remote peer.\n");
printf("\n");
printf("--permanent\n");
printf(" Optional. Only valid for the passive peer. If set, does not terminate after the active peer disconnects.\n");
printf("\n");
printf("--passive-ip=xxx.xxx.xxx.xxx\n");
printf(" Mandatory. IP of the passive peer.\n");
printf("\n");
printf("--passive-port=<integer>\n");
printf(" Mandatory. Port of the passive peer.\n");
printf("\n");
printf("--active-ip=xxx.xxx.xxx.xxx\n");
printf(" Optional. If present, specifies the IP of the active peer. Otherwise,\n");
printf(" the default is used.\n");
printf("\n");
printf("--dev-name=<string>\n");
printf(" Optional, only valid if --active is set and --active-ip is not set. Uses\n");
printf(" the default IP of the specified network interface as source IP.\n");
printf("\n");
printf("--dev-wait-max=<double, [s]>\n");
printf(" Optional, only valid if --dev-name is set. Waits for device to become\n");
printf(" available for up to the specified number of seconds.\n");
printf("\n");
printf("--dev-name-mon=<string>\n");
printf(" Device for radiotap recording. If not specified, no readiotap headers are\n");
printf(" recorded.\n");
printf("\n");
printf("--trace-duration=<integer, [s]>\n");
printf(" Mandatory for active peer, invalid for passive peer. Specifies the\n");
printf(" duration of the trace.\n");
printf("\n");
printf("--max-thrpt=<double, [Mbps]>\n");
printf(" Optional. Throughput upper bound. If the throughput exceeds upper bound,\n");
printf(" terminate experiment. If set, --max-thrpt-duration must be set too.\n");
printf("\n");
printf("--max-thrpt-duration=<double, [s]>\n");
printf(" Optional. Specifies duration over which throughput upper bound must not\n");
printf(" be exceeded. If set, --max-thrpt must be set.\n");
printf("\n");
printf("--log-dir=<string>\n");
printf(" Optional. Directory for file output. If not set, current directory is used.\n");
printf("\n");
printf("--tcp-info-log-interval=<integer, [ms]>\n");
printf(" Optional, between 0 and 1000 ms. Specifies the sampling rate for struct\n");
printf(" tcp_info. If not set, the default value of 100 ms is used. If set to 0,\n");
printf(" logging takes place before and after every socket operation.\n");
printf("\n");
printf("--request-pattern=<string>\n");
printf(" Optional, only valid for receiver. If not set, a continuous TCP flow of\n");
printf(" duration specified in --trace-duration is requested. Possible values are:\n");
printf(" deterministic:AAA:BBB\n");
printf(" AAA, BBB: integer, [ms]\n");
printf(" Generates an ON/OFF pattern with deterministic duration of ON and OFF\n");
printf(" phases. AAA specifies the duration of the request (ON phase), while BBB\n");
printf(" specifies the duration of the inter-request gap (OFF phase).\n");
printf(" normal:AAA:BBB:CCC:DDD:EEE\n");
printf(" AAA, BBB, CCC, DDD, EEE: integer, [ms]\n");
printf(" Generates a random ON/OFF pattern with normally distributed duration of\n");
printf(" of the ON phase, with mean AAA and standard deviation BBB. In order to\n");
printf(" avoid negative or very long values, only values with the interval\n");
printf(" [CCC, DDD] are accepted. The duration of the OFF phase is determined\n");
printf(" EEE and the duration of the ON phase. If ON phase is longer than EEE,\n");
printf(" there is no OFF phase. Otherwise, the duration of the OFF phase is\n");
printf(" EEE - duration of the ON phase.\n");
printf("\n");
#if 0
printf("EXAMPLES\n");
printf("sudo ./trafficGen --role=receiver --active --passive-ip=130.149.49.253 --passive-port=54321 --dev-name=wlan0 --trace-duration=60 --log-dir=. --tcp-info-log-interval=1000\n");
printf(" Generates a continuous TCP flow with duration 60 seconds.\n");
printf("\n");
printf("sudo ./trafficGen --role=receiver --active --passive-ip=130.149.49.253 --passive-port=54321 --dev-name=wlan0 --trace-duration=60 --log-dir=. --tcp-info-log-interval=1000 --request-pattern=normal:1600:400:1200:2400:2000\n");
printf(" Generates a TCP flow with deterministic ON/OFF pattern, with total duration of 60 seconds.\n");
printf("\n");
printf("sudo ./trafficGen --role=receiver --active --passive-ip=130.149.49.253 --passive-port=54321 --dev-name=wlan0 --trace-duration=60 --log-dir=. --tcp-info-log-interval=1000 --request-pattern=deterministic:1600:400\n");
printf(" Generates a TCP flow with normally distributed ON duration, with total duration of 60 seconds.\n");
printf("\n");
#endif
exit(1);
}
void parseInputArguments(int argc, char** argv)
{
enum {HELP='0', ROLE='a', IS_ACTIVE='b', IS_PERMANENT='c', PASSIVE_IP='d', PASSIVE_PORT='e', ACTIVE_IP='f', DEV_NAME='g',
TRACE_DURATION='h', LOG_DIR='i', TCP_INFO_LOG_INTERVAL='j', REQUEST_PATTERN='k', DEV_NAME_MON='l', MAX_THRPT='m', MAX_THRPT_DURATION='n',
DEV_WAIT_MAX='o'};
while(true)
{
static struct option long_options[] =
{
{"help", no_argument, 0, HELP},
{"role", required_argument, 0, ROLE},
{"active", no_argument, 0, IS_ACTIVE},
{"permanent", no_argument, 0, IS_PERMANENT},
{"passive-ip", required_argument, 0, PASSIVE_IP},
{"passive-port", required_argument, 0, PASSIVE_PORT},
{"active-ip", required_argument, 0, ACTIVE_IP},
{"dev-name", required_argument, 0, DEV_NAME},
{"dev-wait-max", required_argument, 0, DEV_WAIT_MAX},
{"dev-name-mon", required_argument, 0, DEV_NAME_MON},
{"trace-duration", required_argument, 0, TRACE_DURATION},
{"max-thrpt", required_argument, 0, MAX_THRPT},
{"max-thrpt-duration", required_argument, 0, MAX_THRPT_DURATION},
{"log-dir", required_argument, 0, LOG_DIR},
{"tcp-info-log-interval", required_argument, 0, TCP_INFO_LOG_INTERVAL},
{"request-pattern", required_argument, 0, REQUEST_PATTERN},
{0, 0, 0, 0}
};
int c = getopt_long (argc, argv, "", long_options, NULL);
if (c == -1) break;
switch(c)
{
case HELP:
printUsageAndExit(__LINE__);
break;
case ROLE:
if(global_info.senderReceiver != global_info.UNDEF) printUsageAndExit(__LINE__);
if(strcmp(optarg, "sender") == 0) global_info.senderReceiver = global_info.SENDER;
else if(strcmp(optarg, "receiver") == 0) global_info.senderReceiver = global_info.RECEIVER;
else printUsageAndExit(__LINE__);
sprintf(buf, "role %s\n", optarg);
config.append(buf);
break;
case IS_ACTIVE:
global_info.ifActive = true;
sprintf(buf, "active 1\n");
config.append(buf);
break;
case IS_PERMANENT:
sender_info.permanent = true;
sprintf(buf, "permanent 1\n");
config.append(buf);
break;
case PASSIVE_IP:
if(!global_info.psvIp.empty()) printUsageAndExit(__LINE__);
global_info.psvIp = optarg;
sprintf(buf, "passive_ip %s\n", global_info.psvIp.c_str());
config.append(buf);
break;
case PASSIVE_PORT:
{
if(global_info.psvPort != 0) printUsageAndExit(__LINE__);
char* endptr = NULL;
global_info.psvPort = strtol(optarg, &endptr, 10);
if(*endptr != '\0') printUsageAndExit(__LINE__);
sprintf(buf, "passive_port %" PRIu16 "\n", global_info.psvPort);
config.append(buf);
break;
}
case ACTIVE_IP:
if(!global_info.actIp.empty()) printUsageAndExit(__LINE__);
global_info.actIp = optarg;
sprintf(buf, "active_ip %s\n", global_info.actIp.c_str());
config.append(buf);
break;
case DEV_NAME:
if(!rcv_info.dev_name.empty()) printUsageAndExit(__LINE__);
rcv_info.dev_name = optarg;
sprintf(buf, "dev_name %s\n", rcv_info.dev_name.c_str());
config.append(buf);
break;
case DEV_WAIT_MAX:
{
if(rcv_info.dev_wait_max != -1) printUsageAndExit(__LINE__);
char* endptr = NULL;
rcv_info.dev_wait_max = 1e6 * strtod(optarg, &endptr);
if(*endptr != '\0') printUsageAndExit(__LINE__);
sprintf(buf, "dev_wait_max %.3f\n", rcv_info.dev_wait_max / 1e6);
config.append(buf);
break;
}
case DEV_NAME_MON:
if(!rcv_info.dev_name_mon.empty()) printUsageAndExit(__LINE__);
rcv_info.dev_name_mon = optarg;
sprintf(buf, "dev_name_mon %s\n", rcv_info.dev_name_mon.c_str());
config.append(buf);
break;
case TRACE_DURATION:
{
if(Tmax != -1) printUsageAndExit(__LINE__);
char* endptr = NULL;
Tmax = (int64_t)1000000 * (int64_t)strtol(optarg, &endptr, 10);
if(*endptr != '\0') printUsageAndExit(__LINE__);
sprintf(buf, "Tmax %" PRId64 "\n", Tmax);
config.append(buf);
break;
}
case MAX_THRPT:
{
if(rcv_info.max_thrpt != -1) printUsageAndExit(__LINE__);
char* endptr = NULL;
rcv_info.max_thrpt = 1e6 * strtod(optarg, &endptr);
if(*endptr != '\0') printUsageAndExit(__LINE__);
sprintf(buf, "max_thrpt %.3f\n", rcv_info.max_thrpt);
config.append(buf);
break;
}
case MAX_THRPT_DURATION:
{
if(rcv_info.max_thrpt_duration != -1) printUsageAndExit(__LINE__);
char* endptr = NULL;
rcv_info.max_thrpt_duration = 1e6 * strtod(optarg, &endptr);
if(*endptr != '\0') printUsageAndExit(__LINE__);
sprintf(buf, "max_thrpt_duration %" PRId64 "\n", rcv_info.max_thrpt_duration);
config.append(buf);
break;
}
case LOG_DIR:
traceDir = optarg;
sprintf(buf, "log_dir %s\n", traceDir.c_str());
config.append(buf);
break;
case TCP_INFO_LOG_INTERVAL:
{
char* endptr = NULL;
global_info.tcp_info_log_interval = (int64_t)1000 * (int64_t)strtol(optarg, &endptr, 10);
if(*endptr != '\0') printUsageAndExit(__LINE__);
sprintf(buf, "tcp_info_log_interval %" PRId64 "\n", global_info.tcp_info_log_interval);
config.append(buf);
break;
}
case REQUEST_PATTERN:
if(!rcv_info.request_pattern.empty()) printUsageAndExit(__LINE__);
parse_request_pattern(optarg);
sprintf(buf, "request_pattern %s\n", optarg);
config.append(buf);
break;
default:
printUsageAndExit(__LINE__);
}
}
/* Input arguments consistency check */
// if(global_info.psvIp.empty() || 49152 > global_info.psvPort || global_info.psvPort > 65535) printUsageAndExit(__LINE__);
if(global_info.psvIp.empty()) printUsageAndExit(__LINE__);
if(global_info.ifActive && sender_info.permanent) printUsageAndExit(__LINE__);
if(global_info.psvIp.empty() || global_info.psvPort == 0) printUsageAndExit(__LINE__);
if(!rcv_info.dev_name.empty() && !(global_info.ifActive && global_info.actIp.empty())) printUsageAndExit(__LINE__);
if((Tmax == -1 && global_info.ifActive) || (Tmax != -1 && !global_info.ifActive)) printUsageAndExit(__LINE__);
if(!rcv_info.request_pattern.empty() && global_info.senderReceiver == global_info.SENDER) printUsageAndExit(__LINE__);
if((rcv_info.max_thrpt != -1 && rcv_info.max_thrpt_duration == -1) || (rcv_info.max_thrpt == -1 && rcv_info.max_thrpt_duration != -1) || (rcv_info.max_thrpt != -1 && global_info.senderReceiver == global_info.SENDER)) printUsageAndExit(__LINE__);
if(global_info.senderReceiver == global_info.SENDER && rcv_info.dev_wait_max != -1) printUsageAndExit(__LINE__);
}
void* runSender(void* _args)
{
int _fd = -1;
int fd = -1;
if(global_info.ifActive)
{
fd = socket(AF_INET, SOCK_STREAM, 0);
assert(-1 != fd);
if(!global_info.actIp.empty())
{
struct sockaddr_in sockaddr_src;
memset(&sockaddr_src, 0, sizeof(sockaddr_src));
sockaddr_src.sin_family = AF_INET;
sockaddr_src.sin_addr.s_addr = inet_addr(global_info.actIp.c_str());
assert(0 == bind(fd, (struct sockaddr*)&sockaddr_src, sizeof(struct sockaddr_in)));
}
struct sockaddr_in sockaddr;
sockaddr.sin_family = AF_INET;
sockaddr.sin_addr.s_addr = inet_addr(global_info.psvIp.c_str());
sockaddr.sin_port = htons(global_info.psvPort);
assert(-1 != connect(fd, (struct sockaddr*)&sockaddr, sizeof(struct sockaddr_in)));
}
/* passive sender */
else
{
_fd = socket(AF_INET, SOCK_STREAM, 0);
assert(-1 != _fd);
if(sender_info.permanent) {
int optval = 1;
setsockopt(_fd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
}
fprintf(sender_info.f_sender_log, "%s Binding to %s:%u.\n", getTimeString(0, true).c_str(), global_info.psvIp.c_str(), global_info.psvPort);
struct sockaddr_in sockaddr;
sockaddr.sin_family = AF_INET;
sockaddr.sin_addr.s_addr = inet_addr(global_info.psvIp.c_str());
sockaddr.sin_port = htons(global_info.psvPort);
assert(0 == bind(_fd, (struct sockaddr*)&sockaddr, sizeof(struct sockaddr_in)));
assert(0 == listen(_fd, 0));
/* waiting for incoming connections */
while(!globalTerminationFlag && fd == -1)
{
fd_set readfds;
FD_ZERO(&readfds);
FD_SET(_fd, &readfds);
struct timeval to;
to.tv_sec = 1;
to.tv_usec = 0;
int ret = select(_fd + 1, &readfds, NULL, NULL, &to);
if(ret < 0)
{
perror("select()");
abort();
}
else if(ret == 0)
{
continue;
}
else if(ret == 1)
{
struct sockaddr_in activeSockaddr;
unsigned senderSockaddrLength = sizeof(struct sockaddr_in);
fd = accept(_fd, (struct sockaddr*)&activeSockaddr, &senderSockaddrLength);
assert(fd > 0 && senderSockaddrLength == sizeof(struct sockaddr_in));
fprintf(sender_info.f_sender_log, "%s Got incoming connection from %s:%d.\n", getTimeString(0, true).c_str(), inet_ntoa(activeSockaddr.sin_addr), ntohs(activeSockaddr.sin_port));
}
else
{
abort();
}
}
if(globalTerminationFlag){
assert(0 == close(_fd));
if(fd != -1)
assert(0 == close(fd));
return NULL;
}
if(_fd != -1) assert(0 == close(_fd));
}
assert(fd != -1);
t_start_sender = now();
fprintf(sender_info.f_sender_log, "%s Starting sender %" PRId64 ".\n", getTimeString(0, true).c_str(), t_start_sender);
// adjust sending buffer size
//assert(0 == setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &sndbufsize, sizeof(sndbufsize)));
/* disable Nagle */
//const int disable_nagle = 1;
//assert(0 == setsockopt(fd, SOL_TCP, TCP_NODELAY, &disable_nagle, sizeof(disable_nagle)));
// log sending buffer size
{
int dummy_int = 0;
unsigned dummy_int_size = sizeof(dummy_int);
assert(0 == getsockopt(fd, SOL_SOCKET, SO_SNDBUF, (void*)&dummy_int, &dummy_int_size));
sprintf(buf, "%s/snd_config_%016" PRId64 ".txt", traceDir.c_str(), t_start_sender);
FILE* f = fopen(buf, "w");
sprintf(buf, "SO_SNDBUF %d\n", dummy_int);
fprintf(f, "%s", buf);
fclose(f);
}
/* open file for logging */
char logFileName[2048];
sprintf(logFileName, "%s/snd_tcpinfo_log_%016" PRId64 ".txt", traceDir.c_str(), t_start_sender);
FILE* logFile = fopen(logFileName, "w");
assert(logFile);
/* starting logger thread */
tcp_logger_info.fd = fd;
tcp_logger_info.logFile = logFile;
terminate_tcp_logger = false;
pthread_t loggerThread;
if(global_info.tcp_info_log_interval > 0)
assert(0 == pthread_create(&loggerThread, NULL, &runTcpStateLogger, NULL));
do // while not hang up
{
/* if passive, read Tmax from the active peer */
if(!global_info.ifActive)
{
fd_set readfds;
FD_ZERO(&readfds);
FD_SET(fd, &readfds);
struct timeval to;
to.tv_sec = 1;
to.tv_usec = 0;
int ret = select(fd + 1, &readfds, NULL, NULL, &to);
if(ret < 0) {
perror("select()");
throw std::runtime_error("Error in select() 1.\n");
} else if(ret == 0) {
sender_info.hang_up = false;
continue;
} else if(ret > 1) {
throw std::runtime_error("Error in select() 2.\n");
}
assert(FD_ISSET(fd, &readfds));
Rcv2Snd_Params rcv2snd_params;
int br = read(fd, &rcv2snd_params, sizeof(rcv2snd_params));
assert(br >= 0);
if(br == 0) {
printf("%s ERROR: Connection %" PRId64 " reset by peer.\n", getTimeString(0, true).c_str(), t_start_sender);
fprintf(sender_info.f_sender_log, "%s ERROR: Connection %" PRId64 " reset by peer.\n", getTimeString(0, true).c_str(), t_start_sender);
break;
} else {
assert(br == sizeof(rcv2snd_params));
}
rcv2snd_params.limitValue = ntohl(rcv2snd_params.limitValue);
sender_info.hang_up = rcv2snd_params.hang_up;
if(rcv2snd_params.limitType == 0) {
Tmax = (int64_t)rcv2snd_params.limitValue * 1000;
fprintf(sender_info.f_sender_log, "%s Will send data for AT LEAST %.3f seconds and %shang up.\n", getTimeString(0, true).c_str(), Tmax / 1e6, sender_info.hang_up ? "" : "NOT ");
} else {
throw std::runtime_error("only supporting time for the moment.");
}
}
int64_t bytesSent = 0;
int64_t bufSend[sndbufsize >> 3];
memset(bufSend, 0, sizeof(int64_t));
int64_t Tstart = now();
int64_t chunk_size = sndbufsize; // [byte]
double nextInfoOutput = Tmax >= 100000000 ? 0.01 : (Tmax >= 5000000 ? 0.1 : 2.0); // never output for short requests
//int cnt_write = 0;
//boost::circular_buffer<int64_t> chunk_times(10);
//boost::circular_buffer<int64_t> chunk_sizes(10);
//boost::circular_buffer<double> chunk_thrpts(10);
//for(int i = 0; i < chunk_times.size(); ++i) {chunk_times.push_back(100000); chunk_sizes.push_back(65536); chunk_thrpts.push_back((8.0 * chunk_sizes.at(i)) / (chunk_times.at(i) / 1e6));}
while(!globalTerminationFlag)
{
//int value = -1;
//assert(0 == ioctl(fd, TIOCOUTQ, &value) && value != -1);
//printf("Still have %d bytes to send.\n", value);
/* send next portion of data */
//for(int64_t i = 0; i < (chunk_size >> 3); ++i)
// bufSend[i] = bytesSent + 8 * (i + 1);
if(global_info.tcp_info_log_interval == 0) recordTcpState(fd, "before write", logFile);
int64_t tic_write = now();
int ret = write(fd, bufSend, chunk_size);
//printf("After write. ret: %d\n", ret);
//++cnt_write;
int64_t toc_write = now();
if(ret == -1 && errno == ECONNRESET) {
perror("write()");
printf("ERROR: Connection %" PRId64 " reset by peer while sending data.\n", t_start_sender);
fprintf(sender_info.f_sender_log, "%s ERROR: Connection %" PRId64 " reset by peer while sending data.\n", getTimeString(0, true).c_str(), t_start_sender);
sender_info.hang_up = true;
break;
} else if(ret == -1){
perror("write()");
static char buf[2048];
sprintf(buf, "Could not write %" PRId64 " bytes to socket.\n", chunk_size);
throw std::runtime_error(buf);
}
assert(ret >= 0);
bytesSent += ret;
if(global_info.tcp_info_log_interval == 0) recordTcpState(fd, "after write", logFile);
if(ret != chunk_size) {
printf("ERROR: Could not complete writing chunk to socket. Potential reason: connection %" PRId64 " reset by peer while sending data.\n", t_start_sender);
fprintf(sender_info.f_sender_log, "%s ERROR: Could not complete writing chunk to socket. Potential reason: connection %" PRId64 " reset by peer while sending data.\n",
getTimeString(0, true).c_str(), t_start_sender);
sender_info.hang_up = true;
break;
}
assert(ret == chunk_size);
const int64_t t = now();
if(t - Tstart >= Tmax - tcp_logger_info.lastTcpInfo.tcpi_rtt / 2)
{
//printf("%d writes, %.0f writes per sec., %.0f ms inter-write time.\n", cnt_write, cnt_write / ((t - Tstart) / 1e6), ((t - Tstart) / 1e3) / cnt_write);
//cnt_write = 0;
printf("Request completed: %6.3f seconds.\n", (t - Tstart) / 1e6);
fprintf(sender_info.f_sender_log, "%s Tmax (%d sec) expired. Sender: %" PRId64 ".\n", getTimeString(0, true).c_str(), (int)(Tmax / 1000000), t_start_sender);
if(global_info.tcp_info_log_interval == 0) recordTcpState(fd, "before write", logFile);
uint8_t _tmp = 1;
int ret = write(fd, (void*)&_tmp, 1);
if(ret == -1 && errno == ECONNRESET) {
perror("write()");
printf("ERROR: Connection %" PRId64 " reset by peer while finalizing request.\n", t_start_sender);
fprintf(sender_info.f_sender_log, "%s ERROR: Connection %" PRId64 " reset by peer while finalizing request.\n", getTimeString(0, true).c_str(), t_start_sender);
sender_info.hang_up = true;
break;
} else if(ret == -1){
perror("write()");
static char buf[2048];
sprintf(buf, "Could not write %u bytes to socket.\n", (unsigned)sizeof(_tmp));
throw std::runtime_error(buf);
} else {
assert(ret == sizeof(_tmp));
//printf("Sent %d bytes.\n", ret);
}
if(global_info.tcp_info_log_interval == 0) recordTcpState(fd, "after write", logFile);
break;
} else if((double)(t - Tstart) / (double)Tmax >= nextInfoOutput) {
nextInfoOutput += Tmax >= 100000000 ? 0.01 : 0.1;
printf("Progress: %6.2f%%.\n", 100.0 * (double)(t - Tstart) / (double)Tmax);
}
// determine chunk size
//chunk_times.push_back(toc_write - tic_write);
//chunk_sizes.push_back(chunk_size);
//chunk_thrpts.push_back((8.0 * chunk_sizes.back()) / (chunk_times.back() / 1e6));
//double chunk_thrpt = std::accumulate(chunk_sizes.begin(), chunk_sizes.end(), 0.0) / (std::accumulate(chunk_times.begin(), chunk_times.end(), 0.0) / 1e6); // [byte/sec]
//for(int i = 0; i < chunk_times.size(); ++i) chunk_thrpt += 1.0 / chunk_times.size() * chunk_sizes.at(i) / ((double)chunk_times.at(i) / 1e6);
//const int64_t chunk_size_old = chunk_size;
//chunk_size = 0.05 / 8.0 * *std::min_element(chunk_thrpts.begin(), chunk_thrpts.end()); // number of byte to be send in approximately 100 ms
//chunk_size = std::min<int64_t>(chunk_size, 65536);
//chunk_size = std::max<int64_t>(chunk_size, 8192);
//chunk_size = sndbufsize;
//printf("old chunk_size: %5" PRId64 ", duration: %8.6f, new chunk_size: %5" PRId64 "\n", chunk_size_old, (toc_write - tic_write) / 1e6, chunk_size);
}
} while(!sender_info.hang_up);
terminate_tcp_logger = true;
if(global_info.tcp_info_log_interval > 0)
assert(0 == pthread_join(loggerThread, NULL));
/* close log file */
assert(0 == fclose(logFile));
/* shutdown connection and close sockets */
shutdown(fd, SHUT_RDWR); // intentionally don't check return value
assert(0 == close(fd));
//if(_fd != -1) assert(0 == close(_fd));
fprintf(sender_info.f_sender_log, "%s All sockets closed.\n", getTimeString(0, true).c_str());
/* write parameters to file */
{
sprintf(buf, "%s/snd_config_%016" PRId64 ".txt", traceDir.c_str(), t_start_sender);
FILE* f = fopen(buf, "w");
fprintf(f, "%s", config.c_str());
fclose(f);
}
return NULL;
}
void* runReceiver(void* _args)
{
#ifndef __SENDER
int _fd = -1;
int fd = -1;
if(global_info.ifActive)
{
/* wait for device to become available */
if(!rcv_info.dev_name.empty() && rcv_info.dev_wait_max > 0 && !wait_for_dev(rcv_info.dev_name, rcv_info.dev_wait_max))
return NULL;
/* create socket */
fd = socket(AF_INET, SOCK_STREAM, 0);
assert(-1 != fd);
/* bind to specified network interface or IP if requested */
if(!global_info.actIp.empty() || !rcv_info.dev_name.empty())
{
if(rcv_info.dev_name.empty())
rcv_info.dev_name = get_dev_for_ip(global_info.actIp);
if(global_info.actIp.empty()) {
global_info.actIp = get_ip_for_dev(rcv_info.dev_name);
printf("Determined %s as IP address of %s.\n", global_info.actIp.c_str(), rcv_info.dev_name.c_str());
}
struct sockaddr_in sockaddr_src;
memset(&sockaddr_src, 0, sizeof(sockaddr_src));
sockaddr_src.sin_family = AF_INET;
sockaddr_src.sin_addr.s_addr = inet_addr(global_info.actIp.c_str());
assert(0 == bind(fd, (struct sockaddr*)&sockaddr_src, sizeof(struct sockaddr_in)));
printf("Bound to specified active IP.\n");
}
/* connect */
struct sockaddr_in sockaddr;
sockaddr.sin_family = AF_INET;
sockaddr.sin_addr.s_addr = inet_addr(global_info.psvIp.c_str());
sockaddr.sin_port = htons(global_info.psvPort);
assert(-1 != connect(fd, (struct sockaddr*)&sockaddr, sizeof(struct sockaddr_in)));
printf("Connected.\n");
}
else
{
_fd = socket(AF_INET, SOCK_STREAM, 0);
assert(-1 != _fd);
printf("Binding to %s:%u.\n", global_info.psvIp.c_str(), global_info.psvPort);
struct sockaddr_in sockaddr;
sockaddr.sin_family = AF_INET;
sockaddr.sin_addr.s_addr = inet_addr(global_info.psvIp.c_str());
sockaddr.sin_port = htons(global_info.psvPort);
assert(0 == bind(_fd, (struct sockaddr*)&sockaddr, sizeof(struct sockaddr_in)));
assert(0 == listen(_fd, 0));
printf("Ready and listening for incoming connections.\n");
while(!globalTerminationFlag && fd == -1)
{
fd_set readfds;
FD_ZERO(&readfds);
FD_SET(_fd, &readfds);
struct timeval to;
to.tv_sec = 1;
to.tv_usec = 0;
int ret = select(_fd + 1, &readfds, NULL, NULL, &to);
if(ret < 0)
{
perror("select()");
abort();
}
else if(ret == 0)
{
continue;
}
else if(ret == 1)
{
struct sockaddr_in activeSockaddr;
unsigned senderSockaddrLength = sizeof(struct sockaddr_in);
fd = accept(_fd, (struct sockaddr*)&activeSockaddr, &senderSockaddrLength);
assert(fd > 0 && senderSockaddrLength == sizeof(struct sockaddr_in));
printf("Got incoming connection from %s:%d.\n", inet_ntoa(activeSockaddr.sin_addr), ntohs(activeSockaddr.sin_port));
}
else
{
abort();
}
}
if(globalTerminationFlag){
assert(0 == close(_fd));
if(fd != -1)
assert(0 == close(fd));
return NULL;
}
}
assert(fd != -1);
// adjust receiving buffer size
//assert(0 == setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &rcvbufsize, sizeof(rcvbufsize)));
// log receiving buffer size
int dummy_int = 0;
unsigned dummy_int_size = sizeof(dummy_int);
assert(0 == getsockopt(fd, SOL_SOCKET, SO_RCVBUF, (void*)&dummy_int, &dummy_int_size));
sprintf(buf, "SO_RCVBUF %d\n", dummy_int);
config.append(buf);
t_start_receiver = now();
/* initialize pcap sniffer and radiotap monitor */
pthread_t snifferThread, radiotapThread;
if(!rcv_info.dev_name.empty())
assert(0 == pthread_create(&snifferThread, NULL, &runSniffer, NULL));
if(!rcv_info.dev_name_mon.empty())
assert(0 == pthread_create(&radiotapThread, NULL, &runRadiotap, NULL));
sleep(2); // give the sniffers some time to initialize
/* open file for logging */
char logFileName[4096];
sprintf(logFileName, "%s/rcv_tcpinfo_log_%016" PRId64 ".txt", traceDir.c_str(), t_start_receiver);
tcp_logger_info.logFile = fopen(logFileName, "w");
assert(tcp_logger_info.logFile);
/* start logger thread */
tcp_logger_info.fd = fd;
pthread_t loggerThread;
if(global_info.tcp_info_log_interval > 0)
assert(0 == pthread_create(&loggerThread, NULL, &runTcpStateLogger, NULL));
/* open file for request logging */
char fn_request_log[4096];
sprintf(fn_request_log, "%s/rcv_request_log_%016" PRId64 ".txt", traceDir.c_str(), t_start_receiver);
rcv_info.file_request_log = fopen(fn_request_log, "w");
assert(rcv_info.file_request_log);
fprintf(rcv_info.file_request_log, "| request_sent | first_data_received | last_data_received | request_size | scheduled_on_duration |\n");
/* loop over requests */
bool log_to_console = true;
while(!globalTerminationFlag)
{
/* if active, send request parameters */
if(global_info.ifActive)
{
const int64_t _now = now();
rcv_info.request_sent = _now;
rcv_info.first_data_received = 0;
assert(Tmax > 0);
if(rcv_info.request_pattern.empty())
{
rcv_info.scheduled_on_duration = Tmax;
Rcv2Snd_Params rcv2snd_params;
rcv2snd_params.limitType = 0;
rcv2snd_params.limitValue = htonl((uint32_t)(rcv_info.scheduled_on_duration / 1000));
rcv2snd_params.hang_up = true;
assert(sizeof(rcv2snd_params) == write(fd, &rcv2snd_params, sizeof(rcv2snd_params)));
}
else if(rcv_info.request_pattern_type == rcv_info.DETERMINISTIC)
{
rcv_info.scheduled_on_duration = rcv_info.request_pattern_deterministic.on_duration;