A Discrete-Event Network Simulator
API
Loading...
Searching...
No Matches
tcp-socket-base.cc
Go to the documentation of this file.
1/*
2 * Copyright (c) 2007 Georgia Tech Research Corporation
3 * Copyright (c) 2010 Adrian Sai-wah Tam
4 *
5 * SPDX-License-Identifier: GPL-2.0-only
6 *
7 * Author: Adrian Sai-wah Tam <adrian.sw.tam@gmail.com>
8 */
9
10#define NS_LOG_APPEND_CONTEXT \
11 if (m_node) \
12 { \
13 std::clog << " [node " << m_node->GetId() << "] "; \
14 }
15
16#include "tcp-socket-base.h"
17
18#include "ipv4-end-point.h"
19#include "ipv4-route.h"
21#include "ipv4.h"
22#include "ipv6-end-point.h"
23#include "ipv6-l3-protocol.h"
24#include "ipv6-route.h"
26#include "rtt-estimator.h"
27#include "tcp-congestion-ops.h"
28#include "tcp-header.h"
29#include "tcp-l4-protocol.h"
31#include "tcp-option-sack.h"
32#include "tcp-option-ts.h"
33#include "tcp-option-winscale.h"
34#include "tcp-rate-ops.h"
35#include "tcp-recovery-ops.h"
36#include "tcp-rx-buffer.h"
37#include "tcp-tx-buffer.h"
38
39#include "ns3/abort.h"
40#include "ns3/data-rate.h"
41#include "ns3/double.h"
42#include "ns3/inet-socket-address.h"
43#include "ns3/inet6-socket-address.h"
44#include "ns3/log.h"
45#include "ns3/node.h"
46#include "ns3/object.h"
47#include "ns3/packet.h"
48#include "ns3/pointer.h"
49#include "ns3/simulation-singleton.h"
50#include "ns3/simulator.h"
51#include "ns3/trace-source-accessor.h"
52#include "ns3/uinteger.h"
53
54#include <algorithm>
55#include <cmath>
56
85
86namespace ns3
87{
88
89NS_LOG_COMPONENT_DEFINE("TcpSocketBase");
90
92
95{
96 static TypeId tid =
97 TypeId("ns3::TcpSocketBase")
99 .SetGroupName("Internet")
100 .AddConstructor<TcpSocketBase>()
101 // .AddAttribute ("TcpState", "State in TCP state machine",
102 // TypeId::ATTR_GET,
103 // EnumValue (CLOSED),
104 // MakeEnumAccessor (&TcpSocketBase::m_state),
105 // MakeEnumChecker (CLOSED, "Closed"))
106 .AddAttribute("MaxSegLifetime",
107 "Maximum segment lifetime in seconds, use for TIME_WAIT state transition "
108 "to CLOSED state",
109 DoubleValue(120), /* RFC793 says MSL=2 minutes*/
112 .AddAttribute("MaxWindowSize",
113 "Max size of advertised window",
114 UintegerValue(65535),
117 .AddAttribute("IcmpCallback",
118 "Callback invoked whenever an icmp error is received on this socket.",
122 .AddAttribute("IcmpCallback6",
123 "Callback invoked whenever an icmpv6 error is received on this socket.",
127 .AddAttribute("WindowScaling",
128 "Enable or disable Window Scaling option",
129 BooleanValue(true),
132 .AddAttribute("Sack",
133 "Enable or disable Sack option",
134 BooleanValue(true),
137 .AddAttribute("Timestamp",
138 "Enable or disable Timestamp option",
139 BooleanValue(true),
142 .AddAttribute("Fack",
143 "Enable or disable FACK option",
144 BooleanValue(false),
147 .AddAttribute(
148 "MinRto",
149 "Minimum retransmit timeout value",
150 TimeValue(Seconds(1)), // RFC 6298 says min RTO=1 sec, but Linux uses 200ms.
151 // See http://www.postel.org/pipermail/end2end-interest/2004-November/004402.html
154 .AddAttribute(
155 "ClockGranularity",
156 "Clock Granularity used in RTO calculations",
157 TimeValue(MilliSeconds(1)), // RFC6298 suggest to use fine clock granularity
161 .AddAttribute("TxBuffer",
162 "TCP Tx buffer",
163 PointerValue(),
166 .AddAttribute("RxBuffer",
167 "TCP Rx buffer",
168 PointerValue(),
171 .AddAttribute("CongestionOps",
172 "Pointer to TcpCongestionOps object",
173 PointerValue(),
176 .AddAttribute("RecoveryOps",
177 "Pointer to TcpRecoveryOps object",
178 PointerValue(),
181 .AddAttribute(
182 "ReTxThreshold",
183 "Threshold for fast retransmit",
184 UintegerValue(3),
187 .AddAttribute("LimitedTransmit",
188 "Enable limited transmit",
189 BooleanValue(true),
192 .AddAttribute("UseEcn",
193 "Parameter to set ECN functionality",
197 "Off",
199 "On",
201 "AcceptOnly"))
202 .AddAttribute("UseAbe",
203 "Parameter to set ABE functionality",
204 BooleanValue(false),
207 .AddTraceSource("RTO",
208 "Retransmission timeout",
210 "ns3::TracedValueCallback::Time")
211 .AddTraceSource("RTT",
212 "Smoothed RTT",
214 "ns3::TracedValueCallback::Time")
215 .AddTraceSource("LastRTT",
216 "RTT of the last (S)ACKed packet",
218 "ns3::TracedValueCallback::Time")
219 .AddTraceSource("NextTxSequence",
220 "Next sequence number to send (SND.NXT)",
222 "ns3::SequenceNumber32TracedValueCallback")
223 .AddTraceSource("HighestSequence",
224 "Highest sequence number ever sent in socket's life time",
226 "ns3::TracedValueCallback::SequenceNumber32")
227 .AddTraceSource("State",
228 "TCP state",
230 "ns3::TcpStatesTracedValueCallback")
231 .AddTraceSource("CongState",
232 "TCP Congestion machine state",
234 "ns3::TcpSocketState::TcpCongStatesTracedValueCallback")
235 .AddTraceSource("EcnState",
236 "Trace ECN state change of socket",
238 "ns3::TcpSocketState::EcnStatesTracedValueCallback")
239 .AddTraceSource("AdvWND",
240 "Advertised Window Size",
242 "ns3::TracedValueCallback::Uint32")
243 .AddTraceSource("RWND",
244 "Remote side's flow control window",
246 "ns3::TracedValueCallback::Uint32")
247 .AddTraceSource("BytesInFlight",
248 "Socket estimation of bytes in flight",
250 "ns3::TracedValueCallback::Uint32")
251 .AddTraceSource("FackAwnd",
252 "Socket estimation of bytes in flight by FACK",
254 "ns3::TracedValueCallback::Uint32")
255 .AddTraceSource("HighestRxSequence",
256 "Highest sequence number received from peer",
258 "ns3::TracedValueCallback::SequenceNumber32")
259 .AddTraceSource("HighestRxAck",
260 "Highest ack received from peer",
262 "ns3::TracedValueCallback::SequenceNumber32")
263 .AddTraceSource("PacingRate",
264 "The current TCP pacing rate",
266 "ns3::TracedValueCallback::DataRate")
267 .AddTraceSource("CongestionWindow",
268 "The TCP connection's congestion window",
270 "ns3::TracedValueCallback::Uint32")
271 .AddTraceSource("CongestionWindowInflated",
272 "The TCP connection's congestion window inflates as in older RFC",
274 "ns3::TracedValueCallback::Uint32")
275 .AddTraceSource("SlowStartThreshold",
276 "TCP slow start threshold (bytes)",
278 "ns3::TracedValueCallback::Uint32")
279 .AddTraceSource("Tx",
280 "Send tcp packet to IP protocol",
282 "ns3::TcpSocketBase::TcpTxRxTracedCallback")
283 .AddTraceSource("Retransmission",
284 "Notification of a TCP retransmission",
286 "ns3::TcpSocketBase::RetransmissionCallback")
287 .AddTraceSource("Rx",
288 "Receive tcp packet from IP protocol",
290 "ns3::TcpSocketBase::TcpTxRxTracedCallback")
291 .AddTraceSource("EcnEchoSeq",
292 "Sequence of last received ECN Echo",
294 "ns3::SequenceNumber32TracedValueCallback")
295 .AddTraceSource("EcnCeSeq",
296 "Sequence of last received CE",
298 "ns3::SequenceNumber32TracedValueCallback")
299 .AddTraceSource("EcnCwrSeq",
300 "Sequence of last received CWR",
302 "ns3::SequenceNumber32TracedValueCallback");
303 return tid;
304}
305
307 : TcpSocket()
308{
309 NS_LOG_FUNCTION(this);
310
312 m_txBuffer->SetRWndCallback(MakeCallback(&TcpSocketBase::GetRWnd, this));
315
316 m_sndFack = 0;
318
319 m_tcb->m_rxBuffer = CreateObject<TcpRxBuffer>();
320
321 m_tcb->m_pacingRate = m_tcb->m_maxPacingRate;
323
324 m_tcb->m_sendEmptyPacketCallback = MakeCallback(&TcpSocketBase::SendEmptyPacket, this);
325
326 bool ok;
327
328 ok = m_tcb->TraceConnectWithoutContext(
329 "PacingRate",
331 NS_ASSERT_MSG(ok, "Could not connect trace source PacingRate");
332
333 ok = m_tcb->TraceConnectWithoutContext("CongestionWindow",
335 NS_ASSERT_MSG(ok, "Could not connect trace source CongestionWindow");
336
337 ok = m_tcb->TraceConnectWithoutContext("CongestionWindowInflated",
339 NS_ASSERT_MSG(ok, "Could not connect trace source CongestionWindowInflated");
340
341 ok = m_tcb->TraceConnectWithoutContext("SlowStartThreshold",
343 NS_ASSERT_MSG(ok, "Could not connect trace source SlowStartThreshold");
344
345 ok = m_tcb->TraceConnectWithoutContext("CongState",
347 NS_ASSERT_MSG(ok, "Could not connect trace source CongState");
348
349 ok = m_tcb->TraceConnectWithoutContext("EcnState",
351 NS_ASSERT_MSG(ok, "Could not connect trace source EcnState");
352
353 ok =
354 m_tcb->TraceConnectWithoutContext("NextTxSequence",
356 NS_ASSERT_MSG(ok, "Could not connect trace source NextTxSequence");
357
358 ok = m_tcb->TraceConnectWithoutContext("HighestSequence",
360 NS_ASSERT_MSG(ok, "Could not connect trace source HighestSequence");
361
362 ok = m_tcb->TraceConnectWithoutContext("BytesInFlight",
364 NS_ASSERT_MSG(ok, "Could not connect trace source BytesInFlight");
365
366 ok = m_tcb->TraceConnectWithoutContext("FackAwnd",
368 NS_ASSERT_MSG(ok, "Could not connect trace source FackAwnd");
369
370 ok = m_tcb->TraceConnectWithoutContext("RTT", MakeCallback(&TcpSocketBase::UpdateRtt, this));
371 NS_ASSERT_MSG(ok, "Could not connect trace source RTT");
372
373 ok = m_tcb->TraceConnectWithoutContext("LastRTT",
375 NS_ASSERT_MSG(ok, "Could not connect trace source LastRTT");
376}
377
378void
385
387 : TcpSocket(sock),
388 // copy object::m_tid and socket::callbacks
390 m_delAckCount(0),
392 m_noDelay(sock.m_noDelay),
397 m_rto(sock.m_rto),
398 m_minRto(sock.m_minRto),
403 m_endPoint(nullptr),
404 m_endPoint6(nullptr),
405 m_node(sock.m_node),
406 m_tcp(sock.m_tcp),
407 m_state(sock.m_state),
408 m_errno(sock.m_errno),
414 m_msl(sock.m_msl),
417 m_rWnd(sock.m_rWnd),
427 m_recover(sock.m_recover),
432 m_txTrace(sock.m_txTrace),
433 m_rxTrace(sock.m_rxTrace),
434 m_pacingTimer(Timer::CANCEL_ON_DESTROY),
438{
439 NS_LOG_FUNCTION(this);
440 NS_LOG_LOGIC("Invoked the copy constructor");
441 // Copy the rtt estimator if it is set
442 if (sock.m_rtt)
443 {
444 m_rtt = sock.m_rtt->Copy();
445 }
446 // Reset all callbacks to null
448 Callback<void, Ptr<Socket>, const Address&> vPSA =
451 SetConnectCallback(vPS, vPS);
452 SetDataSentCallback(vPSUI);
453 SetSendCallback(vPSUI);
454 SetRecvCallback(vPS);
456 m_txBuffer->SetRWndCallback(MakeCallback(&TcpSocketBase::GetRWnd, this));
457 m_tcb = CopyObject(sock.m_tcb);
458 m_tcb->m_rxBuffer = CopyObject(sock.m_tcb->m_rxBuffer);
459
460 m_tcb->m_pacingRate = m_tcb->m_maxPacingRate;
462
464
465 if (sock.m_congestionControl)
466 {
469 m_congestionControl->SetRateOps(m_rateOps);
470 }
471
472 if (sock.m_recoveryOps)
473 {
474 m_recoveryOps = sock.m_recoveryOps->Fork();
475 }
476
477 if (m_tcb->m_sendEmptyPacketCallback.IsNull())
478 {
479 m_tcb->m_sendEmptyPacketCallback = MakeCallback(&TcpSocketBase::SendEmptyPacket, this);
480 }
481
482 m_sndFack = sock.m_sndFack;
484
485 bool ok;
486
487 ok = m_tcb->TraceConnectWithoutContext(
488 "PacingRate",
490 NS_ASSERT_MSG(ok, "Could not connect trace source PacingRate");
491
492 ok = m_tcb->TraceConnectWithoutContext("CongestionWindow",
494 NS_ASSERT_MSG(ok, "Could not connect trace source CongestionWindow");
495
496 ok = m_tcb->TraceConnectWithoutContext("CongestionWindowInflated",
498 NS_ASSERT_MSG(ok, "Could not connect trace source CongestionWindowInflated");
499
500 ok = m_tcb->TraceConnectWithoutContext("SlowStartThreshold",
502 NS_ASSERT_MSG(ok, "Could not connect trace source SlowStartThreshold");
503
504 ok = m_tcb->TraceConnectWithoutContext("CongState",
506 NS_ASSERT_MSG(ok, "Could not connect trace source CongState");
507
508 ok = m_tcb->TraceConnectWithoutContext("EcnState",
510 NS_ASSERT_MSG(ok, "Could not connect trace source EcnState");
511
512 ok =
513 m_tcb->TraceConnectWithoutContext("NextTxSequence",
515 NS_ASSERT_MSG(ok, "Could not connect trace source NextTxSequence");
516
517 ok = m_tcb->TraceConnectWithoutContext("HighestSequence",
519 NS_ASSERT_MSG(ok, "Could not connect trace source HighestSequence");
520 ok = m_tcb->TraceConnectWithoutContext("BytesInFlight",
522 NS_ASSERT_MSG(ok, "Could not connect trace source BytesInFlight");
523
524 ok = m_tcb->TraceConnectWithoutContext("FackAwnd",
526
527 ok = m_tcb->TraceConnectWithoutContext("RTT", MakeCallback(&TcpSocketBase::UpdateRtt, this));
528 NS_ASSERT_MSG(ok, "Could not connect trace source RTT");
529
530 ok = m_tcb->TraceConnectWithoutContext("LastRTT",
532 NS_ASSERT_MSG(ok, "Could not connect trace source LastRTT");
533}
534
536{
537 NS_LOG_FUNCTION(this);
538 m_node = nullptr;
539 if (m_endPoint != nullptr)
540 {
542 /*
543 * Upon Bind, an Ipv4Endpoint is allocated and set to m_endPoint, and
544 * DestroyCallback is set to TcpSocketBase::Destroy. If we called
545 * m_tcp->DeAllocate, it will destroy its Ipv4EndpointDemux::DeAllocate,
546 * which in turn destroys my m_endPoint, and in turn invokes
547 * TcpSocketBase::Destroy to nullify m_node, m_endPoint, and m_tcp.
548 */
549 NS_ASSERT(m_endPoint != nullptr);
550 m_tcp->DeAllocate(m_endPoint);
551 NS_ASSERT(m_endPoint == nullptr);
552 }
553 if (m_endPoint6 != nullptr)
554 {
556 NS_ASSERT(m_endPoint6 != nullptr);
557 m_tcp->DeAllocate(m_endPoint6);
558 NS_ASSERT(m_endPoint6 == nullptr);
559 }
560 m_tcp = nullptr;
562}
563
564/* Associate a node with this TCP socket */
565void
567{
568 m_node = node;
569}
570
571/* Associate the L4 protocol (e.g. mux/demux) with this socket */
572void
577
578/* Set an RTT estimator with this socket */
579void
584
585/* Inherit from Socket class: Returns error code */
588{
589 return m_errno;
590}
591
592/* Inherit from Socket class: Returns socket type, NS3_SOCK_STREAM */
595{
596 return NS3_SOCK_STREAM;
597}
598
599/* Inherit from Socket class: Returns associated node */
602{
603 return m_node;
604}
605
606/* Inherit from Socket class: Bind socket to an end-point in TcpL4Protocol */
607int
609{
610 NS_LOG_FUNCTION(this);
611 m_endPoint = m_tcp->Allocate();
612 if (nullptr == m_endPoint)
613 {
615 return -1;
616 }
617
618 m_tcp->AddSocket(this);
619
620 return SetupCallback();
621}
622
623int
625{
626 NS_LOG_FUNCTION(this);
627 m_endPoint6 = m_tcp->Allocate6();
628 if (nullptr == m_endPoint6)
629 {
631 return -1;
632 }
633
634 m_tcp->AddSocket(this);
635
636 return SetupCallback();
637}
638
639/* Inherit from Socket class: Bind socket (with specific address) to an end-point in TcpL4Protocol
640 */
641int
643{
644 NS_LOG_FUNCTION(this << address);
646 {
648 Ipv4Address ipv4 = transport.GetIpv4();
649 uint16_t port = transport.GetPort();
650 if (ipv4 == Ipv4Address::GetAny() && port == 0)
651 {
652 m_endPoint = m_tcp->Allocate();
653 }
654 else if (ipv4 == Ipv4Address::GetAny() && port != 0)
655 {
656 m_endPoint = m_tcp->Allocate(GetBoundNetDevice(), port);
657 }
658 else if (ipv4 != Ipv4Address::GetAny() && port == 0)
659 {
660 m_endPoint = m_tcp->Allocate(ipv4);
661 }
662 else if (ipv4 != Ipv4Address::GetAny() && port != 0)
663 {
664 m_endPoint = m_tcp->Allocate(GetBoundNetDevice(), ipv4, port);
665 }
666 if (nullptr == m_endPoint)
667 {
669 return -1;
670 }
671 }
672 else if (Inet6SocketAddress::IsMatchingType(address))
673 {
675 Ipv6Address ipv6 = transport.GetIpv6();
676 uint16_t port = transport.GetPort();
677 if (ipv6 == Ipv6Address::GetAny() && port == 0)
678 {
679 m_endPoint6 = m_tcp->Allocate6();
680 }
681 else if (ipv6 == Ipv6Address::GetAny() && port != 0)
682 {
683 m_endPoint6 = m_tcp->Allocate6(GetBoundNetDevice(), port);
684 }
685 else if (ipv6 != Ipv6Address::GetAny() && port == 0)
686 {
687 m_endPoint6 = m_tcp->Allocate6(ipv6);
688 }
689 else if (ipv6 != Ipv6Address::GetAny() && port != 0)
690 {
691 m_endPoint6 = m_tcp->Allocate6(GetBoundNetDevice(), ipv6, port);
692 }
693 if (nullptr == m_endPoint6)
694 {
696 return -1;
697 }
698 }
699 else
700 {
702 return -1;
703 }
704
705 m_tcp->AddSocket(this);
706
707 NS_LOG_LOGIC("TcpSocketBase " << this << " got an endpoint: " << m_endPoint);
708
709 return SetupCallback();
710}
711
712void
714{
716 (m_state == CLOSED) || threshold == m_tcb->m_initialSsThresh,
717 "TcpSocketBase::SetSSThresh() cannot change initial ssThresh after connection started.");
718
719 m_tcb->m_initialSsThresh = threshold;
720}
721
724{
725 return m_tcb->m_initialSsThresh;
726}
727
728void
730{
732 (m_state == CLOSED) || cwnd == m_tcb->m_initialCWnd,
733 "TcpSocketBase::SetInitialCwnd() cannot change initial cwnd after connection started.");
734
735 m_tcb->m_initialCWnd = cwnd;
736}
737
740{
741 return m_tcb->m_initialCWnd;
742}
743
744/* Inherit from Socket class: Initiate connection to a remote address:port */
745int
747{
748 NS_LOG_FUNCTION(this << address);
749
750 // If haven't do so, Bind() this socket first
752 {
753 if (m_endPoint == nullptr)
754 {
755 if (Bind() == -1)
756 {
757 NS_ASSERT(m_endPoint == nullptr);
758 return -1; // Bind() failed
759 }
760 NS_ASSERT(m_endPoint != nullptr);
761 }
763 m_endPoint->SetPeer(transport.GetIpv4(), transport.GetPort());
764 m_endPoint6 = nullptr;
765
766 // Get the appropriate local address and port number from the routing protocol and set up
767 // endpoint
768 if (SetupEndpoint() != 0)
769 {
770 NS_LOG_ERROR("Route to destination does not exist ?!");
771 return -1;
772 }
773 }
774 else if (Inet6SocketAddress::IsMatchingType(address))
775 {
776 // If we are operating on a v4-mapped address, translate the address to
777 // a v4 address and re-call this function
779 Ipv6Address v6Addr = transport.GetIpv6();
780 if (v6Addr.IsIpv4MappedAddress())
781 {
782 Ipv4Address v4Addr = v6Addr.GetIpv4MappedAddress();
783 return Connect(InetSocketAddress(v4Addr, transport.GetPort()));
784 }
785
786 if (m_endPoint6 == nullptr)
787 {
788 if (Bind6() == -1)
789 {
790 NS_ASSERT(m_endPoint6 == nullptr);
791 return -1; // Bind() failed
792 }
793 NS_ASSERT(m_endPoint6 != nullptr);
794 }
795 m_endPoint6->SetPeer(v6Addr, transport.GetPort());
796 m_endPoint = nullptr;
797
798 // Get the appropriate local address and port number from the routing protocol and set up
799 // endpoint
800 if (SetupEndpoint6() != 0)
801 {
802 NS_LOG_ERROR("Route to destination does not exist ?!");
803 return -1;
804 }
805 }
806 else
807 {
809 return -1;
810 }
811
812 // Re-initialize parameters in case this socket is being reused after CLOSE
813 m_rtt->Reset();
816
817 // DoConnect() will do state-checking and send a SYN packet
818 return DoConnect();
819}
820
821/* Inherit from Socket class: Listen on the endpoint for an incoming connection */
822int
824{
825 NS_LOG_FUNCTION(this);
826
827 // Linux quits EINVAL if we're not in CLOSED state, so match what they do
828 if (m_state != CLOSED)
829 {
831 return -1;
832 }
833 // In other cases, set the state to LISTEN and done
834 NS_LOG_DEBUG("CLOSED -> LISTEN");
835 m_state = LISTEN;
836 return 0;
837}
838
839/* Inherit from Socket class: Kill this socket and signal the peer (if any) */
840int
842{
843 NS_LOG_FUNCTION(this);
844 /// @internal
845 /// First we check to see if there is any unread rx data.
846 /// \bugid{426} claims we should send reset in this case.
847 if (m_tcb->m_rxBuffer->Size() != 0)
848 {
849 NS_LOG_WARN("Socket " << this << " << unread rx data during close. Sending reset."
850 << "This is probably due to a bad sink application; check its code");
851 SendRST();
852 return 0;
853 }
854
855 if (m_txBuffer->SizeFromSequence(m_tcb->m_nextTxSequence) > 0)
856 { // App close with pending data must wait until all data transmitted
857 if (!m_closeOnEmpty)
858 {
859 m_closeOnEmpty = true;
860 NS_LOG_INFO("Socket " << this << " deferring close, state " << TcpStateName[m_state]);
861 }
862 return 0;
863 }
864 return DoClose();
865}
866
867/* Inherit from Socket class: Signal a termination of send */
868int
870{
871 NS_LOG_FUNCTION(this);
872
873 // this prevents data from being added to the buffer
874 m_shutdownSend = true;
875 m_closeOnEmpty = true;
876 // if buffer is already empty, send a fin now
877 // otherwise fin will go when buffer empties.
878 if (m_txBuffer->Size() == 0)
879 {
881 {
882 NS_LOG_INFO("Empty tx buffer, send fin");
884
885 if (m_state == ESTABLISHED)
886 { // On active close: I am the first one to send FIN
887 NS_LOG_DEBUG("ESTABLISHED -> FIN_WAIT_1");
889 }
890 else
891 { // On passive close: Peer sent me FIN already
892 NS_LOG_DEBUG("CLOSE_WAIT -> LAST_ACK");
894 }
895 }
896 }
897
898 return 0;
899}
900
901/* Inherit from Socket class: Signal a termination of receive */
902int
904{
905 NS_LOG_FUNCTION(this);
906 m_shutdownRecv = true;
907 return 0;
908}
909
910/* Inherit from Socket class: Send a packet. Parameter flags is not used.
911 Packet has no TCP header. Invoked by upper-layer application */
912int
914{
915 NS_LOG_FUNCTION(this << p);
916 NS_ABORT_MSG_IF(flags, "use of flags is not supported in TcpSocketBase::Send()");
918 {
919 // Store the packet into Tx buffer
920 if (!m_txBuffer->Add(p))
921 { // TxBuffer overflow, send failed
923 return -1;
924 }
925 if (m_shutdownSend)
926 {
928 return -1;
929 }
930
931 m_rateOps->CalculateAppLimited(m_tcb->m_cWnd,
932 m_tcb->m_bytesInFlight,
933 m_tcb->m_segmentSize,
934 m_txBuffer->TailSequence(),
935 m_tcb->m_nextTxSequence,
936 m_txBuffer->GetLost(),
937 m_txBuffer->GetRetransmitsCount());
938
939 // Submit the data to lower layers
940 NS_LOG_LOGIC("txBufSize=" << m_txBuffer->Size() << " state " << TcpStateName[m_state]);
941 if ((m_state == ESTABLISHED || m_state == CLOSE_WAIT) && AvailableWindow() > 0)
942 { // Try to send the data out: Add a little step to allow the application
943 // to fill the buffer
944 if (!m_sendPendingDataEvent.IsPending())
945 {
948 this,
950 }
951 }
952 return p->GetSize();
953 }
954 else
955 { // Connection not established yet
957 return -1; // Send failure
958 }
959}
960
961/* Inherit from Socket class: In TcpSocketBase, it is same as Send() call */
962int
963TcpSocketBase::SendTo(Ptr<Packet> p, uint32_t flags, const Address& /* address */)
964{
965 return Send(p, flags); // SendTo() and Send() are the same
966}
967
968/* Inherit from Socket class: Return data to upper-layer application. Parameter flags
969 is not used. Data is returned as a packet of size no larger than maxSize */
972{
973 NS_LOG_FUNCTION(this);
974 NS_ABORT_MSG_IF(flags, "use of flags is not supported in TcpSocketBase::Recv()");
975 if (m_tcb->m_rxBuffer->Size() == 0 && m_state == CLOSE_WAIT)
976 {
977 return Create<Packet>(); // Send EOF on connection close
978 }
979 Ptr<Packet> outPacket = m_tcb->m_rxBuffer->Extract(maxSize);
980 return outPacket;
981}
982
983/* Inherit from Socket class: Recv and return the remote's address */
986{
987 NS_LOG_FUNCTION(this << maxSize << flags);
988 Ptr<Packet> packet = Recv(maxSize, flags);
989 // Null packet means no data to read, and an empty packet indicates EOF
990 if (packet && packet->GetSize() != 0)
991 {
992 if (m_endPoint != nullptr)
993 {
994 fromAddress =
995 InetSocketAddress(m_endPoint->GetPeerAddress(), m_endPoint->GetPeerPort());
996 }
997 else if (m_endPoint6 != nullptr)
998 {
999 fromAddress =
1000 Inet6SocketAddress(m_endPoint6->GetPeerAddress(), m_endPoint6->GetPeerPort());
1001 }
1002 else
1003 {
1004 fromAddress = InetSocketAddress(Ipv4Address::GetZero(), 0);
1005 }
1006 }
1007 return packet;
1008}
1009
1010/* Inherit from Socket class: Get the max number of bytes an app can send */
1013{
1014 NS_LOG_FUNCTION(this);
1015 return m_txBuffer->Available();
1016}
1017
1018/* Inherit from Socket class: Get the max number of bytes an app can read */
1021{
1022 NS_LOG_FUNCTION(this);
1023 return m_tcb->m_rxBuffer->Available();
1024}
1025
1026/* Inherit from Socket class: Return local address:port */
1027int
1029{
1030 NS_LOG_FUNCTION(this);
1031 if (m_endPoint != nullptr)
1032 {
1033 address = InetSocketAddress(m_endPoint->GetLocalAddress(), m_endPoint->GetLocalPort());
1034 }
1035 else if (m_endPoint6 != nullptr)
1036 {
1037 address = Inet6SocketAddress(m_endPoint6->GetLocalAddress(), m_endPoint6->GetLocalPort());
1038 }
1039 else
1040 { // It is possible to call this method on a socket without a name
1041 // in which case, behavior is unspecified
1042 // Should this return an InetSocketAddress or an Inet6SocketAddress?
1044 }
1045 return 0;
1046}
1047
1048int
1050{
1051 NS_LOG_FUNCTION(this << address);
1052
1053 if (!m_endPoint && !m_endPoint6)
1054 {
1056 return -1;
1057 }
1058
1059 if (m_endPoint)
1060 {
1061 address = InetSocketAddress(m_endPoint->GetPeerAddress(), m_endPoint->GetPeerPort());
1062 }
1063 else if (m_endPoint6)
1064 {
1065 address = Inet6SocketAddress(m_endPoint6->GetPeerAddress(), m_endPoint6->GetPeerPort());
1066 }
1067 else
1068 {
1069 NS_ASSERT(false);
1070 }
1071
1072 return 0;
1073}
1074
1075/* Inherit from Socket class: Bind this socket to the specified NetDevice */
1076void
1078{
1079 NS_LOG_FUNCTION(netdevice);
1080 Socket::BindToNetDevice(netdevice); // Includes sanity check
1081 if (m_endPoint != nullptr)
1082 {
1083 m_endPoint->BindToNetDevice(netdevice);
1084 }
1085
1086 if (m_endPoint6 != nullptr)
1087 {
1088 m_endPoint6->BindToNetDevice(netdevice);
1089 }
1090}
1091
1092/* Clean up after Bind. Set up callback functions in the end-point. */
1093int
1095{
1096 NS_LOG_FUNCTION(this);
1097
1098 if (m_endPoint == nullptr && m_endPoint6 == nullptr)
1099 {
1100 return -1;
1101 }
1102 if (m_endPoint != nullptr)
1103 {
1104 m_endPoint->SetRxCallback(
1106 m_endPoint->SetIcmpCallback(
1108 m_endPoint->SetDestroyCallback(
1110 }
1111 if (m_endPoint6 != nullptr)
1112 {
1113 m_endPoint6->SetRxCallback(
1115 m_endPoint6->SetIcmpCallback(
1117 m_endPoint6->SetDestroyCallback(
1119 }
1120
1121 return 0;
1122}
1123
1124/* Perform the real connection tasks: Send SYN if allowed, RST if invalid */
1125int
1127{
1128 NS_LOG_FUNCTION(this);
1129
1130 // A new connection is allowed only if this socket does not have a connection
1131 if (m_state == CLOSED || m_state == LISTEN || m_state == SYN_SENT || m_state == LAST_ACK ||
1133 { // send a SYN packet and change state into SYN_SENT
1134 // send a SYN packet with ECE and CWR flags set if sender is ECN capable
1135 if (m_tcb->m_useEcn == TcpSocketState::On)
1136 {
1138 }
1139 else
1140 {
1142 }
1143 NS_LOG_DEBUG(TcpStateName[m_state] << " -> SYN_SENT");
1144 m_state = SYN_SENT;
1145 m_tcb->m_ecnState = TcpSocketState::ECN_DISABLED; // because sender is not yet aware about
1146 // receiver's ECN capability
1147 }
1148 else if (m_state != TIME_WAIT)
1149 { // In states SYN_RCVD, ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, and CLOSING, an connection
1150 // exists. We send RST, tear down everything, and close this socket.
1151 SendRST();
1153 }
1154 return 0;
1155}
1156
1157/* Do the action to close the socket. Usually send a packet with appropriate
1158 flags depended on the current m_state. */
1159int
1161{
1162 NS_LOG_FUNCTION(this);
1163 switch (m_state)
1164 {
1165 case SYN_RCVD:
1166 case ESTABLISHED:
1167 // send FIN to close the peer
1169 NS_LOG_DEBUG("ESTABLISHED -> FIN_WAIT_1");
1171 break;
1172 case CLOSE_WAIT:
1173 // send FIN+ACK to close the peer
1175 NS_LOG_DEBUG("CLOSE_WAIT -> LAST_ACK");
1176 m_state = LAST_ACK;
1177 break;
1178 case SYN_SENT:
1179 case CLOSING:
1180 // Send RST if application closes in SYN_SENT and CLOSING
1181 SendRST();
1183 break;
1184 case LISTEN:
1185 // In this state, move to CLOSED and tear down the end point
1187 break;
1188 case LAST_ACK:
1189 case CLOSED:
1190 case FIN_WAIT_1:
1191 case FIN_WAIT_2:
1192 case TIME_WAIT:
1193 default: /* mute compiler */
1194 // Do nothing in these five states
1195 break;
1196 }
1197 return 0;
1198}
1199
1200/* Peacefully close the socket by notifying the upper layer and deallocate end point */
1201void
1203{
1204 NS_LOG_FUNCTION(this);
1205
1206 if (!m_closeNotified)
1207 {
1209 m_closeNotified = true;
1210 }
1211 if (m_lastAckEvent.IsPending())
1212 {
1213 m_lastAckEvent.Cancel();
1214 }
1215 NS_LOG_DEBUG(TcpStateName[m_state] << " -> CLOSED");
1216 m_state = CLOSED;
1218}
1219
1220/* Tell if a sequence number range is out side the range that my rx buffer can
1221 accept */
1222bool
1224{
1225 if (m_state == LISTEN || m_state == SYN_SENT || m_state == SYN_RCVD)
1226 { // Rx buffer in these states are not initialized.
1227 return false;
1228 }
1229 if (m_state == LAST_ACK || m_state == CLOSING || m_state == CLOSE_WAIT)
1230 { // In LAST_ACK and CLOSING states, it only wait for an ACK and the
1231 // sequence number must equals to m_rxBuffer->NextRxSequence ()
1232 return (m_tcb->m_rxBuffer->NextRxSequence() != head);
1233 }
1234
1235 // In all other cases, check if the sequence number is in range
1236 return (tail < m_tcb->m_rxBuffer->NextRxSequence() ||
1237 m_tcb->m_rxBuffer->MaxRxSequence() <= head);
1238}
1239
1240/* Function called by the L3 protocol when it received a packet to pass on to
1241 the TCP. This function is registered as the "RxCallback" function in
1242 SetupCallback(), which invoked by Bind(), and CompleteFork() */
1243void
1245 Ipv4Header header,
1246 uint16_t port,
1247 Ptr<Ipv4Interface> incomingInterface)
1248{
1249 NS_LOG_LOGIC("Socket " << this << " forward up " << m_endPoint->GetPeerAddress() << ":"
1250 << m_endPoint->GetPeerPort() << " to " << m_endPoint->GetLocalAddress()
1251 << ":" << m_endPoint->GetLocalPort());
1252
1253 Address fromAddress = InetSocketAddress(header.GetSource(), port);
1254 Address toAddress = InetSocketAddress(header.GetDestination(), m_endPoint->GetLocalPort());
1255
1256 TcpHeader tcpHeader;
1257 uint32_t bytesRemoved = packet->PeekHeader(tcpHeader);
1258
1259 if (!IsValidTcpSegment(tcpHeader.GetSequenceNumber(),
1260 bytesRemoved,
1261 packet->GetSize() - bytesRemoved))
1262 {
1263 return;
1264 }
1265
1266 if (header.GetEcn() == Ipv4Header::ECN_CE && m_ecnCESeq < tcpHeader.GetSequenceNumber())
1267 {
1268 NS_LOG_INFO("Received CE flag is valid");
1269 NS_LOG_DEBUG(TcpSocketState::EcnStateName[m_tcb->m_ecnState] << " -> ECN_CE_RCVD");
1270 m_ecnCESeq = tcpHeader.GetSequenceNumber();
1271 m_tcb->m_ecnState = TcpSocketState::ECN_CE_RCVD;
1273 }
1274 else if (header.GetEcn() != Ipv4Header::ECN_NotECT &&
1275 m_tcb->m_ecnState != TcpSocketState::ECN_DISABLED)
1276 {
1278 }
1279
1280 DoForwardUp(packet, fromAddress, toAddress);
1281}
1282
1283void
1285 Ipv6Header header,
1286 uint16_t port,
1287 Ptr<Ipv6Interface> incomingInterface)
1288{
1289 NS_LOG_LOGIC("Socket " << this << " forward up " << m_endPoint6->GetPeerAddress() << ":"
1290 << m_endPoint6->GetPeerPort() << " to " << m_endPoint6->GetLocalAddress()
1291 << ":" << m_endPoint6->GetLocalPort());
1292
1293 Address fromAddress = Inet6SocketAddress(header.GetSource(), port);
1294 Address toAddress = Inet6SocketAddress(header.GetDestination(), m_endPoint6->GetLocalPort());
1295
1296 TcpHeader tcpHeader;
1297 uint32_t bytesRemoved = packet->PeekHeader(tcpHeader);
1298
1299 if (!IsValidTcpSegment(tcpHeader.GetSequenceNumber(),
1300 bytesRemoved,
1301 packet->GetSize() - bytesRemoved))
1302 {
1303 return;
1304 }
1305
1306 if (header.GetEcn() == Ipv6Header::ECN_CE && m_ecnCESeq < tcpHeader.GetSequenceNumber())
1307 {
1308 NS_LOG_INFO("Received CE flag is valid");
1309 NS_LOG_DEBUG(TcpSocketState::EcnStateName[m_tcb->m_ecnState] << " -> ECN_CE_RCVD");
1310 m_ecnCESeq = tcpHeader.GetSequenceNumber();
1311 m_tcb->m_ecnState = TcpSocketState::ECN_CE_RCVD;
1313 }
1314 else if (header.GetEcn() != Ipv6Header::ECN_NotECT &&
1315 m_tcb->m_ecnState != TcpSocketState::ECN_DISABLED)
1316 {
1318 }
1319
1320 DoForwardUp(packet, fromAddress, toAddress);
1321}
1322
1323void
1325 uint8_t icmpTtl,
1326 uint8_t icmpType,
1327 uint8_t icmpCode,
1328 uint32_t icmpInfo)
1329{
1330 NS_LOG_FUNCTION(this << icmpSource << static_cast<uint32_t>(icmpTtl)
1331 << static_cast<uint32_t>(icmpType) << static_cast<uint32_t>(icmpCode)
1332 << icmpInfo);
1333 if (!m_icmpCallback.IsNull())
1334 {
1335 m_icmpCallback(icmpSource, icmpTtl, icmpType, icmpCode, icmpInfo);
1336 }
1337}
1338
1339void
1341 uint8_t icmpTtl,
1342 uint8_t icmpType,
1343 uint8_t icmpCode,
1344 uint32_t icmpInfo)
1345{
1346 NS_LOG_FUNCTION(this << icmpSource << static_cast<uint32_t>(icmpTtl)
1347 << static_cast<uint32_t>(icmpType) << static_cast<uint32_t>(icmpCode)
1348 << icmpInfo);
1349 if (!m_icmpCallback6.IsNull())
1350 {
1351 m_icmpCallback6(icmpSource, icmpTtl, icmpType, icmpCode, icmpInfo);
1352 }
1353}
1354
1355bool
1357 const uint32_t tcpHeaderSize,
1358 const uint32_t tcpPayloadSize)
1359{
1360 if (tcpHeaderSize == 0 || tcpHeaderSize > 60)
1361 {
1362 NS_LOG_ERROR("Bytes removed: " << tcpHeaderSize << " invalid");
1363 return false; // Discard invalid packet
1364 }
1365 else if (tcpPayloadSize > 0 && OutOfRange(seq, seq + tcpPayloadSize))
1366 {
1367 // Discard fully out of range data packets
1368 NS_LOG_WARN("At state " << TcpStateName[m_state] << " received packet of seq [" << seq
1369 << ":" << seq + tcpPayloadSize << ") out of range ["
1370 << m_tcb->m_rxBuffer->NextRxSequence() << ":"
1371 << m_tcb->m_rxBuffer->MaxRxSequence() << ")");
1372 // Acknowledgement should be sent for all unacceptable packets (RFC793, p.69)
1374 return false;
1375 }
1376 return true;
1377}
1378
1379void
1380TcpSocketBase::DoForwardUp(Ptr<Packet> packet, const Address& fromAddress, const Address& toAddress)
1381{
1382 // in case the packet still has a priority tag attached, remove it
1383 SocketPriorityTag priorityTag;
1384 packet->RemovePacketTag(priorityTag);
1385
1386 // Peel off TCP header
1387 TcpHeader tcpHeader;
1388 packet->RemoveHeader(tcpHeader);
1389 SequenceNumber32 seq = tcpHeader.GetSequenceNumber();
1390
1391 if (m_state == ESTABLISHED && !(tcpHeader.GetFlags() & TcpHeader::RST))
1392 {
1393 // Check if the sender has responded to ECN echo by reducing the Congestion Window
1394 if (tcpHeader.GetFlags() & TcpHeader::CWR)
1395 {
1396 // Check if a packet with CE bit set is received. If there is no CE bit set, then change
1397 // the state to ECN_IDLE to stop sending ECN Echo messages. If there is CE bit set, the
1398 // packet should continue sending ECN Echo messages
1399 //
1400 if (m_tcb->m_ecnState != TcpSocketState::ECN_CE_RCVD)
1401 {
1402 NS_LOG_DEBUG(TcpSocketState::EcnStateName[m_tcb->m_ecnState] << " -> ECN_IDLE");
1403 m_tcb->m_ecnState = TcpSocketState::ECN_IDLE;
1404 }
1405 }
1406 }
1407
1408 m_rxTrace(packet, tcpHeader, this);
1409
1410 if (tcpHeader.GetFlags() & TcpHeader::SYN)
1411 {
1412 /* The window field in a segment where the SYN bit is set (i.e., a <SYN>
1413 * or <SYN,ACK>) MUST NOT be scaled (from RFC 7323 page 9). But should be
1414 * saved anyway..
1415 */
1416 m_rWnd = tcpHeader.GetWindowSize();
1417
1419 {
1421 }
1422 else
1423 {
1424 m_winScalingEnabled = false;
1425 }
1426
1428 {
1430 }
1431 else
1432 {
1433 m_sackEnabled = false;
1434 m_txBuffer->SetSackEnabled(false);
1435 }
1436
1437 // When receiving a <SYN> or <SYN-ACK> we should adapt TS to the other end
1438 if (tcpHeader.HasOption(TcpOption::TS) && m_timestampEnabled)
1439 {
1441 tcpHeader.GetSequenceNumber());
1442 }
1443 else
1444 {
1445 m_timestampEnabled = false;
1446 }
1447
1448 // Initialize cWnd and ssThresh
1449 m_tcb->m_cWnd = GetInitialCwnd() * GetSegSize();
1450 m_tcb->m_cWndInfl = m_tcb->m_cWnd;
1451 m_tcb->m_ssThresh = GetInitialSSThresh();
1452
1453 if (tcpHeader.GetFlags() & TcpHeader::ACK)
1454 {
1455 EstimateRtt(tcpHeader);
1456 m_highRxAckMark = tcpHeader.GetAckNumber();
1457 }
1458 }
1459 else if (tcpHeader.GetFlags() & TcpHeader::ACK)
1460 {
1461 NS_ASSERT(!(tcpHeader.GetFlags() & TcpHeader::SYN));
1463 {
1464 if (!tcpHeader.HasOption(TcpOption::TS))
1465 {
1466 // Ignoring segment without TS, RFC 7323
1467 NS_LOG_LOGIC("At state " << TcpStateName[m_state] << " received packet of seq ["
1468 << seq << ":" << seq + packet->GetSize()
1469 << ") without TS option. Silently discard it");
1470 return;
1471 }
1472 else
1473 {
1475 tcpHeader.GetSequenceNumber());
1476 }
1477 }
1478
1479 EstimateRtt(tcpHeader);
1480 UpdateWindowSize(tcpHeader);
1481 }
1482
1483 if (m_rWnd.Get() == 0 && m_persistEvent.IsExpired())
1484 { // Zero window: Enter persist state to send 1 byte to probe
1485 NS_LOG_LOGIC(this << " Enter zerowindow persist state");
1487 this << " Cancelled ReTxTimeout event which was set to expire at "
1488 << (Simulator::Now() + Simulator::GetDelayLeft(m_retxEvent)).GetSeconds());
1489 m_retxEvent.Cancel();
1490 NS_LOG_LOGIC("Schedule persist timeout at time "
1491 << Simulator::Now().GetSeconds() << " to expire at time "
1492 << (Simulator::Now() + m_persistTimeout).GetSeconds());
1496 }
1497
1498 // TCP state machine code in different process functions
1499 // C.f.: tcp_rcv_state_process() in tcp_input.c in Linux kernel
1500 switch (m_state)
1501 {
1502 case ESTABLISHED:
1503 ProcessEstablished(packet, tcpHeader);
1504 break;
1505 case LISTEN:
1506 ProcessListen(packet, tcpHeader, fromAddress, toAddress);
1507 break;
1508 case TIME_WAIT:
1509 // Do nothing
1510 break;
1511 case CLOSED:
1512 // Send RST if the incoming packet is not a RST
1513 if ((tcpHeader.GetFlags() & ~(TcpHeader::PSH | TcpHeader::URG)) != TcpHeader::RST)
1514 { // Since m_endPoint is not configured yet, we cannot use SendRST here
1515 TcpHeader h;
1518 h.SetSequenceNumber(m_tcb->m_nextTxSequence);
1519 h.SetAckNumber(m_tcb->m_rxBuffer->NextRxSequence());
1520 h.SetSourcePort(tcpHeader.GetDestinationPort());
1521 h.SetDestinationPort(tcpHeader.GetSourcePort());
1523 AddOptions(h);
1524 m_txTrace(p, h, this);
1525 m_tcp->SendPacket(p, h, toAddress, fromAddress, m_boundnetdevice);
1526 }
1527 break;
1528 case SYN_SENT:
1529 ProcessSynSent(packet, tcpHeader);
1530 break;
1531 case SYN_RCVD:
1532 ProcessSynRcvd(packet, tcpHeader, fromAddress, toAddress);
1533 break;
1534 case FIN_WAIT_1:
1535 case FIN_WAIT_2:
1536 case CLOSE_WAIT:
1537 ProcessWait(packet, tcpHeader);
1538 break;
1539 case CLOSING:
1540 ProcessClosing(packet, tcpHeader);
1541 break;
1542 case LAST_ACK:
1543 ProcessLastAck(packet, tcpHeader);
1544 break;
1545 default: // mute compiler
1546 break;
1547 }
1548
1549 if (m_rWnd.Get() != 0 && m_persistEvent.IsPending())
1550 { // persist probes end, the other end has increased the window
1552 NS_LOG_LOGIC(this << " Leaving zerowindow persist state");
1553 m_persistEvent.Cancel();
1554
1556 }
1557}
1558
1559/* Received a packet upon ESTABLISHED state. This function is mimicking the
1560 role of tcp_rcv_established() in tcp_input.c in Linux kernel. */
1561void
1563{
1564 NS_LOG_FUNCTION(this << tcpHeader);
1565
1566 // Extract the flags. PSH, URG, CWR and ECE are disregarded.
1567 uint8_t tcpflags =
1569
1570 // Different flags are different events
1571 if (tcpflags == TcpHeader::ACK)
1572 {
1573 if (tcpHeader.GetAckNumber() < m_txBuffer->HeadSequence())
1574 {
1575 // Case 1: If the ACK is a duplicate (SEG.ACK < SND.UNA), it can be ignored.
1576 // Pag. 72 RFC 793
1577 NS_LOG_WARN("Ignored ack of " << tcpHeader.GetAckNumber()
1578 << " SND.UNA = " << m_txBuffer->HeadSequence());
1579
1580 // TODO: RFC 5961 5.2 [Blind Data Injection Attack].[Mitigation]
1581 }
1582 else if (tcpHeader.GetAckNumber() > m_tcb->m_highTxMark)
1583 {
1584 // If the ACK acks something not yet sent (SEG.ACK > HighTxMark) then
1585 // send an ACK, drop the segment, and return.
1586 // Pag. 72 RFC 793
1587 NS_LOG_WARN("Ignored ack of " << tcpHeader.GetAckNumber()
1588 << " HighTxMark = " << m_tcb->m_highTxMark);
1589
1590 // Receiver sets ECE flags when it receives a packet with CE bit on or sender hasn't
1591 // responded to ECN echo sent by receiver
1592 if (m_tcb->m_ecnState == TcpSocketState::ECN_CE_RCVD ||
1594 {
1597 << " -> ECN_SENDING_ECE");
1599 }
1600 else
1601 {
1603 }
1604 }
1605 else
1606 {
1607 // SND.UNA < SEG.ACK =< HighTxMark
1608 // Pag. 72 RFC 793
1609 ReceivedAck(packet, tcpHeader);
1610 }
1611 }
1612 else if (tcpflags == TcpHeader::SYN || tcpflags == (TcpHeader::SYN | TcpHeader::ACK))
1613 {
1614 // (a) Received SYN, old NS-3 behaviour is to set state to SYN_RCVD and
1615 // respond with a SYN+ACK. But it is not a legal state transition as of
1616 // RFC793. Thus this is ignored.
1617
1618 // (b) No action for received SYN+ACK, it is probably a duplicated packet
1619 }
1620 else if (tcpflags == TcpHeader::FIN || tcpflags == (TcpHeader::FIN | TcpHeader::ACK))
1621 { // Received FIN or FIN+ACK, bring down this socket nicely
1622 PeerClose(packet, tcpHeader);
1623 }
1624 else if (tcpflags == 0)
1625 { // No flags means there is only data
1626 ReceivedData(packet, tcpHeader);
1627 if (m_tcb->m_rxBuffer->Finished())
1628 {
1629 PeerClose(packet, tcpHeader);
1630 }
1631 }
1632 else
1633 { // Received RST or the TCP flags is invalid, in either case, terminate this socket
1634 if (tcpflags != TcpHeader::RST)
1635 { // this must be an invalid flag, send reset
1636 NS_LOG_LOGIC("Illegal flag " << TcpHeader::FlagsToString(tcpflags)
1637 << " received. Reset packet is sent.");
1638 SendRST();
1639 }
1641 }
1642}
1643
1644bool
1646{
1647 NS_LOG_FUNCTION(this << static_cast<uint32_t>(kind));
1648
1649 switch (kind)
1650 {
1651 case TcpOption::TS:
1652 return m_timestampEnabled;
1654 return m_winScalingEnabled;
1656 case TcpOption::SACK:
1657 return m_sackEnabled;
1658 default:
1659 break;
1660 }
1661 return false;
1662}
1663
1664void
1665TcpSocketBase::ReadOptions(const TcpHeader& tcpHeader, uint32_t* bytesSacked)
1666{
1667 NS_LOG_FUNCTION(this << tcpHeader);
1668
1669 for (const auto& option : tcpHeader.GetOptionList())
1670 {
1671 // Check only for ACK options here
1672 switch (option->GetKind())
1673 {
1674 case TcpOption::SACK:
1675 *bytesSacked = ProcessOptionSack(option);
1676 break;
1677 default:
1678 continue;
1679 }
1680 }
1681}
1682
1683// Sender should reduce the Congestion Window as a response to receiver's
1684// ECN Echo notification only once per window
1685void
1687{
1688 NS_LOG_FUNCTION(this << currentDelivered);
1689 m_tcb->m_ssThresh = m_congestionControl->GetSsThresh(m_tcb, BytesInFlight());
1690 NS_LOG_DEBUG("Reduce ssThresh to " << m_tcb->m_ssThresh);
1691 // Do not update m_cWnd, under assumption that recovery process will
1692 // gradually bring it down to m_ssThresh. Update the 'inflated' value of
1693 // cWnd used for tracing, however.
1694 m_tcb->m_cWndInfl = m_tcb->m_ssThresh;
1695 NS_ASSERT(m_tcb->m_congState != TcpSocketState::CA_CWR);
1696 NS_LOG_DEBUG(TcpSocketState::TcpCongStateName[m_tcb->m_congState] << " -> CA_CWR");
1697 m_congestionControl->CongestionStateSet(m_tcb, TcpSocketState::CA_CWR);
1698 m_tcb->m_congState = TcpSocketState::CA_CWR;
1699 // CWR state will be exited when the ack exceeds the m_recover variable.
1700 // Do not set m_recoverActive (which applies to a loss-based recovery)
1701 // m_recover corresponds to Linux tp->high_seq
1702 m_recover = m_tcb->m_highTxMark;
1703 if (!m_congestionControl->HasCongControl())
1704 {
1705 // If there is a recovery algorithm, invoke it.
1706 m_recoveryOps->EnterRecovery(m_tcb, m_dupAckCount, UnAckDataCount(), currentDelivered);
1707 NS_LOG_INFO("Enter CWR recovery mode; set cwnd to " << m_tcb->m_cWnd << ", ssthresh to "
1708 << m_tcb->m_ssThresh << ", recover to "
1709 << m_recover);
1710 }
1711}
1712
1713void
1715{
1716 NS_LOG_FUNCTION(this);
1718
1719 NS_LOG_DEBUG(TcpSocketState::TcpCongStateName[m_tcb->m_congState] << " -> CA_RECOVERY");
1720
1721 if (!m_sackEnabled)
1722 {
1723 // One segment has left the network, PLUS the head is lost
1724 m_txBuffer->AddRenoSack();
1725 m_txBuffer->MarkHeadAsLost();
1726 }
1727 else
1728 {
1729 if (!m_txBuffer->IsLost(m_txBuffer->HeadSequence()))
1730 {
1731 // We received 3 dupacks, but the head is not marked as lost
1732 // (received less than 3 SACK block ahead).
1733 // Manually set it as lost.
1734 m_txBuffer->MarkHeadAsLost();
1735 }
1736 }
1737
1738 // RFC 6675, point (4):
1739 // (4) Invoke fast retransmit and enter loss recovery as follows:
1740 // (4.1) RecoveryPoint = HighData
1741 m_recover = m_tcb->m_highTxMark;
1742 m_recoverActive = true;
1743
1745 m_tcb->m_congState = TcpSocketState::CA_RECOVERY;
1746
1747 // (4.2) ssthresh = cwnd = (FlightSize / 2)
1748 // If SACK is not enabled, still consider the head as 'in flight' for
1749 // compatibility with old ns-3 versions
1750 uint32_t bytesInFlight =
1751 m_sackEnabled ? BytesInFlight() : BytesInFlight() + m_tcb->m_segmentSize;
1752 m_tcb->m_ssThresh = m_congestionControl->GetSsThresh(m_tcb, bytesInFlight);
1753
1754 if (!m_congestionControl->HasCongControl())
1755 {
1756 m_recoveryOps->EnterRecovery(m_tcb, m_dupAckCount, UnAckDataCount(), currentDelivered);
1757 NS_LOG_INFO(m_dupAckCount << " dupack. Enter fast recovery mode."
1758 << "Reset cwnd to " << m_tcb->m_cWnd << ", ssthresh to "
1759 << m_tcb->m_ssThresh << " at fast recovery seqnum " << m_recover
1760 << " calculated in flight: " << bytesInFlight);
1761 }
1762
1763 // (4.3) Retransmit the first data segment presumed dropped
1764 uint32_t sz = SendDataPacket(m_highRxAckMark, m_tcb->m_segmentSize, true);
1765 NS_ASSERT_MSG(sz > 0, "SendDataPacket returned zero, indicating zero bytes were sent");
1766 // (4.4) Run SetPipe ()
1767 // (4.5) Proceed to step (C)
1768 // these steps are done after the ProcessAck function (SendPendingData)
1769}
1770
1771void
1773{
1774 NS_LOG_FUNCTION(this);
1775 // NOTE: We do not count the DupAcks received in CA_LOSS, because we
1776 // don't know if they are generated by a spurious retransmission or because
1777 // of a real packet loss. With SACK, it is easy to know, but we do not consider
1778 // dupacks. Without SACK, there are some heuristics in the RFC 6582, but
1779 // for now, we do not implement it, leading to ignoring the dupacks.
1780 if (m_tcb->m_congState == TcpSocketState::CA_LOSS)
1781 {
1782 return;
1783 }
1784
1785 // RFC 6675, Section 5, 3rd paragraph:
1786 // If the incoming ACK is a duplicate acknowledgment per the definition
1787 // in Section 2 (regardless of its status as a cumulative
1788 // acknowledgment), and the TCP is not currently in loss recovery
1789 // the TCP MUST increase DupAcks by one ...
1790 if (m_tcb->m_congState != TcpSocketState::CA_RECOVERY)
1791 {
1792 ++m_dupAckCount;
1793 }
1794
1795 if (m_tcb->m_congState == TcpSocketState::CA_OPEN)
1796 {
1797 // From Open we go Disorder
1799 "From OPEN->DISORDER but with " << m_dupAckCount << " dup ACKs");
1800
1802 m_tcb->m_congState = TcpSocketState::CA_DISORDER;
1803
1804 NS_LOG_DEBUG("CA_OPEN -> CA_DISORDER");
1805 }
1806
1807 if (m_tcb->m_congState == TcpSocketState::CA_RECOVERY)
1808 {
1809 if (!m_sackEnabled)
1810 {
1811 // If we are in recovery and we receive a dupack, one segment
1812 // has left the network. This is equivalent to a SACK of one block.
1813 m_txBuffer->AddRenoSack();
1814 }
1815 if (!m_congestionControl->HasCongControl())
1816 {
1817 m_recoveryOps->DoRecovery(m_tcb, currentDelivered, true);
1818 NS_LOG_INFO(m_dupAckCount << " Dupack received in fast recovery mode."
1819 "Increase cwnd to "
1820 << m_tcb->m_cWnd);
1821 }
1822 }
1823 else if (m_tcb->m_congState == TcpSocketState::CA_DISORDER)
1824 {
1825 // m_dupackCount should not exceed its threshold in CA_DISORDER state
1826 // when m_recoverActive has not been set. When recovery point
1827 // have been set after timeout, the sender could enter into CA_DISORDER
1828 // after receiving new ACK smaller than m_recover. After that, m_dupackCount
1829 // can be equal and larger than m_retxThresh and we should avoid entering
1830 // CA_RECOVERY and reducing sending rate again.
1832
1833 uint32_t fackDiff = 0;
1834 if (m_fackEnabled)
1835 {
1836 uint32_t headSeq = m_txBuffer->HeadSequence().GetValue();
1837 if (m_sndFack > headSeq)
1838 {
1839 fackDiff = m_sndFack - headSeq;
1840 }
1841 }
1842
1843 // RFC 6675, Section 5, continuing:
1844 // ... and take the following steps:
1845 // (1) If DupAcks >= DupThresh, go to step (4).
1846 // Sequence number comparison (m_highRxAckMark >= m_recover) will take
1847 // effect only when m_recover has been set. Hence, we can avoid to use
1848 // m_recover in the last congestion event and fail to enter
1849 // CA_RECOVERY when sequence number is advanced significantly since
1850 // the last congestion event, which could be common for
1851 // bandwidth-greedy application in high speed and reliable network
1852 // (such as datacenter network) whose sending rate is constrained by
1853 // TCP socket buffer size at receiver side.
1854
1855 // Check FACK recovery condition
1856
1857 if ((m_fackEnabled && fackDiff > m_tcb->m_segmentSize * 3) ||
1860 {
1861 EnterRecovery(currentDelivered);
1863 }
1864 // (2) If DupAcks < DupThresh but IsLost (HighACK + 1) returns true
1865 // (indicating at least three segments have arrived above the current
1866 // cumulative acknowledgment point, which is taken to indicate loss)
1867 // go to step (4). Note that m_highRxAckMark is (HighACK + 1)
1868 else if (m_txBuffer->IsLost(m_highRxAckMark))
1869 {
1870 EnterRecovery(currentDelivered);
1872 }
1873 else
1874 {
1875 // (3) The TCP MAY transmit previously unsent data segments as per
1876 // Limited Transmit [RFC5681] ...except that the number of octets
1877 // which may be sent is governed by pipe and cwnd as follows:
1878 //
1879 // (3.1) Set HighRxt to HighACK.
1880 // Not clear in RFC. We don't do this here, since we still have
1881 // to retransmit the segment.
1882
1883 if (!m_sackEnabled && m_limitedTx)
1884 {
1885 m_txBuffer->AddRenoSack();
1886
1887 // In limited transmit, cwnd Infl is not updated.
1888 }
1889 }
1890 }
1891}
1892
1893/* Process the newly received ACK */
1894void
1896{
1897 NS_LOG_FUNCTION(this << tcpHeader);
1898
1899 NS_ASSERT(0 != (tcpHeader.GetFlags() & TcpHeader::ACK));
1900 NS_ASSERT(m_tcb->m_segmentSize > 0);
1901
1902 uint32_t previousLost = m_txBuffer->GetLost();
1903 uint32_t priorInFlight = m_tcb->m_bytesInFlight.Get();
1904
1905 // RFC 6675, Section 5, 1st paragraph:
1906 // Upon the receipt of any ACK containing SACK information, the
1907 // scoreboard MUST be updated via the Update () routine (done in ReadOptions)
1908 uint32_t bytesSacked = 0;
1909 uint64_t previousDelivered = m_rateOps->GetConnectionRate().m_delivered;
1910 ReadOptions(tcpHeader, &bytesSacked);
1911
1912 SequenceNumber32 ackNumber = tcpHeader.GetAckNumber();
1913 SequenceNumber32 oldHeadSequence = m_txBuffer->HeadSequence();
1914
1915 if (ackNumber < oldHeadSequence)
1916 {
1917 NS_LOG_DEBUG("Possibly received a stale ACK (ack number < head sequence)");
1918 // If there is any data piggybacked, store it into m_rxBuffer
1919 if (packet->GetSize() > 0)
1920 {
1921 ReceivedData(packet, tcpHeader);
1922 }
1923 return;
1924 }
1925 if ((ackNumber > oldHeadSequence) && (ackNumber < m_recover) &&
1926 (m_tcb->m_congState == TcpSocketState::CA_RECOVERY))
1927 {
1928 uint32_t segAcked = (ackNumber - oldHeadSequence) / m_tcb->m_segmentSize;
1929 for (uint32_t i = 0; i < segAcked; i++)
1930 {
1931 if (m_txBuffer->IsRetransmittedDataAcked(ackNumber - (i * m_tcb->m_segmentSize)))
1932 {
1933 m_tcb->m_isRetransDataAcked = true;
1934 NS_LOG_DEBUG("Ack Number " << ackNumber << "is ACK of retransmitted packet.");
1935 }
1936 }
1937 }
1938
1939 m_txBuffer->DiscardUpTo(ackNumber, MakeCallback(&TcpRateOps::SkbDelivered, m_rateOps));
1940
1941 auto currentDelivered =
1942 static_cast<uint32_t>(m_rateOps->GetConnectionRate().m_delivered - previousDelivered);
1943 m_tcb->m_lastAckedSackedBytes = currentDelivered;
1944
1945 if (m_tcb->m_congState == TcpSocketState::CA_CWR && (ackNumber > m_recover))
1946 {
1947 // Recovery is over after the window exceeds m_recover
1948 // (although it may be re-entered below if ECE is still set)
1949 NS_LOG_DEBUG(TcpSocketState::TcpCongStateName[m_tcb->m_congState] << " -> CA_OPEN");
1951 m_tcb->m_congState = TcpSocketState::CA_OPEN;
1952 if (!m_congestionControl->HasCongControl())
1953 {
1954 m_tcb->m_cWnd = m_tcb->m_ssThresh.Get();
1955 m_recoveryOps->ExitRecovery(m_tcb);
1957 }
1958 }
1959
1960 if (ackNumber > oldHeadSequence && (m_tcb->m_ecnState != TcpSocketState::ECN_DISABLED) &&
1961 (tcpHeader.GetFlags() & TcpHeader::ECE))
1962 {
1963 if (m_ecnEchoSeq < ackNumber)
1964 {
1965 NS_LOG_INFO("Received ECN Echo is valid");
1966 m_ecnEchoSeq = ackNumber;
1967 NS_LOG_DEBUG(TcpSocketState::EcnStateName[m_tcb->m_ecnState] << " -> ECN_ECE_RCVD");
1968 m_tcb->m_ecnState = TcpSocketState::ECN_ECE_RCVD;
1969 if (m_tcb->m_congState != TcpSocketState::CA_CWR)
1970 {
1971 EnterCwr(currentDelivered);
1972 }
1973 }
1974 }
1975 else if (m_tcb->m_ecnState == TcpSocketState::ECN_ECE_RCVD &&
1976 !(tcpHeader.GetFlags() & TcpHeader::ECE))
1977 {
1978 m_tcb->m_ecnState = TcpSocketState::ECN_IDLE;
1979 }
1980
1981 // Update bytes in flight before processing the ACK for proper calculation of congestion window
1982 NS_LOG_INFO("Update bytes in flight before processing the ACK.");
1983 BytesInFlight();
1984
1985 bool receivedData = packet->GetSize() > 0;
1986
1987 // RFC 6675 Section 5: 2nd, 3rd paragraph and point (A), (B) implementation
1988 // are inside the function ProcessAck
1989 ProcessAck(ackNumber, (bytesSacked > 0), currentDelivered, oldHeadSequence, receivedData);
1990 m_tcb->m_isRetransDataAcked = false;
1991
1992 if (m_congestionControl->HasCongControl())
1993 {
1994 uint32_t currentLost = m_txBuffer->GetLost();
1995 uint32_t lost =
1996 (currentLost > previousLost) ? currentLost - previousLost : previousLost - currentLost;
1997 auto rateSample = m_rateOps->GenerateSample(currentDelivered,
1998 lost,
1999 false,
2000 priorInFlight,
2001 m_tcb->m_minRtt);
2002 auto rateConn = m_rateOps->GetConnectionRate();
2003 m_congestionControl->CongControl(m_tcb, rateConn, rateSample);
2004 }
2005
2006 // If there is any data piggybacked, store it into m_rxBuffer
2007 if (receivedData)
2008 {
2009 ReceivedData(packet, tcpHeader);
2010 }
2011
2012 // RFC 6675, Section 5, point (C), try to send more data. NB: (C) is implemented
2013 // inside SendPendingData
2015}
2016
2017void
2019 bool scoreboardUpdated,
2020 uint32_t currentDelivered,
2021 const SequenceNumber32& oldHeadSequence,
2022 bool receivedData)
2023{
2024 NS_LOG_FUNCTION(this << ackNumber << scoreboardUpdated << currentDelivered << oldHeadSequence);
2025 // RFC 6675, Section 5, 2nd paragraph:
2026 // If the incoming ACK is a cumulative acknowledgment, the TCP MUST
2027 // reset DupAcks to zero.
2028 bool exitedFastRecovery = false;
2029 uint32_t oldDupAckCount = m_dupAckCount; // remember the old value
2030 m_tcb->m_lastAckedSeq = ackNumber; // Update lastAckedSeq
2031 uint32_t bytesAcked = 0;
2032
2033 /* In RFC 5681 the definition of duplicate acknowledgment was strict:
2034 *
2035 * (a) the receiver of the ACK has outstanding data,
2036 * (b) the incoming acknowledgment carries no data,
2037 * (c) the SYN and FIN bits are both off,
2038 * (d) the acknowledgment number is equal to the greatest acknowledgment
2039 * received on the given connection (TCP.UNA from [RFC793]),
2040 * (e) the advertised window in the incoming acknowledgment equals the
2041 * advertised window in the last incoming acknowledgment.
2042 *
2043 * With RFC 6675, this definition has been reduced:
2044 *
2045 * (a) the ACK is carrying a SACK block that identifies previously
2046 * unacknowledged and un-SACKed octets between HighACK (TCP.UNA) and
2047 * HighData (m_highTxMark)
2048 *
2049 * The check below implements conditions a), b), and d), and c) is prevented by virtue of not
2050 * reaching this code if SYN or FIN is set, and e) is not supported.
2051 */
2052
2053 if (m_fackEnabled && ackNumber == m_txBuffer->HeadSequence() &&
2054 m_tcb->m_congState == TcpSocketState::CA_RECOVERY)
2055 {
2056 if (m_outstandingRetransBytes > m_tcb->m_segmentSize)
2057 {
2058 m_outstandingRetransBytes -= m_tcb->m_segmentSize;
2059 }
2060 else
2061 {
2063 }
2064 }
2065
2066 bool isDupack = m_sackEnabled ? scoreboardUpdated
2067 : (ackNumber == oldHeadSequence &&
2068 ackNumber < m_tcb->m_highTxMark && !receivedData);
2069
2070 NS_LOG_DEBUG("ACK of " << ackNumber << " SND.UNA=" << oldHeadSequence
2071 << " SND.NXT=" << m_tcb->m_nextTxSequence
2072 << " in state: " << TcpSocketState::TcpCongStateName[m_tcb->m_congState]
2073 << " with m_recover: " << m_recover);
2074
2075 // RFC 6675, Section 5, 3rd paragraph:
2076 // If the incoming ACK is a duplicate acknowledgment per the definition
2077 // in Section 2 (regardless of its status as a cumulative
2078 // acknowledgment), and the TCP is not currently in loss recovery
2079 if (isDupack)
2080 {
2081 // loss recovery check is done inside this function thanks to
2082 // the congestion state machine
2083 DupAck(currentDelivered);
2084 }
2085
2086 if (ackNumber == oldHeadSequence && ackNumber == m_tcb->m_highTxMark)
2087 {
2088 // Dupack, but the ACK is precisely equal to the nextTxSequence
2089 return;
2090 }
2091 else if (ackNumber == oldHeadSequence && ackNumber > m_tcb->m_highTxMark)
2092 {
2093 // ACK of the FIN bit ... nextTxSequence is not updated since we
2094 // don't have anything to transmit
2095 NS_LOG_DEBUG("Update nextTxSequence manually to " << ackNumber);
2096 m_tcb->m_nextTxSequence = ackNumber;
2097 }
2098 else if (ackNumber == oldHeadSequence)
2099 {
2100 // DupAck. Artificially call PktsAcked: after all, one segment has been ACKed.
2101 m_congestionControl->PktsAcked(m_tcb, 1, m_tcb->m_srtt);
2102 }
2103 else if (ackNumber > oldHeadSequence)
2104 {
2105 // Please remember that, with SACK, we can enter here even if we
2106 // received a dupack.
2107 bytesAcked = currentDelivered;
2108 uint32_t segsAcked = bytesAcked / m_tcb->m_segmentSize;
2109 m_bytesAckedNotProcessed += bytesAcked % m_tcb->m_segmentSize;
2110 bytesAcked -= bytesAcked % m_tcb->m_segmentSize;
2111
2112 if (m_bytesAckedNotProcessed >= m_tcb->m_segmentSize)
2113 {
2114 segsAcked += 1;
2115 bytesAcked += m_tcb->m_segmentSize;
2116 m_bytesAckedNotProcessed -= m_tcb->m_segmentSize;
2117 }
2118 NS_LOG_DEBUG("Set segsAcked: " << segsAcked
2119 << " based on currentDelivered: " << currentDelivered);
2120
2121 // Dupack count is reset to eventually fast-retransmit after 3 dupacks.
2122 // Any SACK-ed segment will be cleaned up by DiscardUpTo.
2123 // In the case that we advanced SND.UNA, but the ack contains SACK blocks,
2124 // we do not reset. At the third one we will retransmit.
2125 // If we are already in recovery, this check is useless since dupAcks
2126 // are not considered in this phase. When from Recovery we go back
2127 // to open, then dupAckCount is reset anyway.
2128 if (!isDupack)
2129 {
2130 m_dupAckCount = 0;
2131 }
2132
2133 // RFC 6675, Section 5, part (B)
2134 // (B) Upon receipt of an ACK that does not cover RecoveryPoint, the
2135 // following actions MUST be taken:
2136 //
2137 // (B.1) Use Update () to record the new SACK information conveyed
2138 // by the incoming ACK.
2139 // (B.2) Use SetPipe () to re-calculate the number of octets still
2140 // in the network.
2141 //
2142 // (B.1) is done at the beginning, while (B.2) is delayed to part (C) while
2143 // trying to transmit with SendPendingData. We are not allowed to exit
2144 // the CA_RECOVERY phase. Just process this partial ack (RFC 5681)
2145 if (ackNumber < m_recover && m_tcb->m_congState == TcpSocketState::CA_RECOVERY)
2146 {
2147 if (!m_sackEnabled)
2148 {
2149 // Manually set the head as lost, it will be retransmitted.
2150 NS_LOG_INFO("Partial ACK. Manually setting head as lost");
2151 m_txBuffer->MarkHeadAsLost();
2152 }
2153
2154 // Before retransmitting the packet perform DoRecovery and check if
2155 // there is available window
2156 if (!m_congestionControl->HasCongControl() && segsAcked >= 1)
2157 {
2158 m_recoveryOps->DoRecovery(m_tcb, currentDelivered, false);
2159 }
2160
2161 // If the packet is already retransmitted do not retransmit it
2162 if (!m_txBuffer->IsRetransmittedDataAcked(ackNumber + m_tcb->m_segmentSize))
2163 {
2164 DoRetransmit(); // Assume the next seq is lost. Retransmit lost packet
2165 m_tcb->m_cWndInfl = SafeSubtraction(m_tcb->m_cWndInfl, bytesAcked);
2166 }
2167
2168 // This partial ACK acknowledge the fact that one segment has been
2169 // previously lost and now successfully received. All others have
2170 // been processed when they come under the form of dupACKs
2171 m_congestionControl->PktsAcked(m_tcb, 1, m_tcb->m_srtt);
2172 NewAck(ackNumber, m_isFirstPartialAck);
2173
2175 {
2176 NS_LOG_DEBUG("Partial ACK of " << ackNumber
2177 << " and this is the first (RTO will be reset);"
2178 " cwnd set to "
2179 << m_tcb->m_cWnd << " recover seq: " << m_recover
2180 << " dupAck count: " << m_dupAckCount);
2181 m_isFirstPartialAck = false;
2182 }
2183 else
2184 {
2185 NS_LOG_DEBUG("Partial ACK of "
2186 << ackNumber
2187 << " and this is NOT the first (RTO will not be reset)"
2188 " cwnd set to "
2189 << m_tcb->m_cWnd << " recover seq: " << m_recover
2190 << " dupAck count: " << m_dupAckCount);
2191 }
2192 }
2193 // From RFC 6675 section 5.1
2194 // In addition, a new recovery phase (as described in Section 5) MUST NOT
2195 // be initiated until HighACK is greater than or equal to the new value
2196 // of RecoveryPoint.
2197 else if (ackNumber < m_recover && m_tcb->m_congState == TcpSocketState::CA_LOSS)
2198 {
2199 m_congestionControl->PktsAcked(m_tcb, segsAcked, m_tcb->m_srtt);
2200 m_congestionControl->IncreaseWindow(m_tcb, segsAcked);
2201
2202 NS_LOG_DEBUG(" Cong Control Called, cWnd=" << m_tcb->m_cWnd
2203 << " ssTh=" << m_tcb->m_ssThresh);
2204 if (!m_sackEnabled)
2205 {
2207 m_txBuffer->GetSacked() == 0,
2208 "Some segment got dup-acked in CA_LOSS state: " << m_txBuffer->GetSacked());
2209 }
2210 NewAck(ackNumber, true);
2211 }
2212 else if (m_tcb->m_congState == TcpSocketState::CA_CWR)
2213 {
2214 m_congestionControl->PktsAcked(m_tcb, segsAcked, m_tcb->m_srtt);
2215 // TODO: need to check behavior if marking is compounded by loss
2216 // and/or packet reordering
2217 if (!m_congestionControl->HasCongControl() && segsAcked >= 1)
2218 {
2219 m_recoveryOps->DoRecovery(m_tcb, currentDelivered, false);
2220 }
2221 NewAck(ackNumber, true);
2222 }
2223 else
2224 {
2225 if (m_tcb->m_congState == TcpSocketState::CA_OPEN)
2226 {
2227 m_congestionControl->PktsAcked(m_tcb, segsAcked, m_tcb->m_srtt);
2228 }
2229 else if (m_tcb->m_congState == TcpSocketState::CA_DISORDER)
2230 {
2231 if (segsAcked >= oldDupAckCount)
2232 {
2233 m_congestionControl->PktsAcked(m_tcb,
2234 segsAcked - oldDupAckCount,
2235 m_tcb->m_srtt);
2236 }
2237
2238 if (!isDupack)
2239 {
2240 // The network reorder packets. Linux changes the counting lost
2241 // packet algorithm from FACK to NewReno. We simply go back in Open.
2243 m_tcb->m_congState = TcpSocketState::CA_OPEN;
2244 NS_LOG_DEBUG(segsAcked << " segments acked in CA_DISORDER, ack of " << ackNumber
2245 << " exiting CA_DISORDER -> CA_OPEN");
2246 }
2247 else
2248 {
2249 NS_LOG_DEBUG(segsAcked << " segments acked in CA_DISORDER, ack of " << ackNumber
2250 << " but still in CA_DISORDER");
2251 }
2252 }
2253 // RFC 6675, Section 5:
2254 // Once a TCP is in the loss recovery phase, the following procedure
2255 // MUST be used for each arriving ACK:
2256 // (A) An incoming cumulative ACK for a sequence number greater than
2257 // RecoveryPoint signals the end of loss recovery, and the loss
2258 // recovery phase MUST be terminated. Any information contained in
2259 // the scoreboard for sequence numbers greater than the new value of
2260 // HighACK SHOULD NOT be cleared when leaving the loss recovery
2261 // phase.
2262 else if (m_tcb->m_congState == TcpSocketState::CA_RECOVERY)
2263 {
2264 m_isFirstPartialAck = true;
2265
2266 // Recalculate the segs acked, that are from m_recover to ackNumber
2267 // (which are the ones we have not passed to PktsAcked and that
2268 // can increase cWnd)
2269 // TODO: check consistency for dynamic segment size
2270 segsAcked =
2271 static_cast<uint32_t>(ackNumber - oldHeadSequence) / m_tcb->m_segmentSize;
2272 m_congestionControl->PktsAcked(m_tcb, segsAcked, m_tcb->m_srtt);
2275 m_tcb->m_congState = TcpSocketState::CA_OPEN;
2276 exitedFastRecovery = true;
2277 m_dupAckCount = 0; // From recovery to open, reset dupack
2278
2279 NS_LOG_DEBUG(segsAcked << " segments acked in CA_RECOVER, ack of " << ackNumber
2280 << ", exiting CA_RECOVERY -> CA_OPEN");
2281 }
2282 else if (m_tcb->m_congState == TcpSocketState::CA_LOSS)
2283 {
2284 m_isFirstPartialAck = true;
2285
2286 // Recalculate the segs acked, that are from m_recover to ackNumber
2287 // (which are the ones we have not passed to PktsAcked and that
2288 // can increase cWnd)
2289 segsAcked = (ackNumber - m_recover) / m_tcb->m_segmentSize;
2290
2291 m_congestionControl->PktsAcked(m_tcb, segsAcked, m_tcb->m_srtt);
2292
2294 m_tcb->m_congState = TcpSocketState::CA_OPEN;
2295 NS_LOG_DEBUG(segsAcked << " segments acked in CA_LOSS, ack of" << ackNumber
2296 << ", exiting CA_LOSS -> CA_OPEN");
2297 }
2298
2299 if (ackNumber >= m_recover)
2300 {
2301 // All lost segments in the congestion event have been
2302 // retransmitted successfully. The recovery point (m_recover)
2303 // should be deactivated.
2304 m_recoverActive = false;
2305 }
2306
2307 if (exitedFastRecovery)
2308 {
2309 NewAck(ackNumber, true);
2310 m_tcb->m_cWnd = m_tcb->m_ssThresh.Get();
2311 m_recoveryOps->ExitRecovery(m_tcb);
2312 NS_LOG_DEBUG("Leaving Fast Recovery; BytesInFlight() = "
2313 << BytesInFlight() << "; cWnd = " << m_tcb->m_cWnd);
2314 }
2315 if (m_tcb->m_congState == TcpSocketState::CA_OPEN)
2316 {
2317 m_congestionControl->IncreaseWindow(m_tcb, segsAcked);
2318
2319 m_tcb->m_cWndInfl = m_tcb->m_cWnd;
2320
2321 NS_LOG_LOGIC("Congestion control called: cWnd: " << m_tcb->m_cWnd
2322 << " ssTh: " << m_tcb->m_ssThresh
2323 << " segsAcked: " << segsAcked);
2324
2325 NewAck(ackNumber, true);
2326 }
2327 }
2328 }
2329 // Update the pacing rate, since m_congestionControl->IncreaseWindow() or
2330 // m_congestionControl->PktsAcked () may change m_tcb->m_cWnd
2331 // Make sure that control reaches the end of this function and there is no
2332 // return in between
2334}
2335
2336/* Received a packet upon LISTEN state. */
2337void
2339 const TcpHeader& tcpHeader,
2340 const Address& fromAddress,
2341 const Address& toAddress)
2342{
2343 NS_LOG_FUNCTION(this << tcpHeader);
2344
2345 // Extract the flags. PSH, URG, CWR and ECE are disregarded.
2346 uint8_t tcpflags =
2348
2349 // Fork a socket if received a SYN. Do nothing otherwise.
2350 // C.f.: the LISTEN part in tcp_v4_do_rcv() in tcp_ipv4.c in Linux kernel
2351 if (tcpflags != TcpHeader::SYN)
2352 {
2353 return;
2354 }
2355
2356 // Call socket's notify function to let the server app know we got a SYN
2357 // If the server app refuses the connection, do nothing
2358 if (!NotifyConnectionRequest(fromAddress))
2359 {
2360 return;
2361 }
2362 // Clone the socket, simulate fork
2363 Ptr<TcpSocketBase> newSock = Fork();
2364 NS_LOG_LOGIC("Cloned a TcpSocketBase " << newSock);
2366 newSock,
2367 packet,
2368 tcpHeader,
2369 fromAddress,
2370 toAddress);
2371}
2372
2373/* Received a packet upon SYN_SENT */
2374void
2376{
2377 NS_LOG_FUNCTION(this << tcpHeader);
2378
2379 // Extract the flags. PSH and URG are disregarded.
2380 uint8_t tcpflags = tcpHeader.GetFlags() & ~(TcpHeader::PSH | TcpHeader::URG);
2381
2382 if (tcpflags == 0)
2383 { // Bare data, accept it and move to ESTABLISHED state. This is not a normal behaviour. Remove
2384 // this?
2385 NS_LOG_DEBUG("SYN_SENT -> ESTABLISHED");
2387 m_tcb->m_congState = TcpSocketState::CA_OPEN;
2389 m_connected = true;
2390 m_retxEvent.Cancel();
2392 ReceivedData(packet, tcpHeader);
2394 }
2395 else if (tcpflags & TcpHeader::ACK && !(tcpflags & TcpHeader::SYN))
2396 { // Ignore ACK in SYN_SENT
2397 }
2398 else if (tcpflags & TcpHeader::SYN && !(tcpflags & TcpHeader::ACK))
2399 { // Received SYN, move to SYN_RCVD state and respond with SYN+ACK
2400 NS_LOG_DEBUG("SYN_SENT -> SYN_RCVD");
2401 m_state = SYN_RCVD;
2403 m_tcb->m_rxBuffer->SetNextRxSequence(tcpHeader.GetSequenceNumber() + SequenceNumber32(1));
2404 /* Check if we received an ECN SYN packet. Change the ECN state of receiver to ECN_IDLE if
2405 * the traffic is ECN capable and sender has sent ECN SYN packet
2406 */
2407
2408 if (m_tcb->m_useEcn != TcpSocketState::Off &&
2410 {
2411 NS_LOG_INFO("Received ECN SYN packet");
2413 NS_LOG_DEBUG(TcpSocketState::EcnStateName[m_tcb->m_ecnState] << " -> ECN_IDLE");
2414 m_tcb->m_ecnState = TcpSocketState::ECN_IDLE;
2415 }
2416 else
2417 {
2418 m_tcb->m_ecnState = TcpSocketState::ECN_DISABLED;
2420 }
2421 }
2422 else if (tcpflags & (TcpHeader::SYN | TcpHeader::ACK) &&
2423 m_tcb->m_nextTxSequence + SequenceNumber32(1) == tcpHeader.GetAckNumber())
2424 { // Handshake completed
2425 NS_LOG_DEBUG("SYN_SENT -> ESTABLISHED");
2427 m_tcb->m_congState = TcpSocketState::CA_OPEN;
2429 m_connected = true;
2430 m_retxEvent.Cancel();
2431 m_tcb->m_rxBuffer->SetNextRxSequence(tcpHeader.GetSequenceNumber() + SequenceNumber32(1));
2432 m_tcb->m_highTxMark = ++m_tcb->m_nextTxSequence;
2433 m_txBuffer->SetHeadSequence(m_tcb->m_nextTxSequence);
2434 // Before sending packets, update the pacing rate based on RTT measurement so far
2437
2438 /* Check if we received an ECN SYN-ACK packet. Change the ECN state of sender to ECN_IDLE if
2439 * receiver has sent an ECN SYN-ACK packet and the traffic is ECN Capable
2440 */
2441 if (m_tcb->m_useEcn != TcpSocketState::Off &&
2442 (tcpflags & (TcpHeader::CWR | TcpHeader::ECE)) == (TcpHeader::ECE))
2443 {
2444 NS_LOG_INFO("Received ECN SYN-ACK packet.");
2445 NS_LOG_DEBUG(TcpSocketState::EcnStateName[m_tcb->m_ecnState] << " -> ECN_IDLE");
2446 m_tcb->m_ecnState = TcpSocketState::ECN_IDLE;
2447 }
2448 else
2449 {
2450 m_tcb->m_ecnState = TcpSocketState::ECN_DISABLED;
2451 }
2454 // Always respond to first data packet to speed up the connection.
2455 // Remove to get the behaviour of old NS-3 code.
2457 }
2458 else
2459 { // Other in-sequence input
2460 if (!(tcpflags & TcpHeader::RST))
2461 { // When (1) rx of FIN+ACK; (2) rx of FIN; (3) rx of bad flags
2462 NS_LOG_LOGIC("Illegal flag combination "
2463 << TcpHeader::FlagsToString(tcpHeader.GetFlags())
2464 << " received in SYN_SENT. Reset packet is sent.");
2465 SendRST();
2466 }
2468 }
2469}
2470
2471/* Received a packet upon SYN_RCVD */
2472void
2474 const TcpHeader& tcpHeader,
2475 const Address& fromAddress,
2476 const Address& /* toAddress */)
2477{
2478 NS_LOG_FUNCTION(this << tcpHeader);
2479
2480 // Extract the flags. PSH, URG, CWR and ECE are disregarded.
2481 uint8_t tcpflags =
2483
2484 if (tcpflags == 0 ||
2485 (tcpflags == TcpHeader::ACK &&
2486 m_tcb->m_nextTxSequence + SequenceNumber32(1) == tcpHeader.GetAckNumber()))
2487 { // If it is bare data, accept it and move to ESTABLISHED state. This is
2488 // possibly due to ACK lost in 3WHS. If in-sequence ACK is received, the
2489 // handshake is completed nicely.
2490 NS_LOG_DEBUG("SYN_RCVD -> ESTABLISHED");
2492 m_tcb->m_congState = TcpSocketState::CA_OPEN;
2494 m_connected = true;
2495 m_retxEvent.Cancel();
2496 m_tcb->m_highTxMark = ++m_tcb->m_nextTxSequence;
2497 m_txBuffer->SetHeadSequence(m_tcb->m_nextTxSequence);
2498 if (m_endPoint)
2499 {
2500 m_endPoint->SetPeer(InetSocketAddress::ConvertFrom(fromAddress).GetIpv4(),
2501 InetSocketAddress::ConvertFrom(fromAddress).GetPort());
2502 }
2503 else if (m_endPoint6)
2504 {
2505 m_endPoint6->SetPeer(Inet6SocketAddress::ConvertFrom(fromAddress).GetIpv6(),
2506 Inet6SocketAddress::ConvertFrom(fromAddress).GetPort());
2507 }
2508 // Always respond to first data packet to speed up the connection.
2509 // Remove to get the behaviour of old NS-3 code.
2511 NotifyNewConnectionCreated(this, fromAddress);
2512 ReceivedAck(packet, tcpHeader);
2513 // Update the pacing rate based on RTT measurement so far
2515 // As this connection is established, the socket is available to send data now
2516 if (GetTxAvailable() > 0)
2517 {
2519 }
2520 }
2521 else if (tcpflags == TcpHeader::SYN)
2522 { // Probably the peer lost my SYN+ACK
2523 m_tcb->m_rxBuffer->SetNextRxSequence(tcpHeader.GetSequenceNumber() + SequenceNumber32(1));
2524 /* Check if we received an ECN SYN packet. Change the ECN state of receiver to ECN_IDLE if
2525 * sender has sent an ECN SYN packet and the traffic is ECN Capable
2526 */
2527 if (m_tcb->m_useEcn != TcpSocketState::Off &&
2528 (tcpHeader.GetFlags() & (TcpHeader::CWR | TcpHeader::ECE)) ==
2530 {
2531 NS_LOG_INFO("Received ECN SYN packet");
2533 NS_LOG_DEBUG(TcpSocketState::EcnStateName[m_tcb->m_ecnState] << " -> ECN_IDLE");
2534 m_tcb->m_ecnState = TcpSocketState::ECN_IDLE;
2535 }
2536 else
2537 {
2538 m_tcb->m_ecnState = TcpSocketState::ECN_DISABLED;
2540 }
2541 }
2542 else if (tcpflags == (TcpHeader::FIN | TcpHeader::ACK))
2543 {
2544 if (tcpHeader.GetSequenceNumber() == m_tcb->m_rxBuffer->NextRxSequence())
2545 { // In-sequence FIN before connection complete. Set up connection and close.
2546 m_connected = true;
2547 m_retxEvent.Cancel();
2548 m_tcb->m_highTxMark = ++m_tcb->m_nextTxSequence;
2549 m_txBuffer->SetHeadSequence(m_tcb->m_nextTxSequence);
2550 if (m_endPoint)
2551 {
2552 m_endPoint->SetPeer(InetSocketAddress::ConvertFrom(fromAddress).GetIpv4(),
2553 InetSocketAddress::ConvertFrom(fromAddress).GetPort());
2554 }
2555 else if (m_endPoint6)
2556 {
2557 m_endPoint6->SetPeer(Inet6SocketAddress::ConvertFrom(fromAddress).GetIpv6(),
2558 Inet6SocketAddress::ConvertFrom(fromAddress).GetPort());
2559 }
2560 NotifyNewConnectionCreated(this, fromAddress);
2561 PeerClose(packet, tcpHeader);
2562 }
2563 }
2564 else
2565 { // Other in-sequence input
2566 if (tcpflags != TcpHeader::RST)
2567 { // When (1) rx of SYN+ACK; (2) rx of FIN; (3) rx of bad flags
2568 NS_LOG_LOGIC("Illegal flag " << TcpHeader::FlagsToString(tcpflags)
2569 << " received. Reset packet is sent.");
2570 if (m_endPoint)
2571 {
2572 m_endPoint->SetPeer(InetSocketAddress::ConvertFrom(fromAddress).GetIpv4(),
2573 InetSocketAddress::ConvertFrom(fromAddress).GetPort());
2574 }
2575 else if (m_endPoint6)
2576 {
2577 m_endPoint6->SetPeer(Inet6SocketAddress::ConvertFrom(fromAddress).GetIpv6(),
2578 Inet6SocketAddress::ConvertFrom(fromAddress).GetPort());
2579 }
2580 SendRST();
2581 }
2583 }
2584}
2585
2586/* Received a packet upon CLOSE_WAIT, FIN_WAIT_1, or FIN_WAIT_2 states */
2587void
2589{
2590 NS_LOG_FUNCTION(this << tcpHeader);
2591
2592 // Extract the flags. PSH, URG, CWR and ECE are disregarded.
2593 uint8_t tcpflags =
2595
2596 if (packet->GetSize() > 0 && !(tcpflags & TcpHeader::ACK))
2597 { // Bare data, accept it
2598 ReceivedData(packet, tcpHeader);
2599 }
2600 else if (tcpflags == TcpHeader::ACK)
2601 { // Process the ACK, and if in FIN_WAIT_1, conditionally move to FIN_WAIT_2
2602 ReceivedAck(packet, tcpHeader);
2603 if (m_state == FIN_WAIT_1 && m_txBuffer->Size() == 0 &&
2604 tcpHeader.GetAckNumber() == m_tcb->m_highTxMark + SequenceNumber32(1))
2605 { // This ACK corresponds to the FIN sent
2606 NS_LOG_DEBUG("FIN_WAIT_1 -> FIN_WAIT_2");
2608 }
2609 }
2610 else if (tcpflags == TcpHeader::FIN || tcpflags == (TcpHeader::FIN | TcpHeader::ACK))
2611 { // Got FIN, respond with ACK and move to next state
2612 if (tcpflags & TcpHeader::ACK)
2613 { // Process the ACK first
2614 ReceivedAck(packet, tcpHeader);
2615 }
2616 m_tcb->m_rxBuffer->SetFinSequence(tcpHeader.GetSequenceNumber());
2617 }
2618 else if (tcpflags == TcpHeader::SYN || tcpflags == (TcpHeader::SYN | TcpHeader::ACK))
2619 { // Duplicated SYN or SYN+ACK, possibly due to spurious retransmission
2620 return;
2621 }
2622 else
2623 { // This is a RST or bad flags
2624 if (tcpflags != TcpHeader::RST)
2625 {
2626 NS_LOG_LOGIC("Illegal flag " << TcpHeader::FlagsToString(tcpflags)
2627 << " received. Reset packet is sent.");
2628 SendRST();
2629 }
2631 return;
2632 }
2633
2634 // Check if the close responder sent an in-sequence FIN, if so, respond ACK
2635 if ((m_state == FIN_WAIT_1 || m_state == FIN_WAIT_2) && m_tcb->m_rxBuffer->Finished())
2636 {
2637 if (m_state == FIN_WAIT_1)
2638 {
2639 NS_LOG_DEBUG("FIN_WAIT_1 -> CLOSING");
2640 m_state = CLOSING;
2641 if (m_txBuffer->Size() == 0 &&
2642 tcpHeader.GetAckNumber() == m_tcb->m_highTxMark + SequenceNumber32(1))
2643 { // This ACK corresponds to the FIN sent
2644 TimeWait();
2645 }
2646 }
2647 else if (m_state == FIN_WAIT_2)
2648 {
2649 TimeWait();
2650 }
2652 if (!m_shutdownRecv)
2653 {
2655 }
2656 }
2657}
2658
2659/* Received a packet upon CLOSING */
2660void
2662{
2663 NS_LOG_FUNCTION(this << tcpHeader);
2664
2665 // Extract the flags. PSH and URG are disregarded.
2666 uint8_t tcpflags = tcpHeader.GetFlags() & ~(TcpHeader::PSH | TcpHeader::URG);
2667
2668 if (tcpflags == TcpHeader::ACK)
2669 {
2670 if (tcpHeader.GetSequenceNumber() == m_tcb->m_rxBuffer->NextRxSequence())
2671 { // This ACK corresponds to the FIN sent
2672 TimeWait();
2673 }
2674 }
2675 else
2676 { // CLOSING state means simultaneous close, i.e. no one is sending data to
2677 // anyone. If anything other than ACK is received, respond with a reset.
2678 if (tcpflags == TcpHeader::FIN || tcpflags == (TcpHeader::FIN | TcpHeader::ACK))
2679 { // FIN from the peer as well. We can close immediately.
2681 }
2682 else if (tcpflags != TcpHeader::RST)
2683 { // Receive of SYN or SYN+ACK or bad flags or pure data
2684 NS_LOG_LOGIC("Illegal flag " << TcpHeader::FlagsToString(tcpflags)
2685 << " received. Reset packet is sent.");
2686 SendRST();
2687 }
2689 }
2690}
2691
2692/* Received a packet upon LAST_ACK */
2693void
2695{
2696 NS_LOG_FUNCTION(this << tcpHeader);
2697
2698 // Extract the flags. PSH and URG are disregarded.
2699 uint8_t tcpflags = tcpHeader.GetFlags() & ~(TcpHeader::PSH | TcpHeader::URG);
2700
2701 if (tcpflags == 0)
2702 {
2703 ReceivedData(packet, tcpHeader);
2704 }
2705 else if (tcpflags == TcpHeader::ACK)
2706 {
2707 if (tcpHeader.GetSequenceNumber() == m_tcb->m_rxBuffer->NextRxSequence())
2708 { // This ACK corresponds to the FIN sent. This socket closed peacefully.
2710 }
2711 }
2712 else if (tcpflags == TcpHeader::FIN)
2713 { // Received FIN again, the peer probably lost the FIN+ACK
2715 }
2716 else if (tcpflags == (TcpHeader::FIN | TcpHeader::ACK) || tcpflags == TcpHeader::RST)
2717 {
2719 }
2720 else
2721 { // Received a SYN or SYN+ACK or bad flags
2722 NS_LOG_LOGIC("Illegal flag " << TcpHeader::FlagsToString(tcpflags)
2723 << " received. Reset packet is sent.");
2724 SendRST();
2726 }
2727}
2728
2729/* Peer sent me a FIN. Remember its sequence in rx buffer. */
2730void
2732{
2733 NS_LOG_FUNCTION(this << tcpHeader);
2734
2735 // Ignore all out of range packets
2736 if (tcpHeader.GetSequenceNumber() < m_tcb->m_rxBuffer->NextRxSequence() ||
2737 tcpHeader.GetSequenceNumber() > m_tcb->m_rxBuffer->MaxRxSequence())
2738 {
2739 return;
2740 }
2741 // For any case, remember the FIN position in rx buffer first
2742 m_tcb->m_rxBuffer->SetFinSequence(tcpHeader.GetSequenceNumber() +
2743 SequenceNumber32(p->GetSize()));
2744 NS_LOG_LOGIC("Accepted FIN at seq "
2745 << tcpHeader.GetSequenceNumber() + SequenceNumber32(p->GetSize()));
2746 // If there is any piggybacked data, process it
2747 if (p->GetSize())
2748 {
2749 ReceivedData(p, tcpHeader);
2750 }
2751 // Return if FIN is out of sequence, otherwise move to CLOSE_WAIT state by DoPeerClose
2752 if (!m_tcb->m_rxBuffer->Finished())
2753 {
2754 return;
2755 }
2756
2757 // Simultaneous close: Application invoked Close() when we are processing this FIN packet
2758 if (m_state == FIN_WAIT_1)
2759 {
2760 NS_LOG_DEBUG("FIN_WAIT_1 -> CLOSING");
2761 m_state = CLOSING;
2762 return;
2763 }
2764
2765 DoPeerClose(); // Change state, respond with ACK
2766}
2767
2768/* Received a in-sequence FIN. Close down this socket. */
2769void
2771{
2773 m_state == FIN_WAIT_2);
2774
2775 // Move the state to CLOSE_WAIT
2776 NS_LOG_DEBUG(TcpStateName[m_state] << " -> CLOSE_WAIT");
2778
2779 if (!m_closeNotified)
2780 {
2781 // The normal behaviour for an application is that, when the peer sent a in-sequence
2782 // FIN, the app should prepare to close. The app has two choices at this point: either
2783 // respond with ShutdownSend() call to declare that it has nothing more to send and
2784 // the socket can be closed immediately; or remember the peer's close request, wait
2785 // until all its existing data are pushed into the TCP socket, then call Close()
2786 // explicitly.
2787 NS_LOG_LOGIC("TCP " << this << " calling NotifyNormalClose");
2789 m_closeNotified = true;
2790 }
2791 if (m_shutdownSend)
2792 { // The application declares that it would not sent any more, close this socket
2793 Close();
2794 }
2795 else
2796 { // Need to ack, the application will close later
2798 }
2799 if (m_state == LAST_ACK)
2800 {
2801 m_dataRetrCount = m_dataRetries; // prevent endless FINs
2802 NS_LOG_LOGIC("TcpSocketBase " << this << " scheduling LATO1");
2803 Time lastRto = m_rtt->GetEstimate() + Max(m_clockGranularity, m_rtt->GetVariation() * 4);
2805 }
2806}
2807
2808/* Kill this socket. This is a callback function configured to m_endpoint in
2809 SetupCallback(), invoked when the endpoint is destroyed. */
2810void
2812{
2813 NS_LOG_FUNCTION(this);
2814 m_endPoint = nullptr;
2815 if (m_tcp)
2816 {
2817 m_tcp->RemoveSocket(this);
2818 }
2819 NS_LOG_LOGIC(this << " Cancelled ReTxTimeout event which was set to expire at "
2820 << (Simulator::Now() + Simulator::GetDelayLeft(m_retxEvent)).GetSeconds());
2822}
2823
2824/* Kill this socket. This is a callback function configured to m_endpoint in
2825 SetupCallback(), invoked when the endpoint is destroyed. */
2826void
2828{
2829 NS_LOG_FUNCTION(this);
2830 m_endPoint6 = nullptr;
2831 if (m_tcp)
2832 {
2833 m_tcp->RemoveSocket(this);
2834 }
2835 NS_LOG_LOGIC(this << " Cancelled ReTxTimeout event which was set to expire at "
2836 << (Simulator::Now() + Simulator::GetDelayLeft(m_retxEvent)).GetSeconds());
2838}
2839
2840/* Send an empty packet with specified TCP flags */
2841void
2843{
2844 NS_LOG_FUNCTION(this << static_cast<uint32_t>(flags));
2845
2846 if (m_endPoint == nullptr && m_endPoint6 == nullptr)
2847 {
2848 NS_LOG_WARN("Failed to send empty packet due to null endpoint");
2849 return;
2850 }
2851
2853 TcpHeader header;
2854 SequenceNumber32 s = m_tcb->m_nextTxSequence;
2855 TcpPacketType_t packetType = INVALID;
2856
2857 if (flags & TcpHeader::FIN)
2858 {
2859 packetType = TcpPacketType_t::FIN;
2860 flags |= TcpHeader::ACK;
2861 }
2862 else if (m_state == FIN_WAIT_1 || m_state == LAST_ACK || m_state == CLOSING)
2863 {
2864 ++s;
2865 }
2866
2867 if (flags & TcpHeader::SYN)
2868 {
2869 packetType = TcpPacketType_t::SYN;
2870 if (flags & TcpHeader::ACK)
2871 {
2872 packetType = TcpPacketType_t::SYN_ACK;
2873 }
2874 }
2875 else if (flags & TcpHeader::ACK)
2876 {
2877 packetType = TcpPacketType_t::PURE_ACK;
2878 }
2879
2880 if (flags & TcpHeader::RST)
2881 {
2882 packetType = TcpPacketType_t::RST;
2883 }
2884
2885 NS_ASSERT_MSG(packetType != TcpPacketType_t::INVALID, "Invalid TCP packet type");
2886 AddSocketTags(p, IsEct(packetType));
2887
2888 header.SetFlags(flags);
2889 header.SetSequenceNumber(s);
2890 header.SetAckNumber(m_tcb->m_rxBuffer->NextRxSequence());
2891 if (m_endPoint != nullptr)
2892 {
2893 header.SetSourcePort(m_endPoint->GetLocalPort());
2894 header.SetDestinationPort(m_endPoint->GetPeerPort());
2895 }
2896 else
2897 {
2898 header.SetSourcePort(m_endPoint6->GetLocalPort());
2899 header.SetDestinationPort(m_endPoint6->GetPeerPort());
2900 }
2901 AddOptions(header);
2902
2903 // RFC 6298, clause 2.4
2904 m_rto =
2905 Max(m_rtt->GetEstimate() + Max(m_clockGranularity, m_rtt->GetVariation() * 4), m_minRto);
2906
2907 uint16_t windowSize = AdvertisedWindowSize();
2908 bool hasSyn = flags & TcpHeader::SYN;
2909 bool hasFin = flags & TcpHeader::FIN;
2910 bool isAck = flags == TcpHeader::ACK;
2911 if (hasSyn)
2912 {
2914 { // The window scaling option is set only on SYN packets
2915 AddOptionWScale(header);
2916 }
2917
2918 if (m_sackEnabled)
2919 {
2920 AddOptionSackPermitted(header);
2921 }
2922
2923 if (m_synCount == 0)
2924 { // No more connection retries, give up
2925 NS_LOG_LOGIC("Connection failed.");
2926 m_rtt->Reset(); // According to recommendation -> RFC 6298
2928 m_state = CLOSED;
2930 return;
2931 }
2932 else
2933 { // Exponential backoff of connection time out
2934 int backoffCount = 0x1 << (m_synRetries - m_synCount);
2935 m_rto = m_cnTimeout * backoffCount;
2936 m_synCount--;
2937 }
2938
2939 if (m_synRetries - 1 == m_synCount)
2940 {
2941 UpdateRttHistory(s, 0, false);
2942 }
2943 else
2944 { // This is SYN retransmission
2945 UpdateRttHistory(s, 0, true);
2946 }
2947
2948 windowSize = AdvertisedWindowSize(false);
2949 }
2950 header.SetWindowSize(windowSize);
2951
2952 if (flags & TcpHeader::ACK)
2953 { // If sending an ACK, cancel the delay ACK as well
2954 m_delAckEvent.Cancel();
2955 m_delAckCount = 0;
2956 if (m_highTxAck < header.GetAckNumber())
2957 {
2958 m_highTxAck = header.GetAckNumber();
2959 }
2960 if (m_sackEnabled && m_tcb->m_rxBuffer->GetSackListSize() > 0)
2961 {
2962 AddOptionSack(header);
2963 }
2964 NS_LOG_INFO("Sending a pure ACK, acking seq " << m_tcb->m_rxBuffer->NextRxSequence());
2965 }
2966
2967 m_txTrace(p, header, this);
2968
2969 if (m_endPoint != nullptr)
2970 {
2971 m_tcp->SendPacket(p,
2972 header,
2973 m_endPoint->GetLocalAddress(),
2974 m_endPoint->GetPeerAddress(),
2976 }
2977 else
2978 {
2979 m_tcp->SendPacket(p,
2980 header,
2981 m_endPoint6->GetLocalAddress(),
2982 m_endPoint6->GetPeerAddress(),
2984 }
2985
2986 if (m_retxEvent.IsExpired() && (hasSyn || hasFin) && !isAck)
2987 { // Retransmit SYN / SYN+ACK / FIN / FIN+ACK to guard against lost
2988 NS_LOG_LOGIC("Schedule retransmission timeout at time "
2989 << Simulator::Now().GetSeconds() << " to expire at time "
2990 << (Simulator::Now() + m_rto.Get()).GetSeconds());
2992 }
2993}
2994
2995/* This function closes the endpoint completely. Called upon RST_TX action. */
2996void
3004
3005/* Deallocate the end point and cancel all the timers */
3006void
3008{
3009 // note: it shouldn't be necessary to invalidate the callback and manually call
3010 // TcpL4Protocol::RemoveSocket. Alas, if one relies on the endpoint destruction
3011 // callback, there's a weird memory access to a free'd area. Harmless, but valgrind
3012 // considers it an error.
3013
3014 if (m_endPoint != nullptr)
3015 {
3017 m_endPoint->SetDestroyCallback(MakeNullCallback<void>());
3018 m_tcp->DeAllocate(m_endPoint);
3019 m_endPoint = nullptr;
3020 m_tcp->RemoveSocket(this);
3021 }
3022 else if (m_endPoint6 != nullptr)
3023 {
3025 m_endPoint6->SetDestroyCallback(MakeNullCallback<void>());
3026 m_tcp->DeAllocate(m_endPoint6);
3027 m_endPoint6 = nullptr;
3028 m_tcp->RemoveSocket(this);
3029 }
3030}
3031
3032/* Configure the endpoint to a local address. Called by Connect() if Bind() didn't specify one. */
3033int
3035{
3036 NS_LOG_FUNCTION(this);
3037 Ptr<Ipv4> ipv4 = m_node->GetObject<Ipv4>();
3038 NS_ASSERT(ipv4);
3039 if (!ipv4->GetRoutingProtocol())
3040 {
3041 NS_FATAL_ERROR("No Ipv4RoutingProtocol in the node");
3042 }
3043 // Create a dummy packet, then ask the routing function for the best output
3044 // interface's address
3045 Ipv4Header header;
3046 header.SetDestination(m_endPoint->GetPeerAddress());
3047 Socket::SocketErrno errno_;
3048 Ptr<Ipv4Route> route;
3050 route = ipv4->GetRoutingProtocol()->RouteOutput(Ptr<Packet>(), header, oif, errno_);
3051 if (!route)
3052 {
3053 NS_LOG_LOGIC("Route to " << m_endPoint->GetPeerAddress() << " does not exist");
3054 NS_LOG_ERROR(errno_);
3055 m_errno = errno_;
3056 return -1;
3057 }
3058 NS_LOG_LOGIC("Route exists");
3059 m_endPoint->SetLocalAddress(route->GetSource());
3060 return 0;
3061}
3062
3063int
3065{
3066 NS_LOG_FUNCTION(this);
3067 Ptr<Ipv6L3Protocol> ipv6 = m_node->GetObject<Ipv6L3Protocol>();
3068 NS_ASSERT(ipv6);
3069 if (!ipv6->GetRoutingProtocol())
3070 {
3071 NS_FATAL_ERROR("No Ipv6RoutingProtocol in the node");
3072 }
3073 // Create a dummy packet, then ask the routing function for the best output
3074 // interface's address
3075 Ipv6Header header;
3076 header.SetDestination(m_endPoint6->GetPeerAddress());
3077 Socket::SocketErrno errno_;
3078 Ptr<Ipv6Route> route;
3080 route = ipv6->GetRoutingProtocol()->RouteOutput(Ptr<Packet>(), header, oif, errno_);
3081 if (!route)
3082 {
3083 NS_LOG_LOGIC("Route to " << m_endPoint6->GetPeerAddress() << " does not exist");
3084 NS_LOG_ERROR(errno_);
3085 m_errno = errno_;
3086 return -1;
3087 }
3088 NS_LOG_LOGIC("Route exists");
3089 m_endPoint6->SetLocalAddress(route->GetSource());
3090 return 0;
3091}
3092
3093/* This function is called only if a SYN received in LISTEN state. After
3094 TcpSocketBase cloned, allocate a new end point to handle the incoming
3095 connection and send a SYN+ACK to complete the handshake. */
3096void
3098 const TcpHeader& h,
3099 const Address& fromAddress,
3100 const Address& toAddress)
3101{
3102 NS_LOG_FUNCTION(this << p << h << fromAddress << toAddress);
3103 // Get port and address from peer (connecting host)
3104 if (InetSocketAddress::IsMatchingType(toAddress))
3105 {
3106 m_endPoint = m_tcp->Allocate(GetBoundNetDevice(),
3107 InetSocketAddress::ConvertFrom(toAddress).GetIpv4(),
3108 InetSocketAddress::ConvertFrom(toAddress).GetPort(),
3109 InetSocketAddress::ConvertFrom(fromAddress).GetIpv4(),
3110 InetSocketAddress::ConvertFrom(fromAddress).GetPort());
3111 m_endPoint6 = nullptr;
3112 }
3113 else if (Inet6SocketAddress::IsMatchingType(toAddress))
3114 {
3115 m_endPoint6 = m_tcp->Allocate6(GetBoundNetDevice(),
3116 Inet6SocketAddress::ConvertFrom(toAddress).GetIpv6(),
3117 Inet6SocketAddress::ConvertFrom(toAddress).GetPort(),
3118 Inet6SocketAddress::ConvertFrom(fromAddress).GetIpv6(),
3119 Inet6SocketAddress::ConvertFrom(fromAddress).GetPort());
3120 m_endPoint = nullptr;
3121 }
3122 m_tcp->AddSocket(this);
3123
3124 // Change the cloned socket from LISTEN state to SYN_RCVD
3125 NS_LOG_DEBUG("LISTEN -> SYN_RCVD");
3126 m_state = SYN_RCVD;
3129 SetupCallback();
3130 // Set the sequence number and send SYN+ACK
3131 m_tcb->m_rxBuffer->SetNextRxSequence(h.GetSequenceNumber() + SequenceNumber32(1));
3132
3133 /* Check if we received an ECN SYN packet. Change the ECN state of receiver to ECN_IDLE if
3134 * sender has sent an ECN SYN packet and the traffic is ECN Capable
3135 */
3136 if (m_tcb->m_useEcn != TcpSocketState::Off &&
3138 {
3140 NS_LOG_DEBUG(TcpSocketState::EcnStateName[m_tcb->m_ecnState] << " -> ECN_IDLE");
3141 m_tcb->m_ecnState = TcpSocketState::ECN_IDLE;
3142 }
3143 else
3144 {
3146 m_tcb->m_ecnState = TcpSocketState::ECN_DISABLED;
3147 }
3148}
3149
3150void
3152{ // Wrapper to protected function NotifyConnectionSucceeded() so that it can
3153 // be called as a scheduled event
3155 // The if-block below was moved from ProcessSynSent() to here because we need
3156 // to invoke the NotifySend() only after NotifyConnectionSucceeded() to
3157 // reflect the behaviour in the real world.
3158 if (GetTxAvailable() > 0)
3159 {
3161 }
3162}
3163
3164void
3166{
3167 /*
3168 * Add tags for each socket option.
3169 * Note that currently the socket adds both IPv4 tag and IPv6 tag
3170 * if both options are set. Once the packet got to layer three, only
3171 * the corresponding tags will be read.
3172 */
3173 if (GetIpTos())
3174 {
3175 SocketIpTosTag ipTosTag;
3176 if (m_tcb->m_ecnState != TcpSocketState::ECN_DISABLED && !CheckNoEcn(GetIpTos()) && isEct)
3177 {
3178 ipTosTag.SetTos(MarkEcnCodePoint(GetIpTos(), m_tcb->m_ectCodePoint));
3179 }
3180 else
3181 {
3182 // Set the last received ipTos
3183 ipTosTag.SetTos(GetIpTos());
3184 }
3185 p->AddPacketTag(ipTosTag);
3186 }
3187 else
3188 {
3189 if ((m_tcb->m_ecnState != TcpSocketState::ECN_DISABLED && p->GetSize() > 0 && isEct) ||
3190 m_tcb->m_ecnMode == TcpSocketState::DctcpEcn)
3191 {
3192 SocketIpTosTag ipTosTag;
3193 ipTosTag.SetTos(MarkEcnCodePoint(GetIpTos(), m_tcb->m_ectCodePoint));
3194 p->AddPacketTag(ipTosTag);
3195 }
3196 }
3197
3198 if (IsManualIpv6Tclass())
3199 {
3200 SocketIpv6TclassTag ipTclassTag;
3201 if (m_tcb->m_ecnState != TcpSocketState::ECN_DISABLED && !CheckNoEcn(GetIpv6Tclass()) &&
3202 isEct)
3203 {
3204 ipTclassTag.SetTclass(MarkEcnCodePoint(GetIpv6Tclass(), m_tcb->m_ectCodePoint));
3205 }
3206 else
3207 {
3208 // Set the last received ipTos
3209 ipTclassTag.SetTclass(GetIpv6Tclass());
3210 }
3211 p->AddPacketTag(ipTclassTag);
3212 }
3213 else
3214 {
3215 if ((m_tcb->m_ecnState != TcpSocketState::ECN_DISABLED && p->GetSize() > 0 && isEct) ||
3216 m_tcb->m_ecnMode == TcpSocketState::DctcpEcn)
3217 {
3218 SocketIpv6TclassTag ipTclassTag;
3219 ipTclassTag.SetTclass(MarkEcnCodePoint(GetIpv6Tclass(), m_tcb->m_ectCodePoint));
3220 p->AddPacketTag(ipTclassTag);
3221 }
3222 }
3223
3224 if (IsManualIpTtl())
3225 {
3226 SocketIpTtlTag ipTtlTag;
3227 ipTtlTag.SetTtl(GetIpTtl());
3228 p->AddPacketTag(ipTtlTag);
3229 }
3230
3232 {
3233 SocketIpv6HopLimitTag ipHopLimitTag;
3234 ipHopLimitTag.SetHopLimit(GetIpv6HopLimit());
3235 p->AddPacketTag(ipHopLimitTag);
3236 }
3237
3238 uint8_t priority = GetPriority();
3239 if (priority)
3240 {
3241 SocketPriorityTag priorityTag;
3242 priorityTag.SetPriority(priority);
3243 p->ReplacePacketTag(priorityTag);
3244 }
3245}
3246
3247/* Extract at most maxSize bytes from the TxBuffer at sequence seq, add the
3248 TCP header, and send to TcpL4Protocol */
3251{
3252 NS_LOG_FUNCTION(this << seq << maxSize << withAck);
3253
3254 bool isStartOfTransmission = BytesInFlight() == 0U;
3255 TcpTxItem* outItem = m_txBuffer->CopyFromSequence(maxSize, seq);
3256
3257 m_rateOps->SkbSent(outItem, isStartOfTransmission);
3258
3259 bool isRetransmission = outItem->IsRetrans();
3260 Ptr<Packet> p = outItem->GetPacketCopy();
3261 uint32_t sz = p->GetSize(); // Size of packet
3262 uint8_t flags = withAck ? TcpHeader::ACK : 0;
3263 uint32_t remainingData = m_txBuffer->SizeFromSequence(seq + SequenceNumber32(sz));
3264
3265 // TCP sender should not send data out of the window advertised by the
3266 // peer when it is not retransmission.
3267 NS_ASSERT(isRetransmission ||
3268 ((m_highRxAckMark + SequenceNumber32(m_rWnd)) >= (seq + SequenceNumber32(maxSize))));
3269
3270 if (IsPacingEnabled())
3271 {
3272 NS_LOG_INFO("Pacing is enabled");
3273 if (m_pacingTimer.IsExpired())
3274 {
3275 NS_LOG_DEBUG("Current Pacing Rate " << m_tcb->m_pacingRate);
3276 NS_LOG_DEBUG("Timer is in expired state, activate it "
3277 << m_tcb->m_pacingRate.Get().CalculateBytesTxTime(sz));
3278 m_pacingTimer.Schedule(m_tcb->m_pacingRate.Get().CalculateBytesTxTime(sz));
3279 }
3280 else
3281 {
3282 NS_LOG_INFO("Timer is already in running state");
3283 }
3284 }
3285 else
3286 {
3287 NS_LOG_INFO("Pacing is disabled");
3288 }
3289
3290 if (withAck)
3291 {
3292 m_delAckEvent.Cancel();
3293 m_delAckCount = 0;
3294 }
3295
3296 if (m_tcb->m_ecnState == TcpSocketState::ECN_ECE_RCVD &&
3297 m_ecnEchoSeq.Get() > m_ecnCWRSeq.Get() && !isRetransmission)
3298 {
3299 NS_LOG_DEBUG(TcpSocketState::EcnStateName[m_tcb->m_ecnState] << " -> ECN_CWR_SENT");
3300 m_tcb->m_ecnState = TcpSocketState::ECN_CWR_SENT;
3301 m_ecnCWRSeq = seq;
3302 flags |= TcpHeader::CWR;
3303 NS_LOG_INFO("CWR flags set");
3304 }
3305
3306 bool isEct = IsEct(isRetransmission ? TcpPacketType_t::RE_XMT : TcpPacketType_t::DATA);
3307 AddSocketTags(p, isEct);
3308
3309 if (m_closeOnEmpty && (remainingData == 0))
3310 {
3311 flags |= TcpHeader::FIN;
3312 if (m_state == ESTABLISHED)
3313 { // On active close: I am the first one to send FIN
3314 NS_LOG_DEBUG("ESTABLISHED -> FIN_WAIT_1");
3316 }
3317 else if (m_state == CLOSE_WAIT)
3318 { // On passive close: Peer sent me FIN already
3319 NS_LOG_DEBUG("CLOSE_WAIT -> LAST_ACK");
3320 m_state = LAST_ACK;
3321 }
3322 }
3323 TcpHeader header;
3324 header.SetFlags(flags);
3325 header.SetSequenceNumber(seq);
3326 header.SetAckNumber(m_tcb->m_rxBuffer->NextRxSequence());
3327 if (m_endPoint)
3328 {
3329 header.SetSourcePort(m_endPoint->GetLocalPort());
3330 header.SetDestinationPort(m_endPoint->GetPeerPort());
3331 }
3332 else
3333 {
3334 header.SetSourcePort(m_endPoint6->GetLocalPort());
3335 header.SetDestinationPort(m_endPoint6->GetPeerPort());
3336 }
3338 AddOptions(header);
3339
3340 if (m_retxEvent.IsExpired())
3341 {
3342 // Schedules retransmit timeout. m_rto should be already doubled.
3343
3344 NS_LOG_LOGIC(this << " SendDataPacket Schedule ReTxTimeout at time "
3345 << Simulator::Now().GetSeconds() << " to expire at time "
3346 << (Simulator::Now() + m_rto.Get()).GetSeconds());
3348 }
3349
3350 m_txTrace(p, header, this);
3351 if (isRetransmission)
3352 {
3353 if (m_endPoint)
3354 {
3356 header,
3357 m_endPoint->GetLocalAddress(),
3358 m_endPoint->GetPeerAddress(),
3359 this);
3360 }
3361 else
3362 {
3364 header,
3365 m_endPoint6->GetLocalAddress(),
3366 m_endPoint6->GetPeerAddress(),
3367 this);
3368 }
3369 }
3370
3371 if (m_endPoint)
3372 {
3373 m_tcp->SendPacket(p,
3374 header,
3375 m_endPoint->GetLocalAddress(),
3376 m_endPoint->GetPeerAddress(),
3378 NS_LOG_DEBUG("Send segment of size "
3379 << sz << " with remaining data " << remainingData << " via TcpL4Protocol to "
3380 << m_endPoint->GetPeerAddress() << ". Header " << header);
3381 }
3382 else
3383 {
3384 m_tcp->SendPacket(p,
3385 header,
3386 m_endPoint6->GetLocalAddress(),
3387 m_endPoint6->GetPeerAddress(),
3389 NS_LOG_DEBUG("Send segment of size "
3390 << sz << " with remaining data " << remainingData << " via TcpL4Protocol to "
3391 << m_endPoint6->GetPeerAddress() << ". Header " << header);
3392 }
3393
3394 // Signal to congestion control whether the cwnd is fully used
3395 // This is a simple version of Linux tcp_cwnd_validate() but following
3396 // the principle implemented in Linux that limits the updating of cwnd
3397 // (in the congestion controls) when flight size is >= cwnd
3398 // send will also be cwnd limited if less then one segment of cwnd is available
3399 m_tcb->m_isCwndLimited = (m_tcb->m_cWnd < BytesInFlight() + m_tcb->m_segmentSize);
3400
3401 UpdateRttHistory(seq, sz, isRetransmission);
3402
3403 // Update bytes sent during recovery phase
3404 if (m_tcb->m_congState == TcpSocketState::CA_RECOVERY ||
3405 m_tcb->m_congState == TcpSocketState::CA_CWR)
3406 {
3407 m_recoveryOps->UpdateBytesSent(sz);
3408 }
3409
3410 // Notify the application of the data being sent unless this is a retransmit
3411 if (!isRetransmission)
3412 {
3414 this,
3415 (seq + sz - m_tcb->m_highTxMark.Get()));
3416 }
3417 // Update highTxMark
3418 m_tcb->m_highTxMark = std::max(seq + sz, m_tcb->m_highTxMark.Get());
3419 return sz;
3420}
3421
3422void
3423TcpSocketBase::UpdateRttHistory(const SequenceNumber32& seq, uint32_t sz, bool isRetransmission)
3424{
3425 NS_LOG_FUNCTION(this);
3426
3427 // update the history of sequence numbers used to calculate the RTT
3428 if (!isRetransmission)
3429 { // This is the next expected one, just log at end
3430 m_history.emplace_back(seq, sz, Simulator::Now());
3431 }
3432 else
3433 { // This is a retransmit, find in list and mark as re-tx
3434 for (auto i = m_history.begin(); i != m_history.end(); ++i)
3435 {
3436 if ((seq >= i->seq) && (seq < (i->seq + SequenceNumber32(i->count))))
3437 { // Found it
3438 i->retx = true;
3439 i->count = ((seq + SequenceNumber32(sz)) - i->seq); // And update count in hist
3440 break;
3441 }
3442 }
3443 }
3444}
3445
3446// Note that this function did not implement the PSH flag
3449{
3450 NS_LOG_FUNCTION(this << withAck);
3451 if (m_txBuffer->Size() == 0)
3452 {
3453 return 0; // Nothing to send
3454 }
3455 if (m_endPoint == nullptr && m_endPoint6 == nullptr)
3456 {
3458 "TcpSocketBase::SendPendingData: No endpoint; m_shutdownSend=" << m_shutdownSend);
3459 return 0; // Is this the right way to handle this condition?
3460 }
3461
3462 uint32_t nPacketsSent = 0;
3463 uint32_t availableWindow = AvailableWindow();
3464
3465 // RFC 6675, Section (C)
3466 // If cwnd - pipe >= 1 SMSS, the sender SHOULD transmit one or more
3467 // segments as follows:
3468 // (NOTE: We check > 0, and do the checks for segmentSize in the following
3469 // else branch to control silly window syndrome and Nagle)
3470 while (availableWindow > 0)
3471 {
3472 if (IsPacingEnabled())
3473 {
3474 NS_LOG_INFO("Pacing is enabled");
3475 if (m_pacingTimer.IsRunning())
3476 {
3477 NS_LOG_INFO("Skipping Packet due to pacing" << m_pacingTimer.GetDelayLeft());
3478 break;
3479 }
3480 NS_LOG_INFO("Timer is not running");
3481 }
3482
3484 {
3485 NS_LOG_INFO("FIN_WAIT and OPEN state; no data to transmit");
3486 break;
3487 }
3488 // (C.1) The scoreboard MUST be queried via NextSeg () for the
3489 // sequence number range of the next segment to transmit (if
3490 // any), and the given segment sent. If NextSeg () returns
3491 // failure (no data to send), return without sending anything
3492 // (i.e., terminate steps C.1 -- C.5).
3493 SequenceNumber32 next;
3494 SequenceNumber32 nextHigh;
3495 bool enableRule3 = m_sackEnabled && m_tcb->m_congState == TcpSocketState::CA_RECOVERY;
3496 if (!m_txBuffer->NextSeg(&next, &nextHigh, enableRule3))
3497 {
3498 NS_LOG_INFO("no valid seq to transmit, or no data available");
3499 break;
3500 }
3501 else
3502 {
3503 // It's time to transmit, but before do silly window and Nagle's check
3504 uint32_t availableData = m_txBuffer->SizeFromSequence(next);
3505
3506 // If there's less app data than the full window, ask the app for more
3507 // data before trying to send
3508 if (availableData < availableWindow)
3509 {
3511 }
3512
3513 // Stop sending if we need to wait for a larger Tx window (prevent silly window
3514 // syndrome) but continue if we don't have data
3515 if (availableWindow < m_tcb->m_segmentSize && availableData > availableWindow)
3516 {
3517 NS_LOG_LOGIC("Preventing Silly Window Syndrome. Wait to send.");
3518 break; // No more
3519 }
3520 // Nagle's algorithm (RFC896): Hold off sending if there is unacked data
3521 // in the buffer and the amount of data to send is less than one segment
3522 if (!m_noDelay && UnAckDataCount() > 0 && availableData < m_tcb->m_segmentSize)
3523 {
3524 NS_LOG_DEBUG("Invoking Nagle's algorithm for seq "
3525 << next << ", SFS: " << m_txBuffer->SizeFromSequence(next)
3526 << ". Wait to send.");
3527 break;
3528 }
3529
3530 uint32_t s = std::min(availableWindow, m_tcb->m_segmentSize);
3531 // NextSeg () may have further constrained the segment size
3532 auto maxSizeToSend = static_cast<uint32_t>(nextHigh - next);
3533 s = std::min(s, maxSizeToSend);
3534
3535 // (C.2) If any of the data octets sent in (C.1) are below HighData,
3536 // HighRxt MUST be set to the highest sequence number of the
3537 // retransmitted segment unless NextSeg () rule (4) was
3538 // invoked for this retransmission.
3539 // (C.3) If any of the data octets sent in (C.1) are above HighData,
3540 // HighData must be updated to reflect the transmission of
3541 // previously unsent data.
3542 //
3543 // These steps are done in m_txBuffer with the tags.
3544 if (m_tcb->m_nextTxSequence != next)
3545 {
3546 m_tcb->m_nextTxSequence = next;
3547 }
3548 if (m_tcb->m_bytesInFlight.Get() == 0)
3549 {
3551 }
3552 uint32_t sz = SendDataPacket(m_tcb->m_nextTxSequence, s, withAck);
3553
3554 NS_LOG_LOGIC(" rxwin " << m_rWnd << " segsize " << m_tcb->m_segmentSize
3555 << " highestRxAck " << m_txBuffer->HeadSequence() << " pd->Size "
3556 << m_txBuffer->Size() << " pd->SFS "
3557 << m_txBuffer->SizeFromSequence(m_tcb->m_nextTxSequence));
3558
3559 NS_LOG_DEBUG("cWnd: " << m_tcb->m_cWnd << " total unAck: " << UnAckDataCount()
3560 << " sent seq " << m_tcb->m_nextTxSequence << " size " << sz);
3561 m_tcb->m_nextTxSequence += sz;
3562 ++nPacketsSent;
3563 if (IsPacingEnabled())
3564 {
3565 NS_LOG_INFO("Pacing is enabled");
3566 if (m_pacingTimer.IsExpired())
3567 {
3568 NS_LOG_DEBUG("Current Pacing Rate " << m_tcb->m_pacingRate);
3569 NS_LOG_DEBUG("Timer is in expired state, activate it "
3570 << m_tcb->m_pacingRate.Get().CalculateBytesTxTime(sz));
3571 m_pacingTimer.Schedule(m_tcb->m_pacingRate.Get().CalculateBytesTxTime(sz));
3572 break;
3573 }
3574 }
3575 }
3576
3577 // (C.4) The estimate of the amount of data outstanding in the
3578 // network must be updated by incrementing pipe by the number
3579 // of octets transmitted in (C.1).
3580 //
3581 // Done in BytesInFlight, inside AvailableWindow.
3582 availableWindow = AvailableWindow();
3583
3584 // (C.5) If cwnd - pipe >= 1 SMSS, return to (C.1)
3585 // loop again!
3586 }
3587
3588 if (nPacketsSent > 0)
3589 {
3590 if (!m_sackEnabled)
3591 {
3592 if (!m_limitedTx)
3593 {
3594 // We can't transmit in CA_DISORDER without limitedTx active
3596 }
3597 }
3598
3599 NS_LOG_DEBUG("SendPendingData sent " << nPacketsSent << " segments");
3600 }
3601 else
3602 {
3603 NS_LOG_DEBUG("SendPendingData no segments sent");
3604 }
3605 return nPacketsSent;
3606}
3607
3610{
3611 return m_tcb->m_highTxMark - m_txBuffer->HeadSequence();
3612}
3613
3616{
3617 uint32_t bytesInFlight = m_txBuffer->BytesInFlight();
3618 // Ugly, but we are not modifying the state; m_bytesInFlight is used
3619 // only for tracing purpose.
3620 m_tcb->m_bytesInFlight = bytesInFlight;
3621
3622 NS_LOG_DEBUG("Returning calculated bytesInFlight: " << bytesInFlight);
3623 return bytesInFlight;
3624}
3625
3628{
3629 return std::min(m_rWnd.Get(), m_tcb->m_cWnd.Get());
3630}
3631
3634{
3635 uint32_t win = Window(); // Number of bytes allowed to be outstanding
3636
3637 if (m_sackEnabled && m_fackEnabled && win >= m_tcb->m_ssThresh)
3638 {
3639 // Update awnd (Data sender's estimate of the actual quantity of data outstanding in the
3640 // network)
3641 NS_LOG_DEBUG("FACK is enabled and win >= ssthresh (" << m_tcb->m_ssThresh << ")");
3642
3643 uint32_t sndNxt = (m_tcb->m_highTxMark.Get().GetValue());
3644 uint32_t retranData = m_txBuffer->GetRetransmitsCount();
3645 uint32_t awnd = sndNxt - m_sndFack + retranData;
3646 m_tcb->m_fackAwnd = awnd;
3647
3648 NS_LOG_DEBUG("SndNxt: " << sndNxt << ", SndFack: " << m_sndFack << ", AWND: " << awnd
3649 << ", RetranData :" << retranData);
3650
3651 uint32_t awndDiff = (win > awnd) ? (win - awnd) : 0;
3652 NS_LOG_DEBUG("AWND: " << awnd << ", win: " << win << ", AWND_DIFF: " << awndDiff);
3653 return awndDiff;
3654 }
3655
3656 uint32_t inflight = BytesInFlight();
3657
3658 if (inflight >= win)
3659 {
3660 return 0;
3661 }
3662
3663 return win - inflight;
3664}
3665
3666uint16_t
3668{
3669 NS_LOG_FUNCTION(this << scale);
3670 uint32_t w;
3671
3672 // We don't want to advertise 0 after a FIN is received. So, we just use
3673 // the previous value of the advWnd.
3674 if (m_tcb->m_rxBuffer->GotFin())
3675 {
3676 w = m_advWnd;
3677 }
3678 else
3679 {
3680 NS_ASSERT_MSG(m_tcb->m_rxBuffer->MaxRxSequence() - m_tcb->m_rxBuffer->NextRxSequence() >= 0,
3681 "Unexpected sequence number values");
3682 w = static_cast<uint32_t>(m_tcb->m_rxBuffer->MaxRxSequence() -
3683 m_tcb->m_rxBuffer->NextRxSequence());
3684 }
3685
3686 // Ugly, but we are not modifying the state, that variable
3687 // is used only for tracing purpose.
3688 if (w != m_advWnd)
3689 {
3690 const_cast<TcpSocketBase*>(this)->m_advWnd = w;
3691 }
3692 if (scale)
3693 {
3694 w >>= m_rcvWindShift;
3695 }
3696 if (w > m_maxWinSize)
3697 {
3698 w = m_maxWinSize;
3699 NS_LOG_WARN("Adv window size truncated to "
3700 << m_maxWinSize << "; possibly to avoid overflow of the 16-bit integer");
3701 }
3702 NS_LOG_LOGIC("Returning AdvertisedWindowSize of " << static_cast<uint16_t>(w));
3703 return static_cast<uint16_t>(w);
3704}
3705
3706// Receipt of new packet, put into Rx buffer
3707void
3709{
3710 NS_LOG_FUNCTION(this << tcpHeader);
3711 NS_LOG_DEBUG("Data segment, seq=" << tcpHeader.GetSequenceNumber()
3712 << " pkt size=" << p->GetSize());
3713
3714 // Put into Rx buffer
3715 SequenceNumber32 expectedSeq = m_tcb->m_rxBuffer->NextRxSequence();
3716 if (!m_tcb->m_rxBuffer->Add(p, tcpHeader))
3717 { // Insert failed: No data or RX buffer full
3718 if (m_tcb->m_ecnState == TcpSocketState::ECN_CE_RCVD ||
3720 {
3722 NS_LOG_DEBUG(TcpSocketState::EcnStateName[m_tcb->m_ecnState] << " -> ECN_SENDING_ECE");
3724 }
3725 else
3726 {
3728 }
3729 return;
3730 }
3731 // Notify app to receive if necessary
3732 if (expectedSeq < m_tcb->m_rxBuffer->NextRxSequence())
3733 { // NextRxSeq advanced, we have something to send to the app
3734 if (!m_shutdownRecv)
3735 {
3737 }
3738 // Handle exceptions
3739 if (m_closeNotified)
3740 {
3741 NS_LOG_WARN("Why TCP " << this << " got data after close notification?");
3742 }
3743 // If we received FIN before and now completed all "holes" in rx buffer,
3744 // invoke peer close procedure
3745 if (m_tcb->m_rxBuffer->Finished() && (tcpHeader.GetFlags() & TcpHeader::FIN) == 0)
3746 {
3747 DoPeerClose();
3748 return;
3749 }
3750 }
3751 // Now send a new ACK packet acknowledging all received and delivered data
3752 if (m_tcb->m_rxBuffer->Size() > m_tcb->m_rxBuffer->Available() ||
3753 m_tcb->m_rxBuffer->NextRxSequence() > expectedSeq + p->GetSize())
3754 { // A gap exists in the buffer, or we filled a gap: Always ACK
3756 if (m_tcb->m_ecnState == TcpSocketState::ECN_CE_RCVD ||
3758 {
3760 NS_LOG_DEBUG(TcpSocketState::EcnStateName[m_tcb->m_ecnState] << " -> ECN_SENDING_ECE");
3762 }
3763 else
3764 {
3766 }
3767 }
3768 else
3769 { // In-sequence packet: ACK if delayed ack count allows
3771 {
3772 m_delAckEvent.Cancel();
3773 m_delAckCount = 0;
3775 if (m_tcb->m_ecnState == TcpSocketState::ECN_CE_RCVD ||
3777 {
3778 NS_LOG_DEBUG("Congestion algo " << m_congestionControl->GetName());
3781 << " -> ECN_SENDING_ECE");
3783 }
3784 else
3785 {
3787 }
3788 }
3789 else if (!m_delAckEvent.IsExpired())
3790 {
3792 }
3793 else if (m_delAckEvent.IsExpired())
3794 {
3799 this << " scheduled delayed ACK at "
3801 }
3802 }
3803}
3804
3805Time
3806TcpSocketBase::CalculateRttSample(const TcpHeader& tcpHeader, const RttHistory& rttHistory)
3807{
3808 NS_LOG_FUNCTION(this);
3809 SequenceNumber32 ackSeq = tcpHeader.GetAckNumber();
3810 Time rtt;
3811
3812 if (ackSeq >= (rttHistory.seq + SequenceNumber32(rttHistory.count)))
3813 {
3814 // As per RFC 6298 (Section 3)
3815 // RTT samples MUST NOT be made using segments that were
3816 // retransmitted (and thus for which it is ambiguous whether the reply
3817 // was for the first instance of the packet or a later instance). The
3818 // only case when TCP can safely take RTT samples from retransmitted
3819 // segments is when the TCP timestamp option is employed, since
3820 // the timestamp option removes the ambiguity regarding which instance
3821 // of the data segment triggered the acknowledgment.
3822 if (m_timestampEnabled && tcpHeader.HasOption(TcpOption::TS))
3823 {
3826 rtt = TcpOptionTS::ElapsedTimeFromTsValue(ts->GetEcho());
3827 if (rtt.IsZero())
3828 {
3829 NS_LOG_LOGIC("TcpSocketBase::EstimateRtt - RTT calculated from TcpOption::TS "
3830 "is zero, approximating to 1us.");
3831 NS_LOG_DEBUG("RTT calculated from TcpOption::TS is zero, updating rtt to 1us.");
3832 rtt = MicroSeconds(1);
3833 }
3834 }
3835 else if (!rttHistory.retx)
3836 {
3837 // Elapsed time since the packet was transmitted
3838 rtt = Simulator::Now() - rttHistory.time;
3839 }
3840 }
3841 return rtt;
3842}
3843
3844void
3846{
3847 NS_LOG_FUNCTION(this);
3848 SequenceNumber32 ackSeq = tcpHeader.GetAckNumber();
3849 Time rtt;
3850
3851 // An ack has been received, calculate rtt and log this measurement
3852 // Note we use a linear search (O(n)) for this since for the common
3853 // case the ack'ed packet will be at the head of the list
3854 if (!m_history.empty())
3855 {
3856 RttHistory& earliestTransmittedPktHistory = m_history.front();
3857 rtt = CalculateRttSample(tcpHeader, earliestTransmittedPktHistory);
3858
3859 // Store ACKed packet that has the latest transmission time to update `lastRtt`
3860 RttHistory latestTransmittedPktHistory = earliestTransmittedPktHistory;
3861
3862 // Delete all ACK history with seq <= ack
3863 while (!m_history.empty())
3864 {
3865 RttHistory& rttHistory = m_history.front();
3866 if ((rttHistory.seq + SequenceNumber32(rttHistory.count)) > ackSeq)
3867 {
3868 break; // Done removing
3869 }
3870
3871 latestTransmittedPktHistory = rttHistory;
3872 m_history.pop_front(); // Remove
3873 }
3874
3875 // In case of multiple packets being ACKed in a single acknowledgement, `m_lastRtt` is
3876 // RTT of the last (S)ACKed packet calculated using the data packet with the latest
3877 // transmission time
3878 Time lastRtt = CalculateRttSample(tcpHeader, latestTransmittedPktHistory);
3879 if (!lastRtt.IsZero())
3880 {
3881 NS_LOG_DEBUG("Last RTT sample updated to: " << lastRtt);
3882 m_tcb->m_lastRtt = lastRtt;
3883 }
3884 }
3885
3886 if (!rtt.IsZero())
3887 {
3888 m_rtt->Measurement(rtt); // Log the measurement
3889 // RFC 6298, clause 2.4
3890 m_rto = Max(m_rtt->GetEstimate() + Max(m_clockGranularity, m_rtt->GetVariation() * 4),
3891 m_minRto);
3892 m_tcb->m_srtt = m_rtt->GetEstimate();
3893 m_tcb->m_minRtt = std::min(m_tcb->m_srtt.Get(), m_tcb->m_minRtt);
3894 NS_LOG_INFO(this << m_tcb->m_srtt << m_tcb->m_minRtt);
3895 }
3896}
3897
3898// Called by the ReceivedAck() when new ACK received and by ProcessSynRcvd()
3899// when the three-way handshake completed. This cancels retransmission timer
3900// and advances Tx window
3901void
3902TcpSocketBase::NewAck(const SequenceNumber32& ack, bool resetRTO)
3903{
3904 NS_LOG_FUNCTION(this << ack);
3905
3906 // Reset the data retransmission count. We got a new ACK!
3908
3909 // Update m_sndFack if possible
3910 if (m_fackEnabled && ack.GetValue() > m_sndFack)
3911 {
3912 NS_LOG_INFO(" m_sndFack " << m_sndFack << " updated by normal ack to " << ack.GetValue());
3913 m_sndFack = ack.GetValue();
3914 }
3915
3916 if (m_state != SYN_RCVD && resetRTO)
3917 { // Set RTO unless the ACK is received in SYN_RCVD state
3919 this << " Cancelled ReTxTimeout event which was set to expire at "
3920 << (Simulator::Now() + Simulator::GetDelayLeft(m_retxEvent)).GetSeconds());
3921 m_retxEvent.Cancel();
3922 // On receiving a "New" ack we restart retransmission timer .. RFC 6298
3923 // RFC 6298, clause 2.4
3924 m_rto = Max(m_rtt->GetEstimate() + Max(m_clockGranularity, m_rtt->GetVariation() * 4),
3925 m_minRto);
3926
3927 NS_LOG_LOGIC(this << " Schedule ReTxTimeout at time " << Simulator::Now().GetSeconds()
3928 << " to expire at time "
3929 << (Simulator::Now() + m_rto.Get()).GetSeconds());
3931 }
3932
3933 // Note the highest ACK and tell app to send more
3934 NS_LOG_LOGIC("TCP " << this << " NewAck " << ack << " numberAck "
3935 << (ack - m_txBuffer->HeadSequence())); // Number bytes ack'ed
3936
3937 if (GetTxAvailable() > 0)
3938 {
3940 }
3941 if (ack > m_tcb->m_nextTxSequence)
3942 {
3943 m_tcb->m_nextTxSequence = ack; // If advanced
3944 }
3945 if (m_txBuffer->Size() == 0 && m_state != FIN_WAIT_1 && m_state != CLOSING)
3946 { // No retransmit timer if no data to retransmit
3948 this << " Cancelled ReTxTimeout event which was set to expire at "
3949 << (Simulator::Now() + Simulator::GetDelayLeft(m_retxEvent)).GetSeconds());
3950 m_retxEvent.Cancel();
3951 }
3952}
3953
3954// Retransmit timeout
3955void
3957{
3958 NS_LOG_FUNCTION(this);
3959 NS_LOG_LOGIC(this << " ReTxTimeout Expired at time " << Simulator::Now().GetSeconds());
3960 // If erroneous timeout in closed/timed-wait state, just return
3961 if (m_state == CLOSED || m_state == TIME_WAIT)
3962 {
3963 return;
3964 }
3965
3966 if (m_state == SYN_SENT)
3967 {
3968 NS_ASSERT(m_synCount > 0);
3969 if (m_tcb->m_useEcn == TcpSocketState::On)
3970 {
3972 }
3973 else
3974 {
3976 }
3977 return;
3978 }
3979
3980 // Retransmit non-data packet: Only if in FIN_WAIT_1 or CLOSING state
3981 if (m_txBuffer->Size() == 0)
3982 {
3983 if (m_state == FIN_WAIT_1 || m_state == CLOSING)
3984 { // Must have lost FIN, re-send
3986 }
3987 return;
3988 }
3989
3990 NS_LOG_DEBUG("Checking if Connection is Established");
3991 // If all data are received (non-closing socket and nothing to send), just return
3992 if (m_state <= ESTABLISHED && m_txBuffer->HeadSequence() >= m_tcb->m_highTxMark &&
3993 m_txBuffer->Size() == 0)
3994 {
3995 NS_LOG_DEBUG("Already Sent full data" << m_txBuffer->HeadSequence() << " "
3996 << m_tcb->m_highTxMark);
3997 return;
3998 }
3999
4000 if (m_dataRetrCount == 0)
4001 {
4002 NS_LOG_INFO("No more data retries available. Dropping connection");
4005 return;
4006 }
4007 else
4008 {
4010 }
4011
4012 uint32_t inFlightBeforeRto = BytesInFlight();
4013 bool resetSack = !m_sackEnabled; // Reset SACK information if SACK is not enabled.
4014 // The information in the TcpTxBuffer is guessed, in this case.
4015
4016 // Reset dupAckCount
4017 m_dupAckCount = 0;
4018 if (!m_sackEnabled)
4019 {
4020 m_txBuffer->ResetRenoSack();
4021 }
4022
4023 // From RFC 6675, Section 5.1
4024 // [RFC2018] suggests that a TCP sender SHOULD expunge the SACK
4025 // information gathered from a receiver upon a retransmission timeout
4026 // (RTO) "since the timeout might indicate that the data receiver has
4027 // reneged." Additionally, a TCP sender MUST "ignore prior SACK
4028 // information in determining which data to retransmit."
4029 // It has been suggested that, as long as robust tests for
4030 // reneging are present, an implementation can retain and use SACK
4031 // information across a timeout event [Errata1610].
4032 // The head of the sent list will not be marked as sacked, therefore
4033 // will be retransmitted, if the receiver renegotiate the SACK blocks
4034 // that we received.
4035 m_txBuffer->SetSentListLost(resetSack);
4036
4037 // From RFC 6675, Section 5.1
4038 // If an RTO occurs during loss recovery as specified in this document,
4039 // RecoveryPoint MUST be set to HighData. Further, the new value of
4040 // RecoveryPoint MUST be preserved and the loss recovery algorithm
4041 // outlined in this document MUST be terminated.
4042 m_recover = m_tcb->m_highTxMark;
4043 m_recoverActive = true;
4044
4045 // RFC 6298, clause 2.5, double the timer
4046 Time doubledRto = m_rto + m_rto;
4047 m_rto = Min(doubledRto, Time::FromDouble(60, Time::S));
4048
4049 // Empty RTT history
4050 m_history.clear();
4051
4052 // Please don't reset highTxMark, it is used for retransmission detection
4053
4054 // When a TCP sender detects segment loss using the retransmission timer
4055 // and the given segment has not yet been resent by way of the
4056 // retransmission timer, decrease ssThresh
4057 if (m_tcb->m_congState != TcpSocketState::CA_LOSS || !m_txBuffer->IsHeadRetransmitted())
4058 {
4059 m_tcb->m_ssThresh = m_congestionControl->GetSsThresh(m_tcb, inFlightBeforeRto);
4060 }
4061
4062 // Cwnd set to 1 MSS
4065 m_tcb->m_congState = TcpSocketState::CA_LOSS;
4066 m_tcb->m_cWnd = m_tcb->m_segmentSize;
4067 m_tcb->m_cWndInfl = m_tcb->m_cWnd;
4068
4069 m_pacingTimer.Cancel();
4070
4071 NS_LOG_DEBUG("RTO. Reset cwnd to " << m_tcb->m_cWnd << ", ssthresh to " << m_tcb->m_ssThresh
4072 << ", restart from seqnum " << m_txBuffer->HeadSequence()
4073 << " doubled rto to " << m_rto.Get().GetSeconds() << " s");
4074
4076 "There are some bytes in flight after an RTO: " << BytesInFlight());
4077
4079
4080 NS_ASSERT_MSG(BytesInFlight() <= m_tcb->m_segmentSize,
4081 "In flight (" << BytesInFlight() << ") there is more than one segment ("
4082 << m_tcb->m_segmentSize << ")");
4083}
4084
4085void
4101
4102void
4104{
4105 NS_LOG_FUNCTION(this);
4106
4107 m_lastAckEvent.Cancel();
4108 if (m_state == LAST_ACK)
4109 {
4110 if (m_dataRetrCount == 0)
4111 {
4112 NS_LOG_INFO("LAST-ACK: No more data retries available. Dropping connection");
4115 return;
4116 }
4119 NS_LOG_LOGIC("TcpSocketBase " << this << " rescheduling LATO1");
4120 Time lastRto = m_rtt->GetEstimate() + Max(m_clockGranularity, m_rtt->GetVariation() * 4);
4122 }
4123}
4124
4125// Send 1-byte data to probe for the window size at the receiver when
4126// the local knowledge tells that the receiver has zero window size
4127// C.f.: RFC793 p.42, RFC1112 sec.4.2.2.17
4128void
4130{
4131 NS_LOG_LOGIC("PersistTimeout expired at " << Simulator::Now().GetSeconds());
4133 std::min(Seconds(60), Time(2 * m_persistTimeout)); // max persist timeout = 60s
4134 Ptr<Packet> p = m_txBuffer->CopyFromSequence(1, m_tcb->m_nextTxSequence)->GetPacketCopy();
4135 m_txBuffer->ResetLastSegmentSent();
4136 TcpHeader tcpHeader;
4137 tcpHeader.SetSequenceNumber(m_tcb->m_nextTxSequence);
4138 tcpHeader.SetAckNumber(m_tcb->m_rxBuffer->NextRxSequence());
4140 if (m_endPoint != nullptr)
4141 {
4142 tcpHeader.SetSourcePort(m_endPoint->GetLocalPort());
4143 tcpHeader.SetDestinationPort(m_endPoint->GetPeerPort());
4144 }
4145 else
4146 {
4147 tcpHeader.SetSourcePort(m_endPoint6->GetLocalPort());
4148 tcpHeader.SetDestinationPort(m_endPoint6->GetPeerPort());
4149 }
4150 AddOptions(tcpHeader);
4151 // Send a packet tag for setting ECT bits in IP header
4152 if (m_tcb->m_ecnState != TcpSocketState::ECN_DISABLED)
4153 {
4155 }
4156 m_txTrace(p, tcpHeader, this);
4157
4158 if (m_endPoint != nullptr)
4159 {
4160 m_tcp->SendPacket(p,
4161 tcpHeader,
4162 m_endPoint->GetLocalAddress(),
4163 m_endPoint->GetPeerAddress(),
4165 }
4166 else
4167 {
4168 m_tcp->SendPacket(p,
4169 tcpHeader,
4170 m_endPoint6->GetLocalAddress(),
4171 m_endPoint6->GetPeerAddress(),
4173 }
4174
4175 NS_LOG_LOGIC("Schedule persist timeout at time "
4176 << Simulator::Now().GetSeconds() << " to expire at time "
4177 << (Simulator::Now() + m_persistTimeout).GetSeconds());
4179}
4180
4181void
4183{
4184 NS_LOG_FUNCTION(this);
4185 bool res;
4186 SequenceNumber32 seq;
4187 SequenceNumber32 seqHigh;
4188 uint32_t maxSizeToSend;
4189
4190 // Find the first segment marked as lost and not retransmitted. With Reno,
4191 // that should be the head
4192 res = m_txBuffer->NextSeg(&seq, &seqHigh, false);
4193 if (!res)
4194 {
4195 // We have already retransmitted the head. However, we still received
4196 // three dupacks, or the RTO expired, but no data to transmit.
4197 // Therefore, re-send again the head.
4198 seq = m_txBuffer->HeadSequence();
4199 maxSizeToSend = m_tcb->m_segmentSize;
4200 }
4201 else
4202 {
4203 // NextSeg() may constrain the segment size when res is true
4204 maxSizeToSend = static_cast<uint32_t>(seqHigh - seq);
4205 }
4206 NS_ASSERT(m_sackEnabled || seq == m_txBuffer->HeadSequence());
4207
4208 NS_LOG_INFO("Retransmitting " << seq);
4209 // Update the trace and retransmit the segment
4210 m_tcb->m_nextTxSequence = seq;
4211 uint32_t sz = SendDataPacket(m_tcb->m_nextTxSequence, maxSizeToSend, true);
4212
4213 NS_ASSERT(sz > 0);
4214}
4215
4216void
4218{
4219 m_retxEvent.Cancel();
4220 m_persistEvent.Cancel();
4221 m_delAckEvent.Cancel();
4222 m_lastAckEvent.Cancel();
4223 m_timewaitEvent.Cancel();
4224 m_sendPendingDataEvent.Cancel();
4225 m_pacingTimer.Cancel();
4226}
4227
4228/* Move TCP to Time_Wait state and schedule a transition to Closed state */
4229void
4231{
4232 NS_LOG_DEBUG(TcpStateName[m_state] << " -> TIME_WAIT");
4235 if (!m_closeNotified)
4236 {
4237 // Technically the connection is not fully closed, but we notify now
4238 // because an implementation (real socket) would behave as if closed.
4239 // Notify normal close when entering TIME_WAIT or leaving LAST_ACK.
4241 m_closeNotified = true;
4242 }
4243 // Move from TIME_WAIT to CLOSED after 2*MSL. Max segment lifetime is 2 min
4244 // according to RFC793, p.28
4246}
4247
4248/* Below are the attribute get/set functions */
4249
4250void
4252{
4253 NS_LOG_FUNCTION(this << size);
4254 m_txBuffer->SetMaxBufferSize(size);
4255}
4256
4259{
4260 return m_txBuffer->MaxBufferSize();
4261}
4262
4265{
4266 return m_sndFack;
4267}
4268
4269bool
4271{
4272 return m_fackEnabled;
4273}
4274
4275void
4277{
4278 NS_LOG_FUNCTION(this << size);
4279 uint32_t oldSize = GetRcvBufSize();
4280
4281 m_tcb->m_rxBuffer->SetMaxBufferSize(size);
4282
4283 /* The size has (manually) increased. Actively inform the other end to prevent
4284 * stale zero-window states.
4285 */
4286 if (oldSize < size && m_connected)
4287 {
4288 if (m_tcb->m_ecnState == TcpSocketState::ECN_CE_RCVD ||
4290 {
4292 NS_LOG_DEBUG(TcpSocketState::EcnStateName[m_tcb->m_ecnState] << " -> ECN_SENDING_ECE");
4294 }
4295 else
4296 {
4298 }
4299 }
4300}
4301
4304{
4305 return m_tcb->m_rxBuffer->MaxBufferSize();
4306}
4307
4308void
4310{
4311 NS_LOG_FUNCTION(this << size);
4312 m_tcb->m_segmentSize = size;
4313 m_txBuffer->SetSegmentSize(size);
4314
4315 NS_ABORT_MSG_UNLESS(m_state == CLOSED, "Cannot change segment size dynamically.");
4316}
4317
4320{
4321 return m_tcb->m_segmentSize;
4322}
4323
4324void
4330
4331Time
4333{
4334 return m_cnTimeout;
4335}
4336
4337void
4339{
4340 NS_LOG_FUNCTION(this << count);
4341 m_synRetries = count;
4342}
4343
4346{
4347 return m_synRetries;
4348}
4349
4350void
4352{
4353 NS_LOG_FUNCTION(this << retries);
4354 m_dataRetries = retries;
4355}
4356
4359{
4360 NS_LOG_FUNCTION(this);
4361 return m_dataRetries;
4362}
4363
4364void
4370
4371Time
4373{
4374 return m_delAckTimeout;
4375}
4376
4377void
4379{
4380 NS_LOG_FUNCTION(this << count);
4381 m_delAckMaxCount = count;
4382}
4383
4389
4390void
4392{
4393 NS_LOG_FUNCTION(this << noDelay);
4394 m_noDelay = noDelay;
4395}
4396
4397bool
4399{
4400 return m_noDelay;
4401}
4402
4403void
4409
4410Time
4415
4416bool
4418{
4419 // Broadcast is not implemented. Return true only if allowBroadcast==false
4420 return (!allowBroadcast);
4421}
4422
4423bool
4425{
4426 return false;
4427}
4428
4429void
4431{
4432 NS_LOG_FUNCTION(this << header);
4433
4435 {
4436 AddOptionTimestamp(header);
4437 }
4438}
4439
4440void
4442{
4443 NS_LOG_FUNCTION(this << option);
4444
4446
4447 // In naming, we do the contrary of RFC 1323. The received scaling factor
4448 // is Rcv.Wind.Scale (and not Snd.Wind.Scale)
4449 m_sndWindShift = ws->GetScale();
4450
4451 if (m_sndWindShift > 14)
4452 {
4453 NS_LOG_WARN("Possible error; m_sndWindShift exceeds 14: " << m_sndWindShift);
4454 m_sndWindShift = 14;
4455 }
4456
4457 NS_LOG_INFO(m_node->GetId() << " Received a scale factor of "
4458 << static_cast<int>(m_sndWindShift));
4459}
4460
4461uint8_t
4463{
4464 NS_LOG_FUNCTION(this);
4465 uint32_t maxSpace = m_tcb->m_rxBuffer->MaxBufferSize();
4466 uint8_t scale = 0;
4467
4468 while (maxSpace > m_maxWinSize)
4469 {
4470 maxSpace = maxSpace >> 1;
4471 ++scale;
4472 }
4473
4474 if (scale > 14)
4475 {
4476 NS_LOG_WARN("Possible error; scale exceeds 14: " << scale);
4477 scale = 14;
4478 }
4479
4480 NS_LOG_INFO("Node " << m_node->GetId() << " calculated wscale factor of "
4481 << static_cast<int>(scale) << " for buffer size "
4482 << m_tcb->m_rxBuffer->MaxBufferSize());
4483 return scale;
4484}
4485
4486void
4488{
4489 NS_LOG_FUNCTION(this << header);
4490 NS_ASSERT(header.GetFlags() & TcpHeader::SYN);
4491
4493
4494 // In naming, we do the contrary of RFC 1323. The sended scaling factor
4495 // is Snd.Wind.Scale (and not Rcv.Wind.Scale)
4496
4498 option->SetScale(m_rcvWindShift);
4499
4500 header.AppendOption(option);
4501
4502 NS_LOG_INFO(m_node->GetId() << " Send a scaling factor of "
4503 << static_cast<int>(m_rcvWindShift));
4504}
4505
4508{
4509 NS_LOG_FUNCTION(this << option);
4510
4512
4513 // Update m_sndFack with the highest sequence number acknowledged from the SACK blocks
4514 if (m_fackEnabled)
4515 {
4516 for (const auto& [leftEdge, rightEdge] : s->GetSackList())
4517 {
4518 if (rightEdge.GetValue() > m_sndFack)
4519 {
4520 NS_LOG_INFO(" m_sndFack updated from " << m_sndFack << " to "
4521 << rightEdge.GetValue());
4522 m_sndFack = rightEdge.GetValue();
4523 }
4524 }
4525 }
4526
4527 return m_txBuffer->Update(s->GetSackList(), MakeCallback(&TcpRateOps::SkbDelivered, m_rateOps));
4528}
4529
4530void
4532{
4533 NS_LOG_FUNCTION(this << option);
4534
4536
4537 NS_ASSERT(m_sackEnabled == true);
4538 NS_LOG_INFO(m_node->GetId() << " Received a SACK_PERMITTED option " << s);
4539}
4540
4541void
4543{
4544 NS_LOG_FUNCTION(this << header);
4545 NS_ASSERT(header.GetFlags() & TcpHeader::SYN);
4546
4548 header.AppendOption(option);
4549 NS_LOG_INFO(m_node->GetId() << " Add option SACK-PERMITTED");
4550}
4551
4552void
4554{
4555 NS_LOG_FUNCTION(this << header);
4556
4557 // Calculate the number of SACK blocks allowed in this packet
4558 uint8_t optionLenAvail = header.GetMaxOptionLength() - header.GetOptionLength();
4559 uint8_t allowedSackBlocks = (optionLenAvail - 2) / 8;
4560
4561 TcpOptionSack::SackList sackList = m_tcb->m_rxBuffer->GetSackList();
4562 if (allowedSackBlocks == 0 || sackList.empty())
4563 {
4564 NS_LOG_LOGIC("No space available or sack list empty, not adding sack blocks");
4565 return;
4566 }
4567
4568 // Append the allowed number of SACK blocks
4570
4571 for (auto i = sackList.begin(); allowedSackBlocks > 0 && i != sackList.end(); ++i)
4572 {
4573 option->AddSackBlock(*i);
4574 allowedSackBlocks--;
4575 }
4576
4577 header.AppendOption(option);
4578 NS_LOG_INFO(m_node->GetId() << " Add option SACK " << *option);
4579}
4580
4581void
4583 const SequenceNumber32& seq)
4584{
4585 NS_LOG_FUNCTION(this << option);
4586
4588
4589 // This is valid only when no overflow occurs. It happens
4590 // when a connection last longer than 50 days.
4591 if (m_tcb->m_rcvTimestampValue > ts->GetTimestamp())
4592 {
4593 // Do not save a smaller timestamp (probably there is reordering)
4594 return;
4595 }
4596
4597 m_tcb->m_rcvTimestampValue = ts->GetTimestamp();
4598 m_tcb->m_rcvTimestampEchoReply = ts->GetEcho();
4599
4600 if (seq == m_tcb->m_rxBuffer->NextRxSequence() && seq <= m_highTxAck)
4601 {
4602 m_timestampToEcho = ts->GetTimestamp();
4603 }
4604
4605 NS_LOG_INFO(m_node->GetId() << " Got timestamp=" << m_timestampToEcho
4606 << " and Echo=" << ts->GetEcho());
4607}
4608
4609void
4611{
4612 NS_LOG_FUNCTION(this << header);
4613
4615
4616 option->SetTimestamp(TcpOptionTS::NowToTsValue());
4617 option->SetEcho(m_timestampToEcho);
4618
4619 header.AppendOption(option);
4620 NS_LOG_INFO(m_node->GetId() << " Add option TS, ts=" << option->GetTimestamp()
4621 << " echo=" << m_timestampToEcho);
4622}
4623
4624void
4626{
4627 NS_LOG_FUNCTION(this << header);
4628 // If the connection is not established, the window size is always
4629 // updated
4630 uint32_t receivedWindow = header.GetWindowSize();
4631 receivedWindow <<= m_sndWindShift;
4632 NS_LOG_INFO("Received (scaled) window is " << receivedWindow << " bytes");
4633 if (m_state < ESTABLISHED)
4634 {
4635 m_rWnd = receivedWindow;
4636 NS_LOG_LOGIC("State less than ESTABLISHED; updating rWnd to " << m_rWnd);
4637 return;
4638 }
4639
4640 // Test for conditions that allow updating of the window
4641 // 1) segment contains new data (advancing the right edge of the receive
4642 // buffer),
4643 // 2) segment does not contain new data but the segment acks new data
4644 // (highest sequence number acked advances), or
4645 // 3) the advertised window is larger than the current send window
4646 bool update = false;
4647 if (header.GetAckNumber() == m_highRxAckMark && receivedWindow > m_rWnd)
4648 {
4649 // right edge of the send window is increased (window update)
4650 update = true;
4651 }
4652 if (header.GetAckNumber() > m_highRxAckMark)
4653 {
4654 m_highRxAckMark = header.GetAckNumber();
4655 update = true;
4656 }
4657 if (header.GetSequenceNumber() > m_highRxMark)
4658 {
4660 update = true;
4661 }
4662 if (update)
4663 {
4664 m_rWnd = receivedWindow;
4665 NS_LOG_LOGIC("updating rWnd to " << m_rWnd);
4666 }
4667}
4668
4669void
4671{
4672 NS_LOG_FUNCTION(this << minRto);
4673 m_minRto = minRto;
4674}
4675
4676Time
4678{
4679 return m_minRto;
4680}
4681
4682void
4684{
4685 NS_LOG_FUNCTION(this << clockGranularity);
4686 m_clockGranularity = clockGranularity;
4687}
4688
4689Time
4694
4697{
4698 return m_txBuffer;
4699}
4700
4703{
4704 return m_tcb->m_rxBuffer;
4705}
4706
4707void
4709{
4710 m_retxThresh = retxThresh;
4711 m_txBuffer->SetDupAckThresh(retxThresh);
4712}
4713
4714void
4716{
4717 m_pacingRateTrace(oldValue, newValue);
4718}
4719
4720void
4722{
4723 m_cWndTrace(oldValue, newValue);
4724}
4725
4726void
4728{
4729 m_cWndInflTrace(oldValue, newValue);
4730}
4731
4732void
4734{
4735 m_ssThTrace(oldValue, newValue);
4736}
4737
4738void
4744
4745void
4747 TcpSocketState::EcnState_t newValue) const
4748{
4749 m_ecnStateTrace(oldValue, newValue);
4750}
4751
4752void
4754
4755{
4756 m_nextTxSequenceTrace(oldValue, newValue);
4757}
4758
4759void
4761{
4762 m_highTxMarkTrace(oldValue, newValue);
4763}
4764
4765void
4767{
4768 m_bytesInFlightTrace(oldValue, newValue);
4769}
4770
4771void
4773{
4774 m_fackAwndTrace(oldValue, newValue);
4775}
4776
4777void
4778TcpSocketBase::UpdateRtt(Time oldValue, Time newValue) const
4779{
4780 m_srttTrace(oldValue, newValue);
4781}
4782
4783void
4784TcpSocketBase::UpdateLastRtt(Time oldValue, Time newValue) const
4785{
4786 m_lastRttTrace(oldValue, newValue);
4787}
4788
4789void
4797
4798void
4800{
4801 NS_LOG_FUNCTION(this << recovery);
4802 m_recoveryOps = recovery;
4803}
4804
4807{
4808 return CopyObject<TcpSocketBase>(this);
4809}
4810
4813{
4814 if (a > b)
4815 {
4816 return a - b;
4817 }
4818
4819 return 0;
4820}
4821
4822void
4824{
4825 NS_LOG_FUNCTION(this);
4826 NS_LOG_INFO("Performing Pacing");
4828}
4829
4830bool
4832{
4833 if (!m_tcb->m_pacing)
4834 {
4835 return false;
4836 }
4837 else
4838 {
4839 if (m_tcb->m_paceInitialWindow)
4840 {
4841 return true;
4842 }
4843 SequenceNumber32 highTxMark = m_tcb->m_highTxMark; // cast traced value
4844 if (highTxMark.GetValue() > (GetInitialCwnd() * m_tcb->m_segmentSize))
4845 {
4846 return true;
4847 }
4848 }
4849 return false;
4850}
4851
4852void
4854{
4855 NS_LOG_FUNCTION(this << m_tcb);
4856
4857 // According to Linux, set base pacing rate to (cwnd * mss) / srtt
4858 //
4859 // In (early) slow start, multiply base by the slow start factor.
4860 // In late slow start and congestion avoidance, multiply base by
4861 // the congestion avoidance factor.
4862 // Comment from Linux code regarding early/late slow start:
4863 // Normal Slow Start condition is (tp->snd_cwnd < tp->snd_ssthresh)
4864 // If snd_cwnd >= (tp->snd_ssthresh / 2), we are approaching
4865 // end of slow start and should slow down.
4866
4867 // Similar to Linux, do not update pacing rate here if the
4868 // congestion control implements TcpCongestionOps::CongControl ()
4869 if (m_congestionControl->HasCongControl() || !m_tcb->m_pacing)
4870 {
4871 return;
4872 }
4873
4874 double factor;
4875 if (m_tcb->m_cWnd < m_tcb->m_ssThresh / 2)
4876 {
4877 NS_LOG_DEBUG("Pacing according to slow start factor; " << m_tcb->m_cWnd << " "
4878 << m_tcb->m_ssThresh);
4879 factor = static_cast<double>(m_tcb->m_pacingSsRatio) / 100;
4880 }
4881 else
4882 {
4883 NS_LOG_DEBUG("Pacing according to congestion avoidance factor; " << m_tcb->m_cWnd << " "
4884 << m_tcb->m_ssThresh);
4885 factor = static_cast<double>(m_tcb->m_pacingCaRatio) / 100;
4886 }
4887 Time srtt = m_tcb->m_srtt.Get(); // Get underlying Time value
4888 NS_LOG_DEBUG("Smoothed RTT is " << srtt.GetSeconds());
4889
4890 // Multiply by 8 to convert from bytes per second to bits per second
4891 DataRate pacingRate((std::max(m_tcb->m_cWnd, m_tcb->m_bytesInFlight) * 8 * factor) /
4892 srtt.GetSeconds());
4893 if (pacingRate < m_tcb->m_maxPacingRate)
4894 {
4895 NS_LOG_DEBUG("Pacing rate updated to: " << pacingRate);
4896 m_tcb->m_pacingRate = pacingRate;
4897 }
4898 else
4899 {
4900 NS_LOG_DEBUG("Pacing capped by max pacing rate: " << m_tcb->m_maxPacingRate);
4901 m_tcb->m_pacingRate = m_tcb->m_maxPacingRate;
4902 }
4903}
4904
4905void
4907{
4908 NS_LOG_FUNCTION(this << pacing);
4909 m_tcb->m_pacing = pacing;
4910}
4911
4912void
4914{
4915 NS_LOG_FUNCTION(this << paceWindow);
4916 m_tcb->m_paceInitialWindow = paceWindow;
4917}
4918
4919bool
4921{
4922 NS_LOG_FUNCTION(this << packetType);
4923 NS_ASSERT_MSG(packetType != TcpPacketType_t::INVALID, "Invalid TCP packet type");
4924 if (m_tcb->m_ecnState == TcpSocketState::ECN_DISABLED)
4925 {
4926 return false;
4927 }
4928
4929 NS_ABORT_MSG_IF(!ECN_RESTRICTION_MAP.contains(std::make_pair(packetType, m_tcb->m_ecnMode)),
4930 "Invalid packetType and ecnMode");
4931
4932 return ECN_RESTRICTION_MAP.at(std::make_pair(packetType, m_tcb->m_ecnMode));
4933}
4934
4935void
4937{
4938 NS_LOG_FUNCTION(this << useEcn);
4939 m_tcb->m_useEcn = useEcn;
4940}
4941
4942void
4944{
4945 NS_LOG_FUNCTION(this << useAbe);
4946 if (m_tcb->m_useEcn == TcpSocketState::Off && useAbe)
4947 {
4948 NS_LOG_INFO("Enabling ECN along with ABE");
4949 m_tcb->m_useEcn = TcpSocketState::On;
4950 }
4951 m_tcb->m_abeEnabled = useAbe;
4952}
4953
4954bool
4956{
4957 return m_tcb->m_abeEnabled;
4958}
4959
4962{
4963 return m_rWnd.Get();
4964}
4965
4968{
4969 return m_highRxAckMark.Get();
4970}
4971
4972// RttHistory methods
4974 : seq(s),
4975 count(c),
4976 time(t),
4977 retx(false)
4978{
4979}
4980
4982 : seq(h.seq),
4983 count(h.count),
4984 time(h.time),
4985 retx(h.retx)
4986{
4987}
4988
4989} // namespace ns3
#define Max(a, b)
#define Min(a, b)
a polymophic address class
Definition address.h:114
Callback template class.
Definition callback.h:428
Class for representing data rates.
Definition data-rate.h:78
This class can be used to hold variables of floating point type such as 'double' or 'float'.
Definition double.h:31
Hold variables of type enum.
Definition enum.h:52
An Inet6 address class.
static Inet6SocketAddress ConvertFrom(const Address &addr)
Convert the address to a InetSocketAddress.
uint16_t GetPort() const
Get the port.
static bool IsMatchingType(const Address &addr)
If the address match.
Ipv6Address GetIpv6() const
Get the IPv6 address.
an Inet address class
static bool IsMatchingType(const Address &address)
Ipv4Address GetIpv4() const
static InetSocketAddress ConvertFrom(const Address &address)
Returns an InetSocketAddress which corresponds to the input Address.
Ipv4 addresses are stored in host order in this class.
static Ipv4Address GetZero()
static Ipv4Address GetAny()
Packet header for IPv4.
Definition ipv4-header.h:23
void SetDestination(Ipv4Address destination)
Ipv4Address GetSource() const
EcnType GetEcn() const
Ipv4Address GetDestination() const
Access to the IPv4 forwarding table, interfaces, and configuration.
Definition ipv4.h:69
Describes an IPv6 address.
static Ipv6Address GetAny()
Get the "any" (::) Ipv6Address.
bool IsIpv4MappedAddress() const
If the address is an IPv4-mapped address.
Ipv4Address GetIpv4MappedAddress() const
Return the Ipv4 address.
Packet header for IPv6.
Definition ipv6-header.h:24
void SetDestination(Ipv6Address dst)
Set the "Destination address" field.
Ipv6Address GetDestination() const
Get the "Destination address" field.
EcnType GetEcn() const
Ipv6Address GetSource() const
Get the "Source address" field.
IPv6 layer implementation.
AttributeValue implementation for Pointer.
Definition pointer.h:37
Smart pointer class similar to boost::intrusive_ptr.
Definition ptr.h:70
Helper class to store RTT measurements.
uint32_t count
Number of bytes sent.
RttHistory(SequenceNumber32 s, uint32_t c, Time t)
Constructor - builds an RttHistory with the given parameters.
bool retx
True if this has been retransmitted.
Time time
Time this one was sent.
SequenceNumber32 seq
First sequence number in packet sent.
constexpr NUMERIC_TYPE GetValue() const
Extracts the numeric value of the sequence number.
static EventId Schedule(const Time &delay, FUNC f, Ts &&... args)
Schedule an event to expire after delay.
Definition simulator.h:580
static Time Now()
Return the current simulation virtual time.
Definition simulator.cc:191
static EventId ScheduleNow(FUNC f, Ts &&... args)
Schedule an event to expire Now.
Definition simulator.h:614
static Time GetDelayLeft(const EventId &id)
Get the remaining time until this event will execute.
Definition simulator.cc:200
Ptr< NetDevice > GetBoundNetDevice()
Returns socket's bound NetDevice, if any.
Definition socket.cc:336
Ptr< Packet > Recv()
Read a single packet from the socket.
Definition socket.cc:163
void SetConnectCallback(Callback< void, Ptr< Socket > > connectionSucceeded, Callback< void, Ptr< Socket > > connectionFailed)
Specify callbacks to allow the caller to determine if the connection succeeds of fails.
Definition socket.cc:76
bool IsManualIpTtl() const
Checks if the socket has a specific IPv4 TTL set.
Definition socket.cc:363
void NotifySend(uint32_t spaceAvailable)
Notify through the callback (if set) that some data have been sent.
Definition socket.cc:281
void NotifyNewConnectionCreated(Ptr< Socket > socket, const Address &from)
Notify through the callback (if set) that a new connection has been created.
Definition socket.cc:261
virtual uint8_t GetIpTtl() const
Query the value of IP Time to Live field of this socket.
Definition socket.cc:506
bool NotifyConnectionRequest(const Address &from)
Notify through the callback (if set) that an incoming connection is being requested by a remote host.
Definition socket.cc:243
uint8_t GetIpTos() const
Query the value of IP Type of Service of this socket.
Definition socket.cc:439
SocketType
Enumeration of the possible socket types.
Definition socket.h:96
@ NS3_SOCK_STREAM
Definition socket.h:97
void SetDataSentCallback(Callback< void, Ptr< Socket >, uint32_t > dataSent)
Notify application when a packet has been sent from transport protocol (non-standard socket call).
Definition socket.cc:103
void SetSendCallback(Callback< void, Ptr< Socket >, uint32_t > sendCb)
Notify application when space in transmit buffer is added.
Definition socket.cc:110
void NotifyErrorClose()
Notify through the callback (if set) that the connection has been closed due to an error.
Definition socket.cc:233
void NotifyDataRecv()
Notify through the callback (if set) that some data have been received.
Definition socket.cc:291
Ptr< NetDevice > m_boundnetdevice
the device this socket is bound to (might be null).
Definition socket.h:1071
virtual void BindToNetDevice(Ptr< NetDevice > netdevice)
Bind a socket to specific device.
Definition socket.cc:316
void NotifyNormalClose()
Notify through the callback (if set) that the connection has been closed.
Definition socket.cc:223
virtual uint8_t GetIpv6HopLimit() const
Query the value of IP Hop Limit field of this socket.
Definition socket.cc:531
void SetRecvCallback(Callback< void, Ptr< Socket > > receivedData)
Notify application when new data is available to be read.
Definition socket.cc:117
SocketErrno
Enumeration of the possible errors returned by a socket.
Definition socket.h:73
@ ERROR_SHUTDOWN
Definition socket.h:79
@ ERROR_INVAL
Definition socket.h:82
@ ERROR_ADDRINUSE
Definition socket.h:87
@ ERROR_ADDRNOTAVAIL
Definition socket.h:86
@ ERROR_NOTCONN
Definition socket.h:76
@ ERROR_MSGSIZE
Definition socket.h:77
void NotifyDataSent(uint32_t size)
Notify through the callback (if set) that some data have been sent.
Definition socket.cc:271
void NotifyConnectionSucceeded()
Notify through the callback (if set) that the connection has been established.
Definition socket.cc:203
uint8_t GetPriority() const
Query the priority value of this socket.
Definition socket.cc:382
uint8_t GetIpv6Tclass() const
Query the value of IPv6 Traffic Class field of this socket.
Definition socket.cc:481
bool IsManualIpv6HopLimit() const
Checks if the socket has a specific IPv6 Hop Limit set.
Definition socket.cc:369
bool IsManualIpv6Tclass() const
Checks if the socket has a specific IPv6 Tclass set.
Definition socket.cc:357
void NotifyConnectionFailed()
Notify through the callback (if set) that the connection has not been established due to an error.
Definition socket.cc:213
indicates whether the socket has IP_TOS set.
Definition socket.h:1261
void SetTos(uint8_t tos)
Set the tag's TOS.
Definition socket.cc:787
This class implements a tag that carries the socket-specific TTL of a packet to the IP layer.
Definition socket.h:1114
void SetTtl(uint8_t ttl)
Set the tag's TTL.
Definition socket.cc:593
This class implements a tag that carries the socket-specific HOPLIMIT of a packet to the IPv6 layer.
Definition socket.h:1162
void SetHopLimit(uint8_t hopLimit)
Set the tag's Hop Limit.
Definition socket.cc:657
indicates whether the socket has IPV6_TCLASS set.
Definition socket.h:1356
void SetTclass(uint8_t tclass)
Set the tag's Tclass.
Definition socket.cc:899
indicates whether the socket has a priority set.
Definition socket.h:1308
void SetPriority(uint8_t priority)
Set the tag's priority.
Definition socket.cc:843
Header for the Transmission Control Protocol.
Definition tcp-header.h:36
void SetDestinationPort(uint16_t port)
Set the destination port.
Definition tcp-header.cc:59
void SetSequenceNumber(SequenceNumber32 sequenceNumber)
Set the sequence Number.
Definition tcp-header.cc:65
SequenceNumber32 GetSequenceNumber() const
Get the sequence number.
uint8_t GetMaxOptionLength() const
Get maximum option length.
uint16_t GetDestinationPort() const
Get the destination port.
Ptr< const TcpOption > GetOption(uint8_t kind) const
Get the option specified.
void SetFlags(uint8_t flags)
Set flags of the header.
Definition tcp-header.cc:77
void SetWindowSize(uint16_t windowSize)
Set the window size.
Definition tcp-header.cc:83
const TcpOptionList & GetOptionList() const
Get the list of option in this header.
uint16_t GetWindowSize() const
Get the window size.
uint8_t GetOptionLength() const
Get the total length of appended options.
bool AppendOption(Ptr< const TcpOption > option)
Append an option to the TCP header.
static std::string FlagsToString(uint8_t flags, const std::string &delimiter="|")
Converts an integer into a human readable list of Tcp flags.
Definition tcp-header.cc:28
bool HasOption(uint8_t kind) const
Check if the header has the option specified.
uint16_t GetSourcePort() const
Get the source port.
Definition tcp-header.cc:95
void SetSourcePort(uint16_t port)
Set the source port.
Definition tcp-header.cc:53
void SetAckNumber(SequenceNumber32 ackNumber)
Set the ACK number.
Definition tcp-header.cc:71
uint8_t GetFlags() const
Get the flags.
SequenceNumber32 GetAckNumber() const
Get the ACK number.
@ SACKPERMITTED
SACKPERMITTED.
Definition tcp-option.h:49
@ WINSCALE
WINSCALE.
Definition tcp-option.h:48
std::list< SackBlock > SackList
SACK list definition.
static Time ElapsedTimeFromTsValue(uint32_t echoTime)
Estimate the Time elapsed from a TS echo value.
static uint32_t NowToTsValue()
Return an uint32_t value which represent "now".
virtual void SkbDelivered(TcpTxItem *skb)=0
Update the Rate information after an item is received.
A base class for implementation of a stream socket using TCP.
void AddOptionSack(TcpHeader &header)
Add the SACK option to the header.
int GetSockName(Address &address) const override
Get socket address.
Time m_persistTimeout
Time between sending 1-byte probes.
uint16_t m_maxWinSize
Maximum window size to advertise.
uint8_t m_rcvWindShift
Window shift to apply to outgoing segments.
void SetPaceInitialWindow(bool paceWindow)
Enable or disable pacing of the initial window.
int Bind6() override
Allocate a local IPv6 endpoint for this socket.
void TimeWait()
Move from CLOSING or FIN_WAIT_2 to TIME_WAIT state.
Ptr< TcpCongestionOps > m_congestionControl
Congestion control.
void AddSocketTags(const Ptr< Packet > &p, bool isEct) const
Add Tags for the Socket.
Ptr< TcpTxBuffer > GetTxBuffer() const
Get a pointer to the Tx buffer.
int SetupEndpoint()
Configure the endpoint to a local address.
virtual void LastAckTimeout()
Timeout at LAST_ACK, close the connection.
void ProcessEstablished(Ptr< Packet > packet, const TcpHeader &tcpHeader)
Received a packet upon ESTABLISHED state.
Time m_minRto
minimum value of the Retransmit timeout
uint32_t SendPendingData(bool withAck=false)
Send as much pending data as possible according to the Tx window.
TracedValue< uint32_t > m_advWnd
Advertised Window size.
TracedCallback< Ptr< const Packet >, const TcpHeader &, Ptr< const TcpSocketBase > > m_txTrace
Trace of transmitted packets.
SequenceNumber32 m_recover
Previous highest Tx seqnum for fast recovery (set it to initial seq number).
bool m_recoverActive
Whether "m_recover" has been set/activated It is used to avoid comparing with the old m_recover value...
void DoRetransmit()
Retransmit the first segment marked as lost, without considering available window nor pacing.
bool CheckNoEcn(uint8_t tos) const
Checks if TOS has no ECN codepoints.
virtual void SetNode(Ptr< Node > node)
Set the associated node.
int ShutdownRecv() override
uint8_t m_sndWindShift
Window shift to apply to incoming segments.
Ptr< TcpL4Protocol > m_tcp
the associated TCP L4 protocol
Ptr< TcpSocketState > m_tcb
Congestion control information.
bool GetAllowBroadcast() const override
Query whether broadcast datagram transmissions are allowed.
void UpdateSsThresh(uint32_t oldValue, uint32_t newValue) const
Callback function to hook to TcpSocketState slow start threshold.
TracedCallback< Ptr< const Packet >, const TcpHeader &, Ptr< const TcpSocketBase > > m_rxTrace
Trace of received packets.
virtual void SetTcp(Ptr< TcpL4Protocol > tcp)
Set the associated TCP L4 protocol.
void EnterRecovery(uint32_t currentDelivered)
Enter the CA_RECOVERY, and retransmit the head.
Time GetMinRto() const
Get the Minimum RTO.
void ProcessSynSent(Ptr< Packet > packet, const TcpHeader &tcpHeader)
Received a packet upon SYN_SENT.
void ForwardUp(Ptr< Packet > packet, Ipv4Header header, uint16_t port, Ptr< Ipv4Interface > incomingInterface)
Called by the L3 protocol when it received a packet to pass on to TCP.
bool SetAllowBroadcast(bool allowBroadcast) override
Configure whether broadcast datagram transmissions are allowed.
void CancelAllTimers()
Cancel all timer when endpoint is deleted.
bool GetFackEnabled() const
Check whether Forward Acknowledgment (FACK) is enabled.
Time GetDelAckTimeout() const override
Get the time to delay an ACK.
Ptr< TcpRecoveryOps > m_recoveryOps
Recovery Algorithm.
TracedCallback< uint32_t, uint32_t > m_bytesInFlightTrace
Callback pointer for bytesInFlight trace chaining.
uint32_t GetInitialSSThresh() const override
Get the initial Slow Start Threshold.
void NotifyPacingPerformed()
Notify Pacing.
uint32_t m_sndFack
Sequence number of the forward most acknowledgement.
void SetDelAckTimeout(Time timeout) override
Set the time to delay an ACK.
uint32_t m_outstandingRetransBytes
Number of outstanding retransmitted bytes.
void CloseAndNotify()
Peacefully close the socket by notifying the upper layer and deallocate end point.
Ptr< TcpRateOps > m_rateOps
Rate operations.
void PeerClose(Ptr< Packet > p, const TcpHeader &tcpHeader)
Received a FIN from peer, notify rx buffer.
int Close() override
Close a socket.
bool m_shutdownSend
Send no longer allowed.
bool IsPacingEnabled() const
Return true if packets in the current window should be paced.
void ProcessOptionWScale(const Ptr< const TcpOption > option)
Read and parse the Window scale option.
bool m_closeOnEmpty
Close socket upon tx buffer emptied.
virtual void ReTxTimeout()
An RTO event happened.
void AddOptionSackPermitted(TcpHeader &header)
Add the SACK PERMITTED option to the header.
TracedValue< Time > m_rto
Retransmit timeout.
uint32_t GetSndBufSize() const override
Get the send buffer size.
virtual void ReceivedData(Ptr< Packet > packet, const TcpHeader &tcpHeader)
Recv of a data, put into buffer, call L7 to get it if necessary.
EventId m_timewaitEvent
TIME_WAIT expiration event: Move this socket to CLOSED state.
Ptr< TcpTxBuffer > m_txBuffer
Tx buffer.
static TypeId GetTypeId()
Get the type ID.
uint32_t m_dupAckCount
Dupack counter.
void SetRetxThresh(uint32_t retxThresh)
Set the retransmission threshold (dup ack threshold for a fast retransmit).
int Send(Ptr< Packet > p, uint32_t flags) override
Send data (or dummy data) to the remote host.
TracedCallback< SequenceNumber32, SequenceNumber32 > m_nextTxSequenceTrace
Callback pointer for next tx sequence chaining.
void UpdateBytesInFlight(uint32_t oldValue, uint32_t newValue) const
Callback function to hook to TcpSocketState bytes inflight.
EventId m_delAckEvent
Delayed ACK timeout event.
TracedCallback< Time, Time > m_lastRttTrace
Callback pointer for Last RTT trace chaining.
bool GetTcpNoDelay() const override
Check if Nagle's algorithm is enabled or not.
virtual void SetRtt(Ptr< RttEstimator > rtt)
Set the associated RTT estimator.
TracedCallback< uint32_t, uint32_t > m_cWndTrace
Callback pointer for cWnd trace chaining.
void UpdatePacingRateTrace(DataRate oldValue, DataRate newValue) const
Callback function to hook to TcpSocketState pacing rate.
void SetDataRetries(uint32_t retries) override
Set the number of data transmission retries before giving up.
void AddOptions(TcpHeader &tcpHeader)
Add options to TcpHeader.
TracedCallback< TcpSocketState::EcnState_t, TcpSocketState::EcnState_t > m_ecnStateTrace
Callback pointer for ECN state trace chaining.
void SetSynRetries(uint32_t count) override
Set the number of connection retries before giving up.
TracedCallback< uint32_t, uint32_t > m_fackAwndTrace
Callback pointer for fackAwnd trace chaining.
void ProcessWait(Ptr< Packet > packet, const TcpHeader &tcpHeader)
Received a packet upon CLOSE_WAIT, FIN_WAIT_1, FIN_WAIT_2.
SequenceNumber32 m_highTxAck
Highest ack sent.
uint32_t GetTxAvailable() const override
Returns the number of bytes which can be sent in a single call to Send.
bool m_timestampEnabled
Timestamp option enabled.
virtual void PersistTimeout()
Send 1 byte probe to get an updated window size.
TracedValue< TcpStates_t > m_state
TCP state.
int SetupCallback()
Common part of the two Bind(), i.e.
Ptr< RttEstimator > m_rtt
Round trip time estimator.
Timer m_pacingTimer
Pacing Event.
EventId m_retxEvent
Retransmission event.
uint32_t m_bytesAckedNotProcessed
Bytes acked, but not processed.
void AddOptionTimestamp(TcpHeader &header)
Add the timestamp option to the header.
virtual uint32_t BytesInFlight() const
Return total bytes in flight.
uint32_t GetSegSize() const override
Get the segment size.
virtual void ProcessAck(const SequenceNumber32 &ackNumber, bool scoreboardUpdated, uint32_t currentDelivered, const SequenceNumber32 &oldHeadSequence, bool receivedData)
Process a received ack.
int SendTo(Ptr< Packet > p, uint32_t flags, const Address &toAddress) override
Send data to a specified peer.
uint32_t m_dataRetries
Number of data retransmission attempts.
double m_msl
Max segment lifetime.
void ProcessLastAck(Ptr< Packet > packet, const TcpHeader &tcpHeader)
Received a packet upon LAST_ACK.
bool m_limitedTx
perform limited transmit
virtual uint32_t SendDataPacket(SequenceNumber32 seq, uint32_t maxSize, bool withAck)
Extract at most maxSize bytes from the TxBuffer at sequence seq, add the TCP header,...
TracedCallback< TcpSocketState::TcpCongState_t, TcpSocketState::TcpCongState_t > m_congStateTrace
Callback pointer for congestion state trace chaining.
void ProcessSynRcvd(Ptr< Packet > packet, const TcpHeader &tcpHeader, const Address &fromAddress, const Address &toAddress)
Received a packet upon SYN_RCVD.
virtual void ReceivedAck(Ptr< Packet > packet, const TcpHeader &tcpHeader)
Received an ACK packet.
SocketType GetSocketType() const override
int ShutdownSend() override
uint32_t GetSndFack() const
Get the current FACK sequence number.
TracedValue< SequenceNumber32 > m_ecnCWRSeq
Sequence number of the last sent CWR.
Time GetPersistTimeout() const override
Get the timeout for persistent connection.
void UpdateCwnd(uint32_t oldValue, uint32_t newValue) const
Callback function to hook to TcpSocketState congestion window.
void UpdateLastRtt(Time oldValue, Time newValue) const
Callback function to hook to TcpSocketState lastRtt.
TracedCallback< Ptr< const Packet >, const TcpHeader &, const Address &, const Address &, Ptr< const TcpSocketBase > > m_retransmissionTrace
Trace of retransmitted packets.
uint32_t m_delAckCount
Delayed ACK counter.
Ipv4EndPoint * m_endPoint
the IPv4 endpoint
TcpPacketType_t
Tcp Packet Types.
static uint32_t SafeSubtraction(uint32_t a, uint32_t b)
Performs a safe subtraction between a and b (a-b).
virtual void DelAckTimeout()
Action upon delay ACK timeout, i.e.
Ptr< Packet > RecvFrom(uint32_t maxSize, uint32_t flags, Address &fromAddress) override
Read a single packet from the socket and retrieve the sender address.
Time m_cnTimeout
Timeout for connection retry.
Time GetClockGranularity() const
Get the Clock Granularity (used in RTO calcs).
bool m_winScalingEnabled
Window Scale option enabled (RFC 7323).
void UpdateEcnState(TcpSocketState::EcnState_t oldValue, TcpSocketState::EcnState_t newValue) const
Callback function to hook to EcnState state.
EventId m_sendPendingDataEvent
micro-delay event to send pending data
uint32_t m_delAckMaxCount
Number of packet to fire an ACK before delay timeout.
uint8_t CalculateWScale() const
Calculate window scale value based on receive buffer space.
virtual void NewAck(const SequenceNumber32 &seq, bool resetRTO)
Update buffers w.r.t.
bool m_closeNotified
Told app to close socket.
int Listen() override
Listen for incoming connections.
void Destroy6()
Kill this socket by zeroing its attributes (IPv6).
bool IsEct(TcpPacketType_t packetType) const
Checks if a TCP packet should be ECN-capable (ECT) according to the TcpPacketType and ECN mode.
TracedValue< SequenceNumber32 > m_ecnCESeq
Sequence number of the last received Congestion Experienced.
void SetClockGranularity(Time clockGranularity)
Sets the Clock Granularity (used in RTO calcs).
bool IsValidTcpSegment(const SequenceNumber32 seq, const uint32_t tcpHeaderSize, const uint32_t tcpPayloadSize)
Checks whether the given TCP segment is valid or not.
Time m_clockGranularity
Clock Granularity used in RTO calcs.
void DupAck(uint32_t currentDelivered)
Dupack management.
bool m_shutdownRecv
Receive no longer allowed.
void UpdateCongState(TcpSocketState::TcpCongState_t oldValue, TcpSocketState::TcpCongState_t newValue) const
Callback function to hook to TcpSocketState congestion state.
virtual uint32_t Window() const
Return the max possible number of unacked bytes.
Callback< void, Ipv6Address, uint8_t, uint8_t, uint8_t, uint32_t > m_icmpCallback6
ICMPv6 callback.
std::deque< RttHistory > m_history
List of sent packet.
void ProcessOptionSackPermitted(const Ptr< const TcpOption > option)
Read the SACK PERMITTED option.
int Bind() override
Allocate a local IPv4 endpoint for this socket.
virtual uint32_t AvailableWindow() const
Return unfilled portion of window.
TracedValue< SequenceNumber32 > m_highRxMark
Highest seqno received.
void ReadOptions(const TcpHeader &tcpHeader, uint32_t *bytesSacked)
Read TCP options before Ack processing.
virtual uint16_t AdvertisedWindowSize(bool scale=true) const
The amount of Rx window announced to the peer.
void ForwardUp6(Ptr< Packet > packet, Ipv6Header header, uint16_t port, Ptr< Ipv6Interface > incomingInterface)
Called by the L3 protocol when it received a packet to pass on to TCP.
void SetUseAbe(bool useAbe)
Set ABE mode of use on the socket.
bool m_connected
Connection established.
TracedValue< SequenceNumber32 > m_highRxAckMark
Highest ack received.
void AddOptionWScale(TcpHeader &header)
Add the window scale option to the header.
virtual void SendEmptyPacket(uint8_t flags)
Send a empty packet that carries a flag, e.g., ACK.
void UpdateWindowSize(const TcpHeader &header)
Update the receiver window (RWND) based on the value of the window field in the header.
uint32_t GetRxAvailable() const override
Return number of bytes which can be returned from one or multiple calls to Recv.
bool m_useAbe
ABE mode It will override the UseEcn attribute if it is 'Off' and set it to 'On', but will leave it u...
uint32_t GetDataRetries() const override
Get the number of data transmission retries before giving up.
int SetupEndpoint6()
Configure the endpoint v6 to a local address.
uint32_t GetRetxThresh() const
Get the retransmission threshold (dup ack threshold for a fast retransmit).
void DeallocateEndPoint()
Deallocate m_endPoint and m_endPoint6.
void Destroy()
Kill this socket by zeroing its attributes (IPv4).
void UpdateHighTxMark(SequenceNumber32 oldValue, SequenceNumber32 newValue) const
Callback function to hook to TcpSocketState high tx mark.
TcpSocketBase()
Create an unbound TCP socket.
void SetInitialSSThresh(uint32_t threshold) override
Set the initial Slow Start Threshold.
TracedCallback< DataRate, DataRate > m_pacingRateTrace
Callback pointer for pacing rate trace chaining.
uint32_t m_timestampToEcho
Timestamp to echo.
Ipv6EndPoint * m_endPoint6
the IPv6 endpoint
void SetSndBufSize(uint32_t size) override
Set the send buffer size.
virtual Ptr< TcpSocketBase > Fork()
Call CopyObject<> to clone me.
TracedCallback< uint32_t, uint32_t > m_ssThTrace
Callback pointer for ssTh trace chaining.
SocketErrno m_errno
Socket error code.
SocketErrno GetErrno() const override
Get last error number.
virtual void CompleteFork(Ptr< Packet > p, const TcpHeader &tcpHeader, const Address &fromAddress, const Address &toAddress)
Complete a connection by forking the socket.
void ProcessClosing(Ptr< Packet > packet, const TcpHeader &tcpHeader)
Received a packet upon CLOSING.
TracedCallback< SequenceNumber32, SequenceNumber32 > m_highTxMarkTrace
Callback pointer for high tx mark chaining.
int Connect(const Address &address) override
Initiate a connection to a remote host.
Ptr< Node > m_node
the associated node
void SetSegSize(uint32_t size) override
Set the segment size.
bool GetUseAbe() const
Get ABE mode of use on the socket.
uint32_t m_synRetries
Number of connection attempts.
void SetConnTimeout(Time timeout) override
Set the connection timeout.
void SetDelAckMaxCount(uint32_t count) override
Set the number of packet to fire an ACK before delay timeout.
EventId m_lastAckEvent
Last ACK timeout event.
bool IsTcpOptionEnabled(uint8_t kind) const
Return true if the specified option is enabled.
void UpdatePacingRate()
Dynamically update the pacing rate.
EventId m_persistEvent
Persist event: Send 1 byte to probe for a non-zero Rx window.
void SetPacingStatus(bool pacing)
Enable or disable pacing.
void UpdateRtt(Time oldValue, Time newValue) const
Callback function to hook to TcpSocketState rtt.
void SetCongestionControlAlgorithm(Ptr< TcpCongestionOps > algo)
Install a congestion control algorithm on this socket.
int GetPeerName(Address &address) const override
Get the peer address of a connected socket.
virtual uint32_t UnAckDataCount() const
Return count of number of unacked bytes.
uint32_t m_dataRetrCount
Count of remaining data retransmission attempts.
void UpdateCwndInfl(uint32_t oldValue, uint32_t newValue) const
Callback function to hook to TcpSocketState inflated congestion window.
Ptr< TcpRxBuffer > GetRxBuffer() const
Get a pointer to the Rx buffer.
void SetPersistTimeout(Time timeout) override
Set the timeout for persistent connection.
void ConnectionSucceeded()
Schedule-friendly wrapper for Socket::NotifyConnectionSucceeded().
bool m_noDelay
Set to true to disable Nagle's algorithm.
uint32_t GetDelAckMaxCount() const override
Get the number of packet to fire an ACK before delay timeout.
void ForwardIcmp(Ipv4Address icmpSource, uint8_t icmpTtl, uint8_t icmpType, uint8_t icmpCode, uint32_t icmpInfo)
Called by the L3 protocol when it received an ICMP packet to pass on to TCP.
void ForwardIcmp6(Ipv6Address icmpSource, uint8_t icmpTtl, uint8_t icmpType, uint8_t icmpCode, uint32_t icmpInfo)
Called by the L3 protocol when it received an ICMPv6 packet to pass on to TCP.
virtual void DoForwardUp(Ptr< Packet > packet, const Address &fromAddress, const Address &toAddress)
Called by TcpSocketBase::ForwardUp{,6}().
bool m_isFirstPartialAck
First partial ACK during RECOVERY.
uint8_t MarkEcnCodePoint(const uint8_t tos, const TcpSocketState::EcnCodePoint_t codePoint) const
mark ECN code point
Time m_delAckTimeout
Time to delay an ACK.
Callback< void, Ipv4Address, uint8_t, uint8_t, uint8_t, uint32_t > m_icmpCallback
ICMP callback.
TracedCallback< Time, Time > m_srttTrace
Callback pointer for RTT trace chaining.
void SetInitialCwnd(uint32_t cwnd) override
Set the initial Congestion Window.
void SetUseEcn(TcpSocketState::UseEcn_t useEcn)
Set ECN mode of use on the socket.
void ProcessListen(Ptr< Packet > packet, const TcpHeader &tcpHeader, const Address &fromAddress, const Address &toAddress)
Received a packet upon LISTEN state.
uint32_t m_synCount
Count of remaining connection retries.
bool m_fackEnabled
flag for enabling FACK
int DoConnect()
Perform the real connection tasks: Send SYN if allowed, RST if invalid.
virtual Time CalculateRttSample(const TcpHeader &tcpHeader, const RttHistory &rttHistory)
Calculate RTT sample for the ACKed packet.
uint32_t GetSynRetries() const override
Get the number of connection retries before giving up.
void DoPeerClose()
FIN is in sequence, notify app and respond with a FIN.
void NotifyConstructionCompleted() override
Notifier called once the ObjectBase is fully constructed.
void SendRST()
Send reset and tear down this socket.
bool OutOfRange(SequenceNumber32 head, SequenceNumber32 tail) const
Check if a sequence number range is within the rx window.
TracedValue< SequenceNumber32 > m_ecnEchoSeq
Sequence number of the last received ECN Echo.
uint32_t m_retxThresh
Fast Retransmit threshold.
void UpdateFackAwnd(uint32_t oldValue, uint32_t newValue) const
Callback function to hook to TcpSocketState awnd(FACK's inflight).
uint32_t GetRWnd() const
Get the current value of the receiver's offered window (RCV.WND).
SequenceNumber32 GetHighRxAck() const
Get the current value of the receiver's highest (in-sequence) sequence number acked.
void BindToNetDevice(Ptr< NetDevice > netdevice) override
Bind a socket to specific device.
void EnterCwr(uint32_t currentDelivered)
Enter CA_CWR state upon receipt of an ECN Echo.
virtual void EstimateRtt(const TcpHeader &tcpHeader)
Take into account the packet for RTT estimation.
uint32_t GetInitialCwnd() const override
Get the initial Congestion Window.
TracedValue< uint32_t > m_rWnd
Receiver window (RCV.WND in RFC793).
void ProcessOptionTimestamp(const Ptr< const TcpOption > option, const SequenceNumber32 &seq)
Process the timestamp option from other side.
void SetRcvBufSize(uint32_t size) override
Set the receive buffer size.
void SetTcpNoDelay(bool noDelay) override
Enable/Disable Nagle's algorithm.
virtual void UpdateRttHistory(const SequenceNumber32 &seq, uint32_t sz, bool isRetransmission)
Update the RTT history, when we send TCP segments.
bool m_sackEnabled
RFC SACK option enabled.
void UpdateNextTxSequence(SequenceNumber32 oldValue, SequenceNumber32 newValue) const
Callback function to hook to TcpSocketState next tx sequence.
void SetMinRto(Time minRto)
Sets the Minimum RTO.
Time GetConnTimeout() const override
Get the connection timeout.
Ptr< Node > GetNode() const override
Return the node this socket is associated with.
uint32_t ProcessOptionSack(const Ptr< const TcpOption > option)
Read the SACK option.
void SetRecoveryAlgorithm(Ptr< TcpRecoveryOps > recovery)
Install a recovery algorithm on this socket.
int DoClose()
Close a socket by sending RST, FIN, or FIN+ACK, depend on the current state.
TracedCallback< uint32_t, uint32_t > m_cWndInflTrace
Callback pointer for cWndInfl trace chaining.
uint32_t GetRcvBufSize() const override
Get the receive buffer size.
static const char *const TcpStateName[TcpSocket::LAST_STATE]
Literal names of TCP states for use in log messages.
Definition tcp-socket.h:84
@ CA_EVENT_ECN_IS_CE
received CE marked IP packet.
@ CA_EVENT_ECN_NO_CE
ECT set, but not CE marked.
@ CA_EVENT_DELAYED_ACK
Delayed ack is sent.
@ CA_EVENT_NON_DELAYED_ACK
Non-delayed ack is sent.
@ CA_EVENT_COMPLETE_CWR
end of congestion recovery
@ CA_EVENT_LOSS
loss timeout
@ CA_EVENT_TX_START
first transmit when no packets in flight
UseEcn_t
Parameter value related to ECN enable/disable functionality similar to sysctl for tcp_ecn.
@ AcceptOnly
Enable only when the peer endpoint is ECN capable.
static INTERNET_EXPORT const char *const TcpCongStateName[TcpSocketState::CA_LAST_STATE]
Literal names of TCP states for use in log messages.
TcpCongState_t
Definition of the Congestion state machine.
@ CA_RECOVERY
CWND was reduced, we are fast-retransmitting.
@ CA_DISORDER
In all the respects it is "Open", but requires a bit more attention.
@ CA_CWR
cWnd was reduced due to some congestion notification event, such as ECN, ICMP source quench,...
@ CA_LOSS
CWND was reduced due to RTO timeout or SACK reneging.
@ CA_OPEN
Normal state, no dubious events.
@ DctcpEcn
ECN functionality as described in RFC 8257.
@ ClassicEcn
ECN functionality as described in RFC 3168.
EcnState_t
Definition of the Ecn state machine.
@ ECN_CWR_SENT
Sender has reduced the congestion window, and sent a packet with CWR bit set in TCP header.
@ ECN_DISABLED
ECN disabled traffic.
@ ECN_ECE_RCVD
Last ACK received had ECE bit set in TCP header.
@ ECN_IDLE
ECN is enabled but currently there is no action pertaining to ECE or CWR to be taken.
@ ECN_CE_RCVD
Last packet received had CE bit set in IP header.
@ ECN_SENDING_ECE
Receiver sends an ACK with ECE bit set in TCP header.
static INTERNET_EXPORT const char *const EcnStateName[TcpSocketState::ECN_CWR_SENT+1]
Literal names of ECN states for use in log messages.
Item that encloses the application packet and some flags for it.
Definition tcp-tx-item.h:22
Ptr< Packet > GetPacketCopy() const
Get a copy of the Packet underlying this item.
bool IsRetrans() const
Is the item retransmitted?
Simulation virtual time values and global simulation resolution.
Definition nstime.h:95
double GetSeconds() const
Get an approximation of the time stored in this instance in the indicated unit.
Definition nstime.h:398
Time TimeStep(uint64_t ts)
Scheduler interface.
Definition nstime.h:1370
@ S
second
Definition nstime.h:106
static Time FromDouble(double value, Unit unit)
Create a Time equal to value in unit unit.
Definition nstime.h:517
bool IsZero() const
Exactly equivalent to t == 0.
Definition nstime.h:305
A simple virtual Timer class.
Definition timer.h:67
a unique identifier for an interface.
Definition type-id.h:50
TypeId SetParent(TypeId tid)
Set the parent TypeId.
Definition type-id.cc:999
Hold an unsigned integer type.
Definition uinteger.h:34
uint16_t port
Definition dsdv-manet.cc:33
#define NS_ASSERT(condition)
At runtime, in debugging builds, if this condition is not true, the program prints the source file,...
Definition assert.h:55
#define NS_ASSERT_MSG(condition, message)
At runtime, in debugging builds, if this condition is not true, the program prints the message to out...
Definition assert.h:75
Ptr< const AttributeAccessor > MakePointerAccessor(T1 a1)
Create an AttributeAccessor for a class data member, or a lone class get functor or set method.
Definition pointer.h:250
Ptr< AttributeChecker > MakePointerChecker()
Create a PointerChecker for a type.
Definition pointer.h:273
Callback< R, Args... > MakeCallback(R(T::*memPtr)(Args...), OBJ objPtr)
Build Callbacks for class method members which take varying numbers of arguments and potentially retu...
Definition callback.h:690
Callback< R, Args... > MakeNullCallback()
Build null Callbacks which take no arguments, for varying number of template arguments,...
Definition callback.h:734
#define NS_ABORT_MSG_UNLESS(cond, msg)
Abnormal program termination if a condition is false, with a message.
Definition abort.h:133
#define NS_FATAL_ERROR(msg)
Report a fatal error with a message and terminate.
#define NS_ABORT_MSG_IF(cond, msg)
Abnormal program termination if a condition is true, with a message.
Definition abort.h:97
int64x64_t Max(const int64x64_t &a, const int64x64_t &b)
Maximum.
Definition int64x64.h:231
#define NS_LOG_ERROR(msg)
Use NS_LOG to output a message of level LOG_ERROR.
Definition log.h:246
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition log.h:194
#define NS_LOG_DEBUG(msg)
Use NS_LOG to output a message of level LOG_DEBUG.
Definition log.h:260
#define NS_LOG_LOGIC(msg)
Use NS_LOG to output a message of level LOG_LOGIC.
Definition log.h:274
#define NS_LOG_FUNCTION(parameters)
If log level LOG_FUNCTION is enabled, this macro will output all input parameters separated by ",...
#define NS_LOG_WARN(msg)
Use NS_LOG to output a message of level LOG_WARN.
Definition log.h:253
#define NS_LOG_INFO(msg)
Use NS_LOG to output a message of level LOG_INFO.
Definition log.h:267
Ptr< T > CreateObject(Args &&... args)
Create an object by type, with varying number of constructor parameters.
Definition object.h:627
#define NS_OBJECT_ENSURE_REGISTERED(type)
Register an Object subclass with the TypeId system.
Definition object-base.h:35
Ptr< T > Create(Ts &&... args)
Create class instances by constructors with varying numbers of arguments and return them by Ptr.
Definition ptr.h:492
SequenceNumber< uint32_t > SequenceNumber32
32 bit Sequence number.
@ ESTABLISHED
Connection established.
Definition tcp-socket.h:61
@ FIN_WAIT_2
All buffered data sent, waiting for remote to shutdown.
Definition tcp-socket.h:70
@ LISTEN
Listening for a connection.
Definition tcp-socket.h:57
@ CLOSE_WAIT
Remote side has shutdown and is waiting for us to finish writing our data and to shutdown (we have to...
Definition tcp-socket.h:62
@ SYN_SENT
Sent a connection request, waiting for ack.
Definition tcp-socket.h:58
@ CLOSED
Socket is finished.
Definition tcp-socket.h:56
@ FIN_WAIT_1
Our side has shutdown, waiting to complete transmission of remaining buffered data.
Definition tcp-socket.h:68
@ TIME_WAIT
Timeout to catch resent junk before entering closed, can only be entered from FIN_WAIT2 or CLOSING.
Definition tcp-socket.h:73
@ SYN_RCVD
Received a connection request, sent ack, waiting for final ack in three-way handshake.
Definition tcp-socket.h:59
@ LAST_ACK
Our side has shutdown after remote has shutdown.
Definition tcp-socket.h:65
@ CLOSING
Both sides have shutdown but we still have data we have to finish sending.
Definition tcp-socket.h:71
Time MicroSeconds(uint64_t value)
Construct a Time in the indicated unit.
Definition nstime.h:1307
Time Seconds(double value)
Construct a Time in the indicated unit.
Definition nstime.h:1273
Time MilliSeconds(uint64_t value)
Construct a Time in the indicated unit.
Definition nstime.h:1290
Ptr< const TraceSourceAccessor > MakeTraceSourceAccessor(T a)
Create a TraceSourceAccessor which will control access to the underlying trace source.
const std::map< std::pair< ns3::TcpSocketBase::TcpPacketType_t, ns3::TcpSocketState::EcnMode_t >, bool > ECN_RESTRICTION_MAP
map TcpPacketType and EcnMode to boolean value to check whether ECN-marking is allowed or not
Every class exported by the ns3 library is enclosed in the ns3 namespace.
Ptr< const AttributeChecker > MakeBooleanChecker()
Definition boolean.cc:113
Ptr< const AttributeAccessor > MakeCallbackAccessor(T1 a1)
Definition callback.h:826
Ptr< const AttributeChecker > MakeUintegerChecker()
Definition uinteger.h:85
Ptr< const AttributeAccessor > MakeTimeAccessor(T1 a1)
Definition nstime.h:1376
Ptr< const AttributeAccessor > MakeUintegerAccessor(T1 a1)
Definition uinteger.h:35
Ptr< const AttributeChecker > MakeDoubleChecker()
Definition double.h:82
Ptr< const AttributeChecker > MakeEnumChecker(T v, std::string n, Ts... args)
Make an EnumChecker pre-configured with a set of allowed values by name.
Definition enum.h:181
Ptr< T1 > DynamicCast(const Ptr< T2 > &p)
Cast a Ptr.
Definition ptr.h:643
Ptr< const AttributeChecker > MakeCallbackChecker()
Definition callback.cc:77
Ptr< T > CopyObject(Ptr< const T > object)
Definition object.h:597
Ptr< const AttributeAccessor > MakeBooleanAccessor(T1 a1)
Definition boolean.h:70
Ptr< const AttributeAccessor > MakeDoubleAccessor(T1 a1)
Definition double.h:32
Ptr< const AttributeAccessor > MakeEnumAccessor(T1 a1)
Definition enum.h:223
Ptr< const AttributeChecker > MakeTimeChecker()
Helper to make an unbounded Time checker.
Definition nstime.h:1396
-bbr-example
ns3::Time timeout