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 ns3LogStream << " [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 }
980 Ptr<Packet> outPacket = m_tcb->m_rxBuffer->Extract(maxSize);
982
983 // If the receive window had (nearly) closed, the application read just
984 // reopened it. Proactively advertise the larger window with an ACK instead
985 // of waiting for the sender's persist (zero-window) timer to probe. This
986 // mirrors SetRcvBufSize() and follows the receiver SWS-avoidance rule of
987 // @RFC{1122} sec 4.2.3.3: only advertise once the window grows by at least one
988 // full-sized segment (or half the buffer), and only from a (near) closed
989 // state, to avoid sending a redundant ACK on every read (see @issueid{125}).
991 oldWin < m_tcb->m_segmentSize && newWin > oldWin &&
992 newWin >= std::min(m_tcb->m_segmentSize, GetRcvBufSize() / 2))
993 {
994 if (m_tcb->m_ecnState == TcpSocketState::ECN_CE_RCVD ||
996 {
999 }
1000 else
1001 {
1003 }
1004 }
1005 return outPacket;
1006}
1007
1008/* Inherit from Socket class: Recv and return the remote's address */
1011{
1012 NS_LOG_FUNCTION(this << maxSize << flags);
1013 Ptr<Packet> packet = Recv(maxSize, flags);
1014 // Null packet means no data to read, and an empty packet indicates EOF
1015 if (packet && packet->GetSize() != 0)
1016 {
1017 if (m_endPoint != nullptr)
1018 {
1019 fromAddress =
1020 InetSocketAddress(m_endPoint->GetPeerAddress(), m_endPoint->GetPeerPort());
1021 }
1022 else if (m_endPoint6 != nullptr)
1023 {
1024 fromAddress =
1025 Inet6SocketAddress(m_endPoint6->GetPeerAddress(), m_endPoint6->GetPeerPort());
1026 }
1027 else
1028 {
1029 fromAddress = InetSocketAddress(Ipv4Address::GetZero(), 0);
1030 }
1031 }
1032 return packet;
1033}
1034
1035/* Inherit from Socket class: Get the max number of bytes an app can send */
1038{
1039 NS_LOG_FUNCTION(this);
1040 return m_txBuffer->Available();
1041}
1042
1043/* Inherit from Socket class: Get the max number of bytes an app can read */
1046{
1047 NS_LOG_FUNCTION(this);
1048 return m_tcb->m_rxBuffer->Available();
1049}
1050
1051/* Inherit from Socket class: Return local address:port */
1052int
1054{
1055 NS_LOG_FUNCTION(this);
1056 if (m_endPoint != nullptr)
1057 {
1058 address = InetSocketAddress(m_endPoint->GetLocalAddress(), m_endPoint->GetLocalPort());
1059 }
1060 else if (m_endPoint6 != nullptr)
1061 {
1062 address = Inet6SocketAddress(m_endPoint6->GetLocalAddress(), m_endPoint6->GetLocalPort());
1063 }
1064 else
1065 { // It is possible to call this method on a socket without a name
1066 // in which case, behavior is unspecified
1067 // Should this return an InetSocketAddress or an Inet6SocketAddress?
1069 }
1070 return 0;
1071}
1072
1073int
1075{
1076 NS_LOG_FUNCTION(this << address);
1077
1078 if (!m_endPoint && !m_endPoint6)
1079 {
1081 return -1;
1082 }
1083
1084 if (m_endPoint)
1085 {
1086 address = InetSocketAddress(m_endPoint->GetPeerAddress(), m_endPoint->GetPeerPort());
1087 }
1088 else if (m_endPoint6)
1089 {
1090 address = Inet6SocketAddress(m_endPoint6->GetPeerAddress(), m_endPoint6->GetPeerPort());
1091 }
1092 else
1093 {
1094 NS_ASSERT(false);
1095 }
1096
1097 return 0;
1098}
1099
1100/* Inherit from Socket class: Bind this socket to the specified NetDevice */
1101void
1103{
1104 NS_LOG_FUNCTION(netdevice);
1105 Socket::BindToNetDevice(netdevice); // Includes sanity check
1106 if (m_endPoint != nullptr)
1107 {
1108 m_endPoint->BindToNetDevice(netdevice);
1109 }
1110
1111 if (m_endPoint6 != nullptr)
1112 {
1113 m_endPoint6->BindToNetDevice(netdevice);
1114 }
1115}
1116
1117/* Clean up after Bind. Set up callback functions in the end-point. */
1118int
1120{
1121 NS_LOG_FUNCTION(this);
1122
1123 if (m_endPoint == nullptr && m_endPoint6 == nullptr)
1124 {
1125 return -1;
1126 }
1127 if (m_endPoint != nullptr)
1128 {
1129 m_endPoint->SetRxCallback(
1131 m_endPoint->SetIcmpCallback(
1133 m_endPoint->SetDestroyCallback(
1135 }
1136 if (m_endPoint6 != nullptr)
1137 {
1138 m_endPoint6->SetRxCallback(
1140 m_endPoint6->SetIcmpCallback(
1142 m_endPoint6->SetDestroyCallback(
1144 }
1145
1146 return 0;
1147}
1148
1149/* Perform the real connection tasks: Send SYN if allowed, RST if invalid */
1150int
1152{
1153 NS_LOG_FUNCTION(this);
1154
1155 // A new connection is allowed only if this socket does not have a connection
1156 if (m_state == CLOSED || m_state == LISTEN || m_state == SYN_SENT || m_state == LAST_ACK ||
1158 { // send a SYN packet and change state into SYN_SENT
1159 // send a SYN packet with ECE and CWR flags set if sender is ECN capable
1160 if (m_tcb->m_useEcn == TcpSocketState::On)
1161 {
1163 }
1164 else
1165 {
1167 }
1168 NS_LOG_DEBUG(TcpStateName[m_state] << " -> SYN_SENT");
1169 m_state = SYN_SENT;
1170 m_tcb->m_ecnState = TcpSocketState::ECN_DISABLED; // because sender is not yet aware about
1171 // receiver's ECN capability
1172 }
1173 else if (m_state != TIME_WAIT)
1174 { // In states SYN_RCVD, ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, and CLOSING, an connection
1175 // exists. We send RST, tear down everything, and close this socket.
1176 SendRST();
1178 }
1179 return 0;
1180}
1181
1182/* Do the action to close the socket. Usually send a packet with appropriate
1183 flags depended on the current m_state. */
1184int
1186{
1187 NS_LOG_FUNCTION(this);
1188 switch (m_state)
1189 {
1190 case SYN_RCVD:
1191 case ESTABLISHED:
1192 // send FIN to close the peer
1194 NS_LOG_DEBUG("ESTABLISHED -> FIN_WAIT_1");
1196 break;
1197 case CLOSE_WAIT:
1198 // send FIN+ACK to close the peer
1200 NS_LOG_DEBUG("CLOSE_WAIT -> LAST_ACK");
1201 m_state = LAST_ACK;
1202 break;
1203 case SYN_SENT:
1204 case CLOSING:
1205 // Send RST if application closes in SYN_SENT and CLOSING
1206 SendRST();
1208 break;
1209 case LISTEN:
1210 // In this state, move to CLOSED and tear down the end point
1212 break;
1213 case LAST_ACK:
1214 case CLOSED:
1215 case FIN_WAIT_1:
1216 case FIN_WAIT_2:
1217 case TIME_WAIT:
1218 default: /* mute compiler */
1219 // Do nothing in these five states
1220 break;
1221 }
1222 return 0;
1223}
1224
1225/* Peacefully close the socket by notifying the upper layer and deallocate end point */
1226void
1228{
1229 NS_LOG_FUNCTION(this);
1230
1231 if (!m_closeNotified)
1232 {
1234 m_closeNotified = true;
1235 }
1236 if (m_lastAckEvent.IsPending())
1237 {
1238 m_lastAckEvent.Cancel();
1239 }
1240 NS_LOG_DEBUG(TcpStateName[m_state] << " -> CLOSED");
1241 m_state = CLOSED;
1243}
1244
1245/* Tell if a sequence number range is out side the range that my rx buffer can
1246 accept */
1247bool
1249{
1250 if (m_state == LISTEN || m_state == SYN_SENT || m_state == SYN_RCVD)
1251 { // Rx buffer in these states are not initialized.
1252 return false;
1253 }
1254 if (m_state == LAST_ACK || m_state == CLOSING || m_state == CLOSE_WAIT)
1255 { // In LAST_ACK and CLOSING states, it only wait for an ACK and the
1256 // sequence number must equals to m_rxBuffer->NextRxSequence ()
1257 return (m_tcb->m_rxBuffer->NextRxSequence() != head);
1258 }
1259
1260 // In all other cases, check if the sequence number is in range
1261 return (tail < m_tcb->m_rxBuffer->NextRxSequence() ||
1262 m_tcb->m_rxBuffer->MaxRxSequence() <= head);
1263}
1264
1265/* Function called by the L3 protocol when it received a packet to pass on to
1266 the TCP. This function is registered as the "RxCallback" function in
1267 SetupCallback(), which invoked by Bind(), and CompleteFork() */
1268void
1270 Ipv4Header header,
1271 uint16_t port,
1272 Ptr<Ipv4Interface> incomingInterface)
1273{
1274 NS_LOG_LOGIC("Socket " << this << " forward up " << m_endPoint->GetPeerAddress() << ":"
1275 << m_endPoint->GetPeerPort() << " to " << m_endPoint->GetLocalAddress()
1276 << ":" << m_endPoint->GetLocalPort());
1277
1278 Address fromAddress = InetSocketAddress(header.GetSource(), port);
1279 Address toAddress = InetSocketAddress(header.GetDestination(), m_endPoint->GetLocalPort());
1280
1281 TcpHeader tcpHeader;
1282 uint32_t bytesRemoved = packet->PeekHeader(tcpHeader);
1283
1284 if (!IsValidTcpSegment(tcpHeader.GetSequenceNumber(),
1285 bytesRemoved,
1286 packet->GetSize() - bytesRemoved))
1287 {
1288 return;
1289 }
1290
1291 if (header.GetEcn() == Ipv4Header::ECN_CE && m_ecnCESeq < tcpHeader.GetSequenceNumber())
1292 {
1293 NS_LOG_INFO("Received CE flag is valid");
1294 NS_LOG_DEBUG(TcpSocketState::EcnStateName[m_tcb->m_ecnState] << " -> ECN_CE_RCVD");
1295 m_ecnCESeq = tcpHeader.GetSequenceNumber();
1296 m_tcb->m_ecnState = TcpSocketState::ECN_CE_RCVD;
1298 }
1299 else if (header.GetEcn() != Ipv4Header::ECN_NotECT &&
1300 m_tcb->m_ecnState != TcpSocketState::ECN_DISABLED)
1301 {
1303 }
1304
1305 DoForwardUp(packet, fromAddress, toAddress);
1306}
1307
1308void
1310 Ipv6Header header,
1311 uint16_t port,
1312 Ptr<Ipv6Interface> incomingInterface)
1313{
1314 NS_LOG_LOGIC("Socket " << this << " forward up " << m_endPoint6->GetPeerAddress() << ":"
1315 << m_endPoint6->GetPeerPort() << " to " << m_endPoint6->GetLocalAddress()
1316 << ":" << m_endPoint6->GetLocalPort());
1317
1318 Address fromAddress = Inet6SocketAddress(header.GetSource(), port);
1319 Address toAddress = Inet6SocketAddress(header.GetDestination(), m_endPoint6->GetLocalPort());
1320
1321 TcpHeader tcpHeader;
1322 uint32_t bytesRemoved = packet->PeekHeader(tcpHeader);
1323
1324 if (!IsValidTcpSegment(tcpHeader.GetSequenceNumber(),
1325 bytesRemoved,
1326 packet->GetSize() - bytesRemoved))
1327 {
1328 return;
1329 }
1330
1331 if (header.GetEcn() == Ipv6Header::ECN_CE && m_ecnCESeq < tcpHeader.GetSequenceNumber())
1332 {
1333 NS_LOG_INFO("Received CE flag is valid");
1334 NS_LOG_DEBUG(TcpSocketState::EcnStateName[m_tcb->m_ecnState] << " -> ECN_CE_RCVD");
1335 m_ecnCESeq = tcpHeader.GetSequenceNumber();
1336 m_tcb->m_ecnState = TcpSocketState::ECN_CE_RCVD;
1338 }
1339 else if (header.GetEcn() != Ipv6Header::ECN_NotECT &&
1340 m_tcb->m_ecnState != TcpSocketState::ECN_DISABLED)
1341 {
1343 }
1344
1345 DoForwardUp(packet, fromAddress, toAddress);
1346}
1347
1348void
1350 uint8_t icmpTtl,
1351 uint8_t icmpType,
1352 uint8_t icmpCode,
1353 uint32_t icmpInfo)
1354{
1355 NS_LOG_FUNCTION(this << icmpSource << static_cast<uint32_t>(icmpTtl)
1356 << static_cast<uint32_t>(icmpType) << static_cast<uint32_t>(icmpCode)
1357 << icmpInfo);
1358 if (!m_icmpCallback.IsNull())
1359 {
1360 m_icmpCallback(icmpSource, icmpTtl, icmpType, icmpCode, icmpInfo);
1361 }
1362}
1363
1364void
1366 uint8_t icmpTtl,
1367 uint8_t icmpType,
1368 uint8_t icmpCode,
1369 uint32_t icmpInfo)
1370{
1371 NS_LOG_FUNCTION(this << icmpSource << static_cast<uint32_t>(icmpTtl)
1372 << static_cast<uint32_t>(icmpType) << static_cast<uint32_t>(icmpCode)
1373 << icmpInfo);
1374 if (!m_icmpCallback6.IsNull())
1375 {
1376 m_icmpCallback6(icmpSource, icmpTtl, icmpType, icmpCode, icmpInfo);
1377 }
1378}
1379
1380bool
1382 const uint32_t tcpHeaderSize,
1383 const uint32_t tcpPayloadSize)
1384{
1385 if (tcpHeaderSize == 0 || tcpHeaderSize > 60)
1386 {
1387 NS_LOG_ERROR("Bytes removed: " << tcpHeaderSize << " invalid");
1388 return false; // Discard invalid packet
1389 }
1390 else if (tcpPayloadSize > 0 && OutOfRange(seq, seq + tcpPayloadSize))
1391 {
1392 // Discard fully out of range data packets
1393 NS_LOG_WARN("At state " << TcpStateName[m_state] << " received packet of seq [" << seq
1394 << ":" << seq + tcpPayloadSize << ") out of range ["
1395 << m_tcb->m_rxBuffer->NextRxSequence() << ":"
1396 << m_tcb->m_rxBuffer->MaxRxSequence() << ")");
1397 // Acknowledgement should be sent for all unacceptable packets (RFC793, p.69)
1399 return false;
1400 }
1401 return true;
1402}
1403
1404void
1405TcpSocketBase::DoForwardUp(Ptr<Packet> packet, const Address& fromAddress, const Address& toAddress)
1406{
1407 // in case the packet still has a priority tag attached, remove it
1408 SocketPriorityTag priorityTag;
1409 packet->RemovePacketTag(priorityTag);
1410
1411 // Peel off TCP header
1412 TcpHeader tcpHeader;
1413 packet->RemoveHeader(tcpHeader);
1414 SequenceNumber32 seq = tcpHeader.GetSequenceNumber();
1415
1416 if (m_state == ESTABLISHED && !(tcpHeader.GetFlags() & TcpHeader::RST))
1417 {
1418 // Check if the sender has responded to ECN echo by reducing the Congestion Window
1419 if (tcpHeader.GetFlags() & TcpHeader::CWR)
1420 {
1421 // Check if a packet with CE bit set is received. If there is no CE bit set, then change
1422 // the state to ECN_IDLE to stop sending ECN Echo messages. If there is CE bit set, the
1423 // packet should continue sending ECN Echo messages
1424 //
1425 if (m_tcb->m_ecnState != TcpSocketState::ECN_CE_RCVD)
1426 {
1427 NS_LOG_DEBUG(TcpSocketState::EcnStateName[m_tcb->m_ecnState] << " -> ECN_IDLE");
1428 m_tcb->m_ecnState = TcpSocketState::ECN_IDLE;
1429 }
1430 }
1431 }
1432
1433 m_rxTrace(packet, tcpHeader, this);
1434
1435 if (tcpHeader.GetFlags() & TcpHeader::SYN)
1436 {
1437 /* The window field in a segment where the SYN bit is set (i.e., a <SYN>
1438 * or <SYN,ACK>) MUST NOT be scaled (from RFC 7323 page 9). But should be
1439 * saved anyway..
1440 */
1441 m_rWnd = tcpHeader.GetWindowSize();
1442
1444 {
1446 }
1447 else
1448 {
1449 m_winScalingEnabled = false;
1450 }
1451
1453 {
1455 }
1456 else
1457 {
1458 m_sackEnabled = false;
1459 m_txBuffer->SetSackEnabled(false);
1460 }
1461 // Mirror the negotiated SACK state into the shared TcpSocketState so that
1462 // recovery algorithms (e.g. PRR) can distinguish SACK from non-SACK
1463 // DeliveredData accounting.
1464 m_tcb->m_sackEnabled = m_sackEnabled;
1465
1466 // When receiving a <SYN> or <SYN-ACK> we should adapt TS to the other end
1467 if (tcpHeader.HasOption(TcpOption::TS) && m_timestampEnabled)
1468 {
1470 tcpHeader.GetSequenceNumber());
1471 }
1472 else
1473 {
1474 m_timestampEnabled = false;
1475 }
1476
1477 // Initialize cWnd and ssThresh
1478 m_tcb->m_cWnd = GetInitialCwnd() * GetSegSize();
1479 m_tcb->m_cWndInfl = m_tcb->m_cWnd;
1480 m_tcb->m_ssThresh = GetInitialSSThresh();
1481
1482 if (tcpHeader.GetFlags() & TcpHeader::ACK)
1483 {
1484 EstimateRtt(tcpHeader);
1485 m_highRxAckMark = tcpHeader.GetAckNumber();
1486 }
1487 }
1488 else if (tcpHeader.GetFlags() & TcpHeader::ACK)
1489 {
1490 NS_ASSERT(!(tcpHeader.GetFlags() & TcpHeader::SYN));
1492 {
1493 if (!tcpHeader.HasOption(TcpOption::TS))
1494 {
1495 // Ignoring segment without TS, RFC 7323
1496 NS_LOG_LOGIC("At state " << TcpStateName[m_state] << " received packet of seq ["
1497 << seq << ":" << seq + packet->GetSize()
1498 << ") without TS option. Silently discard it");
1499 return;
1500 }
1501 else
1502 {
1504 tcpHeader.GetSequenceNumber());
1505 }
1506 }
1507
1508 EstimateRtt(tcpHeader);
1509 UpdateWindowSize(tcpHeader);
1510 }
1511
1512 if (m_rWnd.Get() == 0 && m_persistEvent.IsExpired())
1513 { // Zero window: Enter persist state to send 1 byte to probe
1514 NS_LOG_LOGIC(this << " Enter zerowindow persist state");
1516 this << " Cancelled ReTxTimeout event which was set to expire at "
1517 << (Simulator::Now() + Simulator::GetDelayLeft(m_retxEvent)).GetSeconds());
1518 m_retxEvent.Cancel();
1519 NS_LOG_LOGIC("Schedule persist timeout at time "
1520 << Simulator::Now().GetSeconds() << " to expire at time "
1521 << (Simulator::Now() + m_persistTimeout).GetSeconds());
1525 }
1526
1527 // TCP state machine code in different process functions
1528 // C.f.: tcp_rcv_state_process() in tcp_input.c in Linux kernel
1529 switch (m_state)
1530 {
1531 case ESTABLISHED:
1532 ProcessEstablished(packet, tcpHeader);
1533 break;
1534 case LISTEN:
1535 ProcessListen(packet, tcpHeader, fromAddress, toAddress);
1536 break;
1537 case TIME_WAIT:
1538 // Do nothing
1539 break;
1540 case CLOSED:
1541 // Send RST if the incoming packet is not a RST
1542 if ((tcpHeader.GetFlags() & ~(TcpHeader::PSH | TcpHeader::URG)) != TcpHeader::RST)
1543 { // Since m_endPoint is not configured yet, we cannot use SendRST here
1544 TcpHeader h;
1547 h.SetSequenceNumber(m_tcb->m_nextTxSequence);
1548 h.SetAckNumber(m_tcb->m_rxBuffer->NextRxSequence());
1549 h.SetSourcePort(tcpHeader.GetDestinationPort());
1550 h.SetDestinationPort(tcpHeader.GetSourcePort());
1552 AddOptions(h);
1553 m_txTrace(p, h, this);
1554 m_tcp->SendPacket(p, h, toAddress, fromAddress, m_boundnetdevice);
1555 }
1556 break;
1557 case SYN_SENT:
1558 ProcessSynSent(packet, tcpHeader);
1559 break;
1560 case SYN_RCVD:
1561 ProcessSynRcvd(packet, tcpHeader, fromAddress, toAddress);
1562 break;
1563 case FIN_WAIT_1:
1564 case FIN_WAIT_2:
1565 case CLOSE_WAIT:
1566 ProcessWait(packet, tcpHeader);
1567 break;
1568 case CLOSING:
1569 ProcessClosing(packet, tcpHeader);
1570 break;
1571 case LAST_ACK:
1572 ProcessLastAck(packet, tcpHeader);
1573 break;
1574 default: // mute compiler
1575 break;
1576 }
1577
1578 if (m_rWnd.Get() != 0 && m_persistEvent.IsPending())
1579 { // persist probes end, the other end has increased the window
1581 NS_LOG_LOGIC(this << " Leaving zerowindow persist state");
1582 m_persistEvent.Cancel();
1583
1585 }
1586}
1587
1588/* Received a packet upon ESTABLISHED state. This function is mimicking the
1589 role of tcp_rcv_established() in tcp_input.c in Linux kernel. */
1590void
1592{
1593 NS_LOG_FUNCTION(this << tcpHeader);
1594
1595 // Extract the flags. PSH, URG, CWR and ECE are disregarded.
1596 uint8_t tcpflags =
1598
1599 // Different flags are different events
1600 if (tcpflags == TcpHeader::ACK)
1601 {
1602 if (tcpHeader.GetAckNumber() < m_txBuffer->HeadSequence())
1603 {
1604 // Case 1: If the ACK is a duplicate (SEG.ACK < SND.UNA), it can be ignored.
1605 // Pag. 72 RFC 793
1606 NS_LOG_WARN("Ignored ack of " << tcpHeader.GetAckNumber()
1607 << " SND.UNA = " << m_txBuffer->HeadSequence());
1608
1609 // TODO: RFC 5961 5.2 [Blind Data Injection Attack].[Mitigation]
1610 }
1611 else if (tcpHeader.GetAckNumber() > m_tcb->m_highTxMark)
1612 {
1613 // If the ACK acks something not yet sent (SEG.ACK > HighTxMark) then
1614 // send an ACK, drop the segment, and return.
1615 // Pag. 72 RFC 793
1616 NS_LOG_WARN("Ignored ack of " << tcpHeader.GetAckNumber()
1617 << " HighTxMark = " << m_tcb->m_highTxMark);
1618
1619 // Receiver sets ECE flags when it receives a packet with CE bit on or sender hasn't
1620 // responded to ECN echo sent by receiver
1621 if (m_tcb->m_ecnState == TcpSocketState::ECN_CE_RCVD ||
1623 {
1626 << " -> ECN_SENDING_ECE");
1628 }
1629 else
1630 {
1632 }
1633 }
1634 else
1635 {
1636 // SND.UNA < SEG.ACK =< HighTxMark
1637 // Pag. 72 RFC 793
1638 ReceivedAck(packet, tcpHeader);
1639 }
1640 }
1641 else if (tcpflags == TcpHeader::SYN || tcpflags == (TcpHeader::SYN | TcpHeader::ACK))
1642 {
1643 // (a) Received SYN, old NS-3 behaviour is to set state to SYN_RCVD and
1644 // respond with a SYN+ACK. But it is not a legal state transition as of
1645 // RFC793. Thus this is ignored.
1646
1647 // (b) No action for received SYN+ACK, it is probably a duplicated packet
1648 }
1649 else if (tcpflags == TcpHeader::FIN || tcpflags == (TcpHeader::FIN | TcpHeader::ACK))
1650 { // Received FIN or FIN+ACK, bring down this socket nicely
1651 PeerClose(packet, tcpHeader);
1652 }
1653 else if (tcpflags == 0)
1654 { // No flags means there is only data
1655 ReceivedData(packet, tcpHeader);
1656 if (m_tcb->m_rxBuffer->Finished())
1657 {
1658 PeerClose(packet, tcpHeader);
1659 }
1660 }
1661 else
1662 { // Received RST or the TCP flags is invalid, in either case, terminate this socket
1663 if (tcpflags != TcpHeader::RST)
1664 { // this must be an invalid flag, send reset
1665 NS_LOG_LOGIC("Illegal flag " << TcpHeader::FlagsToString(tcpflags)
1666 << " received. Reset packet is sent.");
1667 SendRST();
1668 }
1670 }
1671}
1672
1673bool
1675{
1676 NS_LOG_FUNCTION(this << static_cast<uint32_t>(kind));
1677
1678 switch (kind)
1679 {
1680 case TcpOption::TS:
1681 return m_timestampEnabled;
1683 return m_winScalingEnabled;
1685 case TcpOption::SACK:
1686 return m_sackEnabled;
1687 default:
1688 break;
1689 }
1690 return false;
1691}
1692
1693void
1694TcpSocketBase::ReadOptions(const TcpHeader& tcpHeader, uint32_t* bytesSacked)
1695{
1696 NS_LOG_FUNCTION(this << tcpHeader);
1697
1698 for (const auto& option : tcpHeader.GetOptionList())
1699 {
1700 // Check only for ACK options here
1701 switch (option->GetKind())
1702 {
1703 case TcpOption::SACK:
1704 *bytesSacked = ProcessOptionSack(option);
1705 break;
1706 default:
1707 continue;
1708 }
1709 }
1710}
1711
1712// Sender should reduce the Congestion Window as a response to receiver's
1713// ECN Echo notification only once per window
1714void
1716{
1717 NS_LOG_FUNCTION(this << currentDelivered);
1718 m_tcb->m_ssThresh = m_congestionControl->GetSsThresh(m_tcb, BytesInFlight());
1719 NS_LOG_DEBUG("Reduce ssThresh to " << m_tcb->m_ssThresh);
1720 // Do not update m_cWnd, under assumption that recovery process will
1721 // gradually bring it down to m_ssThresh. Update the 'inflated' value of
1722 // cWnd used for tracing, however.
1723 m_tcb->m_cWndInfl = m_tcb->m_ssThresh;
1724 NS_ASSERT(m_tcb->m_congState != TcpSocketState::CA_CWR);
1725 NS_LOG_DEBUG(TcpSocketState::TcpCongStateName[m_tcb->m_congState] << " -> CA_CWR");
1726 m_congestionControl->CongestionStateSet(m_tcb, TcpSocketState::CA_CWR);
1727 m_tcb->m_congState = TcpSocketState::CA_CWR;
1728 // CWR state will be exited when the ack exceeds the m_recover variable.
1729 // Do not set m_recoverActive (which applies to a loss-based recovery)
1730 // m_recover corresponds to Linux tp->high_seq
1731 m_recover = m_tcb->m_highTxMark;
1732 if (!m_congestionControl->HasCongControl())
1733 {
1734 // If there is a recovery algorithm, invoke it.
1735 m_recoveryOps->EnterRecovery(m_tcb,
1738 currentDelivered,
1739 m_txBuffer->GetSacked());
1740 NS_LOG_INFO("Enter CWR recovery mode; set cwnd to " << m_tcb->m_cWnd << ", ssthresh to "
1741 << m_tcb->m_ssThresh << ", recover to "
1742 << m_recover);
1743 }
1744}
1745
1746void
1748{
1749 NS_LOG_FUNCTION(this);
1751
1752 NS_LOG_DEBUG(TcpSocketState::TcpCongStateName[m_tcb->m_congState] << " -> CA_RECOVERY");
1753
1754 NS_LOG_INFO("Enter CA_RECOVERY from "
1755 << TcpSocketState::TcpCongStateName[m_tcb->m_congState] << ": recovering highRxAck "
1756 << m_highRxAckMark << "; prior recover " << m_recover << " (active "
1757 << m_recoverActive << "), new recover " << m_tcb->m_highTxMark);
1758
1759 if (!m_sackEnabled)
1760 {
1761 // One segment has left the network, PLUS the head is lost
1762 m_txBuffer->AddRenoSack();
1763 m_txBuffer->MarkHeadAsLost();
1764 }
1765 else
1766 {
1767 if (!m_txBuffer->IsLost(m_txBuffer->HeadSequence()))
1768 {
1769 // We received 3 dupacks, but the head is not marked as lost
1770 // (received less than 3 SACK block ahead).
1771 // Manually set it as lost.
1772 m_txBuffer->MarkHeadAsLost();
1773 }
1774 }
1775
1776 // RFC 6675, point (4):
1777 // (4) Invoke fast retransmit and enter loss recovery as follows:
1778 // (4.1) RecoveryPoint = HighData
1779 m_recover = m_tcb->m_highTxMark;
1780 m_recoverActive = true;
1781
1783 m_tcb->m_congState = TcpSocketState::CA_RECOVERY;
1784
1785 // (4.2) ssthresh = cwnd = (FlightSize / 2)
1786 // If SACK is not enabled, still consider the head as 'in flight' for
1787 // compatibility with old ns-3 versions
1788 uint32_t bytesInFlight =
1789 m_sackEnabled ? BytesInFlight() : BytesInFlight() + m_tcb->m_segmentSize;
1790 m_tcb->m_ssThresh = m_congestionControl->GetSsThresh(m_tcb, bytesInFlight);
1791
1792 if (!m_congestionControl->HasCongControl())
1793 {
1794 m_recoveryOps->EnterRecovery(m_tcb,
1797 currentDelivered,
1798 m_txBuffer->GetSacked());
1799 NS_LOG_INFO(m_dupAckCount << " dupack. Enter fast recovery mode."
1800 << "Reset cwnd to " << m_tcb->m_cWnd << ", ssthresh to "
1801 << m_tcb->m_ssThresh << " at fast recovery seqnum " << m_recover
1802 << " calculated in flight: " << bytesInFlight);
1803 }
1804
1805 // (4.3) Retransmit the first data segment presumed dropped
1806 uint32_t sz = SendDataPacket(m_highRxAckMark, m_tcb->m_segmentSize, true);
1807 NS_ASSERT_MSG(sz > 0, "SendDataPacket returned zero, indicating zero bytes were sent");
1808 // (4.4) Run SetPipe ()
1809 // (4.5) Proceed to step (C)
1810 // these steps are done after the ProcessAck function (SendPendingData)
1811}
1812
1813void
1815{
1816 NS_LOG_FUNCTION(this);
1817 // NOTE: We do not count the DupAcks received in CA_LOSS, because we
1818 // don't know if they are generated by a spurious retransmission or because
1819 // of a real packet loss. With SACK, it is easy to know, but we do not consider
1820 // dupacks. Without SACK, there are some heuristics in the RFC 6582, but
1821 // for now, we do not implement it, leading to ignoring the dupacks.
1822 if (m_tcb->m_congState == TcpSocketState::CA_LOSS)
1823 {
1824 return;
1825 }
1826
1827 // RFC 6675, Section 5, 3rd paragraph:
1828 // If the incoming ACK is a duplicate acknowledgment per the definition
1829 // in Section 2 (regardless of its status as a cumulative
1830 // acknowledgment), and the TCP is not currently in loss recovery
1831 // the TCP MUST increase DupAcks by one ...
1832 if (m_tcb->m_congState != TcpSocketState::CA_RECOVERY)
1833 {
1834 ++m_dupAckCount;
1835 }
1836
1837 if (m_tcb->m_congState == TcpSocketState::CA_OPEN)
1838 {
1839 // From Open we go Disorder
1841 "From OPEN->DISORDER but with " << m_dupAckCount << " dup ACKs");
1842
1844 m_tcb->m_congState = TcpSocketState::CA_DISORDER;
1845
1846 NS_LOG_DEBUG("CA_OPEN -> CA_DISORDER");
1847 }
1848
1849 if (m_tcb->m_congState == TcpSocketState::CA_RECOVERY)
1850 {
1851 if (!m_sackEnabled)
1852 {
1853 // If we are in recovery and we receive a dupack, one segment
1854 // has left the network. This is equivalent to a SACK of one block.
1855 m_txBuffer->AddRenoSack();
1856 }
1857 if (!m_congestionControl->HasCongControl())
1858 {
1859 m_recoveryOps->DoRecovery(m_tcb, currentDelivered, true);
1860 NS_LOG_INFO(m_dupAckCount << " Dupack received in fast recovery mode."
1861 "Increase cwnd to "
1862 << m_tcb->m_cWnd);
1863 }
1864 }
1865 else if (m_tcb->m_congState == TcpSocketState::CA_DISORDER)
1866 {
1867 // m_dupackCount should not exceed its threshold in CA_DISORDER state
1868 // when m_recoverActive has not been set. When recovery point
1869 // have been set after timeout, the sender could enter into CA_DISORDER
1870 // after receiving new ACK smaller than m_recover. After that, m_dupackCount
1871 // can be equal and larger than m_retxThresh and we should avoid entering
1872 // CA_RECOVERY and reducing sending rate again.
1874
1875 uint32_t fackDiff = 0;
1876 if (m_fackEnabled)
1877 {
1878 uint32_t headSeq = m_txBuffer->HeadSequence().GetValue();
1879 if (m_sndFack > headSeq)
1880 {
1881 fackDiff = m_sndFack - headSeq;
1882 }
1883 }
1884
1885 // RFC 6675, Section 5, continuing:
1886 // ... and take the following steps:
1887 // (1) If DupAcks >= DupThresh, go to step (4).
1888 // Sequence number comparison (m_highRxAckMark >= m_recover) will take
1889 // effect only when m_recover has been set. Hence, we can avoid to use
1890 // m_recover in the last congestion event and fail to enter
1891 // CA_RECOVERY when sequence number is advanced significantly since
1892 // the last congestion event, which could be common for
1893 // bandwidth-greedy application in high speed and reliable network
1894 // (such as datacenter network) whose sending rate is constrained by
1895 // TCP socket buffer size at receiver side.
1896
1897 // Check FACK recovery condition
1898
1899 if ((m_fackEnabled && fackDiff > m_tcb->m_segmentSize * 3) ||
1902 {
1903 EnterRecovery(currentDelivered);
1905 }
1906 // (2) If DupAcks < DupThresh but IsLost (HighACK + 1) returns true
1907 // (indicating at least three segments have arrived above the current
1908 // cumulative acknowledgment point, which is taken to indicate loss)
1909 // go to step (4). Note that m_highRxAckMark is (HighACK + 1)
1910 else if (m_txBuffer->IsLost(m_highRxAckMark))
1911 {
1912 EnterRecovery(currentDelivered);
1914 }
1915 else
1916 {
1917 // (3) The TCP MAY transmit previously unsent data segments as per
1918 // Limited Transmit [RFC5681] ...except that the number of octets
1919 // which may be sent is governed by pipe and cwnd as follows:
1920 //
1921 // (3.1) Set HighRxt to HighACK.
1922 // Not clear in RFC. We don't do this here, since we still have
1923 // to retransmit the segment.
1924
1925 if (!m_sackEnabled && m_limitedTx)
1926 {
1927 m_txBuffer->AddRenoSack();
1928
1929 // In limited transmit, cwnd Infl is not updated.
1930 }
1931 }
1932 }
1933}
1934
1935/* Process the newly received ACK */
1936void
1938{
1939 NS_LOG_FUNCTION(this << tcpHeader);
1940
1941 NS_ASSERT(0 != (tcpHeader.GetFlags() & TcpHeader::ACK));
1942 NS_ASSERT(m_tcb->m_segmentSize > 0);
1943
1944 uint32_t previousLost = m_txBuffer->GetLost();
1945 uint32_t priorInFlight = m_tcb->m_bytesInFlight.Get();
1946
1947 // RFC 6675, Section 5, 1st paragraph:
1948 // Upon the receipt of any ACK containing SACK information, the
1949 // scoreboard MUST be updated via the Update () routine (done in ReadOptions)
1950 uint32_t bytesSacked = 0;
1951 uint64_t previousDelivered = m_rateOps->GetConnectionRate().m_delivered;
1952 ReadOptions(tcpHeader, &bytesSacked);
1953
1954 SequenceNumber32 ackNumber = tcpHeader.GetAckNumber();
1955 SequenceNumber32 oldHeadSequence = m_txBuffer->HeadSequence();
1956
1957 if (ackNumber < oldHeadSequence)
1958 {
1959 NS_LOG_DEBUG("Possibly received a stale ACK (ack number < head sequence)");
1960 // If there is any data piggybacked, store it into m_rxBuffer
1961 if (packet->GetSize() > 0)
1962 {
1963 ReceivedData(packet, tcpHeader);
1964 }
1965 return;
1966 }
1967 if ((ackNumber > oldHeadSequence) && (ackNumber < m_recover) &&
1968 (m_tcb->m_congState == TcpSocketState::CA_RECOVERY))
1969 {
1970 uint32_t segAcked = (ackNumber - oldHeadSequence) / m_tcb->m_segmentSize;
1971 for (uint32_t i = 0; i < segAcked; i++)
1972 {
1973 if (m_txBuffer->IsRetransmittedDataAcked(ackNumber - (i * m_tcb->m_segmentSize)))
1974 {
1975 m_tcb->m_isRetransDataAcked = true;
1976 NS_LOG_DEBUG("Ack Number " << ackNumber << "is ACK of retransmitted packet.");
1977 }
1978 }
1979 }
1980
1981 m_txBuffer->DiscardUpTo(ackNumber, MakeCallback(&TcpRateOps::SkbDelivered, m_rateOps));
1982
1983 // Without SACK, the guessed SACKs only have meaning during fast recovery
1984 if (!m_sackEnabled && ackNumber > oldHeadSequence)
1985 {
1986 if (m_tcb->m_congState == TcpSocketState::CA_RECOVERY && ackNumber < m_recover)
1987 {
1988 // Partial ACK: the next segment is presumed lost (RFC 6582)
1989 // and will be retransmitted
1990 NS_LOG_INFO("Partial ACK. Manually setting head as lost");
1991 m_txBuffer->MarkHeadAsLost();
1992 }
1993 else
1994 {
1995 // A cumulative ACK that advances outside of fast recovery,
1996 // or that ends it, clears the guesses
1997 m_txBuffer->ResetRenoSack();
1998 }
1999 }
2000
2001 auto currentDelivered =
2002 static_cast<uint32_t>(m_rateOps->GetConnectionRate().m_delivered - previousDelivered);
2003 m_tcb->m_lastAckedSackedBytes = currentDelivered;
2004
2005 if (m_tcb->m_congState == TcpSocketState::CA_CWR && (ackNumber > m_recover))
2006 {
2007 // Recovery is over after the window exceeds m_recover
2008 // (although it may be re-entered below if ECE is still set)
2009 NS_LOG_DEBUG(TcpSocketState::TcpCongStateName[m_tcb->m_congState] << " -> CA_OPEN");
2011 m_tcb->m_congState = TcpSocketState::CA_OPEN;
2012 if (!m_congestionControl->HasCongControl())
2013 {
2014 m_tcb->m_cWnd = m_tcb->m_ssThresh.Get();
2015 m_recoveryOps->ExitRecovery(m_tcb);
2017 }
2018 }
2019
2020 if (ackNumber > oldHeadSequence && (m_tcb->m_ecnState != TcpSocketState::ECN_DISABLED) &&
2021 (tcpHeader.GetFlags() & TcpHeader::ECE))
2022 {
2023 if (m_ecnEchoSeq < ackNumber)
2024 {
2025 NS_LOG_INFO("Received ECN Echo is valid");
2026 m_ecnEchoSeq = ackNumber;
2027 NS_LOG_DEBUG(TcpSocketState::EcnStateName[m_tcb->m_ecnState] << " -> ECN_ECE_RCVD");
2028 m_tcb->m_ecnState = TcpSocketState::ECN_ECE_RCVD;
2029 if (m_tcb->m_congState != TcpSocketState::CA_CWR)
2030 {
2031 EnterCwr(currentDelivered);
2032 }
2033 }
2034 }
2035 else if (m_tcb->m_ecnState == TcpSocketState::ECN_ECE_RCVD &&
2036 !(tcpHeader.GetFlags() & TcpHeader::ECE))
2037 {
2038 m_tcb->m_ecnState = TcpSocketState::ECN_IDLE;
2039 }
2040
2041 // Update bytes in flight before processing the ACK for proper calculation of congestion window
2042 NS_LOG_INFO("Update bytes in flight before processing the ACK.");
2043 BytesInFlight();
2044
2045 bool receivedData = packet->GetSize() > 0;
2046
2047 // RFC 6675 Section 5: 2nd, 3rd paragraph and point (A), (B) implementation
2048 // are inside the function ProcessAck
2049 ProcessAck(ackNumber, (bytesSacked > 0), currentDelivered, oldHeadSequence, receivedData);
2050 m_tcb->m_isRetransDataAcked = false;
2051
2052 if (m_congestionControl->HasCongControl())
2053 {
2054 uint32_t currentLost = m_txBuffer->GetLost();
2055 uint32_t lost =
2056 (currentLost > previousLost) ? currentLost - previousLost : previousLost - currentLost;
2057 auto rateSample = m_rateOps->GenerateSample(currentDelivered,
2058 lost,
2059 false,
2060 priorInFlight,
2061 m_tcb->m_minRtt);
2062 auto rateConn = m_rateOps->GetConnectionRate();
2063 m_congestionControl->CongControl(m_tcb, rateConn, rateSample);
2064 }
2065
2066 // If there is any data piggybacked, store it into m_rxBuffer
2067 if (receivedData)
2068 {
2069 ReceivedData(packet, tcpHeader);
2070 }
2071
2072 // RFC 6675, Section 5, point (C), try to send more data. NB: (C) is implemented
2073 // inside SendPendingData
2075}
2076
2077void
2079 bool scoreboardUpdated,
2080 uint32_t currentDelivered,
2081 const SequenceNumber32& oldHeadSequence,
2082 bool receivedData)
2083{
2084 NS_LOG_FUNCTION(this << ackNumber << scoreboardUpdated << currentDelivered << oldHeadSequence);
2085 // RFC 6675, Section 5, 2nd paragraph:
2086 // If the incoming ACK is a cumulative acknowledgment, the TCP MUST
2087 // reset DupAcks to zero.
2088 bool exitedFastRecovery = false;
2089 uint32_t oldDupAckCount = m_dupAckCount; // remember the old value
2090 m_tcb->m_lastAckedSeq = ackNumber; // Update lastAckedSeq
2091 uint32_t bytesAcked = 0;
2092
2093 /* In RFC 5681 the definition of duplicate acknowledgment was strict:
2094 *
2095 * (a) the receiver of the ACK has outstanding data,
2096 * (b) the incoming acknowledgment carries no data,
2097 * (c) the SYN and FIN bits are both off,
2098 * (d) the acknowledgment number is equal to the greatest acknowledgment
2099 * received on the given connection (TCP.UNA from [RFC793]),
2100 * (e) the advertised window in the incoming acknowledgment equals the
2101 * advertised window in the last incoming acknowledgment.
2102 *
2103 * With RFC 6675, this definition has been reduced:
2104 *
2105 * (a) the ACK is carrying a SACK block that identifies previously
2106 * unacknowledged and un-SACKed octets between HighACK (TCP.UNA) and
2107 * HighData (m_highTxMark)
2108 *
2109 * The check below implements conditions a), b), and d), and c) is prevented by virtue of not
2110 * reaching this code if SYN or FIN is set, and e) is not supported.
2111 */
2112
2113 if (m_fackEnabled && ackNumber == m_txBuffer->HeadSequence() &&
2114 m_tcb->m_congState == TcpSocketState::CA_RECOVERY)
2115 {
2116 if (m_outstandingRetransBytes > m_tcb->m_segmentSize)
2117 {
2118 m_outstandingRetransBytes -= m_tcb->m_segmentSize;
2119 }
2120 else
2121 {
2123 }
2124 }
2125
2126 bool isDupack = m_sackEnabled ? scoreboardUpdated
2127 : (ackNumber == oldHeadSequence &&
2128 ackNumber < m_tcb->m_highTxMark && !receivedData);
2129
2130 NS_LOG_DEBUG("ACK of " << ackNumber << " SND.UNA=" << oldHeadSequence
2131 << " SND.NXT=" << m_tcb->m_nextTxSequence
2132 << " in state: " << TcpSocketState::TcpCongStateName[m_tcb->m_congState]
2133 << " with m_recover: " << m_recover);
2134
2135 // RFC 6675, Section 5, 3rd paragraph:
2136 // If the incoming ACK is a duplicate acknowledgment per the definition
2137 // in Section 2 (regardless of its status as a cumulative
2138 // acknowledgment), and the TCP is not currently in loss recovery
2139 if (isDupack)
2140 {
2141 // loss recovery check is done inside this function thanks to
2142 // the congestion state machine
2143 DupAck(currentDelivered);
2144 }
2145
2146 if (ackNumber == oldHeadSequence && ackNumber == m_tcb->m_highTxMark)
2147 {
2148 // Dupack, but the ACK is precisely equal to the nextTxSequence
2149 return;
2150 }
2151 else if (ackNumber == oldHeadSequence && ackNumber > m_tcb->m_highTxMark)
2152 {
2153 // ACK of the FIN bit ... nextTxSequence is not updated since we
2154 // don't have anything to transmit
2155 NS_LOG_DEBUG("Update nextTxSequence manually to " << ackNumber);
2156 m_tcb->m_nextTxSequence = ackNumber;
2157 }
2158 else if (ackNumber == oldHeadSequence)
2159 {
2160 // DupAck. Artificially call PktsAcked: after all, one segment has been ACKed.
2161 m_congestionControl->PktsAcked(m_tcb, 1, m_tcb->m_srtt);
2162 }
2163 else if (ackNumber > oldHeadSequence)
2164 {
2165 // Please remember that, with SACK, we can enter here even if we
2166 // received a dupack.
2167 bytesAcked = currentDelivered;
2168 uint32_t segsAcked = bytesAcked / m_tcb->m_segmentSize;
2169 m_bytesAckedNotProcessed += bytesAcked % m_tcb->m_segmentSize;
2170 bytesAcked -= bytesAcked % m_tcb->m_segmentSize;
2171
2172 if (m_bytesAckedNotProcessed >= m_tcb->m_segmentSize)
2173 {
2174 segsAcked += 1;
2175 bytesAcked += m_tcb->m_segmentSize;
2176 m_bytesAckedNotProcessed -= m_tcb->m_segmentSize;
2177 }
2178 NS_LOG_DEBUG("Set segsAcked: " << segsAcked
2179 << " based on currentDelivered: " << currentDelivered);
2180
2181 // Dupack count is reset to eventually fast-retransmit after 3 dupacks.
2182 // Any SACK-ed segment will be cleaned up by DiscardUpTo.
2183 // In the case that we advanced SND.UNA, but the ack contains SACK blocks,
2184 // we do not reset. At the third one we will retransmit.
2185 // If we are already in recovery, this check is useless since dupAcks
2186 // are not considered in this phase. When from Recovery we go back
2187 // to open, then dupAckCount is reset anyway.
2188 if (!isDupack)
2189 {
2190 m_dupAckCount = 0;
2191 }
2192
2193 // RFC 6675, Section 5, part (B)
2194 // (B) Upon receipt of an ACK that does not cover RecoveryPoint, the
2195 // following actions MUST be taken:
2196 //
2197 // (B.1) Use Update () to record the new SACK information conveyed
2198 // by the incoming ACK.
2199 // (B.2) Use SetPipe () to re-calculate the number of octets still
2200 // in the network.
2201 //
2202 // (B.1) is done at the beginning, while (B.2) is delayed to part (C) while
2203 // trying to transmit with SendPendingData. We are not allowed to exit
2204 // the CA_RECOVERY phase. Just process this partial ack (RFC 5681)
2205 if (ackNumber < m_recover && m_tcb->m_congState == TcpSocketState::CA_RECOVERY)
2206 {
2207 // Before retransmitting the packet perform DoRecovery and check if
2208 // there is available window
2209 if (!m_congestionControl->HasCongControl() && segsAcked >= 1)
2210 {
2211 m_recoveryOps->DoRecovery(m_tcb, currentDelivered, false);
2212 }
2213
2214 // If the packet is already retransmitted do not retransmit it
2215 if (!m_txBuffer->IsRetransmittedDataAcked(ackNumber + m_tcb->m_segmentSize))
2216 {
2217 DoRetransmit(); // Assume the next seq is lost. Retransmit lost packet
2218 m_tcb->m_cWndInfl = SafeSubtraction(m_tcb->m_cWndInfl, bytesAcked);
2219 }
2220
2221 // This partial ACK acknowledge the fact that one segment has been
2222 // previously lost and now successfully received. All others have
2223 // been processed when they come under the form of dupACKs
2224 m_congestionControl->PktsAcked(m_tcb, 1, m_tcb->m_srtt);
2225 NewAck(ackNumber, m_isFirstPartialAck);
2226
2228 {
2229 NS_LOG_DEBUG("Partial ACK of " << ackNumber
2230 << " and this is the first (RTO will be reset);"
2231 " cwnd set to "
2232 << m_tcb->m_cWnd << " recover seq: " << m_recover
2233 << " dupAck count: " << m_dupAckCount);
2234 m_isFirstPartialAck = false;
2235 }
2236 else
2237 {
2238 NS_LOG_DEBUG("Partial ACK of "
2239 << ackNumber
2240 << " and this is NOT the first (RTO will not be reset)"
2241 " cwnd set to "
2242 << m_tcb->m_cWnd << " recover seq: " << m_recover
2243 << " dupAck count: " << m_dupAckCount);
2244 }
2245 }
2246 // From RFC 6675 section 5.1
2247 // In addition, a new recovery phase (as described in Section 5) MUST NOT
2248 // be initiated until HighACK is greater than or equal to the new value
2249 // of RecoveryPoint.
2250 else if (ackNumber < m_recover && m_tcb->m_congState == TcpSocketState::CA_LOSS)
2251 {
2252 m_congestionControl->PktsAcked(m_tcb, segsAcked, m_tcb->m_srtt);
2253 m_congestionControl->IncreaseWindow(m_tcb, segsAcked);
2254
2255 NS_LOG_DEBUG(" Cong Control Called, cWnd=" << m_tcb->m_cWnd
2256 << " ssTh=" << m_tcb->m_ssThresh);
2257 if (!m_sackEnabled)
2258 {
2260 m_txBuffer->GetSacked() == 0,
2261 "Some segment got dup-acked in CA_LOSS state: " << m_txBuffer->GetSacked());
2262 }
2263 NewAck(ackNumber, true);
2264 }
2265 else if (m_tcb->m_congState == TcpSocketState::CA_CWR)
2266 {
2267 m_congestionControl->PktsAcked(m_tcb, segsAcked, m_tcb->m_srtt);
2268 // TODO: need to check behavior if marking is compounded by loss
2269 // and/or packet reordering
2270 if (!m_congestionControl->HasCongControl() && segsAcked >= 1)
2271 {
2272 m_recoveryOps->DoRecovery(m_tcb, currentDelivered, false);
2273 }
2274 NewAck(ackNumber, true);
2275 }
2276 else
2277 {
2278 if (m_tcb->m_congState == TcpSocketState::CA_OPEN)
2279 {
2280 m_congestionControl->PktsAcked(m_tcb, segsAcked, m_tcb->m_srtt);
2281 }
2282 else if (m_tcb->m_congState == TcpSocketState::CA_DISORDER)
2283 {
2284 if (segsAcked >= oldDupAckCount)
2285 {
2286 m_congestionControl->PktsAcked(m_tcb,
2287 segsAcked - oldDupAckCount,
2288 m_tcb->m_srtt);
2289 }
2290
2291 if (!isDupack)
2292 {
2293 // The network reorder packets. Linux changes the counting lost
2294 // packet algorithm from FACK to NewReno. We simply go back in Open.
2296 m_tcb->m_congState = TcpSocketState::CA_OPEN;
2297 NS_LOG_DEBUG(segsAcked << " segments acked in CA_DISORDER, ack of " << ackNumber
2298 << " exiting CA_DISORDER -> CA_OPEN");
2299 }
2300 else
2301 {
2302 NS_LOG_DEBUG(segsAcked << " segments acked in CA_DISORDER, ack of " << ackNumber
2303 << " but still in CA_DISORDER");
2304 }
2305 }
2306 // RFC 6675, Section 5:
2307 // Once a TCP is in the loss recovery phase, the following procedure
2308 // MUST be used for each arriving ACK:
2309 // (A) An incoming cumulative ACK for a sequence number greater than
2310 // RecoveryPoint signals the end of loss recovery, and the loss
2311 // recovery phase MUST be terminated. Any information contained in
2312 // the scoreboard for sequence numbers greater than the new value of
2313 // HighACK SHOULD NOT be cleared when leaving the loss recovery
2314 // phase.
2315 else if (m_tcb->m_congState == TcpSocketState::CA_RECOVERY)
2316 {
2317 m_isFirstPartialAck = true;
2318
2319 // Recalculate the segs acked, that are from m_recover to ackNumber
2320 // (which are the ones we have not passed to PktsAcked and that
2321 // can increase cWnd)
2322 // TODO: check consistency for dynamic segment size
2323 segsAcked =
2324 static_cast<uint32_t>(ackNumber - oldHeadSequence) / m_tcb->m_segmentSize;
2325 m_congestionControl->PktsAcked(m_tcb, segsAcked, m_tcb->m_srtt);
2328 m_tcb->m_congState = TcpSocketState::CA_OPEN;
2329 exitedFastRecovery = true;
2330 m_dupAckCount = 0; // From recovery to open, reset dupack
2331
2332 NS_LOG_DEBUG(segsAcked << " segments acked in CA_RECOVER, ack of " << ackNumber
2333 << ", exiting CA_RECOVERY -> CA_OPEN");
2334 }
2335 else if (m_tcb->m_congState == TcpSocketState::CA_LOSS)
2336 {
2337 m_isFirstPartialAck = true;
2338
2339 // Recalculate the segs acked, that are from m_recover to ackNumber
2340 // (which are the ones we have not passed to PktsAcked and that
2341 // can increase cWnd)
2342 segsAcked = (ackNumber - m_recover) / m_tcb->m_segmentSize;
2343
2344 m_congestionControl->PktsAcked(m_tcb, segsAcked, m_tcb->m_srtt);
2345
2347 m_tcb->m_congState = TcpSocketState::CA_OPEN;
2348 NS_LOG_DEBUG(segsAcked << " segments acked in CA_LOSS, ack of" << ackNumber
2349 << ", exiting CA_LOSS -> CA_OPEN");
2350 }
2351
2352 if (ackNumber >= m_recover)
2353 {
2354 // All lost segments in the congestion event have been
2355 // retransmitted successfully. The recovery point (m_recover)
2356 // should be deactivated.
2357 m_recoverActive = false;
2358 }
2359
2360 if (exitedFastRecovery)
2361 {
2362 NewAck(ackNumber, true);
2363 m_tcb->m_cWnd = m_tcb->m_ssThresh.Get();
2364 m_recoveryOps->ExitRecovery(m_tcb);
2365 NS_LOG_INFO("Exit CA_RECOVERY -> CA_OPEN: ack "
2366 << ackNumber << " reached recover " << m_recover << "; cWnd "
2367 << m_tcb->m_cWnd << " ssThresh " << m_tcb->m_ssThresh
2368 << " bytesInFlight " << BytesInFlight());
2369 NS_LOG_DEBUG("Leaving Fast Recovery; BytesInFlight() = "
2370 << BytesInFlight() << "; cWnd = " << m_tcb->m_cWnd);
2371 }
2372 if (m_tcb->m_congState == TcpSocketState::CA_OPEN)
2373 {
2374 m_congestionControl->IncreaseWindow(m_tcb, segsAcked);
2375
2376 m_tcb->m_cWndInfl = m_tcb->m_cWnd;
2377
2378 NS_LOG_LOGIC("Congestion control called: cWnd: " << m_tcb->m_cWnd
2379 << " ssTh: " << m_tcb->m_ssThresh
2380 << " segsAcked: " << segsAcked);
2381
2382 NewAck(ackNumber, true);
2383 }
2384 }
2385 }
2386 // Update the pacing rate, since m_congestionControl->IncreaseWindow() or
2387 // m_congestionControl->PktsAcked () may change m_tcb->m_cWnd
2388 // Make sure that control reaches the end of this function and there is no
2389 // return in between
2391}
2392
2393/* Received a packet upon LISTEN state. */
2394void
2396 const TcpHeader& tcpHeader,
2397 const Address& fromAddress,
2398 const Address& toAddress)
2399{
2400 NS_LOG_FUNCTION(this << tcpHeader);
2401
2402 // Extract the flags. PSH, URG, CWR and ECE are disregarded.
2403 uint8_t tcpflags =
2405
2406 // Fork a socket if received a SYN. Do nothing otherwise.
2407 // C.f.: the LISTEN part in tcp_v4_do_rcv() in tcp_ipv4.c in Linux kernel
2408 if (tcpflags != TcpHeader::SYN)
2409 {
2410 return;
2411 }
2412
2413 // Call socket's notify function to let the server app know we got a SYN
2414 // If the server app refuses the connection, do nothing
2415 if (!NotifyConnectionRequest(fromAddress))
2416 {
2417 return;
2418 }
2419 // Clone the socket, simulate fork
2420 Ptr<TcpSocketBase> newSock = Fork();
2421 NS_LOG_LOGIC("Cloned a TcpSocketBase " << newSock);
2423 newSock,
2424 packet,
2425 tcpHeader,
2426 fromAddress,
2427 toAddress);
2428}
2429
2430/* Received a packet upon SYN_SENT */
2431void
2433{
2434 NS_LOG_FUNCTION(this << tcpHeader);
2435
2436 // Extract the flags. PSH and URG are disregarded.
2437 uint8_t tcpflags = tcpHeader.GetFlags() & ~(TcpHeader::PSH | TcpHeader::URG);
2438
2439 if (tcpflags == 0)
2440 { // Bare data, accept it and move to ESTABLISHED state. This is not a normal behaviour. Remove
2441 // this?
2442 NS_LOG_DEBUG("SYN_SENT -> ESTABLISHED");
2444 m_tcb->m_congState = TcpSocketState::CA_OPEN;
2446 m_connected = true;
2447 m_retxEvent.Cancel();
2449 ReceivedData(packet, tcpHeader);
2451 }
2452 else if (tcpflags & TcpHeader::ACK && !(tcpflags & TcpHeader::SYN))
2453 { // Ignore ACK in SYN_SENT
2454 }
2455 else if (tcpflags & TcpHeader::SYN && !(tcpflags & TcpHeader::ACK))
2456 { // Received SYN, move to SYN_RCVD state and respond with SYN+ACK
2457 NS_LOG_DEBUG("SYN_SENT -> SYN_RCVD");
2458 m_state = SYN_RCVD;
2460 m_tcb->m_rxBuffer->SetNextRxSequence(tcpHeader.GetSequenceNumber() + SequenceNumber32(1));
2461 /* Check if we received an ECN SYN packet. Change the ECN state of receiver to ECN_IDLE if
2462 * the traffic is ECN capable and sender has sent ECN SYN packet
2463 */
2464
2465 if (m_tcb->m_useEcn != TcpSocketState::Off &&
2467 {
2468 NS_LOG_INFO("Received ECN SYN packet");
2470 NS_LOG_DEBUG(TcpSocketState::EcnStateName[m_tcb->m_ecnState] << " -> ECN_IDLE");
2471 m_tcb->m_ecnState = TcpSocketState::ECN_IDLE;
2472 }
2473 else
2474 {
2475 m_tcb->m_ecnState = TcpSocketState::ECN_DISABLED;
2477 }
2478 }
2479 else if (tcpflags & (TcpHeader::SYN | TcpHeader::ACK) &&
2480 m_tcb->m_nextTxSequence + SequenceNumber32(1) == tcpHeader.GetAckNumber())
2481 { // Handshake completed
2482 NS_LOG_DEBUG("SYN_SENT -> ESTABLISHED");
2484 m_tcb->m_congState = TcpSocketState::CA_OPEN;
2486 m_connected = true;
2487 m_retxEvent.Cancel();
2488 m_tcb->m_rxBuffer->SetNextRxSequence(tcpHeader.GetSequenceNumber() + SequenceNumber32(1));
2489 m_tcb->m_highTxMark = ++m_tcb->m_nextTxSequence;
2490 m_txBuffer->SetHeadSequence(m_tcb->m_nextTxSequence);
2491 // Before sending packets, update the pacing rate based on RTT measurement so far
2494
2495 /* Check if we received an ECN SYN-ACK packet. Change the ECN state of sender to ECN_IDLE if
2496 * receiver has sent an ECN SYN-ACK packet and the traffic is ECN Capable
2497 */
2498 if (m_tcb->m_useEcn != TcpSocketState::Off &&
2499 (tcpflags & (TcpHeader::CWR | TcpHeader::ECE)) == (TcpHeader::ECE))
2500 {
2501 NS_LOG_INFO("Received ECN SYN-ACK packet.");
2502 NS_LOG_DEBUG(TcpSocketState::EcnStateName[m_tcb->m_ecnState] << " -> ECN_IDLE");
2503 m_tcb->m_ecnState = TcpSocketState::ECN_IDLE;
2504 }
2505 else
2506 {
2507 m_tcb->m_ecnState = TcpSocketState::ECN_DISABLED;
2508 }
2511 // Always respond to first data packet to speed up the connection.
2512 // Remove to get the behaviour of old NS-3 code.
2514 }
2515 else
2516 { // Other in-sequence input
2517 if (!(tcpflags & TcpHeader::RST))
2518 { // When (1) rx of FIN+ACK; (2) rx of FIN; (3) rx of bad flags
2519 NS_LOG_LOGIC("Illegal flag combination "
2520 << TcpHeader::FlagsToString(tcpHeader.GetFlags())
2521 << " received in SYN_SENT. Reset packet is sent.");
2522 SendRST();
2523 }
2525 }
2526}
2527
2528/* Received a packet upon SYN_RCVD */
2529void
2531 const TcpHeader& tcpHeader,
2532 const Address& fromAddress,
2533 const Address& /* toAddress */)
2534{
2535 NS_LOG_FUNCTION(this << tcpHeader);
2536
2537 // Extract the flags. PSH, URG, CWR and ECE are disregarded.
2538 uint8_t tcpflags =
2540
2541 if (tcpflags == 0 ||
2542 (tcpflags == TcpHeader::ACK &&
2543 m_tcb->m_nextTxSequence + SequenceNumber32(1) == tcpHeader.GetAckNumber()))
2544 { // If it is bare data, accept it and move to ESTABLISHED state. This is
2545 // possibly due to ACK lost in 3WHS. If in-sequence ACK is received, the
2546 // handshake is completed nicely.
2547 NS_LOG_DEBUG("SYN_RCVD -> ESTABLISHED");
2549 m_tcb->m_congState = TcpSocketState::CA_OPEN;
2551 m_connected = true;
2552 m_retxEvent.Cancel();
2553 m_tcb->m_highTxMark = ++m_tcb->m_nextTxSequence;
2554 m_txBuffer->SetHeadSequence(m_tcb->m_nextTxSequence);
2555 if (m_endPoint)
2556 {
2557 m_endPoint->SetPeer(InetSocketAddress::ConvertFrom(fromAddress).GetIpv4(),
2558 InetSocketAddress::ConvertFrom(fromAddress).GetPort());
2559 }
2560 else if (m_endPoint6)
2561 {
2562 m_endPoint6->SetPeer(Inet6SocketAddress::ConvertFrom(fromAddress).GetIpv6(),
2563 Inet6SocketAddress::ConvertFrom(fromAddress).GetPort());
2564 }
2565 // Always respond to first data packet to speed up the connection.
2566 // Remove to get the behaviour of old NS-3 code.
2568 NotifyNewConnectionCreated(this, fromAddress);
2569 ReceivedAck(packet, tcpHeader);
2570 // Update the pacing rate based on RTT measurement so far
2572 // As this connection is established, the socket is available to send data now
2573 if (GetTxAvailable() > 0)
2574 {
2576 }
2577 }
2578 else if (tcpflags == TcpHeader::SYN)
2579 { // Probably the peer lost my SYN+ACK
2580 m_tcb->m_rxBuffer->SetNextRxSequence(tcpHeader.GetSequenceNumber() + SequenceNumber32(1));
2581 /* Check if we received an ECN SYN packet. Change the ECN state of receiver to ECN_IDLE if
2582 * sender has sent an ECN SYN packet and the traffic is ECN Capable
2583 */
2584 if (m_tcb->m_useEcn != TcpSocketState::Off &&
2585 (tcpHeader.GetFlags() & (TcpHeader::CWR | TcpHeader::ECE)) ==
2587 {
2588 NS_LOG_INFO("Received ECN SYN packet");
2590 NS_LOG_DEBUG(TcpSocketState::EcnStateName[m_tcb->m_ecnState] << " -> ECN_IDLE");
2591 m_tcb->m_ecnState = TcpSocketState::ECN_IDLE;
2592 }
2593 else
2594 {
2595 m_tcb->m_ecnState = TcpSocketState::ECN_DISABLED;
2597 }
2598 }
2599 else if (tcpflags == (TcpHeader::FIN | TcpHeader::ACK))
2600 {
2601 if (tcpHeader.GetSequenceNumber() == m_tcb->m_rxBuffer->NextRxSequence())
2602 { // In-sequence FIN before connection complete. Set up connection and close.
2603 m_connected = true;
2604 m_retxEvent.Cancel();
2605 m_tcb->m_highTxMark = ++m_tcb->m_nextTxSequence;
2606 m_txBuffer->SetHeadSequence(m_tcb->m_nextTxSequence);
2607 if (m_endPoint)
2608 {
2609 m_endPoint->SetPeer(InetSocketAddress::ConvertFrom(fromAddress).GetIpv4(),
2610 InetSocketAddress::ConvertFrom(fromAddress).GetPort());
2611 }
2612 else if (m_endPoint6)
2613 {
2614 m_endPoint6->SetPeer(Inet6SocketAddress::ConvertFrom(fromAddress).GetIpv6(),
2615 Inet6SocketAddress::ConvertFrom(fromAddress).GetPort());
2616 }
2617 NotifyNewConnectionCreated(this, fromAddress);
2618 PeerClose(packet, tcpHeader);
2619 }
2620 }
2621 else
2622 { // Other in-sequence input
2623 if (tcpflags != TcpHeader::RST)
2624 { // When (1) rx of SYN+ACK; (2) rx of FIN; (3) rx of bad flags
2625 NS_LOG_LOGIC("Illegal flag " << TcpHeader::FlagsToString(tcpflags)
2626 << " received. Reset packet is sent.");
2627 if (m_endPoint)
2628 {
2629 m_endPoint->SetPeer(InetSocketAddress::ConvertFrom(fromAddress).GetIpv4(),
2630 InetSocketAddress::ConvertFrom(fromAddress).GetPort());
2631 }
2632 else if (m_endPoint6)
2633 {
2634 m_endPoint6->SetPeer(Inet6SocketAddress::ConvertFrom(fromAddress).GetIpv6(),
2635 Inet6SocketAddress::ConvertFrom(fromAddress).GetPort());
2636 }
2637 SendRST();
2638 }
2640 }
2641}
2642
2643/* Received a packet upon CLOSE_WAIT, FIN_WAIT_1, or FIN_WAIT_2 states */
2644void
2646{
2647 NS_LOG_FUNCTION(this << tcpHeader);
2648
2649 // Extract the flags. PSH, URG, CWR and ECE are disregarded.
2650 uint8_t tcpflags =
2652
2653 if (packet->GetSize() > 0 && !(tcpflags & TcpHeader::ACK))
2654 { // Bare data, accept it
2655 ReceivedData(packet, tcpHeader);
2656 }
2657 else if (tcpflags == TcpHeader::ACK)
2658 { // Process the ACK, and if in FIN_WAIT_1, conditionally move to FIN_WAIT_2
2659 ReceivedAck(packet, tcpHeader);
2660 if (m_state == FIN_WAIT_1 && m_txBuffer->Size() == 0 &&
2661 tcpHeader.GetAckNumber() == m_tcb->m_highTxMark + SequenceNumber32(1))
2662 { // This ACK corresponds to the FIN sent
2663 NS_LOG_DEBUG("FIN_WAIT_1 -> FIN_WAIT_2");
2665 }
2666 }
2667 else if (tcpflags == TcpHeader::FIN || tcpflags == (TcpHeader::FIN | TcpHeader::ACK))
2668 { // Got FIN, respond with ACK and move to next state
2669 if (tcpflags & TcpHeader::ACK)
2670 { // Process the ACK first
2671 ReceivedAck(packet, tcpHeader);
2672 }
2673 m_tcb->m_rxBuffer->SetFinSequence(tcpHeader.GetSequenceNumber());
2674 }
2675 else if (tcpflags == TcpHeader::SYN || tcpflags == (TcpHeader::SYN | TcpHeader::ACK))
2676 { // Duplicated SYN or SYN+ACK, possibly due to spurious retransmission
2677 return;
2678 }
2679 else
2680 { // This is a RST or bad flags
2681 if (tcpflags != TcpHeader::RST)
2682 {
2683 NS_LOG_LOGIC("Illegal flag " << TcpHeader::FlagsToString(tcpflags)
2684 << " received. Reset packet is sent.");
2685 SendRST();
2686 }
2688 return;
2689 }
2690
2691 // Check if the close responder sent an in-sequence FIN, if so, respond ACK
2692 if ((m_state == FIN_WAIT_1 || m_state == FIN_WAIT_2) && m_tcb->m_rxBuffer->Finished())
2693 {
2694 if (m_state == FIN_WAIT_1)
2695 {
2696 NS_LOG_DEBUG("FIN_WAIT_1 -> CLOSING");
2697 m_state = CLOSING;
2698 if (m_txBuffer->Size() == 0 &&
2699 tcpHeader.GetAckNumber() == m_tcb->m_highTxMark + SequenceNumber32(1))
2700 { // This ACK corresponds to the FIN sent
2701 TimeWait();
2702 }
2703 }
2704 else if (m_state == FIN_WAIT_2)
2705 {
2706 TimeWait();
2707 }
2709 if (!m_shutdownRecv)
2710 {
2712 }
2713 }
2714}
2715
2716/* Received a packet upon CLOSING */
2717void
2719{
2720 NS_LOG_FUNCTION(this << tcpHeader);
2721
2722 // Extract the flags. PSH and URG are disregarded.
2723 uint8_t tcpflags = tcpHeader.GetFlags() & ~(TcpHeader::PSH | TcpHeader::URG);
2724
2725 if (tcpflags == TcpHeader::ACK)
2726 {
2727 if (tcpHeader.GetSequenceNumber() == m_tcb->m_rxBuffer->NextRxSequence())
2728 { // This ACK corresponds to the FIN sent
2729 TimeWait();
2730 }
2731 }
2732 else
2733 { // CLOSING state means simultaneous close, i.e. no one is sending data to
2734 // anyone. If anything other than ACK is received, respond with a reset.
2735 if (tcpflags == TcpHeader::FIN || tcpflags == (TcpHeader::FIN | TcpHeader::ACK))
2736 { // FIN from the peer as well. We can close immediately.
2738 }
2739 else if (tcpflags != TcpHeader::RST)
2740 { // Receive of SYN or SYN+ACK or bad flags or pure data
2741 NS_LOG_LOGIC("Illegal flag " << TcpHeader::FlagsToString(tcpflags)
2742 << " received. Reset packet is sent.");
2743 SendRST();
2744 }
2746 }
2747}
2748
2749/* Received a packet upon LAST_ACK */
2750void
2752{
2753 NS_LOG_FUNCTION(this << tcpHeader);
2754
2755 // Extract the flags. PSH and URG are disregarded.
2756 uint8_t tcpflags = tcpHeader.GetFlags() & ~(TcpHeader::PSH | TcpHeader::URG);
2757
2758 if (tcpflags == 0)
2759 {
2760 ReceivedData(packet, tcpHeader);
2761 }
2762 else if (tcpflags == TcpHeader::ACK)
2763 {
2764 if (tcpHeader.GetSequenceNumber() == m_tcb->m_rxBuffer->NextRxSequence())
2765 { // This ACK corresponds to the FIN sent. This socket closed peacefully.
2767 }
2768 }
2769 else if (tcpflags == TcpHeader::FIN)
2770 { // Received FIN again, the peer probably lost the FIN+ACK
2772 }
2773 else if (tcpflags == (TcpHeader::FIN | TcpHeader::ACK) || tcpflags == TcpHeader::RST)
2774 {
2776 }
2777 else
2778 { // Received a SYN or SYN+ACK or bad flags
2779 NS_LOG_LOGIC("Illegal flag " << TcpHeader::FlagsToString(tcpflags)
2780 << " received. Reset packet is sent.");
2781 SendRST();
2783 }
2784}
2785
2786/* Peer sent me a FIN. Remember its sequence in rx buffer. */
2787void
2789{
2790 NS_LOG_FUNCTION(this << tcpHeader);
2791
2792 // Ignore all out of range packets
2793 if (tcpHeader.GetSequenceNumber() < m_tcb->m_rxBuffer->NextRxSequence() ||
2794 tcpHeader.GetSequenceNumber() > m_tcb->m_rxBuffer->MaxRxSequence())
2795 {
2796 return;
2797 }
2798 // For any case, remember the FIN position in rx buffer first
2799 m_tcb->m_rxBuffer->SetFinSequence(tcpHeader.GetSequenceNumber() +
2800 SequenceNumber32(p->GetSize()));
2801 NS_LOG_LOGIC("Accepted FIN at seq "
2802 << tcpHeader.GetSequenceNumber() + SequenceNumber32(p->GetSize()));
2803 // If there is any piggybacked data, process it
2804 if (p->GetSize())
2805 {
2806 ReceivedData(p, tcpHeader);
2807 }
2808 // Return if FIN is out of sequence, otherwise move to CLOSE_WAIT state by DoPeerClose
2809 if (!m_tcb->m_rxBuffer->Finished())
2810 {
2811 return;
2812 }
2813
2814 // Simultaneous close: Application invoked Close() when we are processing this FIN packet
2815 if (m_state == FIN_WAIT_1)
2816 {
2817 NS_LOG_DEBUG("FIN_WAIT_1 -> CLOSING");
2818 m_state = CLOSING;
2819 return;
2820 }
2821
2822 DoPeerClose(); // Change state, respond with ACK
2823}
2824
2825/* Received a in-sequence FIN. Close down this socket. */
2826void
2828{
2830 m_state == FIN_WAIT_2);
2831
2832 // Move the state to CLOSE_WAIT
2833 NS_LOG_DEBUG(TcpStateName[m_state] << " -> CLOSE_WAIT");
2835
2836 if (!m_closeNotified)
2837 {
2838 // The normal behaviour for an application is that, when the peer sent a in-sequence
2839 // FIN, the app should prepare to close. The app has two choices at this point: either
2840 // respond with ShutdownSend() call to declare that it has nothing more to send and
2841 // the socket can be closed immediately; or remember the peer's close request, wait
2842 // until all its existing data are pushed into the TCP socket, then call Close()
2843 // explicitly.
2844 NS_LOG_LOGIC("TCP " << this << " calling NotifyNormalClose");
2846 m_closeNotified = true;
2847 }
2848 if (m_shutdownSend)
2849 { // The application declares that it would not sent any more, close this socket
2850 Close();
2851 }
2852 else
2853 { // Need to ack, the application will close later
2855 }
2856 if (m_state == LAST_ACK)
2857 {
2858 m_dataRetrCount = m_dataRetries; // prevent endless FINs
2859 NS_LOG_LOGIC("TcpSocketBase " << this << " scheduling LATO1");
2860 Time lastRto = m_rtt->GetEstimate() + Max(m_clockGranularity, m_rtt->GetVariation() * 4);
2862 }
2863}
2864
2865/* Kill this socket. This is a callback function configured to m_endpoint in
2866 SetupCallback(), invoked when the endpoint is destroyed. */
2867void
2869{
2870 NS_LOG_FUNCTION(this);
2871 m_endPoint = nullptr;
2872 if (m_tcp)
2873 {
2874 m_tcp->RemoveSocket(this);
2875 }
2876 NS_LOG_LOGIC(this << " Cancelled ReTxTimeout event which was set to expire at "
2877 << (Simulator::Now() + Simulator::GetDelayLeft(m_retxEvent)).GetSeconds());
2879}
2880
2881/* Kill this socket. This is a callback function configured to m_endpoint in
2882 SetupCallback(), invoked when the endpoint is destroyed. */
2883void
2885{
2886 NS_LOG_FUNCTION(this);
2887 m_endPoint6 = nullptr;
2888 if (m_tcp)
2889 {
2890 m_tcp->RemoveSocket(this);
2891 }
2892 NS_LOG_LOGIC(this << " Cancelled ReTxTimeout event which was set to expire at "
2893 << (Simulator::Now() + Simulator::GetDelayLeft(m_retxEvent)).GetSeconds());
2895}
2896
2897/* Send an empty packet with specified TCP flags */
2898void
2900{
2901 NS_LOG_FUNCTION(this << static_cast<uint32_t>(flags));
2902
2903 if (m_endPoint == nullptr && m_endPoint6 == nullptr)
2904 {
2905 NS_LOG_WARN("Failed to send empty packet due to null endpoint");
2906 return;
2907 }
2908
2910 TcpHeader header;
2911 SequenceNumber32 s = m_tcb->m_nextTxSequence;
2912 TcpPacketType_t packetType = INVALID;
2913
2914 if (flags & TcpHeader::FIN)
2915 {
2916 packetType = TcpPacketType_t::FIN;
2917 flags |= TcpHeader::ACK;
2918 }
2919 else if (m_state == FIN_WAIT_1 || m_state == LAST_ACK || m_state == CLOSING)
2920 {
2921 ++s;
2922 }
2923
2924 if (flags & TcpHeader::SYN)
2925 {
2926 packetType = TcpPacketType_t::SYN;
2927 if (flags & TcpHeader::ACK)
2928 {
2929 packetType = TcpPacketType_t::SYN_ACK;
2930 }
2931 }
2932 else if (flags & TcpHeader::ACK)
2933 {
2934 packetType = TcpPacketType_t::PURE_ACK;
2935 }
2936
2937 if (flags & TcpHeader::RST)
2938 {
2939 packetType = TcpPacketType_t::RST;
2940 }
2941
2942 NS_ASSERT_MSG(packetType != TcpPacketType_t::INVALID, "Invalid TCP packet type");
2943 AddSocketTags(p, IsEct(packetType));
2944
2945 header.SetFlags(flags);
2946 header.SetSequenceNumber(s);
2947 header.SetAckNumber(m_tcb->m_rxBuffer->NextRxSequence());
2948 if (m_endPoint != nullptr)
2949 {
2950 header.SetSourcePort(m_endPoint->GetLocalPort());
2951 header.SetDestinationPort(m_endPoint->GetPeerPort());
2952 }
2953 else
2954 {
2955 header.SetSourcePort(m_endPoint6->GetLocalPort());
2956 header.SetDestinationPort(m_endPoint6->GetPeerPort());
2957 }
2958 AddOptions(header);
2959
2960 // RFC 6298, clause 2.4
2961 m_rto =
2962 Max(m_rtt->GetEstimate() + Max(m_clockGranularity, m_rtt->GetVariation() * 4), m_minRto);
2963
2964 uint16_t windowSize = AdvertisedWindowSize();
2965 bool hasSyn = flags & TcpHeader::SYN;
2966 bool hasFin = flags & TcpHeader::FIN;
2967 bool isAck = flags == TcpHeader::ACK;
2968 if (hasSyn)
2969 {
2971 { // The window scaling option is set only on SYN packets
2972 AddOptionWScale(header);
2973 }
2974
2975 if (m_sackEnabled)
2976 {
2977 AddOptionSackPermitted(header);
2978 }
2979
2980 if (m_synCount == 0)
2981 { // No more connection retries, give up
2982 NS_LOG_LOGIC("Connection failed.");
2983 m_rtt->Reset(); // According to recommendation -> RFC 6298
2985 m_state = CLOSED;
2987 return;
2988 }
2989 else
2990 { // Exponential backoff of connection time out
2991 int backoffCount = 0x1 << (m_synRetries - m_synCount);
2992 m_rto = m_cnTimeout * backoffCount;
2993 m_synCount--;
2994 }
2995
2996 if (m_synRetries - 1 == m_synCount)
2997 {
2998 UpdateRttHistory(s, 0, false);
2999 }
3000 else
3001 { // This is SYN retransmission
3002 UpdateRttHistory(s, 0, true);
3003 }
3004
3005 windowSize = AdvertisedWindowSize(false);
3006 }
3007 header.SetWindowSize(windowSize);
3008
3009 if (flags & TcpHeader::ACK)
3010 { // If sending an ACK, cancel the delay ACK as well
3011 m_delAckEvent.Cancel();
3012 m_delAckCount = 0;
3013 if (m_highTxAck < header.GetAckNumber())
3014 {
3015 m_highTxAck = header.GetAckNumber();
3016 }
3017 if (m_sackEnabled && m_tcb->m_rxBuffer->GetSackListSize() > 0)
3018 {
3019 AddOptionSack(header);
3020 }
3021 NS_LOG_INFO("Sending a pure ACK, acking seq " << m_tcb->m_rxBuffer->NextRxSequence());
3022 }
3023
3024 m_txTrace(p, header, this);
3025
3026 if (m_endPoint != nullptr)
3027 {
3028 m_tcp->SendPacket(p,
3029 header,
3030 m_endPoint->GetLocalAddress(),
3031 m_endPoint->GetPeerAddress(),
3033 }
3034 else
3035 {
3036 m_tcp->SendPacket(p,
3037 header,
3038 m_endPoint6->GetLocalAddress(),
3039 m_endPoint6->GetPeerAddress(),
3041 }
3042
3043 if (m_retxEvent.IsExpired() && (hasSyn || hasFin) && !isAck)
3044 { // Retransmit SYN / SYN+ACK / FIN / FIN+ACK to guard against lost
3045 NS_LOG_LOGIC("Schedule retransmission timeout at time "
3046 << Simulator::Now().GetSeconds() << " to expire at time "
3047 << (Simulator::Now() + m_rto.Get()).GetSeconds());
3049 }
3050}
3051
3052/* This function closes the endpoint completely. Called upon RST_TX action. */
3053void
3061
3062/* Deallocate the end point and cancel all the timers */
3063void
3065{
3066 // note: it shouldn't be necessary to invalidate the callback and manually call
3067 // TcpL4Protocol::RemoveSocket. Alas, if one relies on the endpoint destruction
3068 // callback, there's a weird memory access to a free'd area. Harmless, but valgrind
3069 // considers it an error.
3070
3071 if (m_endPoint != nullptr)
3072 {
3074 m_endPoint->SetDestroyCallback(MakeNullCallback<void>());
3075 m_tcp->DeAllocate(m_endPoint);
3076 m_endPoint = nullptr;
3077 m_tcp->RemoveSocket(this);
3078 }
3079 else if (m_endPoint6 != nullptr)
3080 {
3082 m_endPoint6->SetDestroyCallback(MakeNullCallback<void>());
3083 m_tcp->DeAllocate(m_endPoint6);
3084 m_endPoint6 = nullptr;
3085 m_tcp->RemoveSocket(this);
3086 }
3087}
3088
3089/* Configure the endpoint to a local address. Called by Connect() if Bind() didn't specify one. */
3090int
3092{
3093 NS_LOG_FUNCTION(this);
3094 Ptr<Ipv4> ipv4 = m_node->GetObject<Ipv4>();
3095 NS_ASSERT(ipv4);
3096 if (!ipv4->GetRoutingProtocol())
3097 {
3098 NS_FATAL_ERROR("No Ipv4RoutingProtocol in the node");
3099 }
3100 // Create a dummy packet, then ask the routing function for the best output
3101 // interface's address
3102 Ipv4Header header;
3103 header.SetDestination(m_endPoint->GetPeerAddress());
3104 Socket::SocketErrno errno_;
3105 Ptr<Ipv4Route> route;
3107 route = ipv4->GetRoutingProtocol()->RouteOutput(Ptr<Packet>(), header, oif, errno_);
3108 if (!route)
3109 {
3110 NS_LOG_LOGIC("Route to " << m_endPoint->GetPeerAddress() << " does not exist");
3111 NS_LOG_ERROR(errno_);
3112 m_errno = errno_;
3113 return -1;
3114 }
3115 NS_LOG_LOGIC("Route exists");
3116 m_endPoint->SetLocalAddress(route->GetSource());
3117 return 0;
3118}
3119
3120int
3122{
3123 NS_LOG_FUNCTION(this);
3124 Ptr<Ipv6L3Protocol> ipv6 = m_node->GetObject<Ipv6L3Protocol>();
3125 NS_ASSERT(ipv6);
3126 if (!ipv6->GetRoutingProtocol())
3127 {
3128 NS_FATAL_ERROR("No Ipv6RoutingProtocol in the node");
3129 }
3130 // Create a dummy packet, then ask the routing function for the best output
3131 // interface's address
3132 Ipv6Header header;
3133 header.SetDestination(m_endPoint6->GetPeerAddress());
3134 Socket::SocketErrno errno_;
3135 Ptr<Ipv6Route> route;
3137 route = ipv6->GetRoutingProtocol()->RouteOutput(Ptr<Packet>(), header, oif, errno_);
3138 if (!route)
3139 {
3140 NS_LOG_LOGIC("Route to " << m_endPoint6->GetPeerAddress() << " does not exist");
3141 NS_LOG_ERROR(errno_);
3142 m_errno = errno_;
3143 return -1;
3144 }
3145 NS_LOG_LOGIC("Route exists");
3146 m_endPoint6->SetLocalAddress(route->GetSource());
3147 return 0;
3148}
3149
3150/* This function is called only if a SYN received in LISTEN state. After
3151 TcpSocketBase cloned, allocate a new end point to handle the incoming
3152 connection and send a SYN+ACK to complete the handshake. */
3153void
3155 const TcpHeader& h,
3156 const Address& fromAddress,
3157 const Address& toAddress)
3158{
3159 NS_LOG_FUNCTION(this << p << h << fromAddress << toAddress);
3160 // Get port and address from peer (connecting host)
3161 if (InetSocketAddress::IsMatchingType(toAddress))
3162 {
3163 m_endPoint = m_tcp->Allocate(GetBoundNetDevice(),
3164 InetSocketAddress::ConvertFrom(toAddress).GetIpv4(),
3165 InetSocketAddress::ConvertFrom(toAddress).GetPort(),
3166 InetSocketAddress::ConvertFrom(fromAddress).GetIpv4(),
3167 InetSocketAddress::ConvertFrom(fromAddress).GetPort());
3168 m_endPoint6 = nullptr;
3169 }
3170 else if (Inet6SocketAddress::IsMatchingType(toAddress))
3171 {
3172 m_endPoint6 = m_tcp->Allocate6(GetBoundNetDevice(),
3173 Inet6SocketAddress::ConvertFrom(toAddress).GetIpv6(),
3174 Inet6SocketAddress::ConvertFrom(toAddress).GetPort(),
3175 Inet6SocketAddress::ConvertFrom(fromAddress).GetIpv6(),
3176 Inet6SocketAddress::ConvertFrom(fromAddress).GetPort());
3177 m_endPoint = nullptr;
3178 }
3179 m_tcp->AddSocket(this);
3180
3181 // Change the cloned socket from LISTEN state to SYN_RCVD
3182 NS_LOG_DEBUG("LISTEN -> SYN_RCVD");
3183 m_state = SYN_RCVD;
3186 SetupCallback();
3187 // Set the sequence number and send SYN+ACK
3188 m_tcb->m_rxBuffer->SetNextRxSequence(h.GetSequenceNumber() + SequenceNumber32(1));
3189
3190 /* Check if we received an ECN SYN packet. Change the ECN state of receiver to ECN_IDLE if
3191 * sender has sent an ECN SYN packet and the traffic is ECN Capable
3192 */
3193 if (m_tcb->m_useEcn != TcpSocketState::Off &&
3195 {
3197 NS_LOG_DEBUG(TcpSocketState::EcnStateName[m_tcb->m_ecnState] << " -> ECN_IDLE");
3198 m_tcb->m_ecnState = TcpSocketState::ECN_IDLE;
3199 }
3200 else
3201 {
3203 m_tcb->m_ecnState = TcpSocketState::ECN_DISABLED;
3204 }
3205}
3206
3207void
3209{ // Wrapper to protected function NotifyConnectionSucceeded() so that it can
3210 // be called as a scheduled event
3212 // The if-block below was moved from ProcessSynSent() to here because we need
3213 // to invoke the NotifySend() only after NotifyConnectionSucceeded() to
3214 // reflect the behaviour in the real world.
3215 if (GetTxAvailable() > 0)
3216 {
3218 }
3219}
3220
3221void
3223{
3224 /*
3225 * Add tags for each socket option.
3226 * Note that currently the socket adds both IPv4 tag and IPv6 tag
3227 * if both options are set. Once the packet got to layer three, only
3228 * the corresponding tags will be read.
3229 */
3230 if (GetIpTos())
3231 {
3232 SocketIpTosTag ipTosTag;
3233 if (m_tcb->m_ecnState != TcpSocketState::ECN_DISABLED && !CheckNoEcn(GetIpTos()) && isEct)
3234 {
3235 ipTosTag.SetTos(MarkEcnCodePoint(GetIpTos(), m_tcb->m_ectCodePoint));
3236 }
3237 else
3238 {
3239 // Set the last received ipTos
3240 ipTosTag.SetTos(GetIpTos());
3241 }
3242 p->AddPacketTag(ipTosTag);
3243 }
3244 else
3245 {
3246 if ((m_tcb->m_ecnState != TcpSocketState::ECN_DISABLED && p->GetSize() > 0 && isEct) ||
3247 m_tcb->m_ecnMode == TcpSocketState::DctcpEcn)
3248 {
3249 SocketIpTosTag ipTosTag;
3250 ipTosTag.SetTos(MarkEcnCodePoint(GetIpTos(), m_tcb->m_ectCodePoint));
3251 p->AddPacketTag(ipTosTag);
3252 }
3253 }
3254
3255 if (IsManualIpv6Tclass())
3256 {
3257 SocketIpv6TclassTag ipTclassTag;
3258 if (m_tcb->m_ecnState != TcpSocketState::ECN_DISABLED && !CheckNoEcn(GetIpv6Tclass()) &&
3259 isEct)
3260 {
3261 ipTclassTag.SetTclass(MarkEcnCodePoint(GetIpv6Tclass(), m_tcb->m_ectCodePoint));
3262 }
3263 else
3264 {
3265 // Set the last received ipTos
3266 ipTclassTag.SetTclass(GetIpv6Tclass());
3267 }
3268 p->AddPacketTag(ipTclassTag);
3269 }
3270 else
3271 {
3272 if ((m_tcb->m_ecnState != TcpSocketState::ECN_DISABLED && p->GetSize() > 0 && isEct) ||
3273 m_tcb->m_ecnMode == TcpSocketState::DctcpEcn)
3274 {
3275 SocketIpv6TclassTag ipTclassTag;
3276 ipTclassTag.SetTclass(MarkEcnCodePoint(GetIpv6Tclass(), m_tcb->m_ectCodePoint));
3277 p->AddPacketTag(ipTclassTag);
3278 }
3279 }
3280
3281 if (IsManualIpTtl())
3282 {
3283 SocketIpTtlTag ipTtlTag;
3284 ipTtlTag.SetTtl(GetIpTtl());
3285 p->AddPacketTag(ipTtlTag);
3286 }
3287
3289 {
3290 SocketIpv6HopLimitTag ipHopLimitTag;
3291 ipHopLimitTag.SetHopLimit(GetIpv6HopLimit());
3292 p->AddPacketTag(ipHopLimitTag);
3293 }
3294
3295 uint8_t priority = GetPriority();
3296 if (priority)
3297 {
3298 SocketPriorityTag priorityTag;
3299 priorityTag.SetPriority(priority);
3300 p->ReplacePacketTag(priorityTag);
3301 }
3302}
3303
3304/* Extract at most maxSize bytes from the TxBuffer at sequence seq, add the
3305 TCP header, and send to TcpL4Protocol */
3308{
3309 NS_LOG_FUNCTION(this << seq << maxSize << withAck);
3310
3311 bool isStartOfTransmission = BytesInFlight() == 0U;
3312 TcpTxItem* outItem = m_txBuffer->CopyFromSequence(maxSize, seq);
3313
3314 m_rateOps->SkbSent(outItem, isStartOfTransmission);
3315
3316 bool isRetransmission = outItem->IsRetrans();
3317 Ptr<Packet> p = outItem->GetPacketCopy();
3318 uint32_t sz = p->GetSize(); // Size of packet
3319 uint8_t flags = withAck ? TcpHeader::ACK : 0;
3320 uint32_t remainingData = m_txBuffer->SizeFromSequence(seq + SequenceNumber32(sz));
3321
3322 // TCP sender should not send data out of the window advertised by the
3323 // peer when it is not retransmission.
3324 NS_ASSERT(isRetransmission ||
3325 ((m_highRxAckMark + SequenceNumber32(m_rWnd)) >= (seq + SequenceNumber32(maxSize))));
3326
3327 if (IsPacingEnabled())
3328 {
3329 NS_LOG_INFO("Pacing is enabled");
3330 if (m_pacingTimer.IsExpired())
3331 {
3332 NS_LOG_DEBUG("Current Pacing Rate " << m_tcb->m_pacingRate);
3333 NS_LOG_DEBUG("Timer is in expired state, activate it "
3334 << m_tcb->m_pacingRate.Get().CalculateBytesTxTime(sz));
3335 m_pacingTimer.Schedule(m_tcb->m_pacingRate.Get().CalculateBytesTxTime(sz));
3336 }
3337 else
3338 {
3339 NS_LOG_INFO("Timer is already in running state");
3340 }
3341 }
3342 else
3343 {
3344 NS_LOG_INFO("Pacing is disabled");
3345 }
3346
3347 if (withAck)
3348 {
3349 m_delAckEvent.Cancel();
3350 m_delAckCount = 0;
3351 }
3352
3353 if (m_tcb->m_ecnState == TcpSocketState::ECN_ECE_RCVD &&
3354 m_ecnEchoSeq.Get() > m_ecnCWRSeq.Get() && !isRetransmission)
3355 {
3356 NS_LOG_DEBUG(TcpSocketState::EcnStateName[m_tcb->m_ecnState] << " -> ECN_CWR_SENT");
3357 m_tcb->m_ecnState = TcpSocketState::ECN_CWR_SENT;
3358 m_ecnCWRSeq = seq;
3359 flags |= TcpHeader::CWR;
3360 NS_LOG_INFO("CWR flags set");
3361 }
3362
3363 bool isEct = IsEct(isRetransmission ? TcpPacketType_t::RE_XMT : TcpPacketType_t::DATA);
3364 AddSocketTags(p, isEct);
3365
3366 if (m_closeOnEmpty && (remainingData == 0))
3367 {
3368 flags |= TcpHeader::FIN;
3369 if (m_state == ESTABLISHED)
3370 { // On active close: I am the first one to send FIN
3371 NS_LOG_DEBUG("ESTABLISHED -> FIN_WAIT_1");
3373 }
3374 else if (m_state == CLOSE_WAIT)
3375 { // On passive close: Peer sent me FIN already
3376 NS_LOG_DEBUG("CLOSE_WAIT -> LAST_ACK");
3377 m_state = LAST_ACK;
3378 }
3379 }
3380 TcpHeader header;
3381 header.SetFlags(flags);
3382 header.SetSequenceNumber(seq);
3383 header.SetAckNumber(m_tcb->m_rxBuffer->NextRxSequence());
3384 if (m_endPoint)
3385 {
3386 header.SetSourcePort(m_endPoint->GetLocalPort());
3387 header.SetDestinationPort(m_endPoint->GetPeerPort());
3388 }
3389 else
3390 {
3391 header.SetSourcePort(m_endPoint6->GetLocalPort());
3392 header.SetDestinationPort(m_endPoint6->GetPeerPort());
3393 }
3395 AddOptions(header);
3396
3397 if (m_retxEvent.IsExpired())
3398 {
3399 // Schedules retransmit timeout. m_rto should be already doubled.
3400
3401 NS_LOG_LOGIC(this << " SendDataPacket Schedule ReTxTimeout at time "
3402 << Simulator::Now().GetSeconds() << " to expire at time "
3403 << (Simulator::Now() + m_rto.Get()).GetSeconds());
3405 }
3406
3407 m_txTrace(p, header, this);
3408 if (isRetransmission)
3409 {
3410 if (m_endPoint)
3411 {
3413 header,
3414 m_endPoint->GetLocalAddress(),
3415 m_endPoint->GetPeerAddress(),
3416 this);
3417 }
3418 else
3419 {
3421 header,
3422 m_endPoint6->GetLocalAddress(),
3423 m_endPoint6->GetPeerAddress(),
3424 this);
3425 }
3426 }
3427
3428 if (m_endPoint)
3429 {
3430 m_tcp->SendPacket(p,
3431 header,
3432 m_endPoint->GetLocalAddress(),
3433 m_endPoint->GetPeerAddress(),
3435 NS_LOG_DEBUG("Send segment of size "
3436 << sz << " with remaining data " << remainingData << " via TcpL4Protocol to "
3437 << m_endPoint->GetPeerAddress() << ". Header " << header);
3438 }
3439 else
3440 {
3441 m_tcp->SendPacket(p,
3442 header,
3443 m_endPoint6->GetLocalAddress(),
3444 m_endPoint6->GetPeerAddress(),
3446 NS_LOG_DEBUG("Send segment of size "
3447 << sz << " with remaining data " << remainingData << " via TcpL4Protocol to "
3448 << m_endPoint6->GetPeerAddress() << ". Header " << header);
3449 }
3450
3451 // Signal to congestion control whether the cwnd is fully used
3452 // This is a simple version of Linux tcp_cwnd_validate() but following
3453 // the principle implemented in Linux that limits the updating of cwnd
3454 // (in the congestion controls) when flight size is >= cwnd
3455 // send will also be cwnd limited if less then one segment of cwnd is available
3456 m_tcb->m_isCwndLimited = (m_tcb->m_cWnd < BytesInFlight() + m_tcb->m_segmentSize);
3457
3458 UpdateRttHistory(seq, sz, isRetransmission);
3459
3460 // Update bytes sent during recovery phase
3461 if (m_tcb->m_congState == TcpSocketState::CA_RECOVERY ||
3462 m_tcb->m_congState == TcpSocketState::CA_CWR)
3463 {
3464 m_recoveryOps->UpdateBytesSent(sz);
3465 }
3466
3467 // Notify the application of the data being sent unless this is a retransmit
3468 if (!isRetransmission)
3469 {
3471 this,
3472 (seq + sz - m_tcb->m_highTxMark.Get()));
3473 }
3474 // Update highTxMark
3475 m_tcb->m_highTxMark = std::max(seq + sz, m_tcb->m_highTxMark.Get());
3476 return sz;
3477}
3478
3479void
3480TcpSocketBase::UpdateRttHistory(const SequenceNumber32& seq, uint32_t sz, bool isRetransmission)
3481{
3482 NS_LOG_FUNCTION(this);
3483
3484 // update the history of sequence numbers used to calculate the RTT
3485 if (!isRetransmission)
3486 { // This is the next expected one, just log at end
3487 m_history.emplace_back(seq, sz, Simulator::Now());
3488 }
3489 else
3490 { // This is a retransmit, find in list and mark as re-tx
3491 for (auto i = m_history.begin(); i != m_history.end(); ++i)
3492 {
3493 if ((seq >= i->seq) && (seq < (i->seq + SequenceNumber32(i->count))))
3494 { // Found it
3495 i->retx = true;
3496 i->count = ((seq + SequenceNumber32(sz)) - i->seq); // And update count in hist
3497 break;
3498 }
3499 }
3500 }
3501}
3502
3503// Note that this function did not implement the PSH flag
3506{
3507 NS_LOG_FUNCTION(this << withAck);
3508 if (m_txBuffer->Size() == 0)
3509 {
3510 return 0; // Nothing to send
3511 }
3512 if (m_endPoint == nullptr && m_endPoint6 == nullptr)
3513 {
3515 "TcpSocketBase::SendPendingData: No endpoint; m_shutdownSend=" << m_shutdownSend);
3516 return 0; // Is this the right way to handle this condition?
3517 }
3518
3519 uint32_t nPacketsSent = 0;
3520 uint32_t availableWindow = AvailableWindow();
3521
3522 // RFC 6675, Section (C)
3523 // If cwnd - pipe >= 1 SMSS, the sender SHOULD transmit one or more
3524 // segments as follows:
3525 // (NOTE: We check > 0, and do the checks for segmentSize in the following
3526 // else branch to control silly window syndrome and Nagle)
3527 while (availableWindow > 0)
3528 {
3529 if (IsPacingEnabled())
3530 {
3531 NS_LOG_INFO("Pacing is enabled");
3532 if (m_pacingTimer.IsRunning())
3533 {
3534 NS_LOG_INFO("Skipping Packet due to pacing" << m_pacingTimer.GetDelayLeft());
3535 break;
3536 }
3537 NS_LOG_INFO("Timer is not running");
3538 }
3539
3541 {
3542 NS_LOG_INFO("FIN_WAIT and OPEN state; no data to transmit");
3543 break;
3544 }
3545 // (C.1) The scoreboard MUST be queried via NextSeg () for the
3546 // sequence number range of the next segment to transmit (if
3547 // any), and the given segment sent. If NextSeg () returns
3548 // failure (no data to send), return without sending anything
3549 // (i.e., terminate steps C.1 -- C.5).
3550 SequenceNumber32 next;
3551 SequenceNumber32 nextHigh;
3552 bool enableRule3 = m_sackEnabled && m_tcb->m_congState == TcpSocketState::CA_RECOVERY;
3553 if (!m_txBuffer->NextSeg(&next, &nextHigh, enableRule3))
3554 {
3555 NS_LOG_INFO("no valid seq to transmit, or no data available");
3556 break;
3557 }
3558 else
3559 {
3560 // It's time to transmit, but before do silly window and Nagle's check
3561 uint32_t availableData = m_txBuffer->SizeFromSequence(next);
3562
3563 // If there's less app data than the full window, ask the app for more
3564 // data before trying to send
3565 if (availableData < availableWindow)
3566 {
3568 }
3569
3570 // Stop sending if we need to wait for a larger Tx window (prevent silly window
3571 // syndrome) but continue if we don't have data
3572 if (availableWindow < m_tcb->m_segmentSize && availableData > availableWindow)
3573 {
3574 NS_LOG_LOGIC("Preventing Silly Window Syndrome. Wait to send.");
3575 break; // No more
3576 }
3577 // Nagle's algorithm (RFC896): Hold off sending if there is unacked data
3578 // in the buffer and the amount of data to send is less than one segment
3579 if (!m_noDelay && UnAckDataCount() > 0 && availableData < m_tcb->m_segmentSize)
3580 {
3581 NS_LOG_DEBUG("Invoking Nagle's algorithm for seq "
3582 << next << ", SFS: " << m_txBuffer->SizeFromSequence(next)
3583 << ". Wait to send.");
3584 break;
3585 }
3586
3587 uint32_t s = std::min(availableWindow, m_tcb->m_segmentSize);
3588 // NextSeg () may have further constrained the segment size
3589 auto maxSizeToSend = static_cast<uint32_t>(nextHigh - next);
3590 s = std::min(s, maxSizeToSend);
3591
3592 // (C.2) If any of the data octets sent in (C.1) are below HighData,
3593 // HighRxt MUST be set to the highest sequence number of the
3594 // retransmitted segment unless NextSeg () rule (4) was
3595 // invoked for this retransmission.
3596 // (C.3) If any of the data octets sent in (C.1) are above HighData,
3597 // HighData must be updated to reflect the transmission of
3598 // previously unsent data.
3599 //
3600 // These steps are done in m_txBuffer with the tags.
3601 if (m_tcb->m_nextTxSequence != next)
3602 {
3603 m_tcb->m_nextTxSequence = next;
3604 }
3605 if (m_tcb->m_bytesInFlight.Get() == 0)
3606 {
3608 }
3609 uint32_t sz = SendDataPacket(m_tcb->m_nextTxSequence, s, withAck);
3610
3611 NS_LOG_LOGIC(" rxwin " << m_rWnd << " segsize " << m_tcb->m_segmentSize
3612 << " highestRxAck " << m_txBuffer->HeadSequence() << " pd->Size "
3613 << m_txBuffer->Size() << " pd->SFS "
3614 << m_txBuffer->SizeFromSequence(m_tcb->m_nextTxSequence));
3615
3616 NS_LOG_DEBUG("cWnd: " << m_tcb->m_cWnd << " total unAck: " << UnAckDataCount()
3617 << " sent seq " << m_tcb->m_nextTxSequence << " size " << sz);
3618 m_tcb->m_nextTxSequence += sz;
3619 ++nPacketsSent;
3620 if (IsPacingEnabled())
3621 {
3622 NS_LOG_INFO("Pacing is enabled");
3623 if (m_pacingTimer.IsExpired())
3624 {
3625 NS_LOG_DEBUG("Current Pacing Rate " << m_tcb->m_pacingRate);
3626 NS_LOG_DEBUG("Timer is in expired state, activate it "
3627 << m_tcb->m_pacingRate.Get().CalculateBytesTxTime(sz));
3628 m_pacingTimer.Schedule(m_tcb->m_pacingRate.Get().CalculateBytesTxTime(sz));
3629 break;
3630 }
3631 }
3632 }
3633
3634 // (C.4) The estimate of the amount of data outstanding in the
3635 // network must be updated by incrementing pipe by the number
3636 // of octets transmitted in (C.1).
3637 //
3638 // Done in BytesInFlight, inside AvailableWindow.
3639 availableWindow = AvailableWindow();
3640
3641 // (C.5) If cwnd - pipe >= 1 SMSS, return to (C.1)
3642 // loop again!
3643 }
3644
3645 if (nPacketsSent > 0)
3646 {
3647 if (!m_sackEnabled)
3648 {
3649 if (!m_limitedTx)
3650 {
3651 // We can't transmit in CA_DISORDER without limitedTx active
3653 }
3654 }
3655
3656 NS_LOG_DEBUG("SendPendingData sent " << nPacketsSent << " segments");
3657 }
3658 else
3659 {
3660 NS_LOG_DEBUG("SendPendingData no segments sent");
3661 }
3662 return nPacketsSent;
3663}
3664
3667{
3668 return m_tcb->m_highTxMark - m_txBuffer->HeadSequence();
3669}
3670
3673{
3674 uint32_t bytesInFlight = m_txBuffer->BytesInFlight();
3675 // Ugly, but we are not modifying the state; m_bytesInFlight is used
3676 // only for tracing purpose.
3677 m_tcb->m_bytesInFlight = bytesInFlight;
3678
3679 NS_LOG_DEBUG("Returning calculated bytesInFlight: " << bytesInFlight);
3680 return bytesInFlight;
3681}
3682
3685{
3686 return std::min(m_rWnd.Get(), m_tcb->m_cWnd.Get());
3687}
3688
3691{
3692 uint32_t win = Window(); // Number of bytes allowed to be outstanding
3693
3694 if (m_sackEnabled && m_fackEnabled && win >= m_tcb->m_ssThresh)
3695 {
3696 // Update awnd (Data sender's estimate of the actual quantity of data outstanding in the
3697 // network)
3698 NS_LOG_DEBUG("FACK is enabled and win >= ssthresh (" << m_tcb->m_ssThresh << ")");
3699
3700 uint32_t sndNxt = (m_tcb->m_highTxMark.Get().GetValue());
3701 uint32_t retranData = m_txBuffer->GetRetransmitsCount();
3702 uint32_t awnd = sndNxt - m_sndFack + retranData;
3703 m_tcb->m_fackAwnd = awnd;
3704
3705 NS_LOG_DEBUG("SndNxt: " << sndNxt << ", SndFack: " << m_sndFack << ", AWND: " << awnd
3706 << ", RetranData :" << retranData);
3707
3708 uint32_t awndDiff = (win > awnd) ? (win - awnd) : 0;
3709 NS_LOG_DEBUG("AWND: " << awnd << ", win: " << win << ", AWND_DIFF: " << awndDiff);
3710 return awndDiff;
3711 }
3712
3713 uint32_t inflight = BytesInFlight();
3714
3715 if (inflight >= win)
3716 {
3717 return 0;
3718 }
3719
3720 return win - inflight;
3721}
3722
3723uint16_t
3725{
3726 NS_LOG_FUNCTION(this << scale);
3727 uint32_t w;
3728
3729 // We don't want to advertise 0 after a FIN is received. So, we just use
3730 // the previous value of the advWnd.
3731 if (m_tcb->m_rxBuffer->GotFin())
3732 {
3733 w = m_advWnd;
3734 }
3735 else
3736 {
3737 NS_ASSERT_MSG(m_tcb->m_rxBuffer->MaxRxSequence() - m_tcb->m_rxBuffer->NextRxSequence() >= 0,
3738 "Unexpected sequence number values");
3739 w = static_cast<uint32_t>(m_tcb->m_rxBuffer->MaxRxSequence() -
3740 m_tcb->m_rxBuffer->NextRxSequence());
3741 }
3742
3743 // Ugly, but we are not modifying the state, that variable
3744 // is used only for tracing purpose.
3745 if (w != m_advWnd)
3746 {
3747 const_cast<TcpSocketBase*>(this)->m_advWnd = w;
3748 }
3749 if (scale)
3750 {
3751 w >>= m_rcvWindShift;
3752 }
3753 if (w > m_maxWinSize)
3754 {
3755 w = m_maxWinSize;
3756 NS_LOG_WARN("Adv window size truncated to "
3757 << m_maxWinSize << "; possibly to avoid overflow of the 16-bit integer");
3758 }
3759 NS_LOG_LOGIC("Returning AdvertisedWindowSize of " << static_cast<uint16_t>(w));
3760 return static_cast<uint16_t>(w);
3761}
3762
3763// Receipt of new packet, put into Rx buffer
3764void
3766{
3767 NS_LOG_FUNCTION(this << tcpHeader);
3768 NS_LOG_DEBUG("Data segment, seq=" << tcpHeader.GetSequenceNumber()
3769 << " pkt size=" << p->GetSize());
3770
3771 // Put into Rx buffer
3772 SequenceNumber32 expectedSeq = m_tcb->m_rxBuffer->NextRxSequence();
3773 if (!m_tcb->m_rxBuffer->Add(p, tcpHeader))
3774 { // Insert failed: No data or RX buffer full
3775 if (m_tcb->m_ecnState == TcpSocketState::ECN_CE_RCVD ||
3777 {
3779 NS_LOG_DEBUG(TcpSocketState::EcnStateName[m_tcb->m_ecnState] << " -> ECN_SENDING_ECE");
3781 }
3782 else
3783 {
3785 }
3786 return;
3787 }
3788 // Notify app to receive if necessary
3789 if (expectedSeq < m_tcb->m_rxBuffer->NextRxSequence())
3790 { // NextRxSeq advanced, we have something to send to the app
3791 if (!m_shutdownRecv)
3792 {
3794 }
3795 // Handle exceptions
3796 if (m_closeNotified)
3797 {
3798 NS_LOG_WARN("Why TCP " << this << " got data after close notification?");
3799 }
3800 // If we received FIN before and now completed all "holes" in rx buffer,
3801 // invoke peer close procedure
3802 if (m_tcb->m_rxBuffer->Finished() && (tcpHeader.GetFlags() & TcpHeader::FIN) == 0)
3803 {
3804 DoPeerClose();
3805 return;
3806 }
3807 }
3808 // Now send a new ACK packet acknowledging all received and delivered data
3809 if (m_tcb->m_rxBuffer->Size() > m_tcb->m_rxBuffer->Available() ||
3810 m_tcb->m_rxBuffer->NextRxSequence() > expectedSeq + p->GetSize())
3811 { // A gap exists in the buffer, or we filled a gap: Always ACK
3813 if (m_tcb->m_ecnState == TcpSocketState::ECN_CE_RCVD ||
3815 {
3817 NS_LOG_DEBUG(TcpSocketState::EcnStateName[m_tcb->m_ecnState] << " -> ECN_SENDING_ECE");
3819 }
3820 else
3821 {
3823 }
3824 }
3825 else
3826 { // In-sequence packet: ACK if delayed ack count allows
3828 {
3829 m_delAckEvent.Cancel();
3830 m_delAckCount = 0;
3832 if (m_tcb->m_ecnState == TcpSocketState::ECN_CE_RCVD ||
3834 {
3835 NS_LOG_DEBUG("Congestion algo " << m_congestionControl->GetName());
3838 << " -> ECN_SENDING_ECE");
3840 }
3841 else
3842 {
3844 }
3845 }
3846 else if (!m_delAckEvent.IsExpired())
3847 {
3849 }
3850 else if (m_delAckEvent.IsExpired())
3851 {
3856 this << " scheduled delayed ACK at "
3858 }
3859 }
3860}
3861
3862Time
3863TcpSocketBase::CalculateRttSample(const TcpHeader& tcpHeader, const RttHistory& rttHistory)
3864{
3865 NS_LOG_FUNCTION(this);
3866 SequenceNumber32 ackSeq = tcpHeader.GetAckNumber();
3867 Time rtt;
3868
3869 if (ackSeq >= (rttHistory.seq + SequenceNumber32(rttHistory.count)))
3870 {
3871 // As per RFC 6298 (Section 3)
3872 // RTT samples MUST NOT be made using segments that were
3873 // retransmitted (and thus for which it is ambiguous whether the reply
3874 // was for the first instance of the packet or a later instance). The
3875 // only case when TCP can safely take RTT samples from retransmitted
3876 // segments is when the TCP timestamp option is employed, since
3877 // the timestamp option removes the ambiguity regarding which instance
3878 // of the data segment triggered the acknowledgment.
3879 if (m_timestampEnabled && tcpHeader.HasOption(TcpOption::TS))
3880 {
3883 rtt = TcpOptionTS::ElapsedTimeFromTsValue(ts->GetEcho());
3884 if (rtt.IsZero())
3885 {
3886 NS_LOG_LOGIC("TcpSocketBase::EstimateRtt - RTT calculated from TcpOption::TS "
3887 "is zero, approximating to 1us.");
3888 NS_LOG_DEBUG("RTT calculated from TcpOption::TS is zero, updating rtt to 1us.");
3889 rtt = MicroSeconds(1);
3890 }
3891 }
3892 else if (!rttHistory.retx)
3893 {
3894 // Elapsed time since the packet was transmitted
3895 rtt = Simulator::Now() - rttHistory.time;
3896 }
3897 }
3898 return rtt;
3899}
3900
3901void
3903{
3904 NS_LOG_FUNCTION(this);
3905 SequenceNumber32 ackSeq = tcpHeader.GetAckNumber();
3906 Time rtt;
3907
3908 // An ack has been received, calculate rtt and log this measurement
3909 // Note we use a linear search (O(n)) for this since for the common
3910 // case the ack'ed packet will be at the head of the list
3911 if (!m_history.empty())
3912 {
3913 RttHistory& earliestTransmittedPktHistory = m_history.front();
3914 rtt = CalculateRttSample(tcpHeader, earliestTransmittedPktHistory);
3915
3916 // Store ACKed packet that has the latest transmission time to update `lastRtt`
3917 RttHistory latestTransmittedPktHistory = earliestTransmittedPktHistory;
3918
3919 // Delete all ACK history with seq <= ack
3920 while (!m_history.empty())
3921 {
3922 RttHistory& rttHistory = m_history.front();
3923 if ((rttHistory.seq + SequenceNumber32(rttHistory.count)) > ackSeq)
3924 {
3925 break; // Done removing
3926 }
3927
3928 latestTransmittedPktHistory = rttHistory;
3929 m_history.pop_front(); // Remove
3930 }
3931
3932 // In case of multiple packets being ACKed in a single acknowledgement, `m_lastRtt` is
3933 // RTT of the last (S)ACKed packet calculated using the data packet with the latest
3934 // transmission time
3935 Time lastRtt = CalculateRttSample(tcpHeader, latestTransmittedPktHistory);
3936 if (!lastRtt.IsZero())
3937 {
3938 NS_LOG_DEBUG("Last RTT sample updated to: " << lastRtt);
3939 m_tcb->m_lastRtt = lastRtt;
3940 }
3941 }
3942
3943 if (!rtt.IsZero())
3944 {
3945 m_rtt->Measurement(rtt); // Log the measurement
3946 // RFC 6298, clause 2.4
3947 m_rto = Max(m_rtt->GetEstimate() + Max(m_clockGranularity, m_rtt->GetVariation() * 4),
3948 m_minRto);
3949 m_tcb->m_srtt = m_rtt->GetEstimate();
3950 m_tcb->m_minRtt = std::min(m_tcb->m_srtt.Get(), m_tcb->m_minRtt);
3951 NS_LOG_INFO(this << m_tcb->m_srtt << m_tcb->m_minRtt);
3952 }
3953}
3954
3955// Called by the ReceivedAck() when new ACK received and by ProcessSynRcvd()
3956// when the three-way handshake completed. This cancels retransmission timer
3957// and advances Tx window
3958void
3959TcpSocketBase::NewAck(const SequenceNumber32& ack, bool resetRTO)
3960{
3961 NS_LOG_FUNCTION(this << ack);
3962
3963 // Reset the data retransmission count. We got a new ACK!
3965
3966 // Update m_sndFack if possible
3967 if (m_fackEnabled && ack.GetValue() > m_sndFack)
3968 {
3969 NS_LOG_INFO(" m_sndFack " << m_sndFack << " updated by normal ack to " << ack.GetValue());
3970 m_sndFack = ack.GetValue();
3971 }
3972
3973 if (m_state != SYN_RCVD && resetRTO)
3974 { // Set RTO unless the ACK is received in SYN_RCVD state
3976 this << " Cancelled ReTxTimeout event which was set to expire at "
3977 << (Simulator::Now() + Simulator::GetDelayLeft(m_retxEvent)).GetSeconds());
3978 m_retxEvent.Cancel();
3979 // On receiving a "New" ack we restart retransmission timer .. RFC 6298
3980 // RFC 6298, clause 2.4
3981 m_rto = Max(m_rtt->GetEstimate() + Max(m_clockGranularity, m_rtt->GetVariation() * 4),
3982 m_minRto);
3983
3984 NS_LOG_LOGIC(this << " Schedule ReTxTimeout at time " << Simulator::Now().GetSeconds()
3985 << " to expire at time "
3986 << (Simulator::Now() + m_rto.Get()).GetSeconds());
3988 }
3989
3990 // Note the highest ACK and tell app to send more
3991 NS_LOG_LOGIC("TCP " << this << " NewAck " << ack << " numberAck "
3992 << (ack - m_txBuffer->HeadSequence())); // Number bytes ack'ed
3993
3994 if (GetTxAvailable() > 0)
3995 {
3997 }
3998 if (ack > m_tcb->m_nextTxSequence)
3999 {
4000 m_tcb->m_nextTxSequence = ack; // If advanced
4001 }
4002 if (m_txBuffer->Size() == 0 && m_state != FIN_WAIT_1 && m_state != CLOSING)
4003 { // No retransmit timer if no data to retransmit
4005 this << " Cancelled ReTxTimeout event which was set to expire at "
4006 << (Simulator::Now() + Simulator::GetDelayLeft(m_retxEvent)).GetSeconds());
4007 m_retxEvent.Cancel();
4008 }
4009}
4010
4011// Retransmit timeout
4012void
4014{
4015 NS_LOG_FUNCTION(this);
4016 NS_LOG_LOGIC(this << " ReTxTimeout Expired at time " << Simulator::Now().GetSeconds());
4017 // If erroneous timeout in closed/timed-wait state, just return
4018 if (m_state == CLOSED || m_state == TIME_WAIT)
4019 {
4020 return;
4021 }
4022
4023 if (m_state == SYN_SENT)
4024 {
4025 NS_ASSERT(m_synCount > 0);
4026 if (m_tcb->m_useEcn == TcpSocketState::On)
4027 {
4029 }
4030 else
4031 {
4033 }
4034 return;
4035 }
4036
4037 // Retransmit non-data packet: Only if in FIN_WAIT_1 or CLOSING state
4038 if (m_txBuffer->Size() == 0)
4039 {
4040 if (m_state == FIN_WAIT_1 || m_state == CLOSING)
4041 { // Must have lost FIN, re-send
4043 }
4044 return;
4045 }
4046
4047 NS_LOG_DEBUG("Checking if Connection is Established");
4048 // If all data are received (non-closing socket and nothing to send), just return
4049 if (m_state <= ESTABLISHED && m_txBuffer->HeadSequence() >= m_tcb->m_highTxMark &&
4050 m_txBuffer->Size() == 0)
4051 {
4052 NS_LOG_DEBUG("Already Sent full data" << m_txBuffer->HeadSequence() << " "
4053 << m_tcb->m_highTxMark);
4054 return;
4055 }
4056
4057 if (m_dataRetrCount == 0)
4058 {
4059 NS_LOG_INFO("No more data retries available. Dropping connection");
4062 return;
4063 }
4064 else
4065 {
4067 }
4068
4069 uint32_t inFlightBeforeRto = BytesInFlight();
4070 bool resetSack = !m_sackEnabled; // Reset SACK information if SACK is not enabled.
4071 // The information in the TcpTxBuffer is guessed, in this case.
4072
4073 // Reset dupAckCount
4074 m_dupAckCount = 0;
4075 if (!m_sackEnabled)
4076 {
4077 m_txBuffer->ResetRenoSack();
4078 }
4079
4080 // From RFC 6675, Section 5.1
4081 // [RFC2018] suggests that a TCP sender SHOULD expunge the SACK
4082 // information gathered from a receiver upon a retransmission timeout
4083 // (RTO) "since the timeout might indicate that the data receiver has
4084 // reneged." Additionally, a TCP sender MUST "ignore prior SACK
4085 // information in determining which data to retransmit."
4086 // It has been suggested that, as long as robust tests for
4087 // reneging are present, an implementation can retain and use SACK
4088 // information across a timeout event [Errata1610].
4089 // The head of the sent list will not be marked as sacked, therefore
4090 // will be retransmitted, if the receiver renegotiate the SACK blocks
4091 // that we received.
4092 m_txBuffer->SetSentListLost(resetSack);
4093
4094 // From RFC 6675, Section 5.1
4095 // If an RTO occurs during loss recovery as specified in this document,
4096 // RecoveryPoint MUST be set to HighData. Further, the new value of
4097 // RecoveryPoint MUST be preserved and the loss recovery algorithm
4098 // outlined in this document MUST be terminated.
4099 m_recover = m_tcb->m_highTxMark;
4100 m_recoverActive = true;
4101
4102 // RFC 6298, clause 2.5, double the timer
4103 Time doubledRto = m_rto + m_rto;
4104 m_rto = Min(doubledRto, Time::FromDouble(60, Time::S));
4105
4106 // Empty RTT history
4107 m_history.clear();
4108
4109 // Please don't reset highTxMark, it is used for retransmission detection
4110
4111 // When a TCP sender detects segment loss using the retransmission timer
4112 // and the given segment has not yet been resent by way of the
4113 // retransmission timer, decrease ssThresh
4114 if (m_tcb->m_congState != TcpSocketState::CA_LOSS || !m_txBuffer->IsHeadRetransmitted())
4115 {
4116 m_tcb->m_ssThresh = m_congestionControl->GetSsThresh(m_tcb, inFlightBeforeRto);
4117 }
4118
4119 // Cwnd set to 1 MSS
4122 m_tcb->m_congState = TcpSocketState::CA_LOSS;
4123 m_tcb->m_cWnd = m_tcb->m_segmentSize;
4124 m_tcb->m_cWndInfl = m_tcb->m_cWnd;
4125
4126 m_pacingTimer.Cancel();
4127
4128 NS_LOG_DEBUG("RTO. Reset cwnd to " << m_tcb->m_cWnd << ", ssthresh to " << m_tcb->m_ssThresh
4129 << ", restart from seqnum " << m_txBuffer->HeadSequence()
4130 << " doubled rto to " << m_rto.Get().GetSeconds() << " s");
4131
4133 "There are some bytes in flight after an RTO: " << BytesInFlight());
4134
4136
4137 NS_ASSERT_MSG(BytesInFlight() <= m_tcb->m_segmentSize,
4138 "In flight (" << BytesInFlight() << ") there is more than one segment ("
4139 << m_tcb->m_segmentSize << ")");
4140}
4141
4142void
4158
4159void
4161{
4162 NS_LOG_FUNCTION(this);
4163
4164 m_lastAckEvent.Cancel();
4165 if (m_state == LAST_ACK)
4166 {
4167 if (m_dataRetrCount == 0)
4168 {
4169 NS_LOG_INFO("LAST-ACK: No more data retries available. Dropping connection");
4172 return;
4173 }
4176 NS_LOG_LOGIC("TcpSocketBase " << this << " rescheduling LATO1");
4177 Time lastRto = m_rtt->GetEstimate() + Max(m_clockGranularity, m_rtt->GetVariation() * 4);
4179 }
4180}
4181
4182// Send 1-byte data (or a zero-length segment, if there is no unsent data) to
4183// probe for the window size at the receiver when the local knowledge tells
4184// that the receiver has zero window size
4185// C.f.: RFC793 p.42, RFC1122 sec.4.2.2.17, RFC9293 sec.3.8.6.1
4186void
4188{
4189 NS_LOG_LOGIC("PersistTimeout expired at " << Simulator::Now().GetSeconds());
4191 std::min(Seconds(60), Time(2 * m_persistTimeout)); // max persist timeout = 60s
4192 // CopyFromSequence() returns nullptr when there is no unsent data. In that
4193 // case, send a zero-length probe with an already acknowledged sequence
4194 // number. The receiver finds it unacceptable and must answer with an ACK
4195 // carrying its current window (@RFC{9293} sec 3.10.7.4, @issueid{1326}).
4196 Ptr<Packet> p;
4197 SequenceNumber32 probeSeq = m_tcb->m_nextTxSequence;
4198 TcpTxItem* outItem = m_txBuffer->CopyFromSequence(1, m_tcb->m_nextTxSequence);
4199 if (outItem != nullptr)
4200 {
4201 p = outItem->GetPacketCopy();
4202 // The probe byte is not accounted as sent; return it to the unsent data
4203 m_txBuffer->ResetLastSegmentSent();
4204 }
4205 else
4206 {
4207 p = Create<Packet>();
4208 probeSeq = m_txBuffer->HeadSequence() - 1;
4209 }
4210 TcpHeader tcpHeader;
4211 tcpHeader.SetSequenceNumber(probeSeq);
4212 tcpHeader.SetAckNumber(m_tcb->m_rxBuffer->NextRxSequence());
4214 if (m_endPoint != nullptr)
4215 {
4216 tcpHeader.SetSourcePort(m_endPoint->GetLocalPort());
4217 tcpHeader.SetDestinationPort(m_endPoint->GetPeerPort());
4218 }
4219 else
4220 {
4221 tcpHeader.SetSourcePort(m_endPoint6->GetLocalPort());
4222 tcpHeader.SetDestinationPort(m_endPoint6->GetPeerPort());
4223 }
4224 AddOptions(tcpHeader);
4225 // Send a packet tag for setting ECT bits in IP header
4226 if (m_tcb->m_ecnState != TcpSocketState::ECN_DISABLED)
4227 {
4229 }
4230 m_txTrace(p, tcpHeader, this);
4231
4232 if (m_endPoint != nullptr)
4233 {
4234 m_tcp->SendPacket(p,
4235 tcpHeader,
4236 m_endPoint->GetLocalAddress(),
4237 m_endPoint->GetPeerAddress(),
4239 }
4240 else
4241 {
4242 m_tcp->SendPacket(p,
4243 tcpHeader,
4244 m_endPoint6->GetLocalAddress(),
4245 m_endPoint6->GetPeerAddress(),
4247 }
4248
4249 NS_LOG_LOGIC("Schedule persist timeout at time "
4250 << Simulator::Now().GetSeconds() << " to expire at time "
4251 << (Simulator::Now() + m_persistTimeout).GetSeconds());
4253}
4254
4255void
4257{
4258 NS_LOG_FUNCTION(this);
4259 bool res;
4260 SequenceNumber32 seq;
4261 SequenceNumber32 seqHigh;
4262 uint32_t maxSizeToSend;
4263
4264 // Find the first segment marked as lost and not retransmitted. With Reno,
4265 // that should be the head
4266 res = m_txBuffer->NextSeg(&seq, &seqHigh, false);
4267 if (!res)
4268 {
4269 // We have already retransmitted the head. However, we still received
4270 // three dupacks, or the RTO expired, but no data to transmit.
4271 // Therefore, re-send again the head.
4272 seq = m_txBuffer->HeadSequence();
4273 maxSizeToSend = m_tcb->m_segmentSize;
4274 }
4275 else
4276 {
4277 // NextSeg() may constrain the segment size when res is true
4278 maxSizeToSend = static_cast<uint32_t>(seqHigh - seq);
4279 }
4280 NS_ASSERT(m_sackEnabled || seq == m_txBuffer->HeadSequence());
4281
4282 NS_LOG_INFO("Retransmitting " << seq);
4283 // Update the trace and retransmit the segment
4284 m_tcb->m_nextTxSequence = seq;
4285 uint32_t sz = SendDataPacket(m_tcb->m_nextTxSequence, maxSizeToSend, true);
4286
4287 NS_ASSERT(sz > 0);
4288}
4289
4290void
4292{
4293 m_retxEvent.Cancel();
4294 m_persistEvent.Cancel();
4295 m_delAckEvent.Cancel();
4296 m_lastAckEvent.Cancel();
4297 m_timewaitEvent.Cancel();
4298 m_sendPendingDataEvent.Cancel();
4299 m_pacingTimer.Cancel();
4300}
4301
4302/* Move TCP to Time_Wait state and schedule a transition to Closed state */
4303void
4305{
4306 NS_LOG_DEBUG(TcpStateName[m_state] << " -> TIME_WAIT");
4309 if (!m_closeNotified)
4310 {
4311 // Technically the connection is not fully closed, but we notify now
4312 // because an implementation (real socket) would behave as if closed.
4313 // Notify normal close when entering TIME_WAIT or leaving LAST_ACK.
4315 m_closeNotified = true;
4316 }
4317 // Move from TIME_WAIT to CLOSED after 2*MSL. Max segment lifetime is 2 min
4318 // according to RFC793, p.28
4320}
4321
4322/* Below are the attribute get/set functions */
4323
4324void
4326{
4327 NS_LOG_FUNCTION(this << size);
4328 m_txBuffer->SetMaxBufferSize(size);
4329}
4330
4333{
4334 return m_txBuffer->MaxBufferSize();
4335}
4336
4339{
4340 return m_sndFack;
4341}
4342
4343bool
4345{
4346 return m_fackEnabled;
4347}
4348
4349void
4351{
4352 NS_LOG_FUNCTION(this << size);
4353 uint32_t oldSize = GetRcvBufSize();
4354
4355 m_tcb->m_rxBuffer->SetMaxBufferSize(size);
4356
4357 /* The size has (manually) increased. Actively inform the other end to prevent
4358 * stale zero-window states.
4359 */
4360 if (oldSize < size && m_connected)
4361 {
4362 if (m_tcb->m_ecnState == TcpSocketState::ECN_CE_RCVD ||
4364 {
4366 NS_LOG_DEBUG(TcpSocketState::EcnStateName[m_tcb->m_ecnState] << " -> ECN_SENDING_ECE");
4368 }
4369 else
4370 {
4372 }
4373 }
4374}
4375
4378{
4379 return m_tcb->m_rxBuffer->MaxBufferSize();
4380}
4381
4382void
4384{
4385 NS_LOG_FUNCTION(this << size);
4386 m_tcb->m_segmentSize = size;
4387 m_txBuffer->SetSegmentSize(size);
4388
4389 NS_ABORT_MSG_UNLESS(m_state == CLOSED, "Cannot change segment size dynamically.");
4390}
4391
4394{
4395 return m_tcb->m_segmentSize;
4396}
4397
4398void
4404
4405Time
4407{
4408 return m_cnTimeout;
4409}
4410
4411void
4413{
4414 NS_LOG_FUNCTION(this << count);
4415 m_synRetries = count;
4416}
4417
4420{
4421 return m_synRetries;
4422}
4423
4424void
4426{
4427 NS_LOG_FUNCTION(this << retries);
4428 m_dataRetries = retries;
4429}
4430
4433{
4434 NS_LOG_FUNCTION(this);
4435 return m_dataRetries;
4436}
4437
4438void
4444
4445Time
4447{
4448 return m_delAckTimeout;
4449}
4450
4451void
4453{
4454 NS_LOG_FUNCTION(this << count);
4455 m_delAckMaxCount = count;
4456}
4457
4463
4464void
4466{
4467 NS_LOG_FUNCTION(this << noDelay);
4468 m_noDelay = noDelay;
4469}
4470
4471bool
4473{
4474 return m_noDelay;
4475}
4476
4477void
4483
4484Time
4489
4490bool
4492{
4493 // Broadcast is not implemented. Return true only if allowBroadcast==false
4494 return (!allowBroadcast);
4495}
4496
4497bool
4499{
4500 return false;
4501}
4502
4503void
4505{
4506 NS_LOG_FUNCTION(this << header);
4507
4509 {
4510 AddOptionTimestamp(header);
4511 }
4512}
4513
4514void
4516{
4517 NS_LOG_FUNCTION(this << option);
4518
4520
4521 // In naming, we do the contrary of RFC 1323. The received scaling factor
4522 // is Rcv.Wind.Scale (and not Snd.Wind.Scale)
4523 m_sndWindShift = ws->GetScale();
4524
4525 if (m_sndWindShift > 14)
4526 {
4527 NS_LOG_WARN("Possible error; m_sndWindShift exceeds 14: " << m_sndWindShift);
4528 m_sndWindShift = 14;
4529 }
4530
4531 NS_LOG_INFO(m_node->GetId() << " Received a scale factor of "
4532 << static_cast<int>(m_sndWindShift));
4533}
4534
4535uint8_t
4537{
4538 NS_LOG_FUNCTION(this);
4539 uint32_t maxSpace = m_tcb->m_rxBuffer->MaxBufferSize();
4540 uint8_t scale = 0;
4541
4542 while (maxSpace > m_maxWinSize)
4543 {
4544 maxSpace = maxSpace >> 1;
4545 ++scale;
4546 }
4547
4548 if (scale > 14)
4549 {
4550 NS_LOG_WARN("Possible error; scale exceeds 14: " << scale);
4551 scale = 14;
4552 }
4553
4554 NS_LOG_INFO("Node " << m_node->GetId() << " calculated wscale factor of "
4555 << static_cast<int>(scale) << " for buffer size "
4556 << m_tcb->m_rxBuffer->MaxBufferSize());
4557 return scale;
4558}
4559
4560void
4562{
4563 NS_LOG_FUNCTION(this << header);
4564 NS_ASSERT(header.GetFlags() & TcpHeader::SYN);
4565
4567
4568 // In naming, we do the contrary of RFC 1323. The sended scaling factor
4569 // is Snd.Wind.Scale (and not Rcv.Wind.Scale)
4570
4572 option->SetScale(m_rcvWindShift);
4573
4574 header.AppendOption(option);
4575
4576 NS_LOG_INFO(m_node->GetId() << " Send a scaling factor of "
4577 << static_cast<int>(m_rcvWindShift));
4578}
4579
4582{
4583 NS_LOG_FUNCTION(this << option);
4584
4586
4587 // Update m_sndFack with the highest sequence number acknowledged from the SACK blocks
4588 if (m_fackEnabled)
4589 {
4590 for (const auto& [leftEdge, rightEdge] : s->GetSackList())
4591 {
4592 if (rightEdge.GetValue() > m_sndFack)
4593 {
4594 NS_LOG_INFO(" m_sndFack updated from " << m_sndFack << " to "
4595 << rightEdge.GetValue());
4596 m_sndFack = rightEdge.GetValue();
4597 }
4598 }
4599 }
4600
4601 return m_txBuffer->Update(s->GetSackList(), MakeCallback(&TcpRateOps::SkbDelivered, m_rateOps));
4602}
4603
4604void
4606{
4607 NS_LOG_FUNCTION(this << option);
4608
4610
4611 NS_ASSERT(m_sackEnabled == true);
4612 NS_LOG_INFO(m_node->GetId() << " Received a SACK_PERMITTED option " << s);
4613}
4614
4615void
4617{
4618 NS_LOG_FUNCTION(this << header);
4619 NS_ASSERT(header.GetFlags() & TcpHeader::SYN);
4620
4622 header.AppendOption(option);
4623 NS_LOG_INFO(m_node->GetId() << " Add option SACK-PERMITTED");
4624}
4625
4626void
4628{
4629 NS_LOG_FUNCTION(this << header);
4630
4631 // Calculate the number of SACK blocks allowed in this packet
4632 uint8_t optionLenAvail = header.GetMaxOptionLength() - header.GetOptionLength();
4633 uint8_t allowedSackBlocks = (optionLenAvail - 2) / 8;
4634
4635 TcpOptionSack::SackList sackList = m_tcb->m_rxBuffer->GetSackList();
4636 if (allowedSackBlocks == 0 || sackList.empty())
4637 {
4638 NS_LOG_LOGIC("No space available or sack list empty, not adding sack blocks");
4639 return;
4640 }
4641
4642 // Append the allowed number of SACK blocks
4644
4645 for (auto i = sackList.begin(); allowedSackBlocks > 0 && i != sackList.end(); ++i)
4646 {
4647 option->AddSackBlock(*i);
4648 allowedSackBlocks--;
4649 }
4650
4651 header.AppendOption(option);
4652 NS_LOG_INFO(m_node->GetId() << " Add option SACK " << *option);
4653}
4654
4655void
4657 const SequenceNumber32& seq)
4658{
4659 NS_LOG_FUNCTION(this << option);
4660
4662
4663 // This is valid only when no overflow occurs. It happens
4664 // when a connection last longer than 50 days.
4665 if (m_tcb->m_rcvTimestampValue > ts->GetTimestamp())
4666 {
4667 // Do not save a smaller timestamp (probably there is reordering)
4668 return;
4669 }
4670
4671 m_tcb->m_rcvTimestampValue = ts->GetTimestamp();
4672 m_tcb->m_rcvTimestampEchoReply = ts->GetEcho();
4673
4674 if (seq == m_tcb->m_rxBuffer->NextRxSequence() && seq <= m_highTxAck)
4675 {
4676 m_timestampToEcho = ts->GetTimestamp();
4677 }
4678
4679 NS_LOG_INFO(m_node->GetId() << " Got timestamp=" << m_timestampToEcho
4680 << " and Echo=" << ts->GetEcho());
4681}
4682
4683void
4685{
4686 NS_LOG_FUNCTION(this << header);
4687
4689
4690 option->SetTimestamp(TcpOptionTS::NowToTsValue());
4691 option->SetEcho(m_timestampToEcho);
4692
4693 header.AppendOption(option);
4694 NS_LOG_INFO(m_node->GetId() << " Add option TS, ts=" << option->GetTimestamp()
4695 << " echo=" << m_timestampToEcho);
4696}
4697
4698void
4700{
4701 NS_LOG_FUNCTION(this << header);
4702 // If the connection is not established, the window size is always
4703 // updated
4704 uint32_t receivedWindow = header.GetWindowSize();
4705 receivedWindow <<= m_sndWindShift;
4706 NS_LOG_INFO("Received (scaled) window is " << receivedWindow << " bytes");
4707 if (m_state < ESTABLISHED)
4708 {
4709 m_rWnd = receivedWindow;
4710 NS_LOG_LOGIC("State less than ESTABLISHED; updating rWnd to " << m_rWnd);
4711 return;
4712 }
4713
4714 // Test for conditions that allow updating of the window
4715 // 1) segment contains new data (advancing the right edge of the receive
4716 // buffer),
4717 // 2) segment does not contain new data but the segment acks new data
4718 // (highest sequence number acked advances), or
4719 // 3) the advertised window is larger than the current send window
4720 bool update = false;
4721 if (header.GetAckNumber() == m_highRxAckMark && receivedWindow > m_rWnd)
4722 {
4723 // right edge of the send window is increased (window update)
4724 update = true;
4725 }
4726 if (header.GetAckNumber() > m_highRxAckMark)
4727 {
4728 m_highRxAckMark = header.GetAckNumber();
4729 update = true;
4730 }
4731 if (header.GetSequenceNumber() > m_highRxMark)
4732 {
4734 update = true;
4735 }
4736 if (update)
4737 {
4738 m_rWnd = receivedWindow;
4739 NS_LOG_LOGIC("updating rWnd to " << m_rWnd);
4740 }
4741}
4742
4743void
4745{
4746 NS_LOG_FUNCTION(this << minRto);
4747 m_minRto = minRto;
4748}
4749
4750Time
4752{
4753 return m_minRto;
4754}
4755
4756void
4758{
4759 NS_LOG_FUNCTION(this << clockGranularity);
4760 m_clockGranularity = clockGranularity;
4761}
4762
4763Time
4768
4771{
4772 return m_txBuffer;
4773}
4774
4777{
4778 return m_tcb->m_rxBuffer;
4779}
4780
4781void
4783{
4784 m_retxThresh = retxThresh;
4785 m_txBuffer->SetDupAckThresh(retxThresh);
4786}
4787
4788void
4790{
4791 m_pacingRateTrace(oldValue, newValue);
4792}
4793
4794void
4796{
4797 m_cWndTrace(oldValue, newValue);
4798}
4799
4800void
4802{
4803 m_cWndInflTrace(oldValue, newValue);
4804}
4805
4806void
4808{
4809 m_ssThTrace(oldValue, newValue);
4810}
4811
4812void
4818
4819void
4821 TcpSocketState::EcnState_t newValue) const
4822{
4823 m_ecnStateTrace(oldValue, newValue);
4824}
4825
4826void
4828
4829{
4830 m_nextTxSequenceTrace(oldValue, newValue);
4831}
4832
4833void
4835{
4836 m_highTxMarkTrace(oldValue, newValue);
4837}
4838
4839void
4841{
4842 m_bytesInFlightTrace(oldValue, newValue);
4843}
4844
4845void
4847{
4848 m_fackAwndTrace(oldValue, newValue);
4849}
4850
4851void
4852TcpSocketBase::UpdateRtt(Time oldValue, Time newValue) const
4853{
4854 m_srttTrace(oldValue, newValue);
4855}
4856
4857void
4858TcpSocketBase::UpdateLastRtt(Time oldValue, Time newValue) const
4859{
4860 m_lastRttTrace(oldValue, newValue);
4861}
4862
4863void
4871
4872void
4874{
4875 NS_LOG_FUNCTION(this << recovery);
4876 m_recoveryOps = recovery;
4877}
4878
4881{
4882 return CopyObject<TcpSocketBase>(this);
4883}
4884
4887{
4888 if (a > b)
4889 {
4890 return a - b;
4891 }
4892
4893 return 0;
4894}
4895
4896void
4898{
4899 NS_LOG_FUNCTION(this);
4900 NS_LOG_INFO("Performing Pacing");
4902}
4903
4904bool
4906{
4907 if (!m_tcb->m_pacing)
4908 {
4909 return false;
4910 }
4911 else
4912 {
4913 if (m_tcb->m_paceInitialWindow)
4914 {
4915 return true;
4916 }
4917 SequenceNumber32 highTxMark = m_tcb->m_highTxMark; // cast traced value
4918 if (highTxMark.GetValue() > (GetInitialCwnd() * m_tcb->m_segmentSize))
4919 {
4920 return true;
4921 }
4922 }
4923 return false;
4924}
4925
4926void
4928{
4929 NS_LOG_FUNCTION(this << m_tcb);
4930
4931 // According to Linux, set base pacing rate to (cwnd * mss) / srtt
4932 //
4933 // In (early) slow start, multiply base by the slow start factor.
4934 // In late slow start and congestion avoidance, multiply base by
4935 // the congestion avoidance factor.
4936 // Comment from Linux code regarding early/late slow start:
4937 // Normal Slow Start condition is (tp->snd_cwnd < tp->snd_ssthresh)
4938 // If snd_cwnd >= (tp->snd_ssthresh / 2), we are approaching
4939 // end of slow start and should slow down.
4940
4941 // Similar to Linux, do not update pacing rate here if the
4942 // congestion control implements TcpCongestionOps::CongControl ()
4943 if (m_congestionControl->HasCongControl() || !m_tcb->m_pacing)
4944 {
4945 return;
4946 }
4947
4948 double factor;
4949 if (m_tcb->m_cWnd < m_tcb->m_ssThresh / 2)
4950 {
4951 NS_LOG_DEBUG("Pacing according to slow start factor; " << m_tcb->m_cWnd << " "
4952 << m_tcb->m_ssThresh);
4953 factor = static_cast<double>(m_tcb->m_pacingSsRatio) / 100;
4954 }
4955 else
4956 {
4957 NS_LOG_DEBUG("Pacing according to congestion avoidance factor; " << m_tcb->m_cWnd << " "
4958 << m_tcb->m_ssThresh);
4959 factor = static_cast<double>(m_tcb->m_pacingCaRatio) / 100;
4960 }
4961 Time srtt = m_tcb->m_srtt.Get(); // Get underlying Time value
4962 NS_LOG_DEBUG("Smoothed RTT is " << srtt.GetSeconds());
4963
4964 // Multiply by 8 to convert from bytes per second to bits per second
4965 DataRate pacingRate((std::max(m_tcb->m_cWnd, m_tcb->m_bytesInFlight) * 8 * factor) /
4966 srtt.GetSeconds());
4967 if (pacingRate < m_tcb->m_maxPacingRate)
4968 {
4969 NS_LOG_DEBUG("Pacing rate updated to: " << pacingRate);
4970 m_tcb->m_pacingRate = pacingRate;
4971 }
4972 else
4973 {
4974 NS_LOG_DEBUG("Pacing capped by max pacing rate: " << m_tcb->m_maxPacingRate);
4975 m_tcb->m_pacingRate = m_tcb->m_maxPacingRate;
4976 }
4977}
4978
4979void
4981{
4982 NS_LOG_FUNCTION(this << pacing);
4983 m_tcb->m_pacing = pacing;
4984}
4985
4986void
4988{
4989 NS_LOG_FUNCTION(this << paceWindow);
4990 m_tcb->m_paceInitialWindow = paceWindow;
4991}
4992
4993bool
4995{
4996 NS_LOG_FUNCTION(this << packetType);
4997 NS_ASSERT_MSG(packetType != TcpPacketType_t::INVALID, "Invalid TCP packet type");
4998 if (m_tcb->m_ecnState == TcpSocketState::ECN_DISABLED)
4999 {
5000 return false;
5001 }
5002
5003 NS_ABORT_MSG_IF(!ECN_RESTRICTION_MAP.contains(std::make_pair(packetType, m_tcb->m_ecnMode)),
5004 "Invalid packetType and ecnMode");
5005
5006 return ECN_RESTRICTION_MAP.at(std::make_pair(packetType, m_tcb->m_ecnMode));
5007}
5008
5009void
5011{
5012 NS_LOG_FUNCTION(this << useEcn);
5013 m_tcb->m_useEcn = useEcn;
5014}
5015
5016void
5018{
5019 NS_LOG_FUNCTION(this << useAbe);
5020 if (m_tcb->m_useEcn == TcpSocketState::Off && useAbe)
5021 {
5022 NS_LOG_INFO("Enabling ECN along with ABE");
5023 m_tcb->m_useEcn = TcpSocketState::On;
5024 }
5025 m_tcb->m_abeEnabled = useAbe;
5026}
5027
5028bool
5030{
5031 return m_tcb->m_abeEnabled;
5032}
5033
5036{
5037 return m_rWnd.Get();
5038}
5039
5042{
5043 return m_highRxAckMark.Get();
5044}
5045
5046// RttHistory methods
5048 : seq(s),
5049 count(c),
5050 time(t),
5051 retx(false)
5052{
5053}
5054
5056 : seq(h.seq),
5057 count(h.count),
5058 time(h.time),
5059 retx(h.retx)
5060{
5061}
5062
5063} // 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:789
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:658
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:901
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:845
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
@ S
second
Definition nstime.h:106
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:1410
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:1003
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:76
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:136
#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:99
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:253
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition log.h:201
#define NS_LOG_DEBUG(msg)
Use NS_LOG to output a message of level LOG_DEBUG.
Definition log.h:267
#define NS_LOG_LOGIC(msg)
Use NS_LOG to output a message of level LOG_LOGIC.
Definition log.h:281
#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:260
#define NS_LOG_INFO(msg)
Use NS_LOG to output a message of level LOG_INFO.
Definition log.h:274
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:1347
Time Seconds(double value)
Construct a Time in the indicated unit.
Definition nstime.h:1313
Time MilliSeconds(uint64_t value)
Construct a Time in the indicated unit.
Definition nstime.h:1330
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:1416
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:1436
-bbr-example
ns3::Time timeout