code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007-2009 Strasbourg University * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Sebastien Vincent <vincent@clarinet.u-strasbg.fr> */ #include <iostream> #include "ns3/net-device.h" #include "ipv6-route.h" namespace ns3 { Ipv6Route::Ipv6Route () { } Ipv6Route::~Ipv6Route () { } void Ipv6Route::SetDestination (Ipv6Address dest) { m_dest = dest; } Ipv6Address Ipv6Route::GetDestination () const { return m_dest; } void Ipv6Route::SetSource (Ipv6Address src) { m_source = src; } Ipv6Address Ipv6Route::GetSource () const { return m_source; } void Ipv6Route::SetGateway (Ipv6Address gw) { m_gateway = gw; } Ipv6Address Ipv6Route::GetGateway () const { return m_gateway; } void Ipv6Route::SetOutputDevice (Ptr<NetDevice> outputDevice) { m_outputDevice = outputDevice; } Ptr<NetDevice> Ipv6Route::GetOutputDevice () const { return m_outputDevice; } std::ostream& operator<< (std::ostream& os, Ipv6Route const& route) { os << "source=" << route.GetSource () << " dest="<< route.GetDestination () <<" gw=" << route.GetGateway (); return os; } Ipv6MulticastRoute::Ipv6MulticastRoute () { m_ttls.clear (); } Ipv6MulticastRoute::~Ipv6MulticastRoute () { } void Ipv6MulticastRoute::SetGroup (const Ipv6Address group) { m_group = group; } Ipv6Address Ipv6MulticastRoute::GetGroup () const { return m_group; } void Ipv6MulticastRoute::SetOrigin (const Ipv6Address origin) { m_origin = origin; } Ipv6Address Ipv6MulticastRoute::GetOrigin () const { return m_origin; } void Ipv6MulticastRoute::SetParent (uint32_t parent) { m_parent = parent; } uint32_t Ipv6MulticastRoute::GetParent () const { return m_parent; } void Ipv6MulticastRoute::SetOutputTtl (uint32_t oif, uint32_t ttl) { if (ttl >= MAX_TTL) { // This TTL value effectively disables the interface std::map<uint32_t, uint32_t>::iterator iter; iter = m_ttls.find (oif); if (iter != m_ttls.end ()) { m_ttls.erase (iter); } } else { m_ttls[oif] = ttl; } } uint32_t Ipv6MulticastRoute::GetOutputTtl (uint32_t oif) { // We keep this interface around for compatibility (for now) std::map<uint32_t, uint32_t>::const_iterator iter = m_ttls.find (oif); if (iter == m_ttls.end ()) return((uint32_t)MAX_TTL); return(iter->second); } std::map<uint32_t, uint32_t> Ipv6MulticastRoute::GetOutputTtlMap () const { return(m_ttls); } std::ostream& operator<< (std::ostream& os, Ipv6MulticastRoute const& route) { os << "origin=" << route.GetOrigin () << " group="<< route.GetGroup () <<" parent=" << route.GetParent (); return os; } } /* namespace ns3 */
zy901002-gpsr
src/internet/model/ipv6-route.cc
C++
gpl2
3,342
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2010 Adrian Sai-wah Tam * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Adrian Sai-wah Tam <adrian.sw.tam@gmail.com> */ #ifndef TCP_NEWRENO_H #define TCP_NEWRENO_H #include "tcp-socket-base.h" namespace ns3 { /** * \ingroup socket * \ingroup tcp * * \brief An implementation of a stream socket using TCP. * * This class contains the NewReno implementation of TCP, as of RFC2582. */ class TcpNewReno : public TcpSocketBase { public: static TypeId GetTypeId (void); /** * Create an unbound tcp socket. */ TcpNewReno (void); TcpNewReno (const TcpNewReno& sock); virtual ~TcpNewReno (void); // From TcpSocketBase virtual int Connect (const Address &address); virtual int Listen (void); protected: virtual uint32_t Window (void); // Return the max possible number of unacked bytes virtual Ptr<TcpSocketBase> Fork (void); // Call CopyObject<TcpNewReno> to clone me virtual void NewAck (SequenceNumber32 const& seq); // Inc cwnd and call NewAck() of parent virtual void DupAck (const TcpHeader& t, uint32_t count); // Halving cwnd and reset nextTxSequence virtual void Retransmit (void); // Exit fast recovery upon retransmit timeout // Implementing ns3::TcpSocket -- Attribute get/set virtual void SetSegSize (uint32_t size); virtual void SetSSThresh (uint32_t threshold); virtual uint32_t GetSSThresh (void) const; virtual void SetInitialCwnd (uint32_t cwnd); virtual uint32_t GetInitialCwnd (void) const; private: void InitializeCwnd (void); // set m_cWnd when connection starts protected: TracedValue<uint32_t> m_cWnd; //< Congestion window uint32_t m_ssThresh; //< Slow Start Threshold uint32_t m_initialCWnd; //< Initial cWnd value SequenceNumber32 m_recover; //< Previous highest Tx seqnum for fast recovery bool m_inFastRec; //< currently in fast recovery }; } // namespace ns3 #endif /* TCP_NEWRENO_H */
zy901002-gpsr
src/internet/model/tcp-newreno.h
C++
gpl2
2,681
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007-2009 Strasbourg University * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: David Gross <gdavid.devel@gmail.com> */ #include <list> #include <ctime> #include "ns3/log.h" #include "ns3/assert.h" #include "ns3/uinteger.h" #include "ns3/object-vector.h" #include "ns3/ipv6-address.h" #include "ns3/ipv6-header.h" #include "ns3/ipv6-l3-protocol.h" #include "ns3/ipv6-static-routing.h" #include "ns3/ipv6-list-routing.h" #include "ns3/ipv6-route.h" #include "ns3/trace-source-accessor.h" #include "ns3/random-variable.h" #include "icmpv6-l4-protocol.h" #include "ipv6-extension-demux.h" #include "ipv6-extension.h" #include "ipv6-extension-header.h" #include "ipv6-option-demux.h" #include "ipv6-option.h" #include "udp-header.h" NS_LOG_COMPONENT_DEFINE ("Ipv6Extension"); namespace ns3 { NS_OBJECT_ENSURE_REGISTERED (Ipv6Extension); TypeId Ipv6Extension::GetTypeId () { static TypeId tid = TypeId ("ns3::Ipv6Extension") .SetParent<Object> () .AddAttribute ("ExtensionNumber", "The IPv6 extension number.", UintegerValue (0), MakeUintegerAccessor (&Ipv6Extension::GetExtensionNumber), MakeUintegerChecker<uint8_t> ()) .AddTraceSource ("Drop", "Drop ipv6 packet", MakeTraceSourceAccessor (&Ipv6Extension::m_dropTrace)) ; return tid; } Ipv6Extension::~Ipv6Extension () { NS_LOG_FUNCTION_NOARGS (); } void Ipv6Extension::SetNode (Ptr<Node> node) { NS_LOG_FUNCTION (this << node); m_node = node; } Ptr<Node> Ipv6Extension::GetNode () const { NS_LOG_FUNCTION_NOARGS (); return m_node; } uint8_t Ipv6Extension::ProcessOptions (Ptr<Packet>& packet, uint8_t offset, uint8_t length, Ipv6Header const& ipv6Header, Ipv6Address dst, uint8_t *nextHeader, bool& isDropped) { NS_LOG_FUNCTION (this << packet << offset << length << ipv6Header << dst << nextHeader << isDropped); // For ICMPv6 Error packets Ptr<Packet> malformedPacket = packet->Copy (); malformedPacket->AddHeader (ipv6Header); Ptr<Icmpv6L4Protocol> icmpv6 = GetNode ()->GetObject<Ipv6L3Protocol> ()->GetIcmpv6 (); Ptr<Packet> p = packet->Copy (); p->RemoveAtStart (offset); Ptr<Ipv6OptionDemux> ipv6OptionDemux = GetNode ()->GetObject<Ipv6OptionDemux> (); Ptr<Ipv6Option> ipv6Option; uint8_t processedSize = 0; uint32_t size = p->GetSize (); uint8_t *data = new uint8_t[size]; p->CopyData (data, size); uint8_t optionType = 0; uint8_t optionLength = 0; while (length > processedSize && !isDropped) { optionType = *(data + processedSize); ipv6Option = ipv6OptionDemux->GetOption (optionType); if (ipv6Option == 0) { optionType >>= 6; switch (optionType) { case 0: optionLength = *(data + processedSize + 1) + 2; break; case 1: NS_LOG_LOGIC ("Unknown Option. Drop!"); m_dropTrace (packet); optionLength = 0; isDropped = true; break; case 2: NS_LOG_LOGIC ("Unknown Option. Drop!"); icmpv6->SendErrorParameterError (malformedPacket, ipv6Header.GetSourceAddress (), Icmpv6Header::ICMPV6_UNKNOWN_OPTION, offset + processedSize); m_dropTrace (packet); optionLength = 0; isDropped = true; break; case 3: NS_LOG_LOGIC ("Unknown Option. Drop!"); if (!ipv6Header.GetDestinationAddress ().IsMulticast ()) { icmpv6->SendErrorParameterError (malformedPacket, ipv6Header.GetSourceAddress (), Icmpv6Header::ICMPV6_UNKNOWN_OPTION, offset + processedSize); m_dropTrace (packet); optionLength = 0; isDropped = true; break; } m_dropTrace (packet); optionLength = 0; isDropped = true; break; default: break; } } else { optionLength = ipv6Option->Process (packet, offset + processedSize, ipv6Header, isDropped); } processedSize += optionLength; p->RemoveAtStart (optionLength); } delete [] data; return processedSize; } NS_OBJECT_ENSURE_REGISTERED (Ipv6ExtensionHopByHop); TypeId Ipv6ExtensionHopByHop::GetTypeId () { static TypeId tid = TypeId ("ns3::Ipv6ExtensionHopByHop") .SetParent<Ipv6Extension> () .AddConstructor<Ipv6ExtensionHopByHop> () ; return tid; } Ipv6ExtensionHopByHop::Ipv6ExtensionHopByHop () { NS_LOG_FUNCTION_NOARGS (); } Ipv6ExtensionHopByHop::~Ipv6ExtensionHopByHop () { NS_LOG_FUNCTION_NOARGS (); } uint8_t Ipv6ExtensionHopByHop::GetExtensionNumber () const { NS_LOG_FUNCTION_NOARGS (); return EXT_NUMBER; } uint8_t Ipv6ExtensionHopByHop::Process (Ptr<Packet>& packet, uint8_t offset, Ipv6Header const& ipv6Header, Ipv6Address dst, uint8_t *nextHeader, bool& isDropped) { NS_LOG_FUNCTION (this << packet << offset << ipv6Header << dst << nextHeader << isDropped); Ptr<Packet> p = packet->Copy (); p->RemoveAtStart (offset); Ipv6ExtensionHopByHopHeader hopbyhopHeader; p->RemoveHeader (hopbyhopHeader); if (nextHeader) { *nextHeader = hopbyhopHeader.GetNextHeader (); } uint8_t processedSize = hopbyhopHeader.GetOptionsOffset (); offset += processedSize; uint8_t length = hopbyhopHeader.GetLength () - hopbyhopHeader.GetOptionsOffset (); processedSize += ProcessOptions (packet, offset, length, ipv6Header, dst, nextHeader, isDropped); return processedSize; } NS_OBJECT_ENSURE_REGISTERED (Ipv6ExtensionDestination); TypeId Ipv6ExtensionDestination::GetTypeId () { static TypeId tid = TypeId ("ns3::Ipv6ExtensionDestination") .SetParent<Ipv6Extension> () .AddConstructor<Ipv6ExtensionDestination> () ; return tid; } Ipv6ExtensionDestination::Ipv6ExtensionDestination () { NS_LOG_FUNCTION_NOARGS (); } Ipv6ExtensionDestination::~Ipv6ExtensionDestination () { NS_LOG_FUNCTION_NOARGS (); } uint8_t Ipv6ExtensionDestination::GetExtensionNumber () const { NS_LOG_FUNCTION_NOARGS (); return EXT_NUMBER; } uint8_t Ipv6ExtensionDestination::Process (Ptr<Packet>& packet, uint8_t offset, Ipv6Header const& ipv6Header, Ipv6Address dst, uint8_t *nextHeader, bool& isDropped) { NS_LOG_FUNCTION (this << packet << offset << ipv6Header << dst << nextHeader << isDropped); Ptr<Packet> p = packet->Copy (); p->RemoveAtStart (offset); Ipv6ExtensionDestinationHeader destinationHeader; p->RemoveHeader (destinationHeader); if (nextHeader) { *nextHeader = destinationHeader.GetNextHeader (); } uint8_t processedSize = destinationHeader.GetOptionsOffset (); offset += processedSize; uint8_t length = destinationHeader.GetLength () - destinationHeader.GetOptionsOffset (); processedSize += ProcessOptions (packet, offset, length, ipv6Header, dst, nextHeader, isDropped); return processedSize; } NS_OBJECT_ENSURE_REGISTERED (Ipv6ExtensionFragment); TypeId Ipv6ExtensionFragment::GetTypeId () { static TypeId tid = TypeId ("ns3::Ipv6ExtensionFragment") .SetParent<Ipv6Extension> () .AddConstructor<Ipv6ExtensionFragment> () ; return tid; } Ipv6ExtensionFragment::Ipv6ExtensionFragment () { NS_LOG_FUNCTION_NOARGS (); } Ipv6ExtensionFragment::~Ipv6ExtensionFragment () { NS_LOG_FUNCTION_NOARGS (); } void Ipv6ExtensionFragment::DoDispose () { NS_LOG_FUNCTION_NOARGS (); for (MapFragments_t::iterator it = m_fragments.begin (); it != m_fragments.end (); it++) { it->second = 0; } m_fragments.clear (); Ipv6Extension::DoDispose (); } uint8_t Ipv6ExtensionFragment::GetExtensionNumber () const { NS_LOG_FUNCTION_NOARGS (); return EXT_NUMBER; } uint8_t Ipv6ExtensionFragment::Process (Ptr<Packet>& packet, uint8_t offset, Ipv6Header const& ipv6Header, Ipv6Address dst, uint8_t *nextHeader, bool& isDropped) { NS_LOG_FUNCTION (this << packet << offset << ipv6Header << dst << nextHeader << isDropped); Ptr<Packet> p = packet->Copy (); p->RemoveAtStart (offset); Ipv6ExtensionFragmentHeader fragmentHeader; p->RemoveHeader (fragmentHeader); if (nextHeader) { *nextHeader = fragmentHeader.GetNextHeader (); } bool moreFragment = fragmentHeader.GetMoreFragment (); uint16_t fragmentOffset = fragmentHeader.GetOffset (); uint32_t identification = fragmentHeader.GetIdentification (); Ipv6Address src = ipv6Header.GetSourceAddress (); std::pair<Ipv6Address, uint32_t> fragmentsId = std::make_pair<Ipv6Address, uint32_t> (src, identification); Ptr<Fragments> fragments; MapFragments_t::iterator it = m_fragments.find (fragmentsId); if (it == m_fragments.end ()) { fragments = Create<Fragments> (); m_fragments.insert (std::make_pair (fragmentsId, fragments)); EventId timeout = Simulator::Schedule (Seconds(60), &Ipv6ExtensionFragment::HandleFragmentsTimeout, this, fragmentsId, fragments, ipv6Header); fragments->SetTimeoutEventId (timeout); } else { fragments = it->second; } if (fragmentOffset == 0) { Ptr<Packet> unfragmentablePart = packet->Copy (); unfragmentablePart->RemoveAtEnd (packet->GetSize () - offset); fragments->SetUnfragmentablePart (unfragmentablePart); } fragments->AddFragment (p, fragmentOffset, moreFragment); if (fragments->IsEntire ()) { packet = fragments->GetPacket (); fragments->CancelTimeout(); m_fragments.erase(fragmentsId); isDropped = false; } else { // the fragment is not "dropped", but Ipv6L3Protocol::LocalDeliver must stop processing it. isDropped = true; } return 0; } void Ipv6ExtensionFragment::GetFragments (Ptr<Packet> packet, uint32_t maxFragmentSize, std::list<Ptr<Packet> >& listFragments) { Ptr<Packet> p = packet->Copy (); Ipv6Header ipv6Header; p->RemoveHeader (ipv6Header); uint8_t nextHeader = ipv6Header.GetNextHeader (); uint8_t ipv6HeaderSize = ipv6Header.GetSerializedSize (); uint8_t type; p->CopyData (&type, sizeof(type)); bool moreHeader = true; if (!(nextHeader == Ipv6Header::IPV6_EXT_HOP_BY_HOP || nextHeader == Ipv6Header::IPV6_EXT_ROUTING || (nextHeader == Ipv6Header::IPV6_EXT_DESTINATION && type == Ipv6Header::IPV6_EXT_ROUTING))) { moreHeader = false; ipv6Header.SetNextHeader (Ipv6Header::IPV6_EXT_FRAGMENTATION); } std::list<std::pair<Ipv6ExtensionHeader *, uint8_t> > unfragmentablePart; uint32_t unfragmentablePartSize = 0; Ptr<Ipv6ExtensionDemux> extensionDemux = GetNode ()->GetObject<Ipv6ExtensionDemux> (); Ptr<Ipv6Extension> extension = extensionDemux->GetExtension (nextHeader); uint8_t extensionHeaderLength; while (moreHeader) { if (nextHeader == Ipv6Header::IPV6_EXT_HOP_BY_HOP) { Ipv6ExtensionHopByHopHeader *hopbyhopHeader = new Ipv6ExtensionHopByHopHeader (); p->RemoveHeader (*hopbyhopHeader); nextHeader = hopbyhopHeader->GetNextHeader (); extensionHeaderLength = hopbyhopHeader->GetLength (); uint8_t type; p->CopyData (&type, sizeof(type)); if (!(nextHeader == Ipv6Header::IPV6_EXT_HOP_BY_HOP || nextHeader == Ipv6Header::IPV6_EXT_ROUTING || (nextHeader == Ipv6Header::IPV6_EXT_DESTINATION && type == Ipv6Header::IPV6_EXT_ROUTING))) { moreHeader = false; hopbyhopHeader->SetNextHeader (Ipv6Header::IPV6_EXT_FRAGMENTATION); } unfragmentablePart.push_back (std::make_pair<Ipv6ExtensionHeader *, uint8_t> (hopbyhopHeader, Ipv6Header::IPV6_EXT_HOP_BY_HOP)); unfragmentablePartSize += extensionHeaderLength; } else if (nextHeader == Ipv6Header::IPV6_EXT_ROUTING) { uint8_t buf[2]; p->CopyData (buf, sizeof(buf)); uint8_t numberAddress = buf[1] / 2; Ipv6ExtensionLooseRoutingHeader *routingHeader = new Ipv6ExtensionLooseRoutingHeader (); routingHeader->SetNumberAddress (numberAddress); p->RemoveHeader (*routingHeader); nextHeader = routingHeader->GetNextHeader (); extensionHeaderLength = routingHeader->GetLength (); uint8_t type; p->CopyData (&type, sizeof(type)); if (!(nextHeader == Ipv6Header::IPV6_EXT_HOP_BY_HOP || nextHeader == Ipv6Header::IPV6_EXT_ROUTING || (nextHeader == Ipv6Header::IPV6_EXT_DESTINATION && type == Ipv6Header::IPV6_EXT_ROUTING))) { moreHeader = false; routingHeader->SetNextHeader (Ipv6Header::IPV6_EXT_FRAGMENTATION); } unfragmentablePart.push_back (std::make_pair<Ipv6ExtensionHeader *, uint8_t> (routingHeader, Ipv6Header::IPV6_EXT_ROUTING)); unfragmentablePartSize += extensionHeaderLength; } else if (nextHeader == Ipv6Header::IPV6_EXT_DESTINATION) { Ipv6ExtensionDestinationHeader *destinationHeader = new Ipv6ExtensionDestinationHeader (); p->RemoveHeader (*destinationHeader); nextHeader = destinationHeader->GetNextHeader (); extensionHeaderLength = destinationHeader->GetLength (); uint8_t type; p->CopyData (&type, sizeof(type)); if (!(nextHeader == Ipv6Header::IPV6_EXT_HOP_BY_HOP || nextHeader == Ipv6Header::IPV6_EXT_ROUTING || (nextHeader == Ipv6Header::IPV6_EXT_DESTINATION && type == Ipv6Header::IPV6_EXT_ROUTING))) { moreHeader = false; destinationHeader->SetNextHeader (Ipv6Header::IPV6_EXT_FRAGMENTATION); } unfragmentablePart.push_back (std::make_pair<Ipv6ExtensionHeader *, uint8_t> (destinationHeader, Ipv6Header::IPV6_EXT_DESTINATION)); unfragmentablePartSize += extensionHeaderLength; } } Ipv6ExtensionFragmentHeader fragmentHeader; uint8_t fragmentHeaderSize = fragmentHeader.GetSerializedSize (); uint32_t maxFragmentablePartSize = maxFragmentSize - ipv6HeaderSize - unfragmentablePartSize - fragmentHeaderSize; uint32_t currentFragmentablePartSize = 0; bool moreFragment = true; UniformVariable uvar; uint32_t identification = (uint32_t) uvar.GetValue (0, (uint32_t)-1); uint16_t offset = 0; do { if (p->GetSize () > offset + maxFragmentablePartSize) { moreFragment = true; currentFragmentablePartSize = maxFragmentablePartSize; } else { moreFragment = false; currentFragmentablePartSize = p->GetSize () - offset; } currentFragmentablePartSize -= currentFragmentablePartSize % 8; fragmentHeader.SetNextHeader (nextHeader); fragmentHeader.SetLength (currentFragmentablePartSize); fragmentHeader.SetOffset (offset); fragmentHeader.SetMoreFragment (moreFragment); fragmentHeader.SetIdentification (identification); Ptr<Packet> fragment = p->CreateFragment (offset, currentFragmentablePartSize); offset += currentFragmentablePartSize; fragment->AddHeader (fragmentHeader); for (std::list<std::pair<Ipv6ExtensionHeader *, uint8_t> >::iterator it = unfragmentablePart.begin (); it != unfragmentablePart.end (); it++) { if (it->second == Ipv6Header::IPV6_EXT_HOP_BY_HOP) { fragment->AddHeader (*dynamic_cast<Ipv6ExtensionHopByHopHeader *>(it->first)); } else if (it->second == Ipv6Header::IPV6_EXT_ROUTING) { fragment->AddHeader (*dynamic_cast<Ipv6ExtensionLooseRoutingHeader *>(it->first)); } else if (it->second == Ipv6Header::IPV6_EXT_DESTINATION) { fragment->AddHeader (*dynamic_cast<Ipv6ExtensionDestinationHeader *>(it->first)); } } ipv6Header.SetPayloadLength (fragment->GetSize ()); fragment->AddHeader (ipv6Header); std::ostringstream oss; fragment->Print (oss); listFragments.push_back (fragment); } while (moreFragment); for (std::list<std::pair<Ipv6ExtensionHeader *, uint8_t> >::iterator it = unfragmentablePart.begin (); it != unfragmentablePart.end (); it++) { delete it->first; } unfragmentablePart.clear (); } void Ipv6ExtensionFragment::HandleFragmentsTimeout (std::pair<Ipv6Address, uint32_t> fragmentsId, Ptr<Fragments> fragments, Ipv6Header & ipHeader) { Ptr<Packet> packet = fragments->GetPartialPacket (); // if we have at least 8 bytes, we can send an ICMP. if ( packet->GetSize () > 8 ) { Ptr<Icmpv6L4Protocol> icmp = GetNode()->GetObject<Icmpv6L4Protocol> (); icmp->SendErrorTimeExceeded (packet, ipHeader.GetSourceAddress (), Icmpv6Header::ICMPV6_FRAGTIME); } m_dropTrace (packet); // clear the buffers m_fragments.erase(fragmentsId); } Ipv6ExtensionFragment::Fragments::Fragments () : m_moreFragment (0) { } Ipv6ExtensionFragment::Fragments::~Fragments () { } void Ipv6ExtensionFragment::Fragments::AddFragment (Ptr<Packet> fragment, uint16_t fragmentOffset, bool moreFragment) { std::list<std::pair<Ptr<Packet>, uint16_t> >::iterator it; for (it = m_fragments.begin (); it != m_fragments.end (); it++) { if (it->second > fragmentOffset) { break; } } if (it == m_fragments.end ()) { m_moreFragment = moreFragment; } m_fragments.insert (it, std::make_pair<Ptr<Packet>, uint16_t> (fragment, fragmentOffset)); } void Ipv6ExtensionFragment::Fragments::SetUnfragmentablePart (Ptr<Packet> unfragmentablePart) { m_unfragmentable = unfragmentablePart; } bool Ipv6ExtensionFragment::Fragments::IsEntire () const { bool ret = !m_moreFragment && m_fragments.size () > 0; if (ret) { uint16_t lastEndOffset = 0; for (std::list<std::pair<Ptr<Packet>, uint16_t> >::const_iterator it = m_fragments.begin (); it != m_fragments.end (); it++) { if (lastEndOffset != it->second) { ret = false; break; } lastEndOffset += it->first->GetSize (); } } return ret; } Ptr<Packet> Ipv6ExtensionFragment::Fragments::GetPacket () const { Ptr<Packet> p = m_unfragmentable->Copy (); for (std::list<std::pair<Ptr<Packet>, uint16_t> >::const_iterator it = m_fragments.begin (); it != m_fragments.end (); it++) { p->AddAtEnd (it->first); } return p; } Ptr<Packet> Ipv6ExtensionFragment::Fragments::GetPartialPacket () const { Ptr<Packet> p; if ( m_unfragmentable ) { p = m_unfragmentable->Copy (); } else { return p; } uint16_t lastEndOffset = 0; for (std::list<std::pair<Ptr<Packet>, uint16_t> >::const_iterator it = m_fragments.begin (); it != m_fragments.end (); it++) { if (lastEndOffset != it->second) { break; } p->AddAtEnd (it->first); lastEndOffset += it->first->GetSize (); } return p; } void Ipv6ExtensionFragment::Fragments::SetTimeoutEventId (EventId event) { m_timeoutEventId = event; return; } void Ipv6ExtensionFragment::Fragments::CancelTimeout() { m_timeoutEventId.Cancel (); return; } NS_OBJECT_ENSURE_REGISTERED (Ipv6ExtensionRouting); TypeId Ipv6ExtensionRouting::GetTypeId () { static TypeId tid = TypeId ("ns3::Ipv6ExtensionRouting") .SetParent<Ipv6Extension> () .AddConstructor<Ipv6ExtensionRouting> () ; return tid; } Ipv6ExtensionRouting::Ipv6ExtensionRouting () { NS_LOG_FUNCTION_NOARGS (); } Ipv6ExtensionRouting::~Ipv6ExtensionRouting () { NS_LOG_FUNCTION_NOARGS (); } uint8_t Ipv6ExtensionRouting::GetExtensionNumber () const { NS_LOG_FUNCTION_NOARGS (); return EXT_NUMBER; } uint8_t Ipv6ExtensionRouting::GetTypeRouting () const { NS_LOG_FUNCTION_NOARGS (); return 0; } uint8_t Ipv6ExtensionRouting::Process (Ptr<Packet>& packet, uint8_t offset, Ipv6Header const& ipv6Header, Ipv6Address dst, uint8_t *nextHeader, bool& isDropped) { NS_LOG_FUNCTION (this << packet << offset << ipv6Header << dst << nextHeader << isDropped); // For ICMPv6 Error Packets Ptr<Packet> malformedPacket = packet->Copy (); malformedPacket->AddHeader (ipv6Header); Ptr<Packet> p = packet->Copy (); p->RemoveAtStart (offset); uint8_t buf[4]; packet->CopyData (buf, sizeof(buf)); uint8_t routingNextHeader = buf[0]; uint8_t routingLength = buf[1]; uint8_t routingTypeRouting = buf[2]; uint8_t routingSegmentsLeft = buf[3]; if (nextHeader) { *nextHeader = routingNextHeader; } Ptr<Icmpv6L4Protocol> icmpv6 = GetNode ()->GetObject<Ipv6L3Protocol> ()->GetIcmpv6 (); Ptr<Ipv6ExtensionRoutingDemux> ipv6ExtensionRoutingDemux = GetNode ()->GetObject<Ipv6ExtensionRoutingDemux> (); Ptr<Ipv6ExtensionRouting> ipv6ExtensionRouting = ipv6ExtensionRoutingDemux->GetExtensionRouting (routingTypeRouting); if (ipv6ExtensionRouting == 0) { if (routingSegmentsLeft == 0) { isDropped = false; } else { NS_LOG_LOGIC ("Malformed header. Drop!"); icmpv6->SendErrorParameterError (malformedPacket, ipv6Header.GetSourceAddress (), Icmpv6Header::ICMPV6_MALFORMED_HEADER, offset + 1); m_dropTrace (packet); isDropped = true; } return routingLength; } return ipv6ExtensionRouting->Process (packet, offset, ipv6Header, dst, (uint8_t *)0, isDropped); } NS_OBJECT_ENSURE_REGISTERED (Ipv6ExtensionRoutingDemux); TypeId Ipv6ExtensionRoutingDemux::GetTypeId () { static TypeId tid = TypeId ("ns3::Ipv6ExtensionRoutingDemux") .SetParent<Object> () .AddAttribute ("Routing Extensions", "The set of IPv6 Routing extensions registered with this demux.", ObjectVectorValue (), MakeObjectVectorAccessor (&Ipv6ExtensionRoutingDemux::m_extensionsRouting), MakeObjectVectorChecker<Ipv6ExtensionRouting> ()) ; return tid; } Ipv6ExtensionRoutingDemux::Ipv6ExtensionRoutingDemux () { } Ipv6ExtensionRoutingDemux::~Ipv6ExtensionRoutingDemux () { } void Ipv6ExtensionRoutingDemux::DoDispose () { for (Ipv6ExtensionRoutingList_t::iterator it = m_extensionsRouting.begin (); it != m_extensionsRouting.end (); it++) { (*it)->Dispose (); *it = 0; } m_extensionsRouting.clear (); m_node = 0; Object::DoDispose (); } void Ipv6ExtensionRoutingDemux::SetNode (Ptr<Node> node) { m_node = node; } void Ipv6ExtensionRoutingDemux::Insert (Ptr<Ipv6ExtensionRouting> extensionRouting) { m_extensionsRouting.push_back (extensionRouting); } Ptr<Ipv6ExtensionRouting> Ipv6ExtensionRoutingDemux::GetExtensionRouting (uint8_t typeRouting) { for (Ipv6ExtensionRoutingList_t::iterator i = m_extensionsRouting.begin (); i != m_extensionsRouting.end (); i++) { if ((*i)->GetTypeRouting () == typeRouting) { return *i; } } return 0; } void Ipv6ExtensionRoutingDemux::Remove (Ptr<Ipv6ExtensionRouting> extensionRouting) { m_extensionsRouting.remove (extensionRouting); } NS_OBJECT_ENSURE_REGISTERED (Ipv6ExtensionLooseRouting); TypeId Ipv6ExtensionLooseRouting::GetTypeId () { static TypeId tid = TypeId ("ns3::Ipv6ExtensionLooseRouting") .SetParent<Ipv6ExtensionRouting> () .AddConstructor<Ipv6ExtensionLooseRouting> () ; return tid; } Ipv6ExtensionLooseRouting::Ipv6ExtensionLooseRouting () { NS_LOG_FUNCTION_NOARGS (); } Ipv6ExtensionLooseRouting::~Ipv6ExtensionLooseRouting () { NS_LOG_FUNCTION_NOARGS (); } uint8_t Ipv6ExtensionLooseRouting::GetTypeRouting () const { NS_LOG_FUNCTION_NOARGS (); return TYPE_ROUTING; } uint8_t Ipv6ExtensionLooseRouting::Process (Ptr<Packet>& packet, uint8_t offset, Ipv6Header const& ipv6Header, Ipv6Address dst, uint8_t *nextHeader, bool& isDropped) { NS_LOG_FUNCTION (this << packet << offset << ipv6Header << dst << nextHeader << isDropped); // For ICMPv6 Error packets Ptr<Packet> malformedPacket = packet->Copy (); malformedPacket->AddHeader (ipv6Header); Ptr<Packet> p = packet->Copy (); p->RemoveAtStart (offset); // Copy IPv6 Header : ipv6Header -> ipv6header Buffer tmp; tmp.AddAtStart (ipv6Header.GetSerializedSize ()); Buffer::Iterator it = tmp.Begin (); Ipv6Header ipv6header; ipv6Header.Serialize (it); ipv6header.Deserialize (it); // Get the number of routers' address field uint8_t buf[2]; p->CopyData (buf, sizeof(buf)); uint8_t numberAddress = buf[1] / 2; Ipv6ExtensionLooseRoutingHeader routingHeader; routingHeader.SetNumberAddress (numberAddress); p->RemoveHeader (routingHeader); if (nextHeader) { *nextHeader = routingHeader.GetNextHeader (); } Ptr<Icmpv6L4Protocol> icmpv6 = GetNode ()->GetObject<Ipv6L3Protocol> ()->GetIcmpv6 (); Ipv6Address srcAddress = ipv6header.GetSourceAddress (); Ipv6Address destAddress = ipv6header.GetDestinationAddress (); uint8_t hopLimit = ipv6header.GetHopLimit (); uint8_t segmentsLeft = routingHeader.GetSegmentsLeft (); uint8_t length = (routingHeader.GetLength () >> 3) - 1; uint8_t nbAddress = length / 2; uint8_t nextAddressIndex; Ipv6Address nextAddress; if (segmentsLeft == 0) { isDropped = false; return routingHeader.GetSerializedSize (); } if (length % 2 != 0) { NS_LOG_LOGIC ("Malformed header. Drop!"); icmpv6->SendErrorParameterError (malformedPacket, srcAddress, Icmpv6Header::ICMPV6_MALFORMED_HEADER, offset + 1); m_dropTrace (packet); isDropped = true; return routingHeader.GetSerializedSize (); } if (segmentsLeft > nbAddress) { NS_LOG_LOGIC ("Malformed header. Drop!"); icmpv6->SendErrorParameterError (malformedPacket, srcAddress, Icmpv6Header::ICMPV6_MALFORMED_HEADER, offset + 3); m_dropTrace (packet); isDropped = true; return routingHeader.GetSerializedSize (); } routingHeader.SetSegmentsLeft (segmentsLeft - 1); nextAddressIndex = nbAddress - segmentsLeft; nextAddress = routingHeader.GetRouterAddress (nextAddressIndex); if (nextAddress.IsMulticast () || destAddress.IsMulticast ()) { m_dropTrace (packet); isDropped = true; return routingHeader.GetSerializedSize (); } routingHeader.SetRouterAddress (nextAddressIndex, destAddress); ipv6header.SetDestinationAddress (nextAddress); if (hopLimit <= 1) { NS_LOG_LOGIC ("Time Exceeded : Hop Limit <= 1. Drop!"); icmpv6->SendErrorTimeExceeded (malformedPacket, srcAddress, Icmpv6Header::ICMPV6_HOPLIMIT); m_dropTrace (packet); isDropped = true; return routingHeader.GetSerializedSize (); } routingHeader.SetLength (88); ipv6header.SetHopLimit (hopLimit - 1); p->AddHeader (routingHeader); /* short-circuiting routing stuff * * If we process this option, * the packet was for us so we resend it to * the new destination (modified in the header above). */ Ptr<Ipv6L3Protocol> ipv6 = GetNode ()->GetObject<Ipv6L3Protocol> (); Ptr<Ipv6RoutingProtocol> ipv6rp = ipv6->GetRoutingProtocol (); Socket::SocketErrno err; NS_ASSERT (ipv6rp); Ptr<Ipv6Route> rtentry = ipv6rp->RouteOutput (p, ipv6header, 0, err); if (rtentry) { /* we know a route exists so send packet now */ ipv6->SendRealOut (rtentry, p, ipv6header); } else { NS_LOG_INFO ("No route for next router"); } /* as we directly send packet, mark it as dropped */ isDropped = true; return routingHeader.GetSerializedSize (); } NS_OBJECT_ENSURE_REGISTERED (Ipv6ExtensionESP); TypeId Ipv6ExtensionESP::GetTypeId () { static TypeId tid = TypeId ("ns3::Ipv6ExtensionESP") .SetParent<Ipv6Extension> () .AddConstructor<Ipv6ExtensionESP> () ; return tid; } Ipv6ExtensionESP::Ipv6ExtensionESP () { NS_LOG_FUNCTION_NOARGS (); } Ipv6ExtensionESP::~Ipv6ExtensionESP () { NS_LOG_FUNCTION_NOARGS (); } uint8_t Ipv6ExtensionESP::GetExtensionNumber () const { NS_LOG_FUNCTION_NOARGS (); return EXT_NUMBER; } uint8_t Ipv6ExtensionESP::Process (Ptr<Packet>& packet, uint8_t offset, Ipv6Header const& ipv6Header, Ipv6Address dst, uint8_t *nextHeader, bool& isDropped) { NS_LOG_FUNCTION (this << packet << offset << ipv6Header << dst << nextHeader << isDropped); /* TODO */ return 0; } NS_OBJECT_ENSURE_REGISTERED (Ipv6ExtensionAH); TypeId Ipv6ExtensionAH::GetTypeId () { static TypeId tid = TypeId ("ns3::Ipv6ExtensionAH") .SetParent<Ipv6Extension> () .AddConstructor<Ipv6ExtensionAH> () ; return tid; } Ipv6ExtensionAH::Ipv6ExtensionAH () { NS_LOG_FUNCTION_NOARGS (); } Ipv6ExtensionAH::~Ipv6ExtensionAH () { NS_LOG_FUNCTION_NOARGS (); } uint8_t Ipv6ExtensionAH::GetExtensionNumber () const { NS_LOG_FUNCTION_NOARGS (); return EXT_NUMBER; } uint8_t Ipv6ExtensionAH::Process (Ptr<Packet>& packet, uint8_t offset, Ipv6Header const& ipv6Header, Ipv6Address dst, uint8_t *nextHeader, bool& isDropped) { NS_LOG_FUNCTION (this << packet << offset << ipv6Header << dst << nextHeader << isDropped); /* TODO */ return true; } } /* namespace ns3 */
zy901002-gpsr
src/internet/model/ipv6-extension.cc
C++
gpl2
30,018
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2005 INRIA * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr> */ #include "ns3/assert.h" #include "ns3/abort.h" #include "ns3/log.h" #include "ns3/header.h" #include "ipv4-header.h" NS_LOG_COMPONENT_DEFINE ("Ipv4Header"); namespace ns3 { NS_OBJECT_ENSURE_REGISTERED (Ipv4Header); Ipv4Header::Ipv4Header () : m_calcChecksum (false), m_payloadSize (0), m_identification (0), m_tos (0), m_ttl (0), m_protocol (0), m_flags (0), m_fragmentOffset (0), m_checksum (0), m_goodChecksum (true) { } void Ipv4Header::EnableChecksum (void) { m_calcChecksum = true; } void Ipv4Header::SetPayloadSize (uint16_t size) { m_payloadSize = size; } uint16_t Ipv4Header::GetPayloadSize (void) const { return m_payloadSize; } uint16_t Ipv4Header::GetIdentification (void) const { return m_identification; } void Ipv4Header::SetIdentification (uint16_t identification) { m_identification = identification; } void Ipv4Header::SetTos (uint8_t tos) { m_tos = tos; } void Ipv4Header::SetDscp (DscpType dscp) { m_tos &= 0x3; // Clear out the DSCP part, retain 2 bits of ECN m_tos |= dscp; } void Ipv4Header::SetEcn (EcnType ecn) { m_tos &= 0xFC; // Clear out the ECN part, retain 6 bits of DSCP m_tos |= ecn; } Ipv4Header::DscpType Ipv4Header::GetDscp (void) const { // Extract only first 6 bits of TOS byte, i.e 0xFC return DscpType (m_tos & 0xFC); } std::string Ipv4Header::DscpTypeToString (DscpType dscp) const { switch (dscp) { case DscpDefault: return "Default"; case CS1: return "CS1"; case AF11: return "AF11"; case AF12: return "AF12"; case AF13: return "AF13"; case CS2: return "CS2"; case AF21: return "AF21"; case AF22: return "AF22"; case AF23: return "AF23"; case CS3: return "CS3"; case AF31: return "AF31"; case AF32: return "AF32"; case AF33: return "AF33"; case CS4: return "CS4"; case AF41: return "AF41"; case AF42: return "AF42"; case AF43: return "AF43"; case CS5: return "CS5"; case EF: return "EF"; case CS6: return "CS6"; case CS7: return "CS7"; default: return "Unrecognized DSCP"; }; } Ipv4Header::EcnType Ipv4Header::GetEcn (void) const { // Extract only last 2 bits of TOS byte, i.e 0x3 return EcnType (m_tos & 0x3); } std::string Ipv4Header::EcnTypeToString (EcnType ecn) const { switch (ecn) { case NotECT: return "Not-ECT"; case ECT1: return "ECT (1)"; case ECT0: return "ECT (0)"; case CE: return "CE"; default: return "Unknown ECN"; }; } uint8_t Ipv4Header::GetTos (void) const { return m_tos; } void Ipv4Header::SetMoreFragments (void) { m_flags |= MORE_FRAGMENTS; } void Ipv4Header::SetLastFragment (void) { m_flags &= ~MORE_FRAGMENTS; } bool Ipv4Header::IsLastFragment (void) const { return !(m_flags & MORE_FRAGMENTS); } void Ipv4Header::SetDontFragment (void) { m_flags |= DONT_FRAGMENT; } void Ipv4Header::SetMayFragment (void) { m_flags &= ~DONT_FRAGMENT; } bool Ipv4Header::IsDontFragment (void) const { return (m_flags & DONT_FRAGMENT); } void Ipv4Header::SetFragmentOffset (uint16_t offsetBytes) { // check if the user is trying to set an invalid offset NS_ABORT_MSG_IF ((offsetBytes & 0x7), "offsetBytes must be multiple of 8 bytes"); m_fragmentOffset = offsetBytes; } uint16_t Ipv4Header::GetFragmentOffset (void) const { if ((m_fragmentOffset+m_payloadSize+5*4) > 65535) { NS_LOG_WARN("Fragment will exceed the maximum packet size once reassembled"); } return m_fragmentOffset; } void Ipv4Header::SetTtl (uint8_t ttl) { m_ttl = ttl; } uint8_t Ipv4Header::GetTtl (void) const { return m_ttl; } uint8_t Ipv4Header::GetProtocol (void) const { return m_protocol; } void Ipv4Header::SetProtocol (uint8_t protocol) { m_protocol = protocol; } void Ipv4Header::SetSource (Ipv4Address source) { m_source = source; } Ipv4Address Ipv4Header::GetSource (void) const { return m_source; } void Ipv4Header::SetDestination (Ipv4Address dst) { m_destination = dst; } Ipv4Address Ipv4Header::GetDestination (void) const { return m_destination; } bool Ipv4Header::IsChecksumOk (void) const { return m_goodChecksum; } TypeId Ipv4Header::GetTypeId (void) { static TypeId tid = TypeId ("ns3::Ipv4Header") .SetParent<Header> () .AddConstructor<Ipv4Header> () ; return tid; } TypeId Ipv4Header::GetInstanceTypeId (void) const { return GetTypeId (); } void Ipv4Header::Print (std::ostream &os) const { // ipv4, right ? std::string flags; if (m_flags == 0) { flags = "none"; } else if (m_flags & MORE_FRAGMENTS && m_flags & DONT_FRAGMENT) { flags = "MF|DF"; } else if (m_flags & DONT_FRAGMENT) { flags = "DF"; } else if (m_flags & MORE_FRAGMENTS) { flags = "MF"; } else { flags = "XX"; } os << "tos 0x" << std::hex << m_tos << std::dec << " " << "DSCP " << DscpTypeToString (GetDscp ()) << " " << "ECN " << EcnTypeToString (GetEcn ()) << " " << "ttl " << m_ttl << " " << "id " << m_identification << " " << "protocol " << m_protocol << " " << "offset (bytes) " << m_fragmentOffset << " " << "flags [" << flags << "] " << "length: " << (m_payloadSize + 5 * 4) << " " << m_source << " > " << m_destination ; } uint32_t Ipv4Header::GetSerializedSize (void) const { return 5 * 4; } void Ipv4Header::Serialize (Buffer::Iterator start) const { Buffer::Iterator i = start; uint8_t verIhl = (4 << 4) | (5); i.WriteU8 (verIhl); i.WriteU8 (m_tos); i.WriteHtonU16 (m_payloadSize + 5*4); i.WriteHtonU16 (m_identification); uint32_t fragmentOffset = m_fragmentOffset / 8; uint8_t flagsFrag = (fragmentOffset >> 8) & 0x1f; if (m_flags & DONT_FRAGMENT) { flagsFrag |= (1<<6); } if (m_flags & MORE_FRAGMENTS) { flagsFrag |= (1<<5); } i.WriteU8 (flagsFrag); uint8_t frag = fragmentOffset & 0xff; i.WriteU8 (frag); i.WriteU8 (m_ttl); i.WriteU8 (m_protocol); i.WriteHtonU16 (0); i.WriteHtonU32 (m_source.Get ()); i.WriteHtonU32 (m_destination.Get ()); if (m_calcChecksum) { i = start; uint16_t checksum = i.CalculateIpChecksum (20); NS_LOG_LOGIC ("checksum=" <<checksum); i = start; i.Next (10); i.WriteU16 (checksum); } } uint32_t Ipv4Header::Deserialize (Buffer::Iterator start) { Buffer::Iterator i = start; uint8_t verIhl = i.ReadU8 (); uint8_t ihl = verIhl & 0x0f; uint16_t headerSize = ihl * 4; NS_ASSERT ((verIhl >> 4) == 4); m_tos = i.ReadU8 (); uint16_t size = i.ReadNtohU16 (); m_payloadSize = size - headerSize; m_identification = i.ReadNtohU16 (); uint8_t flags = i.ReadU8 (); m_flags = 0; if (flags & (1<<6)) { m_flags |= DONT_FRAGMENT; } if (flags & (1<<5)) { m_flags |= MORE_FRAGMENTS; } i.Prev (); m_fragmentOffset = i.ReadU8 () & 0x1f; m_fragmentOffset <<= 8; m_fragmentOffset |= i.ReadU8 (); m_fragmentOffset <<= 3; m_ttl = i.ReadU8 (); m_protocol = i.ReadU8 (); m_checksum = i.ReadU16 (); /* i.Next (2); // checksum */ m_source.Set (i.ReadNtohU32 ()); m_destination.Set (i.ReadNtohU32 ()); if (m_calcChecksum) { i = start; uint16_t checksum = i.CalculateIpChecksum (headerSize); NS_LOG_LOGIC ("checksum=" <<checksum); m_goodChecksum = (checksum == 0); } return GetSerializedSize (); } } // namespace ns3
zy901002-gpsr
src/internet/model/ipv4-header.cc
C++
gpl2
8,524
#ifndef ICMPV4_L4_PROTOCOL_H #define ICMPV4_L4_PROTOCOL_H #include "ipv4-l4-protocol.h" #include "icmpv4.h" #include "ns3/ipv4-address.h" namespace ns3 { class Node; class Ipv4Interface; class Ipv4Route; class Icmpv4L4Protocol : public Ipv4L4Protocol { public: static TypeId GetTypeId (void); static const uint8_t PROT_NUMBER; Icmpv4L4Protocol (); virtual ~Icmpv4L4Protocol (); void SetNode (Ptr<Node> node); static uint16_t GetStaticProtocolNumber (void); virtual int GetProtocolNumber (void) const; virtual enum Ipv4L4Protocol::RxStatus Receive (Ptr<Packet> p, Ipv4Header const &header, Ptr<Ipv4Interface> incomingInterface); void SendDestUnreachFragNeeded (Ipv4Header header, Ptr<const Packet> orgData, uint16_t nextHopMtu); void SendTimeExceededTtl (Ipv4Header header, Ptr<const Packet> orgData); void SendDestUnreachPort (Ipv4Header header, Ptr<const Packet> orgData); // From Ipv4L4Protocol virtual void SetDownTarget (Ipv4L4Protocol::DownTargetCallback cb); // From Ipv4L4Protocol virtual Ipv4L4Protocol::DownTargetCallback GetDownTarget (void) const; protected: /* * This function will notify other components connected to the node that a new stack member is now connected * This will be used to notify Layer 3 protocol of layer 4 protocol stack to connect them together. */ virtual void NotifyNewAggregate (); private: void HandleEcho (Ptr<Packet> p, Icmpv4Header header, Ipv4Address source, Ipv4Address destination); void HandleDestUnreach (Ptr<Packet> p, Icmpv4Header header, Ipv4Address source, Ipv4Address destination); void HandleTimeExceeded (Ptr<Packet> p, Icmpv4Header icmp, Ipv4Address source, Ipv4Address destination); void SendDestUnreach (Ipv4Header header, Ptr<const Packet> orgData, uint8_t code, uint16_t nextHopMtu); void SendMessage (Ptr<Packet> packet, Ipv4Address dest, uint8_t type, uint8_t code); void SendMessage (Ptr<Packet> packet, Ipv4Address source, Ipv4Address dest, uint8_t type, uint8_t code, Ptr<Ipv4Route> route); void Forward (Ipv4Address source, Icmpv4Header icmp, uint32_t info, Ipv4Header ipHeader, const uint8_t payload[8]); virtual void DoDispose (void); Ptr<Node> m_node; Ipv4L4Protocol::DownTargetCallback m_downTarget; }; } // namespace ns3 #endif /* ICMPV4_L4_PROTOCOL_H */
zy901002-gpsr
src/internet/model/icmpv4-l4-protocol.h
C++
gpl2
2,671
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2009 University of Washington * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include "ns3/log.h" #include "ns3/ipv4.h" #include "ns3/ipv4-route.h" #include "ns3/node.h" #include "ns3/ipv4-static-routing.h" #include "ipv4-list-routing.h" NS_LOG_COMPONENT_DEFINE ("Ipv4ListRouting"); namespace ns3 { NS_OBJECT_ENSURE_REGISTERED (Ipv4ListRouting); TypeId Ipv4ListRouting::GetTypeId (void) { static TypeId tid = TypeId ("ns3::Ipv4ListRouting") .SetParent<Ipv4RoutingProtocol> () .AddConstructor<Ipv4ListRouting> () ; return tid; } Ipv4ListRouting::Ipv4ListRouting () : m_ipv4 (0) { NS_LOG_FUNCTION_NOARGS (); } Ipv4ListRouting::~Ipv4ListRouting () { NS_LOG_FUNCTION_NOARGS (); } void Ipv4ListRouting::DoDispose (void) { NS_LOG_FUNCTION_NOARGS (); for (Ipv4RoutingProtocolList::iterator rprotoIter = m_routingProtocols.begin (); rprotoIter != m_routingProtocols.end (); rprotoIter++) { // Note: Calling dispose on these protocols causes memory leak // The routing protocols should not maintain a pointer to // this object, so Dispose() shouldn't be necessary. (*rprotoIter).second = 0; } m_routingProtocols.clear (); m_ipv4 = 0; } void Ipv4ListRouting::PrintRoutingTable (Ptr<OutputStreamWrapper> stream) const { *stream->GetStream () << "Node: " << m_ipv4->GetObject<Node> ()->GetId () << " Time: " << Simulator::Now ().GetSeconds () << "s " << "Ipv4ListRouting table" << std::endl; for (Ipv4RoutingProtocolList::const_iterator i = m_routingProtocols.begin (); i != m_routingProtocols.end (); i++) { *stream->GetStream () << " Priority: " << (*i).first << " Protocol: " << (*i).second->GetInstanceTypeId () << std::endl; (*i).second->PrintRoutingTable (stream); } *stream->GetStream () << std::endl; } void Ipv4ListRouting::DoStart (void) { for (Ipv4RoutingProtocolList::iterator rprotoIter = m_routingProtocols.begin (); rprotoIter != m_routingProtocols.end (); rprotoIter++) { Ptr<Ipv4RoutingProtocol> protocol = (*rprotoIter).second; protocol->Start (); } Ipv4RoutingProtocol::DoStart (); } Ptr<Ipv4Route> Ipv4ListRouting::RouteOutput (Ptr<Packet> p, const Ipv4Header &header, Ptr<NetDevice> oif, enum Socket::SocketErrno &sockerr) { NS_LOG_FUNCTION (this << header.GetDestination () << " " << header.GetSource () << " " << oif); Ptr<Ipv4Route> route; for (Ipv4RoutingProtocolList::const_iterator i = m_routingProtocols.begin (); i != m_routingProtocols.end (); i++) { NS_LOG_LOGIC ("Checking protocol " << (*i).second->GetInstanceTypeId () << " with priority " << (*i).first); NS_LOG_LOGIC ("Requesting source address for destination " << header.GetDestination ()); route = (*i).second->RouteOutput (p, header, oif, sockerr); if (route) { NS_LOG_LOGIC ("Found route " << route); sockerr = Socket::ERROR_NOTERROR; return route; } } NS_LOG_LOGIC ("Done checking " << GetTypeId ()); NS_LOG_LOGIC (""); sockerr = Socket::ERROR_NOROUTETOHOST; return 0; } // Patterned after Linux ip_route_input and ip_route_input_slow bool Ipv4ListRouting::RouteInput (Ptr<const Packet> p, const Ipv4Header &header, Ptr<const NetDevice> idev, UnicastForwardCallback ucb, MulticastForwardCallback mcb, LocalDeliverCallback lcb, ErrorCallback ecb) { bool retVal = false; NS_LOG_FUNCTION (p << header << idev); NS_LOG_LOGIC ("RouteInput logic for node: " << m_ipv4->GetObject<Node> ()->GetId ()); NS_ASSERT (m_ipv4 != 0); // Check if input device supports IP NS_ASSERT (m_ipv4->GetInterfaceForDevice (idev) >= 0); uint32_t iif = m_ipv4->GetInterfaceForDevice (idev); retVal = m_ipv4->IsDestinationAddress (header.GetDestination (), iif); if (retVal == true) { NS_LOG_LOGIC ("Address "<< header.GetDestination () << " is a match for local delivery"); if (header.GetDestination ().IsMulticast ()) { Ptr<Packet> packetCopy = p->Copy (); lcb (packetCopy, header, iif); retVal = true; // Fall through } else { lcb (p, header, iif); return true; } } // Check if input device supports IP forwarding if (m_ipv4->IsForwarding (iif) == false) { NS_LOG_LOGIC ("Forwarding disabled for this interface"); ecb (p, header, Socket::ERROR_NOROUTETOHOST); return false; } // Next, try to find a route // If we have already delivered a packet locally (e.g. multicast) // we suppress further downstream local delivery by nulling the callback LocalDeliverCallback downstreamLcb = lcb; if (retVal == true) { downstreamLcb = MakeNullCallback<void, Ptr<const Packet>, const Ipv4Header &, uint32_t > (); } for (Ipv4RoutingProtocolList::const_iterator rprotoIter = m_routingProtocols.begin (); rprotoIter != m_routingProtocols.end (); rprotoIter++) { if ((*rprotoIter).second->RouteInput (p, header, idev, ucb, mcb, downstreamLcb, ecb)) { NS_LOG_LOGIC ("Route found to forward packet in protocol " << (*rprotoIter).second->GetInstanceTypeId ().GetName ()); return true; } } // No routing protocol has found a route. return retVal; } void Ipv4ListRouting::NotifyInterfaceUp (uint32_t interface) { NS_LOG_FUNCTION (this << interface); for (Ipv4RoutingProtocolList::const_iterator rprotoIter = m_routingProtocols.begin (); rprotoIter != m_routingProtocols.end (); rprotoIter++) { (*rprotoIter).second->NotifyInterfaceUp (interface); } } void Ipv4ListRouting::NotifyInterfaceDown (uint32_t interface) { NS_LOG_FUNCTION (this << interface); for (Ipv4RoutingProtocolList::const_iterator rprotoIter = m_routingProtocols.begin (); rprotoIter != m_routingProtocols.end (); rprotoIter++) { (*rprotoIter).second->NotifyInterfaceDown (interface); } } void Ipv4ListRouting::NotifyAddAddress (uint32_t interface, Ipv4InterfaceAddress address) { NS_LOG_FUNCTION (this << interface << address); for (Ipv4RoutingProtocolList::const_iterator rprotoIter = m_routingProtocols.begin (); rprotoIter != m_routingProtocols.end (); rprotoIter++) { (*rprotoIter).second->NotifyAddAddress (interface, address); } } void Ipv4ListRouting::NotifyRemoveAddress (uint32_t interface, Ipv4InterfaceAddress address) { NS_LOG_FUNCTION (this << interface << address); for (Ipv4RoutingProtocolList::const_iterator rprotoIter = m_routingProtocols.begin (); rprotoIter != m_routingProtocols.end (); rprotoIter++) { (*rprotoIter).second->NotifyRemoveAddress (interface, address); } } void Ipv4ListRouting::SetIpv4 (Ptr<Ipv4> ipv4) { NS_LOG_FUNCTION (this << ipv4); NS_ASSERT (m_ipv4 == 0); for (Ipv4RoutingProtocolList::const_iterator rprotoIter = m_routingProtocols.begin (); rprotoIter != m_routingProtocols.end (); rprotoIter++) { (*rprotoIter).second->SetIpv4 (ipv4); } m_ipv4 = ipv4; } void Ipv4ListRouting::AddRoutingProtocol (Ptr<Ipv4RoutingProtocol> routingProtocol, int16_t priority) { NS_LOG_FUNCTION (this << routingProtocol->GetInstanceTypeId () << priority); m_routingProtocols.push_back (std::make_pair (priority, routingProtocol)); m_routingProtocols.sort ( Compare ); if (m_ipv4 != 0) { routingProtocol->SetIpv4 (m_ipv4); } } uint32_t Ipv4ListRouting::GetNRoutingProtocols (void) const { NS_LOG_FUNCTION (this); return m_routingProtocols.size (); } Ptr<Ipv4RoutingProtocol> Ipv4ListRouting::GetRoutingProtocol (uint32_t index, int16_t& priority) const { NS_LOG_FUNCTION (index); if (index > m_routingProtocols.size ()) { NS_FATAL_ERROR ("Ipv4ListRouting::GetRoutingProtocol(): index " << index << " out of range"); } uint32_t i = 0; for (Ipv4RoutingProtocolList::const_iterator rprotoIter = m_routingProtocols.begin (); rprotoIter != m_routingProtocols.end (); rprotoIter++, i++) { if (i == index) { priority = (*rprotoIter).first; return (*rprotoIter).second; } } return 0; } bool Ipv4ListRouting::Compare (const Ipv4RoutingProtocolEntry& a, const Ipv4RoutingProtocolEntry& b) { return a.first > b.first; } } // namespace ns3
zy901002-gpsr
src/internet/model/ipv4-list-routing.cc
C++
gpl2
9,233
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2005 INRIA * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr> */ #ifndef UDP_HEADER_H #define UDP_HEADER_H #include <stdint.h> #include <string> #include "ns3/header.h" #include "ns3/ipv4-address.h" namespace ns3 { /** * \ingroup udp * \brief Packet header for UDP packets * * This class has fields corresponding to those in a network UDP header * (port numbers, payload size, checksum) as well as methods for serialization * to and deserialization from a byte buffer. */ class UdpHeader : public Header { public: /** * \brief Constructor * * Creates a null header */ UdpHeader (); ~UdpHeader (); /** * \brief Enable checksum calculation for UDP */ void EnableChecksums (void); /** * \param port the destination port for this UdpHeader */ void SetDestinationPort (uint16_t port); /** * \param port The source port for this UdpHeader */ void SetSourcePort (uint16_t port); /** * \return The source port for this UdpHeader */ uint16_t GetSourcePort (void) const; /** * \return the destination port for this UdpHeader */ uint16_t GetDestinationPort (void) const; /** * \param source the ip source to use in the underlying * ip packet. * \param destination the ip destination to use in the * underlying ip packet. * \param protocol the protocol number to use in the underlying * ip packet. * * If you want to use udp checksums, you should call this * method prior to adding the header to a packet. */ void InitializeChecksum (Ipv4Address source, Ipv4Address destination, uint8_t protocol); static TypeId GetTypeId (void); virtual TypeId GetInstanceTypeId (void) const; virtual void Print (std::ostream &os) const; virtual uint32_t GetSerializedSize (void) const; virtual void Serialize (Buffer::Iterator start) const; virtual uint32_t Deserialize (Buffer::Iterator start); /** * \brief Is the UDP checksum correct ? * \returns true if the checksum is correct, false otherwise. */ bool IsChecksumOk (void) const; private: uint16_t CalculateHeaderChecksum (uint16_t size) const; uint16_t m_sourcePort; uint16_t m_destinationPort; uint16_t m_payloadSize; Ipv4Address m_source; Ipv4Address m_destination; uint8_t m_protocol; bool m_calcChecksum; bool m_goodChecksum; }; } // namespace ns3 #endif /* UDP_HEADER */
zy901002-gpsr
src/internet/model/udp-header.h
C++
gpl2
3,196
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007-2009 Strasbourg University * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Sebastien Vincent <vincent@clarinet.u-strasbg.fr> */ #ifndef NDISC_CACHE_H #define NDISC_CACHE_H #include <stdint.h> #include <list> #include "ns3/packet.h" #include "ns3/nstime.h" #include "ns3/net-device.h" #include "ns3/ipv6-address.h" #include "ns3/ptr.h" #include "ns3/timer.h" #include "ns3/sgi-hashmap.h" namespace ns3 { class NetDevice; class Ipv6Interface; /** * \class NdiscCache * \brief IPv6 Neighbor Discovery cache. */ class NdiscCache : public Object { public: class Entry; /** * \brief Get the type ID * \return type ID */ static TypeId GetTypeId (); /** * \brief Default value for unres qlen. */ static const uint32_t DEFAULT_UNRES_QLEN = 3; /** * \brief Constructor. */ NdiscCache (); /** * \brief Destructor. */ ~NdiscCache (); /** * \brief Get the NetDevice associated with this cache. * \return NetDevice */ Ptr<NetDevice> GetDevice () const; /** * \brief Get the Ipv6Interface associated with this cache. */ Ptr<Ipv6Interface> GetInterface () const; /** * \brief Lookup in the cache. * \param dst destination address * \return the entry if found, 0 otherwise */ NdiscCache::Entry* Lookup (Ipv6Address dst); /** * \brief Add an entry. * \param to address to add * \return an new Entry */ NdiscCache::Entry* Add (Ipv6Address to); /** * \brief Delete an entry. * \param entry pointer to delete from the list. */ void Remove (NdiscCache::Entry* entry); /** * \brief Flush the cache. */ void Flush (); /** * \brief Set the max number of waiting packet. * \param unresQlen value to set */ void SetUnresQlen (uint32_t unresQlen); /** * \brief Get the max number of waiting packet. * \return max number */ uint32_t GetUnresQlen (); /** * \brief Set the device and interface. * \param device the device * \param interface the IPv6 interface */ void SetDevice (Ptr<NetDevice> device, Ptr<Ipv6Interface> interface); /** * \class Entry * \brief A record that holds information about an NdiscCache entry. */ class Entry { public: /** * \brief Constructor. * \param nd The NdiscCache this entry belongs to. */ Entry (NdiscCache* nd); /** * \brief Changes the state to this entry to INCOMPLETE. * \param p packet that wait to be sent */ void MarkIncomplete (Ptr<Packet> p); /** * \brief Changes the state to this entry to REACHABLE. * \param mac MAC address * \return the list of packet waiting */ std::list<Ptr<Packet> > MarkReachable (Address mac); /** * \brief Changes the state to this entry to PROBE. */ void MarkProbe (); /** * \brief Changes the state to this entry to STALE. * \param mac L2 address * \return the list of packet waiting */ std::list<Ptr<Packet> > MarkStale (Address mac); /** * \brief Changes the state to this entry to STALE. */ void MarkStale (); /** * \brief Changes the state to this entry to REACHABLE. */ void MarkReachable (); /** * \brief Change the state to this entry to DELAY. */ void MarkDelay (); /** * \brief Add a packet (or replace old value) in the queue. * \param p packet to add */ void AddWaitingPacket (Ptr<Packet> p); /** * \brief Clear the waiting packet list. */ void ClearWaitingPacket (); /** * \brief Is the entry STALE * \return true if the entry is in STALE state, false otherwise */ bool IsStale () const; /** * \brief Is the entry REACHABLE * \return true if the entry is in REACHABLE state, false otherwise */ bool IsReachable () const; /** * \brief Is the entry DELAY * \return true if the entry is in DELAY state, false otherwise */ bool IsDelay () const; /** * \brief Is the entry INCOMPLETE * \return true if the entry is in INCOMPLETE state, false otherwise */ bool IsIncomplete () const; /** * \brief Is the entry PROBE * \return true if the entry is in PROBE state, false otherwise */ bool IsProbe () const; /** * \brief Get the MAC address of this entry. * \return the L2 address */ Address GetMacAddress () const; /** * \brief Set the MAC address of this entry. * \param mac the MAC address to set */ void SetMacAddress (Address mac); /** * \brief If the entry is a host or a router. * \return true if the node is a router, 0 if it is a host */ bool IsRouter () const; /** * \brief Set the node type. * \param router true is a router, false means a host */ void SetRouter (bool router); /** * \brief Get the number of NS retransmit. * \return number of NS that have been retransmit */ uint8_t GetNSRetransmit () const; /** * \brief Increment NS retransmit. */ void IncNSRetransmit (); /** * \brief Reset NS retransmit (=0). */ void ResetNSRetransmit (); /** * \brief Get the time of last reachability confirmation. * \return time */ Time GetLastReachabilityConfirmation () const; /** * \brief Update the time of last reachability confirmation. */ void UpdateLastReachabilityconfirmation (); /** * \brief Start the reachable timer. */ void StartReachableTimer (); /** * \brief Stop the reachable timer. */ void StopReachableTimer (); /** * \brief Start retransmit timer. */ void StartRetransmitTimer (); /** * \brief Stop retransmit timer. */ void StopRetransmitTimer (); /** * \brief Start probe timer. */ void StartProbeTimer (); /** * \brief Stop probe timer. */ void StopProbeTimer (); /** * \brief Start delay timer. */ void StartDelayTimer (); /** * \brief Stop delay timer. */ void StopDelayTimer (); /** * \brief Function called when reachable timer timeout. */ void FunctionReachableTimeout (); /** * \brief Function called when retransmit timer timeout. * It verify that the NS retransmit has reached the max so discard the entry * otherwise it retransmit a NS. */ void FunctionRetransmitTimeout (); /** * \brief Function called when probe timer timeout. */ void FunctionProbeTimeout (); /** * \brief Function called when delay timer timeout. */ void FunctionDelayTimeout (); /** * \brief Set the IPv6 address. * \param ipv6Address IPv6 address */ void SetIpv6Address (Ipv6Address ipv6Address); private: /** * \brief The IPv6 address. */ Ipv6Address m_ipv6Address; /** * \brief The Entry state enumeration. */ enum NdiscCacheEntryState_e { INCOMPLETE, /**< No mapping between IPv6 and L2 addresses */ REACHABLE, /**< Mapping exists between IPv6 and L2 addresses */ STALE, /**< Mapping is stale */ DELAY, /**< Try to wait contact from remote host */ PROBE /**< Try to contact IPv6 address to know again its L2 address */ }; /** * \brief The state of the entry. */ NdiscCacheEntryState_e m_state; /** * \brief the NdiscCache associated. */ NdiscCache* m_ndCache; /** * \brief The MAC address. */ Address m_macAddress; /** * \brief The list of packet waiting. */ std::list<Ptr<Packet> > m_waiting; /** * \brief Type of node (router or host). */ bool m_router; /** * \brief Reachable timer (used for NUD in REACHABLE state). */ Timer m_reachableTimer; /** * \brief Retransmission timer (used for NUD in INCOMPLETE state). */ Timer m_retransTimer; /** * \brief Probe timer (used for NUD in PROBE state). */ Timer m_probeTimer; /** * \brief Delay timer (used for NUD when in DELAY state). */ Timer m_delayTimer; /** * \brief Last time we see a reachability confirmation. */ Time m_lastReachabilityConfirmation; /** * \brief Number of NS retransmission. */ uint8_t m_nsRetransmit; }; private: typedef sgi::hash_map<Ipv6Address, NdiscCache::Entry *, Ipv6AddressHash> Cache; typedef sgi::hash_map<Ipv6Address, NdiscCache::Entry *, Ipv6AddressHash>::iterator CacheI; /** * \brief Copy constructor. * \param a cache to copy */ NdiscCache (NdiscCache const &a); /** * \brief Equal operator. * \param a cache to copy */ NdiscCache& operator= (NdiscCache const &a); /** * \brief Dispose this object. */ void DoDispose (); /** * \brief The NetDevice. */ Ptr<NetDevice> m_device; /** * \brief the interface. */ Ptr<Ipv6Interface> m_interface; /** * \brief A list of Entry. */ Cache m_ndCache; /** * \brief Max number of packet stored in m_waiting. */ uint32_t m_unresQlen; }; } /* namespace ns3 */ #endif /* NDISC_CACHE_H */
zy901002-gpsr
src/internet/model/ndisc-cache.h
C++
gpl2
9,963
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007 Georgia Tech Research Corporation * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Raj Bhattacharjea <raj.b@gatech.edu> */ #ifndef TCP_HEADER_H #define TCP_HEADER_H #include <stdint.h> #include "ns3/header.h" #include "ns3/buffer.h" #include "ns3/tcp-socket-factory.h" #include "ns3/ipv4-address.h" #include "ns3/sequence-number.h" namespace ns3 { /** * \ingroup tcp * \brief Header for the Transmission Control Protocol * * This class has fields corresponding to those in a network TCP header * (port numbers, sequence and acknowledgement numbers, flags, etc) as well * as methods for serialization to and deserialization from a byte buffer. */ class TcpHeader : public Header { public: TcpHeader (); virtual ~TcpHeader (); /** * \brief Enable checksum calculation for TCP (XXX currently has no effect) */ void EnableChecksums (void); //Setters /** * \param port The source port for this TcpHeader */ void SetSourcePort (uint16_t port); /** * \param port the destination port for this TcpHeader */ void SetDestinationPort (uint16_t port); /** * \param sequenceNumber the sequence number for this TcpHeader */ void SetSequenceNumber (SequenceNumber32 sequenceNumber); /** * \param ackNumber the ACK number for this TcpHeader */ void SetAckNumber (SequenceNumber32 ackNumber); /** * \param length the length of this TcpHeader */ void SetLength (uint8_t length); /** * \param flags the flags for this TcpHeader */ void SetFlags (uint8_t flags); /** * \param windowSize the window size for this TcpHeader */ void SetWindowSize (uint16_t windowSize); /** * \param urgentPointer the urgent pointer for this TcpHeader */ void SetUrgentPointer (uint16_t urgentPointer); //Getters /** * \return The source port for this TcpHeader */ uint16_t GetSourcePort () const; /** * \return the destination port for this TcpHeader */ uint16_t GetDestinationPort () const; /** * \return the sequence number for this TcpHeader */ SequenceNumber32 GetSequenceNumber () const; /** * \return the ACK number for this TcpHeader */ SequenceNumber32 GetAckNumber () const; /** * \return the length of this TcpHeader */ uint8_t GetLength () const; /** * \return the flags for this TcpHeader */ uint8_t GetFlags () const; /** * \return the window size for this TcpHeader */ uint16_t GetWindowSize () const; /** * \return the urgent pointer for this TcpHeader */ uint16_t GetUrgentPointer () const; /** * \param source the ip source to use in the underlying * ip packet. * \param destination the ip destination to use in the * underlying ip packet. * \param protocol the protocol number to use in the underlying * ip packet. * * If you want to use tcp checksums, you should call this * method prior to adding the header to a packet. */ void InitializeChecksum (Ipv4Address source, Ipv4Address destination, uint8_t protocol); typedef enum { NONE = 0, FIN = 1, SYN = 2, RST = 4, PSH = 8, ACK = 16, URG = 32} Flags_t; static TypeId GetTypeId (void); virtual TypeId GetInstanceTypeId (void) const; virtual void Print (std::ostream &os) const; virtual uint32_t GetSerializedSize (void) const; virtual void Serialize (Buffer::Iterator start) const; virtual uint32_t Deserialize (Buffer::Iterator start); /** * \brief Is the TCP checksum correct ? * \returns true if the checksum is correct, false otherwise. */ bool IsChecksumOk (void) const; private: uint16_t CalculateHeaderChecksum (uint16_t size) const; uint16_t m_sourcePort; uint16_t m_destinationPort; SequenceNumber32 m_sequenceNumber; SequenceNumber32 m_ackNumber; uint8_t m_length; // really a uint4_t uint8_t m_flags; // really a uint6_t uint16_t m_windowSize; uint16_t m_urgentPointer; Ipv4Address m_source; Ipv4Address m_destination; uint8_t m_protocol; uint16_t m_initialChecksum; bool m_calcChecksum; bool m_goodChecksum; }; } // namespace ns3 #endif /* TCP_HEADER */
zy901002-gpsr
src/internet/model/tcp-header.h
C++
gpl2
4,883
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef NSC_TCP_SOCKET_FACTORY_IMPL_H #define NSC_TCP_SOCKET_FACTORY_IMPL_H #include "ns3/tcp-socket-factory.h" #include "ns3/ptr.h" namespace ns3 { class NscTcpL4Protocol; /** * \ingroup internet * \defgroup nsctcp NscTcp * * An alternate implementation of TCP for ns-3 is provided by the * Network Simulation Cradle (NSC) project. NSC is a separately linked * library that provides ported TCP stacks from popular operating systems * such as Linux and FreeBSD. Glue code such as the ns-3 NSC code * allows users to delegate Internet stack processing to the logic * from these operating systems. This allows a user to reproduce * with high fidelity the behavior of a real TCP stack. */ /** * \ingroup nsctcp * * \brief socket factory implementation for creating instances of NSC TCP */ class NscTcpSocketFactoryImpl : public TcpSocketFactory { public: NscTcpSocketFactoryImpl (); virtual ~NscTcpSocketFactoryImpl (); void SetTcp (Ptr<NscTcpL4Protocol> tcp); virtual Ptr<Socket> CreateSocket (void); protected: virtual void DoDispose (void); private: Ptr<NscTcpL4Protocol> m_tcp; }; } // namespace ns3 #endif /* NSC_TCP_SOCKET_FACTORY_IMPL_H */
zy901002-gpsr
src/internet/model/nsc-tcp-socket-factory-impl.h
C++
gpl2
1,904
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2010 Adrian Sai-wah Tam * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Adrian Sai-wah Tam <adrian.sw.tam@gmail.com> */ #define NS_LOG_APPEND_CONTEXT \ if (m_node) { std::clog << Simulator::Now ().GetSeconds () << " [node " << m_node->GetId () << "] "; } #include "tcp-newreno.h" #include "ns3/log.h" #include "ns3/trace-source-accessor.h" #include "ns3/simulator.h" #include "ns3/abort.h" #include "ns3/node.h" NS_LOG_COMPONENT_DEFINE ("TcpNewReno"); namespace ns3 { NS_OBJECT_ENSURE_REGISTERED (TcpNewReno); TypeId TcpNewReno::GetTypeId (void) { static TypeId tid = TypeId ("ns3::TcpNewReno") .SetParent<TcpSocketBase> () .AddConstructor<TcpNewReno> () .AddTraceSource ("CongestionWindow", "The TCP connection's congestion window", MakeTraceSourceAccessor (&TcpNewReno::m_cWnd)) ; return tid; } TcpNewReno::TcpNewReno (void) : m_inFastRec (false) { NS_LOG_FUNCTION (this); } TcpNewReno::TcpNewReno (const TcpNewReno& sock) : TcpSocketBase (sock), m_cWnd (sock.m_cWnd), m_ssThresh (sock.m_ssThresh), m_initialCWnd (sock.m_initialCWnd), m_inFastRec (false) { NS_LOG_FUNCTION (this); NS_LOG_LOGIC ("Invoked the copy constructor"); } TcpNewReno::~TcpNewReno (void) { } /** We initialize m_cWnd from this function, after attributes initialized */ int TcpNewReno::Listen (void) { NS_LOG_FUNCTION (this); InitializeCwnd (); return TcpSocketBase::Listen (); } /** We initialize m_cWnd from this function, after attributes initialized */ int TcpNewReno::Connect (const Address & address) { NS_LOG_FUNCTION (this << address); InitializeCwnd (); return TcpSocketBase::Connect (address); } /** Limit the size of in-flight data by cwnd and receiver's rxwin */ uint32_t TcpNewReno::Window (void) { NS_LOG_FUNCTION (this); return std::min (m_rWnd.Get (), m_cWnd.Get ()); } Ptr<TcpSocketBase> TcpNewReno::Fork (void) { return CopyObject<TcpNewReno> (this); } /** New ACK (up to seqnum seq) received. Increase cwnd and call TcpSocketBase::NewAck() */ void TcpNewReno::NewAck (const SequenceNumber32& seq) { NS_LOG_FUNCTION (this << seq); NS_LOG_LOGIC ("TcpNewReno receieved ACK for seq " << seq << " cwnd " << m_cWnd << " ssthresh " << m_ssThresh); // Check for exit condition of fast recovery if (m_inFastRec && seq < m_recover) { // Partial ACK, partial window deflation (RFC2582 sec.3 bullet #5 paragraph 3) m_cWnd += m_segmentSize; // increase cwnd NS_LOG_INFO ("Partial ACK in fast recovery: cwnd set to " << m_cWnd); TcpSocketBase::NewAck (seq); // update m_nextTxSequence and send new data if allowed by window DoRetransmit (); // Assume the next seq is lost. Retransmit lost packet return; } else if (m_inFastRec && seq >= m_recover) { // Full ACK (RFC2582 sec.3 bullet #5 paragraph 2, option 1) m_cWnd = std::min (m_ssThresh, BytesInFlight () + m_segmentSize); m_inFastRec = false; NS_LOG_INFO ("Received full ACK. Leaving fast recovery with cwnd set to " << m_cWnd); } // Increase of cwnd based on current phase (slow start or congestion avoidance) if (m_cWnd < m_ssThresh) { // Slow start mode, add one segSize to cWnd. Default m_ssThresh is 65535. (RFC2001, sec.1) m_cWnd += m_segmentSize; NS_LOG_INFO ("In SlowStart, updated to cwnd " << m_cWnd << " ssthresh " << m_ssThresh); } else { // Congestion avoidance mode, increase by (segSize*segSize)/cwnd. (RFC2581, sec.3.1) // To increase cwnd for one segSize per RTT, it should be (ackBytes*segSize)/cwnd double adder = static_cast<double> (m_segmentSize * m_segmentSize) / m_cWnd.Get (); adder = std::max (1.0, adder); m_cWnd += static_cast<uint32_t> (adder); NS_LOG_INFO ("In CongAvoid, updated to cwnd " << m_cWnd << " ssthresh " << m_ssThresh); } // Complete newAck processing TcpSocketBase::NewAck (seq); } /** Cut cwnd and enter fast recovery mode upon triple dupack */ void TcpNewReno::DupAck (const TcpHeader& t, uint32_t count) { NS_LOG_FUNCTION (this << count); if (count == 3 && !m_inFastRec) { // triple duplicate ack triggers fast retransmit (RFC2582 sec.3 bullet #1) m_ssThresh = std::max (2 * m_segmentSize, BytesInFlight () / 2); m_cWnd = m_ssThresh + 3 * m_segmentSize; m_recover = m_highTxMark; m_inFastRec = true; NS_LOG_INFO ("Triple dupack. Enter fast recovery mode. Reset cwnd to " << m_cWnd << ", ssthresh to " << m_ssThresh << " at fast recovery seqnum " << m_recover); DoRetransmit (); } else if (m_inFastRec) { // Increase cwnd for every additional dupack (RFC2582, sec.3 bullet #3) m_cWnd += m_segmentSize; NS_LOG_INFO ("Dupack in fast recovery mode. Increase cwnd to " << m_cWnd); SendPendingData (m_connected); }; } /** Retransmit timeout */ void TcpNewReno::Retransmit (void) { NS_LOG_FUNCTION (this); NS_LOG_LOGIC (this << " ReTxTimeout Expired at time " << Simulator::Now ().GetSeconds ()); m_inFastRec = false; // If erroneous timeout in closed/timed-wait state, just return if (m_state == CLOSED || m_state == TIME_WAIT) return; // If all data are received, just return if (m_txBuffer.HeadSequence () >= m_nextTxSequence) return; // According to RFC2581 sec.3.1, upon RTO, ssthresh is set to half of flight // size and cwnd is set to 1*MSS, then the lost packet is retransmitted and // TCP back to slow start m_ssThresh = std::max (2 * m_segmentSize, BytesInFlight () / 2); m_cWnd = m_segmentSize; m_nextTxSequence = m_txBuffer.HeadSequence (); // Restart from highest Ack NS_LOG_INFO ("RTO. Reset cwnd to " << m_cWnd << ", ssthresh to " << m_ssThresh << ", restart from seqnum " << m_nextTxSequence); m_rtt->IncreaseMultiplier (); // Double the next RTO DoRetransmit (); // Retransmit the packet } void TcpNewReno::SetSegSize (uint32_t size) { NS_ABORT_MSG_UNLESS (m_state == CLOSED, "TcpNewReno::SetSegSize() cannot change segment size after connection started."); m_segmentSize = size; } void TcpNewReno::SetSSThresh (uint32_t threshold) { m_ssThresh = threshold; } uint32_t TcpNewReno::GetSSThresh (void) const { return m_ssThresh; } void TcpNewReno::SetInitialCwnd (uint32_t cwnd) { NS_ABORT_MSG_UNLESS (m_state == CLOSED, "TcpNewReno::SetInitialCwnd() cannot change initial cwnd after connection started."); m_initialCWnd = cwnd; } uint32_t TcpNewReno::GetInitialCwnd (void) const { return m_initialCWnd; } void TcpNewReno::InitializeCwnd (void) { /* * Initialize congestion window, default to 1 MSS (RFC2001, sec.1) and must * not be larger than 2 MSS (RFC2581, sec.3.1). Both m_initiaCWnd and * m_segmentSize are set by the attribute system in ns3::TcpSocket. */ m_cWnd = m_initialCWnd * m_segmentSize; } } // namespace ns3
zy901002-gpsr
src/internet/model/tcp-newreno.cc
C++
gpl2
7,633
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2008-2009 Strasbourg University * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: David Gross <gdavid.devel@gmail.com> */ #ifndef IPV6_OPTION_HEADER_H #define IPV6_OPTION_HEADER_H #include <ostream> #include "ns3/header.h" namespace ns3 { /** * \class Ipv6OptionHeader * \brief Header for IPv6 Option. */ class Ipv6OptionHeader : public Header { public: /** * \struct Alignment * \brief represents the alignment requirements of an option header * * Represented as factor*n+offset (eg. 8n+2) See RFC 2460. * No alignment is represented as 1n+0. */ struct Alignment { uint8_t factor; /**< Factor */ uint8_t offset; /**< Offset */ }; /** * \brief Get the type identificator. * \return type identificator */ static TypeId GetTypeId (); /** * \brief Get the instance type ID. * \return instance type ID */ virtual TypeId GetInstanceTypeId () const; /** * \brief Constructor. */ Ipv6OptionHeader (); /** * \brief Destructor. */ virtual ~Ipv6OptionHeader (); /** * \brief Set the type of the option. * \param type the type of the option */ void SetType (uint8_t type); /** * \brief Get the type of the option. * \return the type of the option */ uint8_t GetType () const; /** * \brief Set the option length. * \param length the option length */ void SetLength (uint8_t length); /** * \brief Get the option length. * \return the option length */ uint8_t GetLength () const; /** * \brief Print some informations about the packet. * \param os output stream * \return info about this packet */ virtual void Print (std::ostream &os) const; /** * \brief Get the serialized size of the packet. * \return size */ virtual uint32_t GetSerializedSize () const; /** * \brief Serialize the packet. * \param start Buffer iterator */ virtual void Serialize (Buffer::Iterator start) const; /** * \brief Deserialize the packet. * \param start Buffer iterator * \return size of the packet */ virtual uint32_t Deserialize (Buffer::Iterator start); /** * \brief Get the Alignment requirement of this option header * \return The required alignment * * Subclasses should only implement this method, if special alignment is * required. Default is no alignment (1n+0). */ virtual Alignment GetAlignment () const; private: /** * \brief The type of the option. */ uint8_t m_type; /** * \brief The option length. */ uint8_t m_length; /** * \brief The anonymous data of this option */ Buffer m_data; }; /** * \class Ipv6OptionPad1Header * \brief Header of IPv6 Option Pad1 */ class Ipv6OptionPad1Header : public Ipv6OptionHeader { public: /** * \brief Get the type identificator. * \return type identificator */ static TypeId GetTypeId (); /** * \brief Get the instance type ID. * \return instance type ID */ virtual TypeId GetInstanceTypeId () const; /** * \brief Constructor. */ Ipv6OptionPad1Header (); /** * \brief Destructor. */ virtual ~Ipv6OptionPad1Header (); /** * \brief Print some informations about the packet. * \param os output stream * \return info about this packet */ virtual void Print (std::ostream &os) const; /** * \brief Get the serialized size of the packet. * \return size */ virtual uint32_t GetSerializedSize () const; /** * \brief Serialize the packet. * \param start Buffer iterator */ virtual void Serialize (Buffer::Iterator start) const; /** * \brief Deserialize the packet. * \param start Buffer iterator * \return size of the packet */ virtual uint32_t Deserialize (Buffer::Iterator start); }; /** * \class Ipv6OptionPadnHeader * \brief Header of IPv6 Option Padn */ class Ipv6OptionPadnHeader : public Ipv6OptionHeader { public: /** * \brief Get the type identificator. * \return type identificator */ static TypeId GetTypeId (); /** * \brief Get the instance type ID. * \return instance type ID */ virtual TypeId GetInstanceTypeId () const; /** * \brief Constructor. * \param pad Number of bytes to pad (>=2) */ Ipv6OptionPadnHeader (uint32_t pad = 2); /** * \brief Destructor. */ virtual ~Ipv6OptionPadnHeader (); /** * \brief Print some informations about the packet. * \param os output stream * \return info about this packet */ virtual void Print (std::ostream &os) const; /** * \brief Get the serialized size of the packet. * \return size */ virtual uint32_t GetSerializedSize () const; /** * \brief Serialize the packet. * \param start Buffer iterator */ virtual void Serialize (Buffer::Iterator start) const; /** * \brief Deserialize the packet. * \param start Buffer iterator * \return size of the packet */ virtual uint32_t Deserialize (Buffer::Iterator start); }; /** * \class Ipv6OptionJumbogramHeader * \brief Header of IPv6 Option Jumbogram */ class Ipv6OptionJumbogramHeader : public Ipv6OptionHeader { public: /** * \brief Get the type identificator. * \return type identificator */ static TypeId GetTypeId (); /** * \brief Get the instance type ID. * \return instance type ID */ virtual TypeId GetInstanceTypeId () const; /** * \brief Constructor. */ Ipv6OptionJumbogramHeader (); /** * \brief Destructor. */ virtual ~Ipv6OptionJumbogramHeader (); /** * \brief Set the data length. * \param dataLength the data length */ void SetDataLength (uint32_t dataLength); /** * \brief Get the data length. * \return the data length */ uint32_t GetDataLength () const; /** * \brief Print some informations about the packet. * \param os output stream * \return info about this packet */ virtual void Print (std::ostream &os) const; /** * \brief Get the serialized size of the packet. * \return size */ virtual uint32_t GetSerializedSize () const; /** * \brief Serialize the packet. * \param start Buffer iterator */ virtual void Serialize (Buffer::Iterator start) const; /** * \brief Deserialize the packet. * \param start Buffer iterator * \return size of the packet */ virtual uint32_t Deserialize (Buffer::Iterator start); /** * \brief Get the Alignment requirement of this option header * \return The required alignment */ virtual Alignment GetAlignment () const; private: /** * \brief The data length. */ uint32_t m_dataLength; }; /** * \class Ipv6OptionRouterAlertHeader * \brief Header of IPv6 Option Router Alert */ class Ipv6OptionRouterAlertHeader : public Ipv6OptionHeader { public: /** * \brief Get the type identificator. * \return type identificator */ static TypeId GetTypeId (); /** * \brief Get the instance type ID. * \return instance type ID */ virtual TypeId GetInstanceTypeId () const; /** * \brief Constructor. */ Ipv6OptionRouterAlertHeader (); /** * \brief Destructor. */ virtual ~Ipv6OptionRouterAlertHeader (); /** * \brief Set the field "value". */ void SetValue (uint16_t value); /** * \brief Get the field "value". * \return the field "value" */ uint16_t GetValue () const; /** * \brief Print some informations about the packet. * \param os output stream * \return info about this packet */ virtual void Print (std::ostream &os) const; /** * \brief Get the serialized size of the packet. * \return size */ virtual uint32_t GetSerializedSize () const; /** * \brief Serialize the packet. * \param start Buffer iterator */ virtual void Serialize (Buffer::Iterator start) const; /** * \brief Deserialize the packet. * \param start Buffer iterator * \return size of the packet */ virtual uint32_t Deserialize (Buffer::Iterator start); /** * \brief Get the Alignment requirement of this option header * \return The required alignment */ virtual Alignment GetAlignment () const; private: /** * \brief The value. */ uint16_t m_value; }; } // namespace ns3 #endif /* IPV6_OPTION_HEADER_H */
zy901002-gpsr
src/internet/model/ipv6-option-header.h
C++
gpl2
8,959
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2005 INRIA * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr> */ #ifndef ARP_HEADER_H #define ARP_HEADER_H #include "ns3/header.h" #include "ns3/address.h" #include "ns3/ipv4-address.h" #include <string> namespace ns3 { /** * \ingroup arp * \brief The packet header for an ARP packet */ class ArpHeader : public Header { public: void SetRequest (Address sourceHardwareAddress, Ipv4Address sourceProtocolAddress, Address destinationHardwareAddress, Ipv4Address destinationProtocolAddress); void SetReply (Address sourceHardwareAddress, Ipv4Address sourceProtocolAddress, Address destinationHardwareAddress, Ipv4Address destinationProtocolAddress); bool IsRequest (void) const; bool IsReply (void) const; Address GetSourceHardwareAddress (void); Address GetDestinationHardwareAddress (void); Ipv4Address GetSourceIpv4Address (void); Ipv4Address GetDestinationIpv4Address (void); static TypeId GetTypeId (void); virtual TypeId GetInstanceTypeId (void) const; virtual void Print (std::ostream &os) const; virtual uint32_t GetSerializedSize (void) const; virtual void Serialize (Buffer::Iterator start) const; virtual uint32_t Deserialize (Buffer::Iterator start); enum ArpType_e { ARP_TYPE_REQUEST = 1, ARP_TYPE_REPLY = 2 }; uint16_t m_type; Address m_macSource; Address m_macDest; Ipv4Address m_ipv4Source; Ipv4Address m_ipv4Dest; }; } // namespace ns3 #endif /* ARP_HEADER_H */
zy901002-gpsr
src/internet/model/arp-header.h
C++
gpl2
2,296
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007-2009 Strasbourg University * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Sebastien Vincent <vincent@clarinet.u-strasbg.fr> */ #ifndef IPV6_L4_PROTOCOL_H #define IPV6_L4_PROTOCOL_H #include "ns3/object.h" #include "ns3/ipv6-header.h" namespace ns3 { class Packet; class Ipv6Address; class Ipv6Interface; /** * \class Ipv6L4Protocol * \brief IPv6 L4 protocol abstract class */ class Ipv6L4Protocol : public Object { public: /** * \enum RxStatus_e * \brief Status of receive. */ enum RxStatus_e { RX_OK, /**< Receive OK */ RX_CSUM_FAILED, /**< Checksum of layer 4 protocol failed */ RX_ENDPOINT_UNREACH /**< Destination unreachable */ }; /** * \brief Get the type identifier. * \return type identifier */ static TypeId GetTypeId (void); /** * \brief Destructor. */ virtual ~Ipv6L4Protocol (); /** * \brief Get the protocol number. * \return protocol number */ virtual int GetProtocolNumber () const = 0; /** * \brief Receive method. * * Called from lower-level layers to send the packet up * in the stack. * \param p packet to forward up * \param src source address of packet received * \param dst address of packet received * \param incomingInterface the Ipv6Interface on which the packet arrived * \return status (OK, destination unreachable or checksum failed) */ virtual enum RxStatus_e Receive (Ptr<Packet> p, Ipv6Address const &src, Ipv6Address const &dst, Ptr<Ipv6Interface> incomingInterface) = 0; /** * \brief ICMPv6 receive method. * \param icmpSource the source address of the ICMPv6 message * \param icmpTtl the ttl of the ICMPv6 message * \param icmpType the 'type' field of the ICMPv6 message * \param icmpCode the 'code' field of the ICMPv6 message * \param icmpInfo extra information dependent on the ICMPv6 message * generated by Icmpv6L4Protocol * \param payloadSource the source address of the packet which triggered * the ICMPv6 message * \param payloadDestination the destination address of the packet which * triggered the ICMPv6 message. * \param payload the first 8 bytes of the UDP header of the packet * which triggered the ICMPv6 message. */ virtual void ReceiveIcmp (Ipv6Address icmpSource, uint8_t icmpTtl, uint8_t icmpType, uint8_t icmpCode, uint32_t icmpInfo, Ipv6Address payloadSource, Ipv6Address payloadDestination, const uint8_t* payload); }; } /* namespace ns3 */ #endif /* IPV6_L4_PROTOCOL_H */
zy901002-gpsr
src/internet/model/ipv6-l4-protocol.h
C++
gpl2
3,387
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ // // Copyright (c) 2006 Georgia Tech Research Corporation // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation; // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Author: Rajib Bhattacharjea<raj.b@gatech.edu> // // Ported from: // Georgia Tech Network Simulator - Round Trip Time Estimation Class // George F. Riley. Georgia Tech, Spring 2002 // Implements several variations of round trip time estimators #include <iostream> #include "rtt-estimator.h" #include "ns3/simulator.h" #include "ns3/double.h" namespace ns3 { NS_OBJECT_ENSURE_REGISTERED (RttEstimator); //RttEstimator iid TypeId RttEstimator::GetTypeId (void) { static TypeId tid = TypeId ("ns3::RttEstimator") .SetParent<Object> () .AddAttribute ("MaxMultiplier", "XXX", DoubleValue (64.0), MakeDoubleAccessor (&RttEstimator::m_maxMultiplier), MakeDoubleChecker<double> ()) .AddAttribute ("InitialEstimation", "XXX", TimeValue (Seconds (1.0)), MakeTimeAccessor (&RttEstimator::SetEstimate, &RttEstimator::GetEstimate), MakeTimeChecker ()) .AddAttribute ("MinRTO", "Minimum retransmit timeout value", TimeValue (Seconds (0.2)), MakeTimeAccessor (&RttEstimator::SetMinRto, &RttEstimator::GetMinRto), MakeTimeChecker ()) ; return tid; } void RttEstimator::SetMinRto (Time minRto) { minrto = minRto; } Time RttEstimator::GetMinRto (void) const { return Time (minrto); } void RttEstimator::SetEstimate (Time estimate) { est = estimate; } Time RttEstimator::GetEstimate (void) const { return Time (est); } //RttHistory methods RttHistory::RttHistory (SequenceNumber32 s, uint32_t c, Time t) : seq (s), count (c), time (t), retx (false) { } RttHistory::RttHistory (const RttHistory& h) : seq (h.seq), count (h.count), time (h.time), retx (h.retx) { } // Base class methods RttEstimator::RttEstimator () : next (1), history (), nSamples (0), multiplier (1.0) { //note next=1 everywhere since first segment will have sequence 1 } RttEstimator::RttEstimator(const RttEstimator& c) : Object (c), next (c.next), history (c.history), m_maxMultiplier (c.m_maxMultiplier), est (c.est), minrto (c.minrto), nSamples (c.nSamples), multiplier (c.multiplier) { } RttEstimator::~RttEstimator () { } void RttEstimator::SentSeq (SequenceNumber32 s, uint32_t c) { // Note that a particular sequence has been sent if (s == next) { // This is the next expected one, just log at end history.push_back (RttHistory (s, c, Simulator::Now () )); next = s + SequenceNumber32 (c); // Update next expected } else { // This is a retransmit, find in list and mark as re-tx for (RttHistory_t::iterator i = history.begin (); i != history.end (); ++i) { if ((s >= i->seq) && (s < (i->seq + SequenceNumber32 (i->count)))) { // Found it i->retx = true; // One final test..be sure this re-tx does not extend "next" if ((s + SequenceNumber32 (c)) > next) { next = s + SequenceNumber32 (c); i->count = ((s + SequenceNumber32 (c)) - i->seq); // And update count in hist } break; } } } } Time RttEstimator::AckSeq (SequenceNumber32 a) { // An ack has been received, calculate rtt and log this measurement // Note we use a linear search (O(n)) for this since for the common // case the ack'ed packet will be at the head of the list Time m = Seconds (0.0); if (history.size () == 0) return (m); // No pending history, just exit RttHistory& h = history.front (); if (!h.retx && a >= (h.seq + SequenceNumber32 (h.count))) { // Ok to use this sample m = Simulator::Now () - h.time; // Elapsed time Measurement (m); // Log the measurement ResetMultiplier (); // Reset multiplier on valid measurement } // Now delete all ack history with seq <= ack while(history.size () > 0) { RttHistory& h = history.front (); if ((h.seq + SequenceNumber32 (h.count)) > a) break; // Done removing history.pop_front (); // Remove } return m; } void RttEstimator::ClearSent () { // Clear all history entries next = 1; history.clear (); } void RttEstimator::IncreaseMultiplier () { multiplier = std::min (multiplier * 2.0, m_maxMultiplier); } void RttEstimator::ResetMultiplier () { multiplier = 1.0; } void RttEstimator::Reset () { // Reset to initial state next = 1; est = 1; // XXX: we should go back to the 'initial value' here. Need to add support in Object for this. history.clear (); // Remove all info from the history nSamples = 0; ResetMultiplier (); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Mean-Deviation Estimator NS_OBJECT_ENSURE_REGISTERED (RttMeanDeviation); TypeId RttMeanDeviation::GetTypeId (void) { static TypeId tid = TypeId ("ns3::RttMeanDeviation") .SetParent<RttEstimator> () .AddConstructor<RttMeanDeviation> () .AddAttribute ("Gain", "XXX", DoubleValue (0.1), MakeDoubleAccessor (&RttMeanDeviation::gain), MakeDoubleChecker<double> ()) ; return tid; } RttMeanDeviation::RttMeanDeviation() : variance (0) { } RttMeanDeviation::RttMeanDeviation (const RttMeanDeviation& c) : RttEstimator (c), gain (c.gain), variance (c.variance) { } void RttMeanDeviation::Measurement (Time m) { if (nSamples) { // Not first int64x64_t err = m - est; est = est + gain * err; // estimated rtt variance = variance + gain * (Abs (err) - variance); // variance of rtt } else { // First sample est = m; // Set estimate to current //variance = sample / 2; // And variance to current / 2 variance = m; // try this } nSamples++; } Time RttMeanDeviation::RetransmitTimeout () { // If not enough samples, justjust return 2 times estimate //if (nSamples < 2) return est * 2; int64x64_t retval; if (variance < est / 4.0) { retval = est * 2 * multiplier; // At least twice current est } else { retval = (est + 4 * variance) * multiplier; // As suggested by Jacobson } retval = Max (retval, minrto); return Time (retval); } Ptr<RttEstimator> RttMeanDeviation::Copy () const { return CopyObject<RttMeanDeviation> (this); } void RttMeanDeviation::Reset () { // Reset to initial state variance = 0; RttEstimator::Reset (); } } //namepsace ns3
zy901002-gpsr
src/internet/model/rtt-estimator.cc
C++
gpl2
7,610
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007-2009 Strasbourg University * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: David Gross <gdavid.devel@gmail.com> */ #include <sstream> #include "ns3/node.h" #include "ns3/ptr.h" #include "ns3/object-vector.h" #include "ipv6-option-demux.h" #include "ipv6-option.h" namespace ns3 { NS_OBJECT_ENSURE_REGISTERED (Ipv6OptionDemux); TypeId Ipv6OptionDemux::GetTypeId () { static TypeId tid = TypeId ("ns3::Ipv6OptionDemux") .SetParent<Object> () .AddAttribute ("Options", "The set of IPv6 options registered with this demux.", ObjectVectorValue (), MakeObjectVectorAccessor (&Ipv6OptionDemux::m_options), MakeObjectVectorChecker<Ipv6Option> ()) ; return tid; } Ipv6OptionDemux::Ipv6OptionDemux () { } Ipv6OptionDemux::~Ipv6OptionDemux () { } void Ipv6OptionDemux::DoDispose () { for (Ipv6OptionList_t::iterator it = m_options.begin (); it != m_options.end (); it++) { (*it)->Dispose (); *it = 0; } m_options.clear (); m_node = 0; Object::DoDispose (); } void Ipv6OptionDemux::SetNode (Ptr<Node> node) { m_node = node; } void Ipv6OptionDemux::Insert (Ptr<Ipv6Option> option) { m_options.push_back (option); } Ptr<Ipv6Option> Ipv6OptionDemux::GetOption (int optionNumber) { for (Ipv6OptionList_t::iterator i = m_options.begin (); i != m_options.end (); ++i) { if ((*i)->GetOptionNumber () == optionNumber) { return *i; } } return 0; } void Ipv6OptionDemux::Remove (Ptr<Ipv6Option> option) { m_options.remove (option); } } /* namespace ns3 */
zy901002-gpsr
src/internet/model/ipv6-option-demux.cc
C++
gpl2
2,305
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2006 INRIA * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr> */ #include "ns3/packet.h" #include "ns3/log.h" #include "ns3/node.h" #include "ns3/net-device.h" #include "ns3/object-vector.h" #include "ns3/trace-source-accessor.h" #include "ipv4-l3-protocol.h" #include "arp-l3-protocol.h" #include "arp-header.h" #include "arp-cache.h" #include "ipv4-interface.h" NS_LOG_COMPONENT_DEFINE ("ArpL3Protocol"); namespace ns3 { const uint16_t ArpL3Protocol::PROT_NUMBER = 0x0806; NS_OBJECT_ENSURE_REGISTERED (ArpL3Protocol); TypeId ArpL3Protocol::GetTypeId (void) { static TypeId tid = TypeId ("ns3::ArpL3Protocol") .SetParent<Object> () .AddConstructor<ArpL3Protocol> () .AddAttribute ("CacheList", "The list of ARP caches", ObjectVectorValue (), MakeObjectVectorAccessor (&ArpL3Protocol::m_cacheList), MakeObjectVectorChecker<ArpCache> ()) .AddTraceSource ("Drop", "Packet dropped because not enough room in pending queue for a specific cache entry.", MakeTraceSourceAccessor (&ArpL3Protocol::m_dropTrace)) ; return tid; } ArpL3Protocol::ArpL3Protocol () { NS_LOG_FUNCTION (this); } ArpL3Protocol::~ArpL3Protocol () { NS_LOG_FUNCTION (this); } void ArpL3Protocol::SetNode (Ptr<Node> node) { NS_LOG_FUNCTION (this); m_node = node; } /* * This method is called by AddAgregate and completes the aggregation * by setting the node in the ipv4 stack */ void ArpL3Protocol::NotifyNewAggregate () { if (m_node == 0) { Ptr<Node>node = this->GetObject<Node> (); //verify that it's a valid node and that //the node was not set before if (node != 0) { this->SetNode (node); } } Object::NotifyNewAggregate (); } void ArpL3Protocol::DoDispose (void) { NS_LOG_FUNCTION (this); for (CacheList::iterator i = m_cacheList.begin (); i != m_cacheList.end (); ++i) { Ptr<ArpCache> cache = *i; cache->Dispose (); } m_cacheList.clear (); m_node = 0; Object::DoDispose (); } Ptr<ArpCache> ArpL3Protocol::CreateCache (Ptr<NetDevice> device, Ptr<Ipv4Interface> interface) { NS_LOG_FUNCTION (this << device << interface); Ptr<Ipv4L3Protocol> ipv4 = m_node->GetObject<Ipv4L3Protocol> (); Ptr<ArpCache> cache = CreateObject<ArpCache> (); cache->SetDevice (device, interface); NS_ASSERT (device->IsBroadcast ()); device->AddLinkChangeCallback (MakeCallback (&ArpCache::Flush, cache)); cache->SetArpRequestCallback (MakeCallback (&ArpL3Protocol::SendArpRequest, this)); m_cacheList.push_back (cache); return cache; } Ptr<ArpCache> ArpL3Protocol::FindCache (Ptr<NetDevice> device) { NS_LOG_FUNCTION (this << device); for (CacheList::const_iterator i = m_cacheList.begin (); i != m_cacheList.end (); i++) { if ((*i)->GetDevice () == device) { return *i; } } NS_ASSERT (false); // quiet compiler return 0; } void ArpL3Protocol::Receive (Ptr<NetDevice> device, Ptr<const Packet> p, uint16_t protocol, const Address &from, const Address &to, NetDevice::PacketType packetType) { NS_LOG_FUNCTION (this << device << p->GetSize () << protocol << from << to << packetType); Ptr<Packet> packet = p->Copy (); NS_LOG_LOGIC ("ARP: received packet of size "<< packet->GetSize ()); Ptr<ArpCache> cache = FindCache (device); // // If we're connected to a real world network, then some of the fields sizes // in an ARP packet can vary in ways not seen in simulations. We need to be // able to detect ARP packets with headers we don't recongnize and not process // them instead of crashing. The ArpHeader will return 0 if it can't deal // with the received header. // ArpHeader arp; uint32_t size = packet->RemoveHeader (arp); if (size == 0) { NS_LOG_LOGIC ("ARP: Cannot remove ARP header"); return; } NS_LOG_LOGIC ("ARP: received "<< (arp.IsRequest () ? "request" : "reply") << " node="<<m_node->GetId ()<<", got request from " << arp.GetSourceIpv4Address () << " for address " << arp.GetDestinationIpv4Address () << "; we have addresses: "); for (uint32_t i = 0; i < cache->GetInterface ()->GetNAddresses (); i++) { NS_LOG_LOGIC (cache->GetInterface ()->GetAddress (i).GetLocal () << ", "); } /** * Note: we do not update the ARP cache when we receive an ARP request * from an unknown node. See bug #107 */ bool found = false; for (uint32_t i = 0; i < cache->GetInterface ()->GetNAddresses (); i++) { if (arp.IsRequest () && arp.GetDestinationIpv4Address () == cache->GetInterface ()->GetAddress (i).GetLocal ()) { found = true; NS_LOG_LOGIC ("node="<<m_node->GetId () <<", got request from " << arp.GetSourceIpv4Address () << " -- send reply"); SendArpReply (cache, arp.GetDestinationIpv4Address (), arp.GetSourceIpv4Address (), arp.GetSourceHardwareAddress ()); break; } else if (arp.IsReply () && arp.GetDestinationIpv4Address ().IsEqual (cache->GetInterface ()->GetAddress (i).GetLocal ()) && arp.GetDestinationHardwareAddress () == device->GetAddress ()) { found = true; Ipv4Address from = arp.GetSourceIpv4Address (); ArpCache::Entry *entry = cache->Lookup (from); if (entry != 0) { if (entry->IsWaitReply ()) { NS_LOG_LOGIC ("node="<< m_node->GetId () << ", got reply from " << arp.GetSourceIpv4Address () << " for waiting entry -- flush"); Address from_mac = arp.GetSourceHardwareAddress (); entry->MarkAlive (from_mac); Ptr<Packet> pending = entry->DequeuePending (); while (pending != 0) { cache->GetInterface ()->Send (pending, arp.GetSourceIpv4Address ()); pending = entry->DequeuePending (); } } else { // ignore this reply which might well be an attempt // at poisening my arp cache. NS_LOG_LOGIC ("node="<<m_node->GetId ()<<", got reply from " << arp.GetSourceIpv4Address () << " for non-waiting entry -- drop"); m_dropTrace (packet); } } else { NS_LOG_LOGIC ("node="<<m_node->GetId ()<<", got reply for unknown entry -- drop"); m_dropTrace (packet); } break; } } if (found == false) { NS_LOG_LOGIC ("node="<<m_node->GetId ()<<", got request from " << arp.GetSourceIpv4Address () << " for unknown address " << arp.GetDestinationIpv4Address () << " -- drop"); } } bool ArpL3Protocol::Lookup (Ptr<Packet> packet, Ipv4Address destination, Ptr<NetDevice> device, Ptr<ArpCache> cache, Address *hardwareDestination) { NS_LOG_FUNCTION (this << packet << destination << device << cache); ArpCache::Entry *entry = cache->Lookup (destination); if (entry != 0) { if (entry->IsExpired ()) { if (entry->IsDead ()) { NS_LOG_LOGIC ("node="<<m_node->GetId ()<< ", dead entry for " << destination << " expired -- send arp request"); entry->MarkWaitReply (packet); SendArpRequest (cache, destination); } else if (entry->IsAlive ()) { NS_LOG_LOGIC ("node="<<m_node->GetId ()<< ", alive entry for " << destination << " expired -- send arp request"); entry->MarkWaitReply (packet); SendArpRequest (cache, destination); } else if (entry->IsWaitReply ()) { NS_FATAL_ERROR ("Test for possibly unreachable code-- please file a bug report, with a test case, if this is ever hit"); } } else { if (entry->IsDead ()) { NS_LOG_LOGIC ("node="<<m_node->GetId ()<< ", dead entry for " << destination << " valid -- drop"); m_dropTrace (packet); } else if (entry->IsAlive ()) { NS_LOG_LOGIC ("node="<<m_node->GetId ()<< ", alive entry for " << destination << " valid -- send"); *hardwareDestination = entry->GetMacAddress (); return true; } else if (entry->IsWaitReply ()) { NS_LOG_LOGIC ("node="<<m_node->GetId ()<< ", wait reply for " << destination << " valid -- drop previous"); if (!entry->UpdateWaitReply (packet)) { m_dropTrace (packet); } } } } else { // This is our first attempt to transmit data to this destination. NS_LOG_LOGIC ("node="<<m_node->GetId ()<< ", no entry for " << destination << " -- send arp request"); entry = cache->Add (destination); entry->MarkWaitReply (packet); SendArpRequest (cache, destination); } return false; } void ArpL3Protocol::SendArpRequest (Ptr<const ArpCache> cache, Ipv4Address to) { NS_LOG_FUNCTION (this << cache << to); ArpHeader arp; // need to pick a source address; use routing implementation to select Ptr<Ipv4L3Protocol> ipv4 = m_node->GetObject<Ipv4L3Protocol> (); Ptr<NetDevice> device = cache->GetDevice (); NS_ASSERT (device != 0); Ipv4Header header; header.SetDestination (to); Ptr<Packet> packet = Create<Packet> (); Ipv4Address source = ipv4->SelectSourceAddress (device, to, Ipv4InterfaceAddress::GLOBAL); NS_LOG_LOGIC ("ARP: sending request from node "<<m_node->GetId ()<< " || src: " << device->GetAddress () << " / " << source << " || dst: " << device->GetBroadcast () << " / " << to); arp.SetRequest (device->GetAddress (), source, device->GetBroadcast (), to); packet->AddHeader (arp); cache->GetDevice ()->Send (packet, device->GetBroadcast (), PROT_NUMBER); } void ArpL3Protocol::SendArpReply (Ptr<const ArpCache> cache, Ipv4Address myIp, Ipv4Address toIp, Address toMac) { NS_LOG_FUNCTION (this << cache << toIp << toMac); ArpHeader arp; NS_LOG_LOGIC ("ARP: sending reply from node "<<m_node->GetId ()<< "|| src: " << cache->GetDevice ()->GetAddress () << " / " << myIp << " || dst: " << toMac << " / " << toIp); arp.SetReply (cache->GetDevice ()->GetAddress (), myIp, toMac, toIp); Ptr<Packet> packet = Create<Packet> (); packet->AddHeader (arp); cache->GetDevice ()->Send (packet, toMac, PROT_NUMBER); } } // namespace ns3
zy901002-gpsr
src/internet/model/arp-l3-protocol.cc
C++
gpl2
12,094
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright 2008 University of Washington * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ /** * \ingroup internet * \defgroup globalrouting Global Routing * * \section model Model * * ns-3 global routing performs pre-simulation static route computation * on a layer-3 Ipv4 topology. The user API from the script level is * fairly minimal; once a topology has been constructed and addresses * assigned, the user may call ns3::GlobalRouteManager::PopulateRoutingTables() * and the simulator will initialize the routing database and set up * static unicast forwarding tables for each node. * * The model assumes that all nodes on an ns-3 channel are reachable to * one another, regardless of whether the nodes can use the channel * successfully (in the case of wireless). Therefore, this model * should typically be used only on wired topologies. Layer-2 bridge * devices are supported. API does not yet exist to control the subset * of a topology to which this global static routing is applied. * * If the topology changes during the simulation, by default, routing * will not adjust. There are two ways to make it adjust. * - Set the attribute Ipv4GlobalRouting::RespondToInterfaceEvents to true * - Manually call the sequence of GlobalRouteManager methods to delte global * routes, build global routing database, and initialize routes. * There is a helper method that encapsulates this * (Ipv4GlobalRoutingHelper::RecomputeRoutingTables()) * * \section api API and Usage * * Users must include ns3/global-route-manager.h header file. After the * IPv4 topology has been built and addresses assigned, users call * ns3::GlobalRouteManager::PopulateRoutingTables (), prior to the * ns3::Simulator::Run() call. * * There are two attributes of Ipv4GlobalRouting that govern behavior. * - Ipv4GlobalRouting::RandomEcmpRouting * - Ipv4GlobalRouting::RespondToInterfaceEvents * * \section impl Implementation * * A singleton object, ns3::GlobalRouteManager, builds a global routing * database of information about the topology, and executes a Dijkstra * Shortest Path First (SPF) algorithm on the topology for each node, and * stores the computed routes in each node's IPv4 forwarding table by * making use of the routing API in class ns3::Ipv4. * * The nodes that export data are those that have had an ns3::GlobalRouter * object aggregated to them. The ns3::GlobalRouter can be thought of * as a per-node agent that exports topology information to the * ns3::GlobalRouteManager. When it comes time to build the global * routing database, the list of nodes is iterated and each node with * an ns3::GlobalRouter object is asked to export routing information * concerning the links to which it is attached. * * The format of the data exported conforms to the OSPFv2 standard * (http://www.ietf.org/rfc/rfc2328.txt). In particular, the * information is exported in the form of ns3::GlobalLSA objects that * semantically match the Link State Advertisements of OSPF. * * By using a standard data format for reporting topology, existing * OSPF route computation code can be reused, and that is what is done * by the ns3::GlobalRouteManager. The main computation functions are * ported from the quagga routing suite (http://www.quagga.net). * */
zy901002-gpsr
src/internet/model/global-routing.h
C
gpl2
4,004
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2006 Georgia Tech Research Corporation * 2007 INRIA * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Authors: George F. Riley<riley@ece.gatech.edu> * Mathieu Lacage <mathieu.lacage@sophia.inria.fr> */ #ifndef UDP_SOCKET_H #define UDP_SOCKET_H #include "ns3/socket.h" #include "ns3/traced-callback.h" #include "ns3/callback.h" #include "ns3/ptr.h" #include "ns3/object.h" namespace ns3 { class Node; class Packet; /** * \ingroup socket * * \brief (abstract) base class of all UdpSockets * * This class exists solely for hosting UdpSocket attributes that can * be reused across different implementations, and for declaring * UDP-specific multicast API. */ class UdpSocket : public Socket { public: static TypeId GetTypeId (void); UdpSocket (void); virtual ~UdpSocket (void); /** * \brief Corresponds to socket option MCAST_JOIN_GROUP * * \param interface interface number, or 0 * \param groupAddress multicast group address * \returns on success, zero is returned. On error, -1 is returned, * and errno is set appropriately * * Enable reception of multicast datagrams for this socket on the * interface number specified. If zero is specified as * the interface, then a single local interface is chosen by * system. In the future, this function will generate trigger IGMP * joins as necessary when IGMP is implemented, but for now, this * just enables multicast datagram reception in the system if not already * enabled for this interface/groupAddress combination. * * \attention IGMP is not yet implemented in ns-3 * * This function may be called repeatedly on a given socket but each * join must be for a different multicast address, or for the same * multicast address but on a different interface from previous joins. * This enables host multihoming, and the ability to join the same * group on different interfaces. */ virtual int MulticastJoinGroup (uint32_t interface, const Address &groupAddress) = 0; /** * \brief Corresponds to socket option MCAST_LEAVE_GROUP * * \param interface interface number, or 0 * \param groupAddress multicast group address * \returns on success, zero is returned. On error, -1 is returned, * and errno is set appropriately * * Disable reception of multicast datagrams for this socket on the * interface number specified. If zero is specified as * the interfaceIndex, then a single local interface is chosen by * system. In the future, this function will generate trigger IGMP * leaves as necessary when IGMP is implemented, but for now, this * just disables multicast datagram reception in the system if this * socket is the last for this interface/groupAddress combination. * * \attention IGMP is not yet implemented in ns-3 */ virtual int MulticastLeaveGroup (uint32_t interface, const Address &groupAddress) = 0; private: // Indirect the attribute setting and getting through private virtual methods virtual void SetRcvBufSize (uint32_t size) = 0; virtual uint32_t GetRcvBufSize (void) const = 0; virtual void SetIpTtl (uint8_t ipTtl) = 0; virtual uint8_t GetIpTtl (void) const = 0; virtual void SetIpMulticastTtl (uint8_t ipTtl) = 0; virtual uint8_t GetIpMulticastTtl (void) const = 0; virtual void SetIpMulticastIf (int32_t ipIf) = 0; virtual int32_t GetIpMulticastIf (void) const = 0; virtual void SetIpMulticastLoop (bool loop) = 0; virtual bool GetIpMulticastLoop (void) const = 0; virtual void SetMtuDiscover (bool discover) = 0; virtual bool GetMtuDiscover (void) const = 0; }; } // namespace ns3 #endif /* UDP_SOCKET_H */
zy901002-gpsr
src/internet/model/udp-socket.h
C++
gpl2
4,394
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007-2009 Strasbourg University * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Sebastien Vincent <vincent@clarinet.u-strasbg.fr> */ #include "ipv6-end-point-demux.h" #include "ipv6-end-point.h" #include "ns3/log.h" namespace ns3 { NS_LOG_COMPONENT_DEFINE ("Ipv6EndPointDemux"); Ipv6EndPointDemux::Ipv6EndPointDemux () : m_ephemeral (49152) { NS_LOG_FUNCTION_NOARGS (); } Ipv6EndPointDemux::~Ipv6EndPointDemux () { NS_LOG_FUNCTION_NOARGS (); for (EndPointsI i = m_endPoints.begin (); i != m_endPoints.end (); i++) { Ipv6EndPoint *endPoint = *i; delete endPoint; } m_endPoints.clear (); } bool Ipv6EndPointDemux::LookupPortLocal (uint16_t port) { NS_LOG_FUNCTION (this << port); for (EndPointsI i = m_endPoints.begin (); i != m_endPoints.end (); i++) { if ((*i)->GetLocalPort () == port) { return true; } } return false; } bool Ipv6EndPointDemux::LookupLocal (Ipv6Address addr, uint16_t port) { NS_LOG_FUNCTION (this << addr << port); for (EndPointsI i = m_endPoints.begin (); i != m_endPoints.end (); i++) { if ((*i)->GetLocalPort () == port && (*i)->GetLocalAddress () == addr) { return true; } } return false; } Ipv6EndPoint* Ipv6EndPointDemux::Allocate () { NS_LOG_FUNCTION_NOARGS (); uint16_t port = AllocateEphemeralPort (); if (port == 0) { NS_LOG_WARN ("Ephemeral port allocation failed."); return 0; } Ipv6EndPoint *endPoint = new Ipv6EndPoint (Ipv6Address::GetAny (), port); m_endPoints.push_back (endPoint); NS_LOG_DEBUG ("Now have >>" << m_endPoints.size () << "<< endpoints."); return endPoint; } Ipv6EndPoint* Ipv6EndPointDemux::Allocate (Ipv6Address address) { NS_LOG_FUNCTION (this << address); uint16_t port = AllocateEphemeralPort (); if (port == 0) { NS_LOG_WARN ("Ephemeral port allocation failed."); return 0; } Ipv6EndPoint *endPoint = new Ipv6EndPoint (address, port); m_endPoints.push_back (endPoint); NS_LOG_DEBUG ("Now have >>" << m_endPoints.size () << "<< endpoints."); return endPoint; } Ipv6EndPoint* Ipv6EndPointDemux::Allocate (uint16_t port) { NS_LOG_FUNCTION (this << port); return Allocate (Ipv6Address::GetAny (), port); } Ipv6EndPoint* Ipv6EndPointDemux::Allocate (Ipv6Address address, uint16_t port) { NS_LOG_FUNCTION (this << address << port); if (LookupLocal (address, port)) { NS_LOG_WARN ("Duplicate address/port; failing."); return 0; } Ipv6EndPoint *endPoint = new Ipv6EndPoint (address, port); m_endPoints.push_back (endPoint); NS_LOG_DEBUG ("Now have >>" << m_endPoints.size () << "<< endpoints."); return endPoint; } Ipv6EndPoint* Ipv6EndPointDemux::Allocate (Ipv6Address localAddress, uint16_t localPort, Ipv6Address peerAddress, uint16_t peerPort) { NS_LOG_FUNCTION (this << localAddress << localPort << peerAddress << peerPort); for (EndPointsI i = m_endPoints.begin (); i != m_endPoints.end (); i++) { if ((*i)->GetLocalPort () == localPort && (*i)->GetLocalAddress () == localAddress && (*i)->GetPeerPort () == peerPort && (*i)->GetPeerAddress () == peerAddress) { NS_LOG_WARN ("No way we can allocate this end-point."); /* no way we can allocate this end-point. */ return 0; } } Ipv6EndPoint *endPoint = new Ipv6EndPoint (localAddress, localPort); endPoint->SetPeer (peerAddress, peerPort); m_endPoints.push_back (endPoint); NS_LOG_DEBUG ("Now have >>" << m_endPoints.size () << "<< endpoints."); return endPoint; } void Ipv6EndPointDemux::DeAllocate (Ipv6EndPoint *endPoint) { NS_LOG_FUNCTION_NOARGS (); for (EndPointsI i = m_endPoints.begin (); i != m_endPoints.end (); i++) { if (*i == endPoint) { delete endPoint; m_endPoints.erase (i); break; } } } /* * If we have an exact match, we return it. * Otherwise, if we find a generic match, we return it. * Otherwise, we return 0. */ Ipv6EndPointDemux::EndPoints Ipv6EndPointDemux::Lookup (Ipv6Address daddr, uint16_t dport, Ipv6Address saddr, uint16_t sport, Ptr<Ipv6Interface> incomingInterface) { NS_LOG_FUNCTION (this << daddr << dport << saddr << sport << incomingInterface); EndPoints retval1; /* Matches exact on local port, wildcards on others */ EndPoints retval2; /* Matches exact on local port/adder, wildcards on others */ EndPoints retval3; /* Matches all but local address */ EndPoints retval4; /* Exact match on all 4 */ NS_LOG_DEBUG ("Looking up endpoint for destination address " << daddr); for (EndPointsI i = m_endPoints.begin (); i != m_endPoints.end (); i++) { Ipv6EndPoint* endP = *i; NS_LOG_DEBUG ("Looking at endpoint dport=" << endP->GetLocalPort () << " daddr=" << endP->GetLocalAddress () << " sport=" << endP->GetPeerPort () << " saddr=" << endP->GetPeerAddress ()); if (endP->GetLocalPort () != dport) { NS_LOG_LOGIC ("Skipping endpoint " << &endP << " because endpoint dport " << endP->GetLocalPort () << " does not match packet dport " << dport); continue; } /* Ipv6Address incomingInterfaceAddr = incomingInterface->GetAddress (); */ NS_LOG_DEBUG ("dest addr " << daddr); bool localAddressMatchesWildCard = endP->GetLocalAddress () == Ipv6Address::GetAny (); bool localAddressMatchesExact = endP->GetLocalAddress () == daddr; bool localAddressMatchesAllRouters = endP->GetLocalAddress () == Ipv6Address::GetAllRoutersMulticast (); /* if no match here, keep looking */ if (!(localAddressMatchesExact || localAddressMatchesWildCard)) continue; bool remotePeerMatchesExact = endP->GetPeerPort () == sport; bool remotePeerMatchesWildCard = endP->GetPeerPort () == 0; bool remoteAddressMatchesExact = endP->GetPeerAddress () == saddr; bool remoteAddressMatchesWildCard = endP->GetPeerAddress () == Ipv6Address::GetAny (); /* If remote does not match either with exact or wildcard,i skip this one */ if (!(remotePeerMatchesExact || remotePeerMatchesWildCard)) continue; if (!(remoteAddressMatchesExact || remoteAddressMatchesWildCard)) continue; /* Now figure out which return list to add this one to */ if (localAddressMatchesWildCard && remotePeerMatchesWildCard && remoteAddressMatchesWildCard) { /* Only local port matches exactly */ retval1.push_back (endP); } if ((localAddressMatchesExact || (localAddressMatchesAllRouters))&& remotePeerMatchesWildCard && remoteAddressMatchesWildCard) { /* Only local port and local address matches exactly */ retval2.push_back (endP); } if (localAddressMatchesWildCard && remotePeerMatchesExact && remoteAddressMatchesExact) { /* All but local address */ retval3.push_back (endP); } if (localAddressMatchesExact && remotePeerMatchesExact && remoteAddressMatchesExact) { /* All 4 match */ retval4.push_back (endP); } } /* Here we find the most exact match */ if (!retval4.empty ()) return retval4; if (!retval3.empty ()) return retval3; if (!retval2.empty ()) return retval2; return retval1; /* might be empty if no matches */ } Ipv6EndPoint* Ipv6EndPointDemux::SimpleLookup (Ipv6Address dst, uint16_t dport, Ipv6Address src, uint16_t sport) { uint32_t genericity = 3; Ipv6EndPoint *generic = 0; for (EndPointsI i = m_endPoints.begin (); i != m_endPoints.end (); i++) { uint32_t tmp = 0; if ((*i)->GetLocalPort () != dport) { continue; } if ((*i)->GetLocalAddress () == dst && (*i)->GetPeerPort () == sport && (*i)->GetPeerAddress () == src) { /* this is an exact match. */ return *i; } if ((*i)->GetLocalAddress () == Ipv6Address::GetAny ()) { tmp++; } if ((*i)->GetPeerAddress () == Ipv6Address::GetAny ()) { tmp++; } if (tmp < genericity) { generic = (*i); genericity = tmp; } } return generic; } uint16_t Ipv6EndPointDemux::AllocateEphemeralPort () { NS_LOG_FUNCTION_NOARGS (); uint16_t port = m_ephemeral; do { port++; if (port == 65535) { port = 49152; } if (!LookupPortLocal (port)) { return port; } } while (port != m_ephemeral); return 0; } Ipv6EndPointDemux::EndPoints Ipv6EndPointDemux::GetEndPoints () const { return m_endPoints; } } /* namespace ns3 */
zy901002-gpsr
src/internet/model/ipv6-end-point-demux.cc
C++
gpl2
9,962
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2010 Hajime Tazaki * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Authors: Hajime Tazaki <tazaki@sfc.wide.ad.jp> */ #include <stdint.h> #include "ns3/ipv4-address.h" #include "ipv4-packet-info-tag.h" namespace ns3 { Ipv4PacketInfoTag::Ipv4PacketInfoTag () : m_addr (Ipv4Address ()), m_spec_dst (Ipv4Address ()), m_ifindex (0), m_ttl (0) { } void Ipv4PacketInfoTag::SetAddress (Ipv4Address addr) { m_addr = addr; } Ipv4Address Ipv4PacketInfoTag::GetAddress (void) const { return m_addr; } void Ipv4PacketInfoTag::SetLocalAddress (Ipv4Address addr) { m_spec_dst = addr; } Ipv4Address Ipv4PacketInfoTag::GetLocalAddress (void) const { return m_spec_dst; } void Ipv4PacketInfoTag::SetRecvIf (uint32_t ifindex) { m_ifindex = ifindex; } uint32_t Ipv4PacketInfoTag::GetRecvIf (void) const { return m_ifindex; } void Ipv4PacketInfoTag::SetTtl (uint8_t ttl) { m_ttl = ttl; } uint8_t Ipv4PacketInfoTag::GetTtl (void) const { return m_ttl; } TypeId Ipv4PacketInfoTag::GetTypeId (void) { static TypeId tid = TypeId ("ns3::Ipv4PacketInfoTag") .SetParent<Tag> () .AddConstructor<Ipv4PacketInfoTag> () ; return tid; } TypeId Ipv4PacketInfoTag::GetInstanceTypeId (void) const { return GetTypeId (); } uint32_t Ipv4PacketInfoTag::GetSerializedSize (void) const { return 4 + 4 + sizeof (uint32_t) + sizeof (uint8_t); } void Ipv4PacketInfoTag::Serialize (TagBuffer i) const { uint8_t buf[4]; m_addr.Serialize (buf); i.Write (buf, 4); m_spec_dst.Serialize (buf); i.Write (buf, 4); i.WriteU32 (m_ifindex); i.WriteU8 (m_ttl); } void Ipv4PacketInfoTag::Deserialize (TagBuffer i) { uint8_t buf[4]; i.Read (buf, 4); m_addr.Deserialize (buf); i.Read (buf, 4); m_spec_dst.Deserialize (buf); m_ifindex = i.ReadU32 (); m_ttl = i.ReadU8 (); } void Ipv4PacketInfoTag::Print (std::ostream &os) const { os << "Ipv4 PKTINFO [DestAddr: " << m_addr; os << ", Local Address:" << m_spec_dst; os << ", RecvIf:" << (uint32_t) m_ifindex; os << ", TTL:" << (uint32_t) m_ttl; os << "] "; } } // namespace ns3
zy901002-gpsr
src/internet/model/ipv4-packet-info-tag.cc
C++
gpl2
2,797
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007 INRIA * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr> */ /* taken from src/node/ipv4.h and adapted to IPv6 */ #ifndef IPV6_H #define IPV6_H #include <stdint.h> #include "ns3/object.h" #include "ns3/socket.h" #include "ns3/callback.h" #include "ns3/ipv6-address.h" #include "ipv6-interface-address.h" namespace ns3 { class Node; class NetDevice; class Packet; class Ipv6RoutingProtocol; /** * \ingroup internet * \defgroup ipv6 Ipv6 */ /** * \ingroup ipv6 * \brief Access to the IPv6 forwarding table, interfaces, and configuration * * This class defines the API to manipulate the following aspects of * the IPv6 implementation: * -# set/get an Ipv6RoutingProtocol * -# register a NetDevice for use by the IPv6 layer (basically, to * create IPv6-related state such as addressing and neighbor cache that * is associated with a NetDevice) * -# manipulate the status of the NetDevice from the IPv6 perspective, * such as marking it as Up or Down, * -# adding, deleting, and getting addresses associated to the IPv6 * interfaces. * -# exporting IPv6 configuration attributes * * Each NetDevice has conceptually a single IPv6 interface associated * with it (the corresponding structure in the Linux IPv6 implementation * is struct in_device). Each interface may have one or more IPv6 * addresses associated with it. Each IPv6 address may have different * subnet mask, scope, etc., so all of this per-address information * is stored in an Ipv6InterfaceAddress class (the corresponding * structure in Linux is struct in6_ifaddr) * * IPv6 attributes such as whether IP forwarding is enabled and disabled * are also stored in this class * * TO DO: Add API to allow access to the IPv6 neighbor table * * \see Ipv6RoutingProtocol * \see Ipv6InterfaceAddress */ class Ipv6 : public Object { public: static TypeId GetTypeId (void); /** * \brief Constructor. */ Ipv6 (); /** * \brief Destructor. */ virtual ~Ipv6 (); /** * \brief Register a new routing protocol to be used by this IPv6 stack * * This call will replace any routing protocol that has been previously * registered. If you want to add multiple routing protocols, you must * add them to a Ipv6ListRoutingProtocol directly. * * \param routingProtocol smart pointer to Ipv6RoutingProtocol object */ virtual void SetRoutingProtocol (Ptr<Ipv6RoutingProtocol> routingProtocol) = 0; /** * \brief Get the routing protocol to be used by this IPv6 stack * * \returns smart pointer to Ipv6RoutingProtocol object, or null pointer if none */ virtual Ptr<Ipv6RoutingProtocol> GetRoutingProtocol (void) const = 0; /** * \brief Add a NetDevice interface. * * Once a device has been added, it can never be removed: if you want * to disable it, you can invoke Ipv6::SetDown which will * make sure that it is never used during packet forwarding. * \param device device to add to the list of IPv6 interfaces * which can be used as output interfaces during packet forwarding. * \returns the index of the IPv6 interface added. */ virtual uint32_t AddInterface (Ptr<NetDevice> device) = 0; /** * \brief Get number of interfaces. * \returns the number of interfaces added by the user. */ virtual uint32_t GetNInterfaces (void) const = 0; /** * \brief Return the interface number of the interface that has been * assigned the specified IP address. * * \param address The IP address being searched for * \returns The interface number of the IPv6 interface with the given * address or -1 if not found. * * Each IP interface has one or more IP addresses associated with it. * This method searches the list of interfaces for one that holds a * particular address. This call takes an IP address as a parameter and * returns the interface number of the first interface that has been assigned * that address, or -1 if not found. There must be an exact match. */ virtual int32_t GetInterfaceForAddress (Ipv6Address address) const = 0; /** * \brief Return the interface number of first interface found that * has an IPv6 address within the prefix specified by the input * address and mask parameters * * \param address The IP address assigned to the interface of interest. * \param mask The IP prefix to use in the mask * \returns The interface number of the IPv6 interface with the given * address or -1 if not found. * * Each IP interface has one or more IP addresses associated with it. * This method searches the list of interfaces for the first one found * that holds an address that is included within the prefix * formed by the input address and mask parameters. The value -1 is * returned if no match is found. */ virtual int32_t GetInterfaceForPrefix (Ipv6Address address, Ipv6Prefix mask) const = 0; /** * \brief Get the NetDevice of the specified interface number. * \param interface The interface number of an IPv6 interface. * \returns The NetDevice associated with the IPv6 interface number. */ virtual Ptr<NetDevice> GetNetDevice (uint32_t interface) = 0; /** * \brief Get the interface index of the specified NetDevice. * \param device The NetDevice for an Ipv6Interface * \returns The interface number of an IPv6 interface or -1 if not found. */ virtual int32_t GetInterfaceForDevice (Ptr<const NetDevice> device) const = 0; /** * \brief Add an address on the specified IPv6 interface. * \param interface Interface number of an IPv6 interface * \param address Ipv6InterfaceAddress address to associate with the underlying IPv6 interface * \returns true if the operation succeeded */ virtual bool AddAddress (uint32_t interface, Ipv6InterfaceAddress address) = 0; /** * \brief Get number of addresses on specified IPv6 interface. * \param interface Interface number of an IPv6 interface * \returns the number of Ipv6InterfaceAddress entries for the interface. */ virtual uint32_t GetNAddresses (uint32_t interface) const = 0; /** * \brief Get IPv6 address on specified IPv6 interface. * * Because addresses can be removed, the addressIndex is not guaranteed * to be static across calls to this method. * * \param interface Interface number of an IPv6 interface * \param addressIndex index of Ipv6InterfaceAddress * \returns the Ipv6InterfaceAddress associated to the interface and addressIndex */ virtual Ipv6InterfaceAddress GetAddress (uint32_t interface, uint32_t addressIndex) const = 0; /** * \brief Remove an address on specified IPv6 interface. * * Remove the address at addressIndex on named interface. The addressIndex * for all higher indices will decrement by one after this method is called; * so, for example, to remove 5 addresses from an interface i, one could * call RemoveAddress (i, 0); 5 times. * * \param interface Interface number of an IPv6 interface * \param addressIndex index of Ipv6InterfaceAddress to remove * \returns true if the operation succeeded */ virtual bool RemoveAddress (uint32_t interface, uint32_t addressIndex) = 0; /** * \brief Set metric on specified Ipv6 interface. * * \param interface The interface number of an IPv6 interface * \param metric routing metric (cost) associated to the underlying * IPv6 interface */ virtual void SetMetric (uint32_t interface, uint16_t metric) = 0; /** * \brief Get metric for the specified IPv6 interface. * * \param interface The interface number of an IPv6 interface * \returns routing metric (cost) associated to the underlying * IPv6 interface */ virtual uint16_t GetMetric (uint32_t interface) const = 0; /** * \brief Get MTU for the specified IPv6 interface. * \param interface Interface number of IPv6 interface * \returns the Maximum Transmission Unit (in bytes) associated * to the underlying IPv6 interface */ virtual uint16_t GetMtu (uint32_t interface) const = 0; /** * \brief If the specified interface index is in "up" state. * \param interface Interface number of IPv6 interface * \returns true if the underlying interface is in the "up" state, * false otherwise. */ virtual bool IsUp (uint32_t interface) const = 0; /** * \brief Set the interface into the "up" state. * * In this state, it is considered valid during IPv6 forwarding. * \param interface Interface number of IPv6 interface */ virtual void SetUp (uint32_t interface) = 0; /** * \brief Set the interface into the "down" state. * * In this state, it is ignored during IPv6 forwarding. * \param interface Interface number of IPv6 interface */ virtual void SetDown (uint32_t interface) = 0; /** * \brief If the specified IPv6 interface has forwarding enabled. * \param interface Interface number of IPv6 interface * \returns true if IPv6 forwarding enabled for input datagrams on this device */ virtual bool IsForwarding (uint32_t interface) const = 0; /** * \brief Set forwarding on specified IPv6 interface. * \param interface Interface number of IPv6 interface * \param val Value to set the forwarding flag * * If set to true, IPv6 forwarding is enabled for input datagrams on this device */ virtual void SetForwarding (uint32_t interface, bool val) = 0; /** * \brief Register the IPv6 Extensions. */ virtual void RegisterExtensions () = 0; /** * \brief Register the IPv6 Options. */ virtual void RegisterOptions () = 0; /** * \brief Any interface magic number. */ static const uint32_t IF_ANY = 0xffffffff; private: // Indirect the IPv6 attributes through private pure virtual methods /** * \brief Set IPv6 forwarding state. * \param forward IPv6 forwarding enabled or not */ virtual void SetIpForward (bool forward) = 0; /** * \brief Get IPv6 forwarding state. * \return forwarding state (enabled or not) */ virtual bool GetIpForward (void) const = 0; }; } // namespace ns3 #endif /* IPV6_H */
zy901002-gpsr
src/internet/model/ipv6.h
C++
gpl2
11,009
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr> */ #include "ns3/string.h" #include "nsc-sysctl.h" #include "sim_interface.h" namespace ns3 { class NscStackStringAccessor : public AttributeAccessor { public: NscStackStringAccessor (std::string name) : m_name (name) {} virtual bool Set (ObjectBase * object, const AttributeValue &val) const; virtual bool Get (const ObjectBase * object, AttributeValue &val) const; virtual bool HasGetter (void) const; virtual bool HasSetter (void) const; private: std::string m_name; }; bool NscStackStringAccessor::HasGetter (void) const { return true; } bool NscStackStringAccessor::HasSetter (void) const { return true; } bool NscStackStringAccessor::Set (ObjectBase * object, const AttributeValue & val) const { const StringValue *value = dynamic_cast<const StringValue *> (&val); if (value == 0) { return false; } Ns3NscStack *obj = dynamic_cast<Ns3NscStack *> (object); if (obj == 0) { return false; } obj->Set (m_name, value->Get ()); return true; } bool NscStackStringAccessor::Get (const ObjectBase * object, AttributeValue &val) const { StringValue *value = dynamic_cast<StringValue *> (&val); if (value == 0) { return false; } const Ns3NscStack *obj = dynamic_cast<const Ns3NscStack *> (object); if (obj == 0) { return false; } value->Set (obj->Get (m_name)); return true; } TypeId Ns3NscStack::GetInstanceTypeId (void) const { if (m_stack == 0) { // if we have no stack, we are a normal NscStack without any attributes. return GetTypeId (); } std::string name = "ns3::Ns3NscStack<"; name += m_stack->get_name (); name += ">"; TypeId tid; if (TypeId::LookupByNameFailSafe (name, &tid)) { // if the relevant TypeId has already been registered, no need to do it again. return tid; } else { // Now, we register a new TypeId for this stack which will look // like a subclass of the Ns3NscStack. The class Ns3NscStack is effectively // mutating into a subclass of itself from the point of view of the TypeId // system _here_ tid = TypeId (name.c_str ()); tid.SetParent<Ns3NscStack> (); char buf[256]; for (int i=0; m_stack->sysctl_getnum (i, buf, sizeof(buf)) > 0; i++) { char value[256]; if (m_stack->sysctl_get (buf, value, sizeof(value)) > 0) { tid.AddAttribute (buf, "Help text", StringValue (value), Create<NscStackStringAccessor> (buf), MakeStringChecker ()); } } return tid; } } std::string Ns3NscStack::Get (std::string name) const { char buf[512]; if (m_stack->sysctl_get (name.c_str (), buf, sizeof(buf)) <= 0) { // name.c_str () is not a valid sysctl name, or internal NSC error (eg. error converting value) return NULL; } return std::string (buf); } void Ns3NscStack::Set (std::string name, std::string value) { int ret = m_stack->sysctl_set (name.c_str (), value.c_str ()); if (ret < 0) { NS_FATAL_ERROR ("setting " << name << " to " << value << "failed (retval " << ret << ")"); } } NS_OBJECT_ENSURE_REGISTERED (Ns3NscStack); TypeId Ns3NscStack::Ns3NscStack::GetTypeId (void) { static TypeId tid = TypeId ("ns3::Ns3NscStack") .SetParent<Object> () ; return tid; } } // namespace ns3
zy901002-gpsr
src/internet/model/nsc-sysctl.cc
C++
gpl2
4,216
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2009 University of Washington * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* taken from src/node/ipv4-routing-protocol.h and adapted to IPv6 */ #ifndef IPV6_ROUTING_PROTOCOL_H #define IPV6_ROUTING_PROTOCOL_H #include "ns3/packet.h" #include "ns3/callback.h" #include "ns3/object.h" #include "ns3/socket.h" #include "ipv6-header.h" #include "ipv6-interface-address.h" #include "ipv6.h" namespace ns3 { class Ipv6MulticastRoute; class Ipv6Route; class NetDevice; /** * \ingroup internet * \defgroup ipv6Routing Ipv6RoutingProtocol */ /** * \ingroup ipv6Routing * \brief Abstract base class for Ipv6 routing protocols. * * Defines two virtual functions for packet routing and forwarding. The first, * RouteOutput (), is used for locally originated packets, and the second, * RouteInput (), is used for forwarding and/or delivering received packets. * Also defines the signatures of four callbacks used in RouteInput (). */ class Ipv6RoutingProtocol : public Object { public: static TypeId GetTypeId (void); typedef Callback<void, Ptr<Ipv6Route>, Ptr<const Packet>, const Ipv6Header &> UnicastForwardCallback; typedef Callback<void, Ptr<Ipv6MulticastRoute>, Ptr<const Packet>, const Ipv6Header &> MulticastForwardCallback; typedef Callback<void, Ptr<const Packet>, const Ipv6Header &, uint32_t > LocalDeliverCallback; typedef Callback<void, Ptr<const Packet>, const Ipv6Header &, Socket::SocketErrno > ErrorCallback; /** * \brief Query routing cache for an existing route, for an outbound packet * * This lookup is used by transport protocols. It does not cause any * packet to be forwarded, and is synchronous. Can be used for * multicast or unicast. The Linux equivalent is ip_route_output () * * \param p packet to be routed. Note that this method may modify the packet. * Callers may also pass in a null pointer. * \param header input parameter (used to form key to search for the route) * \param oif Output interface device. May be zero, or may be bound via * socket options to a particular output interface. * \param sockerr Output parameter; socket errno * * \returns a code that indicates what happened in the lookup */ virtual Ptr<Ipv6Route> RouteOutput (Ptr<Packet> p, const Ipv6Header &header, Ptr<NetDevice> oif, Socket::SocketErrno &sockerr) = 0; /** * \brief Route an input packet (to be forwarded or locally delivered) * * This lookup is used in the forwarding process. The packet is * handed over to the Ipv6RoutingProtocol, and will get forwarded onward * by one of the callbacks. The Linux equivalent is ip_route_input (). * There are four valid outcomes, and a matching callbacks to handle each. * * \param p received packet * \param header input parameter used to form a search key for a route * \param idev Pointer to ingress network device * \param ucb Callback for the case in which the packet is to be forwarded * as unicast * \param mcb Callback for the case in which the packet is to be forwarded * as multicast * \param lcb Callback for the case in which the packet is to be locally * delivered * \param ecb Callback to call if there is an error in forwarding * \returns true if the Ipv6RoutingProtocol takes responsibility for * forwarding or delivering the packet, false otherwise */ virtual bool RouteInput (Ptr<const Packet> p, const Ipv6Header &header, Ptr<const NetDevice> idev, UnicastForwardCallback ucb, MulticastForwardCallback mcb, LocalDeliverCallback lcb, ErrorCallback ecb) = 0; /** * \brief Notify when specified interface goes UP. * * Protocols are expected to implement this method to be notified of the state change of * an interface in a node. * \param interface the index of the interface we are being notified about */ virtual void NotifyInterfaceUp (uint32_t interface) = 0; /** * \brief Notify when specified interface goes DOWN. * * Protocols are expected to implement this method to be notified of the state change of * an interface in a node. * \param interface the index of the interface we are being notified about */ virtual void NotifyInterfaceDown (uint32_t interface) = 0; /** * \brief Notify when specified interface add an address. * * Protocols are expected to implement this method to be notified whenever * a new address is added to an interface. Typically used to add a 'network route' on an * interface. Can be invoked on an up or down interface. * \param interface the index of the interface we are being notified about * \param address a new address being added to an interface */ virtual void NotifyAddAddress (uint32_t interface, Ipv6InterfaceAddress address) = 0; /** * \brief Notify when specified interface add an address. * * Protocols are expected to implement this method to be notified whenever * a new address is removed from an interface. Typically used to remove the 'network route' of an * interface. Can be invoked on an up or down interface. * \param interface the index of the interface we are being notified about * \param address a new address being added to an interface */ virtual void NotifyRemoveAddress (uint32_t interface, Ipv6InterfaceAddress address) = 0; /** * \brief Notify a new route. * * Typically this is used to add another route from IPv6 stack (i.e. ICMPv6 * redirect case, ...). * \param dst destination address * \param mask destination mask * \param nextHop nextHop for this destination * \param interface output interface * \param prefixToUse prefix to use as source with this route */ virtual void NotifyAddRoute (Ipv6Address dst, Ipv6Prefix mask, Ipv6Address nextHop, uint32_t interface, Ipv6Address prefixToUse = Ipv6Address::GetZero ()) = 0; /** * \brief Notify route removing. * \param dst destination address * \param mask destination mask * \param nextHop nextHop for this destination * \param interface output interface * \param prefixToUse prefix to use as source with this route */ virtual void NotifyRemoveRoute (Ipv6Address dst, Ipv6Prefix mask, Ipv6Address nextHop, uint32_t interface, Ipv6Address prefixToUse = Ipv6Address::GetZero ()) = 0; /** * \brief Typically, invoked directly or indirectly from ns3::Ipv6::SetRoutingProtocol * \param ipv6 the ipv6 object this routing protocol is being associated with */ virtual void SetIpv6 (Ptr<Ipv6> ipv6) = 0; }; } // namespace ns3 #endif /* IPV6_ROUTING_PROTOCOL_H */
zy901002-gpsr
src/internet/model/ipv6-routing-protocol.h
C++
gpl2
7,391
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007-2009 Strasbourg University * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Sebastien Vincent <vincent@clarinet.u-strasbg.fr> */ #ifndef IPV6_END_POINT_DEMUX_H #define IPV6_END_POINT_DEMUX_H #include <stdint.h> #include <list> #include "ns3/ipv6-address.h" #include "ipv6-interface.h" namespace ns3 { class Ipv6EndPoint; /** * \class Ipv6EndPointDemux * \brief Demultiplexor for end points. */ class Ipv6EndPointDemux { public: typedef std::list<Ipv6EndPoint *>EndPoints; typedef std::list<Ipv6EndPoint *>::iterator EndPointsI; /** * \brief Constructor. */ Ipv6EndPointDemux (); /** * \brief Destructor. */ ~Ipv6EndPointDemux (); /** * \brief Lookup for port local. * \param port port to test * \return true if a port local is in EndPoints, false otherwise */ bool LookupPortLocal (uint16_t port); /** * \brief Lookup for address and port. * \param addr address to test * \param port port to test * \return true if there is a match in EndPoints, false otherwise */ bool LookupLocal (Ipv6Address addr, uint16_t port); /** * \brief lookup for a match with all the parameters. * \param dst destination address to test * \param dport destination port to test * \param src source address to test * \param sport source port to test * \param incomingInterface the incoming interface * \return list en IPv6EndPoints (could be 0 element) */ EndPoints Lookup (Ipv6Address dst, uint16_t dport, Ipv6Address src, uint16_t sport, Ptr<Ipv6Interface> incomingInterface); /** * \brief Simple lookup for a four-tuple match. * \param dst destination address to test * \param dport destination port to test * \param src source address to test * \param sport source port to test * \return match or 0 if not found */ Ipv6EndPoint* SimpleLookup (Ipv6Address dst, uint16_t dport, Ipv6Address src, uint16_t sport); /** * \brief Allocate a Ipv6EndPoint. * \return an empty Ipv6EndPoint instance */ Ipv6EndPoint *Allocate (void); /** * \brief Allocate a Ipv6EndPoint. * \param address IPv6 address * \return an Ipv6EndPoint instance */ Ipv6EndPoint *Allocate (Ipv6Address address); /** * \brief Allocate a Ipv6EndPoint. * \param port local port * \return an Ipv6EndPoint instance */ Ipv6EndPoint *Allocate (uint16_t port); /** * \brief Allocate a Ipv6EndPoint. * \param address local address * \param port local port * \return an Ipv6EndPoint instance */ Ipv6EndPoint *Allocate (Ipv6Address address, uint16_t port); /** * \brief Allocate a Ipv6EndPoint. * \param localAddress local address * \param localPort local port * \param peerAddress peer address * \param peerPort peer port * \return an Ipv6EndPoint instance */ Ipv6EndPoint *Allocate (Ipv6Address localAddress, uint16_t localPort, Ipv6Address peerAddress, uint16_t peerPort); /** * \brief Remove a end point. * \param endPoint the end point to remove */ void DeAllocate (Ipv6EndPoint *endPoint); /** * \brief Get the entire list of end points registered. * \return list of Ipv6EndPoint */ EndPoints GetEndPoints () const; private: /** * \brief Allocate a ephemeral port. * \return a port */ uint16_t AllocateEphemeralPort (); /** * \brief The ephemeral port. */ uint16_t m_ephemeral; /** * \brief A list of IPv6 end points. */ EndPoints m_endPoints; }; } /* namespace ns3 */ #endif /* IPV6_END_POINT_DEMUX_H */
zy901002-gpsr
src/internet/model/ipv6-end-point-demux.h
C++
gpl2
4,238
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2010 Adrian Sai-wah Tam * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Adrian Sai-wah Tam <adrian.sw.tam@gmail.com> */ #ifndef TCP_TAHOE_H #define TCP_TAHOE_H #include "tcp-socket-base.h" namespace ns3 { /** * \ingroup socket * \ingroup tcp * * \brief An implementation of a stream socket using TCP. * * This class contains the Tahoe implementation of TCP. Tahoe is not officially * published in RFC. The reference for implementing this is based on * Kevin Fall and Sally Floyd, "Simulation-based Comparisons of Tahoe, Reno, and SACK TCP", CCR, 1996 * http://inst.eecs.berkeley.edu/~ee122/fa05/projects/Project2/proj2_spec_files/sacks.pdf * In summary, we have slow start, congestion avoidance, and fast retransmit. * The implementation of these algorithms are based on W. R. Stevens's book and * also RFC2001. */ class TcpTahoe : public TcpSocketBase { public: static TypeId GetTypeId (void); /** * Create an unbound tcp socket. */ TcpTahoe (void); TcpTahoe (const TcpTahoe& sock); virtual ~TcpTahoe (void); // From TcpSocketBase virtual int Connect (const Address &address); virtual int Listen (void); protected: virtual uint32_t Window (void); // Return the max possible number of unacked bytes virtual Ptr<TcpSocketBase> Fork (void); // Call CopyObject<TcpTahoe> to clone me virtual void NewAck (SequenceNumber32 const& seq); // Inc cwnd and call NewAck() of parent virtual void DupAck (const TcpHeader& t, uint32_t count); // Treat 3 dupack as timeout virtual void Retransmit (void); // Retransmit time out // Implementing ns3::TcpSocket -- Attribute get/set virtual void SetSegSize (uint32_t size); virtual void SetSSThresh (uint32_t threshold); virtual uint32_t GetSSThresh (void) const; virtual void SetInitialCwnd (uint32_t cwnd); virtual uint32_t GetInitialCwnd (void) const; private: void InitializeCwnd (void); // set m_cWnd when connection starts protected: TracedValue<uint32_t> m_cWnd; //< Congestion window uint32_t m_ssThresh; //< Slow Start Threshold uint32_t m_initialCWnd; //< Initial cWnd value }; } // namespace ns3 #endif /* TCP_TAHOE_H */
zy901002-gpsr
src/internet/model/tcp-tahoe.h
C++
gpl2
2,909
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007-2009 Strasbourg University * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Sebastien Vincent <vincent@clarinet.u-strasbg.fr> */ #ifndef IPV6_ROUTING_TABLE_ENTRY_H #define IPV6_ROUTING_TABLE_ENTRY_H #include <list> #include <vector> #include <ostream> #include "ns3/ipv6-address.h" namespace ns3 { /** * \class Ipv6RoutingTableEntry * \brief A record of an IPv6 route. */ class Ipv6RoutingTableEntry { public: /** * \brief Constructor. */ Ipv6RoutingTableEntry (); /** * \brief Copy constructor. * \param route the route to copy */ Ipv6RoutingTableEntry (Ipv6RoutingTableEntry const & route); /** * \brief Copy constructor. * \param route the route to copy */ Ipv6RoutingTableEntry (Ipv6RoutingTableEntry const* route); /** * \brief Destructor */ ~Ipv6RoutingTableEntry (); /** * \brief Is the route entry correspond to a host ? * \return true if the route is a host, false otherwise */ bool IsHost () const; /** * \brief Get the destination. * \return the IPv6 address of the destination of this route */ Ipv6Address GetDest () const; /** * \brief Get the prefix to use (for multihomed link). * \return prefix address to use */ Ipv6Address GetPrefixToUse () const; /** * \brief Set the prefix to use. * \param prefix prefix to use */ void SetPrefixToUse (Ipv6Address prefix); /** * \brief Is the route entry correspond to a network ? * \return true if the route is a network, false otherwise */ bool IsNetwork () const; /** * \brief Get the destination network. * \return the destination network */ Ipv6Address GetDestNetwork () const; /** * \brief Get the destination prefix. * \return the destination prefix */ Ipv6Prefix GetDestNetworkPrefix () const; /** * \brief Is it the default route ? * \return true if this route is a default route, false otherwise */ bool IsDefault () const; /** * \brief Is it the gateway ? * \return true if this route is a gateway, false otherwise */ bool IsGateway () const; /** * \brief Get the gateway. * \return the IPv6 address of the gateway */ Ipv6Address GetGateway () const; /** * \brief Get the interface index. * \return the index of the interface */ uint32_t GetInterface () const; /** * \brief Create a route to a host. * \param dest destination address * \param nextHop next hop address to route the packet * \param interface interface index * \param prefixToUse prefix that should be used for source address for this destination * \return IPv6Route object */ static Ipv6RoutingTableEntry CreateHostRouteTo (Ipv6Address dest, Ipv6Address nextHop, uint32_t interface, Ipv6Address prefixToUse=Ipv6Address ()); /** * \brief Create a route to a host. * \param dest destination address * \param interface interface index * \return IPv6Route object */ static Ipv6RoutingTableEntry CreateHostRouteTo (Ipv6Address dest, uint32_t interface); /** * \brief Create a route to a network. * \param network network address * \param networkPrefix network prefix * \param nextHop next hop address to route the packet * \param interface interface index * \return IPv6Route object */ static Ipv6RoutingTableEntry CreateNetworkRouteTo (Ipv6Address network, Ipv6Prefix networkPrefix, Ipv6Address nextHop, uint32_t interface); /** * \brief Create a route to a network. * \param network network address * \param networkPrefix network prefix * \param nextHop next hop address to route the packet * \param interface interface index * \param prefixToUse prefix that should be used for source address for this destination * \return IPv6Route object */ static Ipv6RoutingTableEntry CreateNetworkRouteTo (Ipv6Address network, Ipv6Prefix networkPrefix, Ipv6Address nextHop, uint32_t interface, Ipv6Address prefixToUse); /** * \brief Create a route to a network. * \param network network address * \param networkPrefix network prefix * \param interface interface index * \return IPv6Route object */ static Ipv6RoutingTableEntry CreateNetworkRouteTo (Ipv6Address network, Ipv6Prefix networkPrefix, uint32_t interface); /** * \brief Create a default route. * \param nextHop next hop address to route the packet * \param interface interface index * \return IPv6Route object */ static Ipv6RoutingTableEntry CreateDefaultRoute (Ipv6Address nextHop, uint32_t interface); private: /** * \brief Constructor. * \param network network address * \param prefix network prefix * \param gateway the gateway * \param interface the interface index */ Ipv6RoutingTableEntry (Ipv6Address network, Ipv6Prefix prefix, Ipv6Address gateway, uint32_t interface); /** * \brief Constructor. * \param network network address * \param prefix network prefix * \param interface the interface index * \param prefixToUse prefix to use */ Ipv6RoutingTableEntry (Ipv6Address network, Ipv6Prefix prefix, uint32_t interface, Ipv6Address prefixToUse); /** * \brief Constructor. * \param network network address * \param prefix network prefix * \param gateway the gateway * \param interface the interface index * \param prefixToUse prefix to use */ Ipv6RoutingTableEntry (Ipv6Address network, Ipv6Prefix prefix, Ipv6Address gateway, uint32_t interface, Ipv6Address prefixToUse); /** * \brief Constructor. * \param dest destination address * \param prefix destination prefix * \param interface interface index */ Ipv6RoutingTableEntry (Ipv6Address dest, Ipv6Prefix prefix, uint32_t interface); /** * \brief Constructor. * \param dest destination address * \param gateway the gateway * \param interface interface index */ Ipv6RoutingTableEntry (Ipv6Address dest, Ipv6Address gateway, uint32_t interface); /** * \brief Constructor. * \param dest destination address * \param interface interface index */ Ipv6RoutingTableEntry (Ipv6Address dest, uint32_t interface); /** * \brief IPv6 address of the destination. */ Ipv6Address m_dest; /** * \brief IPv6 prefix of the destination */ Ipv6Prefix m_destNetworkPrefix; /** * \brief IPv6 address of the gateway. */ Ipv6Address m_gateway; /** * \brief The interface index. */ uint32_t m_interface; /** * \brief Prefix to use. */ Ipv6Address m_prefixToUse; }; std::ostream& operator<< (std::ostream& os, Ipv6RoutingTableEntry const& route); /** * \class Ipv6MulticastRoutingTableEntry * \brief A record of an IPv6 multicast route. */ class Ipv6MulticastRoutingTableEntry { public: /** * \brief Constructor. */ Ipv6MulticastRoutingTableEntry (); /** * \brief Copy constructor. * \param route the route to copy */ Ipv6MulticastRoutingTableEntry (Ipv6MulticastRoutingTableEntry const & route); /** * \brief Copy constructor. * \param route the route to copy */ Ipv6MulticastRoutingTableEntry (Ipv6MulticastRoutingTableEntry const* route); /** * \brief Get the source of this route * \return IPv6 address of the source of this route */ Ipv6Address GetOrigin () const; /** * \brief Get the group. * \return IPv6 address of the multicast group of this route */ Ipv6Address GetGroup () const; /** * \brief Get the input interface address. * \return input interface index */ uint32_t GetInputInterface () const; /** * \brief Get the number of output interfaces of this route. * \return number of output interfaces of this route. */ uint32_t GetNOutputInterfaces () const; /** * \brief Get a specified output interface. * \param n index * \return a specified output interface */ uint32_t GetOutputInterface (uint32_t n) const; /** * \brief Get all of the output interfaces of this route. * \return a vector of all output interfaces of this route */ std::vector<uint32_t> GetOutputInterfaces () const; /** * \brief Create a multicast route. * \param origin IPv6 address of the origin source * \param group Ipv6Address of the group * \param inputInterface interface number * \param outputInterfaces list of output interface number * \return a multicast route */ static Ipv6MulticastRoutingTableEntry CreateMulticastRoute (Ipv6Address origin, Ipv6Address group, uint32_t inputInterface, std::vector<uint32_t> outputInterfaces); private: /** * \brief Constructor. * \param origin IPv6 address of the source * \param group IPv6 address of the group * \param inputInterface interface number * \param outputInterfaces list of output interface number */ Ipv6MulticastRoutingTableEntry (Ipv6Address origin, Ipv6Address group, uint32_t inputInterface, std::vector<uint32_t> outputInterfaces); /** * \brief The IPv6 address of the source. */ Ipv6Address m_origin; /** * \brief The IPv6 address of the group. */ Ipv6Address m_group; /** * \brief The input interface. */ uint32_t m_inputInterface; /** * \brief The output interfaces. */ std::vector<uint32_t> m_outputInterfaces; }; std::ostream& operator<< (std::ostream& os, Ipv6MulticastRoutingTableEntry const& route); } /* namespace ns3 */ #endif /* IPV6_ROUTING_TABLE_ENTRY_H */
zy901002-gpsr
src/internet/model/ipv6-routing-table-entry.h
C++
gpl2
10,107
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007-2009 Strasbourg University * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Sebastien Vincent <vincent@clarinet.u-strasbg.fr> */ #ifndef IPV6_RAW_SOCKET_IMPL_H #define IPV6_RAW_SOCKET_IMPL_H #include <list> #include "ns3/socket.h" #include "ns3/ipv6-address.h" #include "ns3/ipv6-header.h" namespace ns3 { class NetDevice; class Node; /** * \class Ipv6RawSocketImpl * \brief IPv6 raw socket. */ class Ipv6RawSocketImpl : public Socket { public: /** * \brief Get the type ID of this class. * \return type ID */ static TypeId GetTypeId (); /** * \brief Constructor. */ Ipv6RawSocketImpl (); /** * \brief Destructor. */ virtual ~Ipv6RawSocketImpl (); /** * \brief Set the node. * \param node node to set */ void SetNode (Ptr<Node> node); /** * \brief Get last error number. * \return error number */ virtual enum Socket::SocketErrno GetErrno () const; /** * \brief Get socket type (NS3_SOCK_RAW) * \return socket type */ virtual enum Socket::SocketType GetSocketType () const; /** * \brief Get node. * \return node associated with this raw socket. */ virtual Ptr<Node> GetNode () const; /** * \brief Bind the socket to address. * \param address bind to this address * \return 0 if success, -1 otherwise */ virtual int Bind (const Address& address); /** * \brief Bind socket. * \return 0 if success, -1 otherwise */ virtual int Bind (); /** * \brief Get socket address. * \param address socket address if method success * \return 0 if success, -1 otherwise */ virtual int GetSockName (Address& address) const; /** * \brief Close the socket. * \return 0 if success, -1 otherwise */ virtual int Close (); /** * \brief Shutdown send capability. * \return 0 if success, -1 otherwise */ virtual int ShutdownSend (); /** * \brief Shutdown receive capability. * \return 0 if success, -1 otherwise */ virtual int ShutdownRecv (); /** * \brief Connect to address. * \param address address * \return 0 if success, -1 otherwise */ virtual int Connect (const Address& address); /** * \brief Listen. * \return 0 if success, -1 otherwise */ virtual int Listen (); /** * \brief Get TX size available. * \return TX size */ virtual uint32_t GetTxAvailable () const; /** * \brief Get RX size available. * \return RX size */ virtual uint32_t GetRxAvailable () const; /** * \brief Send a packet. * \param p packet to send * \param flags additionnal flags * \return 0 if success, -1 otherwise */ virtual int Send (Ptr<Packet> p, uint32_t flags); /** * \brief Send a packet. * \param p packet to send * \param flags additionnal flags * \param toAddress destination address * \return 0 if success, -1 otherwise */ virtual int SendTo (Ptr<Packet> p, uint32_t flags, const Address& toAddress); /** * \brief Receive packet. * \param maxSize maximum size * \param flags additionnal flags * \return packet received */ virtual Ptr<Packet> Recv (uint32_t maxSize, uint32_t flags); /** * \brief Receive packet. * \param maxSize maximum size * \param flags additionnal flags * \param fromAddress source address * \return packet received */ virtual Ptr<Packet> RecvFrom (uint32_t maxSize, uint32_t flags, Address& fromAddress); /** * \brief Set protocol field. * \param protocol protocol to set */ void SetProtocol (uint16_t protocol); /** * \brief Forward up to receive method. * \param p packet * \param hdr IPv6 header * \param device device * \return true if forwarded, false otherwise */ bool ForwardUp (Ptr<const Packet> p, Ipv6Header hdr, Ptr<NetDevice> device); virtual bool SetAllowBroadcast (bool allowBroadcast); virtual bool GetAllowBroadcast () const; private: /** * \struct Data * \brief IPv6 raw data and additionnal information. */ struct Data { Ptr<Packet> packet; /**< Packet data */ Ipv6Address fromIp; /**< Source address */ uint16_t fromProtocol; /**< Protocol used */ }; /** * \brief Dispose object. */ virtual void DoDispose (); /** * \brief Last error number. */ enum Socket::SocketErrno m_err; /** * \brief Node. */ Ptr<Node> m_node; /** * \brief Source address. */ Ipv6Address m_src; /** * \brief Destination address. */ Ipv6Address m_dst; /** * \brief Protocol. */ uint16_t m_protocol; /** * \brief Packet waiting to be processed. */ std::list<struct Data> m_data; /** * \brief Flag to shutdown send capability. */ bool m_shutdownSend; /** * \brief Flag to shutdown receive capability. */ bool m_shutdownRecv; /** * \brief ICMPv6 filter. */ uint32_t m_icmpFilter; }; } /* namespace ns3 */ #endif /* IPV6_RAW_SOCKET_IMPL_H */
zy901002-gpsr
src/internet/model/ipv6-raw-socket-impl.h
C++
gpl2
5,650
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2005 INRIA * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr> */ #include "ipv4-routing-table-entry.h" #include "ns3/assert.h" namespace ns3 { /***************************************************** * Network Ipv4RoutingTableEntry *****************************************************/ Ipv4RoutingTableEntry::Ipv4RoutingTableEntry () { } Ipv4RoutingTableEntry::Ipv4RoutingTableEntry (Ipv4RoutingTableEntry const &route) : m_dest (route.m_dest), m_destNetworkMask (route.m_destNetworkMask), m_gateway (route.m_gateway), m_interface (route.m_interface) { } Ipv4RoutingTableEntry::Ipv4RoutingTableEntry (Ipv4RoutingTableEntry const *route) : m_dest (route->m_dest), m_destNetworkMask (route->m_destNetworkMask), m_gateway (route->m_gateway), m_interface (route->m_interface) { } Ipv4RoutingTableEntry::Ipv4RoutingTableEntry (Ipv4Address dest, Ipv4Address gateway, uint32_t interface) : m_dest (dest), m_destNetworkMask (Ipv4Mask::GetOnes ()), m_gateway (gateway), m_interface (interface) { } Ipv4RoutingTableEntry::Ipv4RoutingTableEntry (Ipv4Address dest, uint32_t interface) : m_dest (dest), m_destNetworkMask (Ipv4Mask::GetOnes ()), m_gateway (Ipv4Address::GetZero ()), m_interface (interface) { } Ipv4RoutingTableEntry::Ipv4RoutingTableEntry (Ipv4Address network, Ipv4Mask networkMask, Ipv4Address gateway, uint32_t interface) : m_dest (network), m_destNetworkMask (networkMask), m_gateway (gateway), m_interface (interface) { } Ipv4RoutingTableEntry::Ipv4RoutingTableEntry (Ipv4Address network, Ipv4Mask networkMask, uint32_t interface) : m_dest (network), m_destNetworkMask (networkMask), m_gateway (Ipv4Address::GetZero ()), m_interface (interface) { } bool Ipv4RoutingTableEntry::IsHost (void) const { if (m_destNetworkMask.IsEqual (Ipv4Mask::GetOnes ())) { return true; } else { return false; } } Ipv4Address Ipv4RoutingTableEntry::GetDest (void) const { return m_dest; } bool Ipv4RoutingTableEntry::IsNetwork (void) const { return !IsHost (); } bool Ipv4RoutingTableEntry::IsDefault (void) const { if (m_dest.IsEqual (Ipv4Address::GetZero ())) { return true; } else { return false; } } Ipv4Address Ipv4RoutingTableEntry::GetDestNetwork (void) const { return m_dest; } Ipv4Mask Ipv4RoutingTableEntry::GetDestNetworkMask (void) const { return m_destNetworkMask; } bool Ipv4RoutingTableEntry::IsGateway (void) const { if (m_gateway.IsEqual (Ipv4Address::GetZero ())) { return false; } else { return true; } } Ipv4Address Ipv4RoutingTableEntry::GetGateway (void) const { return m_gateway; } uint32_t Ipv4RoutingTableEntry::GetInterface (void) const { return m_interface; } Ipv4RoutingTableEntry Ipv4RoutingTableEntry::CreateHostRouteTo (Ipv4Address dest, Ipv4Address nextHop, uint32_t interface) { return Ipv4RoutingTableEntry (dest, nextHop, interface); } Ipv4RoutingTableEntry Ipv4RoutingTableEntry::CreateHostRouteTo (Ipv4Address dest, uint32_t interface) { return Ipv4RoutingTableEntry (dest, interface); } Ipv4RoutingTableEntry Ipv4RoutingTableEntry::CreateNetworkRouteTo (Ipv4Address network, Ipv4Mask networkMask, Ipv4Address nextHop, uint32_t interface) { return Ipv4RoutingTableEntry (network, networkMask, nextHop, interface); } Ipv4RoutingTableEntry Ipv4RoutingTableEntry::CreateNetworkRouteTo (Ipv4Address network, Ipv4Mask networkMask, uint32_t interface) { return Ipv4RoutingTableEntry (network, networkMask, interface); } Ipv4RoutingTableEntry Ipv4RoutingTableEntry::CreateDefaultRoute (Ipv4Address nextHop, uint32_t interface) { return Ipv4RoutingTableEntry (Ipv4Address::GetZero (), nextHop, interface); } std::ostream& operator<< (std::ostream& os, Ipv4RoutingTableEntry const& route) { if (route.IsDefault ()) { NS_ASSERT (route.IsGateway ()); os << "default out=" << route.GetInterface () << ", next hop=" << route.GetGateway (); } else if (route.IsHost ()) { if (route.IsGateway ()) { os << "host="<< route.GetDest () << ", out=" << route.GetInterface () << ", next hop=" << route.GetGateway (); } else { os << "host="<< route.GetDest () << ", out=" << route.GetInterface (); } } else if (route.IsNetwork ()) { if (route.IsGateway ()) { os << "network=" << route.GetDestNetwork () << ", mask=" << route.GetDestNetworkMask () << ",out=" << route.GetInterface () << ", next hop=" << route.GetGateway (); } else { os << "network=" << route.GetDestNetwork () << ", mask=" << route.GetDestNetworkMask () << ",out=" << route.GetInterface (); } } else { NS_ASSERT (false); } return os; } /***************************************************** * Ipv4MulticastRoutingTableEntry *****************************************************/ Ipv4MulticastRoutingTableEntry::Ipv4MulticastRoutingTableEntry () { } Ipv4MulticastRoutingTableEntry::Ipv4MulticastRoutingTableEntry (Ipv4MulticastRoutingTableEntry const &route) : m_origin (route.m_origin), m_group (route.m_group), m_inputInterface (route.m_inputInterface), m_outputInterfaces (route.m_outputInterfaces) { } Ipv4MulticastRoutingTableEntry::Ipv4MulticastRoutingTableEntry (Ipv4MulticastRoutingTableEntry const *route) : m_origin (route->m_origin), m_group (route->m_group), m_inputInterface (route->m_inputInterface), m_outputInterfaces (route->m_outputInterfaces) { } Ipv4MulticastRoutingTableEntry::Ipv4MulticastRoutingTableEntry ( Ipv4Address origin, Ipv4Address group, uint32_t inputInterface, std::vector<uint32_t> outputInterfaces) { m_origin = origin; m_group = group; m_inputInterface = inputInterface; m_outputInterfaces = outputInterfaces; } Ipv4Address Ipv4MulticastRoutingTableEntry::GetOrigin (void) const { return m_origin; } Ipv4Address Ipv4MulticastRoutingTableEntry::GetGroup (void) const { return m_group; } uint32_t Ipv4MulticastRoutingTableEntry::GetInputInterface (void) const { return m_inputInterface; } uint32_t Ipv4MulticastRoutingTableEntry::GetNOutputInterfaces (void) const { return m_outputInterfaces.size (); } uint32_t Ipv4MulticastRoutingTableEntry::GetOutputInterface (uint32_t n) const { NS_ASSERT_MSG (n < m_outputInterfaces.size (), "Ipv4MulticastRoutingTableEntry::GetOutputInterface (): index out of bounds"); return m_outputInterfaces[n]; } std::vector<uint32_t> Ipv4MulticastRoutingTableEntry::GetOutputInterfaces (void) const { return m_outputInterfaces; } Ipv4MulticastRoutingTableEntry Ipv4MulticastRoutingTableEntry::CreateMulticastRoute ( Ipv4Address origin, Ipv4Address group, uint32_t inputInterface, std::vector<uint32_t> outputInterfaces) { return Ipv4MulticastRoutingTableEntry (origin, group, inputInterface, outputInterfaces); } std::ostream& operator<< (std::ostream& os, Ipv4MulticastRoutingTableEntry const& route) { os << "origin=" << route.GetOrigin () << ", group=" << route.GetGroup () << ", input interface=" << route.GetInputInterface () << ", output interfaces="; for (uint32_t i = 0; i < route.GetNOutputInterfaces (); ++i) { os << route.GetOutputInterface (i) << " "; } return os; } } // namespace ns3
zy901002-gpsr
src/internet/model/ipv4-routing-table-entry.cc
C++
gpl2
9,059
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007-2009 Strasbourg University * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: David Gross <gdavid.devel@gmail.com> */ #include <sstream> #include "ns3/node.h" #include "ns3/ptr.h" #include "ns3/object-vector.h" #include "ipv6-extension-demux.h" #include "ipv6-extension.h" namespace ns3 { NS_OBJECT_ENSURE_REGISTERED (Ipv6ExtensionDemux); TypeId Ipv6ExtensionDemux::GetTypeId () { static TypeId tid = TypeId ("ns3::Ipv6ExtensionDemux") .SetParent<Object> () .AddAttribute ("Extensions", "The set of IPv6 extensions registered with this demux.", ObjectVectorValue (), MakeObjectVectorAccessor (&Ipv6ExtensionDemux::m_extensions), MakeObjectVectorChecker<Ipv6Extension> ()) ; return tid; } Ipv6ExtensionDemux::Ipv6ExtensionDemux () { } Ipv6ExtensionDemux::~Ipv6ExtensionDemux () { } void Ipv6ExtensionDemux::DoDispose () { for (Ipv6ExtensionList_t::iterator it = m_extensions.begin (); it != m_extensions.end (); it++) { (*it)->Dispose (); *it = 0; } m_extensions.clear (); m_node = 0; Object::DoDispose (); } void Ipv6ExtensionDemux::SetNode (Ptr<Node> node) { m_node = node; } void Ipv6ExtensionDemux::Insert (Ptr<Ipv6Extension> extension) { m_extensions.push_back (extension); } Ptr<Ipv6Extension> Ipv6ExtensionDemux::GetExtension (uint8_t extensionNumber) { for (Ipv6ExtensionList_t::iterator i = m_extensions.begin (); i != m_extensions.end (); ++i) { if ((*i)->GetExtensionNumber () == extensionNumber) { return *i; } } return 0; } void Ipv6ExtensionDemux::Remove (Ptr<Ipv6Extension> extension) { m_extensions.remove (extension); } } /* namespace ns3 */
zy901002-gpsr
src/internet/model/ipv6-extension-demux.cc
C++
gpl2
2,426
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * based on tcp-socket-impl.cc, Author: Raj Bhattacharjea <raj.b@gatech.edu> * Author: Florian Westphal <fw@strlen.de> */ #define NS_LOG_APPEND_CONTEXT \ if (m_node) { std::clog << Simulator::Now ().GetSeconds () << " [node " << m_node->GetId () << "] "; } #include "ns3/node.h" #include "ns3/inet-socket-address.h" #include "ns3/log.h" #include "ns3/ipv4.h" #include "ipv4-end-point.h" #include "nsc-tcp-l4-protocol.h" #include "nsc-tcp-socket-impl.h" #include "ns3/simulation-singleton.h" #include "ns3/simulator.h" #include "ns3/packet.h" #include "ns3/uinteger.h" #include "ns3/trace-source-accessor.h" #include <algorithm> // for ntohs(). #include <arpa/inet.h> #include <netinet/in.h> #include "sim_interface.h" #include "sim_errno.h" NS_LOG_COMPONENT_DEFINE ("NscTcpSocketImpl"); using namespace std; namespace ns3 { NS_OBJECT_ENSURE_REGISTERED (NscTcpSocketImpl); TypeId NscTcpSocketImpl::GetTypeId () { static TypeId tid = TypeId ("ns3::NscTcpSocketImpl") .SetParent<TcpSocket> () .AddTraceSource ("CongestionWindow", "The TCP connection's congestion window", MakeTraceSourceAccessor (&NscTcpSocketImpl::m_cWnd)) ; return tid; } NscTcpSocketImpl::NscTcpSocketImpl () : m_endPoint (0), m_node (0), m_tcp (0), m_localAddress (Ipv4Address::GetZero ()), m_localPort (0), m_peerAddress ("0.0.0.0", 0), m_errno (ERROR_NOTERROR), m_shutdownSend (false), m_shutdownRecv (false), m_connected (false), m_state (CLOSED), m_closeOnEmpty (false), m_txBufferSize (0), m_lastMeasuredRtt (Seconds (0.0)) { NS_LOG_FUNCTION (this); } NscTcpSocketImpl::NscTcpSocketImpl(const NscTcpSocketImpl& sock) : TcpSocket (sock), //copy the base class callbacks m_delAckMaxCount (sock.m_delAckMaxCount), m_delAckTimeout (sock.m_delAckTimeout), m_endPoint (0), m_node (sock.m_node), m_tcp (sock.m_tcp), m_remoteAddress (sock.m_remoteAddress), m_remotePort (sock.m_remotePort), m_localAddress (sock.m_localAddress), m_localPort (sock.m_localPort), m_peerAddress (sock.m_peerAddress), m_errno (sock.m_errno), m_shutdownSend (sock.m_shutdownSend), m_shutdownRecv (sock.m_shutdownRecv), m_connected (sock.m_connected), m_state (sock.m_state), m_closeOnEmpty (sock.m_closeOnEmpty), m_txBufferSize (sock.m_txBufferSize), m_segmentSize (sock.m_segmentSize), m_rxWindowSize (sock.m_rxWindowSize), m_advertisedWindowSize (sock.m_advertisedWindowSize), m_cWnd (sock.m_cWnd), m_ssThresh (sock.m_ssThresh), m_initialCWnd (sock.m_initialCWnd), m_lastMeasuredRtt (Seconds (0.0)), m_cnTimeout (sock.m_cnTimeout), m_cnCount (sock.m_cnCount), m_rxAvailable (0), m_nscTcpSocket (0), m_sndBufSize (sock.m_sndBufSize) { NS_LOG_FUNCTION_NOARGS (); NS_LOG_LOGIC ("Invoked the copy constructor"); //copy the pending data if necessary if(!sock.m_txBuffer.empty () ) { m_txBuffer = sock.m_txBuffer; } //can't "copy" the endpoint just yes, must do this when we know the peer info //too; this is in SYN_ACK_TX } NscTcpSocketImpl::~NscTcpSocketImpl () { NS_LOG_FUNCTION (this); m_node = 0; if (m_endPoint != 0) { NS_ASSERT (m_tcp != 0); /** * Note that this piece of code is a bit tricky: * when DeAllocate is called, it will call into * Ipv4EndPointDemux::Deallocate which triggers * a delete of the associated endPoint which triggers * in turn a call to the method ::Destroy below * will will zero the m_endPoint field. */ NS_ASSERT (m_endPoint != 0); m_tcp->DeAllocate (m_endPoint); NS_ASSERT (m_endPoint == 0); } m_tcp = 0; } void NscTcpSocketImpl::SetNode (Ptr<Node> node) { m_node = node; // Initialize some variables m_cWnd = m_initialCWnd * m_segmentSize; m_rxWindowSize = m_advertisedWindowSize; } void NscTcpSocketImpl::SetTcp (Ptr<NscTcpL4Protocol> tcp) { m_nscTcpSocket = tcp->m_nscStack->new_tcp_socket (); m_tcp = tcp; } enum Socket::SocketErrno NscTcpSocketImpl::GetErrno (void) const { NS_LOG_FUNCTION_NOARGS (); return m_errno; } enum Socket::SocketType NscTcpSocketImpl::GetSocketType (void) const { return NS3_SOCK_STREAM; } Ptr<Node> NscTcpSocketImpl::GetNode (void) const { NS_LOG_FUNCTION_NOARGS (); return m_node; } void NscTcpSocketImpl::Destroy (void) { NS_LOG_FUNCTION_NOARGS (); m_node = 0; m_endPoint = 0; m_tcp = 0; } int NscTcpSocketImpl::FinishBind (void) { NS_LOG_FUNCTION_NOARGS (); if (m_endPoint == 0) { return -1; } m_endPoint->SetRxCallback (MakeCallback (&NscTcpSocketImpl::ForwardUp, Ptr<NscTcpSocketImpl>(this))); m_endPoint->SetDestroyCallback (MakeCallback (&NscTcpSocketImpl::Destroy, Ptr<NscTcpSocketImpl>(this))); m_localAddress = m_endPoint->GetLocalAddress (); m_localPort = m_endPoint->GetLocalPort (); return 0; } int NscTcpSocketImpl::Bind (void) { NS_LOG_FUNCTION_NOARGS (); m_endPoint = m_tcp->Allocate (); return FinishBind (); } int NscTcpSocketImpl::Bind (const Address &address) { NS_LOG_FUNCTION (this<<address); if (!InetSocketAddress::IsMatchingType (address)) { return ERROR_INVAL; } InetSocketAddress transport = InetSocketAddress::ConvertFrom (address); Ipv4Address ipv4 = transport.GetIpv4 (); uint16_t port = transport.GetPort (); if (ipv4 == Ipv4Address::GetAny () && port == 0) { m_endPoint = m_tcp->Allocate (); NS_LOG_LOGIC ("NscTcpSocketImpl "<<this<<" got an endpoint: "<<m_endPoint); } else if (ipv4 == Ipv4Address::GetAny () && port != 0) { m_endPoint = m_tcp->Allocate (port); NS_LOG_LOGIC ("NscTcpSocketImpl "<<this<<" got an endpoint: "<<m_endPoint); } else if (ipv4 != Ipv4Address::GetAny () && port == 0) { m_endPoint = m_tcp->Allocate (ipv4); NS_LOG_LOGIC ("NscTcpSocketImpl "<<this<<" got an endpoint: "<<m_endPoint); } else if (ipv4 != Ipv4Address::GetAny () && port != 0) { m_endPoint = m_tcp->Allocate (ipv4, port); NS_LOG_LOGIC ("NscTcpSocketImpl "<<this<<" got an endpoint: "<<m_endPoint); } m_localPort = port; return FinishBind (); } int NscTcpSocketImpl::ShutdownSend (void) { NS_LOG_FUNCTION_NOARGS (); m_shutdownSend = true; return 0; } int NscTcpSocketImpl::ShutdownRecv (void) { NS_LOG_FUNCTION_NOARGS (); m_shutdownRecv = true; return 0; } int NscTcpSocketImpl::Close (void) { NS_LOG_FUNCTION (this << m_state); if (m_state == CLOSED) { return -1; } if (!m_txBuffer.empty ()) { // App close with pending data must wait until all data transmitted m_closeOnEmpty = true; NS_LOG_LOGIC ("Socket " << this << " deferring close, state " << m_state); return 0; } NS_LOG_LOGIC ("NscTcp socket " << this << " calling disconnect(); moving to CLOSED"); m_nscTcpSocket->disconnect (); m_state = CLOSED; ShutdownSend (); return 0; } int NscTcpSocketImpl::Connect (const Address & address) { NS_LOG_FUNCTION (this << address); if (m_endPoint == 0) { if (Bind () == -1) { NS_ASSERT (m_endPoint == 0); return -1; } NS_ASSERT (m_endPoint != 0); } InetSocketAddress transport = InetSocketAddress::ConvertFrom (address); m_remoteAddress = transport.GetIpv4 (); m_remotePort = transport.GetPort (); std::ostringstream ss; m_remoteAddress.Print (ss); std::string ipstring = ss.str (); m_nscTcpSocket->connect (ipstring.c_str (), m_remotePort); m_state = SYN_SENT; return 0; } int NscTcpSocketImpl::Send (const Ptr<Packet> p, uint32_t flags) { NS_LOG_FUNCTION (this << p); NS_ASSERT (p->GetSize () > 0); if (m_state == ESTABLISHED || m_state == SYN_SENT || m_state == CLOSE_WAIT) { if (p->GetSize () > GetTxAvailable ()) { m_errno = ERROR_MSGSIZE; return -1; } uint32_t sent = p->GetSize (); if (m_state == ESTABLISHED) { m_txBuffer.push (p); m_txBufferSize += sent; SendPendingData (); } else { // SYN_SET -- Queue Data m_txBuffer.push (p); m_txBufferSize += sent; } return sent; } else { m_errno = ERROR_NOTCONN; return -1; } } int NscTcpSocketImpl::SendTo (Ptr<Packet> p, uint32_t flags, const Address &address) { NS_LOG_FUNCTION (this << address << p); if (!m_connected) { m_errno = ERROR_NOTCONN; return -1; } else { return Send (p, flags); //drop the address according to BSD manpages } } uint32_t NscTcpSocketImpl::GetTxAvailable (void) const { NS_LOG_FUNCTION_NOARGS (); if (m_txBufferSize != 0) { NS_ASSERT (m_txBufferSize <= m_sndBufSize); return m_sndBufSize - m_txBufferSize; } else { return m_sndBufSize; } } int NscTcpSocketImpl::Listen (void) { NS_LOG_FUNCTION (this); m_nscTcpSocket->listen (m_localPort); m_state = LISTEN; return 0; } void NscTcpSocketImpl::NSCWakeup () { switch (m_state) { case SYN_SENT: if (!m_nscTcpSocket->is_connected ()) break; m_state = ESTABLISHED; Simulator::ScheduleNow (&NscTcpSocketImpl::ConnectionSucceeded, this); // fall through to schedule read/write events case ESTABLISHED: if (!m_txBuffer.empty ()) Simulator::ScheduleNow (&NscTcpSocketImpl::SendPendingData, this); Simulator::ScheduleNow (&NscTcpSocketImpl::ReadPendingData, this); break; case LISTEN: Simulator::ScheduleNow (&NscTcpSocketImpl::Accept, this); break; case CLOSED: break; default: NS_LOG_DEBUG (this << " invalid state: " << m_state); } } Ptr<Packet> NscTcpSocketImpl::Recv (uint32_t maxSize, uint32_t flags) { NS_LOG_FUNCTION_NOARGS (); if (m_deliveryQueue.empty () ) { m_errno = ERROR_AGAIN; return 0; } Ptr<Packet> p = m_deliveryQueue.front (); if (p->GetSize () <= maxSize) { m_deliveryQueue.pop (); m_rxAvailable -= p->GetSize (); } else { m_errno = ERROR_AGAIN; p = 0; } return p; } Ptr<Packet> NscTcpSocketImpl::RecvFrom (uint32_t maxSize, uint32_t flags, Address &fromAddress) { NS_LOG_FUNCTION (this << maxSize << flags); Ptr<Packet> packet = Recv (maxSize, flags); if (packet != 0) { SocketAddressTag tag; bool found; found = packet->PeekPacketTag (tag); NS_ASSERT (found); // cast found to void, to suppress 'found' set but not used // compiler warning in optimized builds (void) found; fromAddress = tag.GetAddress (); } return packet; } int NscTcpSocketImpl::GetSockName (Address &address) const { NS_LOG_FUNCTION_NOARGS (); address = InetSocketAddress (m_localAddress, m_localPort); return 0; } uint32_t NscTcpSocketImpl::GetRxAvailable (void) const { NS_LOG_FUNCTION_NOARGS (); // We separately maintain this state to avoid walking the queue // every time this might be called return m_rxAvailable; } void NscTcpSocketImpl::ForwardUp (Ptr<Packet> packet, Ipv4Header header, uint16_t port, Ptr<Ipv4Interface> incomingInterface) { NSCWakeup (); } void NscTcpSocketImpl::CompleteFork (void) { // The address pairs (m_localAddress, m_localPort, m_remoteAddress, m_remotePort) // are bogus, but this isn't important at the moment, because // address <-> Socket handling is done by NSC internally. // We only need to add the new ns-3 socket to the list of sockets, so // we use plain Allocate() instead of Allocate(m_localAddress, ... ) struct sockaddr_in sin; size_t sin_len = sizeof(sin); if (0 == m_nscTcpSocket->getpeername ((struct sockaddr*) &sin, &sin_len)) { m_remotePort = ntohs (sin.sin_port); m_remoteAddress = m_remoteAddress.Deserialize ((const uint8_t*) &sin.sin_addr); m_peerAddress = InetSocketAddress (m_remoteAddress, m_remotePort); } m_endPoint = m_tcp->Allocate (); //the cloned socket with be in listen state, so manually change state NS_ASSERT (m_state == LISTEN); m_state = ESTABLISHED; sin_len = sizeof(sin); if (0 == m_nscTcpSocket->getsockname ((struct sockaddr *) &sin, &sin_len)) m_localAddress = m_localAddress.Deserialize ((const uint8_t*) &sin.sin_addr); NS_LOG_LOGIC ("NscTcpSocketImpl " << this << " accepted connection from " << m_remoteAddress << ":" << m_remotePort << " to " << m_localAddress << ":" << m_localPort); //equivalent to FinishBind m_endPoint->SetRxCallback (MakeCallback (&NscTcpSocketImpl::ForwardUp, Ptr<NscTcpSocketImpl>(this))); m_endPoint->SetDestroyCallback (MakeCallback (&NscTcpSocketImpl::Destroy, Ptr<NscTcpSocketImpl>(this))); NotifyNewConnectionCreated (this, m_peerAddress); } void NscTcpSocketImpl::ConnectionSucceeded () { // We would preferred to have scheduled an event directly to // NotifyConnectionSucceeded, but (sigh) these are protected // and we can get the address of it :( struct sockaddr_in sin; size_t sin_len = sizeof(sin); if (0 == m_nscTcpSocket->getsockname ((struct sockaddr *) &sin, &sin_len)) { m_localAddress = m_localAddress.Deserialize ((const uint8_t*)&sin.sin_addr); m_localPort = ntohs (sin.sin_port); } NS_LOG_LOGIC ("NscTcpSocketImpl " << this << " connected to " << m_remoteAddress << ":" << m_remotePort << " from " << m_localAddress << ":" << m_localPort); NotifyConnectionSucceeded (); } bool NscTcpSocketImpl::Accept (void) { if (m_state == CLOSED) { // Happens if application closes listening socket after Accept() was scheduled. return false; } NS_ASSERT (m_state == LISTEN); if (!m_nscTcpSocket->is_listening ()) { return false; } INetStreamSocket *newsock; int res = m_nscTcpSocket->accept (&newsock); if (res != 0) { return false; } // We could obtain a fromAddress using getpeername, but we've already // finished the tcp handshake here, i.e. this is a new connection // and not a connection request. // if (!NotifyConnectionRequest(fromAddress)) // return true; // Clone the socket Ptr<NscTcpSocketImpl> newSock = Copy (); newSock->m_nscTcpSocket = newsock; NS_LOG_LOGIC ("Cloned a NscTcpSocketImpl " << newSock); Simulator::ScheduleNow (&NscTcpSocketImpl::CompleteFork, newSock); return true; } bool NscTcpSocketImpl::ReadPendingData (void) { if (m_state != ESTABLISHED) { return false; } int len, err; uint8_t buffer[8192]; len = sizeof(buffer); m_errno = ERROR_NOTERROR; err = m_nscTcpSocket->read_data (buffer, &len); if (err == 0 && len == 0) { NS_LOG_LOGIC ("ReadPendingData got EOF from socket"); m_state = CLOSE_WAIT; return false; } m_errno = GetNativeNs3Errno (err); switch (m_errno) { case ERROR_NOTERROR: break; // some data was sent case ERROR_AGAIN: return false; default: NS_LOG_WARN ("Error (" << err << ") " << "during read_data, ns-3 errno set to" << m_errno); m_state = CLOSED; return false; } Ptr<Packet> p = Create<Packet> (buffer, len); SocketAddressTag tag; tag.SetAddress (m_peerAddress); p->AddPacketTag (tag); m_deliveryQueue.push (p); m_rxAvailable += p->GetSize (); NotifyDataRecv (); return true; } bool NscTcpSocketImpl::SendPendingData (void) { NS_LOG_FUNCTION (this); NS_LOG_LOGIC ("ENTERING SendPendingData"); if (m_txBuffer.empty ()) { return false; } int ret; size_t size, written = 0; do { NS_ASSERT (!m_txBuffer.empty ()); Ptr<Packet> &p = m_txBuffer.front (); size = p->GetSize (); NS_ASSERT (size > 0); m_errno = ERROR_NOTERROR; uint8_t *buf = new uint8_t[size]; p->CopyData (buf, size); ret = m_nscTcpSocket->send_data ((const char *)buf, size); delete[] buf; if (ret <= 0) { break; } written += ret; NS_ASSERT (m_txBufferSize >= (size_t)ret); m_txBufferSize -= ret; if ((size_t)ret < size) { p->RemoveAtStart (ret); break; } m_txBuffer.pop (); if (m_txBuffer.empty ()) { if (m_closeOnEmpty) { m_nscTcpSocket->disconnect (); m_state = CLOSED; } break; } } while ((size_t) ret == size); if (written > 0) { Simulator::ScheduleNow (&NscTcpSocketImpl::NotifyDataSent, this, ret); return true; } return false; } Ptr<NscTcpSocketImpl> NscTcpSocketImpl::Copy () { return CopyObject<NscTcpSocketImpl> (this); } void NscTcpSocketImpl::SetSndBufSize (uint32_t size) { m_sndBufSize = size; } uint32_t NscTcpSocketImpl::GetSndBufSize (void) const { return m_sndBufSize; } void NscTcpSocketImpl::SetRcvBufSize (uint32_t size) { m_rcvBufSize = size; } uint32_t NscTcpSocketImpl::GetRcvBufSize (void) const { return m_rcvBufSize; } void NscTcpSocketImpl::SetSegSize (uint32_t size) { m_segmentSize = size; } uint32_t NscTcpSocketImpl::GetSegSize (void) const { return m_segmentSize; } void NscTcpSocketImpl::SetAdvWin (uint32_t window) { m_advertisedWindowSize = window; } uint32_t NscTcpSocketImpl::GetAdvWin (void) const { return m_advertisedWindowSize; } void NscTcpSocketImpl::SetSSThresh (uint32_t threshold) { m_ssThresh = threshold; } uint32_t NscTcpSocketImpl::GetSSThresh (void) const { return m_ssThresh; } void NscTcpSocketImpl::SetInitialCwnd (uint32_t cwnd) { m_initialCWnd = cwnd; } uint32_t NscTcpSocketImpl::GetInitialCwnd (void) const { return m_initialCWnd; } void NscTcpSocketImpl::SetConnTimeout (Time timeout) { m_cnTimeout = timeout; } Time NscTcpSocketImpl::GetConnTimeout (void) const { return m_cnTimeout; } void NscTcpSocketImpl::SetConnCount (uint32_t count) { m_cnCount = count; } uint32_t NscTcpSocketImpl::GetConnCount (void) const { return m_cnCount; } void NscTcpSocketImpl::SetDelAckTimeout (Time timeout) { m_delAckTimeout = timeout; } Time NscTcpSocketImpl::GetDelAckTimeout (void) const { return m_delAckTimeout; } void NscTcpSocketImpl::SetDelAckMaxCount (uint32_t count) { m_delAckMaxCount = count; } uint32_t NscTcpSocketImpl::GetDelAckMaxCount (void) const { return m_delAckMaxCount; } void NscTcpSocketImpl::SetPersistTimeout (Time timeout) { m_persistTimeout = timeout; } Time NscTcpSocketImpl::GetPersistTimeout (void) const { return m_persistTimeout; } enum Socket::SocketErrno NscTcpSocketImpl::GetNativeNs3Errno (int error) const { enum nsc_errno err; if (error >= 0) { return ERROR_NOTERROR; } err = (enum nsc_errno) error; switch (err) { case NSC_EADDRINUSE: // fallthrough case NSC_EADDRNOTAVAIL: return ERROR_AFNOSUPPORT; case NSC_EINPROGRESS: // Altough nsc sockets are nonblocking, we pretend they're not. case NSC_EAGAIN: return ERROR_AGAIN; case NSC_EISCONN: // fallthrough case NSC_EALREADY: return ERROR_ISCONN; case NSC_ECONNREFUSED: return ERROR_NOROUTETOHOST; // XXX, better mapping? case NSC_ECONNRESET: // for no, all of these fall through case NSC_EHOSTDOWN: case NSC_ENETUNREACH: case NSC_EHOSTUNREACH: return ERROR_NOROUTETOHOST; case NSC_EMSGSIZE: return ERROR_MSGSIZE; case NSC_ENOTCONN: return ERROR_NOTCONN; case NSC_ESHUTDOWN: return ERROR_SHUTDOWN; case NSC_ETIMEDOUT: return ERROR_NOTCONN; // XXX - this mapping isn't correct case NSC_ENOTDIR: // used by eg. sysctl(2). Shouldn't happen normally, // but is triggered by e.g. show_config(). case NSC_EUNKNOWN: return ERROR_INVAL; // Catches stacks that 'return -1' without real mapping } NS_ASSERT_MSG (0, "Unknown NSC error"); return ERROR_INVAL; } bool NscTcpSocketImpl::SetAllowBroadcast (bool allowBroadcast) { if (allowBroadcast) { return false; } return true; } bool NscTcpSocketImpl::GetAllowBroadcast () const { return false; } } // namespace ns3
zy901002-gpsr
src/internet/model/nsc-tcp-socket-impl.cc
C++
gpl2
21,036
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007 INRIA * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr> */ #ifndef UDP_SOCKET_FACTORY_H #define UDP_SOCKET_FACTORY_H #include "ns3/socket-factory.h" namespace ns3 { class Socket; /** * \ingroup socket * * \brief API to create UDP socket instances * * This abstract class defines the API for UDP socket factory. * All UDP implementations must provide an implementation of CreateSocket * below. * * \see UdpSocketFactoryImpl */ class UdpSocketFactory : public SocketFactory { public: static TypeId GetTypeId (void); }; } // namespace ns3 #endif /* UDP_SOCKET_FACTORY_H */
zy901002-gpsr
src/internet/model/udp-socket-factory.h
C++
gpl2
1,346
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007 INRIA * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr> */ #include "ns3/object.h" #include "ns3/log.h" #include "ns3/uinteger.h" #include "ns3/integer.h" #include "ns3/boolean.h" #include "ns3/trace-source-accessor.h" #include "udp-socket.h" NS_LOG_COMPONENT_DEFINE ("UdpSocket"); namespace ns3 { NS_OBJECT_ENSURE_REGISTERED (UdpSocket); TypeId UdpSocket::GetTypeId (void) { static TypeId tid = TypeId ("ns3::UdpSocket") .SetParent<Socket> () .AddAttribute ("RcvBufSize", "UdpSocket maximum receive buffer size (bytes)", UintegerValue (131072), MakeUintegerAccessor (&UdpSocket::GetRcvBufSize, &UdpSocket::SetRcvBufSize), MakeUintegerChecker<uint32_t> ()) .AddAttribute ("IpTtl", "socket-specific TTL for unicast IP packets (if non-zero)", UintegerValue (0), MakeUintegerAccessor (&UdpSocket::GetIpTtl, &UdpSocket::SetIpTtl), MakeUintegerChecker<uint8_t> ()) .AddAttribute ("IpMulticastTtl", "socket-specific TTL for multicast IP packets (if non-zero)", UintegerValue (0), MakeUintegerAccessor (&UdpSocket::GetIpMulticastTtl, &UdpSocket::SetIpMulticastTtl), MakeUintegerChecker<uint8_t> ()) .AddAttribute ("IpMulticastIf", "interface index for outgoing multicast on this socket; -1 indicates to use default interface", IntegerValue (-1), MakeIntegerAccessor (&UdpSocket::GetIpMulticastIf, &UdpSocket::SetIpMulticastIf), MakeIntegerChecker<int32_t> ()) .AddAttribute ("IpMulticastLoop", "whether outgoing multicast sent also to loopback interface", BooleanValue (false), MakeBooleanAccessor (&UdpSocket::GetIpMulticastLoop, &UdpSocket::SetIpMulticastLoop), MakeBooleanChecker ()) .AddAttribute ("MtuDiscover", "If enabled, every outgoing ip packet will have the DF flag set.", BooleanValue (false), MakeBooleanAccessor (&UdpSocket::SetMtuDiscover, &UdpSocket::GetMtuDiscover), MakeBooleanChecker ()) ; return tid; } UdpSocket::UdpSocket () { NS_LOG_FUNCTION_NOARGS (); } UdpSocket::~UdpSocket () { NS_LOG_FUNCTION_NOARGS (); } } // namespace ns3
zy901002-gpsr
src/internet/model/udp-socket.cc
C++
gpl2
3,427
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2005,2006,2007 INRIA * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr> */ #include "ipv4-interface.h" #include "loopback-net-device.h" #include "ns3/ipv4-address.h" #include "ipv4-l3-protocol.h" #include "arp-l3-protocol.h" #include "arp-cache.h" #include "ns3/net-device.h" #include "ns3/log.h" #include "ns3/packet.h" #include "ns3/node.h" #include "ns3/pointer.h" NS_LOG_COMPONENT_DEFINE ("Ipv4Interface"); namespace ns3 { NS_OBJECT_ENSURE_REGISTERED (Ipv4Interface); TypeId Ipv4Interface::GetTypeId (void) { static TypeId tid = TypeId ("ns3::Ipv4Interface") .SetParent<Object> () .AddAttribute ("ArpCache", "The arp cache for this ipv4 interface", PointerValue (0), MakePointerAccessor (&Ipv4Interface::SetArpCache, &Ipv4Interface::GetArpCache), MakePointerChecker<ArpCache> ()) ; ; return tid; } /** * By default, Ipv4 interface are created in the "down" state * with no IP addresses. Before becoming useable, the user must * invoke SetUp on them once an Ipv4 address and mask have been set. */ Ipv4Interface::Ipv4Interface () : m_ifup (false), m_forwarding (true), m_metric (1), m_node (0), m_device (0), m_cache (0) { NS_LOG_FUNCTION (this); } Ipv4Interface::~Ipv4Interface () { NS_LOG_FUNCTION_NOARGS (); } void Ipv4Interface::DoDispose (void) { NS_LOG_FUNCTION_NOARGS (); m_node = 0; m_device = 0; Object::DoDispose (); } void Ipv4Interface::SetNode (Ptr<Node> node) { m_node = node; DoSetup (); } void Ipv4Interface::SetDevice (Ptr<NetDevice> device) { m_device = device; DoSetup (); } void Ipv4Interface::DoSetup (void) { if (m_node == 0 || m_device == 0) { return; } if (!m_device->NeedsArp ()) { return; } Ptr<ArpL3Protocol> arp = m_node->GetObject<ArpL3Protocol> (); m_cache = arp->CreateCache (m_device, this); } Ptr<NetDevice> Ipv4Interface::GetDevice (void) const { return m_device; } void Ipv4Interface::SetMetric (uint16_t metric) { NS_LOG_FUNCTION (metric); m_metric = metric; } uint16_t Ipv4Interface::GetMetric (void) const { NS_LOG_FUNCTION_NOARGS (); return m_metric; } void Ipv4Interface::SetArpCache (Ptr<ArpCache> a) { m_cache = a; } Ptr<ArpCache> Ipv4Interface::GetArpCache () const { return m_cache; } /** * These are IP interface states and may be distinct from * NetDevice states, such as found in real implementations * (where the device may be down but IP interface state is still up). */ bool Ipv4Interface::IsUp (void) const { NS_LOG_FUNCTION_NOARGS (); return m_ifup; } bool Ipv4Interface::IsDown (void) const { NS_LOG_FUNCTION_NOARGS (); return !m_ifup; } void Ipv4Interface::SetUp (void) { NS_LOG_FUNCTION_NOARGS (); m_ifup = true; } void Ipv4Interface::SetDown (void) { NS_LOG_FUNCTION_NOARGS (); m_ifup = false; } bool Ipv4Interface::IsForwarding (void) const { NS_LOG_FUNCTION_NOARGS (); return m_forwarding; } void Ipv4Interface::SetForwarding (bool val) { NS_LOG_FUNCTION_NOARGS (); m_forwarding = val; } void Ipv4Interface::Send (Ptr<Packet> p, Ipv4Address dest) { NS_LOG_FUNCTION (dest << *p); if (!IsUp ()) { return; } // Check for a loopback device if (DynamicCast<LoopbackNetDevice> (m_device)) { // XXX additional checks needed here (such as whether multicast // goes to loopback)? m_device->Send (p, m_device->GetBroadcast (), Ipv4L3Protocol::PROT_NUMBER); return; } // is this packet aimed at a local interface ? for (Ipv4InterfaceAddressListCI i = m_ifaddrs.begin (); i != m_ifaddrs.end (); ++i) { if (dest == (*i).GetLocal ()) { Ptr<Ipv4L3Protocol> ipv4 = m_node->GetObject<Ipv4L3Protocol> (); ipv4->Receive (m_device, p, Ipv4L3Protocol::PROT_NUMBER, m_device->GetBroadcast (), m_device->GetBroadcast (), NetDevice::PACKET_HOST // note: linux uses PACKET_LOOPBACK here ); return; } } if (m_device->NeedsArp ()) { NS_LOG_LOGIC ("Needs ARP" << " " << dest); Ptr<ArpL3Protocol> arp = m_node->GetObject<ArpL3Protocol> (); Address hardwareDestination; bool found = false; if (dest.IsBroadcast ()) { NS_LOG_LOGIC ("All-network Broadcast"); hardwareDestination = m_device->GetBroadcast (); found = true; } else if (dest.IsMulticast ()) { NS_LOG_LOGIC ("IsMulticast"); NS_ASSERT_MSG (m_device->IsMulticast (), "ArpIpv4Interface::SendTo (): Sending multicast packet over " "non-multicast device"); hardwareDestination = m_device->GetMulticast (dest); found = true; } else { for (Ipv4InterfaceAddressListCI i = m_ifaddrs.begin (); i != m_ifaddrs.end (); ++i) { if (dest.IsSubnetDirectedBroadcast ((*i).GetMask ())) { NS_LOG_LOGIC ("Subnetwork Broadcast"); hardwareDestination = m_device->GetBroadcast (); found = true; break; } } if (!found) { NS_LOG_LOGIC ("ARP Lookup"); found = arp->Lookup (p, dest, m_device, m_cache, &hardwareDestination); } } if (found) { NS_LOG_LOGIC ("Address Resolved. Send."); m_device->Send (p, hardwareDestination, Ipv4L3Protocol::PROT_NUMBER); } } else { NS_LOG_LOGIC ("Doesn't need ARP"); m_device->Send (p, m_device->GetBroadcast (), Ipv4L3Protocol::PROT_NUMBER); } } uint32_t Ipv4Interface::GetNAddresses (void) const { NS_LOG_FUNCTION_NOARGS (); return m_ifaddrs.size (); } bool Ipv4Interface::AddAddress (Ipv4InterfaceAddress addr) { NS_LOG_FUNCTION_NOARGS (); m_ifaddrs.push_back (addr); return true; } Ipv4InterfaceAddress Ipv4Interface::GetAddress (uint32_t index) const { NS_LOG_FUNCTION_NOARGS (); if (index < m_ifaddrs.size ()) { uint32_t tmp = 0; for (Ipv4InterfaceAddressListCI i = m_ifaddrs.begin (); i!= m_ifaddrs.end (); i++) { if (tmp == index) { return *i; } ++tmp; } } NS_ASSERT (false); // Assert if not found Ipv4InterfaceAddress addr; return (addr); // quiet compiler } Ipv4InterfaceAddress Ipv4Interface::RemoveAddress (uint32_t index) { NS_LOG_FUNCTION_NOARGS (); if (index >= m_ifaddrs.size ()) { NS_ASSERT_MSG (false, "Bug in Ipv4Interface::RemoveAddress"); } Ipv4InterfaceAddressListI i = m_ifaddrs.begin (); uint32_t tmp = 0; while (i != m_ifaddrs.end ()) { if (tmp == index) { Ipv4InterfaceAddress addr = *i; m_ifaddrs.erase (i); return addr; } ++tmp; ++i; } NS_ASSERT_MSG (false, "Address " << index << " not found"); Ipv4InterfaceAddress addr; return (addr); // quiet compiler } } // namespace ns3
zy901002-gpsr
src/internet/model/ipv4-interface.cc
C++
gpl2
8,069
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007 Georgia Tech Research Corporation * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Raj Bhattacharjea <raj.b@gatech.edu> */ #ifndef TCP_SOCKET_FACTORY_H #define TCP_SOCKET_FACTORY_H #include "ns3/socket-factory.h" namespace ns3 { class Socket; /** * \ingroup socket * * \brief API to create TCP socket instances * * This abstract class defines the API for TCP sockets. * This class also holds the global default variables used to * initialize newly created sockets, such as values that are * set through the sysctl or proc interfaces in Linux. * All TCP socket factory implementations must provide an implementation * of CreateSocket * below, and should make use of the default values configured below. * * \see TcpSocketFactoryImpl * */ class TcpSocketFactory : public SocketFactory { public: static TypeId GetTypeId (void); }; } // namespace ns3 #endif /* TCP_SOCKET_FACTORY_H */
zy901002-gpsr
src/internet/model/tcp-socket-factory.h
C++
gpl2
1,617
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007-2009 Strasbourg University * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: David Gross <gdavid.devel@gmail.com> */ #include "ns3/assert.h" #include "ns3/log.h" #include "ns3/header.h" #include "ipv6-extension-header.h" namespace ns3 { NS_LOG_COMPONENT_DEFINE ("Ipv6ExtensionHeader"); NS_OBJECT_ENSURE_REGISTERED (Ipv6ExtensionHeader); TypeId Ipv6ExtensionHeader::GetTypeId () { static TypeId tid = TypeId ("ns3::Ipv6ExtensionHeader") .AddConstructor<Ipv6ExtensionHeader> () .SetParent<Header> () ; return tid; } TypeId Ipv6ExtensionHeader::GetInstanceTypeId () const { return GetTypeId (); } Ipv6ExtensionHeader::Ipv6ExtensionHeader () : m_nextHeader (0), m_length (0), m_data (0) { } Ipv6ExtensionHeader::~Ipv6ExtensionHeader () { } void Ipv6ExtensionHeader::SetNextHeader (uint8_t nextHeader) { m_nextHeader = nextHeader; } uint8_t Ipv6ExtensionHeader::GetNextHeader () const { return m_nextHeader; } void Ipv6ExtensionHeader::SetLength (uint16_t length) { m_length = (length >> 3) - 1; } uint16_t Ipv6ExtensionHeader::GetLength () const { return (m_length + 1) << 3; } void Ipv6ExtensionHeader::Print (std::ostream &os) const { os << "( nextHeader = " << (uint32_t)GetNextHeader () << " length = " << (uint32_t)GetLength () << " )"; } uint32_t Ipv6ExtensionHeader::GetSerializedSize () const { return 2; } void Ipv6ExtensionHeader::Serialize (Buffer::Iterator start) const { Buffer::Iterator i = start; i.WriteU8 (m_nextHeader); i.WriteU8 (m_length); i.Write (m_data.PeekData (), m_data.GetSize ()); } uint32_t Ipv6ExtensionHeader::Deserialize (Buffer::Iterator start) { Buffer::Iterator i = start; m_nextHeader = i.ReadU8 (); m_length = i.ReadU8 (); uint32_t dataLength = GetLength () - 2; uint8_t* data = new uint8_t[dataLength]; i.Read (data, dataLength); if (dataLength > m_data.GetSize ()) { m_data.AddAtEnd (dataLength - m_data.GetSize ()); } else { m_data.RemoveAtEnd (m_data.GetSize () - dataLength); } i = m_data.Begin (); i.Write (data, dataLength); delete[] data; return GetSerializedSize (); } OptionField::OptionField (uint32_t optionsOffset) : m_optionData (0), m_optionsOffset (optionsOffset) { } OptionField::~OptionField () { } uint32_t OptionField::GetSerializedSize () const { return m_optionData.GetSize () + CalculatePad ((Ipv6OptionHeader::Alignment) { 8,0}); } void OptionField::Serialize (Buffer::Iterator start) const { start.Write (m_optionData.Begin (), m_optionData.End ()); uint32_t fill = CalculatePad ((Ipv6OptionHeader::Alignment) { 8,0}); NS_LOG_LOGIC ("fill with " << fill << " bytes padding"); switch (fill) { case 0: return; case 1: Ipv6OptionPad1Header ().Serialize (start); return; default: Ipv6OptionPadnHeader (fill).Serialize (start); return; } } uint32_t OptionField::Deserialize (Buffer::Iterator start, uint32_t length) { uint8_t* buf = new uint8_t[length]; start.Read (buf, length); m_optionData = Buffer (); m_optionData.AddAtEnd (length); m_optionData.Begin ().Write (buf, length); delete[] buf; return length; } void OptionField::AddOption (Ipv6OptionHeader const& option) { NS_LOG_FUNCTION_NOARGS (); uint32_t pad = CalculatePad (option.GetAlignment ()); NS_LOG_LOGIC ("need " << pad << " bytes padding"); switch (pad) { case 0: break; //no padding needed case 1: AddOption (Ipv6OptionPad1Header ()); break; default: AddOption (Ipv6OptionPadnHeader (pad)); break; } m_optionData.AddAtEnd (option.GetSerializedSize ()); Buffer::Iterator it = m_optionData.End (); it.Prev (option.GetSerializedSize ()); option.Serialize (it); } uint32_t OptionField::CalculatePad (Ipv6OptionHeader::Alignment alignment) const { return (alignment.offset - (m_optionData.GetSize () + m_optionsOffset)) % alignment.factor; } uint32_t OptionField::GetOptionsOffset () { return m_optionsOffset; } Buffer OptionField::GetOptionBuffer () { return m_optionData; } NS_OBJECT_ENSURE_REGISTERED (Ipv6ExtensionHopByHopHeader); TypeId Ipv6ExtensionHopByHopHeader::GetTypeId () { static TypeId tid = TypeId ("ns3::Ipv6ExtensionHopByHopHeader") .AddConstructor<Ipv6ExtensionHopByHopHeader> () .SetParent<Ipv6ExtensionHeader> () ; return tid; } TypeId Ipv6ExtensionHopByHopHeader::GetInstanceTypeId () const { return GetTypeId (); } Ipv6ExtensionHopByHopHeader::Ipv6ExtensionHopByHopHeader () : OptionField (2) { } Ipv6ExtensionHopByHopHeader::~Ipv6ExtensionHopByHopHeader () { } void Ipv6ExtensionHopByHopHeader::Print (std::ostream &os) const { os << "( nextHeader = " << (uint32_t)GetNextHeader () << " length = " << (uint32_t)GetLength () << " )"; } uint32_t Ipv6ExtensionHopByHopHeader::GetSerializedSize () const { return 2 + OptionField::GetSerializedSize (); } void Ipv6ExtensionHopByHopHeader::Serialize (Buffer::Iterator start) const { Buffer::Iterator i = start; i.WriteU8 (GetNextHeader ()); i.WriteU8 ((GetLength () >> 3) - 1); OptionField::Serialize (i); } uint32_t Ipv6ExtensionHopByHopHeader::Deserialize (Buffer::Iterator start) { Buffer::Iterator i = start; SetNextHeader (i.ReadU8 ()); SetLength ((i.ReadU8 () + 1) << 3); OptionField::Deserialize (i, GetLength () - 2); return GetSerializedSize (); } NS_OBJECT_ENSURE_REGISTERED (Ipv6ExtensionDestinationHeader); TypeId Ipv6ExtensionDestinationHeader::GetTypeId () { static TypeId tid = TypeId ("ns3::Ipv6ExtensionDestinationHeader") .AddConstructor<Ipv6ExtensionDestinationHeader> () .SetParent<Ipv6ExtensionHeader> () ; return tid; } TypeId Ipv6ExtensionDestinationHeader::GetInstanceTypeId () const { return GetTypeId (); } Ipv6ExtensionDestinationHeader::Ipv6ExtensionDestinationHeader () : OptionField (2) { } Ipv6ExtensionDestinationHeader::~Ipv6ExtensionDestinationHeader () { } void Ipv6ExtensionDestinationHeader::Print (std::ostream &os) const { os << "( nextHeader = " << (uint32_t)GetNextHeader () << " length = " << (uint32_t)GetLength () << " )"; } uint32_t Ipv6ExtensionDestinationHeader::GetSerializedSize () const { return 2 + OptionField::GetSerializedSize (); } void Ipv6ExtensionDestinationHeader::Serialize (Buffer::Iterator start) const { Buffer::Iterator i = start; i.WriteU8 (GetNextHeader ()); i.WriteU8 ((GetLength () >> 3) - 1); OptionField::Serialize (i); } uint32_t Ipv6ExtensionDestinationHeader::Deserialize (Buffer::Iterator start) { Buffer::Iterator i = start; SetNextHeader (i.ReadU8 ()); SetLength ((i.ReadU8 () + 1) << 3); OptionField::Deserialize (i, GetLength () - 2); return GetSerializedSize (); } NS_OBJECT_ENSURE_REGISTERED (Ipv6ExtensionFragmentHeader); TypeId Ipv6ExtensionFragmentHeader::GetTypeId () { static TypeId tid = TypeId ("ns3::Ipv6ExtensionFragmentHeader") .AddConstructor<Ipv6ExtensionFragmentHeader> () .SetParent<Ipv6ExtensionHeader> () ; return tid; } TypeId Ipv6ExtensionFragmentHeader::GetInstanceTypeId () const { return GetTypeId (); } Ipv6ExtensionFragmentHeader::Ipv6ExtensionFragmentHeader () : m_offset (0), m_identification (0) { } Ipv6ExtensionFragmentHeader::~Ipv6ExtensionFragmentHeader () { } void Ipv6ExtensionFragmentHeader::SetOffset (uint16_t offset) { // Clear the offset, and save the MF bit m_offset &= 1; m_offset |= offset & (~7); } uint16_t Ipv6ExtensionFragmentHeader::GetOffset () const { return m_offset & (~1); } void Ipv6ExtensionFragmentHeader::SetMoreFragment (bool moreFragment) { m_offset = moreFragment ? m_offset | 1 : m_offset & (~1); } bool Ipv6ExtensionFragmentHeader::GetMoreFragment () const { return m_offset & 1; } void Ipv6ExtensionFragmentHeader::SetIdentification (uint32_t identification) { m_identification = identification; } uint32_t Ipv6ExtensionFragmentHeader::GetIdentification () const { return m_identification; } void Ipv6ExtensionFragmentHeader::Print (std::ostream &os) const { os << "( nextHeader = " << (uint32_t)GetNextHeader () << " length = " << (uint32_t)GetLength () << " offset = " << (uint32_t)GetOffset () << " MF = " << (uint32_t)GetMoreFragment () << " identification = " << (uint32_t)m_identification << " )"; } uint32_t Ipv6ExtensionFragmentHeader::GetSerializedSize () const { return 8; } void Ipv6ExtensionFragmentHeader::Serialize (Buffer::Iterator start) const { Buffer::Iterator i = start; i.WriteU8 (GetNextHeader ()); i.WriteU8 ((GetLength () >> 3) - 1); i.WriteHtonU16 (m_offset); i.WriteHtonU32 (m_identification); } uint32_t Ipv6ExtensionFragmentHeader::Deserialize (Buffer::Iterator start) { Buffer::Iterator i = start; SetNextHeader (i.ReadU8 ()); SetLength ((i.ReadU8 () + 1) << 3); m_offset = i.ReadNtohU16 (); m_identification = i.ReadNtohU32 (); return GetSerializedSize (); } NS_OBJECT_ENSURE_REGISTERED (Ipv6ExtensionRoutingHeader); TypeId Ipv6ExtensionRoutingHeader::GetTypeId () { static TypeId tid = TypeId ("ns3::Ipv6ExtensionRoutingHeader") .AddConstructor<Ipv6ExtensionRoutingHeader> () .SetParent<Ipv6ExtensionHeader> () ; return tid; } TypeId Ipv6ExtensionRoutingHeader::GetInstanceTypeId () const { return GetTypeId (); } Ipv6ExtensionRoutingHeader::Ipv6ExtensionRoutingHeader () : m_typeRouting (0), m_segmentsLeft (0) { } Ipv6ExtensionRoutingHeader::~Ipv6ExtensionRoutingHeader () { } void Ipv6ExtensionRoutingHeader::SetTypeRouting (uint8_t typeRouting) { m_typeRouting = typeRouting; } uint8_t Ipv6ExtensionRoutingHeader::GetTypeRouting () const { return m_typeRouting; } void Ipv6ExtensionRoutingHeader::SetSegmentsLeft (uint8_t segmentsLeft) { m_segmentsLeft = segmentsLeft; } uint8_t Ipv6ExtensionRoutingHeader::GetSegmentsLeft () const { return m_segmentsLeft; } void Ipv6ExtensionRoutingHeader::Print (std::ostream &os) const { os << "( nextHeader = " << (uint32_t)GetNextHeader () << " length = " << (uint32_t)GetLength () << " typeRouting = " << (uint32_t)m_typeRouting << " segmentsLeft = " << (uint32_t)m_segmentsLeft << " )"; } uint32_t Ipv6ExtensionRoutingHeader::GetSerializedSize () const { return 4; } void Ipv6ExtensionRoutingHeader::Serialize (Buffer::Iterator start) const { Buffer::Iterator i = start; i.WriteU8 (GetNextHeader ()); i.WriteU8 ((GetLength () >> 3) - 1); i.WriteU8 (m_typeRouting); i.WriteU8 (m_segmentsLeft); } uint32_t Ipv6ExtensionRoutingHeader::Deserialize (Buffer::Iterator start) { Buffer::Iterator i = start; SetNextHeader (i.ReadU8 ()); SetLength ((i.ReadU8 () + 1) << 3); m_typeRouting = i.ReadU8 (); m_segmentsLeft = i.ReadU8 (); return GetSerializedSize (); } NS_OBJECT_ENSURE_REGISTERED (Ipv6ExtensionLooseRoutingHeader); TypeId Ipv6ExtensionLooseRoutingHeader::GetTypeId () { static TypeId tid = TypeId ("ns3::Ipv6ExtensionLooseRoutingHeader") .AddConstructor<Ipv6ExtensionLooseRoutingHeader> () .SetParent<Ipv6ExtensionRoutingHeader> () ; return tid; } TypeId Ipv6ExtensionLooseRoutingHeader::GetInstanceTypeId () const { return GetTypeId (); } Ipv6ExtensionLooseRoutingHeader::Ipv6ExtensionLooseRoutingHeader () : m_routersAddress (0) { } Ipv6ExtensionLooseRoutingHeader::~Ipv6ExtensionLooseRoutingHeader () { } void Ipv6ExtensionLooseRoutingHeader::SetNumberAddress (uint8_t n) { m_routersAddress.clear (); m_routersAddress.assign (n, Ipv6Address ("")); } void Ipv6ExtensionLooseRoutingHeader::SetRoutersAddress (std::vector<Ipv6Address> routersAddress) { m_routersAddress = routersAddress; } std::vector<Ipv6Address> Ipv6ExtensionLooseRoutingHeader::GetRoutersAddress () const { return m_routersAddress; } void Ipv6ExtensionLooseRoutingHeader::SetRouterAddress (uint8_t index, Ipv6Address addr) { m_routersAddress.at (index) = addr; } Ipv6Address Ipv6ExtensionLooseRoutingHeader::GetRouterAddress (uint8_t index) const { return m_routersAddress.at (index); } void Ipv6ExtensionLooseRoutingHeader::Print (std::ostream &os) const { os << "( nextHeader = " << (uint32_t)GetNextHeader () << " length = " << (uint32_t)GetLength () << " typeRouting = " << (uint32_t)GetTypeRouting () << " segmentsLeft = " << (uint32_t)GetSegmentsLeft () << " "; for (std::vector<Ipv6Address>::const_iterator it = m_routersAddress.begin (); it != m_routersAddress.end (); it++) { os << *it << " "; } os << " )"; } uint32_t Ipv6ExtensionLooseRoutingHeader::GetSerializedSize () const { return 8 + m_routersAddress.size () * 16; } void Ipv6ExtensionLooseRoutingHeader::Serialize (Buffer::Iterator start) const { Buffer::Iterator i = start; uint8_t buff[16]; i.WriteU8 (GetNextHeader ()); i.WriteU8 ((GetLength () >> 3) - 1); i.WriteU8 (GetTypeRouting ()); i.WriteU8 (GetSegmentsLeft ()); i.WriteU32 (0); for (VectorIpv6Address_t::const_iterator it = m_routersAddress.begin (); it != m_routersAddress.end (); it++) { it->Serialize (buff); i.Write (buff, 16); } } uint32_t Ipv6ExtensionLooseRoutingHeader::Deserialize (Buffer::Iterator start) { Buffer::Iterator i = start; uint8_t buff[16]; SetNextHeader (i.ReadU8 ()); SetLength ((i.ReadU8 () + 1) << 3); SetTypeRouting (i.ReadU8 ()); SetSegmentsLeft (i.ReadU8 ()); i.ReadU32 (); for (std::vector<Ipv6Address>::iterator it = m_routersAddress.begin (); it != m_routersAddress.end (); it++) { i.Read (buff, 16); it->Set (buff); } return GetSerializedSize (); } NS_OBJECT_ENSURE_REGISTERED (Ipv6ExtensionESPHeader); TypeId Ipv6ExtensionESPHeader::GetTypeId () { static TypeId tid = TypeId ("ns3::Ipv6ExtensionESPHeader") .AddConstructor<Ipv6ExtensionESPHeader> () .SetParent<Ipv6ExtensionHeader> () ; return tid; } TypeId Ipv6ExtensionESPHeader::GetInstanceTypeId () const { return GetTypeId (); } Ipv6ExtensionESPHeader::Ipv6ExtensionESPHeader () { } Ipv6ExtensionESPHeader::~Ipv6ExtensionESPHeader () { } void Ipv6ExtensionESPHeader::Print (std::ostream &os) const { /* TODO */ } uint32_t Ipv6ExtensionESPHeader::GetSerializedSize () const { /* TODO */ return 0; } void Ipv6ExtensionESPHeader::Serialize (Buffer::Iterator start) const { /* TODO */ } uint32_t Ipv6ExtensionESPHeader::Deserialize (Buffer::Iterator start) { /* TODO */ return 0; } NS_OBJECT_ENSURE_REGISTERED (Ipv6ExtensionAHHeader); TypeId Ipv6ExtensionAHHeader::GetTypeId () { static TypeId tid = TypeId ("ns3::Ipv6ExtensionAHHeader") .AddConstructor<Ipv6ExtensionAHHeader> () .SetParent<Ipv6ExtensionHeader> () ; return tid; } TypeId Ipv6ExtensionAHHeader::GetInstanceTypeId () const { return GetTypeId (); } Ipv6ExtensionAHHeader::Ipv6ExtensionAHHeader () { } Ipv6ExtensionAHHeader::~Ipv6ExtensionAHHeader () { } void Ipv6ExtensionAHHeader::Print (std::ostream &os) const { /* TODO */ } uint32_t Ipv6ExtensionAHHeader::GetSerializedSize () const { /* TODO */ return 0; } void Ipv6ExtensionAHHeader::Serialize (Buffer::Iterator start) const { /* TODO */ } uint32_t Ipv6ExtensionAHHeader::Deserialize (Buffer::Iterator start) { /* TODO */ return 0; } } /* namespace ns3 */
zy901002-gpsr
src/internet/model/ipv6-extension-header.cc
C++
gpl2
15,827
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007-2009 Strasbourg University * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Sebastien Vincent <vincent@clarinet.u-strasbg.fr> */ #ifndef IPV6_INTERFACE_H #define IPV6_INTERFACE_H #include <list> #include "ns3/ipv6-address.h" #include "ns3/ipv6-interface-address.h" #include "ns3/ptr.h" #include "ns3/object.h" #include "ns3/timer.h" namespace ns3 { class NetDevice; class Packet; class Node; class NdiscCache; /** * \class Ipv6Interface * \brief The IPv6 representation of a network interface * * By default IPv6 interfaces are created in the "down" state * with IP "fe80::1" and a /64 prefix. Before becoming useable, * the user must invoke SetUp on them once the final IPv6 address * and mask has been set. */ class Ipv6Interface : public Object { public: /** * \brief Get the type ID * \return type ID */ static TypeId GetTypeId (); /** * \brief Constructs an Ipv6Interface. */ Ipv6Interface (); /** * \brief Destructor. */ virtual ~Ipv6Interface (); /** * \brief Set node associated with interface. * \param node node */ void SetNode (Ptr<Node> node); /** * \brief Set the NetDevice. * \param device NetDevice */ void SetDevice (Ptr<NetDevice> device); /** * \brief Get the NetDevice. * \return the NetDevice associated with this interface */ virtual Ptr<NetDevice> GetDevice () const; /** * \brief Set the metric. * \param metric configured routing metric (cost) of this interface */ void SetMetric (uint16_t metric); /** * \brief Get the metric * \return the metric */ uint16_t GetMetric () const; /** * \brief Is the interface UP ? * \return true if interface is enabled, false otherwise. */ bool IsUp () const; /** * \brief Is the interface DOWN ? * \return true if interface is disabled, false otherwise. */ bool IsDown () const; /** * \brief Enable this interface. */ void SetUp (); /** * \brief Disable this interface. */ void SetDown (); /** * \brief If the interface allows forwarding packets. * \return true if forwarding is enabled, false otherwise */ bool IsForwarding () const; /** * \brief Set forwarding enabled or not. * \param forward forwarding state */ void SetForwarding (bool forward); /** * \brief Set the current hop limit. * \param curHopLimit the value to set */ void SetCurHopLimit (uint8_t curHopLimit); /** * \brief Get the current hop limit value. * \return current hop limit */ uint8_t GetCurHopLimit () const; /** * \brief Set the base reachable time. * \param baseReachableTime the value to set */ void SetBaseReachableTime (uint16_t baseReachableTime); /** * \brief Get the base reachable time. * \return base reachable time */ uint16_t GetBaseReachableTime () const; /** * \brief Set the reachable time. * \param reachableTime value to set */ void SetReachableTime (uint16_t reachableTime); /** * \brief Get the reachable time. * \return reachable time */ uint16_t GetReachableTime () const; /** * \brief Set the retransmission timer. * \param retransTimer value to set */ void SetRetransTimer (uint16_t retransTimer); /** * \brief Get the retransmission timer. * \return retransmission timer */ uint16_t GetRetransTimer () const; /** * \brief Send a packet through this interface. * \param p packet to send * \param dest next hop address of packet. * * \note This method will eventually call the private SendTo * method which must be implemented by subclasses. */ void Send (Ptr<Packet> p, Ipv6Address dest); /** * \brief Add an IPv6 address. * \param iface address to add * \return true if address was added, false otherwise */ bool AddAddress (Ipv6InterfaceAddress iface); /** * \brief Get link-local address from IPv6 interface. * \return link-local Ipv6InterfaceAddress, assert if not found */ Ipv6InterfaceAddress GetLinkLocalAddress () const; /** * \brief Get an address from IPv6 interface. * \param index index * \return Ipv6InterfaceAddress address whose index is i */ Ipv6InterfaceAddress GetAddress (uint32_t index) const; /** * \brief Get an address which is in the same network prefix as destination. * \param dst destination address * \return Corresponding Ipv6InterfaceAddress or assert if not found */ Ipv6InterfaceAddress GetAddressMatchingDestination (Ipv6Address dst); /** * \brief Get number of addresses on this IPv6 interface. * \return number of address */ uint32_t GetNAddresses (void) const; /** * \brief Remove an address from interface. * \param index index to remove * \return Ipv6InterfaceAddress address whose index is index */ Ipv6InterfaceAddress RemoveAddress (uint32_t index); /** * \brief Update state of an interface address. * \param address IPv6 address * \param state new state */ void SetState (Ipv6Address address, Ipv6InterfaceAddress::State_e state); /** * \brief Update NS DAD packet UID of an interface address. * \param address IPv6 address * \param uid packet UID */ void SetNsDadUid (Ipv6Address address, uint32_t uid); protected: /** * \brief Dispose this object. */ virtual void DoDispose (); private: typedef std::list<Ipv6InterfaceAddress> Ipv6InterfaceAddressList; typedef std::list<Ipv6InterfaceAddress>::iterator Ipv6InterfaceAddressListI; typedef std::list<Ipv6InterfaceAddress>::const_iterator Ipv6InterfaceAddressListCI; /** * \brief Initialize interface. */ void DoSetup (); /** * \brief The addresses assigned to this interface. */ Ipv6InterfaceAddressList m_addresses; /** * \brief The state of this interface. */ bool m_ifup; /** * \brief Forwarding state. */ bool m_forwarding; /** * \brief The metric. */ uint16_t m_metric; /** * \brief Node associated with this interface. */ Ptr<Node> m_node; /** * \brief NetDevice associated with this interface. */ Ptr<NetDevice> m_device; /** * \brief Neighbor cache. */ Ptr<NdiscCache> m_ndCache; /** * \brief Current hop limit. */ uint8_t m_curHopLimit; /** * \brief Base value used for computing the random reachable time value (in millisecond). */ uint16_t m_baseReachableTime; /** * \brief Reachable time (in millisecond). * The time a neighbor is considered reachable after receiving a reachability confirmation. */ uint16_t m_reachableTime; /** * \brief Retransmission timer (in millisecond). * Time between retransmission of NS. */ uint16_t m_retransTimer; }; } /* namespace ns3 */ #endif /* IPV6_INTERFACE_H */
zy901002-gpsr
src/internet/model/ipv6-interface.h
C++
gpl2
7,495
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2008 University of Washington * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #ifndef IPV4_INTERFACE_ADDRESS_H #define IPV4_INTERFACE_ADDRESS_H #include <stdint.h> #include <ostream> #include "ns3/ipv4-address.h" namespace ns3 { /** * \ingroup address * * \brief a class to store IPv4 address information on an interface * * Corresponds to Linux struct in_ifaddr. A list of these addresses * is stored in Ipv4Interface. This class is modelled after how current * Linux handles IP aliasing for IPv4. Notably, aliasing of IPv4 * interfaces (e.g., "eth0:1") is not used, and instead an interface * is assigned possibly multiple addresses, with each address being * classified as being primary and secondary. See the iproute2 * documentation for this distinction. */ class Ipv4InterfaceAddress { public: enum InterfaceAddressScope_e { HOST, LINK, GLOBAL }; Ipv4InterfaceAddress (); // Configure m_local, m_mask, and m_broadcast from the below constructor Ipv4InterfaceAddress (Ipv4Address local, Ipv4Mask mask); Ipv4InterfaceAddress (const Ipv4InterfaceAddress &o); void SetLocal (Ipv4Address local); Ipv4Address GetLocal (void) const; void SetMask (Ipv4Mask mask); Ipv4Mask GetMask (void) const; void SetBroadcast (Ipv4Address broadcast); Ipv4Address GetBroadcast (void) const; void SetScope (Ipv4InterfaceAddress::InterfaceAddressScope_e scope); Ipv4InterfaceAddress::InterfaceAddressScope_e GetScope (void) const; bool IsSecondary (void) const; void SetSecondary (void); void SetPrimary (void); private: Ipv4Address m_local; // Interface address // Note: m_peer may be added in future when necessary // Ipv4Address m_peer; // Peer destination address (in Linux: m_address) Ipv4Mask m_mask; // Network mask Ipv4Address m_broadcast; // Broadcast address InterfaceAddressScope_e m_scope; bool m_secondary; // For use in multihoming friend bool operator == (Ipv4InterfaceAddress const &a, Ipv4InterfaceAddress const &b); friend bool operator != (Ipv4InterfaceAddress const &a, Ipv4InterfaceAddress const &b); }; std::ostream& operator<< (std::ostream& os, const Ipv4InterfaceAddress &addr); inline bool operator == (const Ipv4InterfaceAddress &a, const Ipv4InterfaceAddress &b) { return (a.m_local == b.m_local && a.m_mask == b.m_mask && a.m_broadcast == b.m_broadcast && a.m_scope == b.m_scope && a.m_secondary == b.m_secondary); } inline bool operator != (const Ipv4InterfaceAddress &a, const Ipv4InterfaceAddress &b) { return (a.m_local != b.m_local || a.m_mask != b.m_mask || a.m_broadcast != b.m_broadcast || a.m_scope != b.m_scope || a.m_secondary != b.m_secondary); } } // namespace ns3 #endif /* IPV4_ADDRESS_H */
zy901002-gpsr
src/internet/model/ipv4-interface-address.h
C++
gpl2
3,464
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2008 INRIA * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr> */ #ifndef IPV6_RAW_SOCKET_FACTORY_IMPL_H #define IPV6_RAW_SOCKET_FACTORY_IMPL_H #include "ns3/ipv6-raw-socket-factory.h" namespace ns3 { /** * \class Ipv6RawSocketFactoryImpl * \brief Implementation of IPv6 raw socket factory. */ class Ipv6RawSocketFactoryImpl : public Ipv6RawSocketFactory { public: /** * \brief Create a raw IPv6 socket. */ virtual Ptr<Socket> CreateSocket (); }; } /* namespace ns3 */ #endif /* IPV6_RAW_SOCKET_FACTORY_IMPL_H */
zy901002-gpsr
src/internet/model/ipv6-raw-socket-factory-impl.h
C++
gpl2
1,281
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007 INRIA * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr> */ #ifndef IPV4_RAW_SOCKET_FACTORY_H #define IPV4_RAW_SOCKET_FACTORY_H #include "ns3/socket-factory.h" namespace ns3 { class Socket; /** * \ingroup socket * * \brief API to create RAW socket instances * * This abstract class defines the API for RAW socket factory. * */ class Ipv4RawSocketFactory : public SocketFactory { public: static TypeId GetTypeId (void); }; } // namespace ns3 #endif /* IPV4_RAW_SOCKET_FACTORY_H */
zy901002-gpsr
src/internet/model/ipv4-raw-socket-factory.h
C++
gpl2
1,252
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ // // Copyright (c) 2006 Georgia Tech Research Corporation // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation; // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Author: Rajib Bhattacharjea<raj.b@gatech.edu> // // Georgia Tech Network Simulator - Data Descriptors // George F. Riley. Georgia Tech, Spring 2002 #ifndef PENDING_DATA_H #define PENDING_DATA_H #include "ns3/packet.h" #include "pending-data.h" #include "ns3/sequence-number.h" #include "ns3/ptr.h" namespace ns3 { class Packet; /** * \ingroup tcp * * \brief class for managing I/O between applications and TCP */ class PendingData { public: PendingData (); PendingData (uint32_t s, uint8_t* d = NULL, uint32_t msg = 0, uint32_t resp = 0); PendingData (const std::string&); // Construct from string PendingData (uint8_t*, uint32_t&, Packet*); // Construct from serialized buffer PendingData (const PendingData&); // Copy constructor virtual ~PendingData (); // Destructor uint32_t Size () const { return size; } // Serialization uint8_t* Serialize (uint8_t*, uint32_t&); // Serialize to a buffer uint8_t* Construct (uint8_t*, uint32_t&); // Construct from buffer virtual void Clear (); // Remove all associated data virtual void Add (uint32_t s, const uint8_t* d = 0); // Add some data to end virtual void Add (Ptr<Packet> p); /** * This method returns the number of bytes in the PendingData buffer * beyond the sequence number specified by seqOffset. * * The variables seqFront and seqOffset correspond to a sequence number * space in use by the user. What is significant in this method is the * difference between them; i.e. the quantity (seqOffset - seqFront). * This difference is subtracted from Size(), yielding the number of * bytes beyond seqOffset, from the user perspective, in the PendingData * buffer. * * If the first number specified is not a sequence number that corresponds * to the first data byte in the PendingData buffer, the computation * returned will be in error. * * \return number of bytes * \param seqFront sequence number of assumed first byte in the PendingData * \param seqOffset sequence number of offset */ virtual uint32_t SizeFromSeq (const SequenceNumber32& seqFront, const SequenceNumber32& seqOffset); // Inquire available data from offset /** * \return number of bytes in the data buffer beyond the offset specified * \param offset offset (from zero) */ virtual uint32_t SizeFromOffset (uint32_t offset); // Available size from sequence difference /** * Subtracts seqFront from seqOffset after enforcing seqFront is less * than seqOffset * * \param seqFront sequence number to be subtracted from seqOffset * \param seqOffset higher sequence number * \return seqOffset-seqFront */ virtual uint32_t OffsetFromSeq (const SequenceNumber32& seqFront, const SequenceNumber32& seqOffset); virtual Ptr<Packet> CopyFromOffset (uint32_t, uint32_t); // Size, offset, ret packet // Copy data, size, offset specified by sequence difference virtual Ptr<Packet> CopyFromSeq (uint32_t, const SequenceNumber32&, const SequenceNumber32&); /** * Permits object to clear any pending data between seqFront and * seqOffset - 1). Callers should check the return value to determine * whether any data was removed from the front. * * \param seqFront sequence number to start to try to remove from * \param seqOffset first sequence number in buffer that should be retained * \return number of bytes from the front that were removed from the buffer */ virtual uint32_t RemoveToSeq (const SequenceNumber32& seqFront, const SequenceNumber32& seqOffset); PendingData* Copy () const; // Create a copy of this header PendingData* CopyS (uint32_t); // Copy with new size PendingData* CopySD (uint32_t, uint8_t*); // Copy with new size, new data public: uint32_t size; // Number of data bytes std::vector<Ptr<Packet> > data; // Corresponding data (may be null) // The next two fields allow simulated applications to exchange some info uint32_t msgSize; // Total size of message uint32_t responseSize; // Size of response requested }; } //namepsace ns3 #endif /* PENDING_DATA_H */
zy901002-gpsr
src/internet/model/pending-data.h
C++
gpl2
4,913
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2009 University of Washington * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef IPV6_LIST_ROUTING_H #define IPV6_LIST_ROUTING_H #include <list> #include "ns3/ipv6-routing-protocol.h" namespace ns3 { /** * \ingroup internet * \defgroup ipv6ListRouting Ipv6 List Routing */ /** * \ingroup ipv6ListRouting * \class Ipv6ListRouting * \brief Hold list of Ipv6RoutingProtocol objects. * * This class is a specialization of Ipv6RoutingProtocol that allows * other instances of Ipv6RoutingProtocol to be inserted in a * prioritized list. Routing protocols in the list are consulted one * by one, from highest to lowest priority, until a routing protocol * is found that will take the packet (this corresponds to a non-zero * return value to RouteOutput, or a return value of true to RouteInput). * The order by which routing protocols with the same priority value * are consulted is undefined. * */ class Ipv6ListRouting : public Ipv6RoutingProtocol { public: /** * \brief Get the type ID of this class. * \return type ID */ static TypeId GetTypeId (void); /** * \brief Constructor. */ Ipv6ListRouting (); /** * \brief Destructor. */ virtual ~Ipv6ListRouting (); /** * \brief Register a new routing protocol to be used in this IPv4 stack * \param routingProtocol new routing protocol implementation object * \param priority priority to give to this routing protocol. * Values may range between -32768 and +32767. */ virtual void AddRoutingProtocol (Ptr<Ipv6RoutingProtocol> routingProtocol, int16_t priority); /** * \brief Get the number of routing protocols. * \return number of routing protocols in the list */ virtual uint32_t GetNRoutingProtocols (void) const; /** * \brief Get pointer to routing protocol stored at index, * * The first protocol (index 0) the highest priority, the next one (index 1) * the second highest priority, and so on. The priority parameter is an * output parameter and it returns the integer priority of the protocol. * \param index index of protocol to return * \param priority output parameter, set to the priority of the protocol * being returned * \return pointer to routing protocol indexed by */ virtual Ptr<Ipv6RoutingProtocol> GetRoutingProtocol (uint32_t index, int16_t& priority) const; // Below are from Ipv6RoutingProtocol virtual Ptr<Ipv6Route> RouteOutput (Ptr<Packet> p, const Ipv6Header &header, Ptr<NetDevice> oif, Socket::SocketErrno &sockerr); virtual bool RouteInput (Ptr<const Packet> p, const Ipv6Header &header, Ptr<const NetDevice> idev, UnicastForwardCallback ucb, MulticastForwardCallback mcb, LocalDeliverCallback lcb, ErrorCallback ecb); virtual void NotifyInterfaceUp (uint32_t interface); virtual void NotifyInterfaceDown (uint32_t interface); virtual void NotifyAddAddress (uint32_t interface, Ipv6InterfaceAddress address); virtual void NotifyRemoveAddress (uint32_t interface, Ipv6InterfaceAddress address); virtual void NotifyAddRoute (Ipv6Address dst, Ipv6Prefix mask, Ipv6Address nextHop, uint32_t interface, Ipv6Address prefixToUse = Ipv6Address::GetZero ()); virtual void NotifyRemoveRoute (Ipv6Address dst, Ipv6Prefix mask, Ipv6Address nextHop, uint32_t interface, Ipv6Address prefixToUse = Ipv6Address::GetZero ()); virtual void SetIpv6 (Ptr<Ipv6> ipv6); protected: /** * \brief Dispose this object. */ void DoDispose (void); private: typedef std::pair<int16_t, Ptr<Ipv6RoutingProtocol> > Ipv6RoutingProtocolEntry; typedef std::list<Ipv6RoutingProtocolEntry> Ipv6RoutingProtocolList; /** * \brief Compare two routing protocols. * \param a first object to compare * \param b second object to compare * \return true if they are the same, false otherwise */ static bool Compare (const Ipv6RoutingProtocolEntry& a, const Ipv6RoutingProtocolEntry& b); /** * \brief List of routing protocols. */ Ipv6RoutingProtocolList m_routingProtocols; /** * \brief Ipv6 reference. */ Ptr<Ipv6> m_ipv6; }; } // namespace ns3 #endif /* IPV6_LIST_ROUTING_H */
zy901002-gpsr
src/internet/model/ipv6-list-routing.h
C++
gpl2
4,872
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2005,2006,2007 INRIA * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Authors: * Mathieu Lacage <mathieu.lacage@sophia.inria.fr>, * Tom Henderson <tomh@tomh.org> */ #ifndef IPV4_INTERFACE_H #define IPV4_INTERFACE_H #include <list> #include "ns3/ipv4-address.h" #include "ns3/ipv4-interface-address.h" #include "ns3/ptr.h" #include "ns3/object.h" namespace ns3 { class NetDevice; class Packet; class Node; class ArpCache; /** * \brief The IPv4 representation of a network interface * * This class roughly corresponds to the struct in_device * of Linux; the main purpose is to provide address-family * specific information (addresses) about an interface. * * By default, Ipv4 interface are created in the "down" state * no IP addresses. Before becoming useable, the user must * add an address of some type and invoke Setup on them. */ class Ipv4Interface : public Object { public: static TypeId GetTypeId (void); Ipv4Interface (); virtual ~Ipv4Interface(); void SetNode (Ptr<Node> node); void SetDevice (Ptr<NetDevice> device); void SetArpCache (Ptr<ArpCache>); /** * \returns the underlying NetDevice. This method cannot return zero. */ Ptr<NetDevice> GetDevice (void) const; /** * \return ARP cache used by this interface */ Ptr<ArpCache> GetArpCache () const; /** * \param metric configured routing metric (cost) of this interface * * Note: This is synonymous to the Metric value that ifconfig prints * out. It is used by ns-3 global routing, but other routing daemons * choose to ignore it. */ void SetMetric (uint16_t metric); /** * \returns configured routing metric (cost) of this interface * * Note: This is synonymous to the Metric value that ifconfig prints * out. It is used by ns-3 global routing, but other routing daemons * may choose to ignore it. */ uint16_t GetMetric (void) const; /** * These are IP interface states and may be distinct from * NetDevice states, such as found in real implementations * (where the device may be down but IP interface state is still up). */ /** * \returns true if this interface is enabled, false otherwise. */ bool IsUp (void) const; /** * \returns true if this interface is disabled, false otherwise. */ bool IsDown (void) const; /** * Enable this interface */ void SetUp (void); /** * Disable this interface */ void SetDown (void); /** * \returns true if this interface is enabled for IP forwarding of input datagrams */ bool IsForwarding (void) const; /** * \param val Whether to enable or disable IP forwarding for input datagrams */ void SetForwarding (bool val); /** * \param p packet to send * \param dest next hop address of packet. * * This method will eventually call the private * SendTo method which must be implemented by subclasses. */ void Send (Ptr<Packet> p, Ipv4Address dest); /** * \param address The Ipv4InterfaceAddress to add to the interface * \returns true if succeeded */ bool AddAddress (Ipv4InterfaceAddress address); /** * \param index Index of Ipv4InterfaceAddress to return * \returns The Ipv4InterfaceAddress address whose index is i */ Ipv4InterfaceAddress GetAddress (uint32_t index) const; /** * \returns the number of Ipv4InterfaceAddresss stored on this interface */ uint32_t GetNAddresses (void) const; /** * \param index Index of Ipv4InterfaceAddress to remove * \returns The Ipv4InterfaceAddress address whose index is index */ Ipv4InterfaceAddress RemoveAddress (uint32_t index); protected: virtual void DoDispose (void); private: void DoSetup (void); typedef std::list<Ipv4InterfaceAddress> Ipv4InterfaceAddressList; typedef std::list<Ipv4InterfaceAddress>::const_iterator Ipv4InterfaceAddressListCI; typedef std::list<Ipv4InterfaceAddress>::iterator Ipv4InterfaceAddressListI; bool m_ifup; bool m_forwarding; // IN_DEV_FORWARD uint16_t m_metric; Ipv4InterfaceAddressList m_ifaddrs; Ptr<Node> m_node; Ptr<NetDevice> m_device; Ptr<ArpCache> m_cache; }; } // namespace ns3 #endif
zy901002-gpsr
src/internet/model/ipv4-interface.h
C++
gpl2
4,862
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ // // Copyright (c) 2006 Georgia Tech Research Corporation // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation; // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Author: Rajib Bhattacharjea<raj.b@gatech.edu> // // This is a port of Data PDU Headers from: // Georgia Tech Network Simulator // George F. Riley. Georgia Tech, Spring 2002 #include <iostream> #include <algorithm> #include <string.h> #include "ns3/fatal-error.h" #include "ns3/log.h" #include "pending-data.h" NS_LOG_COMPONENT_DEFINE ("PendingData"); namespace ns3 { PendingData::PendingData () : size (0), data (0), msgSize (0), responseSize (0) { NS_LOG_FUNCTION (this); } PendingData::PendingData (uint32_t s, uint8_t* d, uint32_t msg, uint32_t resp) : size (s), data (0), msgSize (msg), responseSize (resp) { NS_LOG_FUNCTION (this << s); if (d) { data.push_back (Create<Packet> (d, size)); } } PendingData::PendingData(const std::string& s) : size (s.length () + 1), data (0), msgSize (0), responseSize (0) { NS_LOG_FUNCTION (this << s.length () + 1); data.push_back (Create<Packet> ((uint8_t*)s.c_str (), size)); } PendingData::PendingData(const PendingData& c) : size (c.Size ()), data (c.data), msgSize (c.msgSize), responseSize (c.responseSize) { NS_LOG_FUNCTION (this << c.Size ()); } PendingData::~PendingData() { NS_LOG_FUNCTION (this); } PendingData* PendingData::Copy () const { NS_LOG_FUNCTION (this); return new PendingData (*this); }; PendingData* PendingData::CopyS (uint32_t s) { // Copy, but with new size (assumes no associated data); NS_LOG_FUNCTION (this << s); return new PendingData (s, 0, msgSize, responseSize); } PendingData* PendingData::CopySD (uint32_t s, uint8_t* d) { // Copy, but with new size (assumes no associated data); NS_LOG_FUNCTION (this << s); return new PendingData (s, d, msgSize, responseSize); } void PendingData::Clear () { // Remove all pending data NS_LOG_FUNCTION (this); data.clear (); size = 0; } void PendingData::Add (uint32_t s, const uint8_t* d) { NS_LOG_FUNCTION (this << s); if (d == 0) { data.push_back (Create<Packet> (d,s)); } else { data.push_back (Create<Packet> (s)); } size += s; } void PendingData::Add (Ptr<Packet> p) { NS_LOG_FUNCTION (this); data.push_back (p); size += p->GetSize (); } uint32_t PendingData::SizeFromSeq (const SequenceNumber32& seqFront, const SequenceNumber32& seqOffset) { NS_LOG_FUNCTION (this << seqFront << seqOffset); uint32_t o1 = OffsetFromSeq (seqFront, seqOffset); // Offset to start of unused data return SizeFromOffset (o1); // Amount of data after offset } uint32_t PendingData::SizeFromOffset (uint32_t offset) { // Find out how much data is available from offset NS_LOG_FUNCTION (this << offset); // XXX should this return zero, or error out? if (offset > size) return 0; // No data at requested offset return size - offset; // Available data after offset } uint32_t PendingData::OffsetFromSeq (const SequenceNumber32& seqFront, const SequenceNumber32& seqOffset) { // f is the first sequence number in this data, o is offset sequence NS_LOG_FUNCTION (this << seqFront << seqOffset); if (seqOffset < seqFront) { return 0; // HuH? Shouldn't happen } return seqOffset - seqFront; } Ptr<Packet> PendingData::CopyFromOffset (uint32_t s, uint32_t o) { // Make a copy of data from starting position "o" for "s" bytes // Return NULL if results in zero length data NS_LOG_FUNCTION (this << s << o); uint32_t s1 = std::min (s, SizeFromOffset (o)); // Insure not beyond end of data if (s1 == 0) { return Create<Packet> (); // No data requested } if (data.size () != 0) { // Actual data exists, make copy and return it uint32_t count = 0; std::vector<Ptr<Packet> >::size_type begin = 0; bool beginFound = false; std::vector<Ptr<Packet> >::size_type end = 0; Ptr<Packet> outPacket; Ptr<Packet> endFragment; for (std::vector<Ptr<Packet> >::size_type i=0; i<data.size (); ++i) { count+=data[i]->GetSize (); if (!beginFound) { if (count > o) { if (count >= o + s1) //then just copy within this packet { Ptr<Packet> toFragment = data[i]; uint32_t packetStart = count - toFragment->GetSize (); uint32_t packetOffset = o - packetStart; outPacket = toFragment->CreateFragment (packetOffset, s1); return outPacket; } begin = i; beginFound = true; Ptr<Packet> toFragment = data[begin]; uint32_t packetStart = count - toFragment->GetSize (); uint32_t packetOffset = o - packetStart; uint32_t fragmentLength = count - o; outPacket = toFragment->CreateFragment (packetOffset, fragmentLength); } } else { if (count >= o + s1) { end = i; Ptr<Packet> toFragment = data[end]; uint32_t packetStart = count - toFragment->GetSize (); uint32_t fragmentLength = o + s1 - packetStart; endFragment = toFragment->CreateFragment (0, fragmentLength); break; } } } for (std::vector<Ptr<Packet> >::size_type i=begin+1; i<end; ++i) { outPacket->AddAtEnd (data[i]); } if (endFragment) { outPacket->AddAtEnd (endFragment); } NS_ASSERT (outPacket->GetSize () == s1); return outPacket; } else { // No actual data, just return dummy-data packet of correct size return Create<Packet> (s1); } } Ptr<Packet> PendingData::CopyFromSeq (uint32_t s, const SequenceNumber32& f, const SequenceNumber32& o) { NS_LOG_FUNCTION (this << s << f << o); return CopyFromOffset (s, OffsetFromSeq (f,o)); } uint32_t PendingData::RemoveToSeq (const SequenceNumber32& seqFront, const SequenceNumber32& seqOffset) { NS_LOG_FUNCTION (this << seqFront << seqOffset); uint32_t count = OffsetFromSeq (seqFront, seqOffset); NS_ASSERT_MSG (count <= size, "Trying to remove more data than in the buffer"); if (count == size) { Clear (); return size; } // Remove whole packets, if possible, from the front of the data // Do not perform buffer manipulations within packet; if a whole packet // cannot be removed, leave it alone std::vector<Ptr<Packet> >::iterator endI = data.begin (); uint32_t current = 0; // Any packet whose data has been completely acked can be removed for (std::vector<Ptr<Packet> >::iterator dataI = data.begin (); dataI < data.end (); dataI++) { if (current + (*dataI)->GetSize () > count) { break; } current += (*dataI)->GetSize (); ++endI; } data.erase (data.begin (), endI); size -= current; return current; } } //namepsace ns3
zy901002-gpsr
src/internet/model/pending-data.cc
C++
gpl2
7,838
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007-2008 Louis Pasteur University * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Sebastien Vincent <vincent@clarinet.u-strasbg.fr> */ #include "ns3/assert.h" #include "ns3/log.h" #include "ns3/header.h" #include "ns3/address-utils.h" #include "ipv6-header.h" NS_LOG_COMPONENT_DEFINE ("Ipv6Header"); namespace ns3 { NS_OBJECT_ENSURE_REGISTERED (Ipv6Header); Ipv6Header::Ipv6Header () : m_version (6), m_trafficClass (0), m_flowLabel (1), m_payloadLength (0), m_nextHeader (0), m_hopLimit (0) { SetSourceAddress (Ipv6Address ("::")); SetDestinationAddress (Ipv6Address ("::")); } void Ipv6Header::SetTrafficClass (uint8_t traffic) { m_trafficClass = traffic; } uint8_t Ipv6Header::GetTrafficClass () const { return m_trafficClass; } void Ipv6Header::SetFlowLabel (uint32_t flow) { m_flowLabel = flow; } uint32_t Ipv6Header::GetFlowLabel () const { return m_flowLabel; } void Ipv6Header::SetPayloadLength (uint16_t len) { m_payloadLength = len; } uint16_t Ipv6Header::GetPayloadLength () const { return m_payloadLength; } void Ipv6Header::SetNextHeader (uint8_t next) { m_nextHeader = next; } uint8_t Ipv6Header::GetNextHeader () const { return m_nextHeader; } void Ipv6Header::SetHopLimit (uint8_t limit) { m_hopLimit = limit; } uint8_t Ipv6Header::GetHopLimit () const { return m_hopLimit; } void Ipv6Header::SetSourceAddress (Ipv6Address src) { m_sourceAddress = src; } Ipv6Address Ipv6Header::GetSourceAddress () const { return m_sourceAddress; } void Ipv6Header::SetDestinationAddress (Ipv6Address dst) { m_destinationAddress = dst; } Ipv6Address Ipv6Header::GetDestinationAddress () const { return m_destinationAddress; } TypeId Ipv6Header::GetTypeId (void) { static TypeId tid = TypeId ("ns3::Ipv6Header") .SetParent<Header> () .AddConstructor<Ipv6Header> () ; return tid; } TypeId Ipv6Header::GetInstanceTypeId (void) const { return GetTypeId (); } void Ipv6Header::Print (std::ostream& os) const { os << "(" "Version " << m_version << " " << "Traffic class 0x" << std::hex << m_trafficClass << std::dec << " " << "Flow Label 0x" << std::hex << m_flowLabel << std::dec << " " << "Payload Length " << m_payloadLength << " " << "Next Header " << std::dec << (uint32_t) m_nextHeader << " " << "Hop Limit " << std::dec << (uint32_t)m_hopLimit << " )" << m_sourceAddress << " > " << m_destinationAddress ; } uint32_t Ipv6Header::GetSerializedSize () const { return 10 * 4; } void Ipv6Header::Serialize (Buffer::Iterator start) const { Buffer::Iterator i = start; uint32_t vTcFl = 0; /* version, Traffic Class and Flow Label fields */ vTcFl= (6 << 28) | (m_trafficClass << 20) | (m_flowLabel); i.WriteHtonU32 (vTcFl); i.WriteHtonU16 (m_payloadLength); i.WriteU8 (m_nextHeader); i.WriteU8 (m_hopLimit); WriteTo (i, m_sourceAddress); WriteTo (i, m_destinationAddress); } uint32_t Ipv6Header::Deserialize (Buffer::Iterator start) { Buffer::Iterator i = start; uint32_t vTcFl = 0; vTcFl = i.ReadNtohU32 (); m_version = vTcFl >> 28; NS_ASSERT ((m_version) == 6); m_trafficClass = (uint8_t)((vTcFl >> 20) & 0x000000ff); m_flowLabel = vTcFl & 0xfff00000; m_payloadLength = i.ReadNtohU16 (); m_nextHeader = i.ReadU8 (); m_hopLimit = i.ReadU8 (); ReadFrom (i, m_sourceAddress); ReadFrom (i, m_destinationAddress); return GetSerializedSize (); } } /* namespace ns3 */
zy901002-gpsr
src/internet/model/ipv6-header.cc
C++
gpl2
4,153
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ #ifndef IPV4_RAW_SOCKET_IMPL_H #define IPV4_RAW_SOCKET_IMPL_H #include "ns3/socket.h" #include "ns3/ipv4-header.h" #include "ns3/ipv4-route.h" #include "ns3/ipv4-interface.h" #include <list> namespace ns3 { class NetDevice; class Node; class Ipv4RawSocketImpl : public Socket { public: static TypeId GetTypeId (void); Ipv4RawSocketImpl (); void SetNode (Ptr<Node> node); virtual enum Socket::SocketErrno GetErrno (void) const; virtual enum Socket::SocketType GetSocketType (void) const; virtual Ptr<Node> GetNode (void) const; virtual int Bind (const Address &address); virtual int Bind (); virtual int GetSockName (Address &address) const; virtual int Close (void); virtual int ShutdownSend (void); virtual int ShutdownRecv (void); virtual int Connect (const Address &address); virtual int Listen (void); virtual uint32_t GetTxAvailable (void) const; virtual int Send (Ptr<Packet> p, uint32_t flags); virtual int SendTo (Ptr<Packet> p, uint32_t flags, const Address &toAddress); virtual uint32_t GetRxAvailable (void) const; virtual Ptr<Packet> Recv (uint32_t maxSize, uint32_t flags); virtual Ptr<Packet> RecvFrom (uint32_t maxSize, uint32_t flags, Address &fromAddress); void SetProtocol (uint16_t protocol); bool ForwardUp (Ptr<const Packet> p, Ipv4Header ipHeader, Ptr<Ipv4Interface> incomingInterface); virtual bool SetAllowBroadcast (bool allowBroadcast); virtual bool GetAllowBroadcast () const; private: virtual void DoDispose (void); struct Data { Ptr<Packet> packet; Ipv4Address fromIp; uint16_t fromProtocol; }; enum Socket::SocketErrno m_err; Ptr<Node> m_node; Ipv4Address m_src; Ipv4Address m_dst; uint16_t m_protocol; std::list<struct Data> m_recv; bool m_shutdownSend; bool m_shutdownRecv; uint32_t m_icmpFilter; bool m_iphdrincl; }; } // namespace ns3 #endif /* IPV4_RAW_SOCKET_IMPL_H */
zy901002-gpsr
src/internet/model/ipv4-raw-socket-impl.h
C++
gpl2
2,026
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2005 INRIA * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr> */ #include "ns3/log.h" #include "ns3/assert.h" #include "ns3/packet.h" #include "ns3/node.h" #include "ns3/boolean.h" #include "ns3/object-vector.h" #include "ns3/ipv4-route.h" #include "udp-l4-protocol.h" #include "udp-header.h" #include "udp-socket-factory-impl.h" #include "ipv4-end-point-demux.h" #include "ipv4-end-point.h" #include "ipv4-l3-protocol.h" #include "udp-socket-impl.h" NS_LOG_COMPONENT_DEFINE ("UdpL4Protocol"); namespace ns3 { NS_OBJECT_ENSURE_REGISTERED (UdpL4Protocol); /* see http://www.iana.org/assignments/protocol-numbers */ const uint8_t UdpL4Protocol::PROT_NUMBER = 17; TypeId UdpL4Protocol::GetTypeId (void) { static TypeId tid = TypeId ("ns3::UdpL4Protocol") .SetParent<Ipv4L4Protocol> () .AddConstructor<UdpL4Protocol> () .AddAttribute ("SocketList", "The list of sockets associated to this protocol.", ObjectVectorValue (), MakeObjectVectorAccessor (&UdpL4Protocol::m_sockets), MakeObjectVectorChecker<UdpSocketImpl> ()) ; return tid; } UdpL4Protocol::UdpL4Protocol () : m_endPoints (new Ipv4EndPointDemux ()) { NS_LOG_FUNCTION_NOARGS (); } UdpL4Protocol::~UdpL4Protocol () { NS_LOG_FUNCTION_NOARGS (); } void UdpL4Protocol::SetNode (Ptr<Node> node) { m_node = node; } /* * This method is called by AddAgregate and completes the aggregation * by setting the node in the udp stack and link it to the ipv4 object * present in the node along with the socket factory */ void UdpL4Protocol::NotifyNewAggregate () { if (m_node == 0) { Ptr<Node> node = this->GetObject<Node> (); if (node != 0) { Ptr<Ipv4> ipv4 = this->GetObject<Ipv4> (); if (ipv4 != 0) { this->SetNode (node); ipv4->Insert (this); Ptr<UdpSocketFactoryImpl> udpFactory = CreateObject<UdpSocketFactoryImpl> (); udpFactory->SetUdp (this); node->AggregateObject (udpFactory); this->SetDownTarget (MakeCallback (&Ipv4::Send, ipv4)); } } } Object::NotifyNewAggregate (); } int UdpL4Protocol::GetProtocolNumber (void) const { return PROT_NUMBER; } void UdpL4Protocol::DoDispose (void) { NS_LOG_FUNCTION_NOARGS (); for (std::vector<Ptr<UdpSocketImpl> >::iterator i = m_sockets.begin (); i != m_sockets.end (); i++) { *i = 0; } m_sockets.clear (); if (m_endPoints != 0) { delete m_endPoints; m_endPoints = 0; } m_node = 0; m_downTarget.Nullify (); /* = MakeNullCallback<void,Ptr<Packet>, Ipv4Address, Ipv4Address, uint8_t, Ptr<Ipv4Route> > (); */ Ipv4L4Protocol::DoDispose (); } Ptr<Socket> UdpL4Protocol::CreateSocket (void) { NS_LOG_FUNCTION_NOARGS (); Ptr<UdpSocketImpl> socket = CreateObject<UdpSocketImpl> (); socket->SetNode (m_node); socket->SetUdp (this); m_sockets.push_back (socket); return socket; } Ipv4EndPoint * UdpL4Protocol::Allocate (void) { NS_LOG_FUNCTION_NOARGS (); return m_endPoints->Allocate (); } Ipv4EndPoint * UdpL4Protocol::Allocate (Ipv4Address address) { NS_LOG_FUNCTION (this << address); return m_endPoints->Allocate (address); } Ipv4EndPoint * UdpL4Protocol::Allocate (uint16_t port) { NS_LOG_FUNCTION (this << port); return m_endPoints->Allocate (port); } Ipv4EndPoint * UdpL4Protocol::Allocate (Ipv4Address address, uint16_t port) { NS_LOG_FUNCTION (this << address << port); return m_endPoints->Allocate (address, port); } Ipv4EndPoint * UdpL4Protocol::Allocate (Ipv4Address localAddress, uint16_t localPort, Ipv4Address peerAddress, uint16_t peerPort) { NS_LOG_FUNCTION (this << localAddress << localPort << peerAddress << peerPort); return m_endPoints->Allocate (localAddress, localPort, peerAddress, peerPort); } void UdpL4Protocol::DeAllocate (Ipv4EndPoint *endPoint) { NS_LOG_FUNCTION (this << endPoint); m_endPoints->DeAllocate (endPoint); } void UdpL4Protocol::ReceiveIcmp (Ipv4Address icmpSource, uint8_t icmpTtl, uint8_t icmpType, uint8_t icmpCode, uint32_t icmpInfo, Ipv4Address payloadSource,Ipv4Address payloadDestination, const uint8_t payload[8]) { NS_LOG_FUNCTION (this << icmpSource << icmpTtl << icmpType << icmpCode << icmpInfo << payloadSource << payloadDestination); uint16_t src, dst; src = payload[0] << 8; src |= payload[1]; dst = payload[2] << 8; dst |= payload[3]; Ipv4EndPoint *endPoint = m_endPoints->SimpleLookup (payloadSource, src, payloadDestination, dst); if (endPoint != 0) { endPoint->ForwardIcmp (icmpSource, icmpTtl, icmpType, icmpCode, icmpInfo); } else { NS_LOG_DEBUG ("no endpoint found source=" << payloadSource << ", destination="<<payloadDestination<< ", src=" << src << ", dst=" << dst); } } enum Ipv4L4Protocol::RxStatus UdpL4Protocol::Receive (Ptr<Packet> packet, Ipv4Header const &header, Ptr<Ipv4Interface> interface) { NS_LOG_FUNCTION (this << packet << header); UdpHeader udpHeader; if(Node::ChecksumEnabled ()) { udpHeader.EnableChecksums (); } udpHeader.InitializeChecksum (header.GetSource (), header.GetDestination (), PROT_NUMBER); packet->RemoveHeader (udpHeader); if(!udpHeader.IsChecksumOk ()) { NS_LOG_INFO ("Bad checksum : dropping packet!"); return Ipv4L4Protocol::RX_CSUM_FAILED; } NS_LOG_DEBUG ("Looking up dst " << header.GetDestination () << " port " << udpHeader.GetDestinationPort ()); Ipv4EndPointDemux::EndPoints endPoints = m_endPoints->Lookup (header.GetDestination (), udpHeader.GetDestinationPort (), header.GetSource (), udpHeader.GetSourcePort (), interface); if (endPoints.empty ()) { NS_LOG_LOGIC ("RX_ENDPOINT_UNREACH"); return Ipv4L4Protocol::RX_ENDPOINT_UNREACH; } for (Ipv4EndPointDemux::EndPointsI endPoint = endPoints.begin (); endPoint != endPoints.end (); endPoint++) { (*endPoint)->ForwardUp (packet->Copy (), header, udpHeader.GetSourcePort (), interface); } return Ipv4L4Protocol::RX_OK; } void UdpL4Protocol::Send (Ptr<Packet> packet, Ipv4Address saddr, Ipv4Address daddr, uint16_t sport, uint16_t dport) { NS_LOG_FUNCTION (this << packet << saddr << daddr << sport << dport); UdpHeader udpHeader; if(Node::ChecksumEnabled ()) { udpHeader.EnableChecksums (); udpHeader.InitializeChecksum (saddr, daddr, PROT_NUMBER); } udpHeader.SetDestinationPort (dport); udpHeader.SetSourcePort (sport); packet->AddHeader (udpHeader); m_downTarget (packet, saddr, daddr, PROT_NUMBER, 0); } void UdpL4Protocol::Send (Ptr<Packet> packet, Ipv4Address saddr, Ipv4Address daddr, uint16_t sport, uint16_t dport, Ptr<Ipv4Route> route) { NS_LOG_FUNCTION (this << packet << saddr << daddr << sport << dport << route); UdpHeader udpHeader; if(Node::ChecksumEnabled ()) { udpHeader.EnableChecksums (); udpHeader.InitializeChecksum (saddr, daddr, PROT_NUMBER); } udpHeader.SetDestinationPort (dport); udpHeader.SetSourcePort (sport); packet->AddHeader (udpHeader); m_downTarget (packet, saddr, daddr, PROT_NUMBER, route); } void UdpL4Protocol::SetDownTarget (Ipv4L4Protocol::DownTargetCallback callback) { m_downTarget = callback; } Ipv4L4Protocol::DownTargetCallback UdpL4Protocol::GetDownTarget (void) const { return m_downTarget; } } // namespace ns3
zy901002-gpsr
src/internet/model/udp-l4-protocol.cc
C++
gpl2
8,696
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright 2007 University of Washington * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Authors: Craig Dowell (craigdo@ee.washington.edu) * Tom Henderson (tomhend@u.washington.edu) */ #ifndef GLOBAL_ROUTE_MANAGER_IMPL_H #define GLOBAL_ROUTE_MANAGER_IMPL_H #include <stdint.h> #include <list> #include <queue> #include <map> #include <vector> #include "ns3/object.h" #include "ns3/ptr.h" #include "ns3/ipv4-address.h" #include "global-router-interface.h" namespace ns3 { const uint32_t SPF_INFINITY = 0xffffffff; class CandidateQueue; class Ipv4GlobalRouting; /** * @brief Vertex used in shortest path first (SPF) computations. See RFC 2328, * Section 16. * * Each router in the simulation is associated with an SPFVertex object. When * calculating routes, each of these routers is, in turn, chosen as the "root" * of the calculation and routes to all of the other routers are eventually * saved in the routing tables of each of the chosen nodes. Each of these * routers in the calculation has an associated SPFVertex. * * The "Root" vertex is the SPFVertex representing the router that is having * its routing tables set. The SPFVertex objects representing other routers * or networks in the simulation are arranged in the SPF tree. It is this * tree that represents the Shortest Paths to the other networks. * * Each SPFVertex has a pointer to the Global Router Link State Advertisement * (LSA) that its underlying router has exported. Within these LSAs are * Global Router Link Records that describe the point to point links from the * underlying router to other nodes (represented by other SPFVertex objects) * in the simulation topology. The combination of the arrangement of the * SPFVertex objects in the SPF tree, along with the details of the link * records that connect them provide the information required to construct the * required routes. */ class SPFVertex { public: /** * @brief Enumeration of the possible types of SPFVertex objects. * @internal * * Currently we use VertexRouter to identify objects that represent a router * in the simulation topology, and VertexNetwork to identify objects that * represent a network. */ enum VertexType { VertexUnknown = 0, /**< Uninitialized Link Record */ VertexRouter, /**< Vertex representing a router in the topology */ VertexNetwork /**< Vertex representing a network in the topology */ }; /** * @brief Construct an empty ("uninitialized") SPFVertex (Shortest Path First * Vertex). * @internal * * The Vertex Type is set to VertexUnknown, the Vertex ID is set to * 255.255.255.255, and the distance from root is set to infinity * (UINT32_MAX). The referenced Link State Advertisement (LSA) is set to * null as is the parent SPFVertex. The outgoing interface index is set to * infinity, the next hop address is set to 0.0.0.0 and the list of children * of the SPFVertex is initialized to empty. * * @see VertexType */ SPFVertex(); /** * @brief Construct an initialized SPFVertex (Shortest Path First Vertex). * @internal * * The Vertex Type is initialized to VertexRouter and the Vertex ID is found * from the Link State ID of the Link State Advertisement (LSA) passed as a * parameter. The Link State ID is set to the Router ID of the advertising * router. The referenced LSA (m_lsa) is set to the given LSA. Other than * these members, initialization is as in the default constructor. * of the SPFVertex is initialized to empty. * * @see SPFVertex::SPFVertex () * @see VertexType * @see GlobalRoutingLSA * @param lsa The Link State Advertisement used for finding initial values. */ SPFVertex(GlobalRoutingLSA* lsa); /** * @brief Destroy an SPFVertex (Shortest Path First Vertex). * @internal * * The children vertices of the SPFVertex are recursively deleted. * * @see SPFVertex::SPFVertex () */ ~SPFVertex(); /** * @brief Get the Vertex Type field of a SPFVertex object. * @internal * * The Vertex Type describes the kind of simulation object a given SPFVertex * represents. * * @see VertexType * @returns The VertexType of the current SPFVertex object. */ VertexType GetVertexType (void) const; /** * @brief Set the Vertex Type field of a SPFVertex object. * @internal * * The Vertex Type describes the kind of simulation object a given SPFVertex * represents. * * @see VertexType * @param type The new VertexType for the current SPFVertex object. */ void SetVertexType (VertexType type); /** * @brief Get the Vertex ID field of a SPFVertex object. * @internal * * The Vertex ID uniquely identifies the simulation object a given SPFVertex * represents. Typically, this is the Router ID for SPFVertex objects * representing routers, and comes from the Link State Advertisement of a * router aggregated to a node in the simulation. These IDs are allocated * automatically by the routing environment and look like IP addresses * beginning at 0.0.0.0 and monotonically increasing as new routers are * instantiated. * * @returns The Ipv4Address Vertex ID of the current SPFVertex object. */ Ipv4Address GetVertexId (void) const; /** * @brief Set the Vertex ID field of a SPFVertex object. * @internal * * The Vertex ID uniquely identifies the simulation object a given SPFVertex * represents. Typically, this is the Router ID for SPFVertex objects * representing routers, and comes from the Link State Advertisement of a * router aggregated to a node in the simulation. These IDs are allocated * automatically by the routing environment and look like IP addresses * beginning at 0.0.0.0 and monotonically increase as new routers are * instantiated. This method is an explicit override of the automatically * generated value. * * @param id The new Ipv4Address Vertex ID for the current SPFVertex object. */ void SetVertexId (Ipv4Address id); /** * @brief Get the Global Router Link State Advertisement returned by the * Global Router represented by this SPFVertex during the route discovery * process. * @internal * * @see GlobalRouter * @see GlobalRoutingLSA * @see GlobalRouter::DiscoverLSAs () * @returns A pointer to the GlobalRoutingLSA found by the router represented * by this SPFVertex object. */ GlobalRoutingLSA* GetLSA (void) const; /** * @brief Set the Global Router Link State Advertisement returned by the * Global Router represented by this SPFVertex during the route discovery * process. * @internal * * @see SPFVertex::GetLSA () * @see GlobalRouter * @see GlobalRoutingLSA * @see GlobalRouter::DiscoverLSAs () * @warning Ownership of the LSA is transferred to the "this" SPFVertex. You * must not delete the LSA after calling this method. * @param lsa A pointer to the GlobalRoutingLSA. */ void SetLSA (GlobalRoutingLSA* lsa); /** * @brief Get the distance from the root vertex to "this" SPFVertex object. * @internal * * Each router in the simulation is associated with an SPFVertex object. When * calculating routes, each of these routers is, in turn, chosen as the "root" * of the calculation and routes to all of the other routers are eventually * saved in the routing tables of each of the chosen nodes. Each of these * routers in the calculation has an associated SPFVertex. * * The "Root" vertex is then the SPFVertex representing the router that is * having its routing tables set. The "this" SPFVertex is the vertex to which * a route is being calculated from the root. The distance from the root that * we're asking for is the number of hops from the root vertex to the vertex * in question. * * The distance is calculated during route discovery and is stored in a * member variable. This method simply fetches that value. * * @returns The distance, in hops, from the root SPFVertex to "this" SPFVertex. */ uint32_t GetDistanceFromRoot (void) const; /** * @brief Set the distance from the root vertex to "this" SPFVertex object. * @internal * * Each router in the simulation is associated with an SPFVertex object. When * calculating routes, each of these routers is, in turn, chosen as the "root" * of the calculation and routes to all of the other routers are eventually * saved in the routing tables of each of the chosen nodes. Each of these * routers in the calculation has an associated SPFVertex. * * The "Root" vertex is then the SPFVertex representing the router that is * having its routing tables set. The "this" SPFVertex is the vertex to which * a route is being calculated from the root. The distance from the root that * we're asking for is the number of hops from the root vertex to the vertex * in question. * * @param distance The distance, in hops, from the root SPFVertex to "this" * SPFVertex. */ void SetDistanceFromRoot (uint32_t distance); /** * @brief Set the IP address and outgoing interface index that should be used * to begin forwarding packets from the root SPFVertex to "this" SPFVertex. * @internal * * Each router node in the simulation is associated with an SPFVertex object. * When calculating routes, each of these routers is, in turn, chosen as the * "root" of the calculation and routes to all of the other routers are * eventually saved in the routing tables of each of the chosen nodes. * * The "Root" vertex is then the SPFVertex representing the router that is * having its routing tables set. The "this" SPFVertex is the vertex that * represents the host or network to which a route is being calculated from * the root. The IP address that we're asking for is the address on the * remote side of a link off of the root node that should be used as the * destination for packets along the path to "this" vertex. * * When initializing the root SPFVertex, the IP address used when forwarding * packets is determined by examining the Global Router Link Records of the * Link State Advertisement generated by the root node's GlobalRouter. This * address is used to forward packets off of the root's network down those * links. As other vertices / nodes are discovered which are further away * from the root, they will be accessible down one of the paths via a link * described by one of these Global Router Link Records. * * To forward packets to these hosts or networks, the root node must begin * the forwarding process by sending the packets to a first hop router down * an interface. This means that the first hop address and interface ID must * be the same for all downstream SPFVertices. We call this "inheriting" * the interface and next hop. * * In this method we are telling the root node which exit direction it should send * should I send a packet to the network or host represented by 'this' SPFVertex. * * @see GlobalRouter * @see GlobalRoutingLSA * @see GlobalRoutingLinkRecord * @param nextHop The IP address to use when forwarding packets to the host * or network represented by "this" SPFVertex. * @param id The interface index to use when forwarding packets to the host or * network represented by "this" SPFVertex. */ void SetRootExitDirection (Ipv4Address nextHop, int32_t id = SPF_INFINITY); typedef std::pair<Ipv4Address, int32_t> NodeExit_t; /** * @brief Set the IP address and outgoing interface index that should be used * to begin forwarding packets from the root SPFVertex to "this" SPFVertex. * @internal * * Each router node in the simulation is associated with an SPFVertex object. * When calculating routes, each of these routers is, in turn, chosen as the * "root" of the calculation and routes to all of the other routers are * eventually saved in the routing tables of each of the chosen nodes. * * The "Root" vertex is then the SPFVertex representing the router that is * having its routing tables set. The "this" SPFVertex is the vertex that * represents the host or network to which a route is being calculated from * the root. The IP address that we're asking for is the address on the * remote side of a link off of the root node that should be used as the * destination for packets along the path to "this" vertex. * * When initializing the root SPFVertex, the IP address used when forwarding * packets is determined by examining the Global Router Link Records of the * Link State Advertisement generated by the root node's GlobalRouter. This * address is used to forward packets off of the root's network down those * links. As other vertices / nodes are discovered which are further away * from the root, they will be accessible down one of the paths via a link * described by one of these Global Router Link Records. * * To forward packets to these hosts or networks, the root node must begin * the forwarding process by sending the packets to a first hop router down * an interface. This means that the first hop address and interface ID must * be the same for all downstream SPFVertices. We call this "inheriting" * the interface and next hop. * * In this method we are telling the root node which exit direction it should send * should I send a packet to the network or host represented by 'this' SPFVertex. * * @see GlobalRouter * @see GlobalRoutingLSA * @see GlobalRoutingLinkRecord * @param nextHop The IP address to use when forwarding packets to the host * or network represented by "this" SPFVertex. * @param exit The pair of next-hop-IP and outgoing-interface-index to use when * forwarding packets to the host or network represented by "this" SPFVertex. */ void SetRootExitDirection (SPFVertex::NodeExit_t exit); /** * \brief Obtain a pair indicating the exit direction from the root * * \param i An index to a pair * \return A pair of next-hop-IP and outgoing-interface-index for * indicating an exit direction from the root. It is 0 if the index 'i' * is out-of-range */ NodeExit_t GetRootExitDirection (uint32_t i) const; /** * \brief Obtain a pair indicating the exit direction from the root * * This method assumes there is only a single exit direction from the root. * Error occur if this assumption is invalid. * * \return The pair of next-hop-IP and outgoing-interface-index for reaching * 'this' vertex from the root */ NodeExit_t GetRootExitDirection () const; /** * \brief Merge into 'this' vertex the list of exit directions from * another vertex * * This merge is necessary when ECMP are found. * * \param vertex From which the list of exit directions are obtain * and are merged into 'this' vertex */ void MergeRootExitDirections (const SPFVertex* vertex); /** * \brief Inherit all root exit directions from a given vertex to 'this' vertex * \param vertex The vertex from which all root exit directions are to be inherited * * After the call of this method, the original root exit directions * in 'this' vertex are all lost. */ void InheritAllRootExitDirections (const SPFVertex* vertex); /** * \brief Get the number of exit directions from root for reaching 'this' vertex * \return The number of exit directions from root */ uint32_t GetNRootExitDirections () const; /** * @brief Get a pointer to the SPFVector that is the parent of "this" * SPFVertex. * @internal * * Each router node in the simulation is associated with an SPFVertex object. * When calculating routes, each of these routers is, in turn, chosen as the * "root" of the calculation and routes to all of the other routers are * eventually saved in the routing tables of each of the chosen nodes. * * The "Root" vertex is then the SPFVertex representing the router that is * having its routing tables set and is the root of the SPF tree. * * This method returns a pointer to the parent node of "this" SPFVertex * (both of which reside in that SPF tree). * * @param i The index to one of the parents * @returns A pointer to the SPFVertex that is the parent of "this" SPFVertex * in the SPF tree. */ SPFVertex* GetParent (uint32_t i = 0) const; /** * @brief Set the pointer to the SPFVector that is the parent of "this" * SPFVertex. * @internal * * Each router node in the simulation is associated with an SPFVertex object. * When calculating routes, each of these routers is, in turn, chosen as the * "root" of the calculation and routes to all of the other routers are * eventually saved in the routing tables of each of the chosen nodes. * * The "Root" vertex is then the SPFVertex representing the router that is * having its routing tables set and is the root of the SPF tree. * * This method sets the parent pointer of "this" SPFVertex (both of which * reside in that SPF tree). * * @param parent A pointer to the SPFVertex that is the parent of "this" * SPFVertex* in the SPF tree. */ void SetParent (SPFVertex* parent); /** * \brief Merge the Parent list from the v into this vertex * * \param v The vertex from which its list of Parent is read * and then merged into the list of Parent of *this* vertex. * Note that the list in v remains intact */ void MergeParent (const SPFVertex* v); /** * @brief Get the number of children of "this" SPFVertex. * @internal * * Each router node in the simulation is associated with an SPFVertex object. * When calculating routes, each of these routers is, in turn, chosen as the * "root" of the calculation and routes to all of the other routers are * eventually saved in the routing tables of each of the chosen nodes. * * The "Root" vertex is then the SPFVertex representing the router that is * having its routing tables set and is the root of the SPF tree. Each vertex * in the SPF tree can have a number of children that represent host or * network routes available via that vertex. * * This method returns the number of children of "this" SPFVertex (which * reside in the SPF tree). * * @returns The number of children of "this" SPFVertex (which reside in the * SPF tree). */ uint32_t GetNChildren (void) const; /** * @brief Get a borrowed SPFVertex pointer to the specified child of "this" * SPFVertex. * @internal * * Each router node in the simulation is associated with an SPFVertex object. * When calculating routes, each of these routers is, in turn, chosen as the * "root" of the calculation and routes to all of the other routers are * eventually saved in the routing tables of each of the chosen nodes. * * The "Root" vertex is then the SPFVertex representing the router that is * having its routing tables set and is the root of the SPF tree. Each vertex * in the SPF tree can have a number of children that represent host or * network routes available via that vertex. * * This method the number of children of "this" SPFVertex (which reside in * the SPF tree. * * @see SPFVertex::GetNChildren * @param n The index (from 0 to the number of children minus 1) of the * child SPFVertex to return. * @warning The pointer returned by GetChild () is a borrowed pointer. You * do not have any ownership of the underlying object and must not delete * that object. * @returns A pointer to the specified child SPFVertex (which resides in the * SPF tree). */ SPFVertex* GetChild (uint32_t n) const; /** * @brief Get a borrowed SPFVertex pointer to the specified child of "this" * SPFVertex. * @internal * * Each router node in the simulation is associated with an SPFVertex object. * When calculating routes, each of these routers is, in turn, chosen as the * "root" of the calculation and routes to all of the other routers are * eventually saved in the routing tables of each of the chosen nodes. * * The "Root" vertex is then the SPFVertex representing the router that is * having its routing tables set and is the root of the SPF tree. Each vertex * in the SPF tree can have a number of children that represent host or * network routes available via that vertex. * * This method the number of children of "this" SPFVertex (which reside in * the SPF tree. * * @see SPFVertex::GetNChildren * @warning Ownership of the pointer added to the children of "this" * SPFVertex is transferred to the "this" SPFVertex. You must not delete the * (now) child SPFVertex after calling this method. * @param child A pointer to the SPFVertex (which resides in the SPF tree) to * be added to the list of children of "this" SPFVertex. * @returns The number of children of "this" SPFVertex after the addition of * the new child. */ uint32_t AddChild (SPFVertex* child); /** * @brief Set the value of the VertexProcessed flag * * Flag to note whether vertex has been processed in stage two of * SPF computation * @param value boolean value to set the flag */ void SetVertexProcessed (bool value); /** * @brief Check the value of the VertexProcessed flag * * Flag to note whether vertex has been processed in stage two of * SPF computation * @returns value of underlying flag */ bool IsVertexProcessed (void) const; void ClearVertexProcessed (void); private: VertexType m_vertexType; Ipv4Address m_vertexId; GlobalRoutingLSA* m_lsa; uint32_t m_distanceFromRoot; int32_t m_rootOif; Ipv4Address m_nextHop; typedef std::list< NodeExit_t > ListOfNodeExit_t; /// store the multiple root's exits for supporting ECMP ListOfNodeExit_t m_ecmpRootExits; typedef std::list<SPFVertex*> ListOfSPFVertex_t; ListOfSPFVertex_t m_parents; ListOfSPFVertex_t m_children; bool m_vertexProcessed; /** * @brief The SPFVertex copy construction is disallowed. There's no need for * it and a compiler provided shallow copy would be wrong. */ SPFVertex (SPFVertex& v); /** * @brief The SPFVertex copy assignment operator is disallowed. There's no * need for it and a compiler provided shallow copy would be wrong. */ SPFVertex& operator= (SPFVertex& v); //friend std::ostream& operator<< (std::ostream& os, const ListOfIf_t& ifs); //friend std::ostream& operator<< (std::ostream& os, const ListOfAddr_t& addrs); friend std::ostream& operator<< (std::ostream& os, const SPFVertex::ListOfSPFVertex_t& vs); }; /** * @brief The Link State DataBase (LSDB) of the Global Route Manager. * * Each node in the simulation participating in global routing has a * GlobalRouter interface. The primary job of this interface is to export * Global Router Link State Advertisements (LSAs). These advertisements in * turn contain a number of Global Router Link Records that describe the * point to point links from the underlying node to other nodes (that will * also export their own LSAs. * * This class implements a searchable database of LSAs gathered from every * router in the simulation. */ class GlobalRouteManagerLSDB { public: /** * @brief Construct an empty Global Router Manager Link State Database. * @internal * * The database map composing the Link State Database is initialized in * this constructor. */ GlobalRouteManagerLSDB (); /** * @brief Destroy an empty Global Router Manager Link State Database. * @internal * * The database map is walked and all of the Link State Advertisements stored * in the database are freed; then the database map itself is clear ()ed to * release any remaining resources. */ ~GlobalRouteManagerLSDB (); /** * @brief Insert an IP address / Link State Advertisement pair into the Link * State Database. * @internal * * The IPV4 address and the GlobalRoutingLSA given as parameters are converted * to an STL pair and are inserted into the database map. * * @see GlobalRoutingLSA * @see Ipv4Address * @param addr The IP address associated with the LSA. Typically the Router * ID. * @param lsa A pointer to the Link State Advertisement for the router. */ void Insert (Ipv4Address addr, GlobalRoutingLSA* lsa); /** * @brief Look up the Link State Advertisement associated with the given * link state ID (address). * @internal * * The database map is searched for the given IPV4 address and corresponding * GlobalRoutingLSA is returned. * * @see GlobalRoutingLSA * @see Ipv4Address * @param addr The IP address associated with the LSA. Typically the Router * ID. * @returns A pointer to the Link State Advertisement for the router specified * by the IP address addr. */ GlobalRoutingLSA* GetLSA (Ipv4Address addr) const; /** * @brief Look up the Link State Advertisement associated with the given * link state ID (address). This is a variation of the GetLSA call * to allow the LSA to be found by matching addr with the LinkData field * of the TransitNetwork link record. * @internal * * @see GetLSA * @param addr The IP address associated with the LSA. Typically the Router * @returns A pointer to the Link State Advertisement for the router specified * by the IP address addr. * ID. */ GlobalRoutingLSA* GetLSAByLinkData (Ipv4Address addr) const; /** * @brief Set all LSA flags to an initialized state, for SPF computation * @internal * * This function walks the database and resets the status flags of all of the * contained Link State Advertisements to LSA_SPF_NOT_EXPLORED. This is done * prior to each SPF calculation to reset the state of the SPFVertex structures * that will reference the LSAs during the calculation. * * @see GlobalRoutingLSA * @see SPFVertex */ void Initialize (); GlobalRoutingLSA* GetExtLSA (uint32_t index) const; uint32_t GetNumExtLSAs () const; private: typedef std::map<Ipv4Address, GlobalRoutingLSA*> LSDBMap_t; typedef std::pair<Ipv4Address, GlobalRoutingLSA*> LSDBPair_t; LSDBMap_t m_database; std::vector<GlobalRoutingLSA*> m_extdatabase; /** * @brief GlobalRouteManagerLSDB copy construction is disallowed. There's no * need for it and a compiler provided shallow copy would be wrong. */ GlobalRouteManagerLSDB (GlobalRouteManagerLSDB& lsdb); /** * @brief The SPFVertex copy assignment operator is disallowed. There's no * need for it and a compiler provided shallow copy would be wrong. */ GlobalRouteManagerLSDB& operator= (GlobalRouteManagerLSDB& lsdb); }; /** * @brief A global router implementation. * * This singleton object can query interface each node in the system * for a GlobalRouter interface. For those nodes, it fetches one or * more Link State Advertisements and stores them in a local database. * Then, it can compute shortest paths on a per-node basis to all routers, * and finally configure each of the node's forwarding tables. * * The design is guided by OSPFv2 RFC 2328 section 16.1.1 and quagga ospfd. */ class GlobalRouteManagerImpl { public: GlobalRouteManagerImpl (); virtual ~GlobalRouteManagerImpl (); /** * @brief Delete all static routes on all nodes that have a * GlobalRouterInterface * * TODO: separate manually assigned static routes from static routes that * the global routing code injects, and only delete the latter * @internal * */ virtual void DeleteGlobalRoutes (); /** * @brief Build the routing database by gathering Link State Advertisements * from each node exporting a GlobalRouter interface. * @internal */ virtual void BuildGlobalRoutingDatabase (); /** * @brief Compute routes using a Dijkstra SPF computation and populate * per-node forwarding tables * @internal */ virtual void InitializeRoutes (); /** * @brief Debugging routine; allow client code to supply a pre-built LSDB * @internal */ void DebugUseLsdb (GlobalRouteManagerLSDB*); /** * @brief Debugging routine; call the core SPF from the unit tests * @internal */ void DebugSPFCalculate (Ipv4Address root); private: /** * @brief GlobalRouteManagerImpl copy construction is disallowed. * There's no need for it and a compiler provided shallow copy would be * wrong. */ GlobalRouteManagerImpl (GlobalRouteManagerImpl& srmi); /** * @brief Global Route Manager Implementation assignment operator is * disallowed. There's no need for it and a compiler provided shallow copy * would be hopelessly wrong. */ GlobalRouteManagerImpl& operator= (GlobalRouteManagerImpl& srmi); SPFVertex* m_spfroot; GlobalRouteManagerLSDB* m_lsdb; bool CheckForStubNode (Ipv4Address root); void SPFCalculate (Ipv4Address root); void SPFProcessStubs (SPFVertex* v); void ProcessASExternals (SPFVertex* v, GlobalRoutingLSA* extlsa); void SPFNext (SPFVertex*, CandidateQueue&); int SPFNexthopCalculation (SPFVertex* v, SPFVertex* w, GlobalRoutingLinkRecord* l, uint32_t distance); void SPFVertexAddParent (SPFVertex* v); GlobalRoutingLinkRecord* SPFGetNextLink (SPFVertex* v, SPFVertex* w, GlobalRoutingLinkRecord* prev_link); void SPFIntraAddRouter (SPFVertex* v); void SPFIntraAddTransit (SPFVertex* v); void SPFIntraAddStub (GlobalRoutingLinkRecord *l, SPFVertex* v); void SPFAddASExternal (GlobalRoutingLSA *extlsa, SPFVertex *v); int32_t FindOutgoingInterfaceId (Ipv4Address a, Ipv4Mask amask = Ipv4Mask ("255.255.255.255")); }; } // namespace ns3 #endif /* GLOBAL_ROUTE_MANAGER_IMPL_H */
zy901002-gpsr
src/internet/model/global-route-manager-impl.h
C++
gpl2
29,825
/* -*- Mode: C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007-2009 Strasbourg University * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA02111-1307USA * * Author: David Gross <gdavid.devel@gmail.com> */ #ifndef IPV6_OPTION_H #define IPV6_OPTION_H #include <map> #include "ns3/object.h" #include "ns3/node.h" #include "ns3/ptr.h" #include "ipv6-interface.h" #include "ns3/ipv6-header.h" #include "ns3/buffer.h" #include "ns3/packet.h" #include "ns3/ipv6-address.h" namespace ns3 { /** * \class Ipv6Option * \brief IPv6 Option base * * If you want to implement a new IPv6 option, all you have to do is * implement a subclass of this class and add it to an Ipv6OptionDemux. */ class Ipv6Option : public Object { public: /** * \brief Get the type identificator. * \return type identificator */ static TypeId GetTypeId (); /** * \brief Destructor. */ virtual ~Ipv6Option (); /** * \brief Set the node. * \param node the node to set */ void SetNode (Ptr<Node> node); /** * \brief Get the option number. * \return option number */ virtual uint8_t GetOptionNumber () const = 0; /** * \brief Process method * * Called from Ipv6L3Protocol::Receive. * \param packet the packet * \param offset the offset of the extension to process * \param ipv6Header the IPv6 header of packet received * \param isDropped if the packet must be dropped * \return the processed size */ virtual uint8_t Process (Ptr<Packet> packet, uint8_t offset, Ipv6Header const& ipv6Header, bool& isDropped) = 0; private: /** * \brief The node. */ Ptr<Node> m_node; }; /** * \class Ipv6OptionPad1 * \brief IPv6 Option Pad1 */ class Ipv6OptionPad1 : public Ipv6Option { public: /** * \brief Pad1 option number. */ static const uint8_t OPT_NUMBER = 0; /** * \brief Get the type identificator. * \return type identificator */ static TypeId GetTypeId (); /** * \brief Constructor. */ Ipv6OptionPad1 (); /** * \brief Destructor. */ ~Ipv6OptionPad1 (); /** * \brief Get the option number. * \return option number */ virtual uint8_t GetOptionNumber () const; /** * \brief Process method * * Called from Ipv6L3Protocol::Receive. * \param packet the packet * \param offset the offset of the extension to process * \param ipv6Header the IPv6 header of packet received * \param isDropped if the packet must be dropped * \return the processed size */ virtual uint8_t Process (Ptr<Packet> packet, uint8_t offset, Ipv6Header const& ipv6Header, bool& isDropped); }; /** * \class Ipv6OptionPadn * \brief IPv6 Option Padn */ class Ipv6OptionPadn : public Ipv6Option { public: /** * \brief PadN option number. */ static const uint8_t OPT_NUMBER = 60; /** * \brief Get the type identificator. * \return type identificator */ static TypeId GetTypeId (); /** * \brief Constructor. */ Ipv6OptionPadn (); /** * \brief Destructor. */ ~Ipv6OptionPadn (); /** * \brief Get the option number. * \return option number */ virtual uint8_t GetOptionNumber () const; /** * \brief Process method * * Called from Ipv6L3Protocol::Receive. * \param packet the packet * \param offset the offset of the extension to process * \param ipv6Header the IPv6 header of packet received * \param isDropped if the packet must be dropped * \return the processed size */ virtual uint8_t Process (Ptr<Packet> packet, uint8_t offset, Ipv6Header const& ipv6Header, bool& isDropped); }; /** * \class Ipv6OptionJumbogram * \brief IPv6 Option Jumbogram */ class Ipv6OptionJumbogram : public Ipv6Option { public: /** * \brief Jumbogram option number. */ static const uint8_t OPT_NUMBER = 44; /** * \brief Get the type identificator. * \return type identificator */ static TypeId GetTypeId (); /** * \brief Constructor. */ Ipv6OptionJumbogram (); /** * \brief Destructor. */ ~Ipv6OptionJumbogram (); /** * \brief Get the option number. * \return option number */ virtual uint8_t GetOptionNumber () const; /** * \brief Process method * Called from Ipv6L3Protocol::Receive. * \param packet the packet * \param offset the offset of the extension to process * \param ipv6Header the IPv6 header of packet received * \param isDropped if the packet must be dropped * \return the processed size */ virtual uint8_t Process (Ptr<Packet> packet, uint8_t offset, Ipv6Header const& ipv6Header, bool& isDropped); private: /** * \brief The length of the packet. */ uint32_t m_length; }; /** * \class Ipv6OptionRouterAlert * \brief IPv6 Option Router Alert */ class Ipv6OptionRouterAlert : public Ipv6Option { public: /** * \brief Router alert option number. */ static const uint8_t OPT_NUMBER = 43; /** * \brief Get the type identificator. * \return type identificator */ static TypeId GetTypeId (); /** * \brief Constructor. */ Ipv6OptionRouterAlert (); /** * \brief Destructor. */ ~Ipv6OptionRouterAlert (); /** * \brief Get the option number. * \return option number */ virtual uint8_t GetOptionNumber () const; /** * \brief Process method * * Called from Ipv6L3Protocol::Receive. * \param packet the packet * \param offset the offset of the extension to process * \param ipv6Header the IPv6 header of packet received * \param isDropped if the packet must be dropped * \return the processed size */ virtual uint8_t Process (Ptr<Packet> packet, uint8_t offset, Ipv6Header const& ipv6Header, bool& isDropped); }; } /* namespace ns3 */ #endif /* IPV6_OPTION_H */
zy901002-gpsr
src/internet/model/ipv6-option.h
C++
gpl2
6,366
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007-2009 Strasbourg University * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Sebastien Vincent <vincent@clarinet.u-strasbg.fr> */ #include "ns3/assert.h" #include "ipv6-routing-table-entry.h" namespace ns3 { Ipv6RoutingTableEntry::Ipv6RoutingTableEntry () { } Ipv6RoutingTableEntry::Ipv6RoutingTableEntry (Ipv6RoutingTableEntry const& route) : m_dest (route.m_dest), m_destNetworkPrefix (route.m_destNetworkPrefix), m_gateway (route.m_gateway), m_interface (route.m_interface), m_prefixToUse (route.m_prefixToUse) { } Ipv6RoutingTableEntry::Ipv6RoutingTableEntry (Ipv6RoutingTableEntry const* route) : m_dest (route->m_dest), m_destNetworkPrefix (route->m_destNetworkPrefix), m_gateway (route->m_gateway), m_interface (route->m_interface), m_prefixToUse (route->m_prefixToUse) { } Ipv6RoutingTableEntry::Ipv6RoutingTableEntry (Ipv6Address dest, Ipv6Address gateway, uint32_t interface) : m_dest (dest), m_destNetworkPrefix (Ipv6Prefix::GetZero ()), m_gateway (gateway), m_interface (interface), m_prefixToUse (Ipv6Address ("::")) { } Ipv6RoutingTableEntry::Ipv6RoutingTableEntry (Ipv6Address dest, uint32_t interface) : m_dest (dest), m_destNetworkPrefix (Ipv6Prefix::GetOnes ()), m_gateway (Ipv6Address::GetZero ()), m_interface (interface), m_prefixToUse (Ipv6Address ("::")) { } Ipv6RoutingTableEntry::Ipv6RoutingTableEntry (Ipv6Address network, Ipv6Prefix networkPrefix, Ipv6Address gateway, uint32_t interface, Ipv6Address prefixToUse) : m_dest (network), m_destNetworkPrefix (networkPrefix), m_gateway (gateway), m_interface (interface), m_prefixToUse (prefixToUse) { } Ipv6RoutingTableEntry::Ipv6RoutingTableEntry (Ipv6Address network, Ipv6Prefix networkPrefix, Ipv6Address gateway, uint32_t interface) : m_dest (network), m_destNetworkPrefix (networkPrefix), m_gateway (gateway), m_interface (interface), m_prefixToUse (Ipv6Address::GetZero ()) { } Ipv6RoutingTableEntry::Ipv6RoutingTableEntry (Ipv6Address network, Ipv6Prefix networkPrefix, uint32_t interface, Ipv6Address prefixToUse) : m_dest (network), m_destNetworkPrefix (networkPrefix), m_gateway (Ipv6Address::GetZero ()), m_interface (interface), m_prefixToUse (prefixToUse) { } Ipv6RoutingTableEntry::Ipv6RoutingTableEntry (Ipv6Address network, Ipv6Prefix networkPrefix, uint32_t interface) : m_dest (network), m_destNetworkPrefix (networkPrefix), m_gateway (Ipv6Address::GetZero ()), m_interface (interface), m_prefixToUse (Ipv6Address ("::")) { } Ipv6RoutingTableEntry::~Ipv6RoutingTableEntry () { } bool Ipv6RoutingTableEntry::IsHost () const { if (m_destNetworkPrefix.IsEqual (Ipv6Prefix::GetOnes ())) { return true; } return false; } Ipv6Address Ipv6RoutingTableEntry::GetDest () const { return m_dest; } Ipv6Address Ipv6RoutingTableEntry::GetPrefixToUse () const { return m_prefixToUse; } void Ipv6RoutingTableEntry::SetPrefixToUse (Ipv6Address prefix) { m_prefixToUse = prefix; } bool Ipv6RoutingTableEntry::IsNetwork () const { return !IsHost (); } bool Ipv6RoutingTableEntry::IsDefault () const { if (m_dest.IsEqual (Ipv6Address::GetZero ())) { return true; } return false; } Ipv6Address Ipv6RoutingTableEntry::GetDestNetwork () const { return m_dest; } Ipv6Prefix Ipv6RoutingTableEntry::GetDestNetworkPrefix () const { return m_destNetworkPrefix; } bool Ipv6RoutingTableEntry::IsGateway () const { if (m_gateway.IsEqual (Ipv6Address::GetZero ())) { return false; } return true; } Ipv6Address Ipv6RoutingTableEntry::GetGateway () const { return m_gateway; } Ipv6RoutingTableEntry Ipv6RoutingTableEntry::CreateHostRouteTo (Ipv6Address dest, Ipv6Address nextHop, uint32_t interface, Ipv6Address prefixToUse) { return Ipv6RoutingTableEntry (dest, Ipv6Prefix::GetOnes (), nextHop, interface, prefixToUse); } Ipv6RoutingTableEntry Ipv6RoutingTableEntry::CreateHostRouteTo (Ipv6Address dest, uint32_t interface) { return Ipv6RoutingTableEntry (dest, interface); } Ipv6RoutingTableEntry Ipv6RoutingTableEntry::CreateNetworkRouteTo (Ipv6Address network, Ipv6Prefix networkPrefix, Ipv6Address nextHop, uint32_t interface) { return Ipv6RoutingTableEntry (network, networkPrefix, nextHop, interface); } Ipv6RoutingTableEntry Ipv6RoutingTableEntry::CreateNetworkRouteTo (Ipv6Address network, Ipv6Prefix networkPrefix, Ipv6Address nextHop, uint32_t interface, Ipv6Address prefixToUse) { return Ipv6RoutingTableEntry (network, networkPrefix, nextHop, interface, prefixToUse); } Ipv6RoutingTableEntry Ipv6RoutingTableEntry::CreateNetworkRouteTo (Ipv6Address network, Ipv6Prefix networkPrefix, uint32_t interface) { return Ipv6RoutingTableEntry (network, networkPrefix, interface, network); } Ipv6RoutingTableEntry Ipv6RoutingTableEntry::CreateDefaultRoute (Ipv6Address nextHop, uint32_t interface) { return Ipv6RoutingTableEntry (Ipv6Address::GetZero (), nextHop, interface); } uint32_t Ipv6RoutingTableEntry::GetInterface () const { return m_interface; } std::ostream& operator<< (std::ostream& os, Ipv6RoutingTableEntry const& route) { if (route.IsDefault ()) { NS_ASSERT (route.IsGateway ()); os << "default out =" << route.GetInterface () << ", next hop =" << route.GetGateway (); } else if (route.IsHost ()) { if (route.IsGateway ()) { os << "host ="<< route.GetDest () << ", out =" << route.GetInterface () << ", next hop =" << route.GetGateway (); } else { os << "host =" << route.GetDest () << ", out =" << route.GetInterface (); } } else if (route.IsNetwork ()) { if (route.IsGateway ()) { os << "network =" << route.GetDestNetwork () << ", mask =" << route.GetDestNetworkPrefix () << ",out =" << route.GetInterface () << ", next hop =" << route.GetGateway (); } else { os << "network =" << route.GetDestNetwork () << ", mask =" << route.GetDestNetworkPrefix () << ",out =" << route.GetInterface (); } } else { NS_ASSERT (false); } return os; } Ipv6MulticastRoutingTableEntry::Ipv6MulticastRoutingTableEntry () { } Ipv6MulticastRoutingTableEntry::Ipv6MulticastRoutingTableEntry (Ipv6MulticastRoutingTableEntry const & route) : m_origin (route.m_origin), m_group (route.m_group), m_inputInterface (route.m_inputInterface), m_outputInterfaces (route.m_outputInterfaces) { } Ipv6MulticastRoutingTableEntry::Ipv6MulticastRoutingTableEntry (Ipv6MulticastRoutingTableEntry const* route) : m_origin (route->m_origin), m_group (route->m_group), m_inputInterface (route->m_inputInterface), m_outputInterfaces (route->m_outputInterfaces) { } Ipv6MulticastRoutingTableEntry::Ipv6MulticastRoutingTableEntry (Ipv6Address origin, Ipv6Address group, uint32_t inputInterface, std::vector<uint32_t> outputInterfaces) : m_origin (origin), m_group (group), m_inputInterface (inputInterface), m_outputInterfaces (outputInterfaces) { } Ipv6Address Ipv6MulticastRoutingTableEntry::GetOrigin () const { return m_origin; } Ipv6Address Ipv6MulticastRoutingTableEntry::GetGroup () const { return m_group; } uint32_t Ipv6MulticastRoutingTableEntry::GetInputInterface () const { return m_inputInterface; } uint32_t Ipv6MulticastRoutingTableEntry::GetNOutputInterfaces () const { return m_outputInterfaces.size (); } uint32_t Ipv6MulticastRoutingTableEntry::GetOutputInterface (uint32_t n) const { NS_ASSERT_MSG (n < m_outputInterfaces.size (), "Ipv6MulticastRoutingTableEntry::GetOutputInterface () : index out of bounds"); return m_outputInterfaces[n]; } std::vector <uint32_t> Ipv6MulticastRoutingTableEntry::GetOutputInterfaces () const { return m_outputInterfaces; } Ipv6MulticastRoutingTableEntry Ipv6MulticastRoutingTableEntry::CreateMulticastRoute (Ipv6Address origin, Ipv6Address group, uint32_t inputInterface, std::vector<uint32_t> outputInterfaces) { return Ipv6MulticastRoutingTableEntry (origin, group, inputInterface, outputInterfaces); } std::ostream& operator<< (std::ostream& os, Ipv6MulticastRoutingTableEntry const& route) { os << "origin =" << route.GetOrigin () << ", group =" << route.GetGroup () << ", input interface =" << route.GetInputInterface () << ", output interfaces ="; for (uint32_t i = 0; i < route.GetNOutputInterfaces (); ++i) { os << route.GetOutputInterface (i) << " "; } return os; } } /* namespace ns3 */
zy901002-gpsr
src/internet/model/ipv6-routing-table-entry.cc
C++
gpl2
9,324
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007 INRIA * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr> */ #include "ns3/uinteger.h" #include "ipv6-raw-socket-factory.h" namespace ns3 { NS_OBJECT_ENSURE_REGISTERED (Ipv6RawSocketFactory); TypeId Ipv6RawSocketFactory::GetTypeId () { static TypeId tid = TypeId ("ns3::Ipv6RawSocketFactory") .SetParent<SocketFactory> () ; return tid; } } // namespace ns3
zy901002-gpsr
src/internet/model/ipv6-raw-socket-factory.cc
C++
gpl2
1,127
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007 INRIA * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr> */ #ifndef IPV6_RAW_SOCKET_FACTORY_H #define IPV6_RAW_SOCKET_FACTORY_H #include "ns3/socket-factory.h" namespace ns3 { class Socket; /** * \ingroup socket * * \brief API to create IPv6 RAW socket instances * * This abstract class defines the API for IPv6 RAW socket factory. * */ class Ipv6RawSocketFactory : public SocketFactory { public: /** * \brief Get the type ID of this class. * \return type ID */ static TypeId GetTypeId (void); }; } // namespace ns3 #endif /* IPV6_RAW_SOCKET_FACTORY_H */
zy901002-gpsr
src/internet/model/ipv6-raw-socket-factory.h
C++
gpl2
1,341
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2006 INRIA * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr> */ #ifndef ARP_L3_PROTOCOL_H #define ARP_L3_PROTOCOL_H #include <list> #include "ns3/ipv4-address.h" #include "ns3/net-device.h" #include "ns3/address.h" #include "ns3/ptr.h" #include "ns3/traced-callback.h" namespace ns3 { class ArpCache; class NetDevice; class Node; class Packet; class Ipv4Interface; /** * \ingroup internet * \defgroup arp Arp * * This is an overview of Arp capabilities (write me). */ /** * \ingroup arp * \brief An implementation of the ARP protocol */ class ArpL3Protocol : public Object { public: static TypeId GetTypeId (void); static const uint16_t PROT_NUMBER; ArpL3Protocol (); virtual ~ArpL3Protocol (); void SetNode (Ptr<Node> node); Ptr<ArpCache> CreateCache (Ptr<NetDevice> device, Ptr<Ipv4Interface> interface); /** * \brief Receive a packet */ void Receive (Ptr<NetDevice> device, Ptr<const Packet> p, uint16_t protocol, const Address &from, const Address &to, NetDevice::PacketType packetType); /** * \brief Perform an ARP lookup * \param p * \param destination * \param device * \param cache * \param hardwareDestination * \return */ bool Lookup (Ptr<Packet> p, Ipv4Address destination, Ptr<NetDevice> device, Ptr<ArpCache> cache, Address *hardwareDestination); protected: virtual void DoDispose (void); /* * This function will notify other components connected to the node that a new stack member is now connected * This will be used to notify Layer 3 protocol of layer 4 protocol stack to connect them together. */ virtual void NotifyNewAggregate (); private: typedef std::list<Ptr<ArpCache> > CacheList; ArpL3Protocol (const ArpL3Protocol &o); ArpL3Protocol &operator = (const ArpL3Protocol &o); Ptr<ArpCache> FindCache (Ptr<NetDevice> device); void SendArpRequest (Ptr<const ArpCache>cache, Ipv4Address to); void SendArpReply (Ptr<const ArpCache> cache, Ipv4Address myIp, Ipv4Address toIp, Address toMac); CacheList m_cacheList; Ptr<Node> m_node; TracedCallback<Ptr<const Packet> > m_dropTrace; }; } // namespace ns3 #endif /* ARP_L3_PROTOCOL_H */
zy901002-gpsr
src/internet/model/arp-l3-protocol.h
C++
gpl2
2,965
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2009 University of Washington * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "ns3/assert.h" #include "ipv4-route.h" #include "ipv4-routing-protocol.h" namespace ns3 { NS_OBJECT_ENSURE_REGISTERED (Ipv4RoutingProtocol); TypeId Ipv4RoutingProtocol::GetTypeId (void) { static TypeId tid = TypeId ("ns3::Ipv4RoutingProtocol") .SetParent<Object> () ; return tid; } } // namespace ns3
zy901002-gpsr
src/internet/model/ipv4-routing-protocol.cc
C++
gpl2
1,096
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007-2009 Strasbourg University * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Sebastien Vincent <vincent@clarinet.u-strasbg.fr> */ #ifndef IPV6_ROUTE_H #define IPV6_ROUTE_H #include <list> #include <map> #include <ostream> #include "ns3/simple-ref-count.h" #include "ns3/ipv6-address.h" #include "ns3/deprecated.h" namespace ns3 { class NetDevice; /** * \ingroup ipv6Routing * \class Ipv6Route * \brief IPv6 route cache entry. */ class Ipv6Route : public SimpleRefCount<Ipv6Route> { public: /** * \brief Constructor. */ Ipv6Route (); /** * \brief Destructor. */ virtual ~Ipv6Route (); /** * \brief Set destination address. * \param dest IPv6 destination address */ void SetDestination (Ipv6Address dest); /** * \brief Get destination address. * \return destination address */ Ipv6Address GetDestination () const; /** * \brief Set source address. * \param src IPv6 source address */ void SetSource (Ipv6Address src); /** * \brief Get source address. * \return source address */ Ipv6Address GetSource () const; /** * \brief Set gateway address. * \param gw IPv6 gateway address */ void SetGateway (Ipv6Address gw); /** * \brief Get gateway address. * \return gateway address */ Ipv6Address GetGateway () const; /** * \brief Set output device for outgoing packets. * \param outputDevice output device */ void SetOutputDevice (Ptr<NetDevice> outputDevice); /** * \brief Get output device. * \return output device */ Ptr<NetDevice> GetOutputDevice () const; private: /** * \brief Destination address. */ Ipv6Address m_dest; /** * \brief source address. */ Ipv6Address m_source; /** * \brief Gateway address. */ Ipv6Address m_gateway; /** * \brief Output device. */ Ptr<NetDevice> m_outputDevice; }; std::ostream& operator<< (std::ostream& os, Ipv6Route const& route); /** * \ingroup ipv6Routing * \class Ipv6MulticastRoute * \brief IPv6 multicast route entry. */ class Ipv6MulticastRoute : public SimpleRefCount<Ipv6MulticastRoute> { public: /** * \brief Maximum number of multicast interfaces on a router. */ static const uint32_t MAX_INTERFACES = 16; /** * \brief Maximum Time-To-Live (TTL). */ static const uint32_t MAX_TTL = 255; /** * \brief Constructor. */ Ipv6MulticastRoute (); /** * \brief Destructor. */ virtual ~Ipv6MulticastRoute (); /** * \brief Set IPv6 group. * \param group Ipv6Address of the multicast group */ void SetGroup (const Ipv6Address group); /** * \brief Get IPv6 group. * \return Ipv6Address of the multicast group */ Ipv6Address GetGroup (void) const; /** * \brief Set origin address. * \param origin Ipv6Address of the origin address */ void SetOrigin (const Ipv6Address origin); /** * \brief Get source address. * \return Ipv6Address of the origin address */ Ipv6Address GetOrigin (void) const; /** * \brief Set parent for this route. * \param iif Parent (input interface) for this route */ void SetParent (uint32_t iif); /** * \brief Get parent for this route. * \return Parent (input interface) for this route */ uint32_t GetParent (void) const; /** * \brief set output TTL for this route. * \param oif Outgoing interface index * \param ttl time-to-live for this route */ void SetOutputTtl (uint32_t oif, uint32_t ttl); /** * \brief Get output TTL for this route. * \param oif outgoing interface * \return TTL for this route */ uint32_t GetOutputTtl (uint32_t oif) NS_DEPRECATED; /** * \return map of output interface Ids and TTLs for this route */ std::map<uint32_t, uint32_t> GetOutputTtlMap () const; private: /** * \brief IPv6 group. */ Ipv6Address m_group; /** * \brief IPv6 origin (source). */ Ipv6Address m_origin; /** * \brief Source interface. */ uint32_t m_parent; /** * \brief TTLs. */ std::map<uint32_t, uint32_t> m_ttls; }; std::ostream& operator<< (std::ostream& os, Ipv6MulticastRoute const& route); } /* namespace ns3 */ #endif /* IPV6_ROUTE_H */
zy901002-gpsr
src/internet/model/ipv6-route.h
C++
gpl2
4,911
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007-2009 Strasbourg University * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Sebastien Vincent <vincent@clarinet.u-strasbg.fr> */ #ifndef IPV6_INTERFACE_ADDRESS_H #define IPV6_INTERFACE_ADDRESS_H #include <stdint.h> #include "ns3/ipv6-address.h" namespace ns3 { /** * \ingroup address * \class Ipv6InterfaceAddress * \brief IPv6 address associated with an interface. */ class Ipv6InterfaceAddress { public: /** * \enum State_e * \brief State of an address associated with an interface. */ enum State_e { TENTATIVE, /**< Address is tentative, no packet can be sent unless DAD finished */ DEPRECATED, /**< Address is deprecated and should not be used */ PREFERRED, /**< Preferred address */ PERMANENT, /**< Permanent address */ HOMEADDRESS, /**< Address is a HomeAddress */ TENTATIVE_OPTIMISTIC, /**< Address is tentative but we are optimistic so we can send packet even if DAD is not yet finished */ INVALID, /**< Invalid state (after a DAD failed) */ }; /** * \enum Scope_e * \brief Scope of address. */ enum Scope_e { HOST, /**< Localhost (::1/128) */ LINKLOCAL, /**< Link-local address (fe80::/64) */ GLOBAL, /**< Global address (2000::/3) */ }; /** * \brief Default constructor. */ Ipv6InterfaceAddress (); /** * \brief Constructor. Prefix is 64 by default. * \param address the IPv6 address to set */ Ipv6InterfaceAddress (Ipv6Address address); /** * \brief Constructor. * \param address IPv6 address to set * \param prefix IPv6 prefix */ Ipv6InterfaceAddress (Ipv6Address address, Ipv6Prefix prefix); /** * \brief Copy constructor. * \param o object to copy */ Ipv6InterfaceAddress (const Ipv6InterfaceAddress& o); /** * \brief Destructor. */ ~Ipv6InterfaceAddress (); /** * \brief Set IPv6 address (and scope). * \param address IPv6 address to set */ void SetAddress (Ipv6Address address); /** * \brief Get the IPv6 address. * \return IPv6 address */ Ipv6Address GetAddress () const; /** * \brief Get the IPv6 prefix. * \return IPv6 prefix */ Ipv6Prefix GetPrefix () const; /** * \brief Set the state. * \param state the state */ void SetState (Ipv6InterfaceAddress::State_e state); /** * \brief Get the address state. * \return address state */ Ipv6InterfaceAddress::State_e GetState () const; /** * \brief Set the scope. * \param scope the scope of address */ void SetScope (Ipv6InterfaceAddress::Scope_e scope); /** * \brief Get address scope. * \return scope */ Ipv6InterfaceAddress::Scope_e GetScope () const; /** * \brief Set the latest DAD probe packet UID. * \param uid packet uid */ void SetNsDadUid (uint32_t uid); /** * \brief Get the latest DAD probe packet UID. * \return uid */ uint32_t GetNsDadUid () const; #if 0 /** * \brief Start the DAD timer. * \param interface interface */ void StartDadTimer (Ptr<Ipv6Interface> interface); /** * \brief Stop the DAD timer. */ void StopDadTimer (); #endif private: /** * \brief The IPv6 address. */ Ipv6Address m_address; /** * \brief The IPv6 prefix. */ Ipv6Prefix m_prefix; /** * \brief State of the address. */ State_e m_state; /** * \brief Scope of the address. */ Scope_e m_scope; friend bool operator == (Ipv6InterfaceAddress const& a, Ipv6InterfaceAddress const& b); friend bool operator != (Ipv6InterfaceAddress const& a, Ipv6InterfaceAddress const& b); /** * \brief Last DAD probe packet UID. */ uint32_t m_nsDadUid; }; std::ostream& operator<< (std::ostream& os, const Ipv6InterfaceAddress &addr); /* follow Ipv4InterfaceAddress way, maybe not inline them */ inline bool operator == (const Ipv6InterfaceAddress& a, const Ipv6InterfaceAddress& b) { return (a.m_address == b.m_address && a.m_prefix == b.m_prefix && a.m_state == b.m_state && a.m_scope == b.m_scope); } inline bool operator != (const Ipv6InterfaceAddress& a, const Ipv6InterfaceAddress& b) { return (a.m_address != b.m_address || a.m_prefix != b.m_prefix || a.m_state != b.m_state || a.m_scope != b.m_scope); } } /* namespace ns3 */ #endif /* IPV6_INTERFACE_ADDRESS_H */
zy901002-gpsr
src/internet/model/ipv6-interface-address.h
C++
gpl2
5,006
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "nsc-tcp-l4-protocol.h" #include "nsc-tcp-socket-factory-impl.h" #include "ns3/socket.h" #include "ns3/assert.h" namespace ns3 { NscTcpSocketFactoryImpl::NscTcpSocketFactoryImpl () : m_tcp (0) { } NscTcpSocketFactoryImpl::~NscTcpSocketFactoryImpl () { NS_ASSERT (m_tcp == 0); } void NscTcpSocketFactoryImpl::SetTcp (Ptr<NscTcpL4Protocol> tcp) { m_tcp = tcp; } Ptr<Socket> NscTcpSocketFactoryImpl::CreateSocket (void) { return m_tcp->CreateSocket (); } void NscTcpSocketFactoryImpl::DoDispose (void) { m_tcp = 0; TcpSocketFactory::DoDispose (); } } // namespace ns3
zy901002-gpsr
src/internet/model/nsc-tcp-socket-factory-impl.cc
C++
gpl2
1,314
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007-2009 Strasbourg University * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Sebastien Vincent <vincent@clarinet.u-strasbg.fr> */ #ifndef IPV6_STATIC_ROUTING_H #define IPV6_STATIC_ROUTING_H #include <stdint.h> #include <list> #include "ns3/ptr.h" #include "ns3/ipv6-address.h" #include "ns3/ipv6.h" #include "ns3/ipv6-header.h" #include "ns3/ipv6-routing-protocol.h" namespace ns3 { class Packet; class NetDevice; class Ipv6Interface; class Ipv6Route; class Node; class Ipv6RoutingTableEntry; class Ipv6MulticastRoutingTableEntry; /** * \ingroup internet * \defgroup ipv6StaticRouting Ipv6StaticRouting */ /** * \ingroup ipv6StaticRouting * \class Ipv6StaticRouting * \brief Static routing protocol for IP version 6 stack. * \see Ipv6RoutingProtocol * \see Ipv6ListRouting */ class Ipv6StaticRouting : public Ipv6RoutingProtocol { public: /** * \brief The interface Id associated with this class. * \return type identifier */ static TypeId GetTypeId (); /** * \brief Constructor. */ Ipv6StaticRouting (); /** * \brief Destructor. */ virtual ~Ipv6StaticRouting (); /** * \brief Add route to host. * \param dest destination address * \param nextHop next hop address to route the packet * \param interface interface index * \param prefixToUse prefix that should be used for source address for this destination * \param metric metric of route in case of multiple routes to same destination */ void AddHostRouteTo (Ipv6Address dest, Ipv6Address nextHop, uint32_t interface, Ipv6Address prefixToUse = Ipv6Address ("::"), uint32_t metric = 0); /** * \brief Add route to host. * \param dest destination address. * \param interface interface index * \param metric metric of route in case of multiple routes to same destination */ void AddHostRouteTo (Ipv6Address dest, uint32_t interface, uint32_t metric = 0); /** * \brief Add route to network. * \param network network address * \param networkPrefix network prefix* * \param nextHop next hop address to route the packet * \param interface interface index * \param metric metric of route in case of multiple routes to same destination */ void AddNetworkRouteTo (Ipv6Address network, Ipv6Prefix networkPrefix, Ipv6Address nextHop, uint32_t interface, uint32_t metric = 0); /** * \brief Add route to network. * \param network network address * \param networkPrefix network prefix* * \param nextHop next hop address to route the packet * \param interface interface index * \param prefixToUse prefix that should be used for source address for this destination * \param metric metric of route in case of multiple routes to same destination */ void AddNetworkRouteTo (Ipv6Address network, Ipv6Prefix networkPrefix, Ipv6Address nextHop, uint32_t interface, Ipv6Address prefixToUse, uint32_t metric = 0); /** * \brief Add route to network. * \param network network address * \param networkPrefix network prefix * \param interface interface index * \param metric metric of route in case of multiple routes to same destination */ void AddNetworkRouteTo (Ipv6Address network, Ipv6Prefix networkPrefix, uint32_t interface, uint32_t metric = 0); /** * \brief Set the default route. * \param nextHop next hop address to route the packet * \param interface interface index * \param prefixToUse prefix to use (i.e for multihoming) * \param metric metric of route in case of multiple routes to same destination */ void SetDefaultRoute (Ipv6Address nextHop, uint32_t interface, Ipv6Address prefixToUse = Ipv6Address ("::"), uint32_t metric = 0); /** * \brief Get the number or entries in the routing table. * \return number of entries */ uint32_t GetNRoutes (); /** * \brief Get the default route. * * If multiple default routes exist, the one with lowest metric is returned. * \return default Ipv6Route */ Ipv6RoutingTableEntry GetDefaultRoute (); /** * \brief Get a specified route. * \param i index * \return the route whose index is i */ Ipv6RoutingTableEntry GetRoute (uint32_t i); /** * \brief Get a metric for route from the static unicast routing table. * \param index The index (into the routing table) of the route to retrieve. * \return If route is set, the metric is returned. If not, an infinity metric (0xffffffff) is returned */ uint32_t GetMetric (uint32_t index); /** * \brief Remove a route from the routing table. * \param i index */ void RemoveRoute (uint32_t i); /** * \brief Remove a route from the routing table. * \param network IPv6 network * \param prefix IPv6 prefix * \param ifIndex interface index * \param prefixToUse IPv6 prefix to use with this route (multihoming) */ void RemoveRoute (Ipv6Address network, Ipv6Prefix prefix, uint32_t ifIndex, Ipv6Address prefixToUse); /** * \brief Add a multicast route for a given multicast source and group. * \param origin IPv6 address of the source * \param group the multicast group address. * \param inputInterface the interface index * \param outputInterfaces the list of output interface indices over which the packet * should be sent (excluding the inputInterface). */ void AddMulticastRoute (Ipv6Address origin, Ipv6Address group, uint32_t inputInterface, std::vector<uint32_t> outputInterfaces); /** * \brief Set the default multicast route. * \param outputInterface default output interface */ void SetDefaultMulticastRoute (uint32_t outputInterface); /** * \brief Get the number of entries in the multicast routing table. * \return number of entries */ uint32_t GetNMulticastRoutes () const; /** * \brief Get the specified multicast route. * \param i index * \return the route whose index is i */ Ipv6MulticastRoutingTableEntry GetMulticastRoute (uint32_t i) const; /** * \brief Remove a static multicast route. * \param origin IPv6 address of the source * \param group the multicast group address. * \param inputInterface the input interface index */ bool RemoveMulticastRoute (Ipv6Address origin, Ipv6Address group, uint32_t inputInterface); /** * \brief Remove a multicast route. * \param i index of route to remove */ void RemoveMulticastRoute (uint32_t i); /** * \brief If the destination is already present in network destination list. * \param dest destination address * \param interfaceIndex interface index * \return true if dest is already in list, false otherwise */ bool HasNetworkDest (Ipv6Address dest, uint32_t interfaceIndex); virtual Ptr<Ipv6Route> RouteOutput (Ptr<Packet> p, const Ipv6Header &header, Ptr<NetDevice> oif, Socket::SocketErrno &sockerr); virtual bool RouteInput (Ptr<const Packet> p, const Ipv6Header &header, Ptr<const NetDevice> idev, UnicastForwardCallback ucb, MulticastForwardCallback mcb, LocalDeliverCallback lcb, ErrorCallback ecb); virtual void NotifyInterfaceUp (uint32_t interface); virtual void NotifyInterfaceDown (uint32_t interface); virtual void NotifyAddAddress (uint32_t interface, Ipv6InterfaceAddress address); virtual void NotifyRemoveAddress (uint32_t interface, Ipv6InterfaceAddress address); virtual void NotifyAddRoute (Ipv6Address dst, Ipv6Prefix mask, Ipv6Address nextHop, uint32_t interface, Ipv6Address prefixToUse = Ipv6Address::GetZero ()); virtual void NotifyRemoveRoute (Ipv6Address dst, Ipv6Prefix mask, Ipv6Address nextHop, uint32_t interface, Ipv6Address prefixToUse = Ipv6Address::GetZero ()); virtual void SetIpv6 (Ptr<Ipv6> ipv6); protected: /** * \brief Dispose this object. */ void DoDispose (); private: typedef std::list<std::pair <Ipv6RoutingTableEntry *, uint32_t> > NetworkRoutes; typedef std::list<std::pair <Ipv6RoutingTableEntry *, uint32_t> >::const_iterator NetworkRoutesCI; typedef std::list<std::pair <Ipv6RoutingTableEntry *, uint32_t> >::iterator NetworkRoutesI; typedef std::list<Ipv6MulticastRoutingTableEntry *> MulticastRoutes; typedef std::list<Ipv6MulticastRoutingTableEntry *>::const_iterator MulticastRoutesCI; typedef std::list<Ipv6MulticastRoutingTableEntry *>::iterator MulticastRoutesI; /** * \brief Lookup in the forwarding table for destination. * \param dest destination address * \param interface output interface if any (put 0 otherwise) * \return Ipv6Route to route the packet to reach dest address */ Ptr<Ipv6Route> LookupStatic (Ipv6Address dest, Ptr<NetDevice> = 0); /** * \brief Lookup in the multicast forwarding table for destination. * \param origin source address * \param group group multicast address * \param ifIndex interface index * \return Ipv6MulticastRoute to route the packet to reach dest address */ Ptr<Ipv6MulticastRoute> LookupStatic (Ipv6Address origin, Ipv6Address group, uint32_t ifIndex); /** * \brief Choose the source address to use with destination address. * \param interface interface index * \param dest IPv6 destination address * \return IPv6 source address to use */ Ipv6Address SourceAddressSelection (uint32_t interface, Ipv6Address dest); /** * \brief the forwarding table for network. */ NetworkRoutes m_networkRoutes; /** * \brief the forwarding table for multicast. */ MulticastRoutes m_multicastRoutes; /** * \brief Ipv6 reference. */ Ptr<Ipv6> m_ipv6; }; } /* namespace ns3 */ #endif /* IPV6_STATIC_ROUTING_H */
zy901002-gpsr
src/internet/model/ipv6-static-routing.h
C++
gpl2
10,300
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright 2007 University of Washington * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Tom Henderson (tomhend@u.washington.edu) */ #include "ns3/assert.h" #include "ns3/log.h" #include "ns3/simulation-singleton.h" #include "global-route-manager.h" #include "global-route-manager-impl.h" namespace ns3 { // --------------------------------------------------------------------------- // // GlobalRouteManager Implementation // // --------------------------------------------------------------------------- void GlobalRouteManager::DeleteGlobalRoutes () { SimulationSingleton<GlobalRouteManagerImpl>::Get ()-> DeleteGlobalRoutes (); } void GlobalRouteManager::BuildGlobalRoutingDatabase (void) { SimulationSingleton<GlobalRouteManagerImpl>::Get ()-> BuildGlobalRoutingDatabase (); } void GlobalRouteManager::InitializeRoutes (void) { SimulationSingleton<GlobalRouteManagerImpl>::Get ()-> InitializeRoutes (); } uint32_t GlobalRouteManager::AllocateRouterId (void) { static uint32_t routerId = 0; return routerId++; } } // namespace ns3
zy901002-gpsr
src/internet/model/global-route-manager.cc
C++
gpl2
1,751
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2005 INRIA * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr> */ #include "udp-header.h" #include "ns3/address-utils.h" namespace ns3 { NS_OBJECT_ENSURE_REGISTERED (UdpHeader); /* The magic values below are used only for debugging. * They can be used to easily detect memory corruption * problems so you can see the patterns in memory. */ UdpHeader::UdpHeader () : m_sourcePort (0xfffd), m_destinationPort (0xfffd), m_payloadSize (0xfffd), m_calcChecksum (false), m_goodChecksum (true) { } UdpHeader::~UdpHeader () { m_sourcePort = 0xfffe; m_destinationPort = 0xfffe; m_payloadSize = 0xfffe; } void UdpHeader::EnableChecksums (void) { m_calcChecksum = true; } void UdpHeader::SetDestinationPort (uint16_t port) { m_destinationPort = port; } void UdpHeader::SetSourcePort (uint16_t port) { m_sourcePort = port; } uint16_t UdpHeader::GetSourcePort (void) const { return m_sourcePort; } uint16_t UdpHeader::GetDestinationPort (void) const { return m_destinationPort; } void UdpHeader::InitializeChecksum (Ipv4Address source, Ipv4Address destination, uint8_t protocol) { m_source = source; m_destination = destination; m_protocol = protocol; } uint16_t UdpHeader::CalculateHeaderChecksum (uint16_t size) const { Buffer buf = Buffer (12); buf.AddAtStart (12); Buffer::Iterator it = buf.Begin (); WriteTo (it, m_source); WriteTo (it, m_destination); it.WriteU8 (0); /* protocol */ it.WriteU8 (m_protocol); /* protocol */ it.WriteU8 (size >> 8); /* length */ it.WriteU8 (size & 0xff); /* length */ it = buf.Begin (); /* we don't CompleteChecksum ( ~ ) now */ return ~(it.CalculateIpChecksum (12)); } bool UdpHeader::IsChecksumOk (void) const { return m_goodChecksum; } TypeId UdpHeader::GetTypeId (void) { static TypeId tid = TypeId ("ns3::UdpHeader") .SetParent<Header> () .AddConstructor<UdpHeader> () ; return tid; } TypeId UdpHeader::GetInstanceTypeId (void) const { return GetTypeId (); } void UdpHeader::Print (std::ostream &os) const { os << "length: " << m_payloadSize + GetSerializedSize () << " " << m_sourcePort << " > " << m_destinationPort ; } uint32_t UdpHeader::GetSerializedSize (void) const { return 8; } void UdpHeader::Serialize (Buffer::Iterator start) const { Buffer::Iterator i = start; i.WriteHtonU16 (m_sourcePort); i.WriteHtonU16 (m_destinationPort); i.WriteHtonU16 (start.GetSize ()); i.WriteU16 (0); if (m_calcChecksum) { uint16_t headerChecksum = CalculateHeaderChecksum (start.GetSize ()); i = start; uint16_t checksum = i.CalculateIpChecksum (start.GetSize (), headerChecksum); i = start; i.Next (6); i.WriteU16 (checksum); } } uint32_t UdpHeader::Deserialize (Buffer::Iterator start) { Buffer::Iterator i = start; m_sourcePort = i.ReadNtohU16 (); m_destinationPort = i.ReadNtohU16 (); m_payloadSize = i.ReadNtohU16 () - GetSerializedSize (); i.Next (2); if(m_calcChecksum) { uint16_t headerChecksum = CalculateHeaderChecksum (start.GetSize ()); i = start; uint16_t checksum = i.CalculateIpChecksum (start.GetSize (), headerChecksum); m_goodChecksum = (checksum == 0); } return GetSerializedSize (); } } // namespace ns3
zy901002-gpsr
src/internet/model/udp-header.cc
C++
gpl2
4,092
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2008 University of Washington * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef IPV4_ADDRESS_GENERATOR_H #define IPV4_ADDRESS_GENERATOR_H #include "ns3/ipv4-address.h" namespace ns3 { /** * \ingroup address * * \brief This generator assigns addresses sequentially from a provided * network address; used in topology code. */ class Ipv4AddressGenerator { public: static void Init (const Ipv4Address net, const Ipv4Mask mask, const Ipv4Address addr = "0.0.0.1"); static Ipv4Address NextNetwork (const Ipv4Mask mask); static Ipv4Address GetNetwork (const Ipv4Mask mask); static void InitAddress (const Ipv4Address addr, const Ipv4Mask mask); static Ipv4Address NextAddress (const Ipv4Mask mask); static Ipv4Address GetAddress (const Ipv4Mask mask); static void Reset (void); static bool AddAllocated (const Ipv4Address addr); static void TestMode (void); }; } // namespace ns3 #endif /* IPV4_ADDRESS_GENERATOR_H */
zy901002-gpsr
src/internet/model/ipv4-address-generator.h
C++
gpl2
1,665
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * based on earlier integration work by Tom Henderson and Sam Jansen. * 2008 Florian Westphal <fw@strlen.de> */ #include "ns3/assert.h" #include "ns3/log.h" #include "ns3/nstime.h" #include "ns3/packet.h" #include "ns3/node.h" #include "ns3/ipv4-route.h" #include "ns3/object-vector.h" #include "ns3/string.h" #include "tcp-header.h" #include "ipv4-end-point-demux.h" #include "ipv4-end-point.h" #include "ipv4-l3-protocol.h" #include "nsc-tcp-l4-protocol.h" #include "nsc-tcp-socket-impl.h" #include "nsc-sysctl.h" #include "nsc-tcp-socket-factory-impl.h" #include "sim_interface.h" #include <vector> #include <sstream> #include <dlfcn.h> #include <iomanip> #include <netinet/in.h> #include <arpa/inet.h> NS_LOG_COMPONENT_DEFINE ("NscTcpL4Protocol"); namespace ns3 { NS_OBJECT_ENSURE_REGISTERED (NscTcpL4Protocol); /* see http://www.iana.org/assignments/protocol-numbers */ const uint8_t NscTcpL4Protocol::PROT_NUMBER = 6; class NscInterfaceImpl : public ISendCallback, public IInterruptCallback { public: NscInterfaceImpl (Ptr<NscTcpL4Protocol> prot); private: virtual void send_callback (const void *data, int datalen); virtual void wakeup (); virtual void gettime (unsigned int *, unsigned int *); private: Ptr<NscTcpL4Protocol> m_prot; }; NscInterfaceImpl::NscInterfaceImpl (Ptr<NscTcpL4Protocol> prot) : m_prot (prot) { } void NscInterfaceImpl::send_callback (const void *data, int datalen) { m_prot->send_callback (data, datalen); } void NscInterfaceImpl::wakeup () { m_prot->wakeup (); } void NscInterfaceImpl::gettime (unsigned int *sec, unsigned int *usec) { m_prot->gettime (sec,usec); } #undef NS_LOG_APPEND_CONTEXT #define NS_LOG_APPEND_CONTEXT \ if (m_node) { std::clog << Simulator::Now ().GetSeconds () << " [node " << m_node->GetId () << "] "; } TypeId NscTcpL4Protocol::GetTypeId (void) { static TypeId tid = TypeId ("ns3::NscTcpL4Protocol") .SetParent<Ipv4L4Protocol> () .AddConstructor<NscTcpL4Protocol>() .AddAttribute ("SocketList", "The list of sockets associated to this protocol.", ObjectVectorValue (), MakeObjectVectorAccessor (&NscTcpL4Protocol::m_sockets), MakeObjectVectorChecker<NscTcpSocketImpl> ()) .AddAttribute ("Library", "Set the linux library to be used to create the stack", TypeId::ATTR_GET|TypeId::ATTR_CONSTRUCT, StringValue ("liblinux2.6.26.so"), MakeStringAccessor (&NscTcpL4Protocol::GetNscLibrary,&NscTcpL4Protocol::SetNscLibrary), MakeStringChecker ()) ; return tid; } int external_rand () { return 1; // TODO } NscTcpL4Protocol::NscTcpL4Protocol () : m_endPoints (new Ipv4EndPointDemux ()), m_nscStack (0), m_nscInterface (new NscInterfaceImpl (this)), m_softTimer (Timer::CANCEL_ON_DESTROY) { m_dlopenHandle = NULL; NS_LOG_LOGIC ("Made a NscTcpL4Protocol "<<this); } NscTcpL4Protocol::~NscTcpL4Protocol () { NS_LOG_FUNCTION (this); dlclose (m_dlopenHandle); } void NscTcpL4Protocol::SetNscLibrary (const std::string &soname) { if (soname!="") { m_nscLibrary = soname; NS_ASSERT (!m_dlopenHandle); m_dlopenHandle = dlopen (soname.c_str (), RTLD_NOW); if (m_dlopenHandle == NULL) NS_FATAL_ERROR (dlerror ()); } } std::string NscTcpL4Protocol::GetNscLibrary () const { return m_nscLibrary; } void NscTcpL4Protocol::SetNode (Ptr<Node> node) { m_node = node; if (m_nscStack) { // stack has already been loaded... return; } NS_ASSERT (m_dlopenHandle); FCreateStack create = (FCreateStack)dlsym (m_dlopenHandle, "nsc_create_stack"); NS_ASSERT (create); m_nscStack = create (m_nscInterface, m_nscInterface, external_rand); int hzval = m_nscStack->get_hz (); NS_ASSERT (hzval > 0); m_softTimer.SetFunction (&NscTcpL4Protocol::SoftInterrupt, this); m_softTimer.SetDelay (MilliSeconds (1000/hzval)); m_nscStack->init (hzval); // This enables stack and NSC debug messages // m_nscStack->set_diagnostic(1000); Ptr<Ns3NscStack> nscStack = Create<Ns3NscStack> (); nscStack->SetStack (m_nscStack); node->AggregateObject (nscStack); m_softTimer.Schedule (); // its likely no ns-3 interface exits at this point, so // we dealy adding the nsc interface until the start of the simulation. Simulator::ScheduleNow (&NscTcpL4Protocol::AddInterface, this); } void NscTcpL4Protocol::NotifyNewAggregate () { if (m_node == 0) { Ptr<Node>node = this->GetObject<Node> (); if (node != 0) { Ptr<Ipv4L3Protocol> ipv4 = this->GetObject<Ipv4L3Protocol> (); if (ipv4 != 0) { this->SetNode (node); ipv4->Insert (this); Ptr<NscTcpSocketFactoryImpl> tcpFactory = CreateObject<NscTcpSocketFactoryImpl> (); tcpFactory->SetTcp (this); node->AggregateObject (tcpFactory); this->SetDownTarget (MakeCallback (&Ipv4L3Protocol::Send, ipv4)); } } } Object::NotifyNewAggregate (); } int NscTcpL4Protocol::GetProtocolNumber (void) const { return PROT_NUMBER; } int NscTcpL4Protocol::GetVersion (void) const { return 2; } void NscTcpL4Protocol::DoDispose (void) { NS_LOG_FUNCTION (this); for (std::vector<Ptr<NscTcpSocketImpl> >::iterator i = m_sockets.begin (); i != m_sockets.end (); i++) { *i = 0; } m_sockets.clear (); if (m_endPoints != 0) { delete m_endPoints; m_endPoints = 0; } m_node = 0; delete m_nscInterface; m_nscInterface = 0; m_downTarget.Nullify (); Ipv4L4Protocol::DoDispose (); } Ptr<Socket> NscTcpL4Protocol::CreateSocket (void) { NS_LOG_FUNCTION (this); Ptr<NscTcpSocketImpl> socket = CreateObject<NscTcpSocketImpl> (); socket->SetNode (m_node); socket->SetTcp (this); m_sockets.push_back (socket); return socket; } Ipv4EndPoint * NscTcpL4Protocol::Allocate (void) { NS_LOG_FUNCTION (this); return m_endPoints->Allocate (); } Ipv4EndPoint * NscTcpL4Protocol::Allocate (Ipv4Address address) { NS_LOG_FUNCTION (this << address); return m_endPoints->Allocate (address); } Ipv4EndPoint * NscTcpL4Protocol::Allocate (uint16_t port) { NS_LOG_FUNCTION (this << port); return m_endPoints->Allocate (port); } Ipv4EndPoint * NscTcpL4Protocol::Allocate (Ipv4Address address, uint16_t port) { NS_LOG_FUNCTION (this << address << port); return m_endPoints->Allocate (address, port); } Ipv4EndPoint * NscTcpL4Protocol::Allocate (Ipv4Address localAddress, uint16_t localPort, Ipv4Address peerAddress, uint16_t peerPort) { NS_LOG_FUNCTION (this << localAddress << localPort << peerAddress << peerPort); return m_endPoints->Allocate (localAddress, localPort, peerAddress, peerPort); } void NscTcpL4Protocol::DeAllocate (Ipv4EndPoint *endPoint) { NS_LOG_FUNCTION (this << endPoint); // NSC m_endPoints->DeAllocate (endPoint); } Ipv4L4Protocol::RxStatus NscTcpL4Protocol::Receive (Ptr<Packet> packet, Ipv4Header const &header, Ptr<Ipv4Interface> incomingInterface) { NS_LOG_FUNCTION (this << packet << header << incomingInterface); Ipv4Header ipHeader; uint32_t packetSize = packet->GetSize (); // The way things work at the moment, the IP header has been removed // by the ns-3 IPv4 processing code. However, the NSC stack expects // a complete IP packet, so we add the IP header back. // Since the original header is already gone, we create a new one // based on the information we have. ipHeader.SetSource (header.GetSource ()); ipHeader.SetDestination (header.GetDestination ()); ipHeader.SetProtocol (PROT_NUMBER); ipHeader.SetPayloadSize (packetSize); ipHeader.SetTtl (1); // all NSC stacks check the IP checksum ipHeader.EnableChecksum (); packet->AddHeader (ipHeader); packetSize = packet->GetSize (); uint8_t *buf = new uint8_t[packetSize]; packet->CopyData (buf, packetSize); const uint8_t *data = const_cast<uint8_t *>(buf); // deliver complete packet to the NSC network stack m_nscStack->if_receive_packet (0, data, packetSize); delete[] buf; wakeup (); return Ipv4L4Protocol::RX_OK; } void NscTcpL4Protocol::SoftInterrupt (void) { m_nscStack->timer_interrupt (); m_nscStack->increment_ticks (); m_softTimer.Schedule (); } void NscTcpL4Protocol::send_callback (const void* data, int datalen) { Ptr<Packet> p; uint32_t ipv4Saddr, ipv4Daddr; NS_ASSERT (datalen > 20); // create packet, without IP header. The TCP header is not touched. // Not using the IP header makes integration easier, but it destroys // eg. ECN. const uint8_t *rawdata = reinterpret_cast<const uint8_t *>(data); rawdata += 20; // skip IP header. IP options aren't supported at this time. datalen -= 20; p = Create<Packet> (rawdata, datalen); // we need the real source/destination ipv4 addresses for Send (). const uint32_t *ipheader = reinterpret_cast<const uint32_t *>(data); ipv4Saddr = *(ipheader+3); ipv4Daddr = *(ipheader+4); Ipv4Address saddr (ntohl (ipv4Saddr)); Ipv4Address daddr (ntohl (ipv4Daddr)); Ptr<Ipv4L3Protocol> ipv4 = m_node->GetObject<Ipv4L3Protocol> (); NS_ASSERT_MSG (ipv4, "nsc callback invoked, but node has no ipv4 object"); m_downTarget (p, saddr, daddr, PROT_NUMBER, 0); m_nscStack->if_send_finish (0); } void NscTcpL4Protocol::wakeup () { // TODO // this should schedule a timer to read from all tcp sockets now... this is // an indication that data might be waiting on the socket Ipv4EndPointDemux::EndPoints endPoints = m_endPoints->GetAllEndPoints (); for (Ipv4EndPointDemux::EndPointsI endPoint = endPoints.begin (); endPoint != endPoints.end (); endPoint++) { // NSC HACK: (ab)use TcpSocket::ForwardUp for signalling (*endPoint)->ForwardUp (NULL, Ipv4Header (), 0, 0); } } void NscTcpL4Protocol::gettime (unsigned int* sec, unsigned int* usec) { // Only used by the Linux network stack, e.g. during ISN generation // and in the kernel rng initialization routine. Also used in Linux // printk output. Time t = Simulator::Now (); int64_t us = t.GetMicroSeconds (); *sec = us / (1000*1000); *usec = us - *sec * (1000*1000); } void NscTcpL4Protocol::AddInterface (void) { Ptr<Ipv4> ip = m_node->GetObject<Ipv4> (); const uint32_t nInterfaces = ip->GetNInterfaces (); NS_ASSERT_MSG (nInterfaces <= 2, "nsc does not support multiple interfaces per node"); // start from 1, ignore the loopback interface (HACK) // we really don't need the loop, but its here to illustrate // how things _should_ be (once nsc can deal with multiple interfaces...) for (uint32_t i = 1; i < nInterfaces; i++) { Ipv4InterfaceAddress ifAddr = ip->GetAddress (i, 0); Ipv4Address addr = ifAddr.GetLocal (); Ipv4Mask mask = ifAddr.GetMask (); uint16_t mtu = ip->GetMtu (i); std::ostringstream addrOss, maskOss; addr.Print (addrOss); mask.Print (maskOss); NS_LOG_LOGIC ("if_attach " << addrOss.str ().c_str () << " " << maskOss.str ().c_str () << " " << mtu); std::string addrStr = addrOss.str (); std::string maskStr = maskOss.str (); const char* addrCStr = addrStr.c_str (); const char* maskCStr = maskStr.c_str (); m_nscStack->if_attach (addrCStr, maskCStr, mtu); if (i == 1) { // We need to come up with a default gateway here. Can't guarantee this to be // correct really... uint8_t addrBytes[4]; addr.Serialize (addrBytes); // XXX: this is all a bit of a horrible hack // // Just increment the last octet, this gives a decent chance of this being // 'enough'. // // All we need is another address on the same network as the interface. This // will force the stack to output the packet out of the network interface. addrBytes[3]++; addr.Deserialize (addrBytes); addrOss.str (""); addr.Print (addrOss); m_nscStack->add_default_gateway (addrOss.str ().c_str ()); } } } void NscTcpL4Protocol::SetDownTarget (Ipv4L4Protocol::DownTargetCallback callback) { m_downTarget = callback; } Ipv4L4Protocol::DownTargetCallback NscTcpL4Protocol::GetDownTarget (void) const { return m_downTarget; } } // namespace ns3
zy901002-gpsr
src/internet/model/nsc-tcp-l4-protocol.cc
C++
gpl2
13,250
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007 Georgia Tech Research Corporation * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Raj Bhattacharjea <raj.b@gatech.edu> */ #include "tcp-socket-factory.h" #include "ns3/uinteger.h" #include "ns3/double.h" namespace ns3 { NS_OBJECT_ENSURE_REGISTERED (TcpSocketFactory); TypeId TcpSocketFactory::GetTypeId (void) { static TypeId tid = TypeId ("ns3::TcpSocketFactory") .SetParent<SocketFactory> () ; return tid; } } // namespace ns3
zy901002-gpsr
src/internet/model/tcp-socket-factory.cc
C++
gpl2
1,152
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2008 INRIA * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr> */ #ifndef ICMPV4_H #define ICMPV4_H #include "ns3/header.h" #include "ns3/ptr.h" #include "ns3/ipv4-header.h" #include <stdint.h> namespace ns3 { class Packet; class Icmpv4Header : public Header { public: enum { ECHO_REPLY = 0, DEST_UNREACH = 3, ECHO = 8, TIME_EXCEEDED = 11 }; void EnableChecksum (void); void SetType (uint8_t type); void SetCode (uint8_t code); uint8_t GetType (void) const; uint8_t GetCode (void) const; static TypeId GetTypeId (void); Icmpv4Header (); virtual ~Icmpv4Header (); virtual TypeId GetInstanceTypeId (void) const; virtual uint32_t GetSerializedSize (void) const; virtual void Serialize (Buffer::Iterator start) const; virtual uint32_t Deserialize (Buffer::Iterator start); virtual void Print (std::ostream &os) const; private: uint8_t m_type; uint8_t m_code; bool m_calcChecksum; }; class Icmpv4Echo : public Header { public: void SetIdentifier (uint16_t id); void SetSequenceNumber (uint16_t seq); void SetData (Ptr<const Packet> data); uint16_t GetIdentifier (void) const; uint16_t GetSequenceNumber (void) const; uint32_t GetDataSize (void) const; uint32_t GetData (uint8_t payload[]) const; static TypeId GetTypeId (void); Icmpv4Echo (); virtual ~Icmpv4Echo (); virtual TypeId GetInstanceTypeId (void) const; virtual uint32_t GetSerializedSize (void) const; virtual void Serialize (Buffer::Iterator start) const; virtual uint32_t Deserialize (Buffer::Iterator start); virtual void Print (std::ostream &os) const; private: uint16_t m_identifier; uint16_t m_sequence; uint8_t *m_data; uint32_t m_dataSize; }; class Icmpv4DestinationUnreachable : public Header { public: enum { NET_UNREACHABLE = 0, HOST_UNREACHABLE = 1, PROTOCOL_UNREACHABLE = 2, PORT_UNREACHABLE = 3, FRAG_NEEDED = 4, SOURCE_ROUTE_FAILED = 5 }; static TypeId GetTypeId (void); Icmpv4DestinationUnreachable (); virtual ~Icmpv4DestinationUnreachable (); void SetNextHopMtu (uint16_t mtu); uint16_t GetNextHopMtu (void) const; void SetData (Ptr<const Packet> data); void SetHeader (Ipv4Header header); void GetData (uint8_t payload[8]) const; Ipv4Header GetHeader (void) const; private: virtual TypeId GetInstanceTypeId (void) const; virtual uint32_t GetSerializedSize (void) const; virtual void Serialize (Buffer::Iterator start) const; virtual uint32_t Deserialize (Buffer::Iterator start); virtual void Print (std::ostream &os) const; private: uint16_t m_nextHopMtu; Ipv4Header m_header; uint8_t m_data[8]; }; class Icmpv4TimeExceeded : public Header { public: enum { TIME_TO_LIVE = 0, FRAGMENT_REASSEMBLY = 1 }; void SetData (Ptr<const Packet> data); void SetHeader (Ipv4Header header); void GetData (uint8_t payload[8]) const; Ipv4Header GetHeader (void) const; static TypeId GetTypeId (void); Icmpv4TimeExceeded (); virtual ~Icmpv4TimeExceeded (); virtual TypeId GetInstanceTypeId (void) const; virtual uint32_t GetSerializedSize (void) const; virtual void Serialize (Buffer::Iterator start) const; virtual uint32_t Deserialize (Buffer::Iterator start); virtual void Print (std::ostream &os) const; private: Ipv4Header m_header; uint8_t m_data[8]; }; } // namespace ns3 #endif /* ICMPV4_H */
zy901002-gpsr
src/internet/model/icmpv4.h
C++
gpl2
4,125
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2005 INRIA * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr> */ #include "ipv4-end-point.h" #include "ns3/packet.h" #include "ns3/log.h" #include "ns3/simulator.h" NS_LOG_COMPONENT_DEFINE ("Ipv4EndPoint"); namespace ns3 { Ipv4EndPoint::Ipv4EndPoint (Ipv4Address address, uint16_t port) : m_localAddr (address), m_localPort (port), m_peerAddr (Ipv4Address::GetAny ()), m_peerPort (0) { } Ipv4EndPoint::~Ipv4EndPoint () { if (!m_destroyCallback.IsNull ()) { m_destroyCallback (); } } Ipv4Address Ipv4EndPoint::GetLocalAddress (void) { return m_localAddr; } void Ipv4EndPoint::SetLocalAddress (Ipv4Address address) { m_localAddr = address; } uint16_t Ipv4EndPoint::GetLocalPort (void) { return m_localPort; } Ipv4Address Ipv4EndPoint::GetPeerAddress (void) { return m_peerAddr; } uint16_t Ipv4EndPoint::GetPeerPort (void) { return m_peerPort; } void Ipv4EndPoint::SetPeer (Ipv4Address address, uint16_t port) { m_peerAddr = address; m_peerPort = port; } void Ipv4EndPoint::BindToNetDevice (Ptr<NetDevice> netdevice) { m_boundnetdevice = netdevice; return; } Ptr<NetDevice> Ipv4EndPoint::GetBoundNetDevice (void) { return m_boundnetdevice; } void Ipv4EndPoint::SetRxCallback (Callback<void,Ptr<Packet>, Ipv4Header, uint16_t, Ptr<Ipv4Interface> > callback) { m_rxCallback = callback; } void Ipv4EndPoint::SetIcmpCallback (Callback<void,Ipv4Address,uint8_t,uint8_t,uint8_t,uint32_t> callback) { m_icmpCallback = callback; } void Ipv4EndPoint::SetDestroyCallback (Callback<void> callback) { m_destroyCallback = callback; } void Ipv4EndPoint::ForwardUp (Ptr<Packet> p, const Ipv4Header& header, uint16_t sport, Ptr<Ipv4Interface> incomingInterface) { if (!m_rxCallback.IsNull ()) { Simulator::ScheduleNow (&Ipv4EndPoint::DoForwardUp, this, p, header, sport, incomingInterface); } } void Ipv4EndPoint::DoForwardUp (Ptr<Packet> p, const Ipv4Header& header, uint16_t sport, Ptr<Ipv4Interface> incomingInterface) { m_rxCallback (p, header, sport, incomingInterface); } void Ipv4EndPoint::ForwardIcmp (Ipv4Address icmpSource, uint8_t icmpTtl, uint8_t icmpType, uint8_t icmpCode, uint32_t icmpInfo) { NS_LOG_FUNCTION (this << icmpSource << (uint32_t)icmpTtl << (uint32_t)icmpType << (uint32_t)icmpCode << icmpInfo); if (!m_icmpCallback.IsNull ()) { Simulator::ScheduleNow (&Ipv4EndPoint::DoForwardIcmp, this, icmpSource, icmpTtl, icmpType, icmpCode, icmpInfo); } } void Ipv4EndPoint::DoForwardIcmp (Ipv4Address icmpSource, uint8_t icmpTtl, uint8_t icmpType, uint8_t icmpCode, uint32_t icmpInfo) { m_icmpCallback (icmpSource,icmpTtl,icmpType,icmpCode,icmpInfo); } } // namespace ns3
zy901002-gpsr
src/internet/model/ipv4-end-point.cc
C++
gpl2
3,688
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2005 INRIA * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr> */ #include "ns3/log.h" #include "ns3/assert.h" #include "ipv4-interface-address.h" NS_LOG_COMPONENT_DEFINE ("Ipv4InterfaceAddress"); namespace ns3 { Ipv4InterfaceAddress::Ipv4InterfaceAddress () : m_scope (GLOBAL), m_secondary (false) { NS_LOG_FUNCTION (this); } Ipv4InterfaceAddress::Ipv4InterfaceAddress (Ipv4Address local, Ipv4Mask mask) : m_scope (GLOBAL), m_secondary (false) { NS_LOG_FUNCTION (this); m_local = local; m_mask = mask; m_broadcast = Ipv4Address (local.Get () | (~mask.Get ())); } Ipv4InterfaceAddress::Ipv4InterfaceAddress (const Ipv4InterfaceAddress &o) : m_local (o.m_local), m_mask (o.m_mask), m_broadcast (o.m_broadcast), m_scope (o.m_scope), m_secondary (o.m_secondary) { NS_LOG_FUNCTION (this); } void Ipv4InterfaceAddress::SetLocal (Ipv4Address local) { NS_LOG_FUNCTION_NOARGS (); m_local = local; } Ipv4Address Ipv4InterfaceAddress::GetLocal (void) const { NS_LOG_FUNCTION_NOARGS (); return m_local; } void Ipv4InterfaceAddress::SetMask (Ipv4Mask mask) { NS_LOG_FUNCTION_NOARGS (); m_mask = mask; } Ipv4Mask Ipv4InterfaceAddress::GetMask (void) const { NS_LOG_FUNCTION_NOARGS (); return m_mask; } void Ipv4InterfaceAddress::SetBroadcast (Ipv4Address broadcast) { NS_LOG_FUNCTION_NOARGS (); m_broadcast = broadcast; } Ipv4Address Ipv4InterfaceAddress::GetBroadcast (void) const { NS_LOG_FUNCTION_NOARGS (); return m_broadcast; } void Ipv4InterfaceAddress::SetScope (Ipv4InterfaceAddress::InterfaceAddressScope_e scope) { NS_LOG_FUNCTION_NOARGS (); m_scope = scope; } Ipv4InterfaceAddress::InterfaceAddressScope_e Ipv4InterfaceAddress::GetScope (void) const { NS_LOG_FUNCTION_NOARGS (); return m_scope; } bool Ipv4InterfaceAddress::IsSecondary (void) const { NS_LOG_FUNCTION_NOARGS (); return m_secondary; } void Ipv4InterfaceAddress::SetSecondary (void) { NS_LOG_FUNCTION_NOARGS (); m_secondary = true; } void Ipv4InterfaceAddress::SetPrimary (void) { NS_LOG_FUNCTION_NOARGS (); m_secondary = false; } std::ostream& operator<< (std::ostream& os, const Ipv4InterfaceAddress &addr) { os << "m_local=" << addr.GetLocal () << "; m_mask=" << addr.GetMask () << "; m_broadcast=" << addr.GetBroadcast () << "; m_scope=" << addr.GetScope () << "; m_secondary=" << addr.IsSecondary (); return os; } } // namespace ns3
zy901002-gpsr
src/internet/model/ipv4-interface-address.cc
C++
gpl2
3,178
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007-2009 Strasbourg University * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: David Gross <gdavid.devel@gmail.com> */ #ifndef IPV6_OPTION_DEMUX_H #define IPV6_OPTION_DEMUX_H #include <list> #include "ns3/object.h" #include "ns3/ptr.h" namespace ns3 { class Ipv6Option; class Node; /** * \class Ipv6OptionDemux * \brief IPv6 Option Demux. */ class Ipv6OptionDemux : public Object { public: /** * \brief The interface ID. * \return type ID */ static TypeId GetTypeId (void); /** * \brief Constructor. */ Ipv6OptionDemux (); /** * \brief Destructor. */ virtual ~Ipv6OptionDemux (); /** * \brief Set the node. * \param node the node to set */ void SetNode (Ptr<Node> node); /** * \brief Insert a new IPv6 Option. * \param option the option to insert */ void Insert (Ptr<Ipv6Option> option); /** * \brief Get the option corresponding to optionNumber. * \param optionNumber the option number of the option to retrieve * \return a matching IPv6 option */ Ptr<Ipv6Option> GetOption (int optionNumber); /** * \brief Remove an option from this demux. * \param option pointer on the option to remove */ void Remove (Ptr<Ipv6Option> option); protected: /** * \brief Dispose this object. */ virtual void DoDispose (); private: typedef std::list<Ptr<Ipv6Option> > Ipv6OptionList_t; /** * \brief List of IPv6 Options supported. */ Ipv6OptionList_t m_options; /** * \brief The node. */ Ptr<Node> m_node; }; } /* namespace ns3 */ #endif /* IPV6_OPTION_DEMUX_H */
zy901002-gpsr
src/internet/model/ipv6-option-demux.h
C++
gpl2
2,293
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright 2007 University of Washington * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Authors: Craig Dowell (craigdo@ee.washington.edu) * Tom Henderson (tomhend@u.washington.edu) */ #ifndef GLOBAL_ROUTER_INTERFACE_H #define GLOBAL_ROUTER_INTERFACE_H #include <stdint.h> #include <list> #include "ns3/object.h" #include "ns3/ptr.h" #include "ns3/node.h" #include "ns3/channel.h" #include "ns3/ipv4-address.h" #include "ns3/net-device-container.h" #include "ns3/bridge-net-device.h" #include "ns3/global-route-manager.h" #include "ns3/ipv4-routing-table-entry.h" namespace ns3 { class GlobalRouter; class Ipv4GlobalRouting; /** * @brief A single link record for a link state advertisement. * * The GlobalRoutingLinkRecord is modeled after the OSPF link record field of * a Link State Advertisement. Right now we will only see two types of link * records corresponding to a stub network and a point-to-point link (channel). */ class GlobalRoutingLinkRecord { public: friend class GlobalRoutingLSA; /** * @enum LinkType * @brief Enumeration of the possible types of Global Routing Link Records. * * These values are defined in the OSPF spec. We currently only use * PointToPoint and StubNetwork types. */ enum LinkType { Unknown = 0, /**< Uninitialized Link Record */ PointToPoint, /**< Record representing a point to point channel */ TransitNetwork, /**< Unused -- for future OSPF compatibility */ StubNetwork, /**< Record represents a leaf node network */ VirtualLink /**< Unused -- for future OSPF compatibility */ }; /** * @brief Construct an empty ("uninitialized") Global Routing Link Record. * * The Link ID and Link Data Ipv4 addresses are set to "0.0.0.0"; * The Link Type is set to Unknown; * The metric is set to 0. */ GlobalRoutingLinkRecord (); /** * Construct an initialized Global Routing Link Record. * * @param linkType The type of link record to construct. * @param linkId The link ID for the record. * @param linkData The link data field for the record. * @param metric The metric field for the record. * @see LinkType * @see SetLinkId * @see SetLinkData */ GlobalRoutingLinkRecord ( LinkType linkType, Ipv4Address linkId, Ipv4Address linkData, uint16_t metric); /** * @brief Destroy a Global Routing Link Record. * * Currently does nothing. Here as a placeholder only. */ ~GlobalRoutingLinkRecord (); /** * Get the Link ID field of the Global Routing Link Record. * * For an OSPF type 1 link (PointToPoint) the Link ID will be the Router ID * of the neighboring router. * * For an OSPF type 3 link (StubNetwork), the Link ID will be the adjacent * neighbor's IP address * * @returns The Ipv4Address corresponding to the Link ID field of the record. */ Ipv4Address GetLinkId (void) const; /** * @brief Set the Link ID field of the Global Routing Link Record. * * For an OSPF type 1 link (PointToPoint) the Link ID must be the Router ID * of the neighboring router. * * For an OSPF type 3 link (StubNetwork), the Link ID must be the adjacent * neighbor's IP address * * @param addr An Ipv4Address to store in the Link ID field of the record. */ void SetLinkId (Ipv4Address addr); /** * @brief Get the Link Data field of the Global Routing Link Record. * * For an OSPF type 1 link (PointToPoint) the Link Data will be the IP * address of the node of the local side of the link. * * For an OSPF type 3 link (StubNetwork), the Link Data will be the * network mask * * @returns The Ipv4Address corresponding to the Link Data field of the record. */ Ipv4Address GetLinkData (void) const; /** * @brief Set the Link Data field of the Global Routing Link Record. * * For an OSPF type 1 link (PointToPoint) the Link Data must be the IP * address of the node of the local side of the link. * * For an OSPF type 3 link (StubNetwork), the Link Data must be set to the * network mask * * @param addr An Ipv4Address to store in the Link Data field of the record. */ void SetLinkData (Ipv4Address addr); /** * @brief Get the Link Type field of the Global Routing Link Record. * * The Link Type describes the kind of link a given record represents. The * values are defined by OSPF. * * @see LinkType * @returns The LinkType of the current Global Routing Link Record. */ LinkType GetLinkType (void) const; /** * @brief Set the Link Type field of the Global Routing Link Record. * * The Link Type describes the kind of link a given record represents. The * values are defined by OSPF. * * @see LinkType * @param linkType The new LinkType for the current Global Routing Link Record. */ void SetLinkType (LinkType linkType); /** * @brief Get the Metric Data field of the Global Routing Link Record. * * The metric is an abstract cost associated with forwarding a packet across * a link. A sum of metrics must have a well-defined meaning. That is, you * shouldn't use bandwidth as a metric (how does the sum of the bandwidth of * two hops relate to the cost of sending a packet); rather you should use * something like delay. * * @returns The metric field of the Global Routing Link Record. */ uint16_t GetMetric (void) const; /** * @brief Set the Metric Data field of the Global Routing Link Record. * * The metric is an abstract cost associated with forwarding a packet across * a link. A sum of metrics must have a well-defined meaning. That is, you * shouldn't use bandwidth as a metric (how does the sum of the bandwidth of * two hops relate to the cost of sending a packet); rather you should use * something like delay. * * @param metric The new metric for the current Global Routing Link Record. */ void SetMetric (uint16_t metric); private: /** * m_linkId and m_linkData are defined by OSPF to have different meanings * depending on the type of link a given link records represents. They work * together. * * For Type 1 link (PointToPoint), set m_linkId to Router ID of * neighboring router. * * For Type 3 link (Stub), set m_linkId to neighbor's IP address */ Ipv4Address m_linkId; /** * m_linkId and m_linkData are defined by OSPF to have different meanings * depending on the type of link a given link records represents. They work * together. * * For Type 1 link (PointToPoint), set m_linkData to local IP address * * For Type 3 link (Stub), set m_linkData to mask */ Ipv4Address m_linkData; // for links to RouterLSA, /** * The type of the Global Routing Link Record. Defined in the OSPF spec. * We currently only use PointToPoint and StubNetwork types. */ LinkType m_linkType; /** * The metric for a given link. * * A metric is abstract cost associated with forwarding a packet across a * link. A sum of metrics must have a well-defined meaning. That is, you * shouldn't use bandwidth as a metric (how does the sum of the bandwidth * of two hops relate to the cost of sending a packet); rather you should * use something like delay. */ uint16_t m_metric; }; /** * @brief a Link State Advertisement (LSA) for a router, used in global * routing. * * Roughly equivalent to a global incarnation of the OSPF link state header * combined with a list of Link Records. Since it's global, there's * no need for age or sequence number. See RFC 2328, Appendix A. */ class GlobalRoutingLSA { public: /** * @enum LSType * @brief corresponds to LS type field of RFC 2328 OSPF LSA header */ enum LSType { Unknown = 0, /**< Uninitialized Type */ RouterLSA, NetworkLSA, SummaryLSA, SummaryLSA_ASBR, ASExternalLSAs }; /** * @enum SPFStatus * @brief Enumeration of the possible values of the status flag in the Routing * Link State Advertisements. */ enum SPFStatus { LSA_SPF_NOT_EXPLORED = 0, /**< New vertex not yet considered */ LSA_SPF_CANDIDATE, /**< Vertex is in the SPF candidate queue */ LSA_SPF_IN_SPFTREE /**< Vertex is in the SPF tree */ }; /** * @brief Create a blank Global Routing Link State Advertisement. * * On completion Ipv4Address variables initialized to 0.0.0.0 and the * list of Link State Records is empty. */ GlobalRoutingLSA(); /** * @brief Create an initialized Global Routing Link State Advertisement. * * On completion the list of Link State Records is empty. * * @param status The status to of the new LSA. * @param linkStateId The Ipv4Address for the link state ID field. * @param advertisingRtr The Ipv4Address for the advertising router field. */ GlobalRoutingLSA(SPFStatus status, Ipv4Address linkStateId, Ipv4Address advertisingRtr); /** * @brief Copy constructor for a Global Routing Link State Advertisement. * * Takes a piece of memory and constructs a semantically identical copy of * the given LSA. * * @param lsa The existing LSA to be used as the source. */ GlobalRoutingLSA (GlobalRoutingLSA& lsa); /** * @brief Destroy an existing Global Routing Link State Advertisement. * * Any Global Routing Link Records present in the list are freed. */ ~GlobalRoutingLSA(); /** * @brief Assignment operator for a Global Routing Link State Advertisement. * * Takes an existing Global Routing Link State Advertisement and overwrites * it to make a semantically identical copy of a given prototype LSA. * * If there are any Global Routing Link Records present in the existing * LSA, they are freed before the assignment happens. * * @param lsa The existing LSA to be used as the source. * @returns Reference to the overwritten LSA. */ GlobalRoutingLSA& operator= (const GlobalRoutingLSA& lsa); /** * @brief Copy any Global Routing Link Records in a given Global Routing Link * State Advertisement to the current LSA. * * Existing Link Records are not deleted -- this is a concatenation of Link * Records. * * @see ClearLinkRecords () * @param lsa The LSA to copy the Link Records from. */ void CopyLinkRecords (const GlobalRoutingLSA& lsa); /** * @brief Add a given Global Routing Link Record to the LSA. * * @param lr The Global Routing Link Record to be added. * @returns The number of link records in the list. */ uint32_t AddLinkRecord (GlobalRoutingLinkRecord* lr); /** * @brief Return the number of Global Routing Link Records in the LSA. * * @returns The number of link records in the list. */ uint32_t GetNLinkRecords (void) const; /** * @brief Return a pointer to the specified Global Routing Link Record. * * @param n The LSA number desired. * @returns The number of link records in the list. */ GlobalRoutingLinkRecord* GetLinkRecord (uint32_t n) const; /** * @brief Release all of the Global Routing Link Records present in the Global * Routing Link State Advertisement and make the list of link records empty. */ void ClearLinkRecords (void); /** * @brief Check to see if the list of Global Routing Link Records present in the * Global Routing Link State Advertisement is empty. * * @returns True if the list is empty, false otherwise. */ bool IsEmpty (void) const; /** * @brief Print the contents of the Global Routing Link State Advertisement and * any Global Routing Link Records present in the list. Quite verbose. */ void Print (std::ostream &os) const; /** * @brief Return the LSType field of the LSA */ LSType GetLSType (void) const; /** * @brief Set the LS type field of the LSA */ void SetLSType (LSType typ); /** * @brief Get the Link State ID as defined by the OSPF spec. We always set it * to the router ID of the router making the advertisement. * * @see RoutingEnvironment::AllocateRouterId () * @see GlobalRouting::GetRouterId () * @returns The Ipv4Address stored as the link state ID. */ Ipv4Address GetLinkStateId (void) const; /** * @brief Set the Link State ID is defined by the OSPF spec. We always set it * to the router ID of the router making the advertisement. * @param addr IPv4 address which will act as ID * @see RoutingEnvironment::AllocateRouterId () * @see GlobalRouting::GetRouterId () */ void SetLinkStateId (Ipv4Address addr); /** * @brief Get the Advertising Router as defined by the OSPF spec. We always * set it to the router ID of the router making the advertisement. * * @see RoutingEnvironment::AllocateRouterId () * @see GlobalRouting::GetRouterId () * @returns The Ipv4Address stored as the advertising router. */ Ipv4Address GetAdvertisingRouter (void) const; /** * @brief Set the Advertising Router as defined by the OSPF spec. We always * set it to the router ID of the router making the advertisement. * * @param rtr ID of the router making advertisement * @see RoutingEnvironment::AllocateRouterId () * @see GlobalRouting::GetRouterId () */ void SetAdvertisingRouter (Ipv4Address rtr); /** * @brief For a Network LSA, set the Network Mask field that precedes * the list of attached routers. */ void SetNetworkLSANetworkMask (Ipv4Mask mask); /** * @brief For a Network LSA, get the Network Mask field that precedes * the list of attached routers. * * @returns the NetworkLSANetworkMask */ Ipv4Mask GetNetworkLSANetworkMask (void) const; /** * @brief Add an attached router to the list in the NetworkLSA * * @param addr The Ipv4Address of the interface on the network link * @returns The number of addresses in the list. */ uint32_t AddAttachedRouter (Ipv4Address addr); /** * @brief Return the number of attached routers listed in the NetworkLSA * * @returns The number of attached routers. */ uint32_t GetNAttachedRouters (void) const; /** * @brief Return an Ipv4Address corresponding to the specified attached router * * @param n The attached router number desired (number in the list). * @returns The Ipv4Address of the requested router */ Ipv4Address GetAttachedRouter (uint32_t n) const; /** * @brief Get the SPF status of the advertisement. * * @see SPFStatus * @returns The SPFStatus of the LSA. */ SPFStatus GetStatus (void) const; /** * @brief Set the SPF status of the advertisement * @param status SPF status to set * @see SPFStatus */ void SetStatus (SPFStatus status); /** * @brief Get the Node pointer of the node that originated this LSA * @returns Node pointer */ Ptr<Node> GetNode (void) const; /** * @brief Set the Node pointer of the node that originated this LSA * @param node Node pointer */ void SetNode (Ptr<Node> node); private: /** * The type of the LSA. Each LSA type has a separate advertisement * format. */ LSType m_lsType; /** * The Link State ID is defined by the OSPF spec. We always set it to the * router ID of the router making the advertisement. * * @see RoutingEnvironment::AllocateRouterId () * @see GlobalRouting::GetRouterId () */ Ipv4Address m_linkStateId; /** * The Advertising Router is defined by the OSPF spec. We always set it to * the router ID of the router making the advertisement. * * @see RoutingEnvironment::AllocateRouterId () * @see GlobalRouting::GetRouterId () */ Ipv4Address m_advertisingRtr; /** * A convenience typedef to avoid too much writers cramp. */ typedef std::list<GlobalRoutingLinkRecord*> ListOfLinkRecords_t; /** * Each Link State Advertisement contains a number of Link Records that * describe the kinds of links that are attached to a given node. We * consider PointToPoint and StubNetwork links. * * m_linkRecords is an STL list container to hold the Link Records that have * been discovered and prepared for the advertisement. * * @see GlobalRouting::DiscoverLSAs () */ ListOfLinkRecords_t m_linkRecords; /** * Each Network LSA contains the network mask of the attached network */ Ipv4Mask m_networkLSANetworkMask; /** * A convenience typedef to avoid too much writers cramp. */ typedef std::list<Ipv4Address> ListOfAttachedRouters_t; /** * Each Network LSA contains a list of attached routers * * m_attachedRouters is an STL list container to hold the addresses that have * been discovered and prepared for the advertisement. * * @see GlobalRouting::DiscoverLSAs () */ ListOfAttachedRouters_t m_attachedRouters; /** * This is a tristate flag used internally in the SPF computation to mark * if an SPFVertex (a data structure representing a vertex in the SPF tree * -- a router) is new, is a candidate for a shortest path, or is in its * proper position in the tree. */ SPFStatus m_status; uint32_t m_node_id; }; std::ostream& operator<< (std::ostream& os, GlobalRoutingLSA& lsa); /** * @brief An interface aggregated to a node to provide global routing info * * An interface aggregated to a node that provides global routing information * to a global route manager. The presence of the interface indicates that * the node is a router. The interface is the mechanism by which the router * advertises its connections to neighboring routers. We're basically * allowing the route manager to query for link state advertisements. */ class GlobalRouter : public Object { public: /** * @brief The Interface ID of the Global Router interface. * * @see Object::GetObject () */ static TypeId GetTypeId (void); /** * @brief Create a Global Router class */ GlobalRouter (); void SetRoutingProtocol (Ptr<Ipv4GlobalRouting> routing); Ptr<Ipv4GlobalRouting> GetRoutingProtocol (void); /** * @brief Get the Router ID associated with this Global Router. * * The Router IDs are allocated in the RoutingEnvironment -- one per Router, * starting at 0.0.0.1 and incrementing with each instantiation of a router. * * @see RoutingEnvironment::AllocateRouterId () * @returns The Router ID associated with the Global Router. */ Ipv4Address GetRouterId (void) const; /** * @brief Walk the connected channels, discover the adjacent routers and build * the associated number of Global Routing Link State Advertisements that * this router can export. * * This is a fairly expensive operation in that every time it is called * the current list of LSAs is built by walking connected point-to-point * channels and peeking into adjacent IPV4 stacks to get address information. * This is done to allow for limited dynamics of the Global Routing * environment. By that we mean that you can discover new link state * advertisements after a network topology change by calling DiscoverLSAs * and then by reading those advertisements. * * @see GlobalRoutingLSA * @see GlobalRouter::GetLSA () * @returns The number of Global Routing Link State Advertisements. */ uint32_t DiscoverLSAs (void); /** * @brief Get the Number of Global Routing Link State Advertisements that this * router can export. * * To get meaningful information you must have previously called DiscoverLSAs. * After you know how many LSAs are present in the router, you may call * GetLSA () to retrieve the actual advertisement. * * @see GlobalRouterLSA * @see GlobalRouting::DiscoverLSAs () * @see GlobalRouting::GetLSA () * @returns The number of Global Routing Link State Advertisements. */ uint32_t GetNumLSAs (void) const; /** * @brief Get a Global Routing Link State Advertisements that this router has * said that it can export. * * This is a fairly inexpensive expensive operation in that the hard work * was done in GetNumLSAs. We just copy the indicated Global Routing Link * State Advertisement into the requested GlobalRoutingLSA object. * * You must call GlobalRouter::GetNumLSAs before calling this method in * order to discover the adjacent routers and build the advertisements. * GetNumLSAs will return the number of LSAs this router advertises. * The parameter n (requested LSA number) must be in the range 0 to * GetNumLSAs() - 1. * * @see GlobalRoutingLSA * @see GlobalRouting::GetNumLSAs () * @param n The index number of the LSA you want to read. * @param lsa The GlobalRoutingLSA class to receive the LSA information. * @returns The number of Global Router Link State Advertisements. */ bool GetLSA (uint32_t n, GlobalRoutingLSA &lsa) const; /** * @brief Inject a route to be circulated to other routers as an external * route * * @param network The Network to inject * @param networkMask The Network Mask to inject */ void InjectRoute (Ipv4Address network, Ipv4Mask networkMask); /** * @brief Get the number of injected routes that have been added * to the routing table. * @return number of injected routes */ uint32_t GetNInjectedRoutes (void); /** * @brief Return the injected route indexed by i * @param i the index of the route * @return a pointer to that Ipv4RoutingTableEntry is returned * */ Ipv4RoutingTableEntry *GetInjectedRoute (uint32_t i); /** * @brief Withdraw a route from the global unicast routing table. * * Calling this function will cause all indexed routes numbered above * index i to have their index decremented. For instance, it is possible to * remove N injected routes by calling RemoveInjectedRoute (0) N times. * * @param i The index (into the injected routing list) of the route to remove. * * @see GlobalRouter::WithdrawRoute () */ void RemoveInjectedRoute (uint32_t i); /** * @brief Withdraw a route from the global unicast routing table. * * @param network The Network to withdraw * @param networkMask The Network Mask to withdraw * @return whether the operation succeeded (will return false if no such route) * * @see GlobalRouter::RemoveInjectedRoute () */ bool WithdrawRoute (Ipv4Address network, Ipv4Mask networkMask); private: virtual ~GlobalRouter (); void ClearLSAs (void); Ptr<NetDevice> GetAdjacent (Ptr<NetDevice> nd, Ptr<Channel> ch) const; bool FindInterfaceForDevice (Ptr<Node> node, Ptr<NetDevice> nd, uint32_t &index) const; Ipv4Address FindDesignatedRouterForLink (Ptr<NetDevice> ndLocal, bool allowRecursion) const; bool AnotherRouterOnLink (Ptr<NetDevice> nd, bool allowRecursion) const; void ProcessBroadcastLink (Ptr<NetDevice> nd, GlobalRoutingLSA *pLSA, NetDeviceContainer &c); void ProcessSingleBroadcastLink (Ptr<NetDevice> nd, GlobalRoutingLSA *pLSA, NetDeviceContainer &c); void ProcessBridgedBroadcastLink (Ptr<NetDevice> nd, GlobalRoutingLSA *pLSA, NetDeviceContainer &c); void ProcessPointToPointLink (Ptr<NetDevice> ndLocal, GlobalRoutingLSA *pLSA); void BuildNetworkLSAs (NetDeviceContainer c); Ptr<BridgeNetDevice> NetDeviceIsBridged (Ptr<NetDevice> nd) const; typedef std::list<GlobalRoutingLSA*> ListOfLSAs_t; ListOfLSAs_t m_LSAs; Ipv4Address m_routerId; Ptr<Ipv4GlobalRouting> m_routingProtocol; typedef std::list<Ipv4RoutingTableEntry *> InjectedRoutes; typedef std::list<Ipv4RoutingTableEntry *>::const_iterator InjectedRoutesCI; typedef std::list<Ipv4RoutingTableEntry *>::iterator InjectedRoutesI; InjectedRoutes m_injectedRoutes; // Routes we are exporting // inherited from Object virtual void DoDispose (void); /** * @brief Global Router copy construction is disallowed. */ GlobalRouter (GlobalRouter& sr); /** * @brief Global Router assignment operator is disallowed. */ GlobalRouter& operator= (GlobalRouter& sr); }; } // namespace ns3 #endif /* GLOBAL_ROUTER_INTERFACE_H */
zy901002-gpsr
src/internet/model/global-router-interface.h
C++
gpl2
23,890
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ // // Copyright (c) 2006 Georgia Tech Research Corporation // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation; // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Author: Rajib Bhattacharjea<raj.b@gatech.edu> // // Georgia Tech Network Simulator - Round Trip Time Estimation Class // George F. Riley. Georgia Tech, Spring 2002 #ifndef RTT_ESTIMATOR_H #define RTT_ESTIMATOR_H #include <deque> #include "ns3/sequence-number.h" #include "ns3/nstime.h" #include "ns3/object.h" namespace ns3 { /** * \ingroup tcp * * \brief Implements several variations of round trip time estimators */ class RttHistory { public: RttHistory (SequenceNumber32 s, uint32_t c, Time t); RttHistory (const RttHistory& h); // Copy constructor public: SequenceNumber32 seq; // First sequence number in packet sent uint32_t count; // Number of bytes sent Time time; // Time this one was sent bool retx; // True if this has been retransmitted }; typedef std::deque<RttHistory> RttHistory_t; class RttEstimator : public Object { // Base class for all RTT Estimators public: static TypeId GetTypeId (void); RttEstimator(); RttEstimator(const RttEstimator&); // Copy constructor virtual ~RttEstimator(); virtual void SentSeq (SequenceNumber32, uint32_t); virtual Time AckSeq (SequenceNumber32); virtual void ClearSent (); virtual void Measurement (Time t) = 0; virtual Time RetransmitTimeout () = 0; void Init (SequenceNumber32 s) { next = s; } virtual Ptr<RttEstimator> Copy () const = 0; virtual void IncreaseMultiplier (); virtual void ResetMultiplier (); virtual void Reset (); void SetMinRto (Time minRto); Time GetMinRto (void) const; void SetEstimate (Time estimate); Time GetEstimate (void) const; private: SequenceNumber32 next; // Next expected sequence to be sent RttHistory_t history; // List of sent packet double m_maxMultiplier; public: int64x64_t est; // Current estimate int64x64_t minrto; // minimum value of the timeout uint32_t nSamples; // Number of samples double multiplier; // RTO Multiplier }; // The "Mean-Deviation" estimator, as discussed by Van Jacobson // "Congestion Avoidance and Control", SIGCOMM 88, Appendix A //Doc:Class Class {\tt RttMeanDeviation} implements the "Mean--Deviation" estimator //Doc:Class as described by Van Jacobson //Doc:Class "Congestion Avoidance and Control", SIGCOMM 88, Appendix A class RttMeanDeviation : public RttEstimator { public: static TypeId GetTypeId (void); RttMeanDeviation (); //Doc:Method RttMeanDeviation (const RttMeanDeviation&); // Copy constructor //Doc:Desc Copy constructor. //Doc:Arg1 {\tt RttMeanDeviation} object to copy. void Measurement (Time); Time RetransmitTimeout (); Ptr<RttEstimator> Copy () const; void Reset (); void Gain (double g) { gain = g; } public: double gain; // Filter gain int64x64_t variance; // Current variance }; } // namespace ns3 #endif /* RTT_ESTIMATOR_H */
zy901002-gpsr
src/internet/model/rtt-estimator.h
C++
gpl2
3,664
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright 2007 University of Washington * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <algorithm> #include <iostream> #include "ns3/log.h" #include "ns3/assert.h" #include "candidate-queue.h" #include "global-route-manager-impl.h" NS_LOG_COMPONENT_DEFINE ("CandidateQueue"); namespace ns3 { std::ostream& operator<< (std::ostream& os, const SPFVertex::VertexType& t) { switch (t) { case SPFVertex::VertexRouter: os << "router"; break; case SPFVertex::VertexNetwork: os << "network"; break; default: os << "unknown"; break; }; return os; } std::ostream& operator<< (std::ostream& os, const CandidateQueue& q) { typedef CandidateQueue::CandidateList_t List_t; typedef List_t::const_iterator CIter_t; const CandidateQueue::CandidateList_t& list = q.m_candidates; os << "*** CandidateQueue Begin (<id, distance, LSA-type>) ***" << std::endl; for (CIter_t iter = list.begin (); iter != list.end (); iter++) { os << "<" << (*iter)->GetVertexId () << ", " << (*iter)->GetDistanceFromRoot () << ", " << (*iter)->GetVertexType () << ">" << std::endl; } os << "*** CandidateQueue End ***"; return os; } CandidateQueue::CandidateQueue() : m_candidates () { NS_LOG_FUNCTION_NOARGS (); } CandidateQueue::~CandidateQueue() { NS_LOG_FUNCTION_NOARGS (); Clear (); } void CandidateQueue::Clear (void) { NS_LOG_FUNCTION_NOARGS (); while (!m_candidates.empty ()) { SPFVertex *p = Pop (); delete p; p = 0; } } void CandidateQueue::Push (SPFVertex *vNew) { NS_LOG_FUNCTION (this << vNew); CandidateList_t::iterator i = std::upper_bound ( m_candidates.begin (), m_candidates.end (), vNew, &CandidateQueue::CompareSPFVertex ); m_candidates.insert (i, vNew); } SPFVertex * CandidateQueue::Pop (void) { NS_LOG_FUNCTION_NOARGS (); if (m_candidates.empty ()) { return 0; } SPFVertex *v = m_candidates.front (); m_candidates.pop_front (); return v; } SPFVertex * CandidateQueue::Top (void) const { NS_LOG_FUNCTION_NOARGS (); if (m_candidates.empty ()) { return 0; } return m_candidates.front (); } bool CandidateQueue::Empty (void) const { NS_LOG_FUNCTION_NOARGS (); return m_candidates.empty (); } uint32_t CandidateQueue::Size (void) const { NS_LOG_FUNCTION_NOARGS (); return m_candidates.size (); } SPFVertex * CandidateQueue::Find (const Ipv4Address addr) const { NS_LOG_FUNCTION_NOARGS (); CandidateList_t::const_iterator i = m_candidates.begin (); for (; i != m_candidates.end (); i++) { SPFVertex *v = *i; if (v->GetVertexId () == addr) { return v; } } return 0; } void CandidateQueue::Reorder (void) { NS_LOG_FUNCTION_NOARGS (); m_candidates.sort (&CandidateQueue::CompareSPFVertex); NS_LOG_LOGIC ("After reordering the CandidateQueue"); NS_LOG_LOGIC (*this); } /* * In this implementation, SPFVertex follows the ordering where * a vertex is ranked first if its GetDistanceFromRoot () is smaller; * In case of a tie, NetworkLSA is always ranked before RouterLSA. * * This ordering is necessary for implementing ECMP */ bool CandidateQueue::CompareSPFVertex (const SPFVertex* v1, const SPFVertex* v2) { NS_LOG_FUNCTION (&v1 << &v2); bool result = false; if (v1->GetDistanceFromRoot () < v2->GetDistanceFromRoot ()) { result = true; } else if (v1->GetDistanceFromRoot () == v2->GetDistanceFromRoot ()) { if (v1->GetVertexType () == SPFVertex::VertexNetwork && v2->GetVertexType () == SPFVertex::VertexRouter) { result = true; } } return result; } } // namespace ns3
zy901002-gpsr
src/internet/model/candidate-queue.cc
C++
gpl2
4,413
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef NSC_TCP_L4_PROTOCOL_H #define NSC_TCP_L4_PROTOCOL_H #include <stdint.h> #include "ns3/packet.h" #include "ns3/ipv4-address.h" #include "ns3/ptr.h" #include "ns3/object-factory.h" #include "ns3/timer.h" #include "ipv4-l4-protocol.h" struct INetStack; namespace ns3 { class Node; class Socket; class Ipv4EndPointDemux; class Ipv4Interface; class NscTcpSocketImpl; class Ipv4EndPoint; class NscInterfaceImpl; /** * \ingroup nsctcp * * \brief Nsc wrapper glue, to interface with the Ipv4 protocol underneath. */ class NscTcpL4Protocol : public Ipv4L4Protocol { public: static const uint8_t PROT_NUMBER; static TypeId GetTypeId (void); /** * \brief Constructor */ NscTcpL4Protocol (); virtual ~NscTcpL4Protocol (); void SetNode (Ptr<Node> node); void SetNscLibrary (const std::string &lib); std::string GetNscLibrary (void) const; virtual int GetProtocolNumber (void) const; virtual int GetVersion (void) const; /** * \return A smart Socket pointer to a NscTcpSocketImpl, allocated by this instance * of the TCP protocol */ Ptr<Socket> CreateSocket (void); Ipv4EndPoint *Allocate (void); Ipv4EndPoint *Allocate (Ipv4Address address); Ipv4EndPoint *Allocate (uint16_t port); Ipv4EndPoint *Allocate (Ipv4Address address, uint16_t port); Ipv4EndPoint *Allocate (Ipv4Address localAddress, uint16_t localPort, Ipv4Address peerAddress, uint16_t peerPort); void DeAllocate (Ipv4EndPoint *endPoint); /** * \brief Receive a packet up the protocol stack * \param p The Packet to dump the contents into * \param header IPv4 Header information * \param incomingInterface The Ipv4Interface it was received on */ virtual Ipv4L4Protocol::RxStatus Receive (Ptr<Packet> p, Ipv4Header const &header, Ptr<Ipv4Interface> incomingInterface); // From Ipv4L4Protocol virtual void SetDownTarget (Ipv4L4Protocol::DownTargetCallback cb); // From Ipv4L4Protocol virtual Ipv4L4Protocol::DownTargetCallback GetDownTarget (void) const; protected: virtual void DoDispose (void); virtual void NotifyNewAggregate (); private: NscTcpL4Protocol (NscTcpL4Protocol const &); NscTcpL4Protocol& operator= (NscTcpL4Protocol const &); // NSC callbacks. // NSC invokes these hooks to interact with the simulator. // In any case, these methods are only to be called by NSC. // // send_callback is invoked by NSCs 'ethernet driver' to re-inject // a packet (i.e. an octet soup consisting of an IP Header, TCP Header // and user payload, if any), into ns-3. void send_callback (const void *data, int datalen); // This is called by the NSC stack whenever something of interest // has happened, e.g. when data arrives on a socket, a listen socket // has a new connection pending, etc. void wakeup (); // This is called by the Linux stack RNG initialization. // Its also used by the cradle code to add a timestamp to // printk/printf/debug output. void gettime (unsigned int *sec, unsigned int *usec); void AddInterface (void); void SoftInterrupt (void); friend class NscInterfaceImpl; friend class NscTcpSocketImpl; Ptr<Node> m_node; Ipv4EndPointDemux *m_endPoints; INetStack* m_nscStack; NscInterfaceImpl *m_nscInterface; void *m_dlopenHandle; std::string m_nscLibrary; Timer m_softTimer; std::vector<Ptr<NscTcpSocketImpl> > m_sockets; Ipv4L4Protocol::DownTargetCallback m_downTarget; }; } // namespace ns3 #endif /* NSC_TCP_L4_PROTOCOL_H */
zy901002-gpsr
src/internet/model/nsc-tcp-l4-protocol.h
C++
gpl2
4,299
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2008 INRIA * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr> */ #include "ns3/socket.h" #include "ipv6-raw-socket-factory-impl.h" #include "ipv6-l3-protocol.h" namespace ns3 { Ptr<Socket> Ipv6RawSocketFactoryImpl::CreateSocket () { Ptr<Ipv6L3Protocol> ipv6 = GetObject<Ipv6L3Protocol> (); Ptr<Socket> socket = ipv6->CreateRawSocket (); return socket; } } /* namespace ns3 */
zy901002-gpsr
src/internet/model/ipv6-raw-socket-factory-impl.cc
C++
gpl2
1,137
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2010 Adrian Sai-wah Tam * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Adrian Sai-wah Tam <adrian.sw.tam@gmail.com> */ #include "ns3/packet.h" #include "ns3/fatal-error.h" #include "ns3/log.h" #include "tcp-rx-buffer.h" NS_LOG_COMPONENT_DEFINE ("TcpRxBuffer"); namespace ns3 { TypeId TcpRxBuffer::GetTypeId (void) { static TypeId tid = TypeId ("ns3::TcpRxBuffer") .SetParent<Object> () .AddConstructor<TcpRxBuffer> () .AddTraceSource ("NextRxSequence", "Next sequence number expected (RCV.NXT)", MakeTraceSourceAccessor (&TcpRxBuffer::m_nextRxSeq)) ; return tid; } /* A user is supposed to create a TcpSocket through a factory. In TcpSocket, * there are attributes SndBufSize and RcvBufSize to control the default Tx and * Rx window sizes respectively, with default of 128 KiByte. The attribute * RcvBufSize is passed to TcpRxBuffer by TcpSocketBase::SetRcvBufSize() and in * turn, TcpRxBuffer:SetMaxBufferSize(). Therefore, the m_maxBuffer value * initialized below is insignificant. */ TcpRxBuffer::TcpRxBuffer (uint32_t n) : m_nextRxSeq (n), m_gotFin (false), m_size (0), m_maxBuffer (32768), m_availBytes (0) { } TcpRxBuffer::~TcpRxBuffer () { } SequenceNumber32 TcpRxBuffer::NextRxSequence (void) const { return m_nextRxSeq; } void TcpRxBuffer::SetNextRxSequence (const SequenceNumber32& s) { m_nextRxSeq = s; } uint32_t TcpRxBuffer::MaxBufferSize (void) const { return m_maxBuffer; } void TcpRxBuffer::SetMaxBufferSize (uint32_t s) { m_maxBuffer = s; } uint32_t TcpRxBuffer::Size (void) const { return m_size; } uint32_t TcpRxBuffer::Available () const { return m_availBytes; } void TcpRxBuffer::IncNextRxSequence () { NS_LOG_FUNCTION (this); // Increment nextRxSeq is valid only if we don't have any data buffered, // this is supposed to be called only during the three-way handshake NS_ASSERT (m_size == 0); m_nextRxSeq++; } // Return the highest sequence number that this TcpRxBuffer can accept SequenceNumber32 TcpRxBuffer::MaxRxSequence (void) const { if (m_gotFin) { // No data allowed beyond FIN return m_finSeq; } else if (m_data.size ()) { // No data allowed beyond Rx window allowed return m_data.begin ()->first + SequenceNumber32 (m_maxBuffer); } return m_nextRxSeq + SequenceNumber32 (m_maxBuffer); } void TcpRxBuffer::SetFinSequence (const SequenceNumber32& s) { NS_LOG_FUNCTION (this); m_gotFin = true; m_finSeq = s; if (m_nextRxSeq == m_finSeq) ++m_nextRxSeq; } bool TcpRxBuffer::Finished (void) { return (m_gotFin && m_finSeq < m_nextRxSeq); } bool TcpRxBuffer::Add (Ptr<Packet> p, TcpHeader const& tcph) { NS_LOG_FUNCTION (this << p << tcph); uint32_t pktSize = p->GetSize (); SequenceNumber32 headSeq = tcph.GetSequenceNumber (); SequenceNumber32 tailSeq = headSeq + SequenceNumber32 (pktSize); NS_LOG_LOGIC ("Add pkt " << p << " len=" << pktSize << " seq=" << headSeq << ", when NextRxSeq=" << m_nextRxSeq << ", buffsize=" << m_size); // Trim packet to fit Rx window specification if (headSeq < m_nextRxSeq) headSeq = m_nextRxSeq; if (m_data.size ()) { SequenceNumber32 maxSeq = m_data.begin ()->first + SequenceNumber32 (m_maxBuffer); if (maxSeq < tailSeq) tailSeq = maxSeq; if (tailSeq < headSeq) headSeq = tailSeq; } // Remove overlapped bytes from packet BufIterator i = m_data.begin (); while (i != m_data.end () && i->first <= tailSeq) { SequenceNumber32 lastByteSeq = i->first + SequenceNumber32 (i->second->GetSize ()); if (lastByteSeq > headSeq) { if (i->first > headSeq && lastByteSeq < tailSeq) { // Rare case: Existing packet is embedded fully in the new packet m_size -= i->second->GetSize (); m_data.erase (i++); continue; } if (i->first <= headSeq) { // Incoming head is overlapped headSeq = lastByteSeq; } if (lastByteSeq >= tailSeq) { // Incoming tail is overlapped tailSeq = i->first; } } ++i; } // We now know how much we are going to store, trim the packet if (headSeq >= tailSeq) { NS_LOG_LOGIC ("Nothing to buffer"); return false; // Nothing to buffer anyway } else { uint32_t start = headSeq - tcph.GetSequenceNumber (); uint32_t length = tailSeq - headSeq; p = p->CreateFragment (start, length); NS_ASSERT (length == p->GetSize ()); } // Insert packet into buffer NS_ASSERT (m_data.find (headSeq) == m_data.end ()); // Shouldn't be there yet m_data [ headSeq ] = p; NS_LOG_LOGIC ("Buffered packet of seqno=" << headSeq << " len=" << p->GetSize ()); // Update variables m_size += p->GetSize (); // Occupancy for (BufIterator i = m_data.begin (); i != m_data.end (); ++i) { if (i->first < m_nextRxSeq) { continue; } else if (i->first > m_nextRxSeq) { break; }; m_nextRxSeq = i->first + SequenceNumber32 (i->second->GetSize ()); m_availBytes += i->second->GetSize (); } NS_LOG_LOGIC ("Updated buffer occupancy=" << m_size << " nextRxSeq=" << m_nextRxSeq); if (m_gotFin && m_nextRxSeq == m_finSeq) { // Account for the FIN packet ++m_nextRxSeq; }; return true; } Ptr<Packet> TcpRxBuffer::Extract (uint32_t maxSize) { NS_LOG_FUNCTION (this << maxSize); uint32_t extractSize = std::min (maxSize, m_availBytes); NS_LOG_LOGIC ("Requested to extract " << extractSize << " bytes from TcpRxBuffer of size=" << m_size); if (extractSize == 0) return 0; // No contiguous block to return NS_ASSERT (m_data.size ()); // At least we have something to extract Ptr<Packet> outPkt = Create<Packet> (); // The packet that contains all the data to return BufIterator i; while (extractSize) { // Check the buffered data for delivery i = m_data.begin (); NS_ASSERT (i->first <= m_nextRxSeq); // in-sequence data expected // Check if we send the whole pkt or just a partial uint32_t pktSize = i->second->GetSize (); if (pktSize <= extractSize) { // Whole packet is extracted outPkt->AddAtEnd (i->second); m_data.erase (i); m_size -= pktSize; m_availBytes -= pktSize; extractSize -= pktSize; } else { // Partial is extracted and done outPkt->AddAtEnd (i->second->CreateFragment (0, extractSize)); m_data[i->first + SequenceNumber32 (extractSize)] = i->second->CreateFragment (extractSize, pktSize - extractSize); m_data.erase (i); m_size -= extractSize; m_availBytes -= extractSize; extractSize = 0; } } if (outPkt->GetSize () == 0) { NS_LOG_LOGIC ("Nothing extracted."); return 0; } NS_LOG_LOGIC ("Extracted " << outPkt->GetSize ( ) << " bytes, bufsize=" << m_size << ", num pkts in buffer=" << m_data.size ()); return outPkt; } } //namepsace ns3
zy901002-gpsr
src/internet/model/tcp-rx-buffer.cc
C++
gpl2
7,862
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2010 Adrian Sai-wah Tam * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Adrian Sai-wah Tam <adrian.sw.tam@gmail.com> */ #include "tcp-rfc793.h" #include "ns3/log.h" NS_LOG_COMPONENT_DEFINE ("TcpRfc793"); namespace ns3 { NS_OBJECT_ENSURE_REGISTERED (TcpRfc793); TypeId TcpRfc793::GetTypeId (void) { static TypeId tid = TypeId ("ns3::TcpRfc793") .SetParent<TcpSocketBase> () .AddConstructor<TcpRfc793> () ; return tid; } TcpRfc793::TcpRfc793 (void) { NS_LOG_FUNCTION (this); SetDelAckMaxCount (0); // Delayed ACK is not in RFC793 } TcpRfc793::TcpRfc793 (const TcpRfc793& sock) : TcpSocketBase (sock) { } TcpRfc793::~TcpRfc793 (void) { } Ptr<TcpSocketBase> TcpRfc793::Fork (void) { return CopyObject<TcpRfc793> (this); } void TcpRfc793::DupAck (const TcpHeader& t, uint32_t count) { } void TcpRfc793::SetSSThresh (uint32_t threshold) { NS_LOG_WARN ("DoD TCP does not perform slow start"); } uint32_t TcpRfc793::GetSSThresh (void) const { NS_LOG_WARN ("DoD TCP does not perform slow start"); return 0; } void TcpRfc793::SetInitialCwnd (uint32_t cwnd) { NS_LOG_WARN ("DoD TCP does not have congestion window"); } uint32_t TcpRfc793::GetInitialCwnd (void) const { NS_LOG_WARN ("DoD TCP does not have congestion window"); return 0; } } // namespace ns3
zy901002-gpsr
src/internet/model/tcp-rfc793.cc
C++
gpl2
1,998
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright 2007 University of Washington * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Authors: Tom Henderson (tomhend@u.washington.edu) */ #include "ns3/log.h" #include "ns3/assert.h" #include "ns3/abort.h" #include "ns3/channel.h" #include "ns3/net-device.h" #include "ns3/node.h" #include "ns3/node-list.h" #include "ns3/ipv4.h" #include "ns3/bridge-net-device.h" #include "ipv4-global-routing.h" #include "global-router-interface.h" #include <vector> NS_LOG_COMPONENT_DEFINE ("GlobalRouter"); namespace ns3 { // --------------------------------------------------------------------------- // // GlobalRoutingLinkRecord Implementation // // --------------------------------------------------------------------------- GlobalRoutingLinkRecord::GlobalRoutingLinkRecord () : m_linkId ("0.0.0.0"), m_linkData ("0.0.0.0"), m_linkType (Unknown), m_metric (0) { NS_LOG_FUNCTION_NOARGS (); } GlobalRoutingLinkRecord::GlobalRoutingLinkRecord ( LinkType linkType, Ipv4Address linkId, Ipv4Address linkData, uint16_t metric) : m_linkId (linkId), m_linkData (linkData), m_linkType (linkType), m_metric (metric) { NS_LOG_FUNCTION (this << linkType << linkId << linkData << metric); } GlobalRoutingLinkRecord::~GlobalRoutingLinkRecord () { NS_LOG_FUNCTION_NOARGS (); } Ipv4Address GlobalRoutingLinkRecord::GetLinkId (void) const { NS_LOG_FUNCTION_NOARGS (); return m_linkId; } void GlobalRoutingLinkRecord::SetLinkId (Ipv4Address addr) { NS_LOG_FUNCTION_NOARGS (); m_linkId = addr; } Ipv4Address GlobalRoutingLinkRecord::GetLinkData (void) const { NS_LOG_FUNCTION_NOARGS (); return m_linkData; } void GlobalRoutingLinkRecord::SetLinkData (Ipv4Address addr) { NS_LOG_FUNCTION_NOARGS (); m_linkData = addr; } GlobalRoutingLinkRecord::LinkType GlobalRoutingLinkRecord::GetLinkType (void) const { NS_LOG_FUNCTION_NOARGS (); return m_linkType; } void GlobalRoutingLinkRecord::SetLinkType ( GlobalRoutingLinkRecord::LinkType linkType) { NS_LOG_FUNCTION_NOARGS (); m_linkType = linkType; } uint16_t GlobalRoutingLinkRecord::GetMetric (void) const { NS_LOG_FUNCTION_NOARGS (); return m_metric; } void GlobalRoutingLinkRecord::SetMetric (uint16_t metric) { NS_LOG_FUNCTION_NOARGS (); m_metric = metric; } // --------------------------------------------------------------------------- // // GlobalRoutingLSA Implementation // // --------------------------------------------------------------------------- GlobalRoutingLSA::GlobalRoutingLSA() : m_lsType (GlobalRoutingLSA::Unknown), m_linkStateId ("0.0.0.0"), m_advertisingRtr ("0.0.0.0"), m_linkRecords (), m_networkLSANetworkMask ("0.0.0.0"), m_attachedRouters (), m_status (GlobalRoutingLSA::LSA_SPF_NOT_EXPLORED), m_node_id (0) { NS_LOG_FUNCTION_NOARGS (); } GlobalRoutingLSA::GlobalRoutingLSA ( GlobalRoutingLSA::SPFStatus status, Ipv4Address linkStateId, Ipv4Address advertisingRtr) : m_lsType (GlobalRoutingLSA::Unknown), m_linkStateId (linkStateId), m_advertisingRtr (advertisingRtr), m_linkRecords (), m_networkLSANetworkMask ("0.0.0.0"), m_attachedRouters (), m_status (status), m_node_id (0) { NS_LOG_FUNCTION (this << status << linkStateId << advertisingRtr); } GlobalRoutingLSA::GlobalRoutingLSA (GlobalRoutingLSA& lsa) : m_lsType (lsa.m_lsType), m_linkStateId (lsa.m_linkStateId), m_advertisingRtr (lsa.m_advertisingRtr), m_networkLSANetworkMask (lsa.m_networkLSANetworkMask), m_status (lsa.m_status), m_node_id (lsa.m_node_id) { NS_LOG_FUNCTION_NOARGS (); NS_ASSERT_MSG (IsEmpty (), "GlobalRoutingLSA::GlobalRoutingLSA (): Non-empty LSA in constructor"); CopyLinkRecords (lsa); } GlobalRoutingLSA& GlobalRoutingLSA::operator= (const GlobalRoutingLSA& lsa) { NS_LOG_FUNCTION_NOARGS (); m_lsType = lsa.m_lsType; m_linkStateId = lsa.m_linkStateId; m_advertisingRtr = lsa.m_advertisingRtr; m_networkLSANetworkMask = lsa.m_networkLSANetworkMask, m_status = lsa.m_status; m_node_id = lsa.m_node_id; ClearLinkRecords (); CopyLinkRecords (lsa); return *this; } void GlobalRoutingLSA::CopyLinkRecords (const GlobalRoutingLSA& lsa) { NS_LOG_FUNCTION_NOARGS (); for (ListOfLinkRecords_t::const_iterator i = lsa.m_linkRecords.begin (); i != lsa.m_linkRecords.end (); i++) { GlobalRoutingLinkRecord *pSrc = *i; GlobalRoutingLinkRecord *pDst = new GlobalRoutingLinkRecord; pDst->SetLinkType (pSrc->GetLinkType ()); pDst->SetLinkId (pSrc->GetLinkId ()); pDst->SetLinkData (pSrc->GetLinkData ()); pDst->SetMetric (pSrc->GetMetric ()); m_linkRecords.push_back (pDst); pDst = 0; } m_attachedRouters = lsa.m_attachedRouters; } GlobalRoutingLSA::~GlobalRoutingLSA() { NS_LOG_FUNCTION_NOARGS (); ClearLinkRecords (); } void GlobalRoutingLSA::ClearLinkRecords (void) { NS_LOG_FUNCTION_NOARGS (); for ( ListOfLinkRecords_t::iterator i = m_linkRecords.begin (); i != m_linkRecords.end (); i++) { NS_LOG_LOGIC ("Free link record"); GlobalRoutingLinkRecord *p = *i; delete p; p = 0; *i = 0; } NS_LOG_LOGIC ("Clear list"); m_linkRecords.clear (); } uint32_t GlobalRoutingLSA::AddLinkRecord (GlobalRoutingLinkRecord* lr) { NS_LOG_FUNCTION_NOARGS (); m_linkRecords.push_back (lr); return m_linkRecords.size (); } uint32_t GlobalRoutingLSA::GetNLinkRecords (void) const { NS_LOG_FUNCTION_NOARGS (); return m_linkRecords.size (); } GlobalRoutingLinkRecord * GlobalRoutingLSA::GetLinkRecord (uint32_t n) const { NS_LOG_FUNCTION_NOARGS (); uint32_t j = 0; for ( ListOfLinkRecords_t::const_iterator i = m_linkRecords.begin (); i != m_linkRecords.end (); i++, j++) { if (j == n) { return *i; } } NS_ASSERT_MSG (false, "GlobalRoutingLSA::GetLinkRecord (): invalid index"); return 0; } bool GlobalRoutingLSA::IsEmpty (void) const { NS_LOG_FUNCTION_NOARGS (); return m_linkRecords.size () == 0; } GlobalRoutingLSA::LSType GlobalRoutingLSA::GetLSType (void) const { NS_LOG_FUNCTION_NOARGS (); return m_lsType; } void GlobalRoutingLSA::SetLSType (GlobalRoutingLSA::LSType typ) { NS_LOG_FUNCTION_NOARGS (); m_lsType = typ; } Ipv4Address GlobalRoutingLSA::GetLinkStateId (void) const { NS_LOG_FUNCTION_NOARGS (); return m_linkStateId; } void GlobalRoutingLSA::SetLinkStateId (Ipv4Address addr) { NS_LOG_FUNCTION_NOARGS (); m_linkStateId = addr; } Ipv4Address GlobalRoutingLSA::GetAdvertisingRouter (void) const { NS_LOG_FUNCTION_NOARGS (); return m_advertisingRtr; } void GlobalRoutingLSA::SetAdvertisingRouter (Ipv4Address addr) { NS_LOG_FUNCTION_NOARGS (); m_advertisingRtr = addr; } void GlobalRoutingLSA::SetNetworkLSANetworkMask (Ipv4Mask mask) { NS_LOG_FUNCTION_NOARGS (); m_networkLSANetworkMask = mask; } Ipv4Mask GlobalRoutingLSA::GetNetworkLSANetworkMask (void) const { NS_LOG_FUNCTION_NOARGS (); return m_networkLSANetworkMask; } GlobalRoutingLSA::SPFStatus GlobalRoutingLSA::GetStatus (void) const { NS_LOG_FUNCTION_NOARGS (); return m_status; } uint32_t GlobalRoutingLSA::AddAttachedRouter (Ipv4Address addr) { NS_LOG_FUNCTION_NOARGS (); m_attachedRouters.push_back (addr); return m_attachedRouters.size (); } uint32_t GlobalRoutingLSA::GetNAttachedRouters (void) const { NS_LOG_FUNCTION_NOARGS (); return m_attachedRouters.size (); } Ipv4Address GlobalRoutingLSA::GetAttachedRouter (uint32_t n) const { NS_LOG_FUNCTION_NOARGS (); uint32_t j = 0; for ( ListOfAttachedRouters_t::const_iterator i = m_attachedRouters.begin (); i != m_attachedRouters.end (); i++, j++) { if (j == n) { return *i; } } NS_ASSERT_MSG (false, "GlobalRoutingLSA::GetAttachedRouter (): invalid index"); return Ipv4Address ("0.0.0.0"); } void GlobalRoutingLSA::SetStatus (GlobalRoutingLSA::SPFStatus status) { NS_LOG_FUNCTION_NOARGS (); m_status = status; } Ptr<Node> GlobalRoutingLSA::GetNode (void) const { NS_LOG_FUNCTION_NOARGS (); return NodeList::GetNode (m_node_id); } void GlobalRoutingLSA::SetNode (Ptr<Node> node) { NS_LOG_FUNCTION (node); m_node_id = node->GetId (); } void GlobalRoutingLSA::Print (std::ostream &os) const { os << std::endl; os << "========== Global Routing LSA ==========" << std::endl; os << "m_lsType = " << m_lsType; if (m_lsType == GlobalRoutingLSA::RouterLSA) { os << " (GlobalRoutingLSA::RouterLSA)"; } else if (m_lsType == GlobalRoutingLSA::NetworkLSA) { os << " (GlobalRoutingLSA::NetworkLSA)"; } else if (m_lsType == GlobalRoutingLSA::ASExternalLSAs) { os << " (GlobalRoutingLSA::ASExternalLSA)"; } else { os << "(Unknown LSType)"; } os << std::endl; os << "m_linkStateId = " << m_linkStateId << " (Router ID)" << std::endl; os << "m_advertisingRtr = " << m_advertisingRtr << " (Router ID)" << std::endl; if (m_lsType == GlobalRoutingLSA::RouterLSA) { for ( ListOfLinkRecords_t::const_iterator i = m_linkRecords.begin (); i != m_linkRecords.end (); i++) { GlobalRoutingLinkRecord *p = *i; os << "---------- RouterLSA Link Record ----------" << std::endl; os << "m_linkType = " << p->m_linkType; if (p->m_linkType == GlobalRoutingLinkRecord::PointToPoint) { os << " (GlobalRoutingLinkRecord::PointToPoint)" << std::endl; os << "m_linkId = " << p->m_linkId << std::endl; os << "m_linkData = " << p->m_linkData << std::endl; os << "m_metric = " << p->m_metric << std::endl; } else if (p->m_linkType == GlobalRoutingLinkRecord::TransitNetwork) { os << " (GlobalRoutingLinkRecord::TransitNetwork)" << std::endl; os << "m_linkId = " << p->m_linkId << " (Designated router for network)" << std::endl; os << "m_linkData = " << p->m_linkData << " (This router's IP address)" << std::endl; os << "m_metric = " << p->m_metric << std::endl; } else if (p->m_linkType == GlobalRoutingLinkRecord::StubNetwork) { os << " (GlobalRoutingLinkRecord::StubNetwork)" << std::endl; os << "m_linkId = " << p->m_linkId << " (Network number of attached network)" << std::endl; os << "m_linkData = " << p->m_linkData << " (Network mask of attached network)" << std::endl; os << "m_metric = " << p->m_metric << std::endl; } else { os << " (Unknown LinkType)" << std::endl; os << "m_linkId = " << p->m_linkId << std::endl; os << "m_linkData = " << p->m_linkData << std::endl; os << "m_metric = " << p->m_metric << std::endl; } os << "---------- End RouterLSA Link Record ----------" << std::endl; } } else if (m_lsType == GlobalRoutingLSA::NetworkLSA) { os << "---------- NetworkLSA Link Record ----------" << std::endl; os << "m_networkLSANetworkMask = " << m_networkLSANetworkMask << std::endl; for ( ListOfAttachedRouters_t::const_iterator i = m_attachedRouters.begin (); i != m_attachedRouters.end (); i++) { Ipv4Address p = *i; os << "attachedRouter = " << p << std::endl; } os << "---------- End NetworkLSA Link Record ----------" << std::endl; } else if (m_lsType == GlobalRoutingLSA::ASExternalLSAs) { os << "---------- ASExternalLSA Link Record --------" << std::endl; os << "m_linkStateId = " << m_linkStateId << std::endl; os << "m_networkLSANetworkMask = " << m_networkLSANetworkMask << std::endl; } else { NS_ASSERT_MSG (0, "Illegal LSA LSType: " << m_lsType); } os << "========== End Global Routing LSA ==========" << std::endl; } std::ostream& operator<< (std::ostream& os, GlobalRoutingLSA& lsa) { lsa.Print (os); return os; } // --------------------------------------------------------------------------- // // GlobalRouter Implementation // // --------------------------------------------------------------------------- NS_OBJECT_ENSURE_REGISTERED (GlobalRouter); TypeId GlobalRouter::GetTypeId (void) { static TypeId tid = TypeId ("ns3::GlobalRouter") .SetParent<Object> (); return tid; } GlobalRouter::GlobalRouter () : m_LSAs () { NS_LOG_FUNCTION_NOARGS (); m_routerId.Set (GlobalRouteManager::AllocateRouterId ()); } GlobalRouter::~GlobalRouter () { NS_LOG_FUNCTION_NOARGS (); ClearLSAs (); } void GlobalRouter::SetRoutingProtocol (Ptr<Ipv4GlobalRouting> routing) { m_routingProtocol = routing; } Ptr<Ipv4GlobalRouting> GlobalRouter::GetRoutingProtocol (void) { return m_routingProtocol; } void GlobalRouter::DoDispose () { NS_LOG_FUNCTION_NOARGS (); m_routingProtocol = 0; for (InjectedRoutesI k = m_injectedRoutes.begin (); k != m_injectedRoutes.end (); k = m_injectedRoutes.erase (k)) { delete (*k); } Object::DoDispose (); } void GlobalRouter::ClearLSAs () { NS_LOG_FUNCTION_NOARGS (); for ( ListOfLSAs_t::iterator i = m_LSAs.begin (); i != m_LSAs.end (); i++) { NS_LOG_LOGIC ("Free LSA"); GlobalRoutingLSA *p = *i; delete p; p = 0; *i = 0; } NS_LOG_LOGIC ("Clear list of LSAs"); m_LSAs.clear (); } Ipv4Address GlobalRouter::GetRouterId (void) const { NS_LOG_FUNCTION_NOARGS (); return m_routerId; } // // DiscoverLSAs is called on all nodes in the system that have a GlobalRouter // interface aggregated. We need to go out and discover any adjacent routers // and build the Link State Advertisements that reflect them and their associated // networks. // uint32_t GlobalRouter::DiscoverLSAs () { NS_LOG_FUNCTION_NOARGS (); Ptr<Node> node = GetObject<Node> (); NS_ABORT_MSG_UNLESS (node, "GlobalRouter::DiscoverLSAs (): GetObject for <Node> interface failed"); NS_LOG_LOGIC ("For node " << node->GetId () ); ClearLSAs (); // // While building the Router-LSA, keep a list of those NetDevices for // which the current node is the designated router and we will later build // a NetworkLSA for. // NetDeviceContainer c; // // We're aggregated to a node. We need to ask the node for a pointer to its // Ipv4 interface. This is where the information regarding the attached // interfaces lives. If we're a router, we had better have an Ipv4 interface. // Ptr<Ipv4> ipv4Local = node->GetObject<Ipv4> (); NS_ABORT_MSG_UNLESS (ipv4Local, "GlobalRouter::DiscoverLSAs (): GetObject for <Ipv4> interface failed"); // // Every router node originates a Router-LSA // GlobalRoutingLSA *pLSA = new GlobalRoutingLSA; pLSA->SetLSType (GlobalRoutingLSA::RouterLSA); pLSA->SetLinkStateId (m_routerId); pLSA->SetAdvertisingRouter (m_routerId); pLSA->SetStatus (GlobalRoutingLSA::LSA_SPF_NOT_EXPLORED); pLSA->SetNode (node); // // Ask the node for the number of net devices attached. This isn't necessarily // equal to the number of links to adjacent nodes (other routers) as the number // of devices may include those for stub networks (e.g., ethernets, etc.) and // bridge devices also take up an "extra" net device. // uint32_t numDevices = node->GetNDevices (); // // Iterate through the devices on the node and walk the channel to see what's // on the other side of the standalone devices.. // for (uint32_t i = 0; i < numDevices; ++i) { Ptr<NetDevice> ndLocal = node->GetDevice (i); // // There is an assumption that bridge ports must never have an IP address // associated with them. This turns out to be a very convenient place to // check and make sure that this is the case. // if (NetDeviceIsBridged (ndLocal)) { // Initialize to value out of bounds to silence compiler uint32_t interfaceBridge = ipv4Local->GetNInterfaces () + 1; bool rc = FindInterfaceForDevice (node, ndLocal, interfaceBridge); NS_ABORT_MSG_IF (rc, "GlobalRouter::DiscoverLSAs(): Bridge ports must not have an IPv4 interface index"); } // // Check to see if the net device we just got has a corresponding IP // interface (could be a pure L2 NetDevice) -- for example a net device // associated with a bridge. We are only going to involve devices with // IP addresses in routing. // bool isForwarding = false; for (uint32_t j = 0; j < ipv4Local->GetNInterfaces (); ++j ) { if (ipv4Local->GetNetDevice (j) == ndLocal && ipv4Local->IsUp (j) && ipv4Local->IsForwarding (j)) { isForwarding = true; break; } } if (!isForwarding) { NS_LOG_LOGIC ("Net device " << ndLocal << "has no IP interface or is not enabled for forwarding, skipping"); continue; } // // We have a net device that we need to check out. If it suports // broadcast and is not a point-point link, then it will be either a stub // network or a transit network depending on the number of routers on // the segment. We add the appropriate link record to the LSA. // // If the device is a point to point link, we treat it separately. In // that case, there may be zero, one, or two link records added. // if (ndLocal->IsBroadcast () && !ndLocal->IsPointToPoint () ) { NS_LOG_LOGIC ("Broadcast link"); ProcessBroadcastLink (ndLocal, pLSA, c); } else if (ndLocal->IsPointToPoint () ) { NS_LOG_LOGIC ("Point=to-point link"); ProcessPointToPointLink (ndLocal, pLSA); } else { NS_ASSERT_MSG (0, "GlobalRouter::DiscoverLSAs (): unknown link type"); } } NS_LOG_LOGIC ("========== LSA for node " << node->GetId () << " =========="); NS_LOG_LOGIC (*pLSA); m_LSAs.push_back (pLSA); pLSA = 0; // // Now, determine whether we need to build a NetworkLSA. This is the case if // we found at least one designated router. // uint32_t nDesignatedRouters = c.GetN (); if (nDesignatedRouters > 0) { NS_LOG_LOGIC ("Build Network LSAs"); BuildNetworkLSAs (c); } // // Build injected route LSAs as external routes // RFC 2328, section 12.4.4 // for (InjectedRoutesCI i = m_injectedRoutes.begin (); i != m_injectedRoutes.end (); i++) { GlobalRoutingLSA *pLSA = new GlobalRoutingLSA; pLSA->SetLSType (GlobalRoutingLSA::ASExternalLSAs); pLSA->SetLinkStateId ((*i)->GetDestNetwork ()); pLSA->SetAdvertisingRouter (m_routerId); pLSA->SetNetworkLSANetworkMask ((*i)->GetDestNetworkMask ()); pLSA->SetStatus (GlobalRoutingLSA::LSA_SPF_NOT_EXPLORED); m_LSAs.push_back (pLSA); } return m_LSAs.size (); } void GlobalRouter::ProcessBroadcastLink (Ptr<NetDevice> nd, GlobalRoutingLSA *pLSA, NetDeviceContainer &c) { NS_LOG_FUNCTION (nd << pLSA << &c); if (nd->IsBridge ()) { ProcessBridgedBroadcastLink (nd, pLSA, c); } else { ProcessSingleBroadcastLink (nd, pLSA, c); } } void GlobalRouter::ProcessSingleBroadcastLink (Ptr<NetDevice> nd, GlobalRoutingLSA *pLSA, NetDeviceContainer &c) { NS_LOG_FUNCTION (nd << pLSA << &c); GlobalRoutingLinkRecord *plr = new GlobalRoutingLinkRecord; NS_ABORT_MSG_IF (plr == 0, "GlobalRouter::ProcessSingleBroadcastLink(): Can't alloc link record"); // // We have some preliminaries to do to get enough information to proceed. // This information we need comes from the internet stack, so notice that // there is an implied assumption that global routing is only going to // work with devices attached to the internet stack (have an ipv4 interface // associated to them. // Ptr<Node> node = nd->GetNode (); Ptr<Ipv4> ipv4Local = node->GetObject<Ipv4> (); NS_ABORT_MSG_UNLESS (ipv4Local, "GlobalRouter::ProcessSingleBroadcastLink (): GetObject for <Ipv4> interface failed"); // Initialize to value out of bounds to silence compiler uint32_t interfaceLocal = ipv4Local->GetNInterfaces () + 1; bool rc = FindInterfaceForDevice (node, nd, interfaceLocal); NS_ABORT_MSG_IF (rc == false, "GlobalRouter::ProcessSingleBroadcastLink(): No interface index associated with device"); if (ipv4Local->GetNAddresses (interfaceLocal) > 1) { NS_LOG_WARN ("Warning, interface has multiple IP addresses; using only the primary one"); } Ipv4Address addrLocal = ipv4Local->GetAddress (interfaceLocal, 0).GetLocal (); Ipv4Mask maskLocal = ipv4Local->GetAddress (interfaceLocal, 0).GetMask (); NS_LOG_LOGIC ("Working with local address " << addrLocal); uint16_t metricLocal = ipv4Local->GetMetric (interfaceLocal); // // Check to see if the net device is connected to a channel/network that has // another router on it. If there is no other router on the link (but us) then // this is a stub network. If we find another router, then what we have here // is a transit network. // if (AnotherRouterOnLink (nd, true) == false) { // // This is a net device connected to a stub network // NS_LOG_LOGIC ("Router-LSA Stub Network"); plr->SetLinkType (GlobalRoutingLinkRecord::StubNetwork); // // According to OSPF, the Link ID is the IP network number of // the attached network. // plr->SetLinkId (addrLocal.CombineMask (maskLocal)); // // and the Link Data is the network mask; converted to Ipv4Address // Ipv4Address maskLocalAddr; maskLocalAddr.Set (maskLocal.Get ()); plr->SetLinkData (maskLocalAddr); plr->SetMetric (metricLocal); pLSA->AddLinkRecord (plr); plr = 0; } else { // // We have multiple routers on a broadcast interface, so this is // a transit network. // NS_LOG_LOGIC ("Router-LSA Transit Network"); plr->SetLinkType (GlobalRoutingLinkRecord::TransitNetwork); // // By definition, the router with the lowest IP address is the // designated router for the network. OSPF says that the Link ID // gets the IP interface address of the designated router in this // case. // Ipv4Address desigRtr = FindDesignatedRouterForLink (nd, true); // // Let's double-check that any designated router we find out on our // network is really on our network. // if (desigRtr != "255.255.255.255") { Ipv4Address networkHere = addrLocal.CombineMask (maskLocal); Ipv4Address networkThere = desigRtr.CombineMask (maskLocal); NS_ABORT_MSG_UNLESS (networkHere == networkThere, "GlobalRouter::ProcessSingleBroadcastLink(): Network number confusion"); } if (desigRtr == addrLocal) { c.Add (nd); NS_LOG_LOGIC ("Node " << node->GetId () << " elected a designated router"); } plr->SetLinkId (desigRtr); // // OSPF says that the Link Data is this router's own IP address. // plr->SetLinkData (addrLocal); plr->SetMetric (metricLocal); pLSA->AddLinkRecord (plr); plr = 0; } } void GlobalRouter::ProcessBridgedBroadcastLink (Ptr<NetDevice> nd, GlobalRoutingLSA *pLSA, NetDeviceContainer &c) { NS_LOG_FUNCTION (nd << pLSA << &c); NS_ASSERT_MSG (nd->IsBridge (), "GlobalRouter::ProcessBridgedBroadcastLink(): Called with non-bridge net device"); #if 0 // // It is possible to admit the possibility that a bridge device on a node // can also participate in routing. This would surprise people who don't // come from Microsoft-land where they do use such a construct. Based on // the principle of least-surprise, we will leave the relatively simple // code in place to do this, but not enable it until someone really wants // the capability. Even then, we will not enable this code as a default // but rather something you will have to go and turn on. // Ptr<BridgeNetDevice> bnd = nd->GetObject<BridgeNetDevice> (); NS_ABORT_MSG_UNLESS (bnd, "GlobalRouter::DiscoverLSAs (): GetObject for <BridgeNetDevice> failed"); // // We have some preliminaries to do to get enough information to proceed. // This information we need comes from the internet stack, so notice that // there is an implied assumption that global routing is only going to // work with devices attached to the internet stack (have an ipv4 interface // associated to them. // Ptr<Node> node = nd->GetNode (); Ptr<Ipv4> ipv4Local = node->GetObject<Ipv4> (); NS_ABORT_MSG_UNLESS (ipv4Local, "GlobalRouter::ProcessBridgedBroadcastLink (): GetObject for <Ipv4> interface failed"); // Initialize to value out of bounds to silence compiler uint32_t interfaceLocal = ipv4Local->GetNInterfaces () + 1; bool rc = FindInterfaceForDevice (node, nd, interfaceLocal); NS_ABORT_MSG_IF (rc == false, "GlobalRouter::ProcessBridgedBroadcastLink(): No interface index associated with device"); if (ipv4Local->GetNAddresses (interfaceLocal) > 1) { NS_LOG_WARN ("Warning, interface has multiple IP addresses; using only the primary one"); } Ipv4Address addrLocal = ipv4Local->GetAddress (interfaceLocal, 0).GetLocal (); Ipv4Mask maskLocal = ipv4Local->GetAddress (interfaceLocal, 0).GetMask ();; NS_LOG_LOGIC ("Working with local address " << addrLocal); uint16_t metricLocal = ipv4Local->GetMetric (interfaceLocal); // // We need to handle a bridge on the router. This means that we have been // given a net device that is a BridgeNetDevice. It has an associated Ipv4 // interface index and address. Some number of other net devices live "under" // the bridge device as so-called bridge ports. In a nutshell, what we have // to do is to repeat what is done for a single broadcast link on all of // those net devices living under the bridge (trolls?) // bool areTransitNetwork = false; Ipv4Address desigRtr ("255.255.255.255"); for (uint32_t i = 0; i < bnd->GetNBridgePorts (); ++i) { Ptr<NetDevice> ndTemp = bnd->GetBridgePort (i); // // We have to decide if we are a transit network. This is characterized // by the presence of another router on the network segment. If we find // another router on any of our bridged links, we are a transit network. // if (AnotherRouterOnLink (ndTemp, true)) { areTransitNetwork = true; // // If we're going to be a transit network, then we have got to elect // a designated router for the whole bridge. This means finding the // router with the lowest IP address on the whole bridge. We ask // for the lowest address on each segment and pick the lowest of them // all. // Ipv4Address desigRtrTemp = FindDesignatedRouterForLink (ndTemp, true); // // Let's double-check that any designated router we find out on our // network is really on our network. // if (desigRtrTemp != "255.255.255.255") { Ipv4Address networkHere = addrLocal.CombineMask (maskLocal); Ipv4Address networkThere = desigRtrTemp.CombineMask (maskLocal); NS_ABORT_MSG_UNLESS (networkHere == networkThere, "GlobalRouter::ProcessSingleBroadcastLink(): Network number confusion"); } if (desigRtrTemp < desigRtr) { desigRtr = desigRtrTemp; } } } // // That's all the information we need to put it all together, just like we did // in the case of a single broadcast link. // GlobalRoutingLinkRecord *plr = new GlobalRoutingLinkRecord; NS_ABORT_MSG_IF (plr == 0, "GlobalRouter::ProcessBridgedBroadcastLink(): Can't alloc link record"); if (areTransitNetwork == false) { // // This is a net device connected to a bridge of stub networks // NS_LOG_LOGIC ("Router-LSA Stub Network"); plr->SetLinkType (GlobalRoutingLinkRecord::StubNetwork); // // According to OSPF, the Link ID is the IP network number of // the attached network. // plr->SetLinkId (addrLocal.CombineMask (maskLocal)); // // and the Link Data is the network mask; converted to Ipv4Address // Ipv4Address maskLocalAddr; maskLocalAddr.Set (maskLocal.Get ()); plr->SetLinkData (maskLocalAddr); plr->SetMetric (metricLocal); pLSA->AddLinkRecord (plr); plr = 0; } else { // // We have multiple routers on a bridged broadcast interface, so this is // a transit network. // NS_LOG_LOGIC ("Router-LSA Transit Network"); plr->SetLinkType (GlobalRoutingLinkRecord::TransitNetwork); // // By definition, the router with the lowest IP address is the // designated router for the network. OSPF says that the Link ID // gets the IP interface address of the designated router in this // case. // if (desigRtr == addrLocal) { c.Add (nd); NS_LOG_LOGIC ("Node " << node->GetId () << " elected a designated router"); } plr->SetLinkId (desigRtr); // // OSPF says that the Link Data is this router's own IP address. // plr->SetLinkData (addrLocal); plr->SetMetric (metricLocal); pLSA->AddLinkRecord (plr); plr = 0; } #endif } void GlobalRouter::ProcessPointToPointLink (Ptr<NetDevice> ndLocal, GlobalRoutingLSA *pLSA) { NS_LOG_FUNCTION (ndLocal << pLSA); // // We have some preliminaries to do to get enough information to proceed. // This information we need comes from the internet stack, so notice that // there is an implied assumption that global routing is only going to // work with devices attached to the internet stack (have an ipv4 interface // associated to them. // Ptr<Node> nodeLocal = ndLocal->GetNode (); Ptr<Ipv4> ipv4Local = nodeLocal->GetObject<Ipv4> (); NS_ABORT_MSG_UNLESS (ipv4Local, "GlobalRouter::ProcessPointToPointLink (): GetObject for <Ipv4> interface failed"); uint32_t interfaceLocal = ipv4Local->GetNInterfaces () + 1; bool rc = FindInterfaceForDevice (nodeLocal, ndLocal, interfaceLocal); NS_ABORT_MSG_IF (rc == false, "GlobalRouter::ProcessPointToPointLink (): No interface index associated with device"); if (ipv4Local->GetNAddresses (interfaceLocal) > 1) { NS_LOG_WARN ("Warning, interface has multiple IP addresses; using only the primary one"); } Ipv4Address addrLocal = ipv4Local->GetAddress (interfaceLocal, 0).GetLocal (); NS_LOG_LOGIC ("Working with local address " << addrLocal); uint16_t metricLocal = ipv4Local->GetMetric (interfaceLocal); // // Now, we're going to walk over to the remote net device on the other end of // the point-to-point channel we know we have. This is where our adjacent // router (to use OSPF lingo) is running. // Ptr<Channel> ch = ndLocal->GetChannel (); // // Get the net device on the other side of the point-to-point channel. // Ptr<NetDevice> ndRemote = GetAdjacent (ndLocal, ch); // // The adjacent net device is aggregated to a node. We need to ask that net // device for its node, then ask that node for its Ipv4 interface. Note a // requirement that nodes on either side of a point-to-point link must have // internet stacks; and an assumption that point-to-point links are incompatible // with bridging. // Ptr<Node> nodeRemote = ndRemote->GetNode (); Ptr<Ipv4> ipv4Remote = nodeRemote->GetObject<Ipv4> (); NS_ABORT_MSG_UNLESS (ipv4Remote, "GlobalRouter::ProcessPointToPointLink(): GetObject for remote <Ipv4> failed"); // // Further note the requirement that nodes on either side of a point-to-point // link must participate in global routing and therefore have a GlobalRouter // interface aggregated. // Ptr<GlobalRouter> rtrRemote = nodeRemote->GetObject<GlobalRouter> (); if (rtrRemote == 0) { // This case is possible if the remote does not participate in global routing return; } // // We're going to need the remote router ID, so we might as well get it now. // Ipv4Address rtrIdRemote = rtrRemote->GetRouterId (); NS_LOG_LOGIC ("Working with remote router " << rtrIdRemote); // // Now, just like we did above, we need to get the IP interface index for the // net device on the other end of the point-to-point channel. // uint32_t interfaceRemote = ipv4Remote->GetNInterfaces () + 1; rc = FindInterfaceForDevice (nodeRemote, ndRemote, interfaceRemote); NS_ABORT_MSG_IF (rc == false, "GlobalRouter::ProcessPointToPointLinks(): No interface index associated with remote device"); // // Now that we have the Ipv4 interface, we can get the (remote) address and // mask we need. // if (ipv4Remote->GetNAddresses (interfaceRemote) > 1) { NS_LOG_WARN ("Warning, interface has multiple IP addresses; using only the primary one"); } Ipv4Address addrRemote = ipv4Remote->GetAddress (interfaceRemote, 0).GetLocal (); Ipv4Mask maskRemote = ipv4Remote->GetAddress (interfaceRemote, 0).GetMask (); NS_LOG_LOGIC ("Working with remote address " << addrRemote); // // Now we can fill out the link records for this link. There are always two // link records; the first is a point-to-point record describing the link and // the second is a stub network record with the network number. // GlobalRoutingLinkRecord *plr; if (ipv4Remote->IsUp (interfaceRemote)) { NS_LOG_LOGIC ("Remote side interface " << interfaceRemote << " is up-- add a type 1 link"); plr = new GlobalRoutingLinkRecord; NS_ABORT_MSG_IF (plr == 0, "GlobalRouter::ProcessPointToPointLink(): Can't alloc link record"); plr->SetLinkType (GlobalRoutingLinkRecord::PointToPoint); plr->SetLinkId (rtrIdRemote); plr->SetLinkData (addrLocal); plr->SetMetric (metricLocal); pLSA->AddLinkRecord (plr); plr = 0; } // Regardless of state of peer, add a type 3 link (RFC 2328: 12.4.1.1) plr = new GlobalRoutingLinkRecord; NS_ABORT_MSG_IF (plr == 0, "GlobalRouter::ProcessPointToPointLink(): Can't alloc link record"); plr->SetLinkType (GlobalRoutingLinkRecord::StubNetwork); plr->SetLinkId (addrRemote); plr->SetLinkData (Ipv4Address (maskRemote.Get ())); // Frown plr->SetMetric (metricLocal); pLSA->AddLinkRecord (plr); plr = 0; } void GlobalRouter::BuildNetworkLSAs (NetDeviceContainer c) { NS_LOG_FUNCTION (&c); uint32_t nDesignatedRouters = c.GetN (); for (uint32_t i = 0; i < nDesignatedRouters; ++i) { // // Build one NetworkLSA for each net device talking to a network that we are the // designated router for. These devices are in the provided container. // Ptr<NetDevice> ndLocal = c.Get (i); Ptr<Node> node = ndLocal->GetNode (); Ptr<Ipv4> ipv4Local = node->GetObject<Ipv4> (); NS_ABORT_MSG_UNLESS (ipv4Local, "GlobalRouter::ProcessPointToPointLink (): GetObject for <Ipv4> interface failed"); uint32_t interfaceLocal = ipv4Local->GetNInterfaces () + 1; bool rc = FindInterfaceForDevice (node, ndLocal, interfaceLocal); NS_ABORT_MSG_IF (rc == false, "GlobalRouter::BuildNetworkLSAs (): No interface index associated with device"); if (ipv4Local->GetNAddresses (interfaceLocal) > 1) { NS_LOG_WARN ("Warning, interface has multiple IP addresses; using only the primary one"); } Ipv4Address addrLocal = ipv4Local->GetAddress (interfaceLocal, 0).GetLocal (); Ipv4Mask maskLocal = ipv4Local->GetAddress (interfaceLocal, 0).GetMask (); GlobalRoutingLSA *pLSA = new GlobalRoutingLSA; NS_ABORT_MSG_IF (pLSA == 0, "GlobalRouter::BuildNetworkLSAs(): Can't alloc link record"); pLSA->SetLSType (GlobalRoutingLSA::NetworkLSA); pLSA->SetLinkStateId (addrLocal); pLSA->SetAdvertisingRouter (m_routerId); pLSA->SetNetworkLSANetworkMask (maskLocal); pLSA->SetStatus (GlobalRoutingLSA::LSA_SPF_NOT_EXPLORED); pLSA->SetNode (node); // // Build a list of AttachedRouters by walking the devices in the channel // and, if we find a node with a GlobalRouter interface and an IPv4 // interface associated with that device, we call it an attached router. // Ptr<Channel> ch = ndLocal->GetChannel (); uint32_t nDevices = ch->GetNDevices (); NS_ASSERT (nDevices); for (uint32_t i = 0; i < nDevices; i++) { Ptr<NetDevice> tempNd = ch->GetDevice (i); NS_ASSERT (tempNd); Ptr<Node> tempNode = tempNd->GetNode (); // // Does the node in question have a GlobalRouter interface? If not it can // hardly be considered an attached router. // Ptr<GlobalRouter> rtr = tempNode->GetObject<GlobalRouter> (); if (rtr == 0) { continue; } // // Does the attached node have an ipv4 interface for the device we're probing? // If not, it can't play router. // uint32_t tempInterface = 0; if (FindInterfaceForDevice (tempNode, tempNd, tempInterface)) { Ptr<Ipv4> tempIpv4 = tempNode->GetObject<Ipv4> (); NS_ASSERT (tempIpv4); if (!tempIpv4->IsUp (tempInterface)) { NS_LOG_LOGIC ("Remote side interface " << tempInterface << " not up"); } else { if (tempIpv4->GetNAddresses (tempInterface) > 1) { NS_LOG_WARN ("Warning, interface has multiple IP addresses; using only the primary one"); } Ipv4Address tempAddr = tempIpv4->GetAddress (tempInterface, 0).GetLocal (); pLSA->AddAttachedRouter (tempAddr); } } } m_LSAs.push_back (pLSA); pLSA = 0; } } // // Given a local net device, we need to walk the channel to which the net device is // attached and look for nodes with GlobalRouter interfaces on them (one of them // will be us). Of these, the router with the lowest IP address on the net device // connecting to the channel becomes the designated router for the link. // Ipv4Address GlobalRouter::FindDesignatedRouterForLink (Ptr<NetDevice> ndLocal, bool allowRecursion) const { NS_LOG_FUNCTION (ndLocal << allowRecursion); Ptr<Channel> ch = ndLocal->GetChannel (); uint32_t nDevices = ch->GetNDevices (); NS_ASSERT (nDevices); NS_LOG_LOGIC ("Looking for designated router off of net device " << ndLocal << " on node " << ndLocal->GetNode ()->GetId ()); Ipv4Address desigRtr ("255.255.255.255"); // // Look through all of the devices on the channel to which the net device // in question is attached. // for (uint32_t i = 0; i < nDevices; i++) { Ptr<NetDevice> ndOther = ch->GetDevice (i); NS_ASSERT (ndOther); Ptr<Node> nodeOther = ndOther->GetNode (); NS_LOG_LOGIC ("Examine channel device " << i << " on node " << nodeOther->GetId ()); // // For all other net devices, we need to check and see if a router // is present. If the net device on the other side is a bridged // device, we need to consider all of the other devices on the // bridge as well (all of the bridge ports. // NS_LOG_LOGIC ("checking to see if the device is bridged"); Ptr<BridgeNetDevice> bnd = NetDeviceIsBridged (ndOther); if (bnd) { NS_LOG_LOGIC ("Device is bridged by BridgeNetDevice " << bnd); // // It is possible that the bridge net device is sitting under a // router, so we have to check for the presence of that router // before we run off and follow all the links // // We require a designated router to have a GlobalRouter interface and // an internet stack that includes the Ipv4 interface. If it doesn't // it can't play router. // NS_LOG_LOGIC ("Checking for router on bridge net device " << bnd); Ptr<GlobalRouter> rtr = nodeOther->GetObject<GlobalRouter> (); Ptr<Ipv4> ipv4 = nodeOther->GetObject<Ipv4> (); if (rtr && ipv4) { // Initialize to value out of bounds to silence compiler uint32_t interfaceOther = ipv4->GetNInterfaces () + 1; if (FindInterfaceForDevice (nodeOther, bnd, interfaceOther)) { NS_LOG_LOGIC ("Found router on bridge net device " << bnd); if (!ipv4->IsUp (interfaceOther)) { NS_LOG_LOGIC ("Remote side interface " << interfaceOther << " not up"); continue; } if (ipv4->GetNAddresses (interfaceOther) > 1) { NS_LOG_WARN ("Warning, interface has multiple IP addresses; using only the primary one"); } Ipv4Address addrOther = ipv4->GetAddress (interfaceOther, 0).GetLocal (); desigRtr = addrOther < desigRtr ? addrOther : desigRtr; NS_LOG_LOGIC ("designated router now " << desigRtr); } } NS_LOG_LOGIC ("Looking through bridge ports of bridge net device " << bnd); for (uint32_t j = 0; j < bnd->GetNBridgePorts (); ++j) { Ptr<NetDevice> ndBridged = bnd->GetBridgePort (j); NS_LOG_LOGIC ("Examining bridge port " << j << " device " << ndBridged); if (ndBridged == ndOther) { NS_LOG_LOGIC ("That bridge port is me, don't walk backward"); continue; } if (allowRecursion) { NS_LOG_LOGIC ("Recursively looking for routers down bridge port " << ndBridged); Ipv4Address addrOther = FindDesignatedRouterForLink (ndBridged, false); desigRtr = addrOther < desigRtr ? addrOther : desigRtr; NS_LOG_LOGIC ("designated router now " << desigRtr); } } } else { NS_LOG_LOGIC ("This device is not bridged"); Ptr<Node> nodeOther = ndOther->GetNode (); NS_ASSERT (nodeOther); // // We require a designated router to have a GlobalRouter interface and // an internet stack that includes the Ipv4 interface. If it doesn't // Ptr<GlobalRouter> rtr = nodeOther->GetObject<GlobalRouter> (); Ptr<Ipv4> ipv4 = nodeOther->GetObject<Ipv4> (); if (rtr && ipv4) { // Initialize to value out of bounds to silence compiler uint32_t interfaceOther = ipv4->GetNInterfaces () + 1; if (FindInterfaceForDevice (nodeOther, ndOther, interfaceOther)) { if (!ipv4->IsUp (interfaceOther)) { NS_LOG_LOGIC ("Remote side interface " << interfaceOther << " not up"); continue; } NS_LOG_LOGIC ("Found router on net device " << ndOther); if (ipv4->GetNAddresses (interfaceOther) > 1) { NS_LOG_WARN ("Warning, interface has multiple IP addresses; using only the primary one"); } Ipv4Address addrOther = ipv4->GetAddress (interfaceOther, 0).GetLocal (); desigRtr = addrOther < desigRtr ? addrOther : desigRtr; NS_LOG_LOGIC ("designated router now " << desigRtr); } } } } return desigRtr; } // // Given a node and an attached net device, take a look off in the channel to // which the net device is attached and look for a node on the other side // that has a GlobalRouter interface aggregated. Life gets more complicated // when there is a bridged net device on the other side. // bool GlobalRouter::AnotherRouterOnLink (Ptr<NetDevice> nd, bool allowRecursion) const { NS_LOG_FUNCTION (nd << allowRecursion); Ptr<Channel> ch = nd->GetChannel (); if (!ch) { // It may be that this net device is a stub device, without a channel return false; } uint32_t nDevices = ch->GetNDevices (); NS_ASSERT (nDevices); NS_LOG_LOGIC ("Looking for routers off of net device " << nd << " on node " << nd->GetNode ()->GetId ()); // // Look through all of the devices on the channel to which the net device // in question is attached. // for (uint32_t i = 0; i < nDevices; i++) { Ptr<NetDevice> ndOther = ch->GetDevice (i); NS_ASSERT (ndOther); NS_LOG_LOGIC ("Examine channel device " << i << " on node " << ndOther->GetNode ()->GetId ()); // // Ignore the net device itself. // if (ndOther == nd) { NS_LOG_LOGIC ("Myself, skip"); continue; } // // For all other net devices, we need to check and see if a router // is present. If the net device on the other side is a bridged // device, we need to consider all of the other devices on the // bridge. // NS_LOG_LOGIC ("checking to see if device is bridged"); Ptr<BridgeNetDevice> bnd = NetDeviceIsBridged (ndOther); if (bnd) { NS_LOG_LOGIC ("Device is bridged by net device " << bnd); NS_LOG_LOGIC ("Looking through bridge ports of bridge net device " << bnd); for (uint32_t j = 0; j < bnd->GetNBridgePorts (); ++j) { Ptr<NetDevice> ndBridged = bnd->GetBridgePort (j); NS_LOG_LOGIC ("Examining bridge port " << j << " device " << ndBridged); if (ndBridged == ndOther) { NS_LOG_LOGIC ("That bridge port is me, skip"); continue; } if (allowRecursion) { NS_LOG_LOGIC ("Recursively looking for routers on bridge port " << ndBridged); if (AnotherRouterOnLink (ndBridged, false)) { NS_LOG_LOGIC ("Found routers on bridge port, return true"); return true; } } } NS_LOG_LOGIC ("No routers on bridged net device, return false"); return false; } NS_LOG_LOGIC ("This device is not bridged"); Ptr<Node> nodeTemp = ndOther->GetNode (); NS_ASSERT (nodeTemp); Ptr<GlobalRouter> rtr = nodeTemp->GetObject<GlobalRouter> (); if (rtr) { NS_LOG_LOGIC ("Found GlobalRouter interface, return true"); return true; } else { NS_LOG_LOGIC ("No GlobalRouter interface on device, continue search"); } } NS_LOG_LOGIC ("No routers found, return false"); return false; } uint32_t GlobalRouter::GetNumLSAs (void) const { NS_LOG_FUNCTION_NOARGS (); return m_LSAs.size (); } // // Get the nth link state advertisement from this router. // bool GlobalRouter::GetLSA (uint32_t n, GlobalRoutingLSA &lsa) const { NS_LOG_FUNCTION_NOARGS (); NS_ASSERT_MSG (lsa.IsEmpty (), "GlobalRouter::GetLSA (): Must pass empty LSA"); // // All of the work was done in GetNumLSAs. All we have to do here is to // walk the list of link state advertisements created there and return the // one the client is interested in. // ListOfLSAs_t::const_iterator i = m_LSAs.begin (); uint32_t j = 0; for (; i != m_LSAs.end (); i++, j++) { if (j == n) { GlobalRoutingLSA *p = *i; lsa = *p; return true; } } return false; } void GlobalRouter::InjectRoute (Ipv4Address network, Ipv4Mask networkMask) { NS_LOG_FUNCTION (network << networkMask); Ipv4RoutingTableEntry *route = new Ipv4RoutingTableEntry (); // // Interface number does not matter here, using 1. // *route = Ipv4RoutingTableEntry::CreateNetworkRouteTo (network, networkMask, 1); m_injectedRoutes.push_back (route); } Ipv4RoutingTableEntry * GlobalRouter::GetInjectedRoute (uint32_t index) { NS_LOG_FUNCTION (index); if (index < m_injectedRoutes.size ()) { uint32_t tmp = 0; for (InjectedRoutesCI i = m_injectedRoutes.begin (); i != m_injectedRoutes.end (); i++) { if (tmp == index) { return *i; } tmp++; } } NS_ASSERT (false); // quiet compiler. return 0; } uint32_t GlobalRouter::GetNInjectedRoutes () { return m_injectedRoutes.size (); } void GlobalRouter::RemoveInjectedRoute (uint32_t index) { NS_LOG_FUNCTION (index); NS_ASSERT (index < m_injectedRoutes.size ()); uint32_t tmp = 0; for (InjectedRoutesI i = m_injectedRoutes.begin (); i != m_injectedRoutes.end (); i++) { if (tmp == index) { NS_LOG_LOGIC ("Removing route " << index << "; size = " << m_injectedRoutes.size ()); delete *i; m_injectedRoutes.erase (i); return; } tmp++; } } bool GlobalRouter::WithdrawRoute (Ipv4Address network, Ipv4Mask networkMask) { NS_LOG_FUNCTION (network << networkMask); for (InjectedRoutesI i = m_injectedRoutes.begin (); i != m_injectedRoutes.end (); i++) { if ((*i)->GetDestNetwork () == network && (*i)->GetDestNetworkMask () == networkMask) { NS_LOG_LOGIC ("Withdrawing route to network/mask " << network << "/" << networkMask); delete *i; m_injectedRoutes.erase (i); return true; } } return false; } // // Link through the given channel and find the net device that's on the // other end. This only makes sense with a point-to-point channel. // Ptr<NetDevice> GlobalRouter::GetAdjacent (Ptr<NetDevice> nd, Ptr<Channel> ch) const { NS_LOG_FUNCTION_NOARGS (); NS_ASSERT_MSG (ch->GetNDevices () == 2, "GlobalRouter::GetAdjacent (): Channel with other than two devices"); // // This is a point to point channel with two endpoints. Get both of them. // Ptr<NetDevice> nd1 = ch->GetDevice (0); Ptr<NetDevice> nd2 = ch->GetDevice (1); // // One of the endpoints is going to be "us" -- that is the net device attached // to the node on which we're running -- i.e., "nd". The other endpoint (the // one to which we are connected via the channel) is the adjacent router. // if (nd1 == nd) { return nd2; } else if (nd2 == nd) { return nd1; } else { NS_ASSERT_MSG (false, "GlobalRouter::GetAdjacent (): Wrong or confused channel?"); return 0; } } // // Given a node and a net device, find an IPV4 interface index that corresponds // to that net device. This function may fail for various reasons. If a node // does not have an internet stack (for example if it is a bridge) we won't have // an IPv4 at all. If the node does have a stack, but the net device in question // is bridged, there will not be an interface associated directly with the device. // bool GlobalRouter::FindInterfaceForDevice (Ptr<Node> node, Ptr<NetDevice> nd, uint32_t &index) const { NS_LOG_FUNCTION_NOARGS (); NS_LOG_LOGIC ("For node " << node->GetId () << " for net device " << nd ); Ptr<Ipv4> ipv4 = node->GetObject<Ipv4> (); if (ipv4 == 0) { NS_LOG_LOGIC ("No Ipv4 interface on node " << node->GetId ()); return false; } for (uint32_t i = 0; i < ipv4->GetNInterfaces (); ++i ) { if (ipv4->GetNetDevice (i) == nd) { NS_LOG_LOGIC ("Device " << nd << " has associated ipv4 index " << i); index = i; return true; } } NS_LOG_LOGIC ("Device " << nd << " has no associated ipv4 index"); return false; } // // Decide whether or not a given net device is being bridged by a BridgeNetDevice. // Ptr<BridgeNetDevice> GlobalRouter::NetDeviceIsBridged (Ptr<NetDevice> nd) const { NS_LOG_FUNCTION (nd); Ptr<Node> node = nd->GetNode (); uint32_t nDevices = node->GetNDevices (); // // There is no bit on a net device that says it is being bridged, so we have // to look for bridges on the node to which the device is attached. If we // find a bridge, we need to look through its bridge ports (the devices it // bridges) to see if we find the device in question. // for (uint32_t i = 0; i < nDevices; ++i) { Ptr<NetDevice> ndTest = node->GetDevice (i); NS_LOG_LOGIC ("Examine device " << i << " " << ndTest); if (ndTest->IsBridge ()) { NS_LOG_LOGIC ("device " << i << " is a bridge net device"); Ptr<BridgeNetDevice> bnd = ndTest->GetObject<BridgeNetDevice> (); NS_ABORT_MSG_UNLESS (bnd, "GlobalRouter::DiscoverLSAs (): GetObject for <BridgeNetDevice> failed"); for (uint32_t j = 0; j < bnd->GetNBridgePorts (); ++j) { NS_LOG_LOGIC ("Examine bridge port " << j << " " << bnd->GetBridgePort (j)); if (bnd->GetBridgePort (j) == nd) { NS_LOG_LOGIC ("Net device " << nd << " is bridged by " << bnd); return bnd; } } } } NS_LOG_LOGIC ("Net device " << nd << " is not bridged"); return 0; } } // namespace ns3
zy901002-gpsr
src/internet/model/global-router-interface.cc
C++
gpl2
54,902
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef NSC_TCP_SOCKET_IMPL_H #define NSC_TCP_SOCKET_IMPL_H #include <stdint.h> #include <queue> #include <vector> #include "ns3/callback.h" #include "ns3/traced-value.h" #include "ns3/tcp-socket.h" #include "ns3/ptr.h" #include "ns3/ipv4-address.h" #include "ns3/inet-socket-address.h" #include "ns3/event-id.h" #include "pending-data.h" #include "ns3/sequence-number.h" struct INetStreamSocket; namespace ns3 { class Ipv4EndPoint; class Node; class Packet; class NscTcpL4Protocol; class TcpHeader; /** * \ingroup socket * \ingroup nsctcp * * \brief Socket logic for the NSC TCP sockets. * * Most of the TCP internal * logic is handled by the NSC tcp library itself; this class maps ns3::Socket * calls to the NSC TCP library. */ class NscTcpSocketImpl : public TcpSocket { public: static TypeId GetTypeId (void); /** * Create an unbound tcp socket. */ NscTcpSocketImpl (); NscTcpSocketImpl (const NscTcpSocketImpl& sock); virtual ~NscTcpSocketImpl (); void SetNode (Ptr<Node> node); void SetTcp (Ptr<NscTcpL4Protocol> tcp); virtual enum SocketErrno GetErrno (void) const; virtual enum SocketType GetSocketType (void) const; virtual Ptr<Node> GetNode (void) const; virtual int Bind (void); virtual int Bind (const Address &address); virtual int Close (void); virtual int ShutdownSend (void); virtual int ShutdownRecv (void); virtual int Connect (const Address &address); virtual int Listen (void); virtual uint32_t GetTxAvailable (void) const; virtual int Send (Ptr<Packet> p, uint32_t flags); virtual int SendTo (Ptr<Packet> p, uint32_t flags, const Address &toAddress); virtual uint32_t GetRxAvailable (void) const; virtual Ptr<Packet> Recv (uint32_t maxSize, uint32_t flags); virtual Ptr<Packet> RecvFrom (uint32_t maxSize, uint32_t flags, Address &fromAddress); virtual int GetSockName (Address &address) const; virtual bool SetAllowBroadcast (bool allowBroadcast); virtual bool GetAllowBroadcast () const; private: void NSCWakeup (void); friend class Tcp; // invoked by Tcp class int FinishBind (void); void ForwardUp (Ptr<Packet> p, Ipv4Header header, uint16_t port, Ptr<Ipv4Interface> incomingInterface); void Destroy (void); //methods for state bool SendPendingData (void); bool ReadPendingData (void); bool Accept (void); void CompleteFork (void); void ConnectionSucceeded (); // Manage data tx/rx // XXX This should be virtual and overridden Ptr<NscTcpSocketImpl> Copy (); // attribute related virtual void SetSndBufSize (uint32_t size); virtual uint32_t GetSndBufSize (void) const; virtual void SetRcvBufSize (uint32_t size); virtual uint32_t GetRcvBufSize (void) const; virtual void SetSegSize (uint32_t size); virtual uint32_t GetSegSize (void) const; virtual void SetAdvWin (uint32_t window); virtual uint32_t GetAdvWin (void) const; virtual void SetSSThresh (uint32_t threshold); virtual uint32_t GetSSThresh (void) const; virtual void SetInitialCwnd (uint32_t cwnd); virtual uint32_t GetInitialCwnd (void) const; virtual void SetConnTimeout (Time timeout); virtual Time GetConnTimeout (void) const; virtual void SetConnCount (uint32_t count); virtual uint32_t GetConnCount (void) const; virtual void SetDelAckTimeout (Time timeout); virtual Time GetDelAckTimeout (void) const; virtual void SetDelAckMaxCount (uint32_t count); virtual uint32_t GetDelAckMaxCount (void) const; virtual void SetPersistTimeout (Time timeout); virtual Time GetPersistTimeout (void) const; enum Socket::SocketErrno GetNativeNs3Errno (int err) const; uint32_t m_delAckMaxCount; Time m_delAckTimeout; Ipv4EndPoint *m_endPoint; Ptr<Node> m_node; Ptr<NscTcpL4Protocol> m_tcp; Ipv4Address m_remoteAddress; uint16_t m_remotePort; //these two are so that the socket/endpoint cloning works Ipv4Address m_localAddress; uint16_t m_localPort; InetSocketAddress m_peerAddress; enum SocketErrno m_errno; bool m_shutdownSend; bool m_shutdownRecv; bool m_connected; //manage the state information TracedValue<TcpStates_t> m_state; bool m_closeOnEmpty; //needed to queue data when in SYN_SENT state std::queue<Ptr<Packet> > m_txBuffer; uint32_t m_txBufferSize; // Window management uint32_t m_segmentSize; //SegmentSize uint32_t m_rxWindowSize; uint32_t m_advertisedWindowSize; //Window to advertise TracedValue<uint32_t> m_cWnd; //Congestion window uint32_t m_ssThresh; //Slow Start Threshold uint32_t m_initialCWnd; //Initial cWnd value // Round trip time estimation Time m_lastMeasuredRtt; // Timer-related members Time m_cnTimeout; uint32_t m_cnCount; Time m_persistTimeout; // Temporary queue for delivering data to application std::queue<Ptr<Packet> > m_deliveryQueue; uint32_t m_rxAvailable; INetStreamSocket* m_nscTcpSocket; // Attributes uint32_t m_sndBufSize; // buffer limit for the outgoing queue uint32_t m_rcvBufSize; // maximum receive socket buffer size }; } // namespace ns3 #endif /* NSC_TCP_SOCKET_IMPL_H */
zy901002-gpsr
src/internet/model/nsc-tcp-socket-impl.h
C++
gpl2
6,034
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr> */ #include <string> #include "ns3/attribute.h" #include "ns3/object.h" struct INetStack; namespace ns3 { // This object represents the underlying nsc stack, // which is aggregated to a Node object, and which provides access to the // sysctls of the nsc stack through attributes. class Ns3NscStack : public Object { public: static TypeId GetTypeId (void); virtual TypeId GetInstanceTypeId (void) const; void SetStack (INetStack *stack) { m_stack = stack; } private: friend class NscStackStringAccessor; void Set (std::string name, std::string value); std::string Get (std::string name) const; INetStack *m_stack; }; } // namespace ns3
zy901002-gpsr
src/internet/model/nsc-sysctl.h
C++
gpl2
1,435
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2008 INRIA * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr> */ #ifndef IPV4_RAW_SOCKET_FACTORY_IMPL_H #define IPV4_RAW_SOCKET_FACTORY_IMPL_H #include "ns3/ipv4-raw-socket-factory.h" namespace ns3 { class Ipv4RawSocketFactoryImpl : public Ipv4RawSocketFactory { public: virtual Ptr<Socket> CreateSocket (void); }; } // namespace ns3 #endif /* IPV4_RAW_SOCKET_FACTORY_IMPL_H */
zy901002-gpsr
src/internet/model/ipv4-raw-socket-factory-impl.h
C++
gpl2
1,136
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2010 Adrian Sai-wah Tam * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Adrian Sai-wah Tam <adrian.sw.tam@gmail.com> */ #ifndef TCP_RFC793_H #define TCP_RFC793_H #include "tcp-socket-base.h" namespace ns3 { /** * \ingroup socket * \ingroup tcp * * \brief An implementation of a stream socket using TCP. * * This class contains an RFC793 implementation of TCP, as well as a sockets * interface for talking to TCP. This serves as a base for other TCP functions * where the sliding window mechanism is handled here. This class provides * connection orientation and sliding window flow control. */ class TcpRfc793 : public TcpSocketBase { public: static TypeId GetTypeId (void); /** * Create an unbound tcp socket. */ TcpRfc793 (void); TcpRfc793 (const TcpRfc793& sock); virtual ~TcpRfc793 (void); protected: virtual Ptr<TcpSocketBase> Fork (); // Call CopyObject<TcpRfc793> to clone me virtual void DupAck (const TcpHeader& t, uint32_t count); virtual void SetSSThresh (uint32_t threshold); virtual uint32_t GetSSThresh (void) const; virtual void SetInitialCwnd (uint32_t cwnd); virtual uint32_t GetInitialCwnd (void) const; }; } // namespace ns3 #endif /* TCP_RFC793_H */
zy901002-gpsr
src/internet/model/tcp-rfc793.h
C++
gpl2
1,929
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2006 INRIA * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr> */ #ifndef ARP_CACHE_H #define ARP_CACHE_H #include <stdint.h> #include <list> #include "ns3/simulator.h" #include "ns3/callback.h" #include "ns3/packet.h" #include "ns3/nstime.h" #include "ns3/net-device.h" #include "ns3/ipv4-address.h" #include "ns3/address.h" #include "ns3/ptr.h" #include "ns3/object.h" #include "ns3/traced-callback.h" #include "ns3/sgi-hashmap.h" namespace ns3 { class NetDevice; class Ipv4Interface; /** * \ingroup arp * \brief An ARP cache * * A cached lookup table for translating layer 3 addresses to layer 2. * This implementation does lookups from IPv4 to a MAC address */ class ArpCache : public Object { private: ArpCache (ArpCache const &); ArpCache& operator= (ArpCache const &); public: static TypeId GetTypeId (void); class Entry; ArpCache (); ~ArpCache (); /** * \param device The hardware NetDevice associated with this ARP chache * \param interface the Ipv4Interface associated with this ARP chache */ void SetDevice (Ptr<NetDevice> device, Ptr<Ipv4Interface> interface); /** * \return The NetDevice that this ARP cache is associated with */ Ptr<NetDevice> GetDevice (void) const; /** * \return the Ipv4Interface that this ARP cache is associated with */ Ptr<Ipv4Interface> GetInterface (void) const; void SetAliveTimeout (Time aliveTimeout); void SetDeadTimeout (Time deadTimeout); void SetWaitReplyTimeout (Time waitReplyTimeout); Time GetAliveTimeout (void) const; Time GetDeadTimeout (void) const; Time GetWaitReplyTimeout (void) const; /** * This callback is set when the ArpCache is set up and allows * the cache to generate an Arp request when the WaitReply * time expires and a retransmission must be sent * * \param arpRequestCallback Callback for transmitting an Arp request. */ void SetArpRequestCallback (Callback<void, Ptr<const ArpCache>, Ipv4Address> arpRequestCallback); /** * This method will schedule a timeout at WaitReplyTimeout interval * in the future, unless a timer is already running for the cache, * in which case this method does nothing. */ void StartWaitReplyTimer (void); /** * \brief Do lookup in the ARP cache against an IP address * \param destination The destination IPv4 address to lookup the MAC address * of * \return An ArpCache::Entry with info about layer 2 */ ArpCache::Entry *Lookup (Ipv4Address destination); /** * \brief Add an Ipv4Address to this ARP cache */ ArpCache::Entry *Add (Ipv4Address to); /** * \brief Clear the ArpCache of all entries */ void Flush (void); /** * \brief A record that that holds information about an ArpCache entry */ class Entry { public: /** * \brief Constructor * \param arp The ArpCache this entry belongs to */ Entry (ArpCache *arp); /** * \brief Changes the state of this entry to dead */ void MarkDead (void); /** * \param macAddress */ void MarkAlive (Address macAddress); /** * \param waiting */ void MarkWaitReply (Ptr<Packet> waiting); /** * \param waiting * \return */ bool UpdateWaitReply (Ptr<Packet> waiting); /** * \return True if the state of this entry is dead; false otherwise. */ bool IsDead (void); /** * \return True if the state of this entry is alive; false otherwise. */ bool IsAlive (void); /** * \return True if the state of this entry is wait_reply; false otherwise. */ bool IsWaitReply (void); /** * \return The MacAddress of this entry */ Address GetMacAddress (void) const; /** * \return The Ipv4Address for this entry */ Ipv4Address GetIpv4Address (void) const; /** * \param destination The Ipv4Address for this entry */ void SetIpv4Address (Ipv4Address destination); /** * \return True if this entry has timed out; false otherwise. * * This function returns true if the time elapsed strictly exceeds * the timeout value (i.e., is not less than or equal to the timeout). */ bool IsExpired (void) const; /** * \returns 0 is no packet is pending, the next packet to send if * packets are pending. */ Ptr<Packet> DequeuePending (void); /** * \returns number of retries that have been sent for an ArpRequest * in WaitReply state. */ uint32_t GetRetries (void) const; /** * \brief Increment the counter of number of retries for an entry */ void IncrementRetries (void); /** * \brief Zero the counter of number of retries for an entry */ void ClearRetries (void); private: enum ArpCacheEntryState_e { ALIVE, WAIT_REPLY, DEAD }; void UpdateSeen (void); Time GetTimeout (void) const; ArpCache *m_arp; ArpCacheEntryState_e m_state; Time m_lastSeen; Address m_macAddress; Ipv4Address m_ipv4Address; std::list<Ptr<Packet> > m_pending; uint32_t m_retries; }; private: typedef sgi::hash_map<Ipv4Address, ArpCache::Entry *, Ipv4AddressHash> Cache; typedef sgi::hash_map<Ipv4Address, ArpCache::Entry *, Ipv4AddressHash>::iterator CacheI; virtual void DoDispose (void); Ptr<NetDevice> m_device; Ptr<Ipv4Interface> m_interface; Time m_aliveTimeout; Time m_deadTimeout; Time m_waitReplyTimeout; EventId m_waitReplyTimer; Callback<void, Ptr<const ArpCache>, Ipv4Address> m_arpRequestCallback; uint32_t m_maxRetries; /** * This function is an event handler for the event that the * ArpCache wants to check whether it must retry any Arp requests. * If there are no Arp requests pending, this event is not scheduled. */ void HandleWaitReplyTimeout (void); uint32_t m_pendingQueueSize; Cache m_arpCache; TracedCallback<Ptr<const Packet> > m_dropTrace; }; } // namespace ns3 #endif /* ARP_CACHE_H */
zy901002-gpsr
src/internet/model/arp-cache.h
C++
gpl2
6,783
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007 INRIA * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr> */ #ifndef IPV4_H #define IPV4_H #include <stdint.h> #include "ns3/object.h" #include "ns3/socket.h" #include "ns3/callback.h" #include "ns3/ipv4-l4-protocol.h" #include "ns3/ipv4-address.h" #include "ipv4-route.h" #include "ipv4-interface-address.h" namespace ns3 { class Node; class NetDevice; class Packet; class Ipv4RoutingProtocol; /** * \ingroup internet * \defgroup ipv4 Ipv4 */ /** * \ingroup ipv4 * \brief Access to the Ipv4 forwarding table, interfaces, and configuration * * This class defines the API to manipulate the following aspects of * the Ipv4 implementation: * -# set/get an Ipv4RoutingProtocol * -# register a NetDevice for use by the Ipv4 layer (basically, to * create Ipv4-related state such as addressing and neighbor cache that * is associated with a NetDevice) * -# manipulate the status of the NetDevice from the Ipv4 perspective, * such as marking it as Up or Down, * -# adding, deleting, and getting addresses associated to the Ipv4 * interfaces. * -# exporting Ipv4 configuration attributes * * Each NetDevice has conceptually a single Ipv4 interface associated * with it (the corresponding structure in the Linux Ipv4 implementation * is struct in_device). Each interface may have one or more Ipv4 * addresses associated with it. Each Ipv4 address may have different * subnet mask, scope, etc., so all of this per-address information * is stored in an Ipv4InterfaceAddress class (the corresponding * structure in Linux is struct in_ifaddr) * * Ipv4 attributes such as whether IP forwarding is enabled and disabled * are also stored in this class * * TO DO: Add API to allow access to the Ipv4 neighbor table * * \see Ipv4RoutingProtocol * \see Ipv4InterfaceAddress */ class Ipv4 : public Object { public: static TypeId GetTypeId (void); Ipv4 (); virtual ~Ipv4 (); /** * \brief Register a new routing protocol to be used by this Ipv4 stack * * This call will replace any routing protocol that has been previously * registered. If you want to add multiple routing protocols, you must * add them to a Ipv4ListRoutingProtocol directly. * * \param routingProtocol smart pointer to Ipv4RoutingProtocol object */ virtual void SetRoutingProtocol (Ptr<Ipv4RoutingProtocol> routingProtocol) = 0; /** * \brief Get the routing protocol to be used by this Ipv4 stack * * \returns smart pointer to Ipv4RoutingProtocol object, or null pointer if none */ virtual Ptr<Ipv4RoutingProtocol> GetRoutingProtocol (void) const = 0; /** * \param device device to add to the list of Ipv4 interfaces * which can be used as output interfaces during packet forwarding. * \returns the index of the Ipv4 interface added. * * Once a device has been added, it can never be removed: if you want * to disable it, you can invoke Ipv4::SetDown which will * make sure that it is never used during packet forwarding. */ virtual uint32_t AddInterface (Ptr<NetDevice> device) = 0; /** * \returns the number of interfaces added by the user. */ virtual uint32_t GetNInterfaces (void) const = 0; /** * \brief Return the interface number of the interface that has been * assigned the specified IP address. * * \param address The IP address being searched for * \returns The interface number of the Ipv4 interface with the given * address or -1 if not found. * * Each IP interface has one or more IP addresses associated with it. * This method searches the list of interfaces for one that holds a * particular address. This call takes an IP address as a parameter and * returns the interface number of the first interface that has been assigned * that address, or -1 if not found. There must be an exact match; this * method will not match broadcast or multicast addresses. */ virtual int32_t GetInterfaceForAddress (Ipv4Address address) const = 0; /** * \param packet packet to send * \param source source address of packet * \param destination address of packet * \param protocol number of packet * \param route route entry * * Higher-level layers call this method to send a packet * down the stack to the MAC and PHY layers. */ virtual void Send (Ptr<Packet> packet, Ipv4Address source, Ipv4Address destination, uint8_t protocol, Ptr<Ipv4Route> route) = 0; /** * \param protocol a pointer to the protocol to add to this L4 Demux. * * Adds a protocol to an internal list of L4 protocols. * */ virtual void Insert (Ptr<Ipv4L4Protocol> protocol) = 0; /** * \brief Determine whether address and interface corresponding to * received packet can be accepted for local delivery * * \param address The IP address being considered * \param iif The incoming Ipv4 interface index * * This method can be used to determine whether a received packet has * an acceptable address for local delivery on the host. The address * may be a unicast, multicast, or broadcast address. This method will * return true if address is an exact match of a unicast address on * one of the host's interfaces (see below), if address corresponds to * a multicast group that the host has joined (and the incoming device * is acceptable), or if address corresponds to a broadcast address. * * If the Ipv4 attribute WeakEsModel is true, the unicast address may * match any of the Ipv4 addresses on any interface. If the attribute is * false, the address must match one assigned to the incoming device. */ virtual bool IsDestinationAddress (Ipv4Address address, uint32_t iif) const = 0; /** * \brief Return the interface number of first interface found that * has an Ipv4 address within the prefix specified by the input * address and mask parameters * * \param address The IP address assigned to the interface of interest. * \param mask The IP prefix to use in the mask * \returns The interface number of the Ipv4 interface with the given * address or -1 if not found. * * Each IP interface has one or more IP addresses associated with it. * This method searches the list of interfaces for the first one found * that holds an address that is included within the prefix * formed by the input address and mask parameters. The value -1 is * returned if no match is found. */ virtual int32_t GetInterfaceForPrefix (Ipv4Address address, Ipv4Mask mask) const = 0; /** * \param interface The interface number of an Ipv4 interface. * \returns The NetDevice associated with the Ipv4 interface number. */ virtual Ptr<NetDevice> GetNetDevice (uint32_t interface) = 0; /** * \param device The NetDevice for an Ipv4Interface * \returns The interface number of an Ipv4 interface or -1 if not found. */ virtual int32_t GetInterfaceForDevice (Ptr<const NetDevice> device) const = 0; /** * \param interface Interface number of an Ipv4 interface * \param address Ipv4InterfaceAddress address to associate with the underlying Ipv4 interface * \returns true if the operation succeeded */ virtual bool AddAddress (uint32_t interface, Ipv4InterfaceAddress address) = 0; /** * \param interface Interface number of an Ipv4 interface * \returns the number of Ipv4InterfaceAddress entries for the interface. */ virtual uint32_t GetNAddresses (uint32_t interface) const = 0; /** * Because addresses can be removed, the addressIndex is not guaranteed * to be static across calls to this method. * * \param interface Interface number of an Ipv4 interface * \param addressIndex index of Ipv4InterfaceAddress * \returns the Ipv4InterfaceAddress associated to the interface and addressIndex */ virtual Ipv4InterfaceAddress GetAddress (uint32_t interface, uint32_t addressIndex) const = 0; /** * Remove the address at addressIndex on named interface. The addressIndex * for all higher indices will decrement by one after this method is called; * so, for example, to remove 5 addresses from an interface i, one could * call RemoveAddress (i, 0); 5 times. * * \param interface Interface number of an Ipv4 interface * \param addressIndex index of Ipv4InterfaceAddress to remove * \returns true if the operation succeeded */ virtual bool RemoveAddress (uint32_t interface, uint32_t addressIndex) = 0; /** * \brief Return the first primary source address with scope less than * or equal to the requested scope, to use in sending a packet to * destination dst out of the specified device. * * This method mirrors the behavior of Linux inet_select_addr() and is * provided because interfaces may have multiple IP addresses configured * on them with different scopes, and with a primary and secondary status. * Secondary addresses are never returned. * \see Ipv4InterfaceAddress * * If a non-zero device pointer is provided, the method first tries to * return a primary address that is configured on that device, and whose * subnet matches that of dst and whose scope is less than or equal to * the requested scope. If a primary address does not match the * subnet of dst but otherwise matches the scope, it is returned. * If no such address on the device is found, the other devices are * searched in order of their interface index, but not considering dst * as a factor in the search. Because a loopback interface is typically * the first one configured on a node, it will be the first alternate * device to be tried. Addresses scoped at LINK scope are not returned * in this phase. * * If no device pointer is provided, the same logic as above applies, only * that there is no preferred device that is consulted first. This means * that if the device pointer is null, input parameter dst will be ignored. * * If there are no possible addresses to return, a warning log message * is issued and the all-zeroes address is returned. * * \param device output NetDevice (optionally provided, only to constrain the search) * \param dst Destination address to match, if device is provided * \param scope Scope of returned address must be less than or equal to this * \returns the first primary Ipv4Address that meets the search criteria */ virtual Ipv4Address SelectSourceAddress (Ptr<const NetDevice> device, Ipv4Address dst, Ipv4InterfaceAddress::InterfaceAddressScope_e scope) = 0; /** * \param interface The interface number of an Ipv4 interface * \param metric routing metric (cost) associated to the underlying * Ipv4 interface */ virtual void SetMetric (uint32_t interface, uint16_t metric) = 0; /** * \param interface The interface number of an Ipv4 interface * \returns routing metric (cost) associated to the underlying * Ipv4 interface */ virtual uint16_t GetMetric (uint32_t interface) const = 0; /** * \param interface Interface number of Ipv4 interface * \returns the Maximum Transmission Unit (in bytes) associated * to the underlying Ipv4 interface */ virtual uint16_t GetMtu (uint32_t interface) const = 0; /** * \param interface Interface number of Ipv4 interface * \returns true if the underlying interface is in the "up" state, * false otherwise. */ virtual bool IsUp (uint32_t interface) const = 0; /** * \param interface Interface number of Ipv4 interface * * Set the interface into the "up" state. In this state, it is * considered valid during Ipv4 forwarding. */ virtual void SetUp (uint32_t interface) = 0; /** * \param interface Interface number of Ipv4 interface * * Set the interface into the "down" state. In this state, it is * ignored during Ipv4 forwarding. */ virtual void SetDown (uint32_t interface) = 0; /** * \param interface Interface number of Ipv4 interface * \returns true if IP forwarding enabled for input datagrams on this device */ virtual bool IsForwarding (uint32_t interface) const = 0; /** * \param interface Interface number of Ipv4 interface * \param val Value to set the forwarding flag * * If set to true, IP forwarding is enabled for input datagrams on this device */ virtual void SetForwarding (uint32_t interface, bool val) = 0; static const uint32_t IF_ANY = 0xffffffff; private: // Indirect the Ipv4 attributes through private pure virtual methods virtual void SetIpForward (bool forward) = 0; virtual bool GetIpForward (void) const = 0; virtual void SetWeakEsModel (bool model) = 0; virtual bool GetWeakEsModel (void) const = 0; }; } // namespace ns3 #endif /* IPV4_H */
zy901002-gpsr
src/internet/model/ipv4.h
C++
gpl2
13,700
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007-2009 Strasbourg University * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Sebastien Vincent <vincent@clarinet.u-strasbg.fr> * Mehdi Benamor <benamor.mehdi@ensi.rnu.tn> * David Gross <gdavid.devel@gmail.com> */ #include "ns3/assert.h" #include "ns3/address-utils.h" #include "ns3/log.h" #include "icmpv6-header.h" namespace ns3 { NS_OBJECT_ENSURE_REGISTERED (Icmpv6Header); NS_LOG_COMPONENT_DEFINE ("Icmpv6Header"); TypeId Icmpv6Header::GetTypeId () { static TypeId tid = TypeId ("ns3::Icmpv6Header") .SetParent<Header> () .AddConstructor<Icmpv6Header> () ; return tid; } TypeId Icmpv6Header::GetInstanceTypeId () const { return GetTypeId (); } Icmpv6Header::Icmpv6Header () : m_calcChecksum (true), m_checksum (0), m_type (0), m_code (0) { } Icmpv6Header::~Icmpv6Header () { } uint8_t Icmpv6Header::GetType () const { return m_type; } void Icmpv6Header::SetType (uint8_t type) { m_type = type; } uint8_t Icmpv6Header::GetCode () const { return m_code; } void Icmpv6Header::SetCode (uint8_t code) { m_code = code; } uint16_t Icmpv6Header::GetChecksum () const { return m_checksum; } void Icmpv6Header::SetChecksum (uint16_t checksum) { m_checksum = checksum; } void Icmpv6Header::Print (std::ostream& os) const { os << "( type = " << (uint32_t)m_type << " code = " << (uint32_t)m_code << " checksum = " << (uint32_t)m_checksum << ")"; } uint32_t Icmpv6Header::GetSerializedSize () const { return 4; } uint32_t Icmpv6Header::Deserialize (Buffer::Iterator start) { Buffer::Iterator i = start; m_type = i.ReadU8 (); m_code = i.ReadU8 (); m_checksum = i.ReadNtohU16 (); #if 0 i.ReadU32 (); /* padding */ #endif return GetSerializedSize (); } void Icmpv6Header::Serialize (Buffer::Iterator start) const { Buffer::Iterator i = start; i.WriteU8 (m_type); i.WriteU8 (m_code); i.WriteU16 (0); #if 0 i.WriteU32 (0); /* padding */ #endif if (m_calcChecksum) { i = start; uint16_t checksum = i.CalculateIpChecksum (i.GetSize (), m_checksum); i = start; i.Next (2); i.WriteU16 (checksum); } } void Icmpv6Header::CalculatePseudoHeaderChecksum (Ipv6Address src, Ipv6Address dst, uint16_t length, uint8_t protocol) { Buffer buf = Buffer (40); uint8_t tmp[16]; Buffer::Iterator it; buf.AddAtStart (40); it = buf.Begin (); src.Serialize (tmp); it.Write (tmp, 16); /* source IPv6 address */ dst.Serialize (tmp); it.Write (tmp, 16); /* destination IPv6 address */ it.WriteU16 (0); /* length */ it.WriteU8 (length >> 8); /* length */ it.WriteU8 (length & 0xff); /* length */ it.WriteU16 (0); /* zero */ it.WriteU8 (0); /* zero */ it.WriteU8 (protocol); /* next header */ it = buf.Begin (); m_checksum = ~(it.CalculateIpChecksum (40)); } NS_OBJECT_ENSURE_REGISTERED (Icmpv6NS); Icmpv6NS::Icmpv6NS () { SetType (ICMPV6_ND_NEIGHBOR_SOLICITATION); SetCode (0); SetReserved (0); m_checksum = 0; } TypeId Icmpv6NS::GetTypeId () { static TypeId tid = TypeId ("ns3::Icmpv6NS") .SetParent<Icmpv6Header> () .AddConstructor<Icmpv6NS> () ; return tid; } TypeId Icmpv6NS::GetInstanceTypeId () const { return GetTypeId (); } Icmpv6NS::Icmpv6NS (Ipv6Address target) { SetType (ICMPV6_ND_NEIGHBOR_SOLICITATION); SetCode (0); SetReserved (0); SetIpv6Target (target); m_checksum = 0; /* test */ /* m_reserved = 0xdeadbeef; */ } Icmpv6NS::~Icmpv6NS () { } uint32_t Icmpv6NS::GetReserved () const { return m_reserved; } void Icmpv6NS::SetReserved (uint32_t reserved) { m_reserved = reserved; } Ipv6Address Icmpv6NS::GetIpv6Target () const { return m_target; } void Icmpv6NS::SetIpv6Target (Ipv6Address target) { m_target = target; } void Icmpv6NS::Print (std::ostream& os) const { os << "( type = " << (uint32_t)GetType () << " (NS) code = " << (uint32_t)GetCode () << " checksum = " << (uint32_t)GetChecksum () << ")"; } uint32_t Icmpv6NS::GetSerializedSize () const { return 24; } void Icmpv6NS::Serialize (Buffer::Iterator start) const { NS_LOG_FUNCTION_NOARGS (); uint8_t buff_target[16]; uint16_t checksum = 0; Buffer::Iterator i = start; i.WriteU8 (GetType ()); i.WriteU8 (GetCode ()); i.WriteU16 (0); i.WriteHtonU32 (m_reserved); m_target.Serialize (buff_target); i.Write (buff_target, 16); if (m_calcChecksum) { i = start; checksum = i.CalculateIpChecksum (i.GetSize (), m_checksum); i = start; i.Next (2); i.WriteU16 (checksum); } } uint32_t Icmpv6NS::Deserialize (Buffer::Iterator start) { uint8_t buf[16]; Buffer::Iterator i = start; SetType (i.ReadU8 ()); SetCode (i.ReadU8 ()); m_checksum = i.ReadU16 (); m_reserved = i.ReadNtohU32 (); i.Read (buf, 16); m_target.Set (buf); return GetSerializedSize (); } NS_OBJECT_ENSURE_REGISTERED (Icmpv6NA); TypeId Icmpv6NA::GetTypeId () { static TypeId tid = TypeId ("ns3::Icmpv6NA") .SetParent<Icmpv6Header> () .AddConstructor<Icmpv6NA> () ; return tid; } TypeId Icmpv6NA::GetInstanceTypeId () const { return GetTypeId (); } Icmpv6NA::Icmpv6NA () { SetType (ICMPV6_ND_NEIGHBOR_ADVERTISEMENT); SetCode (0); SetReserved (0); SetFlagR (0); SetFlagS (0); SetFlagO (0); m_checksum = 0; } Icmpv6NA::~Icmpv6NA () { } uint32_t Icmpv6NA::GetReserved () const { return m_reserved; } void Icmpv6NA::SetReserved (uint32_t reserved) { m_reserved = reserved; } Ipv6Address Icmpv6NA::GetIpv6Target () const { return m_target; } bool Icmpv6NA::GetFlagR () const { return m_flagR; } void Icmpv6NA::SetFlagR (bool r) { m_flagR = r; } bool Icmpv6NA::GetFlagS () const { return m_flagS; } void Icmpv6NA::SetFlagS (bool s) { m_flagS = s; } bool Icmpv6NA::GetFlagO () const { return m_flagO; } void Icmpv6NA::SetFlagO (bool o) { m_flagO = o; } void Icmpv6NA::SetIpv6Target (Ipv6Address target) { m_target = target; } void Icmpv6NA::Print (std::ostream& os) const { os << "( type = " << (uint32_t)GetType () << " (NA) code = " << (uint32_t)GetCode () << " checksum = " << (uint32_t)GetChecksum () << ")"; } uint32_t Icmpv6NA::GetSerializedSize () const { return 24; } void Icmpv6NA::Serialize (Buffer::Iterator start) const { uint8_t buff_target[16]; uint16_t checksum = 0; Buffer::Iterator i = start; uint32_t reserved = m_reserved; i.WriteU8 (GetType ()); i.WriteU8 (GetCode ()); i.WriteU16 (0); if (m_flagR) { reserved |= (uint32_t)(1 << 31); } if (m_flagS) { reserved |= (uint32_t)(1<< 30); } if (m_flagO) { reserved |= (uint32_t)(1<< 29); } i.WriteHtonU32 (reserved); m_target.Serialize (buff_target); i.Write (buff_target, 16); if (m_calcChecksum) { i = start; checksum = i.CalculateIpChecksum (i.GetSize (), GetChecksum ()); i = start; i.Next (2); i.WriteU16 (checksum); } } uint32_t Icmpv6NA::Deserialize (Buffer::Iterator start) { uint8_t buf[16]; Buffer::Iterator i = start; SetType (i.ReadU8 ()); SetCode (i.ReadU8 ()); m_checksum = i.ReadU16 (); m_reserved = i.ReadNtohU32 (); m_flagR = false; m_flagS = false; m_flagO = false; if (m_reserved & (1 << 31)) { m_flagR = true; } if (m_reserved & (1 << 30)) { m_flagS = true; } if (m_reserved & (1 << 29)) { m_flagO = true; } i.Read (buf, 16); m_target.Set (buf); return GetSerializedSize (); } NS_OBJECT_ENSURE_REGISTERED (Icmpv6RA); TypeId Icmpv6RA::GetTypeId () { static TypeId tid = TypeId ("ns3::Icmpv6RA") .SetParent<Icmpv6Header> () .AddConstructor<Icmpv6RA> () ; return tid; } TypeId Icmpv6RA::GetInstanceTypeId () const { return GetTypeId (); } Icmpv6RA::Icmpv6RA () { SetType (ICMPV6_ND_ROUTER_ADVERTISEMENT); SetCode (0); SetFlags (0); SetFlagM (0); SetFlagO (0); SetFlagH (0); SetCurHopLimit (0); SetLifeTime (0); SetRetransmissionTime (0); SetReachableTime (0); } Icmpv6RA::~Icmpv6RA () { } void Icmpv6RA::SetCurHopLimit (uint8_t m) { m_curHopLimit = m; } uint8_t Icmpv6RA::GetCurHopLimit () const { return m_curHopLimit; } uint16_t Icmpv6RA::GetLifeTime () const { return m_LifeTime; } uint32_t Icmpv6RA::GetReachableTime () const { return m_ReachableTime; } uint32_t Icmpv6RA::GetRetransmissionTime () const { return m_RetransmissionTimer; } void Icmpv6RA::SetLifeTime (uint16_t l) { m_LifeTime = l; } void Icmpv6RA::SetReachableTime (uint32_t r) { m_ReachableTime = r; } void Icmpv6RA::SetRetransmissionTime (uint32_t r) { m_RetransmissionTimer = r; } bool Icmpv6RA::GetFlagM () const { return m_flagM; } void Icmpv6RA::SetFlagM (bool m) { m_flagM = m; } bool Icmpv6RA::GetFlagO () const { return m_flagO; } void Icmpv6RA::SetFlagO (bool o) { m_flagO = o; } bool Icmpv6RA::GetFlagH () const { return m_flagH; } void Icmpv6RA::SetFlagH (bool h) { m_flagH = h; } uint8_t Icmpv6RA::GetFlags () const { return m_flags; } void Icmpv6RA::SetFlags (uint8_t f) { m_flags = f; } void Icmpv6RA::Print (std::ostream& os) const { os << "( type = " << (uint32_t)GetType () << " (RA) code = " << (uint32_t)GetCode () << " checksum = " << (uint32_t)GetChecksum () << ")"; } uint32_t Icmpv6RA::GetSerializedSize () const { return 16; } void Icmpv6RA::Serialize (Buffer::Iterator start) const { uint16_t checksum = 0; Buffer::Iterator i = start; uint8_t flags = 0; i.WriteU8 (GetType ()); i.WriteU8 (GetCode ()); i.WriteHtonU16 (0); i.WriteU8 (m_curHopLimit); if (m_flagM) { flags |= (uint8_t)(1<< 7); } if (m_flagO) { flags |= (uint8_t)(1<< 6); } if (m_flagH) { flags |= (uint8_t)(1<< 5); } i.WriteU8 (flags); i.WriteHtonU16 (GetLifeTime ()); i.WriteHtonU32 (GetReachableTime ()); i.WriteHtonU32 (GetRetransmissionTime ()); i = start; checksum = i.CalculateIpChecksum (i.GetSize (), GetChecksum ()); i = start; i.Next (2); i.WriteU16 (checksum); } uint32_t Icmpv6RA::Deserialize (Buffer::Iterator start) { Buffer::Iterator i = start; SetType (i.ReadU8 ()); SetCode (i.ReadU8 ()); m_checksum = i.ReadU16 (); SetCurHopLimit (i.ReadU8 ()); m_flags = i.ReadU8 (); m_flagM = false; m_flagO = false; m_flagH = false; if (m_flags & (1 << 7)) { m_flagM = true; } if (m_flags & (1 << 6)) { m_flagO = true; } if (m_flags & (1 << 5)) { m_flagH = true; } SetLifeTime (i.ReadNtohU16 ()); SetReachableTime (i.ReadNtohU32 ()); SetRetransmissionTime (i.ReadNtohU32 ()); return GetSerializedSize (); } NS_OBJECT_ENSURE_REGISTERED (Icmpv6RS); TypeId Icmpv6RS::GetTypeId () { static TypeId tid = TypeId ("ns3::Icmpv6RS") .SetParent<Icmpv6Header> () .AddConstructor<Icmpv6RS> () ; return tid; } TypeId Icmpv6RS::GetInstanceTypeId () const { return GetTypeId (); } Icmpv6RS::Icmpv6RS () { SetType (ICMPV6_ND_ROUTER_SOLICITATION); SetCode (0); SetReserved (0); } Icmpv6RS::~Icmpv6RS () { } uint32_t Icmpv6RS::GetReserved () const { return m_reserved; } void Icmpv6RS::SetReserved (uint32_t reserved) { m_reserved = reserved; } void Icmpv6RS::Print (std::ostream& os) const { os << "( type = " << (uint32_t)GetType () << " (RS) code = " << (uint32_t)GetCode () << " checksum = " << (uint32_t)GetChecksum () << ")"; } uint32_t Icmpv6RS::GetSerializedSize () const { return 8; } void Icmpv6RS::Serialize (Buffer::Iterator start) const { NS_LOG_FUNCTION_NOARGS (); uint16_t checksum = 0; Buffer::Iterator i = start; i.WriteU8 (GetType ()); i.WriteU8 (GetCode ()); i.WriteU16 (0); i.WriteHtonU32 (m_reserved); if (m_calcChecksum) { i = start; checksum = i.CalculateIpChecksum (i.GetSize (), GetChecksum ()); i = start; i.Next (2); i.WriteU16 (checksum); } } uint32_t Icmpv6RS::Deserialize (Buffer::Iterator start) { NS_LOG_FUNCTION_NOARGS (); Buffer::Iterator i = start; SetType (i.ReadU8 ()); SetCode (i.ReadU8 ()); m_checksum = i.ReadU16 (); m_reserved = i.ReadNtohU32 (); return GetSerializedSize (); } NS_OBJECT_ENSURE_REGISTERED (Icmpv6Redirection); TypeId Icmpv6Redirection::GetTypeId () { static TypeId tid = TypeId ("ns3::Icmpv6Redirection") .SetParent<Icmpv6Header> () .AddConstructor<Icmpv6Redirection> () ; return tid; } TypeId Icmpv6Redirection::GetInstanceTypeId () const { return GetTypeId (); } Icmpv6Redirection::Icmpv6Redirection () : m_target (Ipv6Address ("")), m_destination (Ipv6Address ("")), m_reserved (0) { SetType (ICMPV6_ND_REDIRECTION); SetCode (0); m_checksum = 0; } Icmpv6Redirection::~Icmpv6Redirection () { } void Icmpv6Redirection::SetReserved (uint32_t reserved) { m_reserved = reserved; } uint32_t Icmpv6Redirection::GetReserved () const { return m_reserved; } Ipv6Address Icmpv6Redirection::GetTarget () const { return m_target; } void Icmpv6Redirection::SetTarget (Ipv6Address target) { m_target = target; } Ipv6Address Icmpv6Redirection::GetDestination () const { return m_destination; } void Icmpv6Redirection::SetDestination (Ipv6Address destination) { m_destination = destination; } void Icmpv6Redirection::Print (std::ostream& os) const { os << "( type = " << (uint32_t)GetType () << " (Redirection) code = " << (uint32_t)GetCode () << " checksum = " << (uint32_t)GetChecksum () << " target = " << m_target << " destination = " << m_destination << ")"; } uint32_t Icmpv6Redirection::GetSerializedSize () const { return 40; } void Icmpv6Redirection::Serialize (Buffer::Iterator start) const { uint8_t buff[16]; uint16_t checksum = 0; Buffer::Iterator i = start; i.WriteU8 (GetType ()); i.WriteU8 (GetCode ()); i.WriteU16 (checksum); i.WriteU32 (m_reserved); m_target.Serialize (buff); i.Write (buff, 16); m_destination.Serialize (buff); i.Write (buff, 16); if (m_calcChecksum) { i = start; checksum = i.CalculateIpChecksum (i.GetSize (), GetChecksum ()); i = start; i.Next (2); i.WriteU16 (checksum); } } uint32_t Icmpv6Redirection::Deserialize (Buffer::Iterator start) { uint8_t buff[16]; Buffer::Iterator i = start; SetType (i.ReadU8 ()); SetCode (i.ReadU8 ()); m_checksum = i.ReadU16 (); SetReserved (i.ReadU32 ()); i.Read (buff, 16); m_target.Set (buff); i.Read (buff, 16); m_destination.Set (buff); return GetSerializedSize (); } NS_OBJECT_ENSURE_REGISTERED (Icmpv6Echo); TypeId Icmpv6Echo::GetTypeId () { static TypeId tid = TypeId ("ns3::Icmpv6Echo") .SetParent<Icmpv6Header> () .AddConstructor<Icmpv6Echo> () ; return tid; } TypeId Icmpv6Echo::GetInstanceTypeId () const { return GetTypeId (); } Icmpv6Echo::Icmpv6Echo () { SetType (Icmpv6Header::ICMPV6_ECHO_REQUEST); SetCode (0); m_checksum = 0; SetId (0); SetSeq (0); } Icmpv6Echo::Icmpv6Echo (bool request) { SetType (request ? Icmpv6Header::ICMPV6_ECHO_REQUEST : Icmpv6Header::ICMPV6_ECHO_REPLY); SetCode (0); m_checksum = 0; SetId (0); SetSeq (0); } Icmpv6Echo::~Icmpv6Echo () { } uint16_t Icmpv6Echo::GetId () const { return m_id; } void Icmpv6Echo::SetId (uint16_t id) { m_id = id; } uint16_t Icmpv6Echo::GetSeq () const { return m_seq; } void Icmpv6Echo::SetSeq (uint16_t seq) { m_seq = seq; } void Icmpv6Echo::Print (std::ostream& os) const { os << "( type = " << (GetType () == 128 ? "128 (Request)" : "129 (Reply)") << " code = " << (uint32_t)GetCode () << " checksum = " << (uint32_t)GetChecksum () << ")"; } uint32_t Icmpv6Echo::GetSerializedSize () const { return 8; } void Icmpv6Echo::Serialize (Buffer::Iterator start) const { uint16_t checksum = 0; Buffer::Iterator i = start; i.WriteU8 (GetType ()); i.WriteU8 (GetCode ()); i.WriteHtonU16 (0); i.WriteHtonU16 (m_id); i.WriteHtonU16 (m_seq); if (m_calcChecksum) { i = start; checksum = i.CalculateIpChecksum (i.GetSize (), GetChecksum ()); i = start; i.Next (2); i.WriteU16 (checksum); } } uint32_t Icmpv6Echo::Deserialize (Buffer::Iterator start) { Buffer::Iterator i = start; SetType (i.ReadU8 ()); SetCode (i.ReadU8 ()); m_checksum = i.ReadU16 (); m_id = i.ReadNtohU16 (); m_seq = i.ReadNtohU16 (); return GetSerializedSize (); } NS_OBJECT_ENSURE_REGISTERED (Icmpv6DestinationUnreachable); TypeId Icmpv6DestinationUnreachable::GetTypeId () { static TypeId tid = TypeId ("ns3::Icmpv6DestinationUnreachable") .SetParent<Icmpv6Header> () .AddConstructor<Icmpv6DestinationUnreachable> () ; return tid; } TypeId Icmpv6DestinationUnreachable::GetInstanceTypeId () const { return GetTypeId (); } Icmpv6DestinationUnreachable::Icmpv6DestinationUnreachable () : m_packet (0) { SetType (ICMPV6_ERROR_DESTINATION_UNREACHABLE); } Icmpv6DestinationUnreachable::~Icmpv6DestinationUnreachable () { } Ptr<Packet> Icmpv6DestinationUnreachable::GetPacket () const { return m_packet; } void Icmpv6DestinationUnreachable::SetPacket (Ptr<Packet> p) { NS_ASSERT (p->GetSize () <= 1280); m_packet = p; } void Icmpv6DestinationUnreachable::Print (std::ostream& os) const { os << "( type = " << (uint32_t)GetType () << " (Destination Unreachable) code = " << (uint32_t)GetCode () << " checksum = " << (uint32_t)GetChecksum () << ")"; } uint32_t Icmpv6DestinationUnreachable::GetSerializedSize () const { return 8 + m_packet->GetSize (); } void Icmpv6DestinationUnreachable::Serialize (Buffer::Iterator start) const { uint16_t checksum = 0; Buffer::Iterator i = start; i.WriteU8 (GetType ()); i.WriteU8 (GetCode ()); i.WriteHtonU16 (0); i.WriteHtonU32 (0); uint32_t size = m_packet->GetSize (); uint8_t *buf = new uint8_t[size]; m_packet->CopyData (buf, size); i.Write (buf, size); delete[] buf; i = start; checksum = i.CalculateIpChecksum (i.GetSize (), GetChecksum ()); i = start; i.Next (2); i.WriteU16 (checksum); } uint32_t Icmpv6DestinationUnreachable::Deserialize (Buffer::Iterator start) { uint16_t length = start.GetSize () - 8; uint8_t* data = new uint8_t[length]; Buffer::Iterator i = start; SetType (i.ReadU8 ()); SetCode (i.ReadU8 ()); m_checksum = i.ReadU16 (); i.ReadNtohU32 (); i.Read (data, length); m_packet = Create<Packet> (data, length); delete[] data; return GetSerializedSize (); } NS_OBJECT_ENSURE_REGISTERED (Icmpv6TooBig); TypeId Icmpv6TooBig::GetTypeId () { static TypeId tid = TypeId ("ns3::Icmpv6TooBig") .SetParent<Icmpv6Header> () .AddConstructor<Icmpv6TooBig> () ; return tid; } TypeId Icmpv6TooBig::GetInstanceTypeId () const { return GetTypeId (); } Icmpv6TooBig::Icmpv6TooBig () : m_packet (0), m_mtu (0) { SetType (ICMPV6_ERROR_PACKET_TOO_BIG); } Icmpv6TooBig::~Icmpv6TooBig () { } Ptr<Packet> Icmpv6TooBig::GetPacket () const { return m_packet; } void Icmpv6TooBig::SetPacket (Ptr<Packet> p) { NS_ASSERT (p->GetSize () <= 1280); m_packet = p; } uint32_t Icmpv6TooBig::GetMtu () const { return m_mtu; } void Icmpv6TooBig::SetMtu (uint32_t mtu) { m_mtu = mtu; } void Icmpv6TooBig::Print (std::ostream& os) const { os << "( type = " << (uint32_t)GetType () << " (Too Big) code = " << (uint32_t)GetCode () << " checksum = " << (uint32_t)GetChecksum () << " mtu = " << (uint32_t)GetMtu () << ")"; } uint32_t Icmpv6TooBig::GetSerializedSize () const { return 8 + m_packet->GetSize (); } void Icmpv6TooBig::Serialize (Buffer::Iterator start) const { uint16_t checksum = 0; Buffer::Iterator i = start; i.WriteU8 (GetType ()); i.WriteU8 (GetCode ()); i.WriteHtonU16 (0); i.WriteHtonU32 (GetMtu ()); uint32_t size = m_packet->GetSize (); uint8_t *buf = new uint8_t[size]; m_packet->CopyData (buf, size); i.Write (buf, size); delete[] buf; i = start; checksum = i.CalculateIpChecksum (i.GetSize (), GetChecksum ()); i = start; i.Next (2); i.WriteU16 (checksum); } uint32_t Icmpv6TooBig::Deserialize (Buffer::Iterator start) { uint16_t length = start.GetSize () - 8; uint8_t* data = new uint8_t[length]; Buffer::Iterator i = start; SetType (i.ReadU8 ()); SetCode (i.ReadU8 ()); m_checksum = i.ReadU16 (); SetMtu (i.ReadNtohU32 ()); i.Read (data, length); m_packet = Create<Packet> (data, length); delete[] data; return GetSerializedSize (); } NS_OBJECT_ENSURE_REGISTERED (Icmpv6TimeExceeded); TypeId Icmpv6TimeExceeded::GetTypeId () { static TypeId tid = TypeId ("ns3::Icmpv6TimeExceeded") .SetParent<Icmpv6Header> () .AddConstructor<Icmpv6TimeExceeded> () ; return tid; } TypeId Icmpv6TimeExceeded::GetInstanceTypeId () const { return GetTypeId (); } Icmpv6TimeExceeded::Icmpv6TimeExceeded () : m_packet (0) { SetType (ICMPV6_ERROR_TIME_EXCEEDED); } Icmpv6TimeExceeded::~Icmpv6TimeExceeded () { } Ptr<Packet> Icmpv6TimeExceeded::GetPacket () const { return m_packet; } void Icmpv6TimeExceeded::SetPacket (Ptr<Packet> p) { NS_ASSERT (p->GetSize () <= 1280); m_packet = p; } void Icmpv6TimeExceeded::Print (std::ostream& os) const { os << "( type = " << (uint32_t)GetType () << " (Destination Unreachable) code = " << (uint32_t)GetCode () << " checksum = " << (uint32_t)GetChecksum () << ")"; } uint32_t Icmpv6TimeExceeded::GetSerializedSize () const { return 8 + m_packet->GetSize (); } void Icmpv6TimeExceeded::Serialize (Buffer::Iterator start) const { uint16_t checksum = 0; Buffer::Iterator i = start; i.WriteU8 (GetType ()); i.WriteU8 (GetCode ()); i.WriteHtonU16 (0); i.WriteHtonU32 (0); uint32_t size = m_packet->GetSize (); uint8_t *buf = new uint8_t[size]; m_packet->CopyData (buf, size); i.Write (buf, size); delete[] buf; i = start; checksum = i.CalculateIpChecksum (i.GetSize (), GetChecksum ()); i = start; i.Next (2); i.WriteU16 (checksum); } uint32_t Icmpv6TimeExceeded::Deserialize (Buffer::Iterator start) { uint16_t length = start.GetSize () - 8; uint8_t* data = new uint8_t[length]; Buffer::Iterator i = start; SetType (i.ReadU8 ()); SetCode (i.ReadU8 ()); m_checksum = i.ReadU16 (); i.ReadNtohU32 (); i.Read (data, length); m_packet = Create<Packet> (data, length); delete[] data; return GetSerializedSize (); } NS_OBJECT_ENSURE_REGISTERED (Icmpv6ParameterError); TypeId Icmpv6ParameterError::GetTypeId () { static TypeId tid = TypeId ("ns3::Icmpv6ParameterError") .SetParent<Icmpv6Header> () .AddConstructor<Icmpv6ParameterError> () ; return tid; } TypeId Icmpv6ParameterError::GetInstanceTypeId () const { return GetTypeId (); } Icmpv6ParameterError::Icmpv6ParameterError () : m_packet (0), m_ptr (0) { SetType (ICMPV6_ERROR_PARAMETER_ERROR); } Icmpv6ParameterError::~Icmpv6ParameterError () { } Ptr<Packet> Icmpv6ParameterError::GetPacket () const { return m_packet; } void Icmpv6ParameterError::SetPacket (Ptr<Packet> p) { NS_ASSERT (p->GetSize () <= 1280); m_packet = p; } uint32_t Icmpv6ParameterError::GetPtr () const { return m_ptr; } void Icmpv6ParameterError::SetPtr (uint32_t ptr) { m_ptr = ptr; } void Icmpv6ParameterError::Print (std::ostream& os) const { os << "( type = " << (uint32_t)GetType () << " (Destination Unreachable) code = " << (uint32_t)GetCode () << " checksum = " << (uint32_t)GetChecksum () << " ptr = " << (uint32_t)GetPtr () << ")"; } uint32_t Icmpv6ParameterError::GetSerializedSize () const { return 8 + m_packet->GetSize (); } void Icmpv6ParameterError::Serialize (Buffer::Iterator start) const { uint16_t checksum = 0; Buffer::Iterator i = start; i.WriteU8 (GetType ()); i.WriteU8 (GetCode ()); i.WriteHtonU16 (0); i.WriteHtonU32 (GetPtr ()); uint32_t size = m_packet->GetSize (); uint8_t *buf = new uint8_t[size]; m_packet->CopyData (buf, size); i.Write (buf, size); delete[] buf; i = start; checksum = i.CalculateIpChecksum (i.GetSize (), GetChecksum ()); i = start; i.Next (2); i.WriteU16 (checksum); } uint32_t Icmpv6ParameterError::Deserialize (Buffer::Iterator start) { uint16_t length = start.GetSize () - 8; uint8_t* data = new uint8_t[length]; Buffer::Iterator i = start; SetType (i.ReadU8 ()); SetCode (i.ReadU8 ()); m_checksum = i.ReadU16 (); SetPtr (i.ReadNtohU32 ()); i.Read (data, length); m_packet = Create<Packet> (data, length); delete[] data; return GetSerializedSize (); } NS_OBJECT_ENSURE_REGISTERED (Icmpv6OptionHeader); TypeId Icmpv6OptionHeader::GetTypeId () { static TypeId tid = TypeId ("ns3::Icmpv6OptionHeader") .SetParent<Header> () .AddConstructor<Icmpv6OptionHeader> () ; return tid; } TypeId Icmpv6OptionHeader::GetInstanceTypeId () const { return GetTypeId (); } Icmpv6OptionHeader::Icmpv6OptionHeader () { /* TODO */ m_type = 0; m_len = 0; } Icmpv6OptionHeader::~Icmpv6OptionHeader () { } uint8_t Icmpv6OptionHeader::GetType () const { NS_LOG_FUNCTION_NOARGS (); return m_type; } void Icmpv6OptionHeader::SetType (uint8_t type) { NS_LOG_FUNCTION_NOARGS (); m_type = type; } uint8_t Icmpv6OptionHeader::GetLength () const { NS_LOG_FUNCTION_NOARGS (); return m_len; } void Icmpv6OptionHeader::SetLength (uint8_t len) { NS_LOG_FUNCTION_NOARGS (); m_len = len; } void Icmpv6OptionHeader::Print (std::ostream& os) const { os << "( type = " << (uint32_t)GetType () << " length = " << (uint32_t)GetLength () << ")"; } uint32_t Icmpv6OptionHeader::GetSerializedSize () const { return m_len*8; } uint32_t Icmpv6OptionHeader::Deserialize (Buffer::Iterator start) { return GetSerializedSize (); } void Icmpv6OptionHeader::Serialize (Buffer::Iterator start) const { } NS_OBJECT_ENSURE_REGISTERED (Icmpv6OptionMtu); TypeId Icmpv6OptionMtu::GetTypeId () { static TypeId tid = TypeId ("ns3::Icmpv6OptionMtu") .SetParent<Icmpv6OptionHeader> () .AddConstructor<Icmpv6OptionMtu> () ; return tid; } TypeId Icmpv6OptionMtu::GetInstanceTypeId () const { return GetTypeId (); } Icmpv6OptionMtu::Icmpv6OptionMtu () { SetType (Icmpv6Header::ICMPV6_OPT_MTU); SetLength (1); SetReserved (0); } Icmpv6OptionMtu::Icmpv6OptionMtu (uint32_t mtu) : m_mtu (mtu) { SetType (Icmpv6Header::ICMPV6_OPT_MTU); SetLength (1); SetReserved (0); } Icmpv6OptionMtu::~Icmpv6OptionMtu () { } uint16_t Icmpv6OptionMtu::GetReserved () const { return m_reserved; } void Icmpv6OptionMtu::SetReserved (uint16_t reserved) { m_reserved = reserved; } uint32_t Icmpv6OptionMtu::GetMtu () const { return m_mtu; } void Icmpv6OptionMtu::SetMtu (uint32_t mtu) { m_mtu = mtu; } void Icmpv6OptionMtu::Print (std::ostream& os) const { os << "( type = " << (uint32_t)GetType () << " length = " << (uint32_t)GetLength () << " MTU = " << m_mtu << ")"; } uint32_t Icmpv6OptionMtu::GetSerializedSize () const { return 8; /* m_len = 1 so the real size is multiple by 8 */ } void Icmpv6OptionMtu::Serialize (Buffer::Iterator start) const { Buffer::Iterator i = start; i.WriteU8 (GetType ()); i.WriteU8 (GetLength ()); i.WriteHtonU16 (GetReserved ()); i.WriteHtonU32 (GetMtu ()); } uint32_t Icmpv6OptionMtu::Deserialize (Buffer::Iterator start) { Buffer::Iterator i = start; SetType (i.ReadU8 ()); SetLength (i.ReadU8 ()); SetReserved (i.ReadNtohU16 ()); SetMtu (i.ReadNtohU32 ()); return GetSerializedSize (); } NS_OBJECT_ENSURE_REGISTERED (Icmpv6OptionPrefixInformation); TypeId Icmpv6OptionPrefixInformation::GetTypeId () { static TypeId tid = TypeId ("ns3::Icmpv6OptionPrefixInformation") .SetParent<Icmpv6OptionHeader> () .AddConstructor<Icmpv6OptionPrefixInformation> () ; return tid; } TypeId Icmpv6OptionPrefixInformation::GetInstanceTypeId () const { return GetTypeId (); } Icmpv6OptionPrefixInformation::Icmpv6OptionPrefixInformation () { SetType (Icmpv6Header::ICMPV6_OPT_PREFIX); SetLength (4); SetPrefix (Ipv6Address ("::")); SetPrefixLength (0); SetValidTime (0); SetPreferredTime (0); SetFlags (0); SetReserved (0); } Icmpv6OptionPrefixInformation::Icmpv6OptionPrefixInformation (Ipv6Address prefix, uint8_t prefixlen) { SetType (Icmpv6Header::ICMPV6_OPT_PREFIX); SetLength (4); SetPrefix (prefix); SetPrefixLength (prefixlen); SetValidTime (0); SetPreferredTime (0); SetFlags (0); SetReserved (0); } Icmpv6OptionPrefixInformation::~Icmpv6OptionPrefixInformation () { } uint8_t Icmpv6OptionPrefixInformation::GetPrefixLength () const { return m_prefixLength; } void Icmpv6OptionPrefixInformation::SetPrefixLength (uint8_t prefixLength) { NS_ASSERT (prefixLength <= 128); m_prefixLength = prefixLength; } uint8_t Icmpv6OptionPrefixInformation::GetFlags () const { return m_flags; } void Icmpv6OptionPrefixInformation::SetFlags (uint8_t flags) { m_flags = flags; } uint32_t Icmpv6OptionPrefixInformation::GetValidTime () const { return m_validTime; } void Icmpv6OptionPrefixInformation::SetValidTime (uint32_t validTime) { m_validTime = validTime; } uint32_t Icmpv6OptionPrefixInformation::GetPreferredTime () const { return m_preferredTime; } void Icmpv6OptionPrefixInformation::SetPreferredTime (uint32_t preferredTime) { m_preferredTime = preferredTime; } uint32_t Icmpv6OptionPrefixInformation::GetReserved () const { return m_preferredTime; } void Icmpv6OptionPrefixInformation::SetReserved (uint32_t reserved) { m_reserved = reserved; } Ipv6Address Icmpv6OptionPrefixInformation::GetPrefix () const { return m_prefix; } void Icmpv6OptionPrefixInformation::SetPrefix (Ipv6Address prefix) { m_prefix = prefix; } void Icmpv6OptionPrefixInformation::Print (std::ostream& os) const { os << "( type = " << (uint32_t)GetType () << " length = " << (uint32_t)GetLength () << " prefix " << m_prefix << ")"; } uint32_t Icmpv6OptionPrefixInformation::GetSerializedSize () const { return 32; } void Icmpv6OptionPrefixInformation::Serialize (Buffer::Iterator start) const { Buffer::Iterator i = start; uint8_t buf[16]; memset (buf, 0x00, sizeof (buf)); i.WriteU8 (GetType ()); i.WriteU8 (GetLength ()); i.WriteU8 (m_prefixLength); i.WriteU8 (m_flags); i.WriteHtonU32 (m_validTime); i.WriteHtonU32 (m_preferredTime); i.WriteHtonU32 (m_reserved); m_prefix.GetBytes (buf); i.Write (buf, 16); } uint32_t Icmpv6OptionPrefixInformation::Deserialize (Buffer::Iterator start) { Buffer::Iterator i = start; uint8_t buf[16]; SetType (i.ReadU8 ()); SetLength (i.ReadU8 ()); SetPrefixLength (i.ReadU8 ()); SetFlags (i.ReadU8 ()); SetValidTime (i.ReadNtohU32 ()); SetPreferredTime (i.ReadNtohU32 ()); SetReserved (i.ReadNtohU32 ()); i.Read (buf, 16); Ipv6Address prefix (buf); SetPrefix (prefix); return GetSerializedSize (); } NS_OBJECT_ENSURE_REGISTERED (Icmpv6OptionLinkLayerAddress); TypeId Icmpv6OptionLinkLayerAddress::GetTypeId () { static TypeId tid = TypeId ("ns3::Icmpv6OptionLinkLayerAddress") .SetParent<Icmpv6OptionHeader> () .AddConstructor<Icmpv6OptionLinkLayerAddress> () ; return tid; } TypeId Icmpv6OptionLinkLayerAddress::GetInstanceTypeId () const { return GetTypeId (); } Icmpv6OptionLinkLayerAddress::Icmpv6OptionLinkLayerAddress (bool source) { SetType (source ? Icmpv6Header::ICMPV6_OPT_LINK_LAYER_SOURCE : Icmpv6Header::ICMPV6_OPT_LINK_LAYER_TARGET); } Icmpv6OptionLinkLayerAddress::Icmpv6OptionLinkLayerAddress () { SetType (Icmpv6Header::ICMPV6_OPT_LINK_LAYER_SOURCE); } Icmpv6OptionLinkLayerAddress::Icmpv6OptionLinkLayerAddress (bool source, Address addr) { SetType (source ? Icmpv6Header::ICMPV6_OPT_LINK_LAYER_SOURCE : Icmpv6Header::ICMPV6_OPT_LINK_LAYER_TARGET); SetAddress (addr); SetLength (GetSerializedSize () / 8); } Icmpv6OptionLinkLayerAddress::~Icmpv6OptionLinkLayerAddress () { } Address Icmpv6OptionLinkLayerAddress::GetAddress () const { return m_addr; } void Icmpv6OptionLinkLayerAddress::SetAddress (Address addr) { m_addr = addr; } void Icmpv6OptionLinkLayerAddress::Print (std::ostream& os) const { os << "( type = " << (uint32_t)GetType () << " length = " << (uint32_t)GetLength () << " L2 Address = " << m_addr << ")"; } uint32_t Icmpv6OptionLinkLayerAddress::GetSerializedSize () const { /* TODO add padding */ uint8_t nb = 2 + m_addr.GetLength (); return nb; } void Icmpv6OptionLinkLayerAddress::Serialize (Buffer::Iterator start) const { NS_LOG_FUNCTION_NOARGS (); Buffer::Iterator i = start; uint8_t mac[32]; i.WriteU8 (GetType ()); i.WriteU8 (GetLength ()); m_addr.CopyTo (mac); i.Write (mac, m_addr.GetLength ()); /* XXX if size of the option is not a multiple of 8, add padding */ } uint32_t Icmpv6OptionLinkLayerAddress::Deserialize (Buffer::Iterator start) { Buffer::Iterator i = start; uint8_t mac[32]; SetType (i.ReadU8 ()); SetLength (i.ReadU8 ()); i.Read (mac, (GetLength () * 8) - 2); m_addr.CopyFrom (mac, (GetLength () * 8)-2); return GetSerializedSize (); } NS_OBJECT_ENSURE_REGISTERED (Icmpv6OptionRedirected); TypeId Icmpv6OptionRedirected::GetTypeId () { static TypeId tid = TypeId ("ns3::Icmpv6OptionRedirected") .SetParent<Icmpv6OptionHeader> () .AddConstructor<Icmpv6OptionRedirected> () ; return tid; } TypeId Icmpv6OptionRedirected::GetInstanceTypeId () const { return GetTypeId (); } Icmpv6OptionRedirected::Icmpv6OptionRedirected () : m_packet (0) { SetType (Icmpv6Header::ICMPV6_OPT_REDIRECTED); } Icmpv6OptionRedirected::~Icmpv6OptionRedirected () { m_packet = 0; } Ptr<Packet> Icmpv6OptionRedirected::GetPacket () const { return m_packet; } void Icmpv6OptionRedirected::SetPacket (Ptr<Packet> packet) { NS_ASSERT (packet->GetSize () <= 1280); m_packet = packet; SetLength (1 + (m_packet->GetSize () / 8)); } void Icmpv6OptionRedirected::Print (std::ostream& os) const { os << "( type = " << (uint32_t)GetType () << " length = " << (uint32_t)GetLength () << ")"; } uint32_t Icmpv6OptionRedirected::GetSerializedSize () const { return 8 + m_packet->GetSize (); } void Icmpv6OptionRedirected::Serialize (Buffer::Iterator start) const { NS_LOG_FUNCTION_NOARGS (); Buffer::Iterator i = start; i.WriteU8 (GetType ()); i.WriteU8 (GetLength ()); // Reserved i.WriteU16 (0); i.WriteU32 (0); uint32_t size = m_packet->GetSize (); uint8_t *buf = new uint8_t[size]; m_packet->CopyData (buf, size); i.Write (buf, size); delete[] buf; } uint32_t Icmpv6OptionRedirected::Deserialize (Buffer::Iterator start) { Buffer::Iterator i = start; SetType (i.ReadU8 ()); uint8_t length = i.ReadU8 (); SetLength (length); i.ReadU16 (); i.ReadU32 (); uint32_t len2 = (GetLength () - 1) * 8; uint8_t* buff = new uint8_t[len2]; i.Read (buff, len2); m_packet = Create<Packet> (buff, len2); delete[] buff; return GetSerializedSize (); } } /* namespace ns3 */
zy901002-gpsr
src/internet/model/icmpv6-header.cc
C++
gpl2
35,420
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2010 Hajime Tazaki * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Authors: Hajime Tazaki <tazaki@sfc.wide.ad.jp> */ #ifndef IPV4_PACKET_INFO_TAG_H #define IPV4_PACKET_INFO_TAG_H #include "ns3/tag.h" #include "ns3/ipv4-address.h" namespace ns3 { class Node; class Packet; /** * \brief This class implements Linux struct pktinfo * in order to deliver ancillary information to the socket interface. * This is used with socket option such as IP_PKTINFO, IP_RECVTTL, * IP_RECVTOS. See linux manpage ip(7). * * This tag in the send direction is presently not enabled but we * would accept a patch along those lines in the future. */ class Ipv4PacketInfoTag : public Tag { public: Ipv4PacketInfoTag (); // Implemented, but not used in the stack yet void SetAddress (Ipv4Address addr); // Implemented, but not used in the stack yet Ipv4Address GetAddress (void) const; // This corresponds to "ipi_spec_dst" in struct in_pktinfo. // Implemented, but not used in the stack yet void SetLocalAddress (Ipv4Address addr); // This corresponds to "ipi_spec_dst" in struct in_pktinfo. // Implemented, but not used in the stack yet Ipv4Address GetLocalAddress (void) const; void SetRecvIf (uint32_t ifindex); uint32_t GetRecvIf (void) const; // Implemented, but not used in the stack yet void SetTtl (uint8_t ttl); // Implemented, but not used in the stack yet uint8_t GetTtl (void) const; static TypeId GetTypeId (void); virtual TypeId GetInstanceTypeId (void) const; virtual uint32_t GetSerializedSize (void) const; virtual void Serialize (TagBuffer i) const; virtual void Deserialize (TagBuffer i); virtual void Print (std::ostream &os) const; private: // Linux IP_PKTINFO ip(7) implementation // // struct in_pktinfo { // unsigned int ipi_ifindex; /* Interface index */ // struct in_addr ipi_spec_dst; /* Local address */ // struct in_addr ipi_addr; /* Header Destination // address */ // }; Ipv4Address m_addr; Ipv4Address m_spec_dst; uint32_t m_ifindex; // Uset for IP_RECVTTL, though not implemented yet. uint8_t m_ttl; }; } // namespace ns3 #endif /* IPV4_PACKET_INFO_TAG_H */
zy901002-gpsr
src/internet/model/ipv4-packet-info-tag.h
C++
gpl2
2,905
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007-2009 Strasbourg University * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: David Gross <gdavid.devel@gmail.com> */ #include "ns3/log.h" #include "ns3/assert.h" #include "ns3/uinteger.h" #include "ipv6-option.h" #include "ipv6-option-header.h" NS_LOG_COMPONENT_DEFINE ("Ipv6Option"); namespace ns3 { NS_OBJECT_ENSURE_REGISTERED (Ipv6Option); TypeId Ipv6Option::GetTypeId () { static TypeId tid = TypeId ("ns3::Ipv6Option") .SetParent<Object> () .AddAttribute ("OptionNumber", "The IPv6 option number.", UintegerValue (0), MakeUintegerAccessor (&Ipv6Option::GetOptionNumber), MakeUintegerChecker<uint8_t> ()) ; return tid; } Ipv6Option::~Ipv6Option () { NS_LOG_FUNCTION_NOARGS (); } void Ipv6Option::SetNode (Ptr<Node> node) { NS_LOG_FUNCTION (this << node); m_node = node; } NS_OBJECT_ENSURE_REGISTERED (Ipv6OptionPad1); TypeId Ipv6OptionPad1::GetTypeId () { static TypeId tid = TypeId ("ns3::Ipv6OptionPad1") .SetParent<Ipv6Option> () .AddConstructor<Ipv6OptionPad1> () ; return tid; } Ipv6OptionPad1::Ipv6OptionPad1 () { NS_LOG_FUNCTION_NOARGS (); } Ipv6OptionPad1::~Ipv6OptionPad1 () { NS_LOG_FUNCTION_NOARGS (); } uint8_t Ipv6OptionPad1::GetOptionNumber () const { NS_LOG_FUNCTION_NOARGS (); return OPT_NUMBER; } uint8_t Ipv6OptionPad1::Process (Ptr<Packet> packet, uint8_t offset, Ipv6Header const& ipv6Header, bool& isDropped) { NS_LOG_FUNCTION (this << packet << offset << ipv6Header << isDropped); Ptr<Packet> p = packet->Copy (); p->RemoveAtStart (offset); Ipv6OptionPad1Header pad1Header; p->RemoveHeader (pad1Header); isDropped = false; return pad1Header.GetSerializedSize (); } NS_OBJECT_ENSURE_REGISTERED (Ipv6OptionPadn); TypeId Ipv6OptionPadn::GetTypeId () { static TypeId tid = TypeId ("ns3::Ipv6OptionPadn") .SetParent<Ipv6Option> () .AddConstructor<Ipv6OptionPadn> () ; return tid; } Ipv6OptionPadn::Ipv6OptionPadn () { NS_LOG_FUNCTION_NOARGS (); } Ipv6OptionPadn::~Ipv6OptionPadn () { NS_LOG_FUNCTION_NOARGS (); } uint8_t Ipv6OptionPadn::GetOptionNumber () const { NS_LOG_FUNCTION_NOARGS (); return OPT_NUMBER; } uint8_t Ipv6OptionPadn::Process (Ptr<Packet> packet, uint8_t offset, Ipv6Header const& ipv6Header, bool& isDropped) { NS_LOG_FUNCTION (this << packet << offset << ipv6Header << isDropped); Ptr<Packet> p = packet->Copy (); p->RemoveAtStart (offset); Ipv6OptionPadnHeader padnHeader; p->RemoveHeader (padnHeader); isDropped = false; return padnHeader.GetSerializedSize (); } NS_OBJECT_ENSURE_REGISTERED (Ipv6OptionJumbogram); TypeId Ipv6OptionJumbogram::GetTypeId () { static TypeId tid = TypeId ("ns3::Ipv6OptionJumbogram") .SetParent<Ipv6Option> () .AddConstructor<Ipv6OptionJumbogram> () ; return tid; } Ipv6OptionJumbogram::Ipv6OptionJumbogram () { NS_LOG_FUNCTION_NOARGS (); } Ipv6OptionJumbogram::~Ipv6OptionJumbogram () { NS_LOG_FUNCTION_NOARGS (); } uint8_t Ipv6OptionJumbogram::GetOptionNumber () const { NS_LOG_FUNCTION_NOARGS (); return OPT_NUMBER; } uint8_t Ipv6OptionJumbogram::Process (Ptr<Packet> packet, uint8_t offset, Ipv6Header const& ipv6Header, bool& isDropped) { NS_LOG_FUNCTION (this << packet << offset << ipv6Header << isDropped); Ptr<Packet> p = packet->Copy (); p->RemoveAtStart (offset); Ipv6OptionJumbogramHeader jumbogramHeader; p->RemoveHeader (jumbogramHeader); isDropped = false; return jumbogramHeader.GetSerializedSize (); } NS_OBJECT_ENSURE_REGISTERED (Ipv6OptionRouterAlert); TypeId Ipv6OptionRouterAlert::GetTypeId () { static TypeId tid = TypeId ("ns3::Ipv6OptionRouterAlert") .SetParent<Ipv6Option> () .AddConstructor<Ipv6OptionRouterAlert> () ; return tid; } Ipv6OptionRouterAlert::Ipv6OptionRouterAlert () { NS_LOG_FUNCTION_NOARGS (); } Ipv6OptionRouterAlert::~Ipv6OptionRouterAlert () { NS_LOG_FUNCTION_NOARGS (); } uint8_t Ipv6OptionRouterAlert::GetOptionNumber () const { NS_LOG_FUNCTION_NOARGS (); return OPT_NUMBER; } uint8_t Ipv6OptionRouterAlert::Process (Ptr<Packet> packet, uint8_t offset, Ipv6Header const& ipv6Header, bool& isDropped) { NS_LOG_FUNCTION (this << packet << offset << ipv6Header << isDropped); Ptr<Packet> p = packet->Copy (); p->RemoveAtStart (offset); Ipv6OptionRouterAlertHeader routerAlertHeader; p->RemoveHeader (routerAlertHeader); isDropped = false; return routerAlertHeader.GetSerializedSize (); } } /* namespace ns3 */
zy901002-gpsr
src/internet/model/ipv6-option.cc
C++
gpl2
5,211
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright 2007 University of Washington * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Craig Dowell (craigdo@ee.washington.edu) */ #ifndef CANDIDATE_QUEUE_H #define CANDIDATE_QUEUE_H #include <stdint.h> #include <list> #include "ns3/ipv4-address.h" namespace ns3 { class SPFVertex; /** * \brief A Candidate Queue used in static routing. * * The CandidateQueue is used in the OSPF shortest path computations. It * is a priority queue used to store candidates for the shortest path to a * given network. * * The queue holds Shortest Path First Vertex pointers and orders them * according to the lowest value of the field m_distanceFromRoot. Remaining * vertices are ordered according to increasing distance. This implements a * priority queue. * * Although a STL priority_queue almost does what we want, the requirement * for a Find () operation, the dynamic nature of the data and the derived * requirement for a Reorder () operation led us to implement this simple * enhanced priority queue. */ class CandidateQueue { public: /** * @brief Create an empty SPF Candidate Queue. * @internal * * @see SPFVertex */ CandidateQueue (); /** * @internal Destroy an SPF Candidate Queue and release any resources held * by the contents. * @internal * * @see SPFVertex */ virtual ~CandidateQueue (); /** * @brief Empty the Candidate Queue and release all of the resources * associated with the Shortest Path First Vertex pointers in the queue. * @internal * * @see SPFVertex */ void Clear (void); /** * @brief Push a Shortest Path First Vertex pointer onto the queue according * to the priority scheme. * @internal * * On completion, the top of the queue will hold the Shortest Path First * Vertex pointer that points to a vertex having lowest value of the field * m_distanceFromRoot. Remaining vertices are ordered according to * increasing distance. * * @see SPFVertex * @param vNew The Shortest Path First Vertex to add to the queue. */ void Push (SPFVertex *vNew); /** * @brief Pop the Shortest Path First Vertex pointer at the top of the queue. * @internal * * The caller is given the responsibility for releasing the resources * associated with the vertex. * * @see SPFVertex * @see Top () * @returns The Shortest Path First Vertex pointer at the top of the queue. */ SPFVertex* Pop (void); /** * @brief Return the Shortest Path First Vertex pointer at the top of the * queue. * @internal * * This method does not pop the SPFVertex* off of the queue, it simply * returns the pointer. * * @see SPFVertex * @see Pop () * @returns The Shortest Path First Vertex pointer at the top of the queue. */ SPFVertex* Top (void) const; /** * @brief Test the Candidate Queue to determine if it is empty. * @internal * * @returns True if the queue is empty, false otherwise. */ bool Empty (void) const; /** * @brief Return the number of Shortest Path First Vertex pointers presently * stored in the Candidate Queue. * @internal * * @see SPFVertex * @returns The number of SPFVertex* pointers in the Candidate Queue. */ uint32_t Size (void) const; /** * @brief Searches the Candidate Queue for a Shortest Path First Vertex * pointer that points to a vertex having the given IP address. * @internal * * @see SPFVertex * @param addr The IP address to search for. * @returns The SPFVertex* pointer corresponding to the given IP address. */ SPFVertex* Find (const Ipv4Address addr) const; /** * @brief Reorders the Candidate Queue according to the priority scheme. * @internal * * On completion, the top of the queue will hold the Shortest Path First * Vertex pointer that points to a vertex having lowest value of the field * m_distanceFromRoot. Remaining vertices are ordered according to * increasing distance. * * This method is provided in case the values of m_distanceFromRoot change * during the routing calculations. * * @see SPFVertex */ void Reorder (void); private: /** * Candidate Queue copy construction is disallowed (not implemented) to * prevent the compiler from slipping in incorrect versions that don't * properly deal with deep copies. * \param sr object to copy */ CandidateQueue (CandidateQueue& sr); /** * Candidate Queue assignment operator is disallowed (not implemented) to * prevent the compiler from slipping in incorrect versions that don't * properly deal with deep copies. * \param sr object to assign */ CandidateQueue& operator= (CandidateQueue& sr); /** * \brief return true if v1 < v2 * * SPFVertexes are added into the queue according to the ordering * defined by this method. If v1 should be popped before v2, this * method return true; false otherwise * * \return True if v1 should be popped before v2; false otherwise */ static bool CompareSPFVertex (const SPFVertex* v1, const SPFVertex* v2); typedef std::list<SPFVertex*> CandidateList_t; CandidateList_t m_candidates; friend std::ostream& operator<< (std::ostream& os, const CandidateQueue& q); }; } // namespace ns3 #endif /* CANDIDATE_QUEUE_H */
zy901002-gpsr
src/internet/model/candidate-queue.h
C++
gpl2
5,795
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007-2009 Strasbourg University * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Sebastien Vincent <vincent@clarinet.u-strasbg.fr> */ #ifndef IPV6_L3_PROTOCOL_H #define IPV6_L3_PROTOCOL_H #include <list> #include "ns3/traced-callback.h" #include "ns3/net-device.h" #include "ns3/ipv6.h" #include "ns3/ipv6-address.h" #include "ns3/ipv6-header.h" namespace ns3 { class Node; class Ipv6Interface; class Ipv6L4Protocol; class Ipv6Route; class Ipv6MulticastRoute; class Ipv6RawSocketImpl; class Icmpv6L4Protocol; class Ipv6AutoconfiguredPrefix; /** * \class Ipv6L3Protocol * \brief IPv6 layer implementation. * * This class contains two distinct groups of trace sources. The * trace sources 'Rx' and 'Tx' are called, respectively, immediately * after receiving from the NetDevice and immediately before sending * to a NetDevice for transmitting a packet. These are low level * trace sources that include the Ipv6Header already serialized into * the packet. In contrast, the Drop, SendOutgoing, UnicastForward, * and LocalDeliver trace sources are slightly higher-level and pass * around the Ipv6Header as an explicit parameter and not as part of * the packet. */ class Ipv6L3Protocol : public Ipv6 { public: /** * \brief Get the type ID of this class. * \return type ID */ static TypeId GetTypeId (); /** * \brief The protocol number for IPv6 (0x86DD). */ static const uint16_t PROT_NUMBER; /** * \enum DropReason * \brief Reason why a packet has been dropped. */ enum DropReason { DROP_TTL_EXPIRED = 1, /**< Packet TTL has expired */ DROP_NO_ROUTE, /**< No route to host */ DROP_INTERFACE_DOWN, /**< Interface is down so can not send packet */ DROP_ROUTE_ERROR, /**< Route error */ DROP_UNKNOWN_PROTOCOL, /**< Unknown L4 protocol */ }; /** * \brief Constructor. */ Ipv6L3Protocol (); /** * \brief Destructor. */ virtual ~Ipv6L3Protocol (); /** * \brief Set node for this stack. * \param node node to set */ void SetNode (Ptr<Node> node); /** * \brief Add an L4 protocol. * \param protocol L4 protocol */ void Insert (Ptr<Ipv6L4Protocol> protocol); /** * \brief Remove an L4 protocol. * \param protocol L4 protocol to remove */ void Remove (Ptr<Ipv6L4Protocol> protocol); /** * \brief Get L4 protocol by protocol number. * \param protocolNumber protocol number * \return corresponding Ipv6L4Protocol or 0 if not found */ Ptr<Ipv6L4Protocol> GetProtocol (int protocolNumber) const; /** * \brief Create raw IPv6 socket. * \return newly raw socket */ Ptr<Socket> CreateRawSocket (); /** * \brief Remove raw IPv6 socket. * \param socket socket to remove */ void DeleteRawSocket (Ptr<Socket> socket); /** * \brief Set the default TTL. * \param ttl TTL to set */ void SetDefaultTtl (uint8_t ttl); /** * \brief Receive method when a packet arrive in the stack. * This method removes IPv6 header and forward up to L4 protocol. * * \param device network device * \param p the packet * \param protocol next header value * \param from address of the correspondant * \param to address of the destination * \param packetType type of the packet */ void Receive (Ptr<NetDevice> device, Ptr<const Packet> p, uint16_t protocol, const Address &from, const Address &to, NetDevice::PacketType packetType); /** * \brief Higher-level layers call this method to send a packet * down the stack to the MAC and PHY layers. * * \param packet packet to send * \param source source address of packet * \param destination address of packet * \param protocol number of packet * \param route route to take */ void Send (Ptr<Packet> packet, Ipv6Address source, Ipv6Address destination, uint8_t protocol, Ptr<Ipv6Route> route); /** * \brief Set routing protocol for this stack. * \param routingProtocol IPv6 routing protocol to set */ void SetRoutingProtocol (Ptr<Ipv6RoutingProtocol> routingProtocol); /** * \brief Get current routing protocol used. * \return routing protocol */ Ptr<Ipv6RoutingProtocol> GetRoutingProtocol () const; /** * \brief Add IPv6 interface for a device. * \param device net device * \return interface index */ uint32_t AddInterface (Ptr<NetDevice> device); /** * \brief Get an interface. * \param i interface index * \return IPv6 interface pointer */ Ptr<Ipv6Interface> GetInterface (uint32_t i) const; /** * \brief Get current number of interface on this stack. * \return number of interface registered */ uint32_t GetNInterfaces () const; /** * \brief Get interface index which has specified IPv6 address * \param addr IPv6 address * \return interface index or -1 if not found */ int32_t GetInterfaceForAddress (Ipv6Address addr) const; /** * \brief Get interface index which match specified address/prefix. * \param addr IPv6 address * \param mask IPv6 prefix (mask) * \return interface index or -1 if not found */ int32_t GetInterfaceForPrefix (Ipv6Address addr, Ipv6Prefix mask) const; /** * \brief Get interface index which is on a specified net device. * \param device net device */ int32_t GetInterfaceForDevice (Ptr<const NetDevice> device) const; /** * \brief Add an address on interface. * \param i interface index * \param address to add */ bool AddAddress (uint32_t i, Ipv6InterfaceAddress address); /** * \brief Get an address. * \param interfaceIndex interface index * \param addressIndex address index on the interface * \return Ipv6InterfaceAddress or assert if not found */ Ipv6InterfaceAddress GetAddress (uint32_t interfaceIndex, uint32_t addressIndex) const; /** * \brief Get number of address for an interface. * \param interface interface index * \return number of address */ uint32_t GetNAddresses (uint32_t interface) const; /** * \brief Remove an address from an interface. * \param interfaceIndex interface index * \param addressIndex address index on the interface */ bool RemoveAddress (uint32_t interfaceIndex, uint32_t addressIndex); /** * \brief Set metric for an interface. * \param i index * \param metric */ void SetMetric (uint32_t i, uint16_t metric); /** * \brief Get metric for an interface. * \param i index * \return metric */ uint16_t GetMetric (uint32_t i) const; /** * \brief Get MTU for an interface. * \param i index * \return MTU */ uint16_t GetMtu (uint32_t i) const; /** * \brief Is specified interface up ? * \param i interface index */ bool IsUp (uint32_t i) const; /** * \brief Set an interface up. * \param i interface index */ void SetUp (uint32_t i); /** * \brief set an interface down. * \param i interface index */ void SetDown (uint32_t i); /** * \brief Is interface allows forwarding ? * \param i interface index */ bool IsForwarding (uint32_t i) const; /** * \brief Enable or disable forwarding on interface * \param i interface index * \param val true = enable forwarding, false = disable */ void SetForwarding (uint32_t i, bool val); /** * \brief Get device by index. * \param i device index on this stack * \return NetDevice pointer */ Ptr<NetDevice> GetNetDevice (uint32_t i); /** * \brief Get ICMPv6 protocol. * \return Icmpv6L4Protocol pointer */ Ptr<Icmpv6L4Protocol> GetIcmpv6 () const; /** * \brief Add an autoconfigured address with RA information. * \param interface interface index * \param network network prefix * \param mask network mask * \param flags flags of the prefix information option (home agent, ...) * \param validTime valid time of the prefix * \param preferredTime preferred time of the prefix * \param defaultRouter default router address */ void AddAutoconfiguredAddress (uint32_t interface, Ipv6Address network, Ipv6Prefix mask, uint8_t flags, uint32_t validTime, uint32_t preferredTime, Ipv6Address defaultRouter = Ipv6Address::GetZero ()); /** * \brief Remove an autoconfigured address. * * Typically it is used when an autoconfigured address expires. * \param interface interface index * \param network network prefix * \param mask network mask * \param defaultRouter gateway */ void RemoveAutoconfiguredAddress (uint32_t interface, Ipv6Address network, Ipv6Prefix mask, Ipv6Address defaultRouter); /** * \brief Register the IPv6 Extensions. */ virtual void RegisterExtensions (); /** * \brief Register the IPv6 Options. */ virtual void RegisterOptions (); protected: /** * \brief Dispose object. */ virtual void DoDispose (); /** * \brief Notify other components connected to the node that a new stack member is now connected. * * This will be used to notify Layer 3 protocol of layer 4 protocol stack to connect them together. */ virtual void NotifyNewAggregate (); private: /* for unit-tests */ friend class Ipv6L3ProtocolTestCase; friend class Ipv6ExtensionLooseRouting; typedef std::list<Ptr<Ipv6Interface> > Ipv6InterfaceList; typedef std::list<Ptr<Ipv6RawSocketImpl> > SocketList; typedef std::list<Ptr<Ipv6L4Protocol> > L4List_t; typedef std::list< Ptr<Ipv6AutoconfiguredPrefix> > Ipv6AutoconfiguredPrefixList; typedef std::list< Ptr<Ipv6AutoconfiguredPrefix> >::iterator Ipv6AutoconfiguredPrefixListI; /** * \brief Callback to trace TX (transmission) packets. */ TracedCallback<Ptr<const Packet>, Ptr<Ipv6>, uint32_t> m_txTrace; /** * \brief Callback to trace RX (reception) packets. */ TracedCallback<Ptr<const Packet>, Ptr<Ipv6>, uint32_t> m_rxTrace; /** * \brief Callback to trace drop packets. */ TracedCallback<const Ipv6Header &, Ptr<const Packet>, DropReason, Ptr<Ipv6>, uint32_t> m_dropTrace; /** * \brief Copy constructor. * \param o object to copy */ Ipv6L3Protocol (const Ipv6L3Protocol& o); /** * \brief Copy constructor. * \param o object to copy */ Ipv6L3Protocol &operator = (const Ipv6L3Protocol& o); /** * \brief Construct an IPv6 header. * \param src source IPv6 address * \param dst destination IPv6 address * \param protocol L4 protocol * \param payloadSize payload size * \param ttl TTL * \return newly created IPv6 header */ Ipv6Header BuildHeader (Ipv6Address src, Ipv6Address dst, uint8_t protocol, uint16_t payloadSize, uint8_t ttl); /** * \brief Send packet with route. * \param route route * \param packet packet to send * \param ipHeader IPv6 header to add to the packet */ void SendRealOut (Ptr<Ipv6Route> route, Ptr<Packet> packet, Ipv6Header const& ipHeader); /** * \brief Forward a packet. * \param rtentry route * \param p packet to forward * \param header IPv6 header to add to the packet */ void IpForward (Ptr<Ipv6Route> rtentry, Ptr<const Packet> p, const Ipv6Header& header); /** * \brief Forward a packet in multicast. * \param mrtentry route * \param p packet to forward * \param header IPv6 header to add to the packet */ void IpMulticastForward (Ptr<Ipv6MulticastRoute> mrtentry, Ptr<const Packet> p, const Ipv6Header& header); /** * \brief Deliver a packet. * \param p packet delivered * \param ip IPv6 header * \param iif input interface packet was received */ void LocalDeliver (Ptr<const Packet> p, Ipv6Header const& ip, uint32_t iif); /** * \brief Fallback when no route is found. * \param p packet * \param ipHeader IPv6 header * \param sockErrno error number */ void RouteInputError (Ptr<const Packet> p, const Ipv6Header& ipHeader, Socket::SocketErrno sockErrno); /** * \brief Add an IPv6 interface to the stack. * \param interface interface to add * \return index of newly added interface */ uint32_t AddIpv6Interface (Ptr<Ipv6Interface> interface); /** * \brief Setup loopback interface. */ void SetupLoopback (); /** * \brief Set IPv6 forwarding state. * \param forward IPv6 forwarding enabled or not */ virtual void SetIpForward (bool forward); /** * \brief Get IPv6 forwarding state. * \return forwarding state (enabled or not) */ virtual bool GetIpForward () const; /** * \brief Node attached to stack. */ Ptr<Node> m_node; /** * \brief Forwarding packets (i.e. router mode) state. */ bool m_ipForward; /** * \brief List of transport protocol. */ L4List_t m_protocols; /** * \brief List of IPv6 interfaces. */ Ipv6InterfaceList m_interfaces; /** * \brief Number of IPv6 interfaces managed by the stack. */ uint32_t m_nInterfaces; /** * \brief Default TTL for outgoing packets. */ uint8_t m_defaultTtl; /** * \brief Routing protocol. */ Ptr<Ipv6RoutingProtocol> m_routingProtocol; /** * \brief List of IPv6 raw sockets. */ SocketList m_sockets; /** * \brief List of IPv6 prefix received from RA. */ Ipv6AutoconfiguredPrefixList m_prefixes; }; } /* namespace ns3 */ #endif /* IPV6_L3_PROTOCOL_H */
zy901002-gpsr
src/internet/model/ipv6-l3-protocol.h
C++
gpl2
13,985
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2005 INRIA * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr> */ #include "ns3/assert.h" #include "ns3/address-utils.h" #include "arp-header.h" namespace ns3 { NS_OBJECT_ENSURE_REGISTERED (ArpHeader); void ArpHeader::SetRequest (Address sourceHardwareAddress, Ipv4Address sourceProtocolAddress, Address destinationHardwareAddress, Ipv4Address destinationProtocolAddress) { m_type = ARP_TYPE_REQUEST; m_macSource = sourceHardwareAddress; m_macDest = destinationHardwareAddress; m_ipv4Source = sourceProtocolAddress; m_ipv4Dest = destinationProtocolAddress; } void ArpHeader::SetReply (Address sourceHardwareAddress, Ipv4Address sourceProtocolAddress, Address destinationHardwareAddress, Ipv4Address destinationProtocolAddress) { m_type = ARP_TYPE_REPLY; m_macSource = sourceHardwareAddress; m_macDest = destinationHardwareAddress; m_ipv4Source = sourceProtocolAddress; m_ipv4Dest = destinationProtocolAddress; } bool ArpHeader::IsRequest (void) const { return (m_type == ARP_TYPE_REQUEST) ? true : false; } bool ArpHeader::IsReply (void) const { return (m_type == ARP_TYPE_REPLY) ? true : false; } Address ArpHeader::GetSourceHardwareAddress (void) { return m_macSource; } Address ArpHeader::GetDestinationHardwareAddress (void) { return m_macDest; } Ipv4Address ArpHeader::GetSourceIpv4Address (void) { return m_ipv4Source; } Ipv4Address ArpHeader::GetDestinationIpv4Address (void) { return m_ipv4Dest; } TypeId ArpHeader::GetTypeId (void) { static TypeId tid = TypeId ("ns3::ArpHeader") .SetParent<Header> () .AddConstructor<ArpHeader> () ; return tid; } TypeId ArpHeader::GetInstanceTypeId (void) const { return GetTypeId (); } void ArpHeader::Print (std::ostream &os) const { if (IsRequest ()) { os << "request " << "source mac: " << m_macSource << " " << "source ipv4: " << m_ipv4Source << " " << "dest ipv4: " << m_ipv4Dest ; } else { NS_ASSERT (IsReply ()); os << "reply " << "source mac: " << m_macSource << " " << "source ipv4: " << m_ipv4Source << " " << "dest mac: " << m_macDest << " " << "dest ipv4: " <<m_ipv4Dest ; } } uint32_t ArpHeader::GetSerializedSize (void) const { /* this is the size of an ARP payload. */ return 28; } void ArpHeader::Serialize (Buffer::Iterator start) const { Buffer::Iterator i = start; NS_ASSERT (m_macSource.GetLength () == m_macDest.GetLength ()); /* ethernet */ i.WriteHtonU16 (0x0001); /* ipv4 */ i.WriteHtonU16 (0x0800); i.WriteU8 (m_macSource.GetLength ()); i.WriteU8 (4); i.WriteHtonU16 (m_type); WriteTo (i, m_macSource); WriteTo (i, m_ipv4Source); WriteTo (i, m_macDest); WriteTo (i, m_ipv4Dest); } uint32_t ArpHeader::Deserialize (Buffer::Iterator start) { Buffer::Iterator i = start; i.Next (2); // Skip HRD uint32_t protocolType = i.ReadNtohU16 (); // Read PRO uint32_t hardwareAddressLen = i.ReadU8 (); // Read HLN uint32_t protocolAddressLen = i.ReadU8 (); // Read PLN // // It is implicit here that we have a protocol type of 0x800 (IP). // It is also implicit here that we are using Ipv4 (PLN == 4). // If this isn't the case, we need to return an error since we don't want to // be too fragile if we get connected to real networks. // if (protocolType != 0x800 || protocolAddressLen != 4) { return 0; } m_type = i.ReadNtohU16 (); // Read OP ReadFrom (i, m_macSource, hardwareAddressLen); // Read SHA (size HLN) ReadFrom (i, m_ipv4Source); // Read SPA (size PLN == 4) ReadFrom (i, m_macDest, hardwareAddressLen); // Read THA (size HLN) ReadFrom (i, m_ipv4Dest); // Read TPA (size PLN == 4) return GetSerializedSize (); } } // namespace ns3
zy901002-gpsr
src/internet/model/arp-header.cc
C++
gpl2
4,759
// -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- // // Copyright (c) 2006 Georgia Tech Research Corporation // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation; // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Author: George F. Riley<riley@ece.gatech.edu> // #include "ns3/packet.h" #include "ns3/log.h" #include "ns3/callback.h" #include "ns3/ipv4-address.h" #include "ns3/ipv4-route.h" #include "ns3/node.h" #include "ns3/socket.h" #include "ns3/net-device.h" #include "ns3/uinteger.h" #include "ns3/trace-source-accessor.h" #include "ns3/object-vector.h" #include "ns3/ipv4-header.h" #include "ns3/boolean.h" #include "ns3/ipv4-routing-table-entry.h" #include "loopback-net-device.h" #include "arp-l3-protocol.h" #include "ipv4-l3-protocol.h" #include "ipv4-l4-protocol.h" #include "icmpv4-l4-protocol.h" #include "ipv4-interface.h" #include "ipv4-raw-socket-impl.h" NS_LOG_COMPONENT_DEFINE ("Ipv4L3Protocol"); namespace ns3 { const uint16_t Ipv4L3Protocol::PROT_NUMBER = 0x0800; NS_OBJECT_ENSURE_REGISTERED (Ipv4L3Protocol); TypeId Ipv4L3Protocol::GetTypeId (void) { static TypeId tid = TypeId ("ns3::Ipv4L3Protocol") .SetParent<Ipv4> () .AddConstructor<Ipv4L3Protocol> () .AddAttribute ("DefaultTtl", "The TTL value set by default on all outgoing packets generated on this node.", UintegerValue (64), MakeUintegerAccessor (&Ipv4L3Protocol::m_defaultTtl), MakeUintegerChecker<uint8_t> ()) .AddAttribute ("FragmentExpirationTimeout", "When this timeout expires, the fragments will be cleared from the buffer.", TimeValue (Seconds (30)), MakeTimeAccessor (&Ipv4L3Protocol::m_fragmentExpirationTimeout), MakeTimeChecker ()) .AddTraceSource ("Tx", "Send ipv4 packet to outgoing interface.", MakeTraceSourceAccessor (&Ipv4L3Protocol::m_txTrace)) .AddTraceSource ("Rx", "Receive ipv4 packet from incoming interface.", MakeTraceSourceAccessor (&Ipv4L3Protocol::m_rxTrace)) .AddTraceSource ("Drop", "Drop ipv4 packet", MakeTraceSourceAccessor (&Ipv4L3Protocol::m_dropTrace)) .AddAttribute ("InterfaceList", "The set of Ipv4 interfaces associated to this Ipv4 stack.", ObjectVectorValue (), MakeObjectVectorAccessor (&Ipv4L3Protocol::m_interfaces), MakeObjectVectorChecker<Ipv4Interface> ()) .AddTraceSource ("SendOutgoing", "A newly-generated packet by this node is about to be queued for transmission", MakeTraceSourceAccessor (&Ipv4L3Protocol::m_sendOutgoingTrace)) .AddTraceSource ("UnicastForward", "A unicast IPv4 packet was received by this node and is being forwarded to another node", MakeTraceSourceAccessor (&Ipv4L3Protocol::m_unicastForwardTrace)) .AddTraceSource ("LocalDeliver", "An IPv4 packet was received by/for this node, and it is being forward up the stack", MakeTraceSourceAccessor (&Ipv4L3Protocol::m_localDeliverTrace)) ; return tid; } Ipv4L3Protocol::Ipv4L3Protocol() : m_identification (0) { NS_LOG_FUNCTION (this); } Ipv4L3Protocol::~Ipv4L3Protocol () { NS_LOG_FUNCTION (this); } void Ipv4L3Protocol::Insert (Ptr<Ipv4L4Protocol> protocol) { m_protocols.push_back (protocol); } Ptr<Ipv4L4Protocol> Ipv4L3Protocol::GetProtocol (int protocolNumber) const { for (L4List_t::const_iterator i = m_protocols.begin (); i != m_protocols.end (); ++i) { if ((*i)->GetProtocolNumber () == protocolNumber) { return *i; } } return 0; } void Ipv4L3Protocol::Remove (Ptr<Ipv4L4Protocol> protocol) { m_protocols.remove (protocol); } void Ipv4L3Protocol::SetNode (Ptr<Node> node) { m_node = node; // Add a LoopbackNetDevice if needed, and an Ipv4Interface on top of it SetupLoopback (); } Ptr<Socket> Ipv4L3Protocol::CreateRawSocket (void) { NS_LOG_FUNCTION (this); Ptr<Ipv4RawSocketImpl> socket = CreateObject<Ipv4RawSocketImpl> (); socket->SetNode (m_node); m_sockets.push_back (socket); return socket; } void Ipv4L3Protocol::DeleteRawSocket (Ptr<Socket> socket) { NS_LOG_FUNCTION (this << socket); for (SocketList::iterator i = m_sockets.begin (); i != m_sockets.end (); ++i) { if ((*i) == socket) { m_sockets.erase (i); return; } } return; } /* * This method is called by AddAgregate and completes the aggregation * by setting the node in the ipv4 stack */ void Ipv4L3Protocol::NotifyNewAggregate () { if (m_node == 0) { Ptr<Node>node = this->GetObject<Node>(); // verify that it's a valid node and that // the node has not been set before if (node != 0) { this->SetNode (node); } } Object::NotifyNewAggregate (); } void Ipv4L3Protocol::SetRoutingProtocol (Ptr<Ipv4RoutingProtocol> routingProtocol) { NS_LOG_FUNCTION (this); m_routingProtocol = routingProtocol; m_routingProtocol->SetIpv4 (this); } Ptr<Ipv4RoutingProtocol> Ipv4L3Protocol::GetRoutingProtocol (void) const { return m_routingProtocol; } void Ipv4L3Protocol::DoDispose (void) { NS_LOG_FUNCTION (this); for (L4List_t::iterator i = m_protocols.begin (); i != m_protocols.end (); ++i) { *i = 0; } m_protocols.clear (); for (Ipv4InterfaceList::iterator i = m_interfaces.begin (); i != m_interfaces.end (); ++i) { *i = 0; } m_interfaces.clear (); m_sockets.clear (); m_node = 0; m_routingProtocol = 0; for (MapFragments_t::iterator it = m_fragments.begin (); it != m_fragments.end (); it++) { it->second = 0; } for (MapFragmentsTimers_t::iterator it = m_fragmentsTimers.begin (); it != m_fragmentsTimers.end (); it++) { if (it->second.IsRunning ()) { it->second.Cancel (); } } m_fragments.clear (); m_fragmentsTimers.clear (); Object::DoDispose (); } void Ipv4L3Protocol::SetupLoopback (void) { NS_LOG_FUNCTION (this); Ptr<Ipv4Interface> interface = CreateObject<Ipv4Interface> (); Ptr<LoopbackNetDevice> device = 0; // First check whether an existing LoopbackNetDevice exists on the node for (uint32_t i = 0; i < m_node->GetNDevices (); i++) { if (device = DynamicCast<LoopbackNetDevice> (m_node->GetDevice (i))) { break; } } if (device == 0) { device = CreateObject<LoopbackNetDevice> (); m_node->AddDevice (device); } interface->SetDevice (device); interface->SetNode (m_node); Ipv4InterfaceAddress ifaceAddr = Ipv4InterfaceAddress (Ipv4Address::GetLoopback (), Ipv4Mask::GetLoopback ()); interface->AddAddress (ifaceAddr); uint32_t index = AddIpv4Interface (interface); Ptr<Node> node = GetObject<Node> (); node->RegisterProtocolHandler (MakeCallback (&Ipv4L3Protocol::Receive, this), Ipv4L3Protocol::PROT_NUMBER, device); interface->SetUp (); if (m_routingProtocol != 0) { m_routingProtocol->NotifyInterfaceUp (index); } } void Ipv4L3Protocol::SetDefaultTtl (uint8_t ttl) { m_defaultTtl = ttl; } uint32_t Ipv4L3Protocol::AddInterface (Ptr<NetDevice> device) { NS_LOG_FUNCTION (this << &device); Ptr<Node> node = GetObject<Node> (); node->RegisterProtocolHandler (MakeCallback (&Ipv4L3Protocol::Receive, this), Ipv4L3Protocol::PROT_NUMBER, device); node->RegisterProtocolHandler (MakeCallback (&ArpL3Protocol::Receive, PeekPointer (GetObject<ArpL3Protocol> ())), ArpL3Protocol::PROT_NUMBER, device); Ptr<Ipv4Interface> interface = CreateObject<Ipv4Interface> (); interface->SetNode (m_node); interface->SetDevice (device); interface->SetForwarding (m_ipForward); return AddIpv4Interface (interface); } uint32_t Ipv4L3Protocol::AddIpv4Interface (Ptr<Ipv4Interface>interface) { NS_LOG_FUNCTION (this << interface); uint32_t index = m_interfaces.size (); m_interfaces.push_back (interface); return index; } Ptr<Ipv4Interface> Ipv4L3Protocol::GetInterface (uint32_t index) const { if (index < m_interfaces.size ()) { return m_interfaces[index]; } return 0; } uint32_t Ipv4L3Protocol::GetNInterfaces (void) const { return m_interfaces.size (); } int32_t Ipv4L3Protocol::GetInterfaceForAddress ( Ipv4Address address) const { int32_t interface = 0; for (Ipv4InterfaceList::const_iterator i = m_interfaces.begin (); i != m_interfaces.end (); i++, interface++) { for (uint32_t j = 0; j < (*i)->GetNAddresses (); j++) { if ((*i)->GetAddress (j).GetLocal () == address) { return interface; } } } return -1; } int32_t Ipv4L3Protocol::GetInterfaceForPrefix ( Ipv4Address address, Ipv4Mask mask) const { int32_t interface = 0; for (Ipv4InterfaceList::const_iterator i = m_interfaces.begin (); i != m_interfaces.end (); i++, interface++) { for (uint32_t j = 0; j < (*i)->GetNAddresses (); j++) { if ((*i)->GetAddress (j).GetLocal ().CombineMask (mask) == address.CombineMask (mask)) { return interface; } } } return -1; } int32_t Ipv4L3Protocol::GetInterfaceForDevice ( Ptr<const NetDevice> device) const { int32_t interface = 0; for (Ipv4InterfaceList::const_iterator i = m_interfaces.begin (); i != m_interfaces.end (); i++, interface++) { if ((*i)->GetDevice () == device) { return interface; } } return -1; } bool Ipv4L3Protocol::IsDestinationAddress (Ipv4Address address, uint32_t iif) const { // First check the incoming interface for a unicast address match for (uint32_t i = 0; i < GetNAddresses (iif); i++) { Ipv4InterfaceAddress iaddr = GetAddress (iif, i); if (address == iaddr.GetLocal ()) { NS_LOG_LOGIC ("For me (destination " << address << " match)"); return true; } if (address == iaddr.GetBroadcast ()) { NS_LOG_LOGIC ("For me (interface broadcast address)"); return true; } } if (address.IsMulticast ()) { #ifdef NOTYET if (MulticastCheckGroup (iif, address )) #endif if (true) { NS_LOG_LOGIC ("For me (Ipv4Addr multicast address"); return true; } } if (address.IsBroadcast ()) { NS_LOG_LOGIC ("For me (Ipv4Addr broadcast address)"); return true; } if (GetWeakEsModel ()) // Check other interfaces { for (uint32_t j = 0; j < GetNInterfaces (); j++) { if (j == uint32_t (iif)) continue; for (uint32_t i = 0; i < GetNAddresses (j); i++) { Ipv4InterfaceAddress iaddr = GetAddress (j, i); if (address == iaddr.GetLocal ()) { NS_LOG_LOGIC ("For me (destination " << address << " match) on another interface"); return true; } // This is a small corner case: match another interface's broadcast address if (address == iaddr.GetBroadcast ()) { NS_LOG_LOGIC ("For me (interface broadcast address on another interface)"); return true; } } } } return false; } void Ipv4L3Protocol::Receive ( Ptr<NetDevice> device, Ptr<const Packet> p, uint16_t protocol, const Address &from, const Address &to, NetDevice::PacketType packetType) { NS_LOG_FUNCTION (this << &device << p << protocol << from); NS_LOG_LOGIC ("Packet from " << from << " received on node " << m_node->GetId ()); uint32_t interface = 0; Ptr<Packet> packet = p->Copy (); Ptr<Ipv4Interface> ipv4Interface; for (Ipv4InterfaceList::const_iterator i = m_interfaces.begin (); i != m_interfaces.end (); i++, interface++) { ipv4Interface = *i; if (ipv4Interface->GetDevice () == device) { if (ipv4Interface->IsUp ()) { m_rxTrace (packet, m_node->GetObject<Ipv4> (), interface); break; } else { NS_LOG_LOGIC ("Dropping received packet -- interface is down"); Ipv4Header ipHeader; packet->RemoveHeader (ipHeader); m_dropTrace (ipHeader, packet, DROP_INTERFACE_DOWN, m_node->GetObject<Ipv4> (), interface); return; } } } Ipv4Header ipHeader; if (Node::ChecksumEnabled ()) { ipHeader.EnableChecksum (); } packet->RemoveHeader (ipHeader); // Trim any residual frame padding from underlying devices if (ipHeader.GetPayloadSize () < packet->GetSize ()) { packet->RemoveAtEnd (packet->GetSize () - ipHeader.GetPayloadSize ()); } if (!ipHeader.IsChecksumOk ()) { NS_LOG_LOGIC ("Dropping received packet -- checksum not ok"); m_dropTrace (ipHeader, packet, DROP_BAD_CHECKSUM, m_node->GetObject<Ipv4> (), interface); return; } for (SocketList::iterator i = m_sockets.begin (); i != m_sockets.end (); ++i) { NS_LOG_LOGIC ("Forwarding to raw socket"); Ptr<Ipv4RawSocketImpl> socket = *i; socket->ForwardUp (packet, ipHeader, ipv4Interface); } NS_ASSERT_MSG (m_routingProtocol != 0, "Need a routing protocol object to process packets"); if (!m_routingProtocol->RouteInput (packet, ipHeader, device, MakeCallback (&Ipv4L3Protocol::IpForward, this), MakeCallback (&Ipv4L3Protocol::IpMulticastForward, this), MakeCallback (&Ipv4L3Protocol::LocalDeliver, this), MakeCallback (&Ipv4L3Protocol::RouteInputError, this) )) { NS_LOG_WARN ("No route found for forwarding packet. Drop."); m_dropTrace (ipHeader, packet, DROP_NO_ROUTE, m_node->GetObject<Ipv4> (), interface); } } Ptr<Icmpv4L4Protocol> Ipv4L3Protocol::GetIcmp (void) const { Ptr<Ipv4L4Protocol> prot = GetProtocol (Icmpv4L4Protocol::GetStaticProtocolNumber ()); if (prot != 0) { return prot->GetObject<Icmpv4L4Protocol> (); } else { return 0; } } bool Ipv4L3Protocol::IsUnicast (Ipv4Address ad, Ipv4Mask interfaceMask) const { return !ad.IsMulticast () && !ad.IsSubnetDirectedBroadcast (interfaceMask); } void Ipv4L3Protocol::SendWithHeader (Ptr<Packet> packet, Ipv4Header ipHeader, Ptr<Ipv4Route> route) { NS_LOG_FUNCTION (this << packet << ipHeader << route); SendRealOut (route, packet, ipHeader); } void Ipv4L3Protocol::Send (Ptr<Packet> packet, Ipv4Address source, Ipv4Address destination, uint8_t protocol, Ptr<Ipv4Route> route) { NS_LOG_FUNCTION (this << packet << source << destination << uint32_t (protocol) << route); Ipv4Header ipHeader; bool mayFragment = true; uint8_t ttl = m_defaultTtl; SocketIpTtlTag tag; bool found = packet->RemovePacketTag (tag); if (found) { ttl = tag.GetTtl (); } // Handle a few cases: // 1) packet is destined to limited broadcast address // 2) packet is destined to a subnet-directed broadcast address // 3) packet is not broadcast, and is passed in with a route entry // 4) packet is not broadcast, and is passed in with a route entry but route->GetGateway is not set (e.g., on-demand) // 5) packet is not broadcast, and route is NULL (e.g., a raw socket call, or ICMP) // 1) packet is destined to limited broadcast address or link-local multicast address if (destination.IsBroadcast () || destination.IsLocalMulticast ()) { NS_LOG_LOGIC ("Ipv4L3Protocol::Send case 1: limited broadcast"); ipHeader = BuildHeader (source, destination, protocol, packet->GetSize (), ttl, mayFragment); uint32_t ifaceIndex = 0; for (Ipv4InterfaceList::iterator ifaceIter = m_interfaces.begin (); ifaceIter != m_interfaces.end (); ifaceIter++, ifaceIndex++) { Ptr<Ipv4Interface> outInterface = *ifaceIter; Ptr<Packet> packetCopy = packet->Copy (); NS_ASSERT (packetCopy->GetSize () <= outInterface->GetDevice ()->GetMtu ()); m_sendOutgoingTrace (ipHeader, packetCopy, ifaceIndex); packetCopy->AddHeader (ipHeader); m_txTrace (packetCopy, m_node->GetObject<Ipv4> (), ifaceIndex); outInterface->Send (packetCopy, destination); } return; } // 2) check: packet is destined to a subnet-directed broadcast address uint32_t ifaceIndex = 0; for (Ipv4InterfaceList::iterator ifaceIter = m_interfaces.begin (); ifaceIter != m_interfaces.end (); ifaceIter++, ifaceIndex++) { Ptr<Ipv4Interface> outInterface = *ifaceIter; for (uint32_t j = 0; j < GetNAddresses (ifaceIndex); j++) { Ipv4InterfaceAddress ifAddr = GetAddress (ifaceIndex, j); NS_LOG_LOGIC ("Testing address " << ifAddr.GetLocal () << " with mask " << ifAddr.GetMask ()); if (destination.IsSubnetDirectedBroadcast (ifAddr.GetMask ()) && destination.CombineMask (ifAddr.GetMask ()) == ifAddr.GetLocal ().CombineMask (ifAddr.GetMask ()) ) { NS_LOG_LOGIC ("Ipv4L3Protocol::Send case 2: subnet directed bcast to " << ifAddr.GetLocal ()); ipHeader = BuildHeader (source, destination, protocol, packet->GetSize (), ttl, mayFragment); Ptr<Packet> packetCopy = packet->Copy (); m_sendOutgoingTrace (ipHeader, packetCopy, ifaceIndex); packetCopy->AddHeader (ipHeader); m_txTrace (packetCopy, m_node->GetObject<Ipv4> (), ifaceIndex); outInterface->Send (packetCopy, destination); return; } } } // 3) packet is not broadcast, and is passed in with a route entry // with a valid Ipv4Address as the gateway if (route && route->GetGateway () != Ipv4Address ()) { NS_LOG_LOGIC ("Ipv4L3Protocol::Send case 3: passed in with route"); ipHeader = BuildHeader (source, destination, protocol, packet->GetSize (), ttl, mayFragment); int32_t interface = GetInterfaceForDevice (route->GetOutputDevice ()); m_sendOutgoingTrace (ipHeader, packet, interface); SendRealOut (route, packet->Copy (), ipHeader); return; } // 4) packet is not broadcast, and is passed in with a route entry but route->GetGateway is not set (e.g., on-demand) if (route && route->GetGateway () == Ipv4Address ()) { // This could arise because the synchronous RouteOutput() call // returned to the transport protocol with a source address but // there was no next hop available yet (since a route may need // to be queried). NS_FATAL_ERROR ("Ipv4L3Protocol::Send case 4: This case not yet implemented"); } // 5) packet is not broadcast, and route is NULL (e.g., a raw socket call) NS_LOG_LOGIC ("Ipv4L3Protocol::Send case 5: passed in with no route " << destination); Socket::SocketErrno errno_; Ptr<NetDevice> oif (0); // unused for now ipHeader = BuildHeader (source, destination, protocol, packet->GetSize (), ttl, mayFragment); Ptr<Ipv4Route> newRoute; if (m_routingProtocol != 0) { newRoute = m_routingProtocol->RouteOutput (packet, ipHeader, oif, errno_); } else { NS_LOG_ERROR ("Ipv4L3Protocol::Send: m_routingProtocol == 0"); } if (newRoute) { int32_t interface = GetInterfaceForDevice (newRoute->GetOutputDevice ()); m_sendOutgoingTrace (ipHeader, packet, interface); SendRealOut (newRoute, packet->Copy (), ipHeader); } else { NS_LOG_WARN ("No route to host. Drop."); m_dropTrace (ipHeader, packet, DROP_NO_ROUTE, m_node->GetObject<Ipv4> (), 0); } } // XXX when should we set ip_id? check whether we are incrementing // m_identification on packets that may later be dropped in this stack // and whether that deviates from Linux Ipv4Header Ipv4L3Protocol::BuildHeader ( Ipv4Address source, Ipv4Address destination, uint8_t protocol, uint16_t payloadSize, uint8_t ttl, bool mayFragment) { NS_LOG_FUNCTION (this << source << destination << (uint16_t)protocol << payloadSize << (uint16_t)ttl << mayFragment); Ipv4Header ipHeader; ipHeader.SetSource (source); ipHeader.SetDestination (destination); ipHeader.SetProtocol (protocol); ipHeader.SetPayloadSize (payloadSize); ipHeader.SetTtl (ttl); if (mayFragment == true) { ipHeader.SetMayFragment (); ipHeader.SetIdentification (m_identification); m_identification++; } else { ipHeader.SetDontFragment (); // TBD: set to zero here; will cause traces to change ipHeader.SetIdentification (m_identification); m_identification++; } if (Node::ChecksumEnabled ()) { ipHeader.EnableChecksum (); } return ipHeader; } void Ipv4L3Protocol::SendRealOut (Ptr<Ipv4Route> route, Ptr<Packet> packet, Ipv4Header const &ipHeader) { NS_LOG_FUNCTION (this << packet << &ipHeader); if (route == 0) { NS_LOG_WARN ("No route to host. Drop."); m_dropTrace (ipHeader, packet, DROP_NO_ROUTE, m_node->GetObject<Ipv4> (), 0); return; } packet->AddHeader (ipHeader); Ptr<NetDevice> outDev = route->GetOutputDevice (); int32_t interface = GetInterfaceForDevice (outDev); NS_ASSERT (interface >= 0); Ptr<Ipv4Interface> outInterface = GetInterface (interface); NS_LOG_LOGIC ("Send via NetDevice ifIndex " << outDev->GetIfIndex () << " ipv4InterfaceIndex " << interface); if (!route->GetGateway ().IsEqual (Ipv4Address ("0.0.0.0"))) { if (outInterface->IsUp ()) { NS_LOG_LOGIC ("Send to gateway " << route->GetGateway ()); if ( packet->GetSize () > outInterface->GetDevice ()->GetMtu () ) { std::list<Ptr<Packet> > listFragments; DoFragmentation (packet, outInterface->GetDevice ()->GetMtu (), listFragments); for ( std::list<Ptr<Packet> >::iterator it = listFragments.begin (); it != listFragments.end (); it++ ) { m_txTrace (*it, m_node->GetObject<Ipv4> (), interface); outInterface->Send (*it, route->GetGateway ()); } } else { m_txTrace (packet, m_node->GetObject<Ipv4> (), interface); outInterface->Send (packet, route->GetGateway ()); } } else { NS_LOG_LOGIC ("Dropping -- outgoing interface is down: " << route->GetGateway ()); Ipv4Header ipHeader; packet->RemoveHeader (ipHeader); m_dropTrace (ipHeader, packet, DROP_INTERFACE_DOWN, m_node->GetObject<Ipv4> (), interface); } } else { if (outInterface->IsUp ()) { NS_LOG_LOGIC ("Send to destination " << ipHeader.GetDestination ()); if ( packet->GetSize () > outInterface->GetDevice ()->GetMtu () ) { std::list<Ptr<Packet> > listFragments; DoFragmentation (packet, outInterface->GetDevice ()->GetMtu (), listFragments); for ( std::list<Ptr<Packet> >::iterator it = listFragments.begin (); it != listFragments.end (); it++ ) { NS_LOG_LOGIC ("Sending fragment " << **it ); m_txTrace (*it, m_node->GetObject<Ipv4> (), interface); outInterface->Send (*it, ipHeader.GetDestination ()); } } else { m_txTrace (packet, m_node->GetObject<Ipv4> (), interface); outInterface->Send (packet, ipHeader.GetDestination ()); } } else { NS_LOG_LOGIC ("Dropping -- outgoing interface is down: " << ipHeader.GetDestination ()); Ipv4Header ipHeader; packet->RemoveHeader (ipHeader); m_dropTrace (ipHeader, packet, DROP_INTERFACE_DOWN, m_node->GetObject<Ipv4> (), interface); } } } // This function analogous to Linux ip_mr_forward() void Ipv4L3Protocol::IpMulticastForward (Ptr<Ipv4MulticastRoute> mrtentry, Ptr<const Packet> p, const Ipv4Header &header) { NS_LOG_FUNCTION (this << mrtentry << p << header); NS_LOG_LOGIC ("Multicast forwarding logic for node: " << m_node->GetId ()); std::map<uint32_t, uint32_t> ttlMap = mrtentry->GetOutputTtlMap (); std::map<uint32_t, uint32_t>::iterator mapIter; for (mapIter = ttlMap.begin (); mapIter != ttlMap.end (); mapIter++) { uint32_t interfaceId = mapIter->first; //uint32_t outputTtl = mapIter->second; // Unused for now Ptr<Packet> packet = p->Copy (); Ipv4Header h = header; h.SetTtl (header.GetTtl () - 1); if (h.GetTtl () == 0) { NS_LOG_WARN ("TTL exceeded. Drop."); m_dropTrace (header, packet, DROP_TTL_EXPIRED, m_node->GetObject<Ipv4> (), interfaceId); return; } NS_LOG_LOGIC ("Forward multicast via interface " << interfaceId); Ptr<Ipv4Route> rtentry = Create<Ipv4Route> (); rtentry->SetSource (h.GetSource ()); rtentry->SetDestination (h.GetDestination ()); rtentry->SetGateway (Ipv4Address::GetAny ()); rtentry->SetOutputDevice (GetNetDevice (interfaceId)); SendRealOut (rtentry, packet, h); continue; } } // This function analogous to Linux ip_forward() void Ipv4L3Protocol::IpForward (Ptr<Ipv4Route> rtentry, Ptr<const Packet> p, const Ipv4Header &header) { NS_LOG_FUNCTION (this << rtentry << p << header); NS_LOG_LOGIC ("Forwarding logic for node: " << m_node->GetId ()); // Forwarding Ipv4Header ipHeader = header; Ptr<Packet> packet = p->Copy (); int32_t interface = GetInterfaceForDevice (rtentry->GetOutputDevice ()); ipHeader.SetTtl (ipHeader.GetTtl () - 1); if (ipHeader.GetTtl () == 0) { // Do not reply to ICMP or to multicast/broadcast IP address if (ipHeader.GetProtocol () != Icmpv4L4Protocol::PROT_NUMBER && ipHeader.GetDestination ().IsBroadcast () == false && ipHeader.GetDestination ().IsMulticast () == false) { Ptr<Icmpv4L4Protocol> icmp = GetIcmp (); icmp->SendTimeExceededTtl (ipHeader, packet); } NS_LOG_WARN ("TTL exceeded. Drop."); m_dropTrace (header, packet, DROP_TTL_EXPIRED, m_node->GetObject<Ipv4> (), interface); return; } m_unicastForwardTrace (ipHeader, packet, interface); SendRealOut (rtentry, packet, ipHeader); } void Ipv4L3Protocol::LocalDeliver (Ptr<const Packet> packet, Ipv4Header const&ip, uint32_t iif) { NS_LOG_FUNCTION (this << packet << &ip); Ptr<Packet> p = packet->Copy (); // need to pass a non-const packet up Ipv4Header ipHeader = ip; if ( !ipHeader.IsLastFragment () || ipHeader.GetFragmentOffset () != 0 ) { NS_LOG_LOGIC ("Received a fragment, processing " << *p ); bool isPacketComplete; isPacketComplete = ProcessFragment (p, ipHeader, iif); if ( isPacketComplete == false) { return; } NS_LOG_LOGIC ("Got last fragment, Packet is complete " << *p ); } m_localDeliverTrace (ip, packet, iif); Ptr<Ipv4L4Protocol> protocol = GetProtocol (ip.GetProtocol ()); if (protocol != 0) { // we need to make a copy in the unlikely event we hit the // RX_ENDPOINT_UNREACH codepath Ptr<Packet> copy = p->Copy (); enum Ipv4L4Protocol::RxStatus status = protocol->Receive (p, ip, GetInterface (iif)); switch (status) { case Ipv4L4Protocol::RX_OK: // fall through case Ipv4L4Protocol::RX_ENDPOINT_CLOSED: // fall through case Ipv4L4Protocol::RX_CSUM_FAILED: break; case Ipv4L4Protocol::RX_ENDPOINT_UNREACH: if (ip.GetDestination ().IsBroadcast () == true || ip.GetDestination ().IsMulticast () == true) { break; // Do not reply to broadcast or multicast } // Another case to suppress ICMP is a subnet-directed broadcast bool subnetDirected = false; for (uint32_t i = 0; i < GetNAddresses (iif); i++) { Ipv4InterfaceAddress addr = GetAddress (iif, i); if (addr.GetLocal ().CombineMask (addr.GetMask ()) == ip.GetDestination ().CombineMask (addr.GetMask ()) && ip.GetDestination ().IsSubnetDirectedBroadcast (addr.GetMask ())) { subnetDirected = true; } } if (subnetDirected == false) { GetIcmp ()->SendDestUnreachPort (ip, copy); } } } } bool Ipv4L3Protocol::AddAddress (uint32_t i, Ipv4InterfaceAddress address) { NS_LOG_FUNCTION (this << i << address); Ptr<Ipv4Interface> interface = GetInterface (i); bool retVal = interface->AddAddress (address); if (m_routingProtocol != 0) { m_routingProtocol->NotifyAddAddress (i, address); } return retVal; } Ipv4InterfaceAddress Ipv4L3Protocol::GetAddress (uint32_t interfaceIndex, uint32_t addressIndex) const { Ptr<Ipv4Interface> interface = GetInterface (interfaceIndex); return interface->GetAddress (addressIndex); } uint32_t Ipv4L3Protocol::GetNAddresses (uint32_t interface) const { Ptr<Ipv4Interface> iface = GetInterface (interface); return iface->GetNAddresses (); } bool Ipv4L3Protocol::RemoveAddress (uint32_t i, uint32_t addressIndex) { NS_LOG_FUNCTION (this << i << addressIndex); Ptr<Ipv4Interface> interface = GetInterface (i); Ipv4InterfaceAddress address = interface->RemoveAddress (addressIndex); if (address != Ipv4InterfaceAddress ()) { if (m_routingProtocol != 0) { m_routingProtocol->NotifyRemoveAddress (i, address); } return true; } return false; } Ipv4Address Ipv4L3Protocol::SelectSourceAddress (Ptr<const NetDevice> device, Ipv4Address dst, Ipv4InterfaceAddress::InterfaceAddressScope_e scope) { NS_LOG_FUNCTION (this << device << dst << scope); Ipv4Address addr ("0.0.0.0"); Ipv4InterfaceAddress iaddr; bool found = false; if (device != 0) { int32_t i = GetInterfaceForDevice (device); NS_ASSERT_MSG (i >= 0, "No device found on node"); for (uint32_t j = 0; j < GetNAddresses (i); j++) { iaddr = GetAddress (i, j); if (iaddr.IsSecondary ()) continue; if (iaddr.GetScope () > scope) continue; if (dst.CombineMask (iaddr.GetMask ()) == iaddr.GetLocal ().CombineMask (iaddr.GetMask ()) ) { return iaddr.GetLocal (); } if (!found) { addr = iaddr.GetLocal (); found = true; } } } if (found) { return addr; } // Iterate among all interfaces for (uint32_t i = 0; i < GetNInterfaces (); i++) { for (uint32_t j = 0; j < GetNAddresses (i); j++) { iaddr = GetAddress (i, j); if (iaddr.IsSecondary ()) continue; if (iaddr.GetScope () != Ipv4InterfaceAddress::LINK && iaddr.GetScope () <= scope) { return iaddr.GetLocal (); } } } NS_LOG_WARN ("Could not find source address for " << dst << " and scope " << scope << ", returning 0"); return addr; } void Ipv4L3Protocol::SetMetric (uint32_t i, uint16_t metric) { NS_LOG_FUNCTION (this << i << metric); Ptr<Ipv4Interface> interface = GetInterface (i); interface->SetMetric (metric); } uint16_t Ipv4L3Protocol::GetMetric (uint32_t i) const { Ptr<Ipv4Interface> interface = GetInterface (i); return interface->GetMetric (); } uint16_t Ipv4L3Protocol::GetMtu (uint32_t i) const { Ptr<Ipv4Interface> interface = GetInterface (i); return interface->GetDevice ()->GetMtu (); } bool Ipv4L3Protocol::IsUp (uint32_t i) const { Ptr<Ipv4Interface> interface = GetInterface (i); return interface->IsUp (); } void Ipv4L3Protocol::SetUp (uint32_t i) { NS_LOG_FUNCTION (this << i); Ptr<Ipv4Interface> interface = GetInterface (i); interface->SetUp (); if (m_routingProtocol != 0) { m_routingProtocol->NotifyInterfaceUp (i); } } void Ipv4L3Protocol::SetDown (uint32_t ifaceIndex) { NS_LOG_FUNCTION (this << ifaceIndex); Ptr<Ipv4Interface> interface = GetInterface (ifaceIndex); interface->SetDown (); if (m_routingProtocol != 0) { m_routingProtocol->NotifyInterfaceDown (ifaceIndex); } } bool Ipv4L3Protocol::IsForwarding (uint32_t i) const { NS_LOG_FUNCTION (this << i); Ptr<Ipv4Interface> interface = GetInterface (i); NS_LOG_LOGIC ("Forwarding state: " << interface->IsForwarding ()); return interface->IsForwarding (); } void Ipv4L3Protocol::SetForwarding (uint32_t i, bool val) { NS_LOG_FUNCTION (this << i); Ptr<Ipv4Interface> interface = GetInterface (i); interface->SetForwarding (val); } Ptr<NetDevice> Ipv4L3Protocol::GetNetDevice (uint32_t i) { return GetInterface (i)->GetDevice (); } void Ipv4L3Protocol::SetIpForward (bool forward) { NS_LOG_FUNCTION (this << forward); m_ipForward = forward; for (Ipv4InterfaceList::const_iterator i = m_interfaces.begin (); i != m_interfaces.end (); i++) { (*i)->SetForwarding (forward); } } bool Ipv4L3Protocol::GetIpForward (void) const { return m_ipForward; } void Ipv4L3Protocol::SetWeakEsModel (bool model) { m_weakEsModel = model; } bool Ipv4L3Protocol::GetWeakEsModel (void) const { return m_weakEsModel; } void Ipv4L3Protocol::RouteInputError (Ptr<const Packet> p, const Ipv4Header & ipHeader, Socket::SocketErrno sockErrno) { NS_LOG_FUNCTION (this << p << ipHeader << sockErrno); NS_LOG_LOGIC ("Route input failure-- dropping packet to " << ipHeader << " with errno " << sockErrno); m_dropTrace (ipHeader, p, DROP_ROUTE_ERROR, m_node->GetObject<Ipv4> (), 0); } void Ipv4L3Protocol::DoFragmentation (Ptr<Packet> packet, uint32_t outIfaceMtu, std::list<Ptr<Packet> >& listFragments) { // BEWARE: here we do assume that the header options are not present. // a much more complex handling is necessary in case there are options. // If (when) IPv4 option headers will be implemented, the following code shall be changed. // Of course also the reassemby code shall be changed as well. NS_LOG_FUNCTION (this << *packet << " - MTU: " << outIfaceMtu); Ptr<Packet> p = packet->Copy (); Ipv4Header ipv4Header; p->RemoveHeader (ipv4Header); NS_ASSERT_MSG( (ipv4Header.GetSerializedSize() == 5*4), "IPv4 fragmentation implementation only works without option headers." ); uint16_t offset = 0; bool moreFragment = true; uint32_t currentFragmentablePartSize = 0; // IPv4 fragments are all 8 bytes aligned but the last. // The IP payload size is: // floor( ( outIfaceMtu - ipv4Header.GetSerializedSize() ) /8 ) *8 uint32_t fragmentSize = (outIfaceMtu - ipv4Header.GetSerializedSize () ) & ~uint32_t (0x7); NS_LOG_LOGIC ("Fragmenting - Target Size: " << fragmentSize ); do { Ipv4Header fragmentHeader = ipv4Header; if (p->GetSize () > offset + fragmentSize ) { moreFragment = true; currentFragmentablePartSize = fragmentSize; fragmentHeader.SetMoreFragments (); } else { moreFragment = false; currentFragmentablePartSize = p->GetSize () - offset; fragmentHeader.SetLastFragment (); } NS_LOG_LOGIC ("Fragment creation - " << offset << ", " << currentFragmentablePartSize ); Ptr<Packet> fragment = p->CreateFragment (offset, currentFragmentablePartSize); NS_LOG_LOGIC ("Fragment created - " << offset << ", " << fragment->GetSize () ); fragmentHeader.SetFragmentOffset (offset); fragmentHeader.SetPayloadSize (currentFragmentablePartSize); if (Node::ChecksumEnabled ()) { fragmentHeader.EnableChecksum (); } NS_LOG_LOGIC ("Fragment check - " << fragmentHeader.GetFragmentOffset () ); NS_LOG_LOGIC ("New fragment Header " << fragmentHeader); fragment->AddHeader (fragmentHeader); std::ostringstream oss; fragment->Print (oss); NS_LOG_LOGIC ("New fragment " << *fragment); listFragments.push_back (fragment); offset += currentFragmentablePartSize; } while (moreFragment); return; } bool Ipv4L3Protocol::ProcessFragment (Ptr<Packet>& packet, Ipv4Header& ipHeader, uint32_t iif) { NS_LOG_FUNCTION (this << packet << " " << ipHeader << " " << iif); uint64_t addressCombination = uint64_t (ipHeader.GetSource ().Get ()) << 32 & uint64_t (ipHeader.GetDestination ().Get ()); uint32_t idProto = uint32_t (ipHeader.GetIdentification ()) << 16 & uint32_t (ipHeader.GetProtocol ()); std::pair<uint64_t, uint32_t> key; bool ret = false; Ptr<Packet> p = packet->Copy (); key.first = addressCombination; key.second = idProto; Ptr<Fragments> fragments; MapFragments_t::iterator it = m_fragments.find (key); if (it == m_fragments.end ()) { fragments = Create<Fragments> (); m_fragments.insert (std::make_pair (key, fragments)); m_fragmentsTimers[key] = Simulator::Schedule (m_fragmentExpirationTimeout, &Ipv4L3Protocol::HandleFragmentsTimeout, this, key, ipHeader, iif); } else { fragments = it->second; } NS_LOG_LOGIC ("Adding fragment - Size: " << packet->GetSize ( ) << " - Offset: " << (ipHeader.GetFragmentOffset ()) ); fragments->AddFragment (p, ipHeader.GetFragmentOffset (), !ipHeader.IsLastFragment () ); if ( fragments->IsEntire () ) { packet = fragments->GetPacket (); fragments = 0; m_fragments.erase (key); if (m_fragmentsTimers[key].IsRunning ()) { NS_LOG_LOGIC ("Stopping WaitFragmentsTimer at " << Simulator::Now ().GetSeconds () << " due to complete packet"); m_fragmentsTimers[key].Cancel (); } m_fragmentsTimers.erase (key); ret = true; } return ret; } Ipv4L3Protocol::Fragments::Fragments () : m_moreFragment (0) { } Ipv4L3Protocol::Fragments::~Fragments () { } void Ipv4L3Protocol::Fragments::AddFragment (Ptr<Packet> fragment, uint16_t fragmentOffset, bool moreFragment) { NS_LOG_FUNCTION (this << fragment << " " << fragmentOffset << " " << moreFragment); std::list<std::pair<Ptr<Packet>, uint16_t> >::iterator it; for (it = m_fragments.begin (); it != m_fragments.end (); it++) { if (it->second > fragmentOffset) { break; } } if (it == m_fragments.end ()) { m_moreFragment = moreFragment; } m_fragments.insert (it, std::make_pair<Ptr<Packet>, uint16_t> (fragment, fragmentOffset)); } bool Ipv4L3Protocol::Fragments::IsEntire () const { NS_LOG_FUNCTION (this); bool ret = !m_moreFragment && m_fragments.size () > 0; if (ret) { uint16_t lastEndOffset = 0; for (std::list<std::pair<Ptr<Packet>, uint16_t> >::const_iterator it = m_fragments.begin (); it != m_fragments.end (); it++) { // overlapping fragments do exist NS_LOG_LOGIC ("Checking overlaps " << lastEndOffset << " - " << it->second ); if (lastEndOffset < it->second) { ret = false; break; } // fragments might overlap in strange ways uint16_t fragmentEnd = it->first->GetSize () + it->second; lastEndOffset = std::max ( lastEndOffset, fragmentEnd ); } } return ret; } Ptr<Packet> Ipv4L3Protocol::Fragments::GetPacket () const { NS_LOG_FUNCTION (this); std::list<std::pair<Ptr<Packet>, uint16_t> >::const_iterator it = m_fragments.begin (); Ptr<Packet> p = Create<Packet> (); uint16_t lastEndOffset = 0; for ( it = m_fragments.begin (); it != m_fragments.end (); it++) { if ( lastEndOffset > it->second ) { // The fragments are overlapping. // We do not overwrite the "old" with the "new" because we do not know when each arrived. // This is different from what Linux does. // It is not possible to emulate a fragmentation attack. uint32_t newStart = lastEndOffset - it->second; if ( it->first->GetSize () > newStart ) { uint32_t newSize = it->first->GetSize () - newStart; Ptr<Packet> tempFragment = it->first->CreateFragment (newStart, newSize); p->AddAtEnd (tempFragment); } } else { NS_LOG_LOGIC ("Adding: " << *(it->first) ); p->AddAtEnd (it->first); } lastEndOffset = p->GetSize (); } return p; } Ptr<Packet> Ipv4L3Protocol::Fragments::GetPartialPacket () const { std::list<std::pair<Ptr<Packet>, uint16_t> >::const_iterator it = m_fragments.begin (); Ptr<Packet> p = Create<Packet> (); uint16_t lastEndOffset = 0; if ( m_fragments.begin ()->second > 0 ) { return p; } for ( it = m_fragments.begin (); it != m_fragments.end (); it++) { if ( lastEndOffset > it->second ) { uint32_t newStart = lastEndOffset - it->second; uint32_t newSize = it->first->GetSize () - newStart; Ptr<Packet> tempFragment = it->first->CreateFragment (newStart, newSize); p->AddAtEnd (tempFragment); } else if ( lastEndOffset == it->second ) { NS_LOG_LOGIC ("Adding: " << *(it->first) ); p->AddAtEnd (it->first); } lastEndOffset = p->GetSize (); } return p; } void Ipv4L3Protocol::HandleFragmentsTimeout (std::pair<uint64_t, uint32_t> key, Ipv4Header & ipHeader, uint32_t iif) { NS_LOG_FUNCTION (this); MapFragments_t::iterator it = m_fragments.find (key); Ptr<Packet> packet = it->second->GetPartialPacket (); // if we have at least 8 bytes, we can send an ICMP. if ( packet->GetSize () > 8 ) { Ptr<Icmpv4L4Protocol> icmp = GetIcmp (); icmp->SendTimeExceededTtl (ipHeader, packet); } m_dropTrace (ipHeader, packet, DROP_FRAGMENT_TIMEOUT, m_node->GetObject<Ipv4> (), iif); // clear the buffers it->second = 0; m_fragments.erase (key); m_fragmentsTimers.erase (key); } } // namespace ns3
zy901002-gpsr
src/internet/model/ipv4-l3-protocol.cc
C++
gpl2
43,644
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2008-2009 Strasbourg University * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: David Gross <gdavid.devel@gmail.com> */ #ifndef IPV6_EXTENSION_HEADER_H #define IPV6_EXTENSION_HEADER_H #include <vector> #include <list> #include <ostream> #include "ns3/header.h" #include "ns3/ipv6-address.h" #include "ipv6-option-header.h" namespace ns3 { /** * \class Ipv6ExtensionHeader * \brief Header for IPv6 Extension. */ class Ipv6ExtensionHeader : public Header { public: /** * \brief Get the type identificator. * \return type identificator */ static TypeId GetTypeId (); /** * \brief Get the instance type ID. * \return instance type ID */ virtual TypeId GetInstanceTypeId () const; /** * \brief Constructor. */ Ipv6ExtensionHeader (); /** * \brief Destructor. */ virtual ~Ipv6ExtensionHeader (); /** * \brief Set the "Next header" field. * \param nextHeader the next header number */ void SetNextHeader (uint8_t nextHeader); /** * \brief Get the next header. * \return the next header number */ uint8_t GetNextHeader () const; /** * brief Set the length of the extension. * \param length the length of the extension in bytes */ void SetLength (uint16_t length); /** * \brief Get the length of the extension. * \return the length of the extension */ uint16_t GetLength () const; /** * \brief Print some informations about the packet. * \param os output stream * \return info about this packet */ virtual void Print (std::ostream &os) const; /** * \brief Get the serialized size of the packet. * \return size */ virtual uint32_t GetSerializedSize () const; /** * \brief Serialize the packet. * \param start Buffer iterator */ virtual void Serialize (Buffer::Iterator start) const; /** * \brief Deserialize the packet. * \param start Buffer iterator * \return size of the packet */ virtual uint32_t Deserialize (Buffer::Iterator start); private: /** * \brief The "next header" field. */ uint8_t m_nextHeader; /** * \brief The "length" field. */ uint8_t m_length; /** * \brief The data of the extension. */ Buffer m_data; }; /** * \class OptionField * \brief Option field for an IPv6ExtensionHeader * Enables adding options to an IPv6ExtensionHeader * * Implementor's note: Make sure to add the result of * OptionField::GetSerializedSize () to your IPv6ExtensionHeader::GetSerializedSize () * return value. Call OptionField::Serialize and OptionField::Deserialize at the * end of your corresponding IPv6ExtensionHeader methods. */ class OptionField { public: /** * \brief Constructor. * \param optionsOffset option offset */ OptionField (uint32_t optionsOffset); /** * \brief Destructor. */ ~OptionField (); /** * \brief Get the serialized size of the packet. * \return size */ uint32_t GetSerializedSize () const; /** * \brief Serialize all added options. * \param start Buffer iterator */ void Serialize (Buffer::Iterator start) const; /** * \brief Deserialize the packet. * \param start Buffer iterator * \param length length * \return size of the packet */ uint32_t Deserialize (Buffer::Iterator start, uint32_t length); /** * \brief Serialize the option, prepending pad1 or padn option as necessary * \param option the option header to serialize */ void AddOption (Ipv6OptionHeader const& option); /** * \brief Get the offset where the options begin, measured from the start of * the extension header. * \return the offset from the start of the extension header */ uint32_t GetOptionsOffset (); /** * \brief Get the buffer. * \return buffer */ Buffer GetOptionBuffer (); private: /** * \brief Calculate padding. * \param alignment alignment */ uint32_t CalculatePad (Ipv6OptionHeader::Alignment alignment) const; /** * \brief Data payload. */ Buffer m_optionData; /** * \brief Offset. */ uint32_t m_optionsOffset; }; /** * \class Ipv6ExtensionHopByHopHeader * \brief Header of IPv6 Extension "Hop by Hop" */ class Ipv6ExtensionHopByHopHeader : public Ipv6ExtensionHeader, public OptionField { public: /** * \brief Get the type identificator. * \return type identificator */ static TypeId GetTypeId (); /** * \brief Get the instance type ID. * \return instance type ID */ virtual TypeId GetInstanceTypeId () const; /** * \brief Constructor. */ Ipv6ExtensionHopByHopHeader (); /** * \brief Destructor. */ virtual ~Ipv6ExtensionHopByHopHeader (); /** * \brief Print some informations about the packet. * \param os output stream * \return info about this packet */ virtual void Print (std::ostream &os) const; /** * \brief Get the serialized size of the packet. * \return size */ virtual uint32_t GetSerializedSize () const; /** * \brief Serialize the packet. * \param start Buffer iterator */ virtual void Serialize (Buffer::Iterator start) const; /** * \brief Deserialize the packet. * \param start Buffer iterator * \return size of the packet */ virtual uint32_t Deserialize (Buffer::Iterator start); }; /** * \class Ipv6ExtensionDestinationHeader * \brief Header of IPv6 Extension Destination */ class Ipv6ExtensionDestinationHeader : public Ipv6ExtensionHeader, public OptionField { public: /** * \brief Get the type identificator. * \return type identificator */ static TypeId GetTypeId (); /** * \brief Get the instance type ID. * \return instance type ID */ virtual TypeId GetInstanceTypeId () const; /** * \brief Constructor. */ Ipv6ExtensionDestinationHeader (); /** * \brief Destructor. */ virtual ~Ipv6ExtensionDestinationHeader (); /** * \brief Print some informations about the packet. * \param os output stream * \return info about this packet */ virtual void Print (std::ostream &os) const; /** * \brief Get the serialized size of the packet. * \return size */ virtual uint32_t GetSerializedSize () const; /** * \brief Serialize the packet. * \param start Buffer iterator */ virtual void Serialize (Buffer::Iterator start) const; /** * \brief Deserialize the packet. * \param start Buffer iterator * \return size of the packet */ virtual uint32_t Deserialize (Buffer::Iterator start); }; /** * \class Ipv6ExtensionFragmentHeader * \brief Header of IPv6 Extension Fragment */ class Ipv6ExtensionFragmentHeader : public Ipv6ExtensionHeader { public: /** * \brief Get the type identificator. * \return type identificator */ static TypeId GetTypeId (); /** * \brief Get the instance type ID. * \return instance type ID */ virtual TypeId GetInstanceTypeId () const; /** * \brief Constructor. */ Ipv6ExtensionFragmentHeader (); /** * \brief Destructor. */ virtual ~Ipv6ExtensionFragmentHeader (); /** * \brief Set the "Offset" field. * \param offset the offset of the fragment */ void SetOffset (uint16_t offset); /** * \brief Get the field "Offset". * \return the offset of the fragment */ uint16_t GetOffset () const; /** * \brief Set the status of "More Fragment" bit. * \param moreFragment the bit "More Fragment" */ void SetMoreFragment (bool moreFragment); /** * \brief Get the status of "More Fragment" bit. * \return the status of "More Fragment" bit. */ bool GetMoreFragment () const; /** * \brief Set the "Identification" field. * \param identification the identifier of the fragment */ void SetIdentification (uint32_t identification); /** * \brief Get the field "Identification". * \return the identifier of the fragment */ uint32_t GetIdentification () const; /** * \brief Print some informations about the packet. * \param os output stream * \return info about this packet */ virtual void Print (std::ostream &os) const; /** * \brief Get the serialized size of the packet. * \return size */ virtual uint32_t GetSerializedSize () const; /** * \brief Serialize the packet. * \param start Buffer iterator */ virtual void Serialize (Buffer::Iterator start) const; /** * \brief Deserialize the packet. * \param start Buffer iterator * \return size of the packet */ virtual uint32_t Deserialize (Buffer::Iterator start); private: /** * \brief Offset of the fragment and More Fragment bit. */ uint16_t m_offset; /** * \brief Identifier of the packet. */ uint32_t m_identification; }; /** * \class Ipv6ExtensionRoutingHeader * \brief Header of IPv6 Extension Routing */ class Ipv6ExtensionRoutingHeader : public Ipv6ExtensionHeader { public: /** * \brief Get the type identificator. * \return type identificator */ static TypeId GetTypeId (); /** * \brief Get the instance type ID. * \return instance type ID */ virtual TypeId GetInstanceTypeId () const; /** * \brief Constructor. */ Ipv6ExtensionRoutingHeader (); /** * \brief Destructor. */ virtual ~Ipv6ExtensionRoutingHeader (); /** * \brief Set the "Type of Routing" field. * \param typeRouting the type of routing */ void SetTypeRouting (uint8_t typeRouting); /** * \brief Get the field "Type of Routing". * \return the type of routing */ uint8_t GetTypeRouting () const; /** * \brief Set the "Segments left" field. * \param segmentsLeft the number of segments left */ void SetSegmentsLeft (uint8_t segmentsLeft); /** * \brief Get the field "Segments left". * \return the number of segments left */ uint8_t GetSegmentsLeft () const; /** * \brief Print some informations about the packet. * \param os output stream * \return info about this packet */ virtual void Print (std::ostream &os) const; /** * \brief Get the serialized size of the packet. * \return size */ virtual uint32_t GetSerializedSize () const; /** * \brief Serialize the packet. * \param start Buffer iterator */ virtual void Serialize (Buffer::Iterator start) const; /** * \brief Deserialize the packet. * \param start Buffer iterator * \return size of the packet */ virtual uint32_t Deserialize (Buffer::Iterator start); private: /** * \brief Type of routing. */ uint8_t m_typeRouting; /** * \brief Number of left segments. */ uint8_t m_segmentsLeft; }; /** * \class Ipv6ExtensionLooseRoutingHeader * \brief Header of IPv6 Extension Routing : Type 0 (Loose Routing) */ class Ipv6ExtensionLooseRoutingHeader : public Ipv6ExtensionRoutingHeader { public: /** * \brief Get the type identificator. * \return type identificator */ static TypeId GetTypeId (); /** * \brief Get the instance type ID. * \return instance type ID */ virtual TypeId GetInstanceTypeId () const; /** * \brief Constructor. */ Ipv6ExtensionLooseRoutingHeader (); /** * \brief Destructor. */ virtual ~Ipv6ExtensionLooseRoutingHeader (); /** * \brief Set the number of routers' address. * \param n the number of routers' address */ void SetNumberAddress (uint8_t n); /** * \brief Set the vector of routers' address * \param routersAddress the vector of routers's address */ void SetRoutersAddress (std::vector<Ipv6Address> routersAddress); /** * \brief Get the vector of routers' address * \return the vector of routers' address */ std::vector<Ipv6Address> GetRoutersAddress () const; /** * \brief Set a Router IPv6 Address. * \param index the index of the IPv6 Address * \param addr the new IPv6 Address */ void SetRouterAddress (uint8_t index, Ipv6Address addr); /** * \brief Get a Router IPv6 Address. * \param index the index of the IPv6 Address * \return the router IPv6 Address */ Ipv6Address GetRouterAddress (uint8_t index) const; /** * \brief Print some informations about the packet. * \param os output stream * \return info about this packet */ virtual void Print (std::ostream &os) const; /** * \brief Get the serialized size of the packet. * \return size */ virtual uint32_t GetSerializedSize () const; /** * \brief Serialize the packet. * \param start Buffer iterator */ virtual void Serialize (Buffer::Iterator start) const; /** * \brief Deserialize the packet. * \param start Buffer iterator * \return size of the packet */ virtual uint32_t Deserialize (Buffer::Iterator start); private: /** * \brief A vector of IPv6 Address. */ typedef std::vector<Ipv6Address> VectorIpv6Address_t; /** * \brief The vector of Routers' IPv6 Address. */ VectorIpv6Address_t m_routersAddress; }; /** * \class Ipv6ExtensionESPHeader * \brief Header of IPv6 Extension ESP */ class Ipv6ExtensionESPHeader : public Ipv6ExtensionHeader { public: /** * \brief Get the type identificator. * \return type identificator */ static TypeId GetTypeId (); /** * \brief Get the instance type ID. * \return instance type ID */ virtual TypeId GetInstanceTypeId () const; /** * \brief Constructor. */ Ipv6ExtensionESPHeader (); /** * \brief Destructor. */ virtual ~Ipv6ExtensionESPHeader (); /** * \brief Print some informations about the packet. * \param os output stream * \return info about this packet */ virtual void Print (std::ostream &os) const; /** * \brief Get the serialized size of the packet. * \return size */ virtual uint32_t GetSerializedSize () const; /** * \brief Serialize the packet. * \param start Buffer iterator */ virtual void Serialize (Buffer::Iterator start) const; /** * \brief Deserialize the packet. * \param start Buffer iterator * \return size of the packet */ virtual uint32_t Deserialize (Buffer::Iterator start); }; /** * \class Ipv6ExtensionAHHeader * \brief Header of IPv6 Extension AH */ class Ipv6ExtensionAHHeader : public Ipv6ExtensionHeader { public: /** * \brief Get the type identificator. * \return type identificator */ static TypeId GetTypeId (); /** * \brief Get the instance type ID. * \return instance type ID */ virtual TypeId GetInstanceTypeId () const; /** * \brief Constructor. */ Ipv6ExtensionAHHeader (); /** * \brief Destructor. */ virtual ~Ipv6ExtensionAHHeader (); /** * \brief Print some informations about the packet. * \param os output stream * \return info about this packet */ virtual void Print (std::ostream &os) const; /** * \brief Get the serialized size of the packet. * \return size */ virtual uint32_t GetSerializedSize () const; /** * \brief Serialize the packet. * \param start Buffer iterator */ virtual void Serialize (Buffer::Iterator start) const; /** * \brief Deserialize the packet. * \param start Buffer iterator * \return size of the packet */ virtual uint32_t Deserialize (Buffer::Iterator start); }; } // namespace ns3 #endif /* IPV6_EXTENSION_HEADER_H */
zy901002-gpsr
src/internet/model/ipv6-extension-header.h
C++
gpl2
15,984
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2010 Adrian Sai-wah Tam * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Adrian Sai-wah Tam <adrian.sw.tam@gmail.com> */ #define NS_LOG_APPEND_CONTEXT \ if (m_node) { std::clog << Simulator::Now ().GetSeconds () << " [node " << m_node->GetId () << "] "; } #include "ns3/abort.h" #include "ns3/node.h" #include "ns3/inet-socket-address.h" #include "ns3/log.h" #include "ns3/ipv4.h" #include "ns3/ipv4-interface-address.h" #include "ns3/ipv4-route.h" #include "ns3/ipv4-routing-protocol.h" #include "ns3/simulation-singleton.h" #include "ns3/simulator.h" #include "ns3/packet.h" #include "ns3/uinteger.h" #include "ns3/trace-source-accessor.h" #include "tcp-socket-base.h" #include "tcp-l4-protocol.h" #include "ipv4-end-point.h" #include "tcp-header.h" #include "rtt-estimator.h" #include <algorithm> NS_LOG_COMPONENT_DEFINE ("TcpSocketBase"); namespace ns3 { NS_OBJECT_ENSURE_REGISTERED (TcpSocketBase); TypeId TcpSocketBase::GetTypeId (void) { static TypeId tid = TypeId ("ns3::TcpSocketBase") .SetParent<TcpSocket> () // .AddAttribute ("TcpState", "State in TCP state machine", // TypeId::ATTR_GET, // EnumValue (CLOSED), // MakeEnumAccessor (&TcpSocketBase::m_state), // MakeEnumChecker (CLOSED, "Closed")) .AddTraceSource ("RTO", "Retransmission timeout", MakeTraceSourceAccessor (&TcpSocketBase::m_rto)) .AddTraceSource ("RTT", "Last RTT sample", MakeTraceSourceAccessor (&TcpSocketBase::m_lastRtt)) .AddTraceSource ("NextTxSequence", "Next sequence number to send (SND.NXT)", MakeTraceSourceAccessor (&TcpSocketBase::m_nextTxSequence)) .AddTraceSource ("HighestSequence", "Highest sequence number ever sent in socket's life time", MakeTraceSourceAccessor (&TcpSocketBase::m_highTxMark)) .AddTraceSource ("State", "TCP state", MakeTraceSourceAccessor (&TcpSocketBase::m_state)) .AddTraceSource ("RWND", "Remote side's flow control window", MakeTraceSourceAccessor (&TcpSocketBase::m_rWnd)) ; return tid; } TcpSocketBase::TcpSocketBase (void) : m_dupAckCount (0), m_delAckCount (0), m_endPoint (0), m_node (0), m_tcp (0), m_rtt (0), m_nextTxSequence (0), // Change this for non-zero initial sequence number m_highTxMark (0), m_rxBuffer (0), m_txBuffer (0), m_state (CLOSED), m_errno (ERROR_NOTERROR), m_closeNotified (false), m_closeOnEmpty (false), m_shutdownSend (false), m_shutdownRecv (false), m_connected (false), m_segmentSize (0), // For attribute initialization consistency (quiet valgrind) m_rWnd (0) { NS_LOG_FUNCTION (this); } TcpSocketBase::TcpSocketBase (const TcpSocketBase& sock) : TcpSocket (sock), //copy object::m_tid and socket::callbacks m_dupAckCount (sock.m_dupAckCount), m_delAckCount (0), m_delAckMaxCount (sock.m_delAckMaxCount), m_cnCount (sock.m_cnCount), m_delAckTimeout (sock.m_delAckTimeout), m_persistTimeout (sock.m_persistTimeout), m_cnTimeout (sock.m_cnTimeout), m_endPoint (0), m_node (sock.m_node), m_tcp (sock.m_tcp), m_rtt (0), m_nextTxSequence (sock.m_nextTxSequence), m_highTxMark (sock.m_highTxMark), m_rxBuffer (sock.m_rxBuffer), m_txBuffer (sock.m_txBuffer), m_state (sock.m_state), m_errno (sock.m_errno), m_closeNotified (sock.m_closeNotified), m_closeOnEmpty (sock.m_closeOnEmpty), m_shutdownSend (sock.m_shutdownSend), m_shutdownRecv (sock.m_shutdownRecv), m_connected (sock.m_connected), m_segmentSize (sock.m_segmentSize), m_rWnd (sock.m_rWnd) { NS_LOG_FUNCTION (this); NS_LOG_LOGIC ("Invoked the copy constructor"); // Copy the rtt estimator if it is set if (sock.m_rtt) { m_rtt = sock.m_rtt->Copy (); } // Reset all callbacks to null Callback<void, Ptr< Socket > > vPS = MakeNullCallback<void, Ptr<Socket> > (); Callback<void, Ptr<Socket>, const Address &> vPSA = MakeNullCallback<void, Ptr<Socket>, const Address &> (); Callback<void, Ptr<Socket>, uint32_t> vPSUI = MakeNullCallback<void, Ptr<Socket>, uint32_t> (); SetConnectCallback (vPS, vPS); SetDataSentCallback (vPSUI); SetSendCallback (vPSUI); SetRecvCallback (vPS); } TcpSocketBase::~TcpSocketBase (void) { NS_LOG_FUNCTION (this); m_node = 0; if (m_endPoint != 0) { NS_ASSERT (m_tcp != 0); /* * Upon Bind, an Ipv4Endpoint is allocated and set to m_endPoint, and * DestroyCallback is set to TcpSocketBase::Destroy. If we called * m_tcp->DeAllocate, it wil destroy its Ipv4EndpointDemux::DeAllocate, * which in turn destroys my m_endPoint, and in turn invokes * TcpSocketBase::Destroy to nullify m_node, m_endPoint, and m_tcp. */ NS_ASSERT (m_endPoint != 0); m_tcp->DeAllocate (m_endPoint); NS_ASSERT (m_endPoint == 0); } m_tcp = 0; CancelAllTimers (); } /** Associate a node with this TCP socket */ void TcpSocketBase::SetNode (Ptr<Node> node) { m_node = node; } /** Associate the L4 protocol (e.g. mux/demux) with this socket */ void TcpSocketBase::SetTcp (Ptr<TcpL4Protocol> tcp) { m_tcp = tcp; } /** Set an RTT estimator with this socket */ void TcpSocketBase::SetRtt (Ptr<RttEstimator> rtt) { m_rtt = rtt; } /** Inherit from Socket class: Returns error code */ enum Socket::SocketErrno TcpSocketBase::GetErrno (void) const { return m_errno; } /** Inherit from Socket class: Returns socket type, NS3_SOCK_STREAM */ enum Socket::SocketType TcpSocketBase::GetSocketType (void) const { return NS3_SOCK_STREAM; } /** Inherit from Socket class: Returns associated node */ Ptr<Node> TcpSocketBase::GetNode (void) const { NS_LOG_FUNCTION_NOARGS (); return m_node; } /** Inherit from Socket class: Bind socket to an end-point in TcpL4Protocol */ int TcpSocketBase::Bind (void) { NS_LOG_FUNCTION_NOARGS (); m_endPoint = m_tcp->Allocate (); if (0 == m_endPoint) { m_errno = ERROR_ADDRNOTAVAIL; return -1; } return SetupCallback (); } /** Inherit from Socket class: Bind socket (with specific address) to an end-point in TcpL4Protocol */ int TcpSocketBase::Bind (const Address &address) { NS_LOG_FUNCTION (this << address); if (!InetSocketAddress::IsMatchingType (address)) { m_errno = ERROR_INVAL; return -1; } InetSocketAddress transport = InetSocketAddress::ConvertFrom (address); Ipv4Address ipv4 = transport.GetIpv4 (); uint16_t port = transport.GetPort (); if (ipv4 == Ipv4Address::GetAny () && port == 0) { m_endPoint = m_tcp->Allocate (); if (0 == m_endPoint) { m_errno = ERROR_ADDRNOTAVAIL; return -1; } } else if (ipv4 == Ipv4Address::GetAny () && port != 0) { m_endPoint = m_tcp->Allocate (port); if (0 == m_endPoint) { m_errno = ERROR_ADDRINUSE; return -1; } } else if (ipv4 != Ipv4Address::GetAny () && port == 0) { m_endPoint = m_tcp->Allocate (ipv4); if (0 == m_endPoint) { m_errno = ERROR_ADDRNOTAVAIL; return -1; } } else if (ipv4 != Ipv4Address::GetAny () && port != 0) { m_endPoint = m_tcp->Allocate (ipv4, port); if (0 == m_endPoint) { m_errno = ERROR_ADDRINUSE; return -1; } } NS_LOG_LOGIC ("TcpSocketBase " << this << " got an endpoint: " << m_endPoint); return SetupCallback (); } /** Inherit from Socket class: Initiate connection to a remote address:port */ int TcpSocketBase::Connect (const Address & address) { NS_LOG_FUNCTION (this << address); // If haven't do so, Bind() this socket first if (m_endPoint == 0) { if (Bind () == -1) { NS_ASSERT (m_endPoint == 0); return -1; // Bind() failed } NS_ASSERT (m_endPoint != 0); } InetSocketAddress transport = InetSocketAddress::ConvertFrom (address); m_endPoint->SetPeer (transport.GetIpv4 (), transport.GetPort ()); // Get the appropriate local address and port number from the routing protocol and set up endpoint if (SetupEndpoint () != 0) { // Route to destination does not exist return -1; } // DoConnect() will do state-checking and send a SYN packet return DoConnect (); } /** Inherit from Socket class: Listen on the endpoint for an incoming connection */ int TcpSocketBase::Listen (void) { NS_LOG_FUNCTION (this); // Linux quits EINVAL if we're not in CLOSED state, so match what they do if (m_state != CLOSED) { m_errno = ERROR_INVAL; return -1; } // In other cases, set the state to LISTEN and done NS_LOG_INFO ("CLOSED -> LISTEN"); m_state = LISTEN; return 0; } /** Inherit from Socket class: Kill this socket and signal the peer (if any) */ int TcpSocketBase::Close (void) { NS_LOG_FUNCTION (this); // First we check to see if there is any unread rx data // Bug number 426 claims we should send reset in this case. if (m_rxBuffer.Size () != 0) { SendRST (); return 0; } if (m_txBuffer.SizeFromSequence (m_nextTxSequence) > 0) { // App close with pending data must wait until all data transmitted if (m_closeOnEmpty == false) { m_closeOnEmpty = true; NS_LOG_INFO ("Socket " << this << " deferring close, state " << TcpStateName[m_state]); } return 0; } return DoClose (); } /** Inherit from Socket class: Signal a termination of send */ int TcpSocketBase::ShutdownSend (void) { NS_LOG_FUNCTION (this); m_shutdownSend = true; return 0; } /** Inherit from Socket class: Signal a termination of receive */ int TcpSocketBase::ShutdownRecv (void) { NS_LOG_FUNCTION (this); m_shutdownRecv = true; return 0; } /** Inherit from Socket class: Send a packet. Parameter flags is not used. Packet has no TCP header. Invoked by upper-layer application */ int TcpSocketBase::Send (Ptr<Packet> p, uint32_t flags) { NS_LOG_FUNCTION (this << p); NS_ABORT_MSG_IF (flags, "use of flags is not supported in TcpSocketBase::Send()"); if (m_state == ESTABLISHED || m_state == SYN_SENT || m_state == CLOSE_WAIT) { // Store the packet into Tx buffer if (!m_txBuffer.Add (p)) { // TxBuffer overflow, send failed m_errno = ERROR_MSGSIZE; return -1; } // Submit the data to lower layers NS_LOG_LOGIC ("txBufSize=" << m_txBuffer.Size () << " state " << TcpStateName[m_state]); if (m_state == ESTABLISHED || m_state == CLOSE_WAIT) { // Try to send the data out SendPendingData (m_connected); } return p->GetSize (); } else { // Connection not established yet m_errno = ERROR_NOTCONN; return -1; // Send failure } } /** Inherit from Socket class: In TcpSocketBase, it is same as Send() call */ int TcpSocketBase::SendTo (Ptr<Packet> p, uint32_t flags, const Address &address) { return Send (p, flags); // SendTo() and Send() are the same } /** Inherit from Socket class: Return data to upper-layer application. Parameter flags is not used. Data is returned as a packet of size no larger than maxSize */ Ptr<Packet> TcpSocketBase::Recv (uint32_t maxSize, uint32_t flags) { NS_LOG_FUNCTION (this); NS_ABORT_MSG_IF (flags, "use of flags is not supported in TcpSocketBase::Recv()"); if (m_rxBuffer.Size () == 0 && m_state == CLOSE_WAIT) { return Create<Packet> (); // Send EOF on connection close } Ptr<Packet> outPacket = m_rxBuffer.Extract (maxSize); if (outPacket != 0 && outPacket->GetSize () != 0) { SocketAddressTag tag; tag.SetAddress (InetSocketAddress (m_endPoint->GetPeerAddress (), m_endPoint->GetPeerPort ())); outPacket->AddPacketTag (tag); } return outPacket; } /** Inherit from Socket class: Recv and return the remote's address */ Ptr<Packet> TcpSocketBase::RecvFrom (uint32_t maxSize, uint32_t flags, Address &fromAddress) { NS_LOG_FUNCTION (this << maxSize << flags); Ptr<Packet> packet = Recv (maxSize, flags); // Null packet means no data to read, and an empty packet indicates EOF if (packet != 0 && packet->GetSize () != 0) { SocketAddressTag tag; bool found; found = packet->PeekPacketTag (tag); NS_ASSERT (found); //cast found to void , to suppress 'found' set but not used compiler warning //in optimized builds (void) found; fromAddress = tag.GetAddress (); } return packet; } /** Inherit from Socket class: Get the max number of bytes an app can send */ uint32_t TcpSocketBase::GetTxAvailable (void) const { NS_LOG_FUNCTION (this); return m_txBuffer.Available (); } /** Inherit from Socket class: Get the max number of bytes an app can read */ uint32_t TcpSocketBase::GetRxAvailable (void) const { NS_LOG_FUNCTION (this); return m_rxBuffer.Available (); } /** Inherit from Socket class: Return local address:port */ int TcpSocketBase::GetSockName (Address &address) const { NS_LOG_FUNCTION (this); if (m_endPoint != 0) { address = InetSocketAddress (m_endPoint->GetLocalAddress (), m_endPoint->GetLocalPort ()); } else { // It is possible to call this method on a socket without a name // in which case, behavior is unspecified address = InetSocketAddress (Ipv4Address::GetZero (), 0); } return 0; } /** Inherit from Socket class: Bind this socket to the specified NetDevice */ void TcpSocketBase::BindToNetDevice (Ptr<NetDevice> netdevice) { NS_LOG_FUNCTION (netdevice); Socket::BindToNetDevice (netdevice); // Includes sanity check if (m_endPoint == 0) { if (Bind () == -1) { NS_ASSERT (m_endPoint == 0); return; } NS_ASSERT (m_endPoint != 0); } m_endPoint->BindToNetDevice (netdevice); return; } /** Clean up after Bind. Set up callback functions in the end-point. */ int TcpSocketBase::SetupCallback (void) { NS_LOG_FUNCTION (this); if (m_endPoint == 0) { return -1; } m_endPoint->SetRxCallback (MakeCallback (&TcpSocketBase::ForwardUp, Ptr<TcpSocketBase> (this))); m_endPoint->SetDestroyCallback (MakeCallback (&TcpSocketBase::Destroy, Ptr<TcpSocketBase> (this))); return 0; } /** Perform the real connection tasks: Send SYN if allowed, RST if invalid */ int TcpSocketBase::DoConnect (void) { NS_LOG_FUNCTION (this); // A new connection is allowed only if this socket does not have a connection if (m_state == CLOSED || m_state == LISTEN || m_state == SYN_SENT || m_state == LAST_ACK || m_state == CLOSE_WAIT) { // send a SYN packet and change state into SYN_SENT SendEmptyPacket (TcpHeader::SYN); NS_LOG_INFO (TcpStateName[m_state] << " -> SYN_SENT"); m_state = SYN_SENT; } else if (m_state != TIME_WAIT) { // In states SYN_RCVD, ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, and CLOSING, an connection // exists. We send RST, tear down everything, and close this socket. CloseAndNotify (); SendRST (); } return 0; } /** Do the action to close the socket. Usually send a packet with appropriate flags depended on the current m_state. */ int TcpSocketBase::DoClose (void) { NS_LOG_FUNCTION (this); switch (m_state) { case SYN_RCVD: case ESTABLISHED: // send FIN to close the peer SendEmptyPacket (TcpHeader::FIN); NS_LOG_INFO ("ESTABLISHED -> FIN_WAIT_1"); m_state = FIN_WAIT_1; break; case CLOSE_WAIT: // send FIN+ACK to close the peer SendEmptyPacket (TcpHeader::FIN | TcpHeader::ACK); NS_LOG_INFO ("CLOSE_WAIT -> LAST_ACK"); m_state = LAST_ACK; break; case SYN_SENT: case CLOSING: // Send RST if application closes in SYN_SENT and CLOSING CloseAndNotify (); SendRST (); break; case LISTEN: case LAST_ACK: // In these three states, move to CLOSED and tear down the end point CloseAndNotify (); break; case CLOSED: case FIN_WAIT_1: case FIN_WAIT_2: case TIME_WAIT: default: /* mute compiler */ // Do nothing in these four states break; } return 0; } /** Peacefully close the socket by notifying the upper layer and deallocate end point */ void TcpSocketBase::CloseAndNotify (void) { NS_LOG_FUNCTION (this); if (!m_closeNotified) NotifyNormalClose (); m_closeNotified = true; NS_LOG_INFO (TcpStateName[m_state] << " -> CLOSED"); m_state = CLOSED; DeallocateEndPoint (); } /** Tell if a sequence number is out side the range that my rx buffer can accpet */ bool TcpSocketBase::OutOfRange (SequenceNumber32 s) const { if (m_state == LISTEN || m_state == SYN_SENT || m_state == SYN_RCVD) { // Rx buffer in these states are not initialized. return false; } if (m_state == LAST_ACK || m_state == CLOSING) { // In LAST_ACK and CLOSING states, it only wait for an ACK and the // sequence number must equals to m_rxBuffer.NextRxSequence () return (m_rxBuffer.NextRxSequence () != s); }; // In all other cases, check if the sequence number is in range return (m_rxBuffer.MaxRxSequence () < s || m_rxBuffer.NextRxSequence () > s); } /** Function called by the L3 protocol when it received a packet to pass on to the TCP. This function is registered as the "RxCallback" function in SetupCallback(), which invoked by Bind(), and CompleteFork() */ void TcpSocketBase::ForwardUp (Ptr<Packet> packet, Ipv4Header header, uint16_t port, Ptr<Ipv4Interface> incomingInterface) { NS_LOG_LOGIC ("Socket " << this << " forward up " << m_endPoint->GetPeerAddress () << ":" << m_endPoint->GetPeerPort () << " to " << m_endPoint->GetLocalAddress () << ":" << m_endPoint->GetLocalPort ()); Address fromAddress = InetSocketAddress (header.GetSource (), port); Address toAddress = InetSocketAddress (header.GetDestination (), m_endPoint->GetLocalPort ()); // Peel off TCP header and do validity checking TcpHeader tcpHeader; packet->RemoveHeader (tcpHeader); if (tcpHeader.GetFlags () & TcpHeader::ACK) { EstimateRtt (tcpHeader); } // Update Rx window size, i.e. the flow control window if (m_rWnd.Get () == 0 && tcpHeader.GetWindowSize () != 0) { // persist probes end NS_LOG_LOGIC (this << " Leaving zerowindow persist state"); m_persistEvent.Cancel (); } m_rWnd = tcpHeader.GetWindowSize (); // Discard out of range packets if (OutOfRange (tcpHeader.GetSequenceNumber ())) { NS_LOG_LOGIC ("At state " << TcpStateName[m_state] << " received packet of seq " << tcpHeader.GetSequenceNumber () << " out of range [" << m_rxBuffer.NextRxSequence () << ":" << m_rxBuffer.MaxRxSequence () << "]"); return; } // TCP state machine code in different process functions // C.f.: tcp_rcv_state_process() in tcp_input.c in Linux kernel switch (m_state) { case ESTABLISHED: ProcessEstablished (packet, tcpHeader); break; case LISTEN: ProcessListen (packet, tcpHeader, fromAddress, toAddress); break; case TIME_WAIT: // Do nothing break; case CLOSED: // Send RST if the incoming packet is not a RST if ((tcpHeader.GetFlags () & ~(TcpHeader::PSH | TcpHeader::URG)) != TcpHeader::RST) { SendRST (); } break; case SYN_SENT: ProcessSynSent (packet, tcpHeader); break; case SYN_RCVD: ProcessSynRcvd (packet, tcpHeader, fromAddress, toAddress); break; case FIN_WAIT_1: case FIN_WAIT_2: case CLOSE_WAIT: ProcessWait (packet, tcpHeader); break; case CLOSING: ProcessClosing (packet, tcpHeader); break; case LAST_ACK: ProcessLastAck (packet, tcpHeader); break; default: // mute compiler break; } } /** Received a packet upon ESTABLISHED state. This function is mimicking the role of tcp_rcv_established() in tcp_input.c in Linux kernel. */ void TcpSocketBase::ProcessEstablished (Ptr<Packet> packet, const TcpHeader& tcpHeader) { NS_LOG_FUNCTION (this << tcpHeader); // Extract the flags. PSH and URG are not honoured. uint8_t tcpflags = tcpHeader.GetFlags () & ~(TcpHeader::PSH | TcpHeader::URG); // Different flags are different events if (tcpflags == TcpHeader::ACK) { ReceivedAck (packet, tcpHeader); } else if (tcpflags == TcpHeader::SYN) { // Received SYN, old NS-3 behaviour is to set state to SYN_RCVD and // respond with a SYN+ACK. But it is not a legal state transition as of // RFC793. Thus this is ignored. } else if (tcpflags == (TcpHeader::SYN | TcpHeader::ACK)) { // No action for received SYN+ACK, it is probably a duplicated packet } else if (tcpflags == TcpHeader::FIN || tcpflags == (TcpHeader::FIN | TcpHeader::ACK)) { // Received FIN or FIN+ACK, bring down this socket nicely PeerClose (packet, tcpHeader); } else if (tcpflags == 0) { // No flags means there is only data ReceivedData (packet, tcpHeader); if (m_rxBuffer.Finished ()) { PeerClose (packet, tcpHeader); } } else { // Received RST or the TCP flags is invalid, in either case, terminate this socket CloseAndNotify (); if (tcpflags != TcpHeader::RST) { // this must be an invalid flag, send reset NS_LOG_LOGIC ("Illegal flag " << tcpflags << " received. Reset packet is sent."); SendRST (); } } } /** Process the newly received ACK */ void TcpSocketBase::ReceivedAck (Ptr<Packet> packet, const TcpHeader& tcpHeader) { NS_LOG_FUNCTION (this << tcpHeader); // Received ACK. Compare the ACK number against highest unacked seqno if (0 == (tcpHeader.GetFlags () & TcpHeader::ACK)) { // Ignore if no ACK flag } else if (tcpHeader.GetAckNumber () < m_txBuffer.HeadSequence ()) { // Case 1: Old ACK, ignored. NS_LOG_LOGIC ("Ignored ack of " << tcpHeader.GetAckNumber ()); } else if (tcpHeader.GetAckNumber () == m_txBuffer.HeadSequence ()) { // Case 2: Potentially a duplicated ACK if (tcpHeader.GetAckNumber () < m_nextTxSequence) { NS_LOG_LOGIC ("Dupack of " << tcpHeader.GetAckNumber ()); DupAck (tcpHeader, ++m_dupAckCount); } // otherwise, the ACK is precisely equal to the nextTxSequence NS_ASSERT (tcpHeader.GetAckNumber () <= m_nextTxSequence); } else if (tcpHeader.GetAckNumber () > m_txBuffer.HeadSequence ()) { // Case 3: New ACK, reset m_dupAckCount and update m_txBuffer NS_LOG_LOGIC ("New ack of " << tcpHeader.GetAckNumber ()); NewAck (tcpHeader.GetAckNumber ()); m_dupAckCount = 0; } // If there is any data piggybacked, store it into m_rxBuffer if (packet->GetSize () > 0) { ReceivedData (packet, tcpHeader); } } /** Received a packet upon LISTEN state. */ void TcpSocketBase::ProcessListen (Ptr<Packet> packet, const TcpHeader& tcpHeader, const Address& fromAddress, const Address& toAddress) { NS_LOG_FUNCTION (this << tcpHeader); // Extract the flags. PSH and URG are not honoured. uint8_t tcpflags = tcpHeader.GetFlags () & ~(TcpHeader::PSH | TcpHeader::URG); // Fork a socket if received a SYN. Do nothing otherwise. // C.f.: the LISTEN part in tcp_v4_do_rcv() in tcp_ipv4.c in Linux kernel if (tcpflags != TcpHeader::SYN) return; // Call socket's notify function to let the server app know we got a SYN // If the server app refuses the connection, do nothing if (!NotifyConnectionRequest (fromAddress)) return; // Clone the socket, simulate fork Ptr<TcpSocketBase> newSock = Fork (); NS_LOG_LOGIC ("Cloned a TcpSocketBase " << newSock); Simulator::ScheduleNow (&TcpSocketBase::CompleteFork, newSock, packet, tcpHeader, fromAddress, toAddress); } /** Received a packet upon SYN_SENT */ void TcpSocketBase::ProcessSynSent (Ptr<Packet> packet, const TcpHeader& tcpHeader) { NS_LOG_FUNCTION (this << tcpHeader); // Extract the flags. PSH and URG are not honoured. uint8_t tcpflags = tcpHeader.GetFlags () & ~(TcpHeader::PSH | TcpHeader::URG); if (tcpflags == 0) { // Bare data, accept it and move to ESTABLISHED state. This is not a normal behaviour. Remove this? NS_LOG_INFO ("SYN_SENT -> ESTABLISHED"); m_state = ESTABLISHED; m_connected = true; m_retxEvent.Cancel (); ReceivedData (packet, tcpHeader); Simulator::ScheduleNow (&TcpSocketBase::ConnectionSucceeded, this); } else if (tcpflags == TcpHeader::ACK) { // Ignore ACK in SYN_SENT } else if (tcpflags == TcpHeader::SYN) { // Received SYN, move to SYN_RCVD state and respond with SYN+ACK NS_LOG_INFO ("SYN_SENT -> SYN_RCVD"); m_state = SYN_RCVD; m_rxBuffer.SetNextRxSequence (tcpHeader.GetSequenceNumber () + SequenceNumber32 (1)); SendEmptyPacket (TcpHeader::SYN | TcpHeader::ACK); } else if (tcpflags == (TcpHeader::SYN | TcpHeader::ACK) && m_nextTxSequence + SequenceNumber32 (1) == tcpHeader.GetAckNumber ()) { // Handshake completed NS_LOG_INFO ("SYN_SENT -> ESTABLISHED"); m_state = ESTABLISHED; m_connected = true; m_retxEvent.Cancel (); m_rxBuffer.SetNextRxSequence (tcpHeader.GetSequenceNumber () + SequenceNumber32 (1)); m_highTxMark = ++m_nextTxSequence; m_txBuffer.SetHeadSequence (m_nextTxSequence); SendEmptyPacket (TcpHeader::ACK); if (GetTxAvailable () > 0) { NotifySend (GetTxAvailable ()); } SendPendingData (m_connected); Simulator::ScheduleNow (&TcpSocketBase::ConnectionSucceeded, this); } else { // Other in-sequence input CloseAndNotify (); if (tcpflags != TcpHeader::RST) { // When (1) rx of FIN+ACK; (2) rx of FIN; (3) rx of bad flags NS_LOG_LOGIC ("Illegal flag " << tcpflags << " received. Reset packet is sent."); SendRST (); } } } /** Received a packet upon SYN_RCVD */ void TcpSocketBase::ProcessSynRcvd (Ptr<Packet> packet, const TcpHeader& tcpHeader, const Address& fromAddress, const Address& toAddress) { NS_LOG_FUNCTION (this << tcpHeader); // Extract the flags. PSH and URG are not honoured. uint8_t tcpflags = tcpHeader.GetFlags () & ~(TcpHeader::PSH | TcpHeader::URG); if (tcpflags == 0 || (tcpflags == TcpHeader::ACK && m_nextTxSequence + SequenceNumber32 (1) == tcpHeader.GetAckNumber ())) { // If it is bare data, accept it and move to ESTABLISHED state. This is // possibly due to ACK lost in 3WHS. If in-sequence ACK is received, the // handshake is completed nicely. NS_LOG_INFO ("SYN_RCVD -> ESTABLISHED"); m_state = ESTABLISHED; m_connected = true; m_retxEvent.Cancel (); m_highTxMark = ++m_nextTxSequence; m_txBuffer.SetHeadSequence (m_nextTxSequence); m_endPoint->SetPeer (m_endPoint->GetPeerAddress (), m_endPoint->GetPeerPort ()); // Always respond to first data packet to speed up the connection. // Remove to get the behaviour of old NS-3 code. m_delAckCount = m_delAckMaxCount; ReceivedAck (packet, tcpHeader); NotifyNewConnectionCreated (this, fromAddress); } else if (tcpflags == TcpHeader::SYN) { // Probably the peer lost my SYN+ACK m_rxBuffer.SetNextRxSequence (tcpHeader.GetSequenceNumber () + SequenceNumber32 (1)); SendEmptyPacket (TcpHeader::SYN | TcpHeader::ACK); } else if (tcpflags == (TcpHeader::FIN | TcpHeader::ACK)) { if (tcpHeader.GetSequenceNumber () == m_rxBuffer.NextRxSequence ()) { // In-sequence FIN before connection complete. Set up connection and close. m_connected = true; m_retxEvent.Cancel (); m_highTxMark = ++m_nextTxSequence; m_txBuffer.SetHeadSequence (m_nextTxSequence); m_endPoint->SetPeer (m_endPoint->GetPeerAddress (), m_endPoint->GetPeerPort ()); PeerClose (packet, tcpHeader); } } else { // Other in-sequence input CloseAndNotify (); if (tcpflags != TcpHeader::RST) { // When (1) rx of SYN+ACK; (2) rx of FIN; (3) rx of bad flags NS_LOG_LOGIC ("Illegal flag " << tcpflags << " received. Reset packet is sent."); SendRST (); } } } /** Received a packet upon CLOSE_WAIT, FIN_WAIT_1, or FIN_WAIT_2 states */ void TcpSocketBase::ProcessWait (Ptr<Packet> packet, const TcpHeader& tcpHeader) { NS_LOG_FUNCTION (this << tcpHeader); // Extract the flags. PSH and URG are not honoured. uint8_t tcpflags = tcpHeader.GetFlags () & ~(TcpHeader::PSH | TcpHeader::URG); if (packet->GetSize () > 0) { // Bare data, accept it ReceivedData (packet, tcpHeader); } else if (tcpflags == TcpHeader::ACK) { // Process the ACK, and if in FIN_WAIT_1, conditionally move to FIN_WAIT_2 ReceivedAck (packet, tcpHeader); if (m_state == FIN_WAIT_1 && m_txBuffer.Size () == 0 && tcpHeader.GetAckNumber () == m_highTxMark + SequenceNumber32 (1)) { // This ACK corresponds to the FIN sent NS_LOG_INFO ("FIN_WAIT_1 -> FIN_WAIT_2"); m_state = FIN_WAIT_2; } } else if (tcpflags == TcpHeader::FIN || tcpflags == (TcpHeader::FIN | TcpHeader::ACK)) { // Got FIN, respond with ACK and move to next state if (tcpflags & TcpHeader::ACK) { // Process the ACK first ReceivedAck (packet, tcpHeader); } m_rxBuffer.SetFinSequence (tcpHeader.GetSequenceNumber ()); } else if (tcpflags == TcpHeader::SYN || tcpflags == (TcpHeader::SYN | TcpHeader::ACK)) { // Duplicated SYN or SYN+ACK, possibly due to spurious retransmission return; } else { // This is a RST or bad flags CloseAndNotify (); if (tcpflags != TcpHeader::RST) { NS_LOG_LOGIC ("Illegal flag " << tcpflags << " received. Reset packet is sent."); SendRST (); } return; } // Check if the close responder sent an in-sequence FIN, if so, respond ACK if ((m_state == FIN_WAIT_1 || m_state == FIN_WAIT_2) && m_rxBuffer.Finished ()) { if (m_state == FIN_WAIT_1) { NS_LOG_INFO ("FIN_WAIT_1 -> CLOSING"); m_state = CLOSING; if (m_txBuffer.Size () == 0 && tcpHeader.GetAckNumber () == m_highTxMark + SequenceNumber32 (1)) { // This ACK corresponds to the FIN sent NS_LOG_INFO ("CLOSING -> TIME_WAIT"); m_state = TIME_WAIT; CancelAllTimers (); } } else if (m_state == FIN_WAIT_2) { NS_LOG_INFO ("FIN_WAIT_2 -> TIME_WAIT"); m_state = TIME_WAIT; CancelAllTimers (); // TODO: In TIME_WAIT, we supposed to move to CLOSED after 2*MSL time // but this move is not yet implemeneted. Is this necessary? }; SendEmptyPacket (TcpHeader::ACK); if (!m_shutdownRecv) NotifyDataRecv (); } } /** Received a packet upon CLOSING */ void TcpSocketBase::ProcessClosing (Ptr<Packet> packet, const TcpHeader& tcpHeader) { NS_LOG_FUNCTION (this << tcpHeader); // Extract the flags. PSH and URG are not honoured. uint8_t tcpflags = tcpHeader.GetFlags () & ~(TcpHeader::PSH | TcpHeader::URG); if (tcpflags == TcpHeader::ACK) { if (tcpHeader.GetSequenceNumber () == m_rxBuffer.NextRxSequence ()) { // This ACK corresponds to the FIN sent NS_LOG_INFO ("CLOSING -> TIME_WAIT"); m_state = TIME_WAIT; CancelAllTimers (); // TODO: In TIME_WAIT, we supposed to move to CLOSED after 2*MSL time // but this move is not yet implemeneted. Is this necessary? } } else { // CLOSING state means simultaneous close, i.e. no one is sending data to // anyone. If anything other than ACK is received, respond with a reset. CloseAndNotify (); if (tcpflags == TcpHeader::FIN || tcpflags == (TcpHeader::FIN | TcpHeader::ACK)) { // FIN from the peer as well. We can close immediately. SendEmptyPacket (TcpHeader::ACK); } else if (tcpflags != TcpHeader::RST) { // Receive of SYN or SYN+ACK or bad flags or pure data NS_LOG_LOGIC ("Illegal flag " << tcpflags << " received. Reset packet is sent."); SendRST (); } } } /** Received a packet upon LAST_ACK */ void TcpSocketBase::ProcessLastAck (Ptr<Packet> packet, const TcpHeader& tcpHeader) { NS_LOG_FUNCTION (this << tcpHeader); // Extract the flags. PSH and URG are not honoured. uint8_t tcpflags = tcpHeader.GetFlags () & ~(TcpHeader::PSH | TcpHeader::URG); if (tcpflags == 0) { ReceivedData (packet, tcpHeader); } else if (tcpflags == TcpHeader::ACK) { if (tcpHeader.GetSequenceNumber () == m_rxBuffer.NextRxSequence ()) { // This ACK corresponds to the FIN sent. This socket closed peacefully. CloseAndNotify (); } } else if (tcpflags == TcpHeader::FIN) { // Received FIN again, the peer probably lost the FIN+ACK SendEmptyPacket (TcpHeader::FIN | TcpHeader::ACK); } else if (tcpflags == (TcpHeader::FIN | TcpHeader::ACK) || tcpflags == TcpHeader::RST) { CloseAndNotify (); } else { // Received a SYN or SYN+ACK or bad flags CloseAndNotify (); NS_LOG_LOGIC ("Illegal flag " << tcpflags << " received. Reset packet is sent."); SendRST (); } } /** Peer sent me a FIN. Remember its sequence in rx buffer. */ void TcpSocketBase::PeerClose (Ptr<Packet> p, const TcpHeader& tcpHeader) { NS_LOG_FUNCTION (this << tcpHeader); // Ignore all out of range packets if (tcpHeader.GetSequenceNumber () < m_rxBuffer.NextRxSequence () || tcpHeader.GetSequenceNumber () > m_rxBuffer.MaxRxSequence ()) { return; }; // For any case, remember the FIN position in rx buffer first m_rxBuffer.SetFinSequence (tcpHeader.GetSequenceNumber () + SequenceNumber32 (p->GetSize ())); NS_LOG_LOGIC ("Accepted FIN at seq " << tcpHeader.GetSequenceNumber () + SequenceNumber32 (p->GetSize ())); // If there is any piggybacked data, process it if (p->GetSize ()) { ReceivedData (p, tcpHeader); } // Return if FIN is out of sequence, otherwise move to CLOSE_WAIT state by DoPeerClose if (!m_rxBuffer.Finished ()) { return; }; // Simultaneous close: Application invoked Close() when we are processing this FIN packet if (m_state == FIN_WAIT_1) { NS_LOG_INFO ("FIN_WAIT_1 -> CLOSING"); m_state = CLOSING; return; } DoPeerClose (); // Change state, respond with ACK } /** Received a in-sequence FIN. Close down this socket. */ void TcpSocketBase::DoPeerClose (void) { NS_ASSERT (m_state == ESTABLISHED || m_state == SYN_RCVD); // Move the state to CLOSE_WAIT NS_LOG_INFO (TcpStateName[m_state] << " -> CLOSE_WAIT"); m_state = CLOSE_WAIT; if (!m_closeNotified) { // The normal behaviour for an application is that, when the peer sent a in-sequence // FIN, the app should prepare to close. The app has two choices at this point: either // respond with ShutdownSend() call to declare that it has nothing more to send and // the socket can be closed immediately; or remember the peer's close request, wait // until all its existing data are pushed into the TCP socket, then call Close() // explicitly. NS_LOG_LOGIC ("TCP " << this << " calling NotifyNormalClose"); if (!m_closeNotified) NotifyNormalClose (); m_closeNotified = true; } if (m_shutdownSend) { // The application declares that it would not sent any more, close this socket Close (); } else { // Need to ack, the application will close later SendEmptyPacket (TcpHeader::ACK); } if (m_state == LAST_ACK) { NS_LOG_LOGIC ("TcpSocketBase " << this << " scheduling LATO1"); m_lastAckEvent = Simulator::Schedule (m_rtt->RetransmitTimeout (), &TcpSocketBase::LastAckTimeout, this); } } /** Kill this socket. This is a callback function configured to m_endpoint in SetupCallback(), invoked when the endpoint is destroyed. */ void TcpSocketBase::Destroy (void) { NS_LOG_FUNCTION (this); m_node = 0; m_endPoint = 0; m_tcp = 0; NS_LOG_LOGIC (this << " Cancelled ReTxTimeout event which was set to expire at " << (Simulator::Now () + Simulator::GetDelayLeft (m_retxEvent)).GetSeconds ()); CancelAllTimers (); } /** Send an empty packet with specified TCP flags */ void TcpSocketBase::SendEmptyPacket (uint8_t flags) { NS_LOG_FUNCTION (this << (uint32_t)flags); Ptr<Packet> p = Create<Packet> (); TcpHeader header; SequenceNumber32 s = m_nextTxSequence; if (m_endPoint == 0) { NS_LOG_WARN ("Failed to send empty packet due to null endpoint"); return; } if (flags & TcpHeader::FIN) { flags |= TcpHeader::ACK; } else if (m_state == FIN_WAIT_1 || m_state == LAST_ACK || m_state == CLOSING) { ++s; } header.SetFlags (flags); header.SetSequenceNumber (s); header.SetAckNumber (m_rxBuffer.NextRxSequence ()); header.SetSourcePort (m_endPoint->GetLocalPort ()); header.SetDestinationPort (m_endPoint->GetPeerPort ()); header.SetWindowSize (AdvertisedWindowSize ()); m_tcp->SendPacket (p, header, m_endPoint->GetLocalAddress (), m_endPoint->GetPeerAddress (), m_boundnetdevice); m_rto = m_rtt->RetransmitTimeout (); bool hasSyn = flags & TcpHeader::SYN; bool hasFin = flags & TcpHeader::FIN; bool isAck = flags == TcpHeader::ACK; if (hasSyn) { // Exponential backoff of connection time out m_rto = m_cnTimeout; m_cnTimeout = m_cnTimeout + m_cnTimeout; m_cnCount--; } if (flags & TcpHeader::ACK) { // If sending an ACK, cancel the delay ACK as well m_delAckEvent.Cancel (); m_delAckCount = 0; } if (m_retxEvent.IsExpired () && (hasSyn || hasFin) && !isAck ) { // Retransmit SYN / SYN+ACK / FIN / FIN+ACK to guard against lost NS_LOG_LOGIC ("Schedule retransmission timeout at time " << Simulator::Now ().GetSeconds () << " to expire at time " << (Simulator::Now () + m_rto.Get ()).GetSeconds ()); m_retxEvent = Simulator::Schedule (m_rto, &TcpSocketBase::SendEmptyPacket, this, flags); } } /** This function closes the endpoint completely. Called upon RST_TX action. */ void TcpSocketBase::SendRST (void) { NS_LOG_FUNCTION (this); SendEmptyPacket (TcpHeader::RST); NotifyErrorClose (); DeallocateEndPoint (); } /** Deallocate the end point the cancel all the timers */ void TcpSocketBase::DeallocateEndPoint (void) { if (m_endPoint != 0) { m_endPoint->SetDestroyCallback (MakeNullCallback<void> ()); m_tcp->DeAllocate (m_endPoint); m_endPoint = 0; CancelAllTimers (); } } /** Configure the endpoint to a local address. Called by Connect() if Bind() didn't specify one. */ int TcpSocketBase::SetupEndpoint () { NS_LOG_FUNCTION (this); Ptr<Ipv4> ipv4 = m_node->GetObject<Ipv4> (); NS_ASSERT (ipv4 != 0); if (ipv4->GetRoutingProtocol () == 0) { NS_FATAL_ERROR ("No Ipv4RoutingProtocol in the node"); } // Create a dummy packet, then ask the routing function for the best output // interface's address Ipv4Header header; header.SetDestination (m_endPoint->GetPeerAddress ()); Socket::SocketErrno errno_; Ptr<Ipv4Route> route; Ptr<NetDevice> oif = m_boundnetdevice; route = ipv4->GetRoutingProtocol ()->RouteOutput (Ptr<Packet> (), header, oif, errno_); if (route == 0) { NS_LOG_LOGIC ("Route to " << m_endPoint->GetPeerAddress () << " does not exist"); NS_LOG_ERROR (errno_); m_errno = errno_; return -1; } NS_LOG_LOGIC ("Route exists"); m_endPoint->SetLocalAddress (route->GetSource ()); return 0; } /** This function is called only if a SYN received in LISTEN state. After TcpSocketBase cloned, allocate a new end point to handle the incoming connection and send a SYN+ACK to complete the handshake. */ void TcpSocketBase::CompleteFork (Ptr<Packet> p, const TcpHeader& h, const Address& fromAddress, const Address& toAddress) { // Get port and address from peer (connecting host) m_endPoint = m_tcp->Allocate (InetSocketAddress::ConvertFrom (toAddress).GetIpv4 (), InetSocketAddress::ConvertFrom (toAddress).GetPort (), InetSocketAddress::ConvertFrom (fromAddress).GetIpv4 (), InetSocketAddress::ConvertFrom (fromAddress).GetPort ()); // Change the cloned socket from LISTEN state to SYN_RCVD NS_LOG_INFO ("LISTEN -> SYN_RCVD"); m_state = SYN_RCVD; SetupCallback (); // Set the sequence number and send SYN+ACK m_rxBuffer.SetNextRxSequence (h.GetSequenceNumber () + SequenceNumber32 (1)); SendEmptyPacket (TcpHeader::SYN | TcpHeader::ACK); } void TcpSocketBase::ConnectionSucceeded () { // Wrapper to protected function NotifyConnectionSucceeded() so that it can // be called as a scheduled event NotifyConnectionSucceeded (); } // Send as much pending data as possible according to the Tx window. Note that // this function did not implement the PSH flag bool TcpSocketBase::SendPendingData (bool withAck) { NS_LOG_FUNCTION (this << withAck); if (m_txBuffer.Size () == 0) return false; // Nothing to send if (m_endPoint == 0) { NS_LOG_INFO ("TcpSocketBase::SendPendingData: No endpoint; m_shutdownSend=" << m_shutdownSend); return false; // Is this the right way to handle this condition? } uint32_t nPacketsSent = 0; while (m_txBuffer.SizeFromSequence (m_nextTxSequence)) { uint32_t w = AvailableWindow (); // Get available window size NS_LOG_LOGIC ("TcpSocketBase " << this << " SendPendingData" << " w " << w << " rxwin " << m_rWnd << " segsize " << m_segmentSize << " nextTxSeq " << m_nextTxSequence << " highestRxAck " << m_txBuffer.HeadSequence () << " pd->Size " << m_txBuffer.Size () << " pd->SFS " << m_txBuffer.SizeFromSequence (m_nextTxSequence)); // Quit if send disallowed if (m_shutdownSend) { m_errno = ERROR_SHUTDOWN; return false; } // Stop sending if we need to wait for a larger Tx window if (w < m_segmentSize && m_txBuffer.SizeFromSequence (m_nextTxSequence) > w) { break; // No more } uint32_t s = std::min (w, m_segmentSize); // Send no more than window Ptr<Packet> p = m_txBuffer.CopyFromSequence (s, m_nextTxSequence); NS_LOG_LOGIC ("TcpSocketBase " << this << " SendPendingData" << " txseq " << m_nextTxSequence << " s " << s << " datasize " << p->GetSize ()); uint8_t flags = 0; uint32_t sz = p->GetSize (); // Size of packet uint32_t remainingData = m_txBuffer.SizeFromSequence (m_nextTxSequence + SequenceNumber32 (sz)); if (m_closeOnEmpty && (remainingData == 0)) { flags = TcpHeader::FIN; if (m_state == ESTABLISHED) { // On active close: I am the first one to send FIN NS_LOG_INFO ("ESTABLISHED -> FIN_WAIT_1"); m_state = FIN_WAIT_1; } else { // On passive close: Peer sent me FIN already NS_LOG_INFO ("CLOSE_WAIT -> LAST_ACK"); m_state = LAST_ACK; } } if (withAck) { flags |= TcpHeader::ACK; } TcpHeader header; header.SetFlags (flags); header.SetSequenceNumber (m_nextTxSequence); header.SetAckNumber (m_rxBuffer.NextRxSequence ()); header.SetSourcePort (m_endPoint->GetLocalPort ()); header.SetDestinationPort (m_endPoint->GetPeerPort ()); header.SetWindowSize (AdvertisedWindowSize ()); if (m_retxEvent.IsExpired () ) { // Schedule retransmit m_rto = m_rtt->RetransmitTimeout (); NS_LOG_LOGIC (this << " SendPendingData Schedule ReTxTimeout at time " << Simulator::Now ().GetSeconds () << " to expire at time " << (Simulator::Now () + m_rto.Get ()).GetSeconds () ); m_retxEvent = Simulator::Schedule (m_rto, &TcpSocketBase::ReTxTimeout, this); } NS_LOG_LOGIC ("Send packet via TcpL4Protocol with flags 0x" << std::hex << static_cast<uint32_t> (flags) << std::dec); m_tcp->SendPacket (p, header, m_endPoint->GetLocalAddress (), m_endPoint->GetPeerAddress (), m_boundnetdevice); m_rtt->SentSeq (m_nextTxSequence, sz); // notify the RTT // Notify the application of the data being sent Simulator::ScheduleNow (&TcpSocketBase::NotifyDataSent, this, sz); nPacketsSent++; // Count sent this loop m_nextTxSequence += sz; // Advance next tx sequence // Update highTxMark m_highTxMark = std::max (m_nextTxSequence, m_highTxMark); } NS_LOG_LOGIC ("SendPendingData sent " << nPacketsSent << " packets"); return (nPacketsSent > 0); } uint32_t TcpSocketBase::UnAckDataCount () { NS_LOG_FUNCTION (this); return m_nextTxSequence.Get () - m_txBuffer.HeadSequence (); } uint32_t TcpSocketBase::BytesInFlight () { NS_LOG_FUNCTION (this); return m_highTxMark.Get () - m_txBuffer.HeadSequence (); } uint32_t TcpSocketBase::Window () { NS_LOG_FUNCTION (this); return m_rWnd; } uint32_t TcpSocketBase::AvailableWindow () { NS_LOG_FUNCTION_NOARGS (); uint32_t unack = UnAckDataCount (); // Number of outstanding bytes uint32_t win = Window (); // Number of bytes allowed to be outstanding NS_LOG_LOGIC ("UnAckCount=" << unack << ", Win=" << win); return (win < unack) ? 0 : (win - unack); } uint16_t TcpSocketBase::AdvertisedWindowSize () { uint32_t max = 0xffff; return std::min (m_rxBuffer.MaxBufferSize () - m_rxBuffer.Size (), max); } // Receipt of new packet, put into Rx buffer void TcpSocketBase::ReceivedData (Ptr<Packet> p, const TcpHeader& tcpHeader) { NS_LOG_FUNCTION (this << tcpHeader); NS_LOG_LOGIC ("seq " << tcpHeader.GetSequenceNumber () << " ack " << tcpHeader.GetAckNumber () << " pkt size " << p->GetSize () ); // Put into Rx buffer SequenceNumber32 expectedSeq = m_rxBuffer.NextRxSequence (); if (!m_rxBuffer.Add (p, tcpHeader)) { // Insert failed: No data or RX buffer full SendEmptyPacket (TcpHeader::ACK); return; } // Now send a new ACK packet acknowledging all received and delivered data if (tcpHeader.GetSequenceNumber () > expectedSeq) { // Out of sequence packet: Always ACK SendEmptyPacket (TcpHeader::ACK); } else { // In-sequence packet: ACK if delayed ack count allows if (++m_delAckCount >= m_delAckMaxCount) { m_delAckEvent.Cancel (); m_delAckCount = 0; SendEmptyPacket (TcpHeader::ACK); } else if (m_delAckEvent.IsExpired ()) { m_delAckEvent = Simulator::Schedule (m_delAckTimeout, &TcpSocketBase::DelAckTimeout, this); } } // Notify app to receive if necessary if (expectedSeq < m_rxBuffer.NextRxSequence ()) { // NextRxSeq advanced, we have something to send to the app if (!m_shutdownRecv) NotifyDataRecv (); // Handle exceptions if (m_closeNotified) { NS_LOG_WARN ("Why TCP " << this << " got data after close notification?"); } // If we received FIN before and now completed all "holes" in rx buffer, // invoke peer close procedure if (m_rxBuffer.Finished () && (tcpHeader.GetFlags () & TcpHeader::FIN) == 0) { DoPeerClose (); } } } /** Called by ForwardUp() to estimate RTT */ void TcpSocketBase::EstimateRtt (const TcpHeader& tcpHeader) { // Use m_rtt for the estimation. Note, RTT of duplicated acknowledgement // (which should be ignored) is handled by m_rtt. Once timestamp option // is implemented, this function would be more elaborated. m_rtt->AckSeq (tcpHeader.GetAckNumber () ); }; // Called by the ReceivedAck() when new ACK received and by ProcessSynRcvd() // when the three-way handshake completed. This cancels retransmission timer // and advances Tx window void TcpSocketBase::NewAck (SequenceNumber32 const& ack) { NS_LOG_FUNCTION (this << ack); if (m_state != SYN_RCVD) { // Set RTO unless the ACK is received in SYN_RCVD state NS_LOG_LOGIC (this << " Cancelled ReTxTimeout event which was set to expire at " << (Simulator::Now () + Simulator::GetDelayLeft (m_retxEvent)).GetSeconds ()); m_retxEvent.Cancel (); // On recieving a "New" ack we restart retransmission timer .. RFC 2988 m_rto = m_rtt->RetransmitTimeout (); NS_LOG_LOGIC (this << " Schedule ReTxTimeout at time " << Simulator::Now ().GetSeconds () << " to expire at time " << (Simulator::Now () + m_rto.Get ()).GetSeconds ()); m_retxEvent = Simulator::Schedule (m_rto, &TcpSocketBase::ReTxTimeout, this); } if (m_rWnd.Get () == 0 && m_persistEvent.IsExpired ()) { // Zero window: Enter persist state to send 1 byte to probe NS_LOG_LOGIC (this << "Enter zerowindow persist state"); NS_LOG_LOGIC (this << "Cancelled ReTxTimeout event which was set to expire at " << (Simulator::Now () + Simulator::GetDelayLeft (m_retxEvent)).GetSeconds ()); m_retxEvent.Cancel (); NS_LOG_LOGIC ("Schedule persist timeout at time " << Simulator::Now ().GetSeconds () << " to expire at time " << (Simulator::Now () + m_persistTimeout).GetSeconds ()); m_persistEvent = Simulator::Schedule (m_persistTimeout, &TcpSocketBase::PersistTimeout, this); NS_ASSERT (m_persistTimeout == Simulator::GetDelayLeft (m_persistEvent)); } // Note the highest ACK and tell app to send more NS_LOG_LOGIC ("TCP " << this << " NewAck " << ack << " numberAck " << (ack - m_txBuffer.HeadSequence ())); // Number bytes ack'ed m_txBuffer.DiscardUpTo (ack); if (GetTxAvailable () > 0) { NotifySend (GetTxAvailable ()); } if (ack > m_nextTxSequence) { m_nextTxSequence = ack; // If advanced } if (m_txBuffer.Size () == 0 && m_state != FIN_WAIT_1 && m_state != CLOSING) { // No retransmit timer if no data to retransmit NS_LOG_LOGIC (this << " Cancelled ReTxTimeout event which was set to expire at " << (Simulator::Now () + Simulator::GetDelayLeft (m_retxEvent)).GetSeconds ()); m_retxEvent.Cancel (); } // Try to send more data SendPendingData (m_connected); } // Retransmit timeout void TcpSocketBase::ReTxTimeout () { NS_LOG_FUNCTION (this); NS_LOG_LOGIC (this << " ReTxTimeout Expired at time " << Simulator::Now ().GetSeconds ()); // If erroneous timeout in closed/timed-wait state, just return if (m_state == CLOSED || m_state == TIME_WAIT) return; // If all data are received, just return if (m_state <= ESTABLISHED && m_txBuffer.HeadSequence () >= m_nextTxSequence) return; Retransmit (); } void TcpSocketBase::DelAckTimeout (void) { m_delAckCount = 0; SendEmptyPacket (TcpHeader::ACK); } void TcpSocketBase::LastAckTimeout (void) { NS_LOG_FUNCTION (this); m_lastAckEvent.Cancel (); if (m_state == LAST_ACK) { CloseAndNotify (); } if (!m_closeNotified) { m_closeNotified = true; } } // Send 1-byte data to probe for the window size at the receiver when // the local knowledge tells that the receiver has zero window size // C.f.: RFC793 p.42, RFC1112 sec.4.2.2.17 void TcpSocketBase::PersistTimeout () { NS_LOG_LOGIC ("PersistTimeout expired at " << Simulator::Now ().GetSeconds ()); m_persistTimeout = std::min (Seconds (60), Time (2 * m_persistTimeout)); // max persist timeout = 60s Ptr<Packet> p = m_txBuffer.CopyFromSequence (1, m_nextTxSequence); TcpHeader tcpHeader; tcpHeader.SetSequenceNumber (m_nextTxSequence); tcpHeader.SetAckNumber (m_rxBuffer.NextRxSequence ()); tcpHeader.SetSourcePort (m_endPoint->GetLocalPort ()); tcpHeader.SetDestinationPort (m_endPoint->GetPeerPort ()); tcpHeader.SetWindowSize (AdvertisedWindowSize ()); m_tcp->SendPacket (p, tcpHeader, m_endPoint->GetLocalAddress (), m_endPoint->GetPeerAddress (), m_boundnetdevice); NS_LOG_LOGIC ("Schedule persist timeout at time " << Simulator::Now ().GetSeconds () << " to expire at time " << (Simulator::Now () + m_persistTimeout).GetSeconds ()); m_persistEvent = Simulator::Schedule (m_persistTimeout, &TcpSocketBase::PersistTimeout, this); } void TcpSocketBase::Retransmit () { m_nextTxSequence = m_txBuffer.HeadSequence (); // Start from highest Ack m_rtt->IncreaseMultiplier (); // Double the timeout value for next retx timer m_dupAckCount = 0; DoRetransmit (); // Retransmit the packet } void TcpSocketBase::DoRetransmit () { NS_LOG_FUNCTION (this); uint8_t flags = TcpHeader::ACK; // Retransmit SYN packet if (m_state == SYN_SENT) { if (m_cnCount > 0) { SendEmptyPacket (TcpHeader::SYN); } else { NotifyConnectionFailed (); } return; } // Retransmit non-data packet: Only if in FIN_WAIT_1 or CLOSING state if (m_txBuffer.Size () == 0) { if (m_state == FIN_WAIT_1 || m_state == CLOSING) { // Must have lost FIN, re-send SendEmptyPacket (TcpHeader::FIN); } return; } // Retransmit a data packet: Extract data Ptr<Packet> p = m_txBuffer.CopyFromSequence (m_segmentSize, m_txBuffer.HeadSequence ()); // Close-on-Empty check if (m_closeOnEmpty && m_txBuffer.Size () == p->GetSize ()) { flags |= TcpHeader::FIN; } // Reset transmission timeout NS_LOG_LOGIC ("TcpSocketBase " << this << " retxing seq " << m_txBuffer.HeadSequence ()); if (m_retxEvent.IsExpired ()) { m_rto = m_rtt->RetransmitTimeout (); NS_LOG_LOGIC (this << " Schedule ReTxTimeout at time " << Simulator::Now ().GetSeconds () << " to expire at time " << (Simulator::Now () + m_rto.Get ()).GetSeconds ()); m_retxEvent = Simulator::Schedule (m_rto, &TcpSocketBase::ReTxTimeout, this); } m_rtt->SentSeq (m_txBuffer.HeadSequence (), p->GetSize ()); // And send the packet TcpHeader tcpHeader; tcpHeader.SetSequenceNumber (m_txBuffer.HeadSequence ()); tcpHeader.SetAckNumber (m_rxBuffer.NextRxSequence ()); tcpHeader.SetSourcePort (m_endPoint->GetLocalPort ()); tcpHeader.SetDestinationPort (m_endPoint->GetPeerPort ()); tcpHeader.SetFlags (flags); tcpHeader.SetWindowSize (AdvertisedWindowSize ()); m_tcp->SendPacket (p, tcpHeader, m_endPoint->GetLocalAddress (), m_endPoint->GetPeerAddress (), m_boundnetdevice); } void TcpSocketBase::CancelAllTimers () { m_retxEvent.Cancel (); m_persistEvent.Cancel (); m_delAckEvent.Cancel (); m_lastAckEvent.Cancel (); } /** Below are the attribute get/set functions */ void TcpSocketBase::SetSndBufSize (uint32_t size) { m_txBuffer.SetMaxBufferSize (size); } uint32_t TcpSocketBase::GetSndBufSize (void) const { return m_txBuffer.MaxBufferSize (); } void TcpSocketBase::SetRcvBufSize (uint32_t size) { m_rxBuffer.SetMaxBufferSize (size); } uint32_t TcpSocketBase::GetRcvBufSize (void) const { return m_rxBuffer.MaxBufferSize (); } void TcpSocketBase::SetSegSize (uint32_t size) { m_segmentSize = size; NS_ABORT_MSG_UNLESS (m_state == CLOSED, "Cannot change segment size dynamically."); } uint32_t TcpSocketBase::GetSegSize (void) const { return m_segmentSize; } void TcpSocketBase::SetConnTimeout (Time timeout) { m_cnTimeout = timeout; } Time TcpSocketBase::GetConnTimeout (void) const { return m_cnTimeout; } void TcpSocketBase::SetConnCount (uint32_t count) { m_cnCount = count; } uint32_t TcpSocketBase::GetConnCount (void) const { return m_cnCount; } void TcpSocketBase::SetDelAckTimeout (Time timeout) { m_delAckTimeout = timeout; } Time TcpSocketBase::GetDelAckTimeout (void) const { return m_delAckTimeout; } void TcpSocketBase::SetDelAckMaxCount (uint32_t count) { m_delAckMaxCount = count; } uint32_t TcpSocketBase::GetDelAckMaxCount (void) const { return m_delAckMaxCount; } void TcpSocketBase::SetPersistTimeout (Time timeout) { m_persistTimeout = timeout; } Time TcpSocketBase::GetPersistTimeout (void) const { return m_persistTimeout; } bool TcpSocketBase::SetAllowBroadcast (bool allowBroadcast) { // Broadcast is not implemented. Return true only if allowBroadcast==false return (!allowBroadcast); } bool TcpSocketBase::GetAllowBroadcast () const { return false; } } // namespace ns3
zy901002-gpsr
src/internet/model/tcp-socket-base.cc
C++
gpl2
58,378
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2010 Adrian Sai-wah Tam * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Adrian Sai-wah Tam <adrian.sw.tam@gmail.com> */ #define NS_LOG_APPEND_CONTEXT \ if (m_node) { std::clog << Simulator::Now ().GetSeconds () << " [node " << m_node->GetId () << "] "; } #include "tcp-tahoe.h" #include "ns3/log.h" #include "ns3/trace-source-accessor.h" #include "ns3/simulator.h" #include "ns3/abort.h" #include "ns3/node.h" NS_LOG_COMPONENT_DEFINE ("TcpTahoe"); namespace ns3 { NS_OBJECT_ENSURE_REGISTERED (TcpTahoe); TypeId TcpTahoe::GetTypeId (void) { static TypeId tid = TypeId ("ns3::TcpTahoe") .SetParent<TcpSocketBase> () .AddConstructor<TcpTahoe> () .AddTraceSource ("CongestionWindow", "The TCP connection's congestion window", MakeTraceSourceAccessor (&TcpTahoe::m_cWnd)) ; return tid; } TcpTahoe::TcpTahoe (void) : m_initialCWnd (0) { NS_LOG_FUNCTION (this); } TcpTahoe::TcpTahoe (const TcpTahoe& sock) : TcpSocketBase (sock), m_cWnd (sock.m_cWnd), m_ssThresh (sock.m_ssThresh), m_initialCWnd (sock.m_initialCWnd) { NS_LOG_FUNCTION (this); NS_LOG_LOGIC ("Invoked the copy constructor"); } TcpTahoe::~TcpTahoe (void) { } /** We initialize m_cWnd from this function, after attributes initialized */ int TcpTahoe::Listen (void) { NS_LOG_FUNCTION (this); InitializeCwnd (); return TcpSocketBase::Listen (); } /** We initialize m_cWnd from this function, after attributes initialized */ int TcpTahoe::Connect (const Address & address) { NS_LOG_FUNCTION (this << address); InitializeCwnd (); return TcpSocketBase::Connect (address); } /** Limit the size of in-flight data by cwnd and receiver's rxwin */ uint32_t TcpTahoe::Window (void) { NS_LOG_FUNCTION (this); return std::min (m_rWnd.Get (), m_cWnd.Get ()); } Ptr<TcpSocketBase> TcpTahoe::Fork (void) { return CopyObject<TcpTahoe> (this); } /** New ACK (up to seqnum seq) received. Increase cwnd and call TcpSocketBase::NewAck() */ void TcpTahoe::NewAck (SequenceNumber32 const& seq) { NS_LOG_FUNCTION (this << seq); NS_LOG_LOGIC ("TcpTahoe receieved ACK for seq " << seq << " cwnd " << m_cWnd << " ssthresh " << m_ssThresh); if (m_cWnd < m_ssThresh) { // Slow start mode, add one segSize to cWnd. Default m_ssThresh is 65535. (RFC2001, sec.1) m_cWnd += m_segmentSize; NS_LOG_INFO ("In SlowStart, updated to cwnd " << m_cWnd << " ssthresh " << m_ssThresh); } else { // Congestion avoidance mode, increase by (segSize*segSize)/cwnd. (RFC2581, sec.3.1) // To increase cwnd for one segSize per RTT, it should be (ackBytes*segSize)/cwnd double adder = static_cast<double> (m_segmentSize * m_segmentSize) / m_cWnd.Get (); adder = std::max (1.0, adder); m_cWnd += static_cast<uint32_t> (adder); NS_LOG_INFO ("In CongAvoid, updated to cwnd " << m_cWnd << " ssthresh " << m_ssThresh); } TcpSocketBase::NewAck (seq); // Complete newAck processing } /** Cut down ssthresh upon triple dupack */ void TcpTahoe::DupAck (const TcpHeader& t, uint32_t count) { NS_LOG_FUNCTION (this << "t " << count); if (count == 3) { // triple duplicate ack triggers fast retransmit (RFC2001, sec.3) NS_LOG_INFO ("Triple Dup Ack: old ssthresh " << m_ssThresh << " cwnd " << m_cWnd); // fast retransmit in Tahoe means triggering RTO earlier. Tx is restarted // from the highest ack and run slow start again. // (Fall & Floyd 1996, sec.1) m_ssThresh = std::max (static_cast<unsigned> (m_cWnd / 2), m_segmentSize * 2); // Half ssthresh m_cWnd = m_segmentSize; // Run slow start again m_nextTxSequence = m_txBuffer.HeadSequence (); // Restart from highest Ack NS_LOG_INFO ("Triple Dup Ack: new ssthresh " << m_ssThresh << " cwnd " << m_cWnd); NS_LOG_LOGIC ("Triple Dup Ack: retransmit missing segment at " << Simulator::Now ().GetSeconds ()); DoRetransmit (); } } /** Retransmit timeout */ void TcpTahoe::Retransmit (void) { NS_LOG_FUNCTION (this); NS_LOG_LOGIC (this << " ReTxTimeout Expired at time " << Simulator::Now ().GetSeconds ()); // If erroneous timeout in closed/timed-wait state, just return if (m_state == CLOSED || m_state == TIME_WAIT) return; // If all data are received, just return if (m_txBuffer.HeadSequence () >= m_nextTxSequence) return; m_ssThresh = std::max (static_cast<unsigned> (m_cWnd / 2), m_segmentSize * 2); // Half ssthresh m_cWnd = m_segmentSize; // Set cwnd to 1 segSize (RFC2001, sec.2) m_nextTxSequence = m_txBuffer.HeadSequence (); // Restart from highest Ack m_rtt->IncreaseMultiplier (); // Double the next RTO DoRetransmit (); // Retransmit the packet } void TcpTahoe::SetSegSize (uint32_t size) { NS_ABORT_MSG_UNLESS (m_state == CLOSED, "TcpTahoe::SetSegSize() cannot change segment size after connection started."); m_segmentSize = size; } void TcpTahoe::SetSSThresh (uint32_t threshold) { m_ssThresh = threshold; } uint32_t TcpTahoe::GetSSThresh (void) const { return m_ssThresh; } void TcpTahoe::SetInitialCwnd (uint32_t cwnd) { NS_ABORT_MSG_UNLESS (m_state == CLOSED, "TcpTahoe::SetInitialCwnd() cannot change initial cwnd after connection started."); m_initialCWnd = cwnd; } uint32_t TcpTahoe::GetInitialCwnd (void) const { return m_initialCWnd; } void TcpTahoe::InitializeCwnd (void) { /* * Initialize congestion window, default to 1 MSS (RFC2001, sec.1) and must * not be larger than 2 MSS (RFC2581, sec.3.1). Both m_initiaCWnd and * m_segmentSize are set by the attribute system in ns3::TcpSocket. */ m_cWnd = m_initialCWnd * m_segmentSize; } } // namespace ns3
zy901002-gpsr
src/internet/model/tcp-tahoe.cc
C++
gpl2
6,440
// -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- // // Copyright (c) 2008 University of Washington // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation; // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // #ifndef IPV4_GLOBAL_ROUTING_H #define IPV4_GLOBAL_ROUTING_H #include <list> #include <stdint.h> #include "ns3/ipv4-address.h" #include "ns3/ipv4-header.h" #include "ns3/ptr.h" #include "ns3/ipv4.h" #include "ns3/ipv4-routing-protocol.h" #include "ns3/random-variable.h" namespace ns3 { class Packet; class NetDevice; class Ipv4Interface; class Ipv4Address; class Ipv4Header; class Ipv4RoutingTableEntry; class Ipv4MulticastRoutingTableEntry; class Node; /** * \brief Global routing protocol for IP version 4 stacks. * * In ns-3 we have the concept of a pluggable routing protocol. Routing * protocols are added to a list maintained by the Ipv4L3Protocol. Every * stack gets one routing protocol for free -- the Ipv4StaticRouting routing * protocol is added in the constructor of the Ipv4L3Protocol (this is the * piece of code that implements the functionality of the IP layer). * * As an option to running a dynamic routing protocol, a GlobalRouteManager * object has been created to allow users to build routes for all participating * nodes. One can think of this object as a "routing oracle"; it has * an omniscient view of the topology, and can construct shortest path * routes between all pairs of nodes. These routes must be stored * somewhere in the node, so therefore this class Ipv4GlobalRouting * is used as one of the pluggable routing protocols. It is kept distinct * from Ipv4StaticRouting because these routes may be dynamically cleared * and rebuilt in the middle of the simulation, while manually entered * routes into the Ipv4StaticRouting may need to be kept distinct. * * This class deals with Ipv4 unicast routes only. * * \see Ipv4RoutingProtocol * \see GlobalRouteManager */ class Ipv4GlobalRouting : public Ipv4RoutingProtocol { public: static TypeId GetTypeId (void); /** * \brief Construct an empty Ipv4GlobalRouting routing protocol, * * The Ipv4GlobalRouting class supports host and network unicast routes. * This method initializes the lists containing these routes to empty. * * \see Ipv4GlobalRouting */ Ipv4GlobalRouting (); virtual ~Ipv4GlobalRouting (); // These methods inherited from base class virtual Ptr<Ipv4Route> RouteOutput (Ptr<Packet> p, const Ipv4Header &header, Ptr<NetDevice> oif, Socket::SocketErrno &sockerr); virtual bool RouteInput (Ptr<const Packet> p, const Ipv4Header &header, Ptr<const NetDevice> idev, UnicastForwardCallback ucb, MulticastForwardCallback mcb, LocalDeliverCallback lcb, ErrorCallback ecb); virtual void NotifyInterfaceUp (uint32_t interface); virtual void NotifyInterfaceDown (uint32_t interface); virtual void NotifyAddAddress (uint32_t interface, Ipv4InterfaceAddress address); virtual void NotifyRemoveAddress (uint32_t interface, Ipv4InterfaceAddress address); virtual void SetIpv4 (Ptr<Ipv4> ipv4); virtual void PrintRoutingTable (Ptr<OutputStreamWrapper> stream) const; /** * \brief Add a host route to the global routing table. * * \param dest The Ipv4Address destination for this route. * \param nextHop The Ipv4Address of the next hop in the route. * \param interface The network interface index used to send packets to the * destination. * * \see Ipv4Address */ void AddHostRouteTo (Ipv4Address dest, Ipv4Address nextHop, uint32_t interface); /** * \brief Add a host route to the global routing table. * * \param dest The Ipv4Address destination for this route. * \param interface The network interface index used to send packets to the * destination. * * \see Ipv4Address */ void AddHostRouteTo (Ipv4Address dest, uint32_t interface); /** * \brief Add a network route to the global routing table. * * \param network The Ipv4Address network for this route. * \param networkMask The Ipv4Mask to extract the network. * \param nextHop The next hop in the route to the destination network. * \param interface The network interface index used to send packets to the * destination. * * \see Ipv4Address */ void AddNetworkRouteTo (Ipv4Address network, Ipv4Mask networkMask, Ipv4Address nextHop, uint32_t interface); /** * \brief Add a network route to the global routing table. * * \param network The Ipv4Address network for this route. * \param networkMask The Ipv4Mask to extract the network. * \param interface The network interface index used to send packets to the * destination. * * \see Ipv4Address */ void AddNetworkRouteTo (Ipv4Address network, Ipv4Mask networkMask, uint32_t interface); /** * \brief Add an external route to the global routing table. * * \param network The Ipv4Address network for this route. * \param networkMask The Ipv4Mask to extract the network. * \param nextHop The next hop Ipv4Address * \param interface The network interface index used to send packets to the * destination. */ void AddASExternalRouteTo (Ipv4Address network, Ipv4Mask networkMask, Ipv4Address nextHop, uint32_t interface); /** * \brief Get the number of individual unicast routes that have been added * to the routing table. * * \warning The default route counts as one of the routes. */ uint32_t GetNRoutes (void) const; /** * \brief Get a route from the global unicast routing table. * * Externally, the unicast global routing table appears simply as a table with * n entries. The one subtlety of note is that if a default route has been set * it will appear as the zeroth entry in the table. This means that if you * add only a default route, the table will have one entry that can be accessed * either by explicitly calling GetDefaultRoute () or by calling GetRoute (0). * * Similarly, if the default route has been set, calling RemoveRoute (0) will * remove the default route. * * \param i The index (into the routing table) of the route to retrieve. If * the default route has been set, it will occupy index zero. * \return If route is set, a pointer to that Ipv4RoutingTableEntry is returned, otherwise * a zero pointer is returned. * * \see Ipv4RoutingTableEntry * \see Ipv4GlobalRouting::RemoveRoute */ Ipv4RoutingTableEntry *GetRoute (uint32_t i) const; /** * \brief Remove a route from the global unicast routing table. * * Externally, the unicast global routing table appears simply as a table with * n entries. The one subtlety of note is that if a default route has been set * it will appear as the zeroth entry in the table. This means that if the * default route has been set, calling RemoveRoute (0) will remove the * default route. * * \param i The index (into the routing table) of the route to remove. If * the default route has been set, it will occupy index zero. * * \see Ipv4RoutingTableEntry * \see Ipv4GlobalRouting::GetRoute * \see Ipv4GlobalRouting::AddRoute */ void RemoveRoute (uint32_t i); protected: void DoDispose (void); private: /// Set to true if packets are randomly routed among ECMP; set to false for using only one route consistently bool m_randomEcmpRouting; /// Set to true if this interface should respond to interface events by globallly recomputing routes bool m_respondToInterfaceEvents; /// A uniform random number generator for randomly routing packets among ECMP UniformVariable m_rand; typedef std::list<Ipv4RoutingTableEntry *> HostRoutes; typedef std::list<Ipv4RoutingTableEntry *>::const_iterator HostRoutesCI; typedef std::list<Ipv4RoutingTableEntry *>::iterator HostRoutesI; typedef std::list<Ipv4RoutingTableEntry *> NetworkRoutes; typedef std::list<Ipv4RoutingTableEntry *>::const_iterator NetworkRoutesCI; typedef std::list<Ipv4RoutingTableEntry *>::iterator NetworkRoutesI; typedef std::list<Ipv4RoutingTableEntry *> ASExternalRoutes; typedef std::list<Ipv4RoutingTableEntry *>::const_iterator ASExternalRoutesCI; typedef std::list<Ipv4RoutingTableEntry *>::iterator ASExternalRoutesI; Ptr<Ipv4Route> LookupGlobal (Ipv4Address dest, Ptr<NetDevice> oif = 0); HostRoutes m_hostRoutes; NetworkRoutes m_networkRoutes; ASExternalRoutes m_ASexternalRoutes; // External routes imported Ptr<Ipv4> m_ipv4; }; } // Namespace ns3 #endif /* IPV4_GLOBAL_ROUTING_H */
zy901002-gpsr
src/internet/model/ipv4-global-routing.h
C++
gpl2
9,246
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2006 Georgia Tech Research Corporation * 2007 INRIA * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Authors: George F. Riley<riley@ece.gatech.edu> * Mathieu Lacage <mathieu.lacage@sophia.inria.fr> */ #ifndef TCP_SOCKET_H #define TCP_SOCKET_H #include "ns3/socket.h" #include "ns3/traced-callback.h" #include "ns3/callback.h" #include "ns3/ptr.h" #include "ns3/object.h" #include "ns3/nstime.h" namespace ns3 { class Node; class Packet; /* Names of the 11 TCP states */ typedef enum { CLOSED, // 0 LISTEN, // 1 SYN_SENT, // 2 SYN_RCVD, // 3 ESTABLISHED, // 4 CLOSE_WAIT, // 5 LAST_ACK, // 6 FIN_WAIT_1, // 7 FIN_WAIT_2, // 8 CLOSING, // 9 TIME_WAIT, // 10 LAST_STATE } TcpStates_t; /** * \ingroup socket * * \brief (abstract) base class of all TcpSockets * * This class exists solely for hosting TcpSocket attributes that can * be reused across different implementations. */ class TcpSocket : public Socket { public: static TypeId GetTypeId (void); TcpSocket (void); virtual ~TcpSocket (void); // Literal names of TCP states for use in log messages */ static const char* const TcpStateName[LAST_STATE]; private: // Indirect the attribute setting and getting through private virtual methods virtual void SetSndBufSize (uint32_t size) = 0; virtual uint32_t GetSndBufSize (void) const = 0; virtual void SetRcvBufSize (uint32_t size) = 0; virtual uint32_t GetRcvBufSize (void) const = 0; virtual void SetSegSize (uint32_t size) = 0; virtual uint32_t GetSegSize (void) const = 0; virtual void SetSSThresh (uint32_t threshold) = 0; virtual uint32_t GetSSThresh (void) const = 0; virtual void SetInitialCwnd (uint32_t count) = 0; virtual uint32_t GetInitialCwnd (void) const = 0; virtual void SetConnTimeout (Time timeout) = 0; virtual Time GetConnTimeout (void) const = 0; virtual void SetConnCount (uint32_t count) = 0; virtual uint32_t GetConnCount (void) const = 0; virtual void SetDelAckTimeout (Time timeout) = 0; virtual Time GetDelAckTimeout (void) const = 0; virtual void SetDelAckMaxCount (uint32_t count) = 0; virtual uint32_t GetDelAckMaxCount (void) const = 0; virtual void SetPersistTimeout (Time timeout) = 0; virtual Time GetPersistTimeout (void) const = 0; }; } // namespace ns3 #endif /* TCP_SOCKET_H */
zy901002-gpsr
src/internet/model/tcp-socket.h
C++
gpl2
3,071
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2009 University of Washington * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #ifndef IPV4_ROUTE_H #define IPV4_ROUTE_H #include <list> #include <map> #include <ostream> #include "ns3/simple-ref-count.h" #include "ns3/ipv4-address.h" #include "ns3/deprecated.h" namespace ns3 { class NetDevice; /** * \ingroup ipv4Routing * *\brief Ipv4 route cache entry (similar to Linux struct rtable) * * This is a reference counted object. In the future, we will add other * entries from struct dst_entry, struct rtable, and struct dst_ops as needed. */ class Ipv4Route : public SimpleRefCount<Ipv4Route> { public: Ipv4Route (); /** * \param dest Destination Ipv4Address */ void SetDestination (Ipv4Address dest); /** * \return Destination Ipv4Address of the route */ Ipv4Address GetDestination (void) const; /** * \param src Source Ipv4Address */ void SetSource (Ipv4Address src); /** * \return Source Ipv4Address of the route */ Ipv4Address GetSource (void) const; /** * \param gw Gateway (next hop) Ipv4Address */ void SetGateway (Ipv4Address gw); /** * \return Ipv4Address of the gateway (next hop) */ Ipv4Address GetGateway (void) const; /** * Equivalent in Linux to dst_entry.dev * * \param outputDevice pointer to NetDevice for outgoing packets */ void SetOutputDevice (Ptr<NetDevice> outputDevice); /** * \return pointer to NetDevice for outgoing packets */ Ptr<NetDevice> GetOutputDevice (void) const; #ifdef NOTYET // rtable.idev void SetInputIfIndex (uint32_t iif); uint32_t GetInputIfIndex (void) const; #endif private: Ipv4Address m_dest; Ipv4Address m_source; Ipv4Address m_gateway; Ptr<NetDevice> m_outputDevice; #ifdef NOTYET uint32_t m_inputIfIndex; #endif }; std::ostream& operator<< (std::ostream& os, Ipv4Route const& route); /** * \ingroup ipv4Routing * * \brief Ipv4 multicast route cache entry (similar to Linux struct mfc_cache) */ class Ipv4MulticastRoute : public SimpleRefCount<Ipv4MulticastRoute> { public: Ipv4MulticastRoute (); /** * \param group Ipv4Address of the multicast group */ void SetGroup (const Ipv4Address group); /** * \return Ipv4Address of the multicast group */ Ipv4Address GetGroup (void) const; /** * \param origin Ipv4Address of the origin address */ void SetOrigin (const Ipv4Address origin); /** * \return Ipv4Address of the origin address */ Ipv4Address GetOrigin (void) const; /** * \param iif Parent (input interface) for this route */ void SetParent (uint32_t iif); /** * \return Parent (input interface) for this route */ uint32_t GetParent (void) const; /** * \param oif Outgoing interface index * \param ttl time-to-live for this route */ void SetOutputTtl (uint32_t oif, uint32_t ttl); /** * \param oif outgoing interface * \return TTL for this route */ uint32_t GetOutputTtl (uint32_t oif) NS_DEPRECATED; /** * \return map of output interface Ids and TTLs for this route */ std::map<uint32_t, uint32_t> GetOutputTtlMap () const; static const uint32_t MAX_INTERFACES = 16; // Maximum number of multicast interfaces on a router static const uint32_t MAX_TTL = 255; // Maximum time-to-live (TTL) private: Ipv4Address m_group; // Group Ipv4Address m_origin; // Source of packet uint32_t m_parent; // Source interface std::map<uint32_t, uint32_t> m_ttls; }; } // namespace ns3 #endif /* IPV4_ROUTE_H */
zy901002-gpsr
src/internet/model/ipv4-route.h
C++
gpl2
4,216
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007 Georgia Tech Research Corporation * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Raj Bhattacharjea <raj.b@gatech.edu> */ #ifndef TCP_SOCKET_FACTORY_IMPL_H #define TCP_SOCKET_FACTORY_IMPL_H #include "ns3/tcp-socket-factory.h" #include "ns3/ptr.h" namespace ns3 { class TcpL4Protocol; /** * \ingroup internet * \defgroup tcp Tcp * * This class serves to create sockets of the TcpSocketBase type. */ /** * \ingroup tcp * * \brief socket factory implementation for native ns-3 TCP * */ class TcpSocketFactoryImpl : public TcpSocketFactory { public: TcpSocketFactoryImpl (); virtual ~TcpSocketFactoryImpl (); void SetTcp (Ptr<TcpL4Protocol> tcp); virtual Ptr<Socket> CreateSocket (void); protected: virtual void DoDispose (void); private: Ptr<TcpL4Protocol> m_tcp; }; } // namespace ns3 #endif /* TCP_SOCKET_FACTORY_IMPL_H */
zy901002-gpsr
src/internet/model/tcp-socket-factory-impl.h
C++
gpl2
1,563
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2006 Georgia Tech Research Corporation * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: George F. Riley<riley@ece.gatech.edu> * Gustavo Carneiro <gjc@inescporto.pt> */ #ifndef IPV4_STATIC_ROUTING_H #define IPV4_STATIC_ROUTING_H #include <list> #include <utility> #include <stdint.h> #include "ns3/ipv4-address.h" #include "ns3/ipv4-header.h" #include "ns3/socket.h" #include "ns3/ptr.h" #include "ns3/ipv4.h" #include "ns3/ipv4-routing-protocol.h" namespace ns3 { class Packet; class NetDevice; class Ipv4Interface; class Ipv4Address; class Ipv4Header; class Ipv4RoutingTableEntry; class Ipv4MulticastRoutingTableEntry; class Node; /** * \ingroup internet * \defgroup ipv4StaticRouting Ipv4StaticRouting */ /** * \ingroup ipv4StaticRouting * * \brief Static routing protocol for IP version 4 stacks. * * This class provides a basic set of methods for inserting static * unicast and multicast routes into the Ipv4 routing system. * This particular protocol is designed to be inserted into an * Ipv4ListRouting protocol but can be used also as a standalone * protocol. * * The Ipv4StaticRouting class inherits from the abstract base class * Ipv4RoutingProtocol that defines the interface methods that a routing * protocol must support. * * \see Ipv4RoutingProtocol * \see Ipv4ListRouting * \see Ipv4ListRouting::AddRoutingProtocol */ class Ipv4StaticRouting : public Ipv4RoutingProtocol { public: static TypeId GetTypeId (void); Ipv4StaticRouting (); virtual ~Ipv4StaticRouting (); virtual Ptr<Ipv4Route> RouteOutput (Ptr<Packet> p, const Ipv4Header &header, Ptr<NetDevice> oif, Socket::SocketErrno &sockerr); virtual bool RouteInput (Ptr<const Packet> p, const Ipv4Header &header, Ptr<const NetDevice> idev, UnicastForwardCallback ucb, MulticastForwardCallback mcb, LocalDeliverCallback lcb, ErrorCallback ecb); virtual void NotifyInterfaceUp (uint32_t interface); virtual void NotifyInterfaceDown (uint32_t interface); virtual void NotifyAddAddress (uint32_t interface, Ipv4InterfaceAddress address); virtual void NotifyRemoveAddress (uint32_t interface, Ipv4InterfaceAddress address); virtual void SetIpv4 (Ptr<Ipv4> ipv4); virtual void PrintRoutingTable (Ptr<OutputStreamWrapper> stream) const; /** * \brief Add a network route to the static routing table. * * \param network The Ipv4Address network for this route. * \param networkMask The Ipv4Mask to extract the network. * \param nextHop The next hop in the route to the destination network. * \param interface The network interface index used to send packets to the * destination. * \param metric Metric of route in case of multiple routes to same destination * * \see Ipv4Address */ void AddNetworkRouteTo (Ipv4Address network, Ipv4Mask networkMask, Ipv4Address nextHop, uint32_t interface, uint32_t metric = 0); /** * \brief Add a network route to the static routing table. * * \param network The Ipv4Address network for this route. * \param networkMask The Ipv4Mask to extract the network. * \param interface The network interface index used to send packets to the * destination. * \param metric Metric of route in case of multiple routes to same destination * * \see Ipv4Address */ void AddNetworkRouteTo (Ipv4Address network, Ipv4Mask networkMask, uint32_t interface, uint32_t metric = 0); /** * \brief Add a host route to the static routing table. * * \param dest The Ipv4Address destination for this route. * \param nextHop The Ipv4Address of the next hop in the route. * \param interface The network interface index used to send packets to the * destination. * \param metric Metric of route in case of multiple routes to same destination * * \see Ipv4Address */ void AddHostRouteTo (Ipv4Address dest, Ipv4Address nextHop, uint32_t interface, uint32_t metric = 0); /** * \brief Add a host route to the static routing table. * * \param dest The Ipv4Address destination for this route. * \param interface The network interface index used to send packets to the * destination. * \param metric Metric of route in case of multiple routes to same destination * * \see Ipv4Address */ void AddHostRouteTo (Ipv4Address dest, uint32_t interface, uint32_t metric = 0); /** * \brief Add a default route to the static routing table. * * This method tells the routing system what to do in the case where a specific * route to a destination is not found. The system forwards packets to the * specified node in the hope that it knows better how to route the packet. * * If the default route is set, it is returned as the selected route from * LookupStatic irrespective of destination address if no specific route is * found. * * \param nextHop The Ipv4Address to send packets to in the hope that they * will be forwarded correctly. * \param interface The network interface index used to send packets. * \param metric Metric of route in case of multiple routes to same destination * * \see Ipv4Address * \see Ipv4StaticRouting::Lookup */ void SetDefaultRoute (Ipv4Address nextHop, uint32_t interface, uint32_t metric = 0); /** * \brief Get the number of individual unicast routes that have been added * to the routing table. * * \warning The default route counts as one of the routes. */ uint32_t GetNRoutes (void) const; /** * \brief Get the default route with lowest metric from the static routing table. * * \return If the default route is set, a pointer to that Ipv4RoutingTableEntry is * returned, otherwise an empty routing table entry is returned. * If multiple default routes exist, the one with lowest metric is returned. * * \see Ipv4RoutingTableEntry */ Ipv4RoutingTableEntry GetDefaultRoute (void); /** * \brief Get a route from the static unicast routing table. * * Externally, the unicast static routing table appears simply as a table with * n entries. * * \param i The index (into the routing table) of the route to retrieve. * \return If route is set, a pointer to that Ipv4RoutingTableEntry is returned, otherwise * a zero pointer is returned. * * \see Ipv4RoutingTableEntry * \see Ipv4StaticRouting::RemoveRoute */ Ipv4RoutingTableEntry GetRoute (uint32_t i) const; /** * \brief Get a metric for route from the static unicast routing table. * * \param index The index (into the routing table) of the route to retrieve. * \return If route is set, the metric is returned. If not, an infinity metric (0xffffffff) is returned * */ uint32_t GetMetric (uint32_t index); /** * \brief Remove a route from the static unicast routing table. * * Externally, the unicast static routing table appears simply as a table with * n entries. * * \param i The index (into the routing table) of the route to remove. * * \see Ipv4RoutingTableEntry * \see Ipv4StaticRouting::GetRoute * \see Ipv4StaticRouting::AddRoute */ void RemoveRoute (uint32_t i); /** * \brief Add a multicast route to the static routing table. * * A multicast route must specify an origin IP address, a multicast group and * an input network interface index as conditions and provide a vector of * output network interface indices over which packets matching the conditions * are sent. * * Typically there are two main types of multicast routes: routes of the * first kind are used during forwarding. All of the conditions must be * explicitly provided. The second kind of routes are used to get packets off * of a local node. The difference is in the input interface. Routes for * forwarding will always have an explicit input interface specified. Routes * off of a node will always set the input interface to a wildcard specified * by the index Ipv4RoutingProtocol::INTERFACE_ANY. * * For routes off of a local node wildcards may be used in the origin and * multicast group addresses. The wildcard used for Ipv4Adresses is that * address returned by Ipv4Address::GetAny () -- typically "0.0.0.0". Usage * of a wildcard allows one to specify default behavior to varying degrees. * * For example, making the origin address a wildcard, but leaving the * multicast group specific allows one (in the case of a node with multiple * interfaces) to create different routes using different output interfaces * for each multicast group. * * If the origin and multicast addresses are made wildcards, you have created * essentially a default multicast address that can forward to multiple * interfaces. Compare this to the actual default multicast address that is * limited to specifying a single output interface for compatibility with * existing functionality in other systems. * * \param origin The Ipv4Address of the origin of packets for this route. May * be Ipv4Address:GetAny for open groups. * \param group The Ipv4Address of the multicast group or this route. * \param inputInterface The input network interface index over which to * expect packets destined for this route. May be * Ipv4RoutingProtocol::INTERFACE_ANY for packets of local origin. * \param outputInterfaces A vector of network interface indices used to specify * how to send packets to the destination(s). * * \see Ipv4Address */ void AddMulticastRoute (Ipv4Address origin, Ipv4Address group, uint32_t inputInterface, std::vector<uint32_t> outputInterfaces); /** * \brief Add a default multicast route to the static routing table. * * This is the multicast equivalent of the unicast version SetDefaultRoute. * We tell the routing system what to do in the case where a specific route * to a destination multicast group is not found. The system forwards * packets out the specified interface in the hope that "something out there" * knows better how to route the packet. This method is only used in * initially sending packets off of a host. The default multicast route is * not consulted during forwarding -- exact routes must be specified using * AddMulticastRoute for that case. * * Since we're basically sending packets to some entity we think may know * better what to do, we don't pay attention to "subtleties" like origin * address, nor do we worry about forwarding out multiple interfaces. If the * default multicast route is set, it is returned as the selected route from * LookupStatic irrespective of origin or multicast group if another specific * route is not found. * * \param outputInterface The network interface index used to specify where * to send packets in the case of unknown routes. * * \see Ipv4Address */ void SetDefaultMulticastRoute (uint32_t outputInterface); /** * \brief Get the number of individual multicast routes that have been added * to the routing table. * * \warning The default multicast route counts as one of the routes. */ uint32_t GetNMulticastRoutes (void) const; /** * \brief Get a route from the static multicast routing table. * * Externally, the multicast static routing table appears simply as a table * with n entries. * * \param i The index (into the routing table) of the multicast route to * retrieve. * \return If route \e i is set, a pointer to that Ipv4MulticastRoutingTableEntry is * returned, otherwise a zero pointer is returned. * * \see Ipv4MulticastRoutingTableEntry * \see Ipv4StaticRouting::RemoveRoute */ Ipv4MulticastRoutingTableEntry GetMulticastRoute (uint32_t i) const; /** * \brief Remove a route from the static multicast routing table. * * Externally, the multicast static routing table appears simply as a table * with n entries. * This method causes the multicast routing table to be searched for the first * route that matches the parameters and removes it. * * Wildcards may be provided to this function, but the wildcards are used to * exactly match wildcards in the routes (see AddMulticastRoute). That is, * calling RemoveMulticastRoute with the origin set to "0.0.0.0" will not * remove routes with any address in the origin, but will only remove routes * with "0.0.0.0" set as the the origin. * * \param origin The IP address specified as the origin of packets for the * route. * \param group The IP address specified as the multicast group address of * the route. * \param inputInterface The network interface index specified as the expected * input interface for the route. * \returns true if a route was found and removed, false otherwise. * * \see Ipv4MulticastRoutingTableEntry * \see Ipv4StaticRouting::AddMulticastRoute */ bool RemoveMulticastRoute (Ipv4Address origin, Ipv4Address group, uint32_t inputInterface); /** * \brief Remove a route from the static multicast routing table. * * Externally, the multicast static routing table appears simply as a table * with n entries. * * \param index The index (into the multicast routing table) of the route to * remove. * * \see Ipv4RoutingTableEntry * \see Ipv4StaticRouting::GetRoute * \see Ipv4StaticRouting::AddRoute */ void RemoveMulticastRoute (uint32_t index); protected: virtual void DoDispose (void); private: typedef std::list<std::pair <Ipv4RoutingTableEntry *, uint32_t> > NetworkRoutes; typedef std::list<std::pair <Ipv4RoutingTableEntry *, uint32_t> >::const_iterator NetworkRoutesCI; typedef std::list<std::pair <Ipv4RoutingTableEntry *, uint32_t> >::iterator NetworkRoutesI; typedef std::list<Ipv4MulticastRoutingTableEntry *> MulticastRoutes; typedef std::list<Ipv4MulticastRoutingTableEntry *>::const_iterator MulticastRoutesCI; typedef std::list<Ipv4MulticastRoutingTableEntry *>::iterator MulticastRoutesI; Ptr<Ipv4Route> LookupStatic (Ipv4Address dest, Ptr<NetDevice> oif = 0); Ptr<Ipv4MulticastRoute> LookupStatic (Ipv4Address origin, Ipv4Address group, uint32_t interface); Ipv4Address SourceAddressSelection (uint32_t interface, Ipv4Address dest); NetworkRoutes m_networkRoutes; MulticastRoutes m_multicastRoutes; Ptr<Ipv4> m_ipv4; }; } // Namespace ns3 #endif /* IPV4_STATIC_ROUTING_H */
zy901002-gpsr
src/internet/model/ipv4-static-routing.h
C++
gpl2
15,217
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2008 INRIA * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr> */ #include "ipv4-raw-socket-factory-impl.h" #include "ipv4-l3-protocol.h" #include "ns3/socket.h" namespace ns3 { Ptr<Socket> Ipv4RawSocketFactoryImpl::CreateSocket (void) { Ptr<Ipv4L3Protocol> ipv4 = GetObject<Ipv4L3Protocol> (); Ptr<Socket> socket = ipv4->CreateRawSocket (); return socket; } } // namespace ns3
zy901002-gpsr
src/internet/model/ipv4-raw-socket-factory-impl.cc
C++
gpl2
1,138
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007 Georgia Tech Research Corporation * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Raj Bhattacharjea <raj.b@gatech.edu> */ #ifndef TCP_L4_PROTOCOL_H #define TCP_L4_PROTOCOL_H #include <stdint.h> #include "ns3/packet.h" #include "ns3/ipv4-address.h" #include "ns3/ptr.h" #include "ns3/object-factory.h" #include "ipv4-l4-protocol.h" #include "ns3/net-device.h" namespace ns3 { class Node; class Socket; class TcpHeader; class Ipv4EndPointDemux; class Ipv4Interface; class TcpSocketBase; class Ipv4EndPoint; /** * \ingroup tcp * \brief A layer between the sockets interface and IP * * This class allocates "endpoint" objects (ns3::Ipv4EndPoint) for TCP, * and SHOULD checksum packets its receives from the socket layer going down * the stack , but currently checksumming is disabled. It also receives * packets from IP, and forwards them up to the endpoints. */ class TcpL4Protocol : public Ipv4L4Protocol { public: static TypeId GetTypeId (void); static const uint8_t PROT_NUMBER; /** * \brief Constructor */ TcpL4Protocol (); virtual ~TcpL4Protocol (); void SetNode (Ptr<Node> node); virtual int GetProtocolNumber (void) const; /** * \return A smart Socket pointer to a TcpSocket allocated by this instance * of the TCP protocol */ Ptr<Socket> CreateSocket (void); Ptr<Socket> CreateSocket (TypeId socketTypeId); Ipv4EndPoint *Allocate (void); Ipv4EndPoint *Allocate (Ipv4Address address); Ipv4EndPoint *Allocate (uint16_t port); Ipv4EndPoint *Allocate (Ipv4Address address, uint16_t port); Ipv4EndPoint *Allocate (Ipv4Address localAddress, uint16_t localPort, Ipv4Address peerAddress, uint16_t peerPort); void DeAllocate (Ipv4EndPoint *endPoint); /** * \brief Send a packet via TCP * \param packet The packet to send * \param saddr The source Ipv4Address * \param daddr The destination Ipv4Address * \param sport The source port number * \param dport The destination port number * \param oif The output interface bound. Defaults to null (unspecified). */ void Send (Ptr<Packet> packet, Ipv4Address saddr, Ipv4Address daddr, uint16_t sport, uint16_t dport, Ptr<NetDevice> oif = 0); /** * \brief Receive a packet up the protocol stack * \param p The Packet to dump the contents into * \param header IPv4 Header information * \param incomingInterface The Ipv4Interface it was received on */ virtual enum Ipv4L4Protocol::RxStatus Receive (Ptr<Packet> p, Ipv4Header const &header, Ptr<Ipv4Interface> incomingInterface); // From Ipv4L4Protocol virtual void SetDownTarget (Ipv4L4Protocol::DownTargetCallback cb); // From Ipv4L4Protocol virtual Ipv4L4Protocol::DownTargetCallback GetDownTarget (void) const; protected: virtual void DoDispose (void); /* * This function will notify other components connected to the node that a new stack member is now connected * This will be used to notify Layer 3 protocol of layer 4 protocol stack to connect them together. */ virtual void NotifyNewAggregate (); private: Ptr<Node> m_node; Ipv4EndPointDemux *m_endPoints; TypeId m_rttTypeId; TypeId m_socketTypeId; private: friend class TcpSocketBase; void SendPacket (Ptr<Packet>, const TcpHeader &, Ipv4Address, Ipv4Address, Ptr<NetDevice> oif = 0); TcpL4Protocol (const TcpL4Protocol &o); TcpL4Protocol &operator = (const TcpL4Protocol &o); std::vector<Ptr<TcpSocketBase> > m_sockets; Ipv4L4Protocol::DownTargetCallback m_downTarget; }; } // namespace ns3 #endif /* TCP_L4_PROTOCOL_H */
zy901002-gpsr
src/internet/model/tcp-l4-protocol.h
C++
gpl2
4,413
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007 INRIA * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr> */ #ifndef UDP_SOCKET_FACTORY_IMPL_H #define UDP_SOCKET_FACTORY_IMPL_H #include "ns3/udp-socket-factory.h" #include "ns3/ptr.h" namespace ns3 { class UdpL4Protocol; /** * \ingroup internet * \defgroup udp Udp * * This is an implementation of the User Datagram Protocol described in * RFC 768. It implements a connectionless, unreliable datagram packet * service. Packets may be reordered or duplicated before they arrive. * UDP generates and checks checksums to catch transmission errors. * * The following options are not presently part of this implementation: * UDP_CORK, MSG_DONTROUTE, path MTU discovery control (e.g. * IP_MTU_DISCOVER). MTU handling is also weak in ns-3 for the moment; * it is best to send datagrams that do not exceed 1500 byte MTU (e.g. * 1472 byte UDP datagrams) */ /** * \ingroup udp * \brief Object to create UDP socket instances * \internal * * This class implements the API for creating UDP sockets. * It is a socket factory (deriving from class SocketFactory). */ class UdpSocketFactoryImpl : public UdpSocketFactory { public: UdpSocketFactoryImpl (); virtual ~UdpSocketFactoryImpl (); void SetUdp (Ptr<UdpL4Protocol> udp); /** * \brief Implements a method to create a Udp-based socket and return * a base class smart pointer to the socket. * \internal * * \return smart pointer to Socket */ virtual Ptr<Socket> CreateSocket (void); protected: virtual void DoDispose (void); private: Ptr<UdpL4Protocol> m_udp; }; } // namespace ns3 #endif /* UDP_SOCKET_FACTORY_IMPL_H */
zy901002-gpsr
src/internet/model/udp-socket-factory-impl.h
C++
gpl2
2,390
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2010 Adrian Sai-wah Tam * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Adrian Sai-wah Tam <adrian.sw.tam@gmail.com> */ #ifndef TCP_TX_BUFFER_H #define TCP_TX_BUFFER_H #include <list> #include "ns3/traced-value.h" #include "ns3/trace-source-accessor.h" #include "ns3/object.h" #include "ns3/sequence-number.h" #include "ns3/ptr.h" namespace ns3 { class Packet; /** * \ingroup tcp * * \brief class for keeping the data sent by the application to the TCP socket, i.e. * the sending buffer. */ class TcpTxBuffer : public Object { public: static TypeId GetTypeId (void); TcpTxBuffer (uint32_t n = 0); virtual ~TcpTxBuffer (void); // Accessors /** * Returns the first byte's sequence number */ SequenceNumber32 HeadSequence (void) const; /** * Returns the last byte's sequence number + 1 */ SequenceNumber32 TailSequence (void) const; /** * Returns total number of bytes in this Tx buffer */ uint32_t Size (void) const; /** * Returns the Tx window size */ uint32_t MaxBufferSize (void) const; /** * Set the Tx window size */ void SetMaxBufferSize (uint32_t n); /** * Returns the available capacity in this Tx window */ uint32_t Available (void) const; /** * Append a data packet to the end of the buffer * * \param p The packet to be appended to the Tx buffer * \return Boolean to indicate success */ bool Add (Ptr<Packet> p); /** * Returns the number of bytes from the buffer in the range [seq, tailSequence) */ uint32_t SizeFromSequence (const SequenceNumber32& seq) const; /** * Copy data of size numBytes into a packet, data from the range [seq, seq+numBytes) */ Ptr<Packet> CopyFromSequence (uint32_t numBytes, const SequenceNumber32& seq); /** * Set the m_firstByteSeq to seq. Supposed to be called only when the * connection is just set up and we did not send any data out yet. */ void SetHeadSequence (const SequenceNumber32& seq); /** * Discard data up to but not including this sequence number. * * \param seq The sequence number of the head byte */ void DiscardUpTo (const SequenceNumber32& seq); private: typedef std::list<Ptr<Packet> >::iterator BufIterator; TracedValue<SequenceNumber32> m_firstByteSeq; //< Sequence number of the first byte in data (SND.UNA) uint32_t m_size; //< Number of data bytes uint32_t m_maxBuffer; //< Max number of data bytes in buffer (SND.WND) std::list<Ptr<Packet> > m_data; //< Corresponding data (may be null) }; } // namepsace ns3 #endif /* TCP_TX_BUFFER_H */
zy901002-gpsr
src/internet/model/tcp-tx-buffer.h
C++
gpl2
3,351