1 /* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
3 * Copyright (c) 2007 INRIA
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;
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.
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
18 * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr>
23 #include "ns3/inet-socket-address.h"
24 #include "ns3/ipv4-route.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"
35 NS_LOG_COMPONENT_DEFINE ("UdpSocketImpl");
39 static const uint32_t MAX_IPV4_UDP_DATAGRAM_SIZE = 65507;
41 // Add attributes generic to all UdpSockets to base class UdpSocket
43 UdpSocketImpl::GetTypeId (void)
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.",
52 MakeCallbackAccessor (&UdpSocketImpl::m_icmpCallback),
53 MakeCallbackChecker ())
58 UdpSocketImpl::UdpSocketImpl ()
62 m_errno (ERROR_NOTERROR),
63 m_shutdownSend (false),
64 m_shutdownRecv (false),
68 NS_LOG_FUNCTION_NOARGS ();
71 UdpSocketImpl::~UdpSocketImpl ()
73 NS_LOG_FUNCTION_NOARGS ();
75 // XXX todo: leave any multicast groups that have been joined
79 NS_ASSERT (m_udp != 0);
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.
88 NS_ASSERT (m_endPoint != 0);
89 m_udp->DeAllocate (m_endPoint);
90 NS_ASSERT (m_endPoint == 0);
96 UdpSocketImpl::SetNode (Ptr<Node> node)
98 NS_LOG_FUNCTION_NOARGS ();
103 UdpSocketImpl::SetUdp (Ptr<UdpL4Protocol> udp)
105 NS_LOG_FUNCTION_NOARGS ();
110 enum Socket::SocketErrno
111 UdpSocketImpl::GetErrno (void) const
113 NS_LOG_FUNCTION_NOARGS ();
118 UdpSocketImpl::GetNode (void) const
120 NS_LOG_FUNCTION_NOARGS ();
125 UdpSocketImpl::Destroy (void)
127 NS_LOG_FUNCTION_NOARGS ();
134 UdpSocketImpl::FinishBind (void)
136 NS_LOG_FUNCTION_NOARGS ();
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)));
148 UdpSocketImpl::Bind (void)
150 NS_LOG_FUNCTION_NOARGS ();
151 m_endPoint = m_udp->Allocate ();
152 return FinishBind ();
156 UdpSocketImpl::Bind (const Address &address)
158 NS_LOG_FUNCTION (this << address);
160 if (!InetSocketAddress::IsMatchingType (address))
162 NS_LOG_ERROR ("Not IsMatchingType");
163 m_errno = ERROR_INVAL;
166 InetSocketAddress transport = InetSocketAddress::ConvertFrom (address);
167 Ipv4Address ipv4 = transport.GetIpv4 ();
168 uint16_t port = transport.GetPort ();
169 if (ipv4 == Ipv4Address::GetAny () && port == 0)
171 m_endPoint = m_udp->Allocate ();
173 else if (ipv4 == Ipv4Address::GetAny () && port != 0)
175 m_endPoint = m_udp->Allocate (port);
177 else if (ipv4 != Ipv4Address::GetAny () && port == 0)
179 m_endPoint = m_udp->Allocate (ipv4);
181 else if (ipv4 != Ipv4Address::GetAny () && port != 0)
183 m_endPoint = m_udp->Allocate (ipv4, port);
186 return FinishBind ();
190 UdpSocketImpl::ShutdownSend (void)
192 NS_LOG_FUNCTION_NOARGS ();
193 m_shutdownSend = true;
198 UdpSocketImpl::ShutdownRecv (void)
200 NS_LOG_FUNCTION_NOARGS ();
201 m_shutdownRecv = true;
206 UdpSocketImpl::Close (void)
208 NS_LOG_FUNCTION_NOARGS ();
209 if (m_shutdownRecv == true && m_shutdownSend == true)
211 m_errno = Socket::ERROR_BADF;
214 m_shutdownRecv = true;
215 m_shutdownSend = true;
220 UdpSocketImpl::Connect(const Address & address)
222 NS_LOG_FUNCTION (this << address);
223 InetSocketAddress transport = InetSocketAddress::ConvertFrom (address);
224 m_defaultAddress = transport.GetIpv4 ();
225 m_defaultPort = transport.GetPort ();
226 NotifyConnectionSucceeded ();
233 UdpSocketImpl::Listen (void)
235 m_errno = Socket::ERROR_OPNOTSUPP;
240 UdpSocketImpl::Send (Ptr<Packet> p, uint32_t flags)
242 NS_LOG_FUNCTION (this << p << flags);
246 m_errno = ERROR_NOTCONN;
253 UdpSocketImpl::DoSend (Ptr<Packet> p)
255 NS_LOG_FUNCTION (this << p);
260 NS_ASSERT (m_endPoint == 0);
263 NS_ASSERT (m_endPoint != 0);
267 m_errno = ERROR_SHUTDOWN;
271 return DoSendTo (p, m_defaultAddress, m_defaultPort);
275 UdpSocketImpl::DoSendTo (Ptr<Packet> p, const Address &address)
277 NS_LOG_FUNCTION (this << p << address);
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);
289 // connected UDP socket must use default addresses
290 NS_LOG_LOGIC ("Connected");
291 return DoSendTo (p, m_defaultAddress, m_defaultPort);
296 UdpSocketImpl::DoSendTo (Ptr<Packet> p, Ipv4Address dest, uint16_t port)
298 NS_LOG_FUNCTION (this << p << dest << port);
304 NS_ASSERT (m_endPoint == 0);
307 NS_ASSERT (m_endPoint != 0);
311 m_errno = ERROR_SHUTDOWN;
315 if (p->GetSize () > GetTxAvailable () )
317 m_errno = ERROR_MSGSIZE;
321 Ptr<Ipv4> ipv4 = m_node->GetObject<Ipv4> ();
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 ())
334 tag.SetTtl (m_ipMulticastTtl);
335 p->AddPacketTag (tag);
337 else if (m_ipTtl != 0 && !dest.IsMulticast () && !dest.IsBroadcast ())
340 tag.SetTtl (m_ipTtl);
341 p->AddPacketTag (tag);
344 SocketSetDontFragmentTag tag;
345 bool found = p->RemovePacketTag (tag);
356 p->AddPacketTag (tag);
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
368 if (dest.IsBroadcast ())
370 NS_LOG_LOGIC ("Limited broadcast start.");
371 for (uint32_t i = 0; i < ipv4->GetNInterfaces (); i++ )
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 ())
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 ());
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 ());
399 NS_LOG_LOGIC ("Limited broadcast end.");
402 else if (ipv4->GetRoutingProtocol () != 0)
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_);
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 ());
422 NS_LOG_LOGIC ("No route to destination");
423 NS_LOG_ERROR (errno_);
430 NS_LOG_ERROR ("ERROR_NOROUTETOHOST");
431 m_errno = ERROR_NOROUTETOHOST;
438 // XXX maximum message size for UDP broadcast is limited by MTU
439 // size of underlying link; we are not checking that now.
441 UdpSocketImpl::GetTxAvailable (void) const
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;
450 UdpSocketImpl::SendTo (Ptr<Packet> p, uint32_t flags, const Address &address)
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);
460 UdpSocketImpl::GetRxAvailable (void) const
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;
469 UdpSocketImpl::Recv (uint32_t maxSize, uint32_t flags)
471 NS_LOG_FUNCTION (this << maxSize << flags);
472 if (m_deliveryQueue.empty() )
474 m_errno = ERROR_AGAIN;
477 Ptr<Packet> p = m_deliveryQueue.front ();
478 if (p->GetSize () <= maxSize)
480 m_deliveryQueue.pop ();
481 m_rxAvailable -= p->GetSize ();
491 UdpSocketImpl::RecvFrom (uint32_t maxSize, uint32_t flags,
492 Address &fromAddress)
494 NS_LOG_FUNCTION (this << maxSize << flags);
495 Ptr<Packet> packet = Recv (maxSize, flags);
498 SocketAddressTag tag;
500 found = packet->PeekPacketTag (tag);
502 fromAddress = tag.GetAddress ();
508 UdpSocketImpl::GetSockName (Address &address) const
510 NS_LOG_FUNCTION_NOARGS ();
513 address = InetSocketAddress (m_endPoint->GetLocalAddress (), m_endPoint->GetLocalPort());
517 address = InetSocketAddress(Ipv4Address::GetZero(), 0);
523 UdpSocketImpl::MulticastJoinGroup (uint32_t interface, const Address &groupAddress)
525 NS_LOG_FUNCTION (interface << groupAddress);
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 ()
537 UdpSocketImpl::MulticastLeaveGroup (uint32_t interface, const Address &groupAddress)
539 NS_LOG_FUNCTION (interface << groupAddress);
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 ()
551 UdpSocketImpl::ForwardUp (Ptr<Packet> packet, Ipv4Address ipv4, uint16_t port)
553 NS_LOG_FUNCTION (this << packet << ipv4 << port);
559 if ((m_rxAvailable + packet->GetSize ()) <= m_rcvBufSize)
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 ();
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
575 // drop and trace packet
576 NS_LOG_WARN ("No receive buffer space available. Drop.");
577 m_dropTrace (packet);
582 UdpSocketImpl::ForwardIcmp (Ipv4Address icmpSource, uint8_t icmpTtl,
583 uint8_t icmpType, uint8_t icmpCode,
586 NS_LOG_FUNCTION (this << icmpSource << (uint32_t)icmpTtl << (uint32_t)icmpType <<
587 (uint32_t)icmpCode << icmpInfo);
588 if (!m_icmpCallback.IsNull ())
590 m_icmpCallback (icmpSource, icmpTtl, icmpType, icmpCode, icmpInfo);
596 UdpSocketImpl::SetRcvBufSize (uint32_t size)
602 UdpSocketImpl::GetRcvBufSize (void) const
608 UdpSocketImpl::SetIpTtl (uint8_t ipTtl)
614 UdpSocketImpl::GetIpTtl (void) const
620 UdpSocketImpl::SetIpMulticastTtl (uint8_t ipTtl)
622 m_ipMulticastTtl = ipTtl;
626 UdpSocketImpl::GetIpMulticastTtl (void) const
628 return m_ipMulticastTtl;
632 UdpSocketImpl::SetIpMulticastIf (int32_t ipIf)
634 m_ipMulticastIf = ipIf;
638 UdpSocketImpl::GetIpMulticastIf (void) const
640 return m_ipMulticastIf;
644 UdpSocketImpl::SetIpMulticastLoop (bool loop)
646 m_ipMulticastLoop = loop;
650 UdpSocketImpl::GetIpMulticastLoop (void) const
652 return m_ipMulticastLoop;
656 UdpSocketImpl::SetMtuDiscover (bool discover)
658 m_mtuDiscover = discover;
661 UdpSocketImpl::GetMtuDiscover (void) const
663 return m_mtuDiscover;