-
Notifications
You must be signed in to change notification settings - Fork 0
/
mptest_fairness.cc
1326 lines (1135 loc) · 43.7 KB
/
mptest_fairness.cc
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
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* NaturalShare policy, test Mbox with 2 senders & 1 receiver
* MP policy realized in pktArrival of right router
*/
#include <fstream>
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/internet-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/applications-module.h"
//packet tag head files
#include "ns3/tag.h"
#include "ns3/packet.h"
#include "ns3/uinteger.h"
//head files
#include "ns3/point-to-point-layout-module.h"
#include "ns3/rtt-estimator.h"
#include "ns3/nstime.h"
#include "ns3/flow-monitor-helper.h"
#include "ns3/random-variable-stream.h"
#include "ns3/udp-socket-factory.h"
#include "ns3/tcp-socket-factory.h"
#include "ns3/ipv4-flow-classifier.h"
#include "ns3/traffic-control-module.h"
#include "ns3/point-to-point-net-device.h"
#include "ns3/tools.h"
#include <iostream>
#include <iomanip>
#include <vector>
#include <map>
#include <fstream>
#include <cstdio>
#include <ctime>
#include <locale>
#include <time.h>
#include <stdlib.h>
using namespace std;
using namespace ns3;
/*
* Gloable Variable
*/
#define ARRAY_SIZE 1000
std::string attackerDataRate = "4Mbps"; // currently no use, but keep for compatibility
std::string clientDataRate = "1Mbps";
double period = 0.5; // will it influence the cwnd / rwnd value?
double duration = period / 1;
double moment = 0;
uint16_t port = 5001;
uint16_t attackerport = 5003;
uint16_t mmtu = 1599;
std::ofstream queueFile ("queueLength.dat", std::ios::out);
//std::ofstream congestionUsageFile ("congestionUsage.dat", std::ios::out);
//std::ofstream normalUsageFile ("normalUsage.dat", std::ios::out);
std::ofstream droprateFile ("dropRate.dat", std::ios::out);
//std::ofstream rawdropFile ("rawDropRate.dat", std::ios::out);
Ptr<Node> router;
Ptr<PointToPointNetDevice> p2pDevice;
// uint32_t nLeaf = 4;
// uint32_t nAttacker = 4;
// int size = nLeaf + nAttacker;
uint32_t nLeft = 4; // # receiver
uint32_t nRight = 4; // # senders
uint32_t nAttacker = 2;
double detectPeriod = 0.0;
uint32_t lock = 0;
uint32_t dropArray[ARRAY_SIZE];
//uint32_t dropTag[5000];
uint32_t congWin[ARRAY_SIZE];
//uint32_t verifyWin[5000]; // representing the verified capabilities
//uint32_t tagWin[5000]; // representing the tagged packets
uint32_t receiveWin[ARRAY_SIZE]; // representing the received packets (usage) /// rwnd: RX's largest # packets it can receive without ACK, actual # packets = min (rwnd, cwnd)
uint16_t enableEarlyDrop = 1;
uint32_t bootStrap = 0;
// Used for measuring real time loss rate
uint32_t realtimePeriod = 0;
uint32_t realtimePacketFeedback = 50;
double realtimeLossRate = 0;
uint32_t realtimeDrop = 0;
double lossRateArray[ARRAY_SIZE];
// Used for crossing traffic
uint32_t nCrossing = 0;
// parameters
double lossRateThreshold = 0.05;
double beta = 0.8;
// for fairshare
double total_capacity = 0;
// for RTT record
// vector< vector<double> > rtt;
vector<string> fileName;
string qFileName;
double tPkt[ARRAY_SIZE];
int txCnt[ARRAY_SIZE];
int rxCnt[ARRAY_SIZE];
double recvData[ARRAY_SIZE]; // record tcp data for rate calculation
double recvBit[ARRAY_SIZE]; // record p2p packet size
bool isPrintHeader;
bool isPrintTx;
bool isPrintLeft;
bool isPrintRx;
bool isChangeFair;
bool firstRtt = true;
bool isTcp;
string fairness;
// log component definition
NS_LOG_COMPONENT_DEFINE ("TestForMiddlePolice");
// for recording the congestion window
std::ofstream windowFile ("natural_flat_window.data", std::ios::out);
std::ofstream lossRateFile ("natural_flat_LR.data", std::ios::out);
// tool function
// vector<int> getPktSizes(Ptr <const Packet> p) // get [p2p size, ip size, tcp size, data size]
// {
// Ptr<Packet> pktCopy = p->Copy();
// vector<int> res;
// PppHeader pppH;
// Ipv4Header ipH;
// TcpHeader tcpH;
// res.push_back((int)pktCopy->GetSize());
// pktCopy->RemoveHeader(pppH);
// res.push_back((int)pktCopy->GetSize());
// pktCopy->RemoveHeader(ipH);
// res.push_back((int)pktCopy->GetSize());
// pktCopy->RemoveHeader(tcpH);
// res.push_back((int)pktCopy->GetSize());
// return res;
// }
// uint32_t getTcpSize(Ptr <const Packet> p)
// {
// Ptr<Packet> pktCopy = p->Copy();
// PppHeader pppH;
// Ipv4Header ipH;
// TcpHeader tcpH;
// pktCopy->RemoveHeader(pppH);
// pktCopy->RemoveHeader(ipH);
// pktCopy->RemoveHeader(tcpH);
// return pktCopy->GetSize();
// }
// string
// printPkt(Ptr <const Packet> p)
// {
// Ptr<Packet> pktCopy = p->Copy();
// stringstream ss;
// pktCopy->Print(ss);
// return ss.str();
// }
// string
// logIpv4Header (Ptr<const Packet> p)
// {
// Ptr<Packet> pktCopy = p->Copy ();
// PppHeader pppH;
// Ipv4Header ipH;
// pktCopy->RemoveHeader (pppH);
// pktCopy->PeekHeader (ipH); /// need to know the exact structure of header
// stringstream ss;
// ipH.Print (ss);
// return ss.str ();
// }
// string
// logPppHeader (Ptr<const Packet> p)
// {
// Ptr<Packet> pktCopy = p->Copy ();
// PppHeader pppH;
// pktCopy->PeekHeader (pppH);
// stringstream ss;
// pppH.Print (ss);
// return ss.str ();
// }
// string
// logTcpHeader (Ptr<const Packet> p)
// {
// Ptr<Packet> pktCopy = p->Copy ();
// PppHeader pppH;
// Ipv4Header ipH;
// TcpHeader tcpH;
// pktCopy->RemoveHeader (pppH);
// pktCopy->RemoveHeader (ipH);
// pktCopy->PeekHeader (tcpH);
// stringstream ss;
// tcpH.Print (ss);
// return ss.str ();
// }
// string
// logPktIpv4Address (Ptr<const Packet> p)
// {
// Ptr<Packet> pktCopy = p->Copy ();
// PppHeader pppH;
// Ipv4Header ipH;
// pktCopy->RemoveHeader (pppH);
// pktCopy->PeekHeader (ipH);
// stringstream ss;
// ipH.GetSource ().Print (ss);
// ss << " > ";
// ipH.GetDestination ().Print (ss);
// return ss.str ();
// }
//=========================================================================//
//=========================Begin of TAG definition=========================//
//=========================================================================//
class MyTag : public Tag
{
public:
static TypeId GetTypeId (void);
virtual TypeId GetInstanceTypeId (void) const;
virtual uint32_t GetSerializedSize (void) const;
virtual void Serialize (TagBuffer i) const;
virtual void Deserialize (TagBuffer i);
virtual void Print (std::ostream &os) const;
// these are our accessors to our tag structure
void SetSimpleValue (uint32_t value);
uint32_t GetSimpleValue (void) const;
private:
uint32_t m_simpleValue;
};
TypeId
MyTag::GetTypeId (void)
{
static TypeId tid = TypeId ("ns3::MyTag")
.SetParent<Tag> ()
.AddConstructor<MyTag> ()
.AddAttribute ("SimpleValue", "A simple value", EmptyAttributeValue (),
MakeUintegerAccessor (&MyTag::GetSimpleValue),
MakeUintegerChecker<uint32_t> ());
return tid;
}
TypeId
MyTag::GetInstanceTypeId (void) const
{
return GetTypeId ();
}
uint32_t
MyTag::GetSerializedSize (void) const
{
return 4;
}
void
MyTag::Serialize (TagBuffer i) const
{
i.WriteU32 (m_simpleValue);
}
void
MyTag::Deserialize (TagBuffer i)
{
m_simpleValue = i.ReadU32 ();
}
void
MyTag::Print (std::ostream &os) const
{
os << "v=" << (uint32_t) m_simpleValue;
}
void
MyTag::SetSimpleValue (uint32_t value)
{
m_simpleValue = value;
}
uint32_t
MyTag::GetSimpleValue (void) const
{
return m_simpleValue;
}
//=========================================================================//
//===============Beigining of Application definition=======================//
//=========================================================================//
class MyApp : public Application
{
public:
MyApp ();
virtual ~MyApp ();
//void Setup (Ptr<Socket> socket, Address address, uint32_t packetSize, uint32_t nPackets, DataRate dataRate);
void Setup (Ptr<Socket> socket, Address address, uint32_t packetSize, DataRate dataRate);
void SetTagValue (uint32_t value);
void SetDataRate (DataRate rate);
private:
virtual void StartApplication (void);
virtual void StopApplication (void);
void ScheduleTx (void);
void SendPacket (void);
Ptr<Socket> m_socket;
Address m_peer;
uint32_t m_packetSize;
//uint32_t m_nPackets;
DataRate m_dataRate;
EventId m_sendEvent;
bool m_running;
//uint32_t m_packetsSent;
uint32_t m_tagValue;
};
MyApp::MyApp ()
: m_socket (0),
m_peer (),
m_packetSize (0),
//m_nPackets (0),
m_dataRate (0),
m_sendEvent (),
m_running (false),
//m_packetsSent (0)
m_tagValue (0)
{
}
MyApp::~MyApp ()
{
m_socket = 0;
}
void
//MyApp::Setup (Ptr<Socket> socket, Address address, uint32_t packetSize, uint32_t nPackets, DataRate dataRate)
MyApp::Setup (Ptr<Socket> socket, Address address, uint32_t packetSize, DataRate dataRate)
{
m_socket = socket;
m_peer = address;
m_packetSize = packetSize;
//m_nPackets = nPackets;
m_dataRate = dataRate;
}
void
MyApp::SetDataRate (DataRate rate)
{
m_dataRate = rate;
}
void
MyApp::SetTagValue (uint32_t value)
{
m_tagValue = value;
}
void
MyApp::StartApplication (void)
{
m_running = true;
//m_packetsSent = 0;
m_socket->Bind ();
m_socket->Connect (m_peer);
SendPacket ();
}
void
MyApp::StopApplication (void)
{
m_running = false;
if (m_sendEvent.IsRunning ())
{
Simulator::Cancel (m_sendEvent);
}
if (m_socket)
{
m_socket->Close ();
}
}
void
MyApp::SendPacket (void)
{
MyTag tag;
tag.SetSimpleValue (m_tagValue);
Ptr<Packet> packet = Create<Packet> (m_packetSize);
packet->AddPacketTag (tag); //add tags
m_socket->Send (packet);
ScheduleTx ();
txCnt[m_tagValue - 1] ++;
// if(txCnt[m_tagValue - 1] % 500 == 0)
stringstream ss;
ss << "TX: " << Simulator::Now ().GetSeconds () << " s: " << m_tagValue // << ". " << m_cnt - 1
<< " ; total: " << txCnt[m_tagValue - 1];
if (isPrintTx)
NS_LOG_INFO (ss.str ());
//}
}
void
MyApp::ScheduleTx (void)
{
if (m_running)
{
Time tNext (Seconds (m_packetSize * 8 / static_cast<double> (m_dataRate.GetBitRate ())));
// mark the count
m_sendEvent = Simulator::Schedule (tNext, &MyApp::SendPacket, this);
}
}
void attackFlow(PointToPointDumbbellHelper d, uint32_t nAttacker)
{
for (uint32_t i = d.RightCount() - nAttacker; i < d.RightCount(); ++i)
{
Ptr<Socket> ns3Socket = isTcp? Socket::CreateSocket(d.GetRight(i), TcpSocketFactory::GetTypeId())
:Socket::CreateSocket (d.GetRight(i), UdpSocketFactory::GetTypeId ());
Address sinkAddress(InetSocketAddress(d.GetLeftIpv4Address(i), attackerport));
Ptr<MyApp> app = CreateObject<MyApp>();
uint32_t tagValue = i + 1; //take the least significant 8 bits
app->SetTagValue(tagValue);
app->Setup(ns3Socket, sinkAddress, 1000, DataRate(attackerDataRate));
d.GetRight(i)->AddApplication(app);
app->SetStartTime(Seconds(0.0));
// app->SetStopTime(Seconds(duration));
}
}
void
clearArray ()
{
for (uint32_t j = 0; j < nRight; ++j)
{
//std::cout << "client no: " << j << "; arrived: "<< receiveWin[j] << "; drop rate: " << 1.0 * dropArray[j] / receiveWin[j] << std::endl;
receiveWin[j] = 0;
dropArray[j] = 0;
recvData[j] = 0.0;
recvBit[j] = 0.0;
rxCnt[j] = 0;
}
total_capacity = 0;
}
// the sloping probability for best effort packets
bool
slopingProb (double lossRate)
{
if (lossRate > lossRateThreshold)
{
return true;
}
else
{
double dropP = 20.0 * lossRate;
double randP = (double) rand () / RAND_MAX;
if (dropP <= randP)
{
return true;
}
}
return false;
}
int rxTagCnt = 0;
static void
PktArrival (Ptr<const Packet> p)
{
Ptr<Packet> pktCopy = p->Copy ();
MyTag tag;
// printHeader(p);
vector<int> tmp = getPktSizes(p, isTcp? TCP:UDP);
// vector<int> tmp{500,500,500,500};
// printPkt(pktCopy);
// functionality: switch the fairness
if(isChangeFair)
if(floor(Simulator::Now().GetSeconds()) == 50 || floor(Simulator::Now().GetSeconds() == 100) )
{
// fairness = fairness == "persender"? "natural":"persender";
if(fairness == "natural") fairness = "persender";
else fairness = "natural";
cout << "Fairness change!" << endl;
isChangeFair = false;
}
if (pktCopy->PeekPacketTag (tag)) // if find a tag
{
/// logging header/address
// compatible with the setting
uint32_t index = tag.GetSimpleValue () - 1;
rxCnt[index] ++;
receiveWin[index] ++;
double ttemp = Simulator::Now ().GetSeconds ();
stringstream ss;
// if(!index)
ss << "- RX: " << Simulator::Now ().GetSeconds () << " : " << index + 1 << ". " << rxCnt[index]
<< " : rt pkt time = " << ttemp - tPkt[index] << " s "; // tcp size: " << getTcpSize(p);
if (isPrintRx)
NS_LOG_INFO (ss.str () + "; " + logPktIpv4Address (p));
if (isPrintHeader)
// NS_LOG_INFO ("- TCP Header: " + logTcpHeader (p));
NS_LOG_INFO (printPkt(p));
tPkt[index] = ttemp;
if (++realtimePeriod ==
realtimePacketFeedback) // calculating a real-time loss rate every 50 packets
{
realtimeLossRate = (double) realtimeDrop / (double)realtimePeriod;
realtimePeriod = 0;
realtimeDrop = 0;
}
bool tmpDrop = false;
if (enableEarlyDrop > 0)
{
if (receiveWin[index] > congWin[index])
{
// cout << index << " : rwnd = " << receiveWin[index] << " ; cwnd = " << congWin[index] <<
// "; rtLR = " << realtimeLossRate << "; LLR = " << lossRateArray[index] << endl;
if (realtimeLossRate > lossRateThreshold || lossRateArray[index] > lossRateThreshold)
// why this condition: if not, no good put, bw -> 0
{
tmpDrop = true;
// realtimeDrop--; // shouldn't -- after I cancel the MacTxDrop
}
}
}
if(tmpDrop) p2pDevice->SetEarlyDrop (true);
else
{
recvData[index] += (double) tmp[3] / 1000.0; // size in KB
recvBit[index] += (double) tmp[0] / 1000.0; // raw size in KB
}
}
// filename[n] // should defined globally
ofstream fout[nRight];
for (int i = 0; i < nRight; i++)
fout[i].open (fileName[i], ios::out | ios::app);
if (Simulator::Now ().GetSeconds () > detectPeriod)
{
cout << endl
<< Simulator::Now ().GetSeconds () << "s detection period: " << bootStrap++ << endl;
if (windowFile.is_open ())
windowFile << Simulator::Now ().GetSeconds () << " ";
if (lossRateFile.is_open ())
lossRateFile << Simulator::Now ().GetSeconds () << " ";
for (uint32_t j = 0; j < nRight; j++)
{
// loss rate & cwnd update
double lossRate = receiveWin[j] > 0 ? (double) dropArray[j] / receiveWin[j] : 0.0;
lossRateArray[j] = receiveWin[j] > 5 ? (1 - beta) * lossRate + beta * lossRateArray[j]
: beta * lossRateArray[j]; // similar to a time average
total_capacity += receiveWin[j] >= dropArray[j]? receiveWin[j] - dropArray[j] : 0;
}
cout << "total capacity: " << total_capacity << endl;
// rate allocation
for(uint32_t j = 0; j < nRight; ++ j)
{
if(fairness == "natural")
congWin[j] = receiveWin[j] >= dropArray[j]? receiveWin[j] - dropArray[j] : 0;
else if(fairness == "persender")
congWin[j] = total_capacity / nRight;
else ;
// output to file & stdout
if (windowFile.is_open ())
windowFile << congWin[j] << " ";
if (lossRateFile.is_open ())
lossRateFile << lossRateArray[j] << " ";
cout << "Client No." << j << "; cwnd: " << congWin[j]
<< "; loss rate: " << lossRateArray[j] << "; rwnd: " << receiveWin[j]
<< "; drop window: " << dropArray[j] << "; realtime loss: " << realtimeLossRate
<< endl;
// fout[j] << Simulator::Now().GetSeconds() << " " << congWin[j] << endl;
cout << Simulator::Now ().GetSeconds () << ": raw: " << recvBit[j] * 8.0 / period << " kbps"
<< "; data: " << recvData[j] * 8.0 / period << " kbps" << endl;
// cout << " = pkt sizes: " << tmp[0] << " " << tmp[1] << " " << tmp[2] << " " << tmp[3] << endl;
fout[j] << Simulator::Now ().GetSeconds () << " " << recvData[j] * 8.0 / period << " kbps"
<< endl; // output the ephermal data rate (omit pkt size 1kB)
}
if (windowFile.is_open ())
windowFile << endl;
if (lossRateFile.is_open ())
lossRateFile << endl;
detectPeriod += period; // update for next period
clearArray ();
}
// close the file
for (int i = 0; i < nRight; i++)
fout[i].close ();
}
int pktLeft = 0;
int pktTagLeft = 0;
static void
PktArrivalLeft (Ptr<const Packet> p)
{
pktLeft++;
Ptr<Packet> pktCopy = p->Copy ();
MyTag tag;
if (pktCopy->PeekPacketTag (tag)) // if find a tag
{
// compatible with the setting
uint32_t index = tag.GetSimpleValue () - 1;
stringstream ss;
ss << " Left router: " << Simulator::Now ().GetSeconds () << ": " << index + 1
<< ". " // << cnt
<< " ; total(tag): " << ++pktTagLeft << " ; total: " << pktLeft;
if (isPrintLeft)
NS_LOG_INFO (ss.str () + "; " + logPktIpv4Address (p));
if (isPrintHeader)
// NS_LOG_INFO ("- TCP Header: " + logTcpHeader (p));
// NS_LOG_INFO ("- IP header: " + logIpv4Header(p));
NS_LOG_INFO (printPkt(p));
}
}
static void
PktDropLeft (Ptr<const Packet> p)
{
stringstream ss;
ss << " - Left: drop packet!";
NS_LOG_INFO (ss.str ());
}
static void
PktDrop (Ptr<const Packet> p)
{
realtimeDrop += 1;
MyTag tag;
if (p->PeekPacketTag (tag))
dropArray[tag.GetSimpleValue () - 1] += 1;
// if(dropArray[tag.GetSimpleValue() - 1] % 20 == 0)
// cout << Simulator::Now().GetSeconds() << " Drop packet!" << endl;
}
static void
PktDropOverflowLeft (Ptr<const Packet> p)
{
stringstream ss;
ss << " - Left: drop for overflow!" << endl;
NS_LOG_INFO (ss.str ());
}
static void
PktDropOverflow (Ptr<const Packet> p)
{
cout << "Dropping for overflow" << endl;
}
uint32_t cnt2[ARRAY_SIZE] = {0};
static void
QueueChange (uint32_t vOld, uint32_t vNew)
{
stringstream ss;
ss << " " << Simulator::Now().GetSeconds() << "s: Queue #packet changed to " << vNew;
// NS_LOG_INFO (ss.str());
fstream fout;
fout.open(qFileName, ios::out | ios::app);
fout << Simulator::Now().GetSeconds() << " " << vNew << endl; // keep trace for draw the queue size
fout.close();
}
static void
PktEnqueue (Ptr<const Packet> p)
{
stringstream ss;
NS_LOG_INFO (ss.str());
Ptr<Packet> pcp = p->Copy();
MyTag tag;
if(pcp->PeekPacketTag(tag))
{
int idx = tag.GetSimpleValue() - 1;
stringstream ss;
// ss << " " << Simulator::Now().GetSeconds() << "s: Tc Queue drop! " << idx + 1<< ". " << ++ cnt2[idx - 1];
ss << " " << Simulator::Now().GetSeconds() << "s: packet enqueued! node " << idx + 1;
NS_LOG_INFO(ss.str());
}
}
static void
PktDequeue (Ptr<const Packet> p)
{
stringstream ss;
ss << " " << Simulator::Now().GetSeconds() << "s: packet dequeued!";
NS_LOG_INFO (ss.str());
}
static void
QueueDrop (Ptr<const QueueDiscItem> qi)
{
realtimeDrop += 1;
Ptr<Packet> p = qi->GetPacket();
MyTag tag;
if(p->PeekPacketTag(tag))
{
int idx = tag.GetSimpleValue() - 1;
dropArray[idx] += 1;
stringstream ss;
ss << " " << Simulator::Now().GetSeconds() << "s: Tc Queue drop! " << idx + 1<< ". " << ++ cnt2[idx - 1];
// if(cnt2[idx - 1] % 20 == 0)
// NS_LOG_INFO(ss.str());
cout << ss.str() << endl;
}
}
static void
RttTracer (Time oldval, Time newval)
{
stringstream ss;
if (firstRtt)
{
ss << "0.0 " << oldval.GetSeconds () << std::endl;
firstRtt = false;
}
ss << Simulator::Now ().GetSeconds () << " " << newval.GetSeconds () << std::endl;
cout << ss.str() << endl;
}
// following is my test tracing function
int cntn[4][4] = {0};
MyTag tag;
uint32_t idx;
static void
PktMacRx (Ptr<const Packet> p)
{
Ptr<Packet> pktCopy = p->Copy();
if(pktCopy->PeekPacketTag(tag)) idx = tag.GetSimpleValue() - 1;
if(idx == 0)
cout << " " << Simulator::Now().GetSeconds() << "s " << idx + 1 << " : " << cntn[idx][0] ++ <<" : Mac Rx, packet passed up from Phy" << endl;
}
static void
PktPhyTxBegin (Ptr<const Packet> p)
{
Ptr<Packet> pktCopy = p->Copy();
if(pktCopy->PeekPacketTag(tag)) idx = tag.GetSimpleValue() - 1;
if(idx == 0)
cout << idx + 1 << " : " << cntn[idx][1] ++ <<" : Phy Tx Begin" << endl;
}
static void
PktPhyTxEnd (Ptr<const Packet> p)
{
Ptr<Packet> pktCopy = p->Copy();
if(pktCopy->PeekPacketTag(tag)) idx = tag.GetSimpleValue() - 1;
if(idx == 0)
cout << " " << idx + 1 << " : " << cntn[idx][2] ++ <<" : Phy Tx End" << endl;
}
static void
PktPhyRxEnd (Ptr<const Packet> p)
{
Ptr<Packet> pktCopy = p->Copy();
if(pktCopy->PeekPacketTag(tag)) idx = tag.GetSimpleValue() - 1;
if(idx == 0)
cout << " " << idx + 1 << " : " << cntn[idx][3] ++ <<" : Phy Rx End" << endl;
}
static void
PktTxDrop (Ptr<const Packet> p)
{
Ptr<Packet> pktCopy = p->Copy();
if(pktCopy->PeekPacketTag(tag)) idx = tag.GetSimpleValue() - 1;
if(idx == 0)
cout << "==" << idx + 1 << " : " << cntn[idx][3] ++ <<" : Phy Tx Drop!!!" << endl;
}
//===========================Main Function=============================//
int
main (int argc, char *argv[])
{
uint32_t maxPackets = 250;
uint32_t modeBytes = 0;
double minTh = 100;
double maxTh = 200;
uint32_t pktSize = 1000; // 1000 KB
double stopTime = 3;
string pktPrint;
string prot;
isPrintHeader = false; // if print tcp header
isPrintTx = false;
isPrintLeft = false;
isPrintRx = false;
isTcp = true;
isChangeFair = false;
uint32_t maxWinSize = 131070;
fairness = "persender"; // choose from: natural, persender
string appDataRate = "20Mbps"; // no use here
string queueType = "RED";
string bottleNeckLinkBw = "100Mbps";
string bottleNeckLinkDelay = "5ms";
string attackFlowType;
// just copy the original below
std::string mtu = "1599";
// define the file names here
ofstream fout[nRight];
for (int i = 0; i < nRight; i++)
{
fileName.push_back ("wndOutput_" + to_string (i) + ".dat");
remove (fileName[i].c_str ());
}
qFileName = "queue.dat";
remove(qFileName.c_str());
// initialize tPkt
for (int i = 0; i < ARRAY_SIZE; i++)
{
tPkt[i] = 0.0;
txCnt[i] = 0;
rxCnt[i] = 0;
}
//get the local time
std::time_t t = std::time (NULL);
char localTime[100];
std::strftime (localTime, 100, "%c", std::localtime (&t));
CommandLine cmd;
cmd.AddValue ("nLeft", "Number of left side nodes", nLeft);
cmd.AddValue ("enableEarlyDrop", "enableEarlyDrop", enableEarlyDrop);
cmd.AddValue ("attackerDataRate", "attack data rate", attackerDataRate);
cmd.AddValue ("clientDataRate", "legitimate users data rate", clientDataRate);
cmd.AddValue ("bottleNeckLinkDelay", "bottle neck link delay", bottleNeckLinkDelay); /// added
cmd.AddValue ("bottleNeckLinkBw", "bottle neck link bandwidth", bottleNeckLinkBw);
cmd.AddValue ("stopTime", "Stopping time for simulation", stopTime);
cmd.AddValue ("attackFlowType", "Type of attacking flows", attackFlowType);
cmd.AddValue ("nRight", "Number of TCP attacking flows", nRight);
cmd.AddValue ("maxPackets", "Max Packets allowed in the queue", maxPackets);
cmd.AddValue ("queueType", "Set Queue type to DropTail or RED", queueType);
cmd.AddValue ("appDataRate", "Set OnOff App DataRate", appDataRate);
cmd.AddValue ("modeBytes", "Set Queue mode to Packets <0> or bytes <1>", modeBytes);
cmd.AddValue ("nCrossing", "The number of crossing traffic flows", nCrossing);
cmd.AddValue ("enablePacketPrint", "enable printing packet detail in log", pktPrint);
cmd.AddValue ("fairness", "Set the fairness policy of the mbox", fairness);
cmd.AddValue ("protocol", "The protocol of TCP / UDP", prot);
cmd.AddValue ("redMinTh", "RED queue minimum threshold", minTh);
cmd.AddValue ("redMaxTh", "RED queue maximum threshold", maxTh);
cmd.AddValue ("maxWindowSize", "Max TCP window size", maxWinSize);
cmd.Parse (argc, argv);
cout << "bottlelNeck Link BW: " << bottleNeckLinkBw << endl;
cout << "client Data Rate: " << clientDataRate << endl;
cout << "attacker Data Rate: " << attackerDataRate << endl;
cout << "bottleNeck Link Delay: " << bottleNeckLinkDelay << endl;
cout << "fairness: " << fairness << endl;
isPrintHeader = pktPrint == "y"? true : (pktPrint == "n"? false : isPrintHeader);
isTcp = prot == "TCP"? true: (prot == "UDP"? false : isTcp);
cout << "protocol: " << prot << endl;
attackFlowType = isTcp? "ns3::TcpSocketFactory":"ns3::UdpSocketFactory"; // if we need here?
string flowType = isTcp? "ns3::TcpSocketFactory":"ns3::UdpSocketFactory"; // change all to udp
// TcpOptionWinScale winScale;
// cout << "win scale: " << winScale.GetScale() << "; id: " << winScale.GetTypeId() << endl;
// cout << winScale.GetSerializedSize() << endl;
// winScale.SetScale(2);
// cout << "win scale: " << winScale.GetScale() << endl;
// from command line arguments
// Config::SetDefault("ns3::TcpSocketBase::MaxWindowSize", UintegerValue(131070)); // doesn't work
// Config::SetDefault("ns3::TcpSocket::RcvBufSize", UintegerValue (maxWinSize));
/* 1. DropTail: simple active queuing management(AQM) algorithm, drop packets after queue is full (not fair, -> bad global tcp sync)
2. RED (Random Early Detection): monitor average queue size, mark/drop packet based on probability (control queue size, avoid global sync, ...)
see http://www.roman10.net/2011/11/10/drop-tail-and-redtwo-aqm-mechanisms/ */
Packet::EnablePrinting ();
Packet::EnableChecking ();
if ((queueType != "RED") && (queueType != "DropTail"))
{
NS_ABORT_MSG ("Invalid queue type: Use --queueType=RED or --queueType=DropTail");
}
//configuration
//Config::SetDefault ("ns3::OnOffApplication::PacketSize", UintegerValue (pktSize));
Config::SetDefault ("ns3::TcpL4Protocol::SocketType", StringValue ("ns3::TcpNewReno"));
//Config::SetDefault ("ns3::OnOffApplication::DataRate", StringValue (appDataRate));
// if (modeBytes)
// {
// Config::SetDefault("ns3::DropTailQueue::Mode", StringValue("QUEUE_MODE_PACKETS"));
// Config::SetDefault("ns3::DropTailQueue::MaxPackets", UintegerValue(maxPackets));
// Config::SetDefault("ns3::RedQueue::Mode", StringValue("QUEUE_MODE_PACKETS"));
// Config::SetDefault("ns3::RedQueue::QueueLimit", UintegerValue(maxPackets));
// }
// else
// {
// Config::SetDefault("ns3::DropTailQueue::Mode", StringValue("QUEUE_MODE_BYTES"));
// Config::SetDefault("ns3::DropTailQueue::MaxBytes", UintegerValue(maxPackets * pktSize));
// Config::SetDefault("ns3::RedQueue::Mode", StringValue("QUEUE_MODE_BYTES"));
// Config::SetDefault("ns3::RedQueue::QueueLimit", UintegerValue(maxPackets * pktSize));
// minTh *= pktSize;
// maxTh *= pktSize;
// }
// minTh *= pktSize;
// maxTh *= pktSize;
/// set log components
LogComponentEnable ("TestForMiddlePolice", LOG_LEVEL_INFO); /// test here
// LogComponentEnable ("PointToPointDumbbellHelper", LOG_LEVEL_INFO); /// none
// LogComponentEnable ("PointToPointHelper", LOG_LEVEL_INFO); /// none
// LogComponentEnable ("PacketSink", LOG_LEVEL_INFO);
// LogComponentEnable ("PacketSocket", LOG_LEVEL_INFO); /// after testing: no this module in the code
// LogComponentEnable ("PacketSocketClient", LOG_LEVEL_INFO); /// no this
// LogComponentEnable ("PacketSocketServer", LOG_LEVEL_INFO); /// no this
//===================Create network topology===========================//
// Need to create three links for this topo
// 1. The connection between left nodes and left router
// 2. The connection between right nodes and right router
// 3. The connection between two routers
PointToPointHelper bottleNeckLink;
bottleNeckLink.SetDeviceAttribute ("DataRate", StringValue (bottleNeckLinkBw));
bottleNeckLink.SetDeviceAttribute ("Mtu", StringValue (mtu)); /// maximum transmission unit, largest packet or frame size, that can be sent in a packet- or frame-based network
bottleNeckLink.SetChannelAttribute ("Delay", StringValue (bottleNeckLinkDelay));
bottleNeckLink.SetQueue(
"ns3::DropTailQueue",
"MaxSize", StringValue("100p")); // normal 200p, 20p only for test
//leaf helper:
PointToPointHelper pointToPointLeaf;
pointToPointLeaf.SetDeviceAttribute ("DataRate", StringValue ("100000Mbps")); // 1 Tbps
pointToPointLeaf.SetChannelAttribute ("Delay", StringValue ("1ms"));
// Dumbbell constructor: nLeaf normal flows and nAttacker attack flows
/// left nodes <-> router <-> router <-> right nodes, like the shape of dumpbell
PointToPointDumbbellHelper d1 (nLeft, pointToPointLeaf, nRight, pointToPointLeaf, bottleNeckLink);
// Install Stack to the whole nodes
InternetStackHelper stack;
d1.InstallStack (stack);
// for debug