src/internet-stack/udp-socket-impl.cc
author Tom Henderson <tomh@tomh.org>
Wed Aug 05 20:53:44 2009 -0700 (2009-08-05)
changeset 4697 6e048d6486d8
parent 4603 67a0a49c1db4
child 5152 f14eff131d13
child 5680 25c3039f4144
permissions -rw-r--r--
Implement UdpSocketImpl::Close ()
     1 /* -*-  Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
     2 /*
     3  * Copyright (c) 2007 INRIA
     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: Mathieu Lacage <mathieu.lacage@sophia.inria.fr>
    19  */
    20 
    21 #include "ns3/log.h"
    22 #include "ns3/node.h"
    23 #include "ns3/inet-socket-address.h"
    24 #include "ns3/ipv4-route.h"
    25 #include "ns3/ipv4.h"
    26 #include "ns3/ipv4-header.h"
    27 #include "ns3/ipv4-routing-protocol.h"
    28 #include "ns3/udp-socket-factory.h"
    29 #include "ns3/trace-source-accessor.h"
    30 #include "udp-socket-impl.h"
    31 #include "udp-l4-protocol.h"
    32 #include "ipv4-end-point.h"
    33 #include <limits>
    34 
    35 NS_LOG_COMPONENT_DEFINE ("UdpSocketImpl");
    36 
    37 namespace ns3 {
    38 
    39 static const uint32_t MAX_IPV4_UDP_DATAGRAM_SIZE = 65507;
    40 
    41 // Add attributes generic to all UdpSockets to base class UdpSocket
    42 TypeId
    43 UdpSocketImpl::GetTypeId (void)
    44 {
    45   static TypeId tid = TypeId ("ns3::UdpSocketImpl")
    46     .SetParent<UdpSocket> ()
    47     .AddConstructor<UdpSocketImpl> ()
    48     .AddTraceSource ("Drop", "Drop UDP packet due to receive buffer overflow",
    49                      MakeTraceSourceAccessor (&UdpSocketImpl::m_dropTrace))
    50     .AddAttribute ("IcmpCallback", "Callback invoked whenever an icmp error is received on this socket.",
    51                    CallbackValue (),
    52                    MakeCallbackAccessor (&UdpSocketImpl::m_icmpCallback),
    53                    MakeCallbackChecker ())
    54     ;
    55   return tid;
    56 }
    57 
    58 UdpSocketImpl::UdpSocketImpl ()
    59   : m_endPoint (0),
    60     m_node (0),
    61     m_udp (0),
    62     m_errno (ERROR_NOTERROR),
    63     m_shutdownSend (false),
    64     m_shutdownRecv (false),
    65     m_connected (false),
    66     m_rxAvailable (0)
    67 {
    68   NS_LOG_FUNCTION_NOARGS ();
    69 }
    70 
    71 UdpSocketImpl::~UdpSocketImpl ()
    72 {
    73   NS_LOG_FUNCTION_NOARGS ();
    74 
    75   // XXX todo:  leave any multicast groups that have been joined
    76   m_node = 0;
    77   if (m_endPoint != 0)
    78     {
    79       NS_ASSERT (m_udp != 0);
    80       /**
    81        * Note that this piece of code is a bit tricky:
    82        * when DeAllocate is called, it will call into
    83        * Ipv4EndPointDemux::Deallocate which triggers
    84        * a delete of the associated endPoint which triggers
    85        * in turn a call to the method ::Destroy below
    86        * will will zero the m_endPoint field.
    87        */
    88       NS_ASSERT (m_endPoint != 0);
    89       m_udp->DeAllocate (m_endPoint);
    90       NS_ASSERT (m_endPoint == 0);
    91     }
    92   m_udp = 0;
    93 }
    94 
    95 void 
    96 UdpSocketImpl::SetNode (Ptr<Node> node)
    97 {
    98   NS_LOG_FUNCTION_NOARGS ();
    99   m_node = node;
   100 
   101 }
   102 void 
   103 UdpSocketImpl::SetUdp (Ptr<UdpL4Protocol> udp)
   104 {
   105   NS_LOG_FUNCTION_NOARGS ();
   106   m_udp = udp;
   107 }
   108 
   109 
   110 enum Socket::SocketErrno
   111 UdpSocketImpl::GetErrno (void) const
   112 {
   113   NS_LOG_FUNCTION_NOARGS ();
   114   return m_errno;
   115 }
   116 
   117 Ptr<Node>
   118 UdpSocketImpl::GetNode (void) const
   119 {
   120   NS_LOG_FUNCTION_NOARGS ();
   121   return m_node;
   122 }
   123 
   124 void 
   125 UdpSocketImpl::Destroy (void)
   126 {
   127   NS_LOG_FUNCTION_NOARGS ();
   128   m_node = 0;
   129   m_endPoint = 0;
   130   m_udp = 0;
   131 }
   132 
   133 int
   134 UdpSocketImpl::FinishBind (void)
   135 {
   136   NS_LOG_FUNCTION_NOARGS ();
   137   if (m_endPoint == 0)
   138     {
   139       return -1;
   140     }
   141   m_endPoint->SetRxCallback (MakeCallback (&UdpSocketImpl::ForwardUp, Ptr<UdpSocketImpl> (this)));
   142   m_endPoint->SetIcmpCallback (MakeCallback (&UdpSocketImpl::ForwardIcmp, Ptr<UdpSocketImpl> (this)));
   143   m_endPoint->SetDestroyCallback (MakeCallback (&UdpSocketImpl::Destroy, Ptr<UdpSocketImpl> (this)));
   144   return 0;
   145 }
   146 
   147 int
   148 UdpSocketImpl::Bind (void)
   149 {
   150   NS_LOG_FUNCTION_NOARGS ();
   151   m_endPoint = m_udp->Allocate ();
   152   return FinishBind ();
   153 }
   154 
   155 int 
   156 UdpSocketImpl::Bind (const Address &address)
   157 {
   158   NS_LOG_FUNCTION (this << address);
   159 
   160   if (!InetSocketAddress::IsMatchingType (address))
   161     {
   162       NS_LOG_ERROR ("Not IsMatchingType");
   163       m_errno = ERROR_INVAL;
   164       return -1;
   165     }
   166   InetSocketAddress transport = InetSocketAddress::ConvertFrom (address);
   167   Ipv4Address ipv4 = transport.GetIpv4 ();
   168   uint16_t port = transport.GetPort ();
   169   if (ipv4 == Ipv4Address::GetAny () && port == 0)
   170     {
   171       m_endPoint = m_udp->Allocate ();
   172     }
   173   else if (ipv4 == Ipv4Address::GetAny () && port != 0)
   174     {
   175       m_endPoint = m_udp->Allocate (port);
   176     }
   177   else if (ipv4 != Ipv4Address::GetAny () && port == 0)
   178     {
   179       m_endPoint = m_udp->Allocate (ipv4);
   180     }
   181   else if (ipv4 != Ipv4Address::GetAny () && port != 0)
   182     {
   183       m_endPoint = m_udp->Allocate (ipv4, port);
   184     }
   185 
   186   return FinishBind ();
   187 }
   188 
   189 int 
   190 UdpSocketImpl::ShutdownSend (void)
   191 {
   192   NS_LOG_FUNCTION_NOARGS ();
   193   m_shutdownSend = true;
   194   return 0;
   195 }
   196 
   197 int 
   198 UdpSocketImpl::ShutdownRecv (void)
   199 {
   200   NS_LOG_FUNCTION_NOARGS ();
   201   m_shutdownRecv = true;
   202   return 0;
   203 }
   204 
   205 int
   206 UdpSocketImpl::Close (void)
   207 {
   208   NS_LOG_FUNCTION_NOARGS ();
   209   if (m_shutdownRecv == true && m_shutdownSend == true)
   210     {
   211       m_errno = Socket::ERROR_BADF;
   212       return -1;
   213     }
   214   m_shutdownRecv = true;
   215   m_shutdownSend = true;
   216   return 0;
   217 }
   218 
   219 int
   220 UdpSocketImpl::Connect(const Address & address)
   221 {
   222   NS_LOG_FUNCTION (this << address);
   223   InetSocketAddress transport = InetSocketAddress::ConvertFrom (address);
   224   m_defaultAddress = transport.GetIpv4 ();
   225   m_defaultPort = transport.GetPort ();
   226   NotifyConnectionSucceeded ();
   227   m_connected = true;
   228 
   229   return 0;
   230 }
   231 
   232 int 
   233 UdpSocketImpl::Listen (void)
   234 {
   235   m_errno = Socket::ERROR_OPNOTSUPP;
   236   return -1;
   237 }
   238 
   239 int 
   240 UdpSocketImpl::Send (Ptr<Packet> p, uint32_t flags)
   241 {
   242   NS_LOG_FUNCTION (this << p << flags);
   243 
   244   if (!m_connected)
   245     {
   246       m_errno = ERROR_NOTCONN;
   247       return -1;
   248     }
   249   return DoSend (p);
   250 }
   251 
   252 int 
   253 UdpSocketImpl::DoSend (Ptr<Packet> p)
   254 {
   255   NS_LOG_FUNCTION (this << p);
   256   if (m_endPoint == 0)
   257     {
   258       if (Bind () == -1)
   259        {
   260           NS_ASSERT (m_endPoint == 0);
   261          return -1;
   262        }
   263       NS_ASSERT (m_endPoint != 0);
   264     }
   265   if (m_shutdownSend)
   266     {
   267       m_errno = ERROR_SHUTDOWN;
   268       return -1;
   269     } 
   270   
   271   return DoSendTo (p, m_defaultAddress, m_defaultPort);
   272 }
   273 
   274 int
   275 UdpSocketImpl::DoSendTo (Ptr<Packet> p, const Address &address)
   276 {
   277   NS_LOG_FUNCTION (this << p << address);
   278 
   279   if (!m_connected)
   280     {
   281       NS_LOG_LOGIC ("Not connected");
   282       InetSocketAddress transport = InetSocketAddress::ConvertFrom (address);
   283       Ipv4Address ipv4 = transport.GetIpv4 ();
   284       uint16_t port = transport.GetPort ();
   285       return DoSendTo (p, ipv4, port);
   286     }
   287   else
   288     {
   289       // connected UDP socket must use default addresses
   290       NS_LOG_LOGIC ("Connected");
   291       return DoSendTo (p, m_defaultAddress, m_defaultPort);
   292     }
   293 }
   294 
   295 int
   296 UdpSocketImpl::DoSendTo (Ptr<Packet> p, Ipv4Address dest, uint16_t port)
   297 {
   298   NS_LOG_FUNCTION (this << p << dest << port);
   299 
   300   if (m_endPoint == 0)
   301     {
   302       if (Bind () == -1)
   303 	{
   304           NS_ASSERT (m_endPoint == 0);
   305 	  return -1;
   306 	}
   307       NS_ASSERT (m_endPoint != 0);
   308     }
   309   if (m_shutdownSend)
   310     {
   311       m_errno = ERROR_SHUTDOWN;
   312       return -1;
   313     }
   314 
   315   if (p->GetSize () > GetTxAvailable () )
   316     {
   317       m_errno = ERROR_MSGSIZE;
   318       return -1;
   319     }
   320 
   321   Ptr<Ipv4> ipv4 = m_node->GetObject<Ipv4> ();
   322 
   323   // Locally override the IP TTL for this socket
   324   // We cannot directly modify the TTL at this stage, so we set a Packet tag
   325   // The destination can be either multicast, unicast/anycast, or
   326   // either all-hosts broadcast or limited (subnet-directed) broadcast.
   327   // For the latter two broadcast types, the TTL will later be set to one
   328   // irrespective of what is set in these socket options.  So, this tagging  
   329   // may end up setting the TTL of a limited broadcast packet to be
   330   // the same as a unicast, but it will be fixed further down the stack
   331   if (m_ipMulticastTtl != 0 && dest.IsMulticast ())
   332     {
   333       SocketIpTtlTag tag;
   334       tag.SetTtl (m_ipMulticastTtl);
   335       p->AddPacketTag (tag);
   336     }
   337   else if (m_ipTtl != 0 && !dest.IsMulticast () && !dest.IsBroadcast ())
   338     {
   339       SocketIpTtlTag tag;
   340       tag.SetTtl (m_ipTtl);
   341       p->AddPacketTag (tag);
   342     }
   343   {
   344     SocketSetDontFragmentTag tag;
   345     bool found = p->RemovePacketTag (tag);
   346     if (!found)
   347       {
   348         if (m_mtuDiscover)
   349           {
   350             tag.Enable ();
   351           }
   352         else
   353           {
   354             tag.Disable ();
   355           }
   356         p->AddPacketTag (tag);
   357       }
   358   }
   359   //
   360   // If dest is set to the limited broadcast address (all ones),
   361   // convert it to send a copy of the packet out of every 
   362   // interface as a subnet-directed broadcast.
   363   // Exception:  if the interface has a /32 address, there is no
   364   // valid subnet-directed broadcast, so send it as limited broadcast
   365   // Note also that some systems will only send limited broadcast packets
   366   // out of the "default" interface; here we send it out all interfaces
   367   //
   368   if (dest.IsBroadcast ())
   369     {
   370       NS_LOG_LOGIC ("Limited broadcast start.");
   371       for (uint32_t i = 0; i < ipv4->GetNInterfaces (); i++ )
   372         {
   373           // Get the primary address
   374           Ipv4InterfaceAddress iaddr = ipv4->GetAddress (i, 0);
   375           Ipv4Address addri = iaddr.GetLocal ();
   376           Ipv4Mask maski = iaddr.GetMask ();
   377           if (maski == Ipv4Mask::GetOnes ())
   378             {
   379               // if the network mask is 255.255.255.255, do not convert dest
   380               NS_LOG_LOGIC ("Sending one copy from " << addri << " to " << dest
   381                             << " (mask is " << maski << ")");
   382               m_udp->Send (p->Copy (), addri, dest,
   383                            m_endPoint->GetLocalPort (), port);
   384               NotifyDataSent (p->GetSize ());
   385               NotifySend (GetTxAvailable ());
   386             }
   387           else
   388             {
   389               // Convert to subnet-directed broadcast
   390               Ipv4Address bcast = addri.GetSubnetDirectedBroadcast (maski);
   391               NS_LOG_LOGIC ("Sending one copy from " << addri << " to " << bcast
   392                             << " (mask is " << maski << ")");
   393               m_udp->Send (p->Copy (), addri, bcast,
   394                            m_endPoint->GetLocalPort (), port);
   395               NotifyDataSent (p->GetSize ());
   396               NotifySend (GetTxAvailable ());
   397             }
   398         }
   399       NS_LOG_LOGIC ("Limited broadcast end.");
   400       return p->GetSize();
   401     }
   402   else if (ipv4->GetRoutingProtocol () != 0)
   403     {
   404       Ipv4Header header;
   405       header.SetDestination (dest);
   406       Socket::SocketErrno errno_;
   407       Ptr<Ipv4Route> route;
   408       uint32_t oif = 0; //specify non-zero if bound to a source address
   409       // TBD-- we could cache the route and just check its validity
   410       route = ipv4->GetRoutingProtocol ()->RouteOutput (p, header, oif, errno_); 
   411       if (route != 0)
   412         {
   413           NS_LOG_LOGIC ("Route exists");
   414           header.SetSource (route->GetSource ());
   415           m_udp->Send (p->Copy (), header.GetSource (), header.GetDestination (),
   416                        m_endPoint->GetLocalPort (), port, route);
   417           NotifyDataSent (p->GetSize ());
   418           return p->GetSize();
   419         }
   420       else 
   421         {
   422           NS_LOG_LOGIC ("No route to destination");
   423           NS_LOG_ERROR (errno_);
   424           m_errno = errno_;
   425           return -1;
   426         }
   427     }
   428   else
   429    {
   430       NS_LOG_ERROR ("ERROR_NOROUTETOHOST");
   431       m_errno = ERROR_NOROUTETOHOST;
   432       return -1;
   433    }
   434 
   435   return 0;
   436 }
   437 
   438 // XXX maximum message size for UDP broadcast is limited by MTU
   439 // size of underlying link; we are not checking that now.
   440 uint32_t
   441 UdpSocketImpl::GetTxAvailable (void) const
   442 {
   443   NS_LOG_FUNCTION_NOARGS ();
   444   // No finite send buffer is modelled, but we must respect
   445   // the maximum size of an IP datagram (65535 bytes - headers).
   446   return MAX_IPV4_UDP_DATAGRAM_SIZE;
   447 }
   448 
   449 int 
   450 UdpSocketImpl::SendTo (Ptr<Packet> p, uint32_t flags, const Address &address)
   451 {
   452   NS_LOG_FUNCTION (this << p << flags << address);
   453   InetSocketAddress transport = InetSocketAddress::ConvertFrom (address);
   454   Ipv4Address ipv4 = transport.GetIpv4 ();
   455   uint16_t port = transport.GetPort ();
   456   return DoSendTo (p, ipv4, port);
   457 }
   458 
   459 uint32_t
   460 UdpSocketImpl::GetRxAvailable (void) const
   461 {
   462   NS_LOG_FUNCTION_NOARGS ();
   463   // We separately maintain this state to avoid walking the queue 
   464   // every time this might be called
   465   return m_rxAvailable;
   466 }
   467 
   468 Ptr<Packet>
   469 UdpSocketImpl::Recv (uint32_t maxSize, uint32_t flags)
   470 {
   471   NS_LOG_FUNCTION (this << maxSize << flags);
   472   if (m_deliveryQueue.empty() )
   473     {
   474       m_errno = ERROR_AGAIN;
   475       return 0;
   476     }
   477   Ptr<Packet> p = m_deliveryQueue.front ();
   478   if (p->GetSize () <= maxSize) 
   479     {
   480       m_deliveryQueue.pop ();
   481       m_rxAvailable -= p->GetSize ();
   482     }
   483   else
   484     {
   485       p = 0; 
   486     }
   487   return p;
   488 }
   489 
   490 Ptr<Packet>
   491 UdpSocketImpl::RecvFrom (uint32_t maxSize, uint32_t flags, 
   492   Address &fromAddress)
   493 {
   494   NS_LOG_FUNCTION (this << maxSize << flags);
   495   Ptr<Packet> packet = Recv (maxSize, flags);
   496   if (packet != 0)
   497     {
   498       SocketAddressTag tag;
   499       bool found;
   500       found = packet->PeekPacketTag (tag);
   501       NS_ASSERT (found);
   502       fromAddress = tag.GetAddress ();
   503     }
   504   return packet;
   505 }
   506 
   507 int
   508 UdpSocketImpl::GetSockName (Address &address) const
   509 {
   510   NS_LOG_FUNCTION_NOARGS ();
   511   if (m_endPoint != 0)
   512     {
   513       address = InetSocketAddress (m_endPoint->GetLocalAddress (), m_endPoint->GetLocalPort());
   514     }
   515   else
   516     {
   517       address = InetSocketAddress(Ipv4Address::GetZero(), 0);
   518     }
   519   return 0;
   520 }
   521 
   522 int 
   523 UdpSocketImpl::MulticastJoinGroup (uint32_t interface, const Address &groupAddress)
   524 {
   525   NS_LOG_FUNCTION (interface << groupAddress);
   526   /*
   527    1) sanity check interface
   528    2) sanity check that it has not been called yet on this interface/group
   529    3) determine address family of groupAddress
   530    4) locally store a list of (interface, groupAddress)
   531    5) call ipv4->MulticastJoinGroup () or Ipv6->MulticastJoinGroup ()
   532   */
   533   return 0;
   534 } 
   535 
   536 int 
   537 UdpSocketImpl::MulticastLeaveGroup (uint32_t interface, const Address &groupAddress) 
   538 {
   539   NS_LOG_FUNCTION (interface << groupAddress);
   540   /*
   541    1) sanity check interface
   542    2) determine address family of groupAddress
   543    3) delete from local list of (interface, groupAddress); raise a LOG_WARN
   544       if not already present (but return 0) 
   545    5) call ipv4->MulticastLeaveGroup () or Ipv6->MulticastLeaveGroup ()
   546   */
   547   return 0;
   548 }
   549 
   550 void 
   551 UdpSocketImpl::ForwardUp (Ptr<Packet> packet, Ipv4Address ipv4, uint16_t port)
   552 {
   553   NS_LOG_FUNCTION (this << packet << ipv4 << port);
   554 
   555   if (m_shutdownRecv)
   556     {
   557       return;
   558     }
   559   if ((m_rxAvailable + packet->GetSize ()) <= m_rcvBufSize)
   560     {
   561       Address address = InetSocketAddress (ipv4, port);
   562       SocketAddressTag tag;
   563       tag.SetAddress (address);
   564       packet->AddPacketTag (tag);
   565       m_deliveryQueue.push (packet);
   566       m_rxAvailable += packet->GetSize ();
   567       NotifyDataRecv ();
   568     }
   569   else
   570     {
   571       // In general, this case should not occur unless the
   572       // receiving application reads data from this socket slowly
   573       // in comparison to the arrival rate
   574       //
   575       // drop and trace packet
   576       NS_LOG_WARN ("No receive buffer space available.  Drop.");
   577       m_dropTrace (packet);
   578     }
   579 }
   580 
   581 void
   582 UdpSocketImpl::ForwardIcmp (Ipv4Address icmpSource, uint8_t icmpTtl, 
   583                             uint8_t icmpType, uint8_t icmpCode,
   584                             uint32_t icmpInfo)
   585 {
   586   NS_LOG_FUNCTION (this << icmpSource << (uint32_t)icmpTtl << (uint32_t)icmpType <<
   587                    (uint32_t)icmpCode << icmpInfo);
   588   if (!m_icmpCallback.IsNull ())
   589     {
   590       m_icmpCallback (icmpSource, icmpTtl, icmpType, icmpCode, icmpInfo);
   591     }
   592 }
   593 
   594 
   595 void 
   596 UdpSocketImpl::SetRcvBufSize (uint32_t size)
   597 {
   598   m_rcvBufSize = size;
   599 }
   600 
   601 uint32_t 
   602 UdpSocketImpl::GetRcvBufSize (void) const
   603 {
   604   return m_rcvBufSize;
   605 }
   606 
   607 void 
   608 UdpSocketImpl::SetIpTtl (uint8_t ipTtl)
   609 {
   610   m_ipTtl = ipTtl;
   611 }
   612 
   613 uint8_t 
   614 UdpSocketImpl::GetIpTtl (void) const
   615 {
   616   return m_ipTtl;
   617 }
   618 
   619 void 
   620 UdpSocketImpl::SetIpMulticastTtl (uint8_t ipTtl)
   621 {
   622   m_ipMulticastTtl = ipTtl;
   623 }
   624 
   625 uint8_t 
   626 UdpSocketImpl::GetIpMulticastTtl (void) const
   627 {
   628   return m_ipMulticastTtl;
   629 }
   630 
   631 void 
   632 UdpSocketImpl::SetIpMulticastIf (int32_t ipIf)
   633 {
   634   m_ipMulticastIf = ipIf;
   635 }
   636 
   637 int32_t 
   638 UdpSocketImpl::GetIpMulticastIf (void) const
   639 {
   640   return m_ipMulticastIf;
   641 }
   642 
   643 void 
   644 UdpSocketImpl::SetIpMulticastLoop (bool loop)
   645 {
   646   m_ipMulticastLoop = loop;
   647 }
   648 
   649 bool 
   650 UdpSocketImpl::GetIpMulticastLoop (void) const
   651 {
   652   return m_ipMulticastLoop;
   653 }
   654 
   655 void 
   656 UdpSocketImpl::SetMtuDiscover (bool discover)
   657 {
   658   m_mtuDiscover = discover;
   659 }
   660 bool 
   661 UdpSocketImpl::GetMtuDiscover (void) const
   662 {
   663   return m_mtuDiscover;
   664 }
   665 
   666 
   667 } //namespace ns3