src/internet-stack/ipv4-l3-protocol.cc
author Qasim Javed <qasimj@gmail.com>
Thu Aug 06 01:55:49 2009 +0600 (2009-08-06)
changeset 4638 19aa5f9b4bdf
parent 4637 0882bb6eac0b
permissions -rw-r--r--
Source NAT working! Run (examples/netfilter-example.cc)
     1 // -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*-
     2 //
     3 // Copyright (c) 2006 Georgia Tech Research Corporation
     4 //
     5 // This program is free software; you can redistribute it and/or modify
     6 // it under the terms of the GNU General Public License version 2 as
     7 // published by the Free Software Foundation;
     8 //
     9 // This program is distributed in the hope that it will be useful,
    10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    12 // GNU General Public License for more details.
    13 //
    14 // You should have received a copy of the GNU General Public License
    15 // along with this program; if not, write to the Free Software
    16 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
    17 //
    18 // Author: George F. Riley<riley@ece.gatech.edu>
    19 //
    20 
    21 #include "ns3/packet.h"
    22 #include "ns3/log.h"
    23 #include "ns3/callback.h"
    24 #include "ns3/ipv4-address.h"
    25 #include "ns3/ipv4-route.h"
    26 #include "ns3/node.h"
    27 #include "ns3/socket.h"
    28 #include "ns3/net-device.h"
    29 #include "ns3/uinteger.h"
    30 #include "ns3/trace-source-accessor.h"
    31 #include "ns3/object-vector.h"
    32 #include "ns3/ipv4-header.h"
    33 #include "ns3/boolean.h"
    34 #include "ns3/ipv4-routing-table-entry.h"
    35 
    36 #include "loopback-net-device.h"
    37 #include "arp-l3-protocol.h"
    38 #include "ipv4-l3-protocol.h"
    39 #include "ipv4-l4-protocol.h"
    40 #include "icmpv4-l4-protocol.h"
    41 #include "ipv4-interface.h"
    42 #include "ipv4-raw-socket-impl.h"
    43 
    44 NS_LOG_COMPONENT_DEFINE ("Ipv4L3Protocol");
    45 
    46 namespace ns3 {
    47 
    48 const uint16_t Ipv4L3Protocol::PROT_NUMBER = 0x0800;
    49 
    50 NS_OBJECT_ENSURE_REGISTERED (Ipv4L3Protocol);
    51 
    52 TypeId 
    53 Ipv4L3Protocol::GetTypeId (void)
    54 {
    55   static TypeId tid = TypeId ("ns3::Ipv4L3Protocol")
    56     .SetParent<Ipv4> ()
    57     .AddConstructor<Ipv4L3Protocol> ()
    58     .AddAttribute ("DefaultTtl", "The TTL value set by default on all outgoing packets generated on this node.",
    59                    UintegerValue (64),
    60                    MakeUintegerAccessor (&Ipv4L3Protocol::m_defaultTtl),
    61                    MakeUintegerChecker<uint8_t> ())
    62     .AddTraceSource ("Tx", "Send ipv4 packet to outgoing interface.",
    63                    MakeTraceSourceAccessor (&Ipv4L3Protocol::m_txTrace))
    64     .AddTraceSource ("Rx", "Receive ipv4 packet from incoming interface.",
    65                      MakeTraceSourceAccessor (&Ipv4L3Protocol::m_rxTrace))
    66     .AddTraceSource ("Drop", "Drop ipv4 packet",
    67                      MakeTraceSourceAccessor (&Ipv4L3Protocol::m_dropTrace))
    68     .AddAttribute ("InterfaceList", "The set of Ipv4 interfaces associated to this Ipv4 stack.",
    69                    ObjectVectorValue (),
    70                    MakeObjectVectorAccessor (&Ipv4L3Protocol::m_interfaces),
    71                    MakeObjectVectorChecker<Ipv4Interface> ())
    72     ;
    73   return tid;
    74 }
    75 
    76 uint32_t NfPreRoutingHookFunction (Hooks_t hookNumber, Ptr<Packet> p, Ptr<NetDevice> in, Ptr<NetDevice> out, ContinueCallback& ccb)
    77 {
    78   std::cout << "NfPreRoutingHookFunction called at node " << in->GetNode () << " at NF_PRE_ROUTING" << std::endl;
    79   Ipv4Header ipHeader;
    80 
    81   p->PeekHeader (ipHeader);
    82   
    83   if (ipHeader.GetProtocol () == 6 /* TCP */ )
    84     std::cout << "This is a TCP packet at node " << in->GetNode () << std::endl;
    85   else if (ipHeader.GetProtocol () == 17 /* UDP */ )
    86     std::cout << "This is a UDP packet at node " << in->GetNode () << std::endl;
    87   
    88   //p->Print (std::cout);
    89   //std::cout<<std::endl;
    90 
    91   return 0;
    92 }
    93 
    94 uint32_t NfPostRoutingHookFunction (Hooks_t hookNumber, Ptr<Packet> p, Ptr<NetDevice> in, Ptr<NetDevice> out, ContinueCallback& ccb)
    95 {
    96   std::cout << "NfPostRoutingHookFunction called at node " << out->GetNode () << " at NF_POST_ROUTING" << std::endl;
    97   Ipv4Header ipHeader;
    98 
    99   p->PeekHeader (ipHeader);
   100 
   101   if (ipHeader.GetProtocol () == 6 /* TCP */ )
   102     std::cout << "This is a TCP packet at node " << out->GetNode () << std::endl;
   103   else if (ipHeader.GetProtocol () == 17 /* UDP */ )
   104     std::cout << "This is a UDP packet at node " << out->GetNode () << std::endl;
   105   
   106   //p->Print (std::cout);
   107   //std::cout<<std::endl;
   108 
   109   return 0;
   110 }
   111 
   112 Ipv4L3Protocol::Ipv4L3Protocol ()
   113   : m_nInterfaces (0),
   114     m_identification (0)
   115 {
   116   NS_LOG_FUNCTION_NOARGS ();
   117   /*NetfilterHookCallback nhc = MakeCallback(&NfPreRoutingHookFunction);
   118   NetfilterHookCallback nhc2 = MakeCallback(&NfPostRoutingHookFunction);
   119   Ipv4NetfilterHook nfh = Ipv4NetfilterHook(1, NF_INET_PRE_ROUTING, 2, nhc); 
   120   Ipv4NetfilterHook nfh2 = Ipv4NetfilterHook(1, NF_INET_POST_ROUTING, 2, nhc2); 
   121   netfilter.RegisterNetfilterHook(nfh);
   122   netfilter.RegisterNetfilterHook(nfh2);*/
   123 }
   124 
   125 Ipv4L3Protocol::~Ipv4L3Protocol ()
   126 {
   127   NS_LOG_FUNCTION (this);
   128 }
   129 
   130 void
   131 Ipv4L3Protocol::Insert(Ptr<Ipv4L4Protocol> protocol)
   132 {
   133   m_protocols.push_back (protocol);
   134 }
   135 Ptr<Ipv4L4Protocol>
   136 Ipv4L3Protocol::GetProtocol (int protocolNumber) const
   137 {
   138   for (L4List_t::const_iterator i = m_protocols.begin (); i != m_protocols.end (); ++i)
   139     {
   140       if ((*i)->GetProtocolNumber () == protocolNumber)
   141 	{
   142 	  return *i;
   143 	}
   144     }
   145   return 0;
   146 }
   147 void
   148 Ipv4L3Protocol::Remove (Ptr<Ipv4L4Protocol> protocol)
   149 {
   150   m_protocols.remove (protocol);
   151 }
   152 
   153 void
   154 Ipv4L3Protocol::SetNode (Ptr<Node> node)
   155 {
   156   m_node = node;
   157   // Add a LoopbackNetDevice if needed, and an Ipv4Interface on top of it
   158   SetupLoopback ();
   159 }
   160 
   161 Ptr<Socket> 
   162 Ipv4L3Protocol::CreateRawSocket (void)
   163 {
   164   NS_LOG_FUNCTION (this);
   165   Ptr<Ipv4RawSocketImpl> socket = CreateObject<Ipv4RawSocketImpl> ();
   166   socket->SetNode (m_node);
   167   m_sockets.push_back (socket);
   168   return socket;
   169 }
   170 void 
   171 Ipv4L3Protocol::DeleteRawSocket (Ptr<Socket> socket)
   172 {
   173   NS_LOG_FUNCTION (this << socket);
   174   for (SocketList::iterator i = m_sockets.begin (); i != m_sockets.end (); ++i)
   175     {
   176       if ((*i) == socket)
   177         {
   178           m_sockets.erase (i);
   179           return;
   180         }
   181     }
   182   return;
   183 }
   184 /*
   185  * This method is called by AddAgregate and completes the aggregation
   186  * by setting the node in the ipv4 stack
   187  */
   188 void
   189 Ipv4L3Protocol::NotifyNewAggregate ()
   190 {
   191   Ptr<Node>node = this->GetObject<Node>();
   192   // verify that it's a valid node and that
   193   // the node has not been set before
   194   if (node!= 0 && m_node == 0)
   195     {
   196       this->SetNode (node);
   197     }
   198   Object::NotifyNewAggregate ();
   199 }
   200 
   201 void 
   202 Ipv4L3Protocol::SetRoutingProtocol (Ptr<Ipv4RoutingProtocol> routingProtocol)
   203 {
   204   NS_LOG_FUNCTION (this);
   205   m_routingProtocol = routingProtocol;
   206   m_routingProtocol->SetIpv4 (this);
   207 }
   208 
   209 
   210 Ptr<Ipv4RoutingProtocol> 
   211 Ipv4L3Protocol::GetRoutingProtocol (void) const
   212 {
   213   return m_routingProtocol;
   214 }
   215 
   216 void 
   217 Ipv4L3Protocol::DoDispose (void)
   218 {
   219   NS_LOG_FUNCTION (this);
   220   for (L4List_t::iterator i = m_protocols.begin (); i != m_protocols.end (); ++i)
   221     {
   222       *i = 0;
   223     }
   224   m_protocols.clear ();
   225 
   226   for (Ipv4InterfaceList::iterator i = m_interfaces.begin (); i != m_interfaces.end (); ++i)
   227     {
   228       *i = 0;
   229     }
   230   m_interfaces.clear ();
   231   m_node = 0;
   232   m_routingProtocol = 0;
   233   Object::DoDispose ();
   234 }
   235 
   236 void
   237 Ipv4L3Protocol::SetupLoopback (void)
   238 {
   239   NS_LOG_FUNCTION_NOARGS ();
   240 
   241   Ptr<Ipv4Interface> interface = CreateObject<Ipv4Interface> ();
   242   Ptr<LoopbackNetDevice> device = 0;
   243   // First check whether an existing LoopbackNetDevice exists on the node
   244   for (uint32_t i = 0; i < m_node->GetNDevices (); i++)
   245     {
   246       if (device = DynamicCast<LoopbackNetDevice> (m_node->GetDevice (i)))
   247         {
   248           break;
   249         }
   250     }
   251   if (device == 0)
   252     {
   253       device = CreateObject<LoopbackNetDevice> (); 
   254       m_node->AddDevice (device);
   255     }
   256   interface->SetDevice (device);
   257   interface->SetNode (m_node);
   258   Ipv4InterfaceAddress ifaceAddr = Ipv4InterfaceAddress (Ipv4Address::GetLoopback (), Ipv4Mask::GetLoopback ());
   259   interface->AddAddress (ifaceAddr);
   260   uint32_t index = AddIpv4Interface (interface);
   261   Ptr<Node> node = GetObject<Node> ();
   262   node->RegisterProtocolHandler (MakeCallback (&Ipv4L3Protocol::Receive, this), 
   263                                  Ipv4L3Protocol::PROT_NUMBER, device);
   264   interface->SetUp ();
   265   if (m_routingProtocol != 0)
   266     {
   267       m_routingProtocol->NotifyInterfaceUp (index);
   268     }
   269 }
   270 
   271 void 
   272 Ipv4L3Protocol::SetDefaultTtl (uint8_t ttl)
   273 {
   274   NS_LOG_FUNCTION_NOARGS ();
   275   m_defaultTtl = ttl;
   276 }
   277     
   278 uint32_t 
   279 Ipv4L3Protocol::AddInterface (Ptr<NetDevice> device)
   280 {
   281   NS_LOG_FUNCTION (this << &device);
   282 
   283   Ptr<Node> node = GetObject<Node> ();
   284   node->RegisterProtocolHandler (MakeCallback (&Ipv4L3Protocol::Receive, this), 
   285                                  Ipv4L3Protocol::PROT_NUMBER, device);
   286   node->RegisterProtocolHandler (MakeCallback (&ArpL3Protocol::Receive, PeekPointer (GetObject<ArpL3Protocol> ())),
   287                                  ArpL3Protocol::PROT_NUMBER, device);
   288 
   289   Ptr<Ipv4Interface> interface = CreateObject<Ipv4Interface> ();
   290   interface->SetNode (m_node);
   291   interface->SetDevice (device);
   292   interface->SetForwarding (m_ipForward);
   293   return AddIpv4Interface (interface);
   294 }
   295 
   296 uint32_t 
   297 Ipv4L3Protocol::AddIpv4Interface (Ptr<Ipv4Interface>interface)
   298 {
   299   NS_LOG_FUNCTION (this << interface);
   300   uint32_t index = m_nInterfaces;
   301   m_interfaces.push_back (interface);
   302   m_nInterfaces++;
   303   return index;
   304 }
   305 
   306 Ptr<Ipv4Interface>
   307 Ipv4L3Protocol::GetInterface (uint32_t index) const
   308 {
   309   NS_LOG_FUNCTION (this << index);
   310   uint32_t tmp = 0;
   311   for (Ipv4InterfaceList::const_iterator i = m_interfaces.begin (); i != m_interfaces.end (); i++)
   312     {
   313       if (index == tmp) 
   314 	{
   315 	  return *i;
   316 	}
   317       tmp++;
   318     }
   319   return 0;
   320 }
   321 
   322 uint32_t 
   323 Ipv4L3Protocol::GetNInterfaces (void) const
   324 {
   325   NS_LOG_FUNCTION_NOARGS ();
   326   return m_nInterfaces;
   327 }
   328 
   329 int32_t 
   330 Ipv4L3Protocol::GetInterfaceForAddress (
   331   Ipv4Address address) const
   332 {
   333   NS_LOG_FUNCTION (this << address);
   334 
   335   int32_t interface = 0;
   336   for (Ipv4InterfaceList::const_iterator i = m_interfaces.begin (); 
   337        i != m_interfaces.end (); 
   338        i++, interface++)
   339     {
   340       for (uint32_t j = 0; j < (*i)->GetNAddresses (); j++)
   341         {
   342           if ((*i)->GetAddress (j).GetLocal () == address)
   343             {
   344               return interface;
   345             }
   346         }
   347     }
   348 
   349   return -1;
   350 }
   351 
   352 int32_t 
   353 Ipv4L3Protocol::GetInterfaceForPrefix (
   354   Ipv4Address address, 
   355   Ipv4Mask mask) const
   356 {
   357   NS_LOG_FUNCTION (this << address << mask);
   358 
   359   int32_t interface = 0;
   360   for (Ipv4InterfaceList::const_iterator i = m_interfaces.begin (); 
   361        i != m_interfaces.end (); 
   362        i++, interface++)
   363     {
   364       for (uint32_t j = 0; j < (*i)->GetNAddresses (); j++)
   365         {
   366           if ((*i)->GetAddress (j).GetLocal ().CombineMask (mask) == address.CombineMask (mask))
   367             {
   368               return interface;
   369             }
   370         }
   371     }
   372 
   373   return -1;
   374 }
   375 
   376 int32_t 
   377 Ipv4L3Protocol::GetInterfaceForDevice (
   378   Ptr<const NetDevice> device) const
   379 {
   380   NS_LOG_FUNCTION (this << device->GetIfIndex());
   381 
   382   int32_t interface = 0;
   383   for (Ipv4InterfaceList::const_iterator i = m_interfaces.begin (); 
   384        i != m_interfaces.end (); 
   385        i++, interface++)
   386     {
   387       if ((*i)->GetDevice () == device)
   388         {
   389           return interface;
   390         }
   391     }
   392 
   393   return -1;
   394 }
   395 
   396 void 
   397 Ipv4L3Protocol::Receive( Ptr<NetDevice> device, Ptr<const Packet> p, uint16_t protocol, const Address &from,
   398                          const Address &to, NetDevice::PacketType packetType)
   399 {
   400   NS_LOG_FUNCTION (this << &device << p << protocol <<  from);
   401 
   402   NS_LOG_LOGIC ("Packet from " << from << " received on node " << 
   403     m_node->GetId ());
   404 
   405   uint32_t interface = 0;
   406   Ptr<Packet> packet = p->Copy ();
   407   
   408   // TODO: Netfilter
   409   
   410   NS_LOG_DEBUG ("NF_INET_PRE_ROUTING Hook");
   411   netfilter.ProcessHook ((uint8_t)1, NF_INET_PRE_ROUTING, packet, device, device);
   412 
   413   Ptr<Ipv4Interface> ipv4Interface;
   414   for (Ipv4InterfaceList::const_iterator i = m_interfaces.begin (); 
   415        i != m_interfaces.end (); 
   416        i++)
   417     {
   418       ipv4Interface = *i;
   419       if (ipv4Interface->GetDevice () == device)
   420         {
   421           if (ipv4Interface->IsUp ())
   422             {
   423               m_rxTrace (packet, interface);
   424               break;
   425             }
   426           else
   427             {
   428               NS_LOG_LOGIC ("Dropping received packet-- interface is down");
   429               m_dropTrace (packet);
   430               return;
   431             }
   432         }
   433       interface++;
   434     }
   435 
   436   Ipv4Header ipHeader;
   437   if (Node::ChecksumEnabled ())
   438     {
   439       ipHeader.EnableChecksum ();
   440     }
   441   packet->RemoveHeader (ipHeader);
   442 
   443   if (!ipHeader.IsChecksumOk ()) 
   444     {
   445       m_dropTrace (packet);
   446       return;
   447     }
   448 
   449   for (SocketList::iterator i = m_sockets.begin (); i != m_sockets.end (); ++i)
   450     {
   451       Ptr<Ipv4RawSocketImpl> socket = *i;
   452       socket->ForwardUp (packet, ipHeader, device);
   453     }
   454 
   455   m_routingProtocol->RouteInput (packet, ipHeader, device, 
   456     MakeCallback (&Ipv4L3Protocol::IpForward, this),
   457     MakeCallback (&Ipv4L3Protocol::IpMulticastForward, this),
   458     MakeCallback (&Ipv4L3Protocol::LocalDeliver, this),
   459     MakeCallback (&Ipv4L3Protocol::RouteInputError, this)
   460   );
   461 
   462 }
   463 
   464 Ptr<Icmpv4L4Protocol> 
   465 Ipv4L3Protocol::GetIcmp (void) const
   466 {
   467   Ptr<Ipv4L4Protocol> prot = GetProtocol (Icmpv4L4Protocol::GetStaticProtocolNumber ());
   468   if (prot != 0)
   469     {
   470       return prot->GetObject<Icmpv4L4Protocol> ();
   471     }
   472   else
   473     {
   474       return 0;
   475     }
   476 }
   477 
   478 bool
   479 Ipv4L3Protocol::IsUnicast (Ipv4Address ad, Ipv4Mask interfaceMask) const
   480 {
   481   return !ad.IsMulticast () && !ad.IsSubnetDirectedBroadcast (interfaceMask);
   482 }
   483 
   484 void 
   485 Ipv4L3Protocol::Send (Ptr<Packet> packet, 
   486             Ipv4Address source, 
   487             Ipv4Address destination,
   488             uint8_t protocol,
   489             Ptr<Ipv4Route> route)
   490 {
   491   NS_LOG_FUNCTION (this << packet << source << destination << uint32_t(protocol) << route);
   492 
   493   Ipv4Header ipHeader;
   494   bool mayFragment = true;
   495   uint8_t ttl = m_defaultTtl;
   496   SocketIpTtlTag tag;
   497   Ptr<NetDevice> outDev;
   498 
   499   if (!route) 
   500   {
   501     std::cout<< "Route: " << *route << std::endl;
   502     outDev = route->GetOutputDevice ();
   503   }
   504 
   505   // Netfilter LOCAL_OUT Hook
   506   //Ptr<Packet> packetCopy = packet->Copy ();
   507 
   508   bool found = packet->RemovePacketTag (tag);
   509   if (found)
   510     {
   511       ttl = tag.GetTtl ();
   512     }
   513 
   514   // Handle a few cases:
   515   // 1) packet is destined to limited broadcast address
   516   // 2) packet is destined to a subnet-directed broadcast address
   517   // 3) packet is not broadcast, and is passed in with a route entry
   518   // 4) packet is not broadcast, and is passed in with a route entry but route->GetGateway is not set (e.g., on-demand)
   519   // 5) packet is not broadcast, and route is NULL (e.g., a raw socket call, or ICMP)
   520   
   521   // 1) packet is destined to limited broadcast address
   522   if (destination.IsBroadcast ()) 
   523     {
   524       NS_LOG_LOGIC ("Ipv4L3Protocol::Send case 1:  limited broadcast");
   525       ttl = 1;
   526       ipHeader = BuildHeader (source, destination, protocol, packet->GetSize (), ttl, mayFragment);
   527       uint32_t ifaceIndex = 0;
   528       for (Ipv4InterfaceList::iterator ifaceIter = m_interfaces.begin ();
   529            ifaceIter != m_interfaces.end (); ifaceIter++, ifaceIndex++)
   530       {
   531         Ptr<Ipv4Interface> outInterface = *ifaceIter;
   532         Ptr<Packet> packetCopy = packet->Copy ();
   533 
   534         NS_ASSERT (packetCopy->GetSize () <= outInterface->GetDevice()->GetMtu ());
   535         packetCopy->AddHeader (ipHeader);
   536 
   537         /*NS_LOG_DEBUG ("NF_INET_LOCAL_OUT Hook");
   538         netfilter.ProcessHook ((uint8_t)1, NF_INET_LOCAL_OUT, packetCopy, outDev, outDev);*/
   539 
   540         NS_LOG_DEBUG ("NF_INET_POST_ROUTING Hook");
   541         Callback<uint32_t, Ptr<Packet> > ccb = MakeCallback (&Ipv4Netfilter::NetfilterConntrackConfirm, &netfilter);
   542         netfilter.ProcessHook ((uint8_t)1, NF_INET_POST_ROUTING, packetCopy, outDev, outDev, ccb);
   543 
   544         m_txTrace (packetCopy, ifaceIndex);
   545         outInterface->Send (packetCopy, destination);
   546       }
   547       return;
   548     }
   549 
   550   // 2) check: packet is destined to a subnet-directed broadcast address
   551   uint32_t ifaceIndex = 0;
   552   for (Ipv4InterfaceList::iterator ifaceIter = m_interfaces.begin ();
   553     ifaceIter != m_interfaces.end (); ifaceIter++, ifaceIndex++)
   554     {
   555       Ptr<Ipv4Interface> outInterface = *ifaceIter;
   556       for (uint32_t j = 0; j < GetNAddresses (ifaceIndex); j++)
   557         {
   558           Ipv4InterfaceAddress ifAddr = GetAddress (ifaceIndex, j);
   559           NS_LOG_LOGIC ("Testing address " << ifAddr.GetLocal () << " with mask " << ifAddr.GetMask ());
   560           if (destination.IsSubnetDirectedBroadcast (ifAddr.GetMask ()) && 
   561               destination.CombineMask (ifAddr.GetMask ()) == ifAddr.GetLocal ().CombineMask (ifAddr.GetMask ())   )  
   562           {
   563             NS_LOG_LOGIC ("Ipv4L3Protocol::Send case 2:  subnet directed bcast to " << ifAddr.GetLocal ());
   564             ttl = 1;
   565             ipHeader = BuildHeader (source, destination, protocol, packet->GetSize (), ttl, mayFragment);
   566             Ptr<Packet> packetCopy = packet->Copy ();
   567             packetCopy->AddHeader (ipHeader);
   568 
   569             /*NS_LOG_DEBUG ("NF_INET_LOCAL_OUT Hook");
   570             netfilter.ProcessHook ((uint8_t)1, NF_INET_LOCAL_OUT, packetCopy, outDev, outDev);*/
   571 
   572             NS_LOG_DEBUG ("NF_INET_POST_ROUTING Hook");
   573             Callback<uint32_t, Ptr<Packet> > ccb = MakeCallback (&Ipv4Netfilter::NetfilterConntrackConfirm, &netfilter);
   574             netfilter.ProcessHook ((uint8_t)1, NF_INET_POST_ROUTING, packetCopy, outDev, outDev, ccb);
   575 
   576             m_txTrace (packetCopy, ifaceIndex);
   577             outInterface->Send (packetCopy, destination);
   578             return;
   579           }
   580         }
   581     }
   582 
   583   // 3) packet is not broadcast, and is passed in with a route entry
   584   //    with a valid Ipv4Address as the gateway
   585   if (route && route->GetGateway () != Ipv4Address ())
   586   {
   587     NS_LOG_LOGIC ("Ipv4L3Protocol::Send case 3:  passed in with route");
   588 
   589     Ptr<Packet> packetCopy = packet->Copy ();
   590     NS_LOG_DEBUG ("NF_INET_LOCAL_OUT Hook");
   591     ipHeader = BuildHeader (source, destination, protocol, packetCopy->GetSize (), ttl, mayFragment);
   592     packetCopy->AddHeader (ipHeader);
   593     NS_LOG_DEBUG (" :: Add Ipv4 Header :: ");
   594     netfilter.ProcessHook ((uint8_t)1, NF_INET_LOCAL_OUT, packetCopy, outDev, outDev);
   595     NS_LOG_DEBUG (" :: Remove Ipv4 Header :: ");
   596     packetCopy->RemoveHeader (ipHeader);
   597 
   598     SendRealOut (route, packetCopy, ipHeader);
   599     return; 
   600   } 
   601   // 4) packet is not broadcast, and is passed in with a route entry but route->GetGateway is not set (e.g., on-demand)
   602   if (route && route->GetGateway () != Ipv4Address ())
   603     {
   604       // This could arise because the synchronous RouteOutput() call
   605       // returned to the transport protocol with a source address but
   606       // there was no next hop available yet (since a route may need
   607       // to be queried).  
   608       NS_FATAL_ERROR ("This case not yet implemented");
   609     }
   610   // 5) packet is not broadcast, and route is NULL (e.g., a raw socket call)
   611   NS_LOG_LOGIC ("Ipv4L3Protocol::Send case 4:  passed in with no route " << destination);
   612   Ptr<Packet> packetCopy = packet->Copy ();
   613   Socket::SocketErrno errno_; 
   614   uint32_t oif = 0; // unused for now
   615   ipHeader = BuildHeader (source, destination, protocol, packet->GetSize (), ttl, mayFragment);
   616   
   617   NS_LOG_DEBUG (" :: Add Ipv4 Header :: ");
   618   packetCopy->AddHeader (ipHeader);
   619   NS_LOG_DEBUG ("NF_INET_LOCAL_OUT Hook");
   620   netfilter.ProcessHook ((uint8_t)1, NF_INET_LOCAL_OUT, packetCopy, outDev, outDev);
   621   NS_LOG_DEBUG (" :: Remove Ipv4 Header :: ");
   622   packetCopy->RemoveHeader (ipHeader);
   623 
   624   Ptr<Ipv4Route> newRoute = m_routingProtocol->RouteOutput (packet, ipHeader, oif, errno_);
   625   if (newRoute)
   626     {
   627       SendRealOut (newRoute, packet, ipHeader);
   628     }
   629   else
   630     {
   631       NS_LOG_WARN ("No route to host.  Drop.");
   632       m_dropTrace (packet);
   633     }
   634 }
   635 
   636 // XXX when should we set ip_id?   check whether we are incrementing
   637 // m_identification on packets that may later be dropped in this stack
   638 // and whether that deviates from Linux
   639 Ipv4Header
   640 Ipv4L3Protocol::BuildHeader (
   641             Ipv4Address source, 
   642             Ipv4Address destination,
   643             uint8_t protocol,
   644             uint16_t payloadSize,
   645             uint8_t ttl,
   646             bool mayFragment)
   647 {
   648   NS_LOG_FUNCTION_NOARGS ();
   649   Ipv4Header ipHeader;
   650   ipHeader.SetSource (source);
   651   ipHeader.SetDestination (destination);
   652   ipHeader.SetProtocol (protocol);
   653   ipHeader.SetPayloadSize (payloadSize);
   654   ipHeader.SetTtl (ttl);
   655   if (mayFragment == true)
   656     {
   657       ipHeader.SetMayFragment ();
   658       ipHeader.SetIdentification (m_identification);
   659       m_identification ++;
   660     }
   661   else
   662     {
   663       ipHeader.SetDontFragment ();
   664       // TBD:  set to zero here; will cause traces to change
   665       ipHeader.SetIdentification (m_identification);
   666       m_identification ++;
   667     }
   668   if (Node::ChecksumEnabled ())
   669     {
   670       ipHeader.EnableChecksum ();
   671     }
   672   return ipHeader;
   673 }
   674 
   675 void
   676 Ipv4L3Protocol::SendRealOut (Ptr<Ipv4Route> route,
   677                              Ptr<Packet> packet,
   678                              Ipv4Header const &ipHeader)
   679 {
   680   NS_LOG_FUNCTION (this << packet << &ipHeader);
   681   Ptr<NetDevice> outDev = route->GetOutputDevice ();
   682 
   683   // We add a header regardless of whether there is a route, since 
   684   // we may want to drop trace
   685   packet->AddHeader (ipHeader);
   686 
   687   Callback<uint32_t, Ptr<Packet> > ccb = MakeCallback (&Ipv4Netfilter::NetfilterConntrackConfirm, &netfilter);
   688   NS_LOG_DEBUG ("NF_INET_POST_ROUTING Hook");
   689   netfilter.ProcessHook ((uint8_t)1, NF_INET_POST_ROUTING, packet, outDev, outDev, ccb);
   690 
   691   if (route == 0)
   692     {
   693       NS_LOG_WARN ("No route to host.  Drop.");
   694       m_dropTrace (packet);
   695       return;
   696     }
   697 
   698   int32_t interface = GetInterfaceForDevice (outDev);
   699   NS_ASSERT (interface >= 0);
   700   Ptr<Ipv4Interface> outInterface = GetInterface (interface);
   701   NS_LOG_LOGIC ("Send via NetDevice ifIndex " << outDev->GetIfIndex () << " ipv4InterfaceIndex " << interface);
   702 
   703   NS_ASSERT (packet->GetSize () <= outInterface->GetDevice ()->GetMtu ());
   704   if (!route->GetGateway ().IsEqual (Ipv4Address ("0.0.0.0"))) 
   705     {
   706       if (outInterface->IsUp ())
   707         {
   708           NS_LOG_LOGIC ("Send to gateway " << route->GetGateway ());
   709           m_txTrace (packet, interface);
   710           outInterface->Send (packet, route->GetGateway ());
   711         }
   712       else
   713         {
   714           NS_LOG_LOGIC ("Dropping-- outgoing interface is down: " << route->GetGateway ());
   715           m_dropTrace (packet);
   716         }
   717     } 
   718   else 
   719     {
   720       if (outInterface->IsUp ())
   721         {
   722           NS_LOG_LOGIC ("Send to destination " << ipHeader.GetDestination ());
   723           m_txTrace (packet, interface);
   724           outInterface->Send (packet, ipHeader.GetDestination ());
   725         }
   726       else
   727         {
   728           NS_LOG_LOGIC ("Dropping-- outgoing interface is down: " << ipHeader.GetDestination ());
   729           m_dropTrace (packet);
   730         }
   731     }
   732 }
   733 
   734 // This function analogous to Linux ip_mr_forward()
   735 void
   736 Ipv4L3Protocol::IpMulticastForward (Ptr<Ipv4MulticastRoute> mrtentry, Ptr<const Packet> p, const Ipv4Header &header)
   737 {
   738   NS_LOG_FUNCTION (mrtentry << p << header);
   739   NS_LOG_LOGIC ("Multicast forwarding logic for node: " << m_node->GetId ());
   740   // The output interfaces we could forward this onto are encoded
   741   // in the OutputTtl of the Ipv4MulticastRoute
   742   for (uint32_t i = 0; i < Ipv4MulticastRoute::MAX_INTERFACES; i++)
   743     {
   744       if (mrtentry->GetOutputTtl (i) < Ipv4MulticastRoute::MAX_TTL)
   745         {
   746           Ptr<Packet> packet = p->Copy ();
   747           Ipv4Header h = header;
   748           h.SetTtl (header.GetTtl () - 1);
   749           if (h.GetTtl () == 0)
   750             {
   751               NS_LOG_WARN ("TTL exceeded.  Drop.");
   752               m_dropTrace (packet);
   753               return;
   754             }
   755           NS_LOG_LOGIC ("Forward multicast via interface " << i);
   756           Ptr<Ipv4Route> rtentry = Create<Ipv4Route> ();
   757           rtentry->SetSource (h.GetSource ());
   758           rtentry->SetDestination (h.GetDestination ());
   759           rtentry->SetGateway (Ipv4Address::GetAny ());
   760           rtentry->SetOutputDevice (GetNetDevice (i));
   761           SendRealOut (rtentry, packet, h);
   762           return; 
   763         }
   764     }
   765 }
   766 
   767 // This function analogous to Linux ip_forward()
   768 void
   769 Ipv4L3Protocol::IpForward (Ptr<Ipv4Route> rtentry, Ptr<const Packet> p, const Ipv4Header &header)
   770 {
   771   NS_LOG_FUNCTION (rtentry << p << header);
   772   NS_LOG_LOGIC ("Forwarding logic for node: " << m_node->GetId ());
   773   // Forwarding
   774   Ipv4Header ipHeader = header;
   775   Ptr<Packet> packet = p->Copy ();
   776   Ptr<NetDevice> outDev = rtentry->GetOutputDevice ();
   777   ipHeader.SetTtl (ipHeader.GetTtl () - 1);
   778   if (ipHeader.GetTtl () == 0)
   779     {
   780       // Do not reply to ICMP or to multicast/broadcast IP address 
   781       if (ipHeader.GetProtocol () != Icmpv4L4Protocol::PROT_NUMBER && 
   782         ipHeader.GetDestination ().IsBroadcast () == false && 
   783         ipHeader.GetDestination ().IsMulticast () == false)
   784         {
   785           Ptr<Icmpv4L4Protocol> icmp = GetIcmp ();
   786           icmp->SendTimeExceededTtl (ipHeader, packet);
   787         }
   788       NS_LOG_WARN ("TTL exceeded.  Drop.");
   789       m_dropTrace (packet);
   790       return;
   791     }
   792   // Netfilter FORWARD Hook
   793   NS_LOG_DEBUG ("NF_INET_FORWARD Hook");
   794   netfilter.ProcessHook ((uint8_t)1, NF_INET_FORWARD, packet, outDev, outDev);
   795 
   796   SendRealOut (rtentry, packet, ipHeader);
   797 }
   798 
   799 void
   800 Ipv4L3Protocol::LocalDeliver (Ptr<const Packet> packet, Ipv4Header const&ip, uint32_t iif)
   801 {
   802   NS_LOG_FUNCTION (this << packet << &ip);
   803   Ptr<Packet> pkt = packet->Copy (); // need to pass a non-const packet up
   804   
   805   // Netfilter LOCAL_IN Hook
   806   Ptr<NetDevice> device;
   807   pkt->AddHeader(ip);
   808   Callback<uint32_t, Ptr<Packet> > ccb = MakeCallback (&Ipv4Netfilter::NetfilterConntrackConfirm, &netfilter);
   809   NS_LOG_DEBUG ("NF_INET_LOCAL_IN Hook");
   810   netfilter.ProcessHook ((uint8_t)1, NF_INET_LOCAL_IN, pkt, device, device, ccb);
   811   
   812 
   813   Ptr<Packet> p = packet->Copy (); // need to pass a non-const packet up
   814   //p->RemoveHeader(ip);
   815 
   816   Ptr<Ipv4L4Protocol> protocol = GetProtocol (ip.GetProtocol ());
   817   if (protocol != 0)
   818     {
   819       // we need to make a copy in the unlikely event we hit the
   820       // RX_ENDPOINT_UNREACH codepath
   821       Ptr<Packet> copy = p->Copy ();
   822       enum Ipv4L4Protocol::RxStatus status = 
   823         protocol->Receive (p, ip.GetSource (), ip.GetDestination (), GetInterface (iif));
   824       switch (status) {
   825       case Ipv4L4Protocol::RX_OK:
   826         // fall through
   827       case Ipv4L4Protocol::RX_CSUM_FAILED:
   828         break;
   829       case Ipv4L4Protocol::RX_ENDPOINT_UNREACH:
   830         if (ip.GetDestination ().IsBroadcast () == true || 
   831           ip.GetDestination ().IsMulticast () == true)
   832           {
   833             break;  // Do not reply to broadcast or multicast
   834           }
   835         // Another case to suppress ICMP is a subnet-directed broadcast
   836         bool subnetDirected = false;
   837         for (uint32_t i = 0; i < GetNAddresses (iif); i++)
   838           {
   839             Ipv4InterfaceAddress addr = GetAddress (iif, i);
   840             if (addr.GetLocal ().CombineMask (addr.GetMask ()) == ip.GetDestination ().CombineMask (addr.GetMask ()) &&
   841               ip.GetDestination ().IsSubnetDirectedBroadcast (addr.GetMask ()))
   842               {
   843                 subnetDirected = true;
   844               }
   845           }
   846         if (subnetDirected == false)
   847           {
   848             GetIcmp ()->SendDestUnreachPort (ip, copy);
   849           }
   850       }
   851     }
   852 }
   853 
   854 bool
   855 Ipv4L3Protocol::AddAddress (uint32_t i, Ipv4InterfaceAddress address)
   856 {
   857   NS_LOG_FUNCTION (this << i << address);
   858   Ptr<Ipv4Interface> interface = GetInterface (i);
   859   bool retVal = interface->AddAddress (address);
   860   if (m_routingProtocol != 0)
   861     {
   862       m_routingProtocol->NotifyAddAddress (i, address);
   863     }
   864   return retVal;
   865 }
   866 
   867 Ipv4InterfaceAddress 
   868 Ipv4L3Protocol::GetAddress (uint32_t interfaceIndex, uint32_t addressIndex) const
   869 {
   870   NS_LOG_FUNCTION (this << interfaceIndex << addressIndex);
   871   Ptr<Ipv4Interface> interface = GetInterface (interfaceIndex);
   872   return interface->GetAddress (addressIndex);
   873 }
   874 
   875 uint32_t 
   876 Ipv4L3Protocol::GetNAddresses (uint32_t interface) const
   877 {
   878   NS_LOG_FUNCTION (this << interface);
   879   Ptr<Ipv4Interface> iface = GetInterface (interface);
   880   return iface->GetNAddresses ();
   881 }
   882 
   883 bool
   884 Ipv4L3Protocol::RemoveAddress (uint32_t i, uint32_t addressIndex)
   885 {
   886   NS_LOG_FUNCTION (this << i << addressIndex);
   887   Ptr<Ipv4Interface> interface = GetInterface (i);
   888   Ipv4InterfaceAddress address = interface->RemoveAddress (addressIndex);
   889   if (address != Ipv4InterfaceAddress ())
   890     {
   891       if (m_routingProtocol != 0)
   892         {
   893           m_routingProtocol->NotifyRemoveAddress (i, address);
   894         }
   895       return true;
   896     }
   897   return false;
   898 }
   899 
   900 void 
   901 Ipv4L3Protocol::SetMetric (uint32_t i, uint16_t metric)
   902 {
   903   NS_LOG_FUNCTION (i << metric);
   904   Ptr<Ipv4Interface> interface = GetInterface (i);
   905   interface->SetMetric (metric);
   906 }
   907 
   908 uint16_t
   909 Ipv4L3Protocol::GetMetric (uint32_t i) const
   910 {
   911   NS_LOG_FUNCTION (i);
   912   Ptr<Ipv4Interface> interface = GetInterface (i);
   913   return interface->GetMetric ();
   914 }
   915 
   916 uint16_t 
   917 Ipv4L3Protocol::GetMtu (uint32_t i) const
   918 {
   919   NS_LOG_FUNCTION (this << i);
   920   Ptr<Ipv4Interface> interface = GetInterface (i);
   921   return interface->GetDevice ()->GetMtu ();
   922 }
   923 
   924 bool 
   925 Ipv4L3Protocol::IsUp (uint32_t i) const
   926 {
   927   NS_LOG_FUNCTION (this << i);
   928   Ptr<Ipv4Interface> interface = GetInterface (i);
   929   return interface->IsUp ();
   930 }
   931 
   932 void 
   933 Ipv4L3Protocol::SetUp (uint32_t i)
   934 {
   935   NS_LOG_FUNCTION (this << i);
   936   Ptr<Ipv4Interface> interface = GetInterface (i);
   937   interface->SetUp ();
   938 
   939   if (m_routingProtocol != 0)
   940     {
   941       m_routingProtocol->NotifyInterfaceUp (i);
   942     }
   943 }
   944 
   945 void 
   946 Ipv4L3Protocol::SetDown (uint32_t ifaceIndex)
   947 {
   948   NS_LOG_FUNCTION (this << ifaceIndex);
   949   Ptr<Ipv4Interface> interface = GetInterface (ifaceIndex);
   950   interface->SetDown ();
   951 
   952   if (m_routingProtocol != 0)
   953     {
   954       m_routingProtocol->NotifyInterfaceDown (ifaceIndex);
   955     }
   956 }
   957 
   958 bool 
   959 Ipv4L3Protocol::IsForwarding (uint32_t i) const
   960 {
   961   NS_LOG_FUNCTION (this << i);
   962   Ptr<Ipv4Interface> interface = GetInterface (i);
   963   NS_LOG_LOGIC ("Forwarding state: " << interface->IsForwarding ());
   964   return interface->IsForwarding ();
   965 }
   966 
   967 void 
   968 Ipv4L3Protocol::SetForwarding (uint32_t i, bool val)
   969 {
   970   NS_LOG_FUNCTION (this << i);
   971   Ptr<Ipv4Interface> interface = GetInterface (i);
   972   interface->SetForwarding (val);
   973 }
   974 
   975 Ptr<NetDevice>
   976 Ipv4L3Protocol::GetNetDevice (uint32_t i)
   977 {
   978   NS_LOG_FUNCTION (this << i);
   979   return GetInterface (i)-> GetDevice ();
   980 }
   981 
   982 void 
   983 Ipv4L3Protocol::SetIpForward (bool forward) 
   984 {
   985   NS_LOG_FUNCTION (this << forward);
   986   m_ipForward = forward;
   987   for (Ipv4InterfaceList::const_iterator i = m_interfaces.begin (); i != m_interfaces.end (); i++)
   988     {
   989       (*i)->SetForwarding (forward);
   990     }
   991 }
   992 
   993 bool 
   994 Ipv4L3Protocol::GetIpForward (void) const
   995 {
   996   return m_ipForward;
   997 }
   998 
   999 void
  1000 Ipv4L3Protocol::RouteInputError (Ptr<const Packet> p, const Ipv4Header & ipHeader, Socket::SocketErrno sockErrno)
  1001 {
  1002   NS_LOG_FUNCTION (this << p << ipHeader << sockErrno);
  1003   NS_LOG_LOGIC ("Route input failure-- dropping packet to " << ipHeader << " with errno " << sockErrno); 
  1004   m_dropTrace (p);
  1005 }
  1006   
  1007 Ipv4Netfilter* 
  1008 Ipv4L3Protocol::GetNetfilter()
  1009 {
  1010   return &netfilter;
  1011 }
  1012 
  1013 
  1014 }//namespace ns3