From 622ced44623c4d3c199ba801f42ed3d3736cda19 Mon Sep 17 00:00:00 2001 From: Craig Dowell Date: Mon, 27 Oct 2008 13:01:28 -0700 Subject: [PATCH 01/52] merge in tap device --- src/devices/emutap/host-tap-net-device.cc | 194 +++++++++++++ src/devices/emutap/host-tap-net-device.h | 90 ++++++ src/devices/emutap/tap-channel.cc | 61 ++++ src/devices/emutap/tap-channel.h | 36 +++ src/devices/emutap/tap-manager-client.cc | 180 ++++++++++++ src/devices/emutap/tap-manager-client.h | 21 ++ src/devices/emutap/tap-manager.cc | 339 ++++++++++++++++++++++ src/devices/emutap/tap-net-device.cc | 323 +++++++++++++++++++++ src/devices/emutap/tap-net-device.h | 103 +++++++ src/devices/emutap/wscript | 26 ++ src/wscript | 3 +- wscript | 44 +++ 12 files changed, 1419 insertions(+), 1 deletion(-) create mode 100644 src/devices/emutap/host-tap-net-device.cc create mode 100644 src/devices/emutap/host-tap-net-device.h create mode 100644 src/devices/emutap/tap-channel.cc create mode 100644 src/devices/emutap/tap-channel.h create mode 100644 src/devices/emutap/tap-manager-client.cc create mode 100644 src/devices/emutap/tap-manager-client.h create mode 100644 src/devices/emutap/tap-manager.cc create mode 100644 src/devices/emutap/tap-net-device.cc create mode 100644 src/devices/emutap/tap-net-device.h create mode 100644 src/devices/emutap/wscript diff --git a/src/devices/emutap/host-tap-net-device.cc b/src/devices/emutap/host-tap-net-device.cc new file mode 100644 index 000000000..c83000b1b --- /dev/null +++ b/src/devices/emutap/host-tap-net-device.cc @@ -0,0 +1,194 @@ +/* -*- 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 + */ +#include "host-tap-net-device.h" +#include "ns3/node.h" +#include "ns3/tap-channel.h" +#include "ns3/log.h" + +NS_LOG_COMPONENT_DEFINE ("HostTapNetDevice"); + +namespace ns3 { + +TypeId +HostTapNetDevice::GetTypeId (void) +{ + static TypeId tid = TypeId ("ns3::HostTapNetDevice") + .SetParent () + .AddConstructor () + ; + return tid; +} + +HostTapNetDevice::HostTapNetDevice () + : m_node (0), + m_mtu (0xffff), + m_name (""), + m_ifIndex (0) +{ + NS_LOG_FUNCTION (this); +} + +void +HostTapNetDevice::SetChannel (Ptr channel) +{ + m_channel = channel; + m_channel->SetHostDevice (this); +} + +void +HostTapNetDevice::SetAddress (Mac48Address address) +{ + m_address = address; +} + +Mac48Address +HostTapNetDevice::GetMacAddress (void) const +{ + return m_address; +} + +void +HostTapNetDevice::SetName(const std::string name) +{ + m_name = name; +} +std::string +HostTapNetDevice::GetName(void) const +{ + return m_name; +} +void +HostTapNetDevice::SetIfIndex(const uint32_t index) +{ + m_ifIndex = index; +} +uint32_t +HostTapNetDevice::GetIfIndex(void) const +{ + return m_ifIndex; +} +Ptr +HostTapNetDevice::GetChannel (void) const +{ + return m_channel; +} +Address +HostTapNetDevice::GetAddress (void) const +{ + return m_address; +} +bool +HostTapNetDevice::SetMtu (const uint16_t mtu) +{ + m_mtu = mtu; + return true; +} +uint16_t +HostTapNetDevice::GetMtu (void) const +{ + return m_mtu; +} +bool +HostTapNetDevice::IsLinkUp (void) const +{ + return true; +} +void +HostTapNetDevice::SetLinkChangeCallback (Callback callback) +{} +bool +HostTapNetDevice::IsBroadcast (void) const +{ + return true; +} +Address +HostTapNetDevice::GetBroadcast (void) const +{ + return Mac48Address ("ff:ff:ff:ff:ff:ff"); +} +bool +HostTapNetDevice::IsMulticast (void) const +{ + return true; +} +Address +HostTapNetDevice::GetMulticast (void) const +{ + return Mac48Address::GetMulticastPrefix (); +} +Address +HostTapNetDevice::MakeMulticastAddress (Ipv4Address multicastGroup) const +{ + return Mac48Address::GetMulticast (multicastGroup); +} +bool +HostTapNetDevice::IsPointToPoint (void) const +{ + return false; +} +bool +HostTapNetDevice::Send(Ptr packet, const Address& dest, uint16_t protocolNumber) +{ + return false; +} +bool +HostTapNetDevice::SendFrom(Ptr packet, const Address& source, const Address& dest, uint16_t protocolNumber) +{ + return false; +} +Ptr +HostTapNetDevice::GetNode (void) const +{ + return m_node; +} +void +HostTapNetDevice::SetNode (Ptr node) +{ + m_node = node; +} +bool +HostTapNetDevice::NeedsArp (void) const +{ + return false; +} +void +HostTapNetDevice::SetReceiveCallback (NetDevice::ReceiveCallback cb) +{} + +void +HostTapNetDevice::DoDispose (void) +{ + NS_LOG_FUNCTION (this); + m_node = 0; + m_channel = 0; + NetDevice::DoDispose (); +} + +void +HostTapNetDevice::SetPromiscReceiveCallback (PromiscReceiveCallback cb) +{} + +bool +HostTapNetDevice::SupportsSendFrom (void) const +{ + return false; +} + +} // namespace ns3 diff --git a/src/devices/emutap/host-tap-net-device.h b/src/devices/emutap/host-tap-net-device.h new file mode 100644 index 000000000..91b4b7ee2 --- /dev/null +++ b/src/devices/emutap/host-tap-net-device.h @@ -0,0 +1,90 @@ +/* -*- 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 + */ +#ifndef HOST_TAP_NET_DEVICE_H +#define HOST_TAP_NET_DEVICE_H + +#include "ns3/net-device.h" +#include "ns3/mac48-address.h" +#include "ns3/traced-callback.h" +#include +#include + +namespace ns3 { + +class Node; +class TapChannel; + + +/** + * \ingroup netdevice + * + * \brief a NetDevice to get packets to and from a host tap device. + */ +class HostTapNetDevice : public NetDevice +{ +public: + static TypeId GetTypeId (void); + HostTapNetDevice (); + + void SetAddress (Mac48Address address); + void SetChannel (Ptr channel); + + Mac48Address GetMacAddress (void) const; + + // inherited from NetDevice base class. + virtual void SetName(const std::string name); + virtual std::string GetName(void) const; + virtual void SetIfIndex(const uint32_t index); + virtual uint32_t GetIfIndex(void) const; + virtual Ptr GetChannel (void) const; + virtual Address GetAddress (void) const; + virtual bool SetMtu (const uint16_t mtu); + virtual uint16_t GetMtu (void) const; + virtual bool IsLinkUp (void) const; + virtual void SetLinkChangeCallback (Callback callback); + virtual bool IsBroadcast (void) const; + virtual Address GetBroadcast (void) const; + virtual bool IsMulticast (void) const; + virtual Address GetMulticast (void) const; + virtual Address MakeMulticastAddress (Ipv4Address multicastGroup) const; + virtual bool IsPointToPoint (void) const; + virtual bool Send(Ptr packet, const Address& dest, uint16_t protocolNumber); + virtual bool SendFrom(Ptr packet, const Address& source, const Address& dest, uint16_t protocolNumber); + virtual Ptr GetNode (void) const; + virtual void SetNode (Ptr node); + virtual bool NeedsArp (void) const; + virtual void SetReceiveCallback (NetDevice::ReceiveCallback cb); + virtual void SetPromiscReceiveCallback (PromiscReceiveCallback cb); + virtual bool SupportsSendFrom (void) const; + +protected: + virtual void DoDispose (void); +private: + Ptr m_node; + uint16_t m_mtu; + std::string m_name; + uint32_t m_ifIndex; + Mac48Address m_address; + Ptr m_channel; +}; + +} // namespace ns3 + +#endif /* HOST_TAP_NET_DEVICE_H */ diff --git a/src/devices/emutap/tap-channel.cc b/src/devices/emutap/tap-channel.cc new file mode 100644 index 000000000..d07944fb1 --- /dev/null +++ b/src/devices/emutap/tap-channel.cc @@ -0,0 +1,61 @@ +#include "tap-channel.h" +#include "host-tap-net-device.h" +#include "tap-net-device.h" + +namespace ns3 { + + +TapChannel::TapChannel () + : m_hostDevice (0), + m_device (0) +{} + +void +TapChannel::DoDispose (void) +{ + m_device = 0; + m_hostDevice = 0; + Channel::DoDispose (); +} + +void +TapChannel::SetDevice (Ptr device) +{ + m_device = device; +} + +void +TapChannel::SetHostDevice (Ptr device) +{ + m_hostDevice = device; +} + +Ptr +TapChannel::GetHostDevice (void) const +{ + return m_hostDevice; +} + +uint32_t +TapChannel::GetNDevices (void) const +{ + return 2; +} +Ptr +TapChannel::GetDevice (uint32_t i) const +{ + if (i == 0) + { + return m_device; + } + else if (i == 1) + { + return m_hostDevice; + } + else + { + return 0; + } +} + +} // namespace ns3 diff --git a/src/devices/emutap/tap-channel.h b/src/devices/emutap/tap-channel.h new file mode 100644 index 000000000..fcf529c6c --- /dev/null +++ b/src/devices/emutap/tap-channel.h @@ -0,0 +1,36 @@ +#ifndef TAP_CHANNEL_H +#define TAP_CHANNEL_H + +#include "ns3/channel.h" + +namespace ns3 { + +class HostTapNetDevice; +class TapNetDevice; +class NetDevice; + + +class TapChannel : public Channel +{ +public: + TapChannel (); + + void SetHostDevice (Ptr device); + void SetDevice (Ptr device); + + Ptr GetHostDevice (void) const; + + // overriden from Channel base class + virtual uint32_t GetNDevices (void) const; + virtual Ptr GetDevice (uint32_t i) const; + +private: + virtual void DoDispose (void); + + Ptr m_hostDevice; + Ptr m_device; +}; + +} // namespace ns3 + +#endif /* TAP_CHANNEL_H */ diff --git a/src/devices/emutap/tap-manager-client.cc b/src/devices/emutap/tap-manager-client.cc new file mode 100644 index 000000000..24c624faf --- /dev/null +++ b/src/devices/emutap/tap-manager-client.cc @@ -0,0 +1,180 @@ +#include "tap-manager-client.h" +#include "ns3/log.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +NS_LOG_COMPONENT_DEFINE("TapManagerClient"); + +#define TAP_MANAGER "ns3-tap-manager" + +namespace ns3 { + +static std::string +EncodeAsString (struct sockaddr_un un, int len) +{ + uint8_t *buffer = (uint8_t *)&un; + std::ostringstream oss; + oss.setf (std::ios::hex, std::ios::basefield); + oss.fill('0'); + for (uint8_t i = 0; i < len; i++) + { + oss << ":" << std::setw (2) << (uint32_t)buffer[i]; + } + return oss.str (); +} + +bool +TapManagerClient::Exists (std::string filename) const +{ + struct stat st; + int retval = ::stat (filename.c_str (), &st); + return retval == 0; +} + +std::string +TapManagerClient::FindManager (void) const +{ + std::list locations; + locations.push_back ("./src/devices/tap"); + locations.push_back ("./build/debug/src/devices/tap"); + locations.push_back ("./build/optimized/src/devices/tap"); + for (std::list::const_iterator i = locations.begin (); i != locations.end (); ++i) + { + if (Exists (*i + "/" + TAP_MANAGER)) + { + return *i + "/" + TAP_MANAGER; + } + } + NS_FATAL_ERROR ("Could not find manager"); + return ""; // quiet compiler +} + +int +TapManagerClient::AllocateTap (Mac48Address host, Ipv4Address ad, Ipv4Mask mask, Ipv4Address gateway) +{ + NS_LOG_FUNCTION (host << ad << mask << gateway); + // create a socket to get information back from the tap manager. + int sock = socket (PF_UNIX, SOCK_DGRAM, 0); + if (sock == -1) + { + NS_FATAL_ERROR ("Socket creation, errno=" << strerror (errno)); + } + + struct sockaddr_un un; + memset (&un, 0, sizeof (un)); + un.sun_family = AF_UNIX; + int status = bind (sock, (struct sockaddr*)&un, sizeof (sa_family_t)); // let the kernel allocate an endpoint for us. + if (status == -1) + { + NS_FATAL_ERROR ("Could not bind: errno=" << strerror (errno)); + } + socklen_t len = sizeof (un); + status = getsockname (sock, (struct sockaddr*)&un, &len); + if (status == -1) + { + NS_FATAL_ERROR ("Could not get socket address: errno=" << strerror (errno)); + } + NS_LOG_DEBUG ("Allocated enpoint=" << EncodeAsString (un, len) << ", len=" << len); + + pid_t pid = ::fork (); + if (pid == 0) + { + // child. + NS_LOG_DEBUG ("Child"); + + std::ostringstream oss; + oss << "--path=" << EncodeAsString (un, len); + std::string pathArg = oss.str (); + oss.str (""); + oss << "--mac-addr=" << host; + std::string hostArg = oss.str (); + oss.str (""); + oss << "--ip-addr=" << ad; + std::string ipArg = oss.str (); + oss.str (""); + oss << "--ip-gw=" << gateway; + std::string ipGw = oss.str (); + oss.str (""); + oss << "--ip-netmask=" << mask; + std::string ipMask = oss.str (); + oss.str (""); + status = ::execl (FindManager ().c_str (), + TAP_MANAGER, + pathArg.c_str (), + hostArg.c_str (), + ipArg.c_str (), + ipGw.c_str (), + ipMask.c_str (), + (char *)NULL); + if (status == -1) + { + NS_LOG_ERROR ("Cannot execl tap-manager, errno=" << ::strerror (errno)); + } + ::_exit (-1); + } + else + { + // parent + NS_LOG_DEBUG ("Parent"); + int st; + pid_t waited = waitpid (pid, &st, 0); + if (waited == -1) + { + NS_FATAL_ERROR ("Cannot wait for tap-manager, errno=" << strerror (errno)); + } + NS_ASSERT (pid == waited); + if (!WIFEXITED (st)) + { + // tap manager did not complete successfully + NS_FATAL_ERROR ("tap-manager did not exit correctly"); + } + else if (WEXITSTATUS (st) != 0) + { + NS_FATAL_ERROR ("tap-manager did not complete successfully, err=" << WEXITSTATUS (st)); + } + // the tap fd should be available on our unix socket now. + size_t msg_size = sizeof(int); + char control[CMSG_SPACE(msg_size)]; + struct cmsghdr *cmsg; + uint8_t buffer; + struct iovec iov; + iov.iov_base = &buffer; + iov.iov_len = 1; + struct msghdr msg; + msg.msg_name = 0; + msg.msg_namelen = 0; + msg.msg_iov = &iov; + msg.msg_iovlen = 1; + msg.msg_control = control; + msg.msg_controllen = sizeof (control); + msg.msg_flags = 0; + ssize_t bytesRead = recvmsg (sock, &msg, 0); + if (bytesRead != 1) + { + NS_FATAL_ERROR ("Did not get byte from tap-manager"); + } + NS_LOG_ERROR ("read bytes=" << bytesRead); + for (cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL; cmsg = CMSG_NXTHDR(&msg, cmsg)) + { + if (cmsg->cmsg_level == SOL_SOCKET && + cmsg->cmsg_type == SCM_RIGHTS) + { + int *fd = (int*)CMSG_DATA (cmsg); + NS_LOG_ERROR ("got tap fd=" << *fd); + return *fd; + } + } + NS_FATAL_ERROR ("Did not get SCM_RIGHTS from tap-manager"); + } + return -1; +} + +} // namespace ns3 diff --git a/src/devices/emutap/tap-manager-client.h b/src/devices/emutap/tap-manager-client.h new file mode 100644 index 000000000..eb5ce96d8 --- /dev/null +++ b/src/devices/emutap/tap-manager-client.h @@ -0,0 +1,21 @@ +#ifndef TAP_MANAGER_CLIENT_H +#define TAP_MANAGER_CLIENT_H + +#include "ns3/mac48-address.h" +#include "ns3/ipv4-address.h" +#include + +namespace ns3 { + +class TapManagerClient +{ +public: + int AllocateTap (Mac48Address host, Ipv4Address ad, Ipv4Mask mask, Ipv4Address gateway); +private: + std::string FindManager (void) const; + bool Exists (std::string filename) const; +}; + +} // namespace ns3 + +#endif /* TAP_MANAGER_CLIENT_H */ diff --git a/src/devices/emutap/tap-manager.cc b/src/devices/emutap/tap-manager.cc new file mode 100644 index 000000000..a68ec9fc7 --- /dev/null +++ b/src/devices/emutap/tap-manager.cc @@ -0,0 +1,339 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define noENABLE_LOG + +#define EXIT_ERROR(x, err) \ + std::cout << __FILE__ << ":" << __LINE__ << ": Unrecoverable Error: " << x; \ + std::cout << " errno=" << strerror (errno) << std::endl; \ + exit (err) +#ifdef ENABLE_LOG +#define LOG(x) \ + std::cout << x << std::endl; +#else +#define LOG(x) +#endif + + +#define CHECK_ARG(el,var) \ + { \ + char start[] = "--" el "="; \ + if (strncmp (*argv, start, strlen (start)) == 0) \ + { \ + var = *argv + strlen (start); \ + LOG ("--" << el << "=" << var); \ + } \ + } + +#define ASCII_DOT (0x2e) +#define ASCII_ZERO (0x30) +#define ASCII_a (0x41) +#define ASCII_z (0x5a) +#define ASCII_A (0x61) +#define ASCII_Z (0x7a) +#define ASCII_COLON (0x3a) +#define ASCII_ZERO (0x30) +static char +AsciiToLowCase (char c) +{ + if (c >= ASCII_a && c <= ASCII_z) { + return c; + } else if (c >= ASCII_A && c <= ASCII_Z) { + return c + (ASCII_a - ASCII_A); + } else { + return c; + } +} +static uint32_t +AsciiToIpv4 (const char *address) +{ + uint32_t host = 0; + while (true) { + uint8_t byte = 0; + while (*address != ASCII_DOT && + *address != 0) { + byte *= 10; + byte += *address - ASCII_ZERO; + address++; + } + host <<= 8; + host |= byte; + if (*address == 0) { + break; + } + address++; + } + return host; +} + +static void +AsciiToMac48 (const char *str, uint8_t addr[6]) +{ + int i = 0; + while (*str != 0 && i < 6) + { + uint8_t byte = 0; + while (*str != ASCII_COLON && *str != 0) + { + byte <<= 4; + char low = AsciiToLowCase (*str); + if (low >= ASCII_a) + { + byte |= low - ASCII_a + 10; + } + else + { + byte |= low - ASCII_ZERO; + } + str++; + } + addr[i] = byte; + i++; + if (*str == 0) + { + break; + } + str++; + } +} + +static void +SetInetAddress (sockaddr *ad, uint32_t networkOrder) +{ + struct sockaddr_in *sin = (struct sockaddr_in*)ad; + sin->sin_family = AF_INET; + sin->sin_port = 0; // unused + sin->sin_addr.s_addr = htonl (networkOrder); +} + + +static int +CreateTap (const char *mac_addr, const char *ip, + const char *gw, const char *netmask) +{ + // opening the tun device usually requires root privs + int tap = open ("/dev/net/tun", O_RDWR); + if (tap == -1) + { + EXIT_ERROR ("Could not open /dev/net/tun", 1); + } + // now, crate a tap device. + struct ifreq ifr; + // make sure that the tap device will not send us the tun_pi header. + ifr.ifr_flags = IFF_TAP | IFF_NO_PI; + ifr.ifr_name[0] = 0; // allow the kernel to pick a device name. + int status = ioctl (tap, TUNSETIFF, (void *) &ifr); + if (status == -1) + { + EXIT_ERROR ("Could not allocate a tap device", 2); + } + std::string tapDeviceName = (char *)ifr.ifr_name; + LOG ("Allocated TAP device=" << tapDeviceName); + + // set its hardware address to something we know will be unique within the simulation + ifr.ifr_hwaddr.sa_family = 1; // this is ARPHRD_ETHER from if_arp.h + AsciiToMac48 (mac_addr, (uint8_t*)ifr.ifr_hwaddr.sa_data); + status = ioctl (tap, SIOCSIFHWADDR, &ifr); + if (status == -1) + { + EXIT_ERROR ("Could not set hardware address=" << mac_addr << " for=" << (char *)ifr.ifr_name, 3); + } + LOG ("device=" << (char *)ifr.ifr_name << " addr=" << mac_addr); + + + // The ip address must be set using an AF_INET socket. + int fd = socket (AF_INET, SOCK_DGRAM, 0); + + // set interface up. + status = ioctl (fd, SIOCGIFFLAGS, &ifr); + if (status == -1) + { + EXIT_ERROR ("Could not get flags for interface=" << (char *)ifr.ifr_name, 4); + } + ifr.ifr_flags |= IFF_UP | IFF_RUNNING; + status = ioctl (fd, SIOCSIFFLAGS, &ifr); + if (status == -1) + { + EXIT_ERROR ("Could not bring interface " << (char *)ifr.ifr_name << " up", 5); + } + LOG ("device=" << (char *)ifr.ifr_name << " is up"); + + + // set its ip address. + SetInetAddress (&ifr.ifr_addr, AsciiToIpv4 (ip)); + status = ioctl (fd, SIOCSIFADDR, &ifr); + if (status == -1) + { + EXIT_ERROR ("Could not set ip address=" << ip << " for=" << (char *)ifr.ifr_name, 6); + } + LOG ("device=" << (char *)ifr.ifr_name << " addr=" << ip); + + // set its ip mask to be /32 + SetInetAddress (&ifr.ifr_netmask, 0xffffffff); + status = ioctl (fd, SIOCSIFNETMASK, &ifr); + if (status == -1) + { + EXIT_ERROR ("Could not set ip mask=" << netmask << " for=" << (char *)ifr.ifr_name, 7); + } + LOG ("device=" << (char *)ifr.ifr_name << " mask=" << netmask); + + // add routing entry for gateway. + struct rtentry rt; + SetInetAddress (&rt.rt_dst, AsciiToIpv4 (gw)); + SetInetAddress (&rt.rt_genmask, 0xffffffff); + rt.rt_flags = RTF_UP; + rt.rt_metric = 2; + rt.rt_dev = (char*)tapDeviceName.c_str (); + status = ioctl (fd, SIOCADDRT, &rt); + if (status == -1) + { + EXIT_ERROR ("Could not add routing table entry", 8); + } + LOG ("added routing table entry for gw."); + + // add routing entry for subnet through gateway. + uint32_t network = AsciiToIpv4 (ip) & AsciiToIpv4 (netmask); + SetInetAddress (&rt.rt_dst, network); + SetInetAddress (&rt.rt_gateway, AsciiToIpv4 (gw)); + SetInetAddress (&rt.rt_genmask, AsciiToIpv4 (netmask)); + rt.rt_flags = RTF_UP | RTF_GATEWAY; + rt.rt_metric = 2; + rt.rt_dev = (char*)tapDeviceName.c_str (); + status = ioctl (fd, SIOCADDRT, &rt); + if (status == -1) + { + EXIT_ERROR ("Could not add routing table entry", 9); + } + LOG ("added routing table entry for subnet."); + + return tap; +} + +static struct sockaddr_un +DecodeFromString (const char *path, socklen_t *len) +{ + sockaddr_un un; + uint8_t *buffer = (uint8_t *)&un; + std::istringstream iss; + iss.str (path); + uint8_t n = 0; + while (!iss.bad () && !iss.eof () && !iss.fail ()) + { + char c; + iss.read (&c, 1); + uint32_t tmp; + iss >> std::hex >> tmp; + //LOG (std::hex << tmp); + buffer[n] = tmp; + n++; + } + *len = n; + return un; +} + +static void +SendFd (const char *path, int fd) +{ + // send back configuration to caller. + int sock = socket (PF_UNIX, SOCK_DGRAM, 0); + if (sock == -1) + { + EXIT_ERROR ("Socket creation", 10); + } + LOG ("Socket Created"); + + socklen_t local_len; + struct sockaddr_un local = DecodeFromString (path, &local_len); + LOG ("len=" << local_len); + int status = connect (sock, (struct sockaddr*)&local, local_len); + if (status == -1) + { + EXIT_ERROR ("Could not connect to caller", 11); + } + LOG ("Socket Connected"); + + // we send a single byte whose content is meaningless. + // we also return as ancillary data the tap file descriptor + struct cmsghdr *cmsg; + size_t msg_size = sizeof(int); + char control[CMSG_SPACE(msg_size)]; + struct iovec iov; + struct msghdr msg; + char buffer = 0; + iov.iov_base = &buffer; + iov.iov_len = 1; + msg.msg_name = 0; + msg.msg_namelen = 0; + msg.msg_iov = &iov; + msg.msg_iovlen = 1; + msg.msg_control = control; + msg.msg_controllen = sizeof (control); + msg.msg_flags = 0; + + cmsg = CMSG_FIRSTHDR(&msg); + cmsg->cmsg_level = SOL_SOCKET; + cmsg->cmsg_type = SCM_RIGHTS; + cmsg->cmsg_len = CMSG_LEN(msg_size); + msg.msg_controllen = cmsg->cmsg_len; + + int *fdptr = (int*) (CMSG_DATA(cmsg)); + *fdptr = fd; + + ssize_t len = sendmsg(sock, &msg, 0); + if (len == -1) + { + EXIT_ERROR ("Could not send SCM_RIGHTS", 12); + } + LOG ("Sent SCM_RIGHTS"); +} + + + + +int main (int argc, char *argv[]) +{ + char *path = 0; + char *mac_addr = 0; + char *ip_addr = 0; + char *ip_gw = 0; + char *ip_netmask = 0; + char *stop = 0; + argv++; + argc--; + while (argc > 0) + { + CHECK_ARG("path", path); + CHECK_ARG("mac-addr", mac_addr); + CHECK_ARG("ip-addr", ip_addr); + CHECK_ARG("ip-gw", ip_gw); + CHECK_ARG("ip-netmask", ip_netmask); + CHECK_ARG("stop", stop); + argv++; + argc--; + } + + int tap = CreateTap (mac_addr, ip_addr, ip_gw, ip_netmask); + + if (stop) + { + while (1) {} + } + + SendFd (path, tap); + + return 0; +} diff --git a/src/devices/emutap/tap-net-device.cc b/src/devices/emutap/tap-net-device.cc new file mode 100644 index 000000000..85f189dc5 --- /dev/null +++ b/src/devices/emutap/tap-net-device.cc @@ -0,0 +1,323 @@ +/* -*- 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 + */ +#include "tap-net-device.h" +#include "tap-manager-client.h" +#include "ns3/node.h" +#include "ns3/channel.h" +#include "ns3/packet.h" +#include "ns3/log.h" +#include "ns3/system-thread.h" +#include "ns3/realtime-simulator-impl.h" +#include "ns3/make-event.h" +#include "ns3/simulator.h" +#include "ns3/ethernet-header.h" +#include "ns3/trace-source-accessor.h" +#include "host-tap-net-device.h" +#include "tap-channel.h" +#include +#include + +NS_LOG_COMPONENT_DEFINE ("TapNetDevice"); + +namespace ns3 { + +TypeId +TapNetDevice::GetTypeId (void) +{ + static TypeId tid = TypeId ("ns3::TapNetDevice") + .SetParent () + .AddConstructor () + .AddTraceSource ("Rx", "A packet has been received", + MakeTraceSourceAccessor (&TapNetDevice::m_rxTrace)) + .AddTraceSource ("Tx", "A packet has been sent", + MakeTraceSourceAccessor (&TapNetDevice::m_txTrace)) + .AddTraceSource ("Drop", "A packet has been dropped", + MakeTraceSourceAccessor (&TapNetDevice::m_dropTrace)) + ; + return tid; +} + +TapNetDevice::TapNetDevice () + : m_node (0), + m_mtu (0xffff), + m_name (""), + m_ifIndex (0), + m_tap (-1) +{ + NS_LOG_FUNCTION (this); +} + +void +TapNetDevice::SetChannel (Ptr channel) +{ + m_channel = channel; + m_channel->SetDevice (this); +} + +void +TapNetDevice::SetupHost (Ipv4Address ad, Ipv4Mask mask, Ipv4Address gateway) +{ + NS_LOG_FUNCTION (this << ad << mask << gateway); + NS_ASSERT (m_tap == -1); + + Mac48Address hostMacAddress = m_channel->GetHostDevice ()->GetMacAddress (); + + TapManagerClient manager; + m_tap = manager.AllocateTap (hostMacAddress, ad, mask, gateway); + + m_thread = Create (MakeCallback (&TapNetDevice::ReadThread, this)); + m_thread->Start (); +} + + +void +TapNetDevice::ReadThread (void) +{ + NS_LOG_FUNCTION (this); + + while (1) + { + uint8_t *buffer = (uint8_t *)malloc (0xffff); + ssize_t bytesRead = read (m_tap, buffer, 0xffff); + if (bytesRead == -1) + { + if (errno == EBADF || errno == EINTR) + { + // the device was closed from under us by ::DoDispose + return; + } + NS_FATAL_ERROR ("Error reading from tap device: errno=" << strerror (errno)); + } + // Note: we purposedly don't use a smart pointer to manage this packet + // because the want to hand over ownership of this packet to the ForwardUp + // method. + DynamicCast (Simulator::GetImplementation ())-> + ScheduleRealtimeNow (MakeEvent (&TapNetDevice::ForwardUp, this, buffer, (uint32_t)bytesRead)); + } +} + +void +TapNetDevice::ForwardUp (uint8_t *buffer, uint32_t size) +{ + NS_LOG_FUNCTION (this << buffer << size); + + // swallow packet reference in smart pointer. + Ptr packet = Create (buffer, size); + free (buffer); + Ptr copy = packet->Copy (); + + EthernetHeader header = EthernetHeader (false); + packet->RemoveHeader (header); + + uint16_t protocol = header.GetLengthType (); + Mac48Address to = header.GetDestination (); + Mac48Address from = header.GetSource (); + + NetDevice::PacketType packetType; + if (to == m_address) + { + packetType = NetDevice::PACKET_HOST; + } + else if (to.IsBroadcast ()) + { + packetType = NetDevice::PACKET_HOST; + } + else if (to.IsMulticast ()) + { + packetType = NetDevice::PACKET_MULTICAST; + } + else + { + packetType = NetDevice::PACKET_OTHERHOST; + } + m_rxTrace (copy, from, to); + if (packetType != NetDevice::PACKET_OTHERHOST) + { + m_rxCallback (this, packet, protocol, from); + } + if (!m_promiscCallback.IsNull ()) + { + m_promiscCallback (this, packet, protocol, from, to, packetType); + } +} + +void +TapNetDevice::SetAddress (Mac48Address address) +{ + m_address = address; +} + +void +TapNetDevice::SetName(const std::string name) +{ + m_name = name; +} +std::string +TapNetDevice::GetName(void) const +{ + return m_name; +} +void +TapNetDevice::SetIfIndex(const uint32_t index) +{ + m_ifIndex = index; +} +uint32_t +TapNetDevice::GetIfIndex(void) const +{ + return m_ifIndex; +} +Ptr +TapNetDevice::GetChannel (void) const +{ + return m_channel; +} +Address +TapNetDevice::GetAddress (void) const +{ + return m_address; +} +bool +TapNetDevice::SetMtu (const uint16_t mtu) +{ + m_mtu = mtu; + return true; +} +uint16_t +TapNetDevice::GetMtu (void) const +{ + return m_mtu; +} +bool +TapNetDevice::IsLinkUp (void) const +{ + return true; +} +void +TapNetDevice::SetLinkChangeCallback (Callback callback) +{} +bool +TapNetDevice::IsBroadcast (void) const +{ + return true; +} +Address +TapNetDevice::GetBroadcast (void) const +{ + return Mac48Address ("ff:ff:ff:ff:ff:ff"); +} +bool +TapNetDevice::IsMulticast (void) const +{ + return true; +} +Address +TapNetDevice::GetMulticast (void) const +{ + return Mac48Address::GetMulticastPrefix (); +} +Address +TapNetDevice::MakeMulticastAddress (Ipv4Address multicastGroup) const +{ + return Mac48Address::GetMulticast (multicastGroup); +} +bool +TapNetDevice::IsPointToPoint (void) const +{ + return false; +} +bool +TapNetDevice::Send(Ptr packet, const Address& dest, uint16_t protocolNumber) +{ + NS_LOG_FUNCTION (this << packet << dest << protocolNumber); + return SendFrom (packet, m_address, dest, protocolNumber); +} +bool +TapNetDevice::SendFrom(Ptr packet, const Address& source, const Address& dest, uint16_t protocolNumber) +{ + NS_LOG_FUNCTION (this << packet << source << dest << protocolNumber); + Mac48Address to = Mac48Address::ConvertFrom (dest); + Mac48Address from = Mac48Address::ConvertFrom (source); + + EthernetHeader header = EthernetHeader (false); + header.SetSource (from); + header.SetDestination (to); + header.SetLengthType (protocolNumber); + packet->AddHeader (header); + + ssize_t written = write (m_tap, packet->PeekData (), packet->GetSize ()); + if (written == -1 || written != (ssize_t)packet->GetSize ()) + { + m_dropTrace (packet, from, to); + return false; + } + + m_txTrace (packet, from, to); + + return true; +} + +Ptr +TapNetDevice::GetNode (void) const +{ + return m_node; +} +void +TapNetDevice::SetNode (Ptr node) +{ + m_node = node; +} +bool +TapNetDevice::NeedsArp (void) const +{ + return true; +} +void +TapNetDevice::SetReceiveCallback (NetDevice::ReceiveCallback cb) +{ + m_rxCallback = cb; +} + +void +TapNetDevice::DoDispose (void) +{ + NS_LOG_FUNCTION (this); + close (m_tap); + m_thread->Join (); + m_thread = 0; + m_node = 0; + m_channel = 0; + NetDevice::DoDispose (); +} + + +void +TapNetDevice::SetPromiscReceiveCallback (PromiscReceiveCallback cb) +{ + m_promiscCallback = cb; +} + +bool +TapNetDevice::SupportsSendFrom (void) const +{ + return true; +} + +} // namespace ns3 diff --git a/src/devices/emutap/tap-net-device.h b/src/devices/emutap/tap-net-device.h new file mode 100644 index 000000000..d0f493b92 --- /dev/null +++ b/src/devices/emutap/tap-net-device.h @@ -0,0 +1,103 @@ +/* -*- 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 + */ +#ifndef TAP_NET_DEVICE_H +#define TAP_NET_DEVICE_H + +#include "ns3/net-device.h" +#include "ns3/mac48-address.h" +#include "ns3/traced-callback.h" +#include +#include + +namespace ns3 { + +class Node; +class SystemThread; +class TapChannel; + +/** + * \ingroup netdevice + * + * \brief a NetDevice to get packets to and from a host tap device. + */ +class TapNetDevice : public NetDevice +{ +public: + static TypeId GetTypeId (void); + TapNetDevice (); + + void SetAddress (Mac48Address address); + + void SetChannel (Ptr channel); + + void SetupHost (Ipv4Address ad, Ipv4Mask mask, Ipv4Address gateway); + + // inherited from NetDevice base class. + virtual void SetName(const std::string name); + virtual std::string GetName(void) const; + virtual void SetIfIndex(const uint32_t index); + virtual uint32_t GetIfIndex(void) const; + virtual Ptr GetChannel (void) const; + virtual Address GetAddress (void) const; + virtual bool SetMtu (const uint16_t mtu); + virtual uint16_t GetMtu (void) const; + virtual bool IsLinkUp (void) const; + virtual void SetLinkChangeCallback (Callback callback); + virtual bool IsBroadcast (void) const; + virtual Address GetBroadcast (void) const; + virtual bool IsMulticast (void) const; + virtual Address GetMulticast (void) const; + virtual Address MakeMulticastAddress (Ipv4Address multicastGroup) const; + virtual bool IsPointToPoint (void) const; + virtual bool Send(Ptr packet, const Address& dest, uint16_t protocolNumber); + virtual bool SendFrom(Ptr packet, const Address& source, const Address& dest, uint16_t protocolNumber); + virtual Ptr GetNode (void) const; + virtual void SetNode (Ptr node); + virtual bool NeedsArp (void) const; + virtual void SetReceiveCallback (NetDevice::ReceiveCallback cb); + virtual void SetPromiscReceiveCallback (PromiscReceiveCallback cb); + virtual bool SupportsSendFrom (void) const; + +protected: + virtual void DoDispose (void); +private: + void Receive (Ptr packet, uint16_t protocol, + Mac48Address to, Mac48Address from); + void ForwardUp (uint8_t *buffer, uint32_t size); + void ReadThread (void); + + NetDevice::ReceiveCallback m_rxCallback; + NetDevice::PromiscReceiveCallback m_promiscCallback; + Ptr m_node; + uint16_t m_mtu; + std::string m_name; + uint32_t m_ifIndex; + Mac48Address m_address; + int m_tap; + Ptr m_thread; + TracedCallback,Mac48Address,Mac48Address> m_rxTrace; + TracedCallback,Mac48Address,Mac48Address> m_txTrace; + TracedCallback,Mac48Address,Mac48Address> m_dropTrace; + Ptr m_channel; +}; + +} // namespace ns3 + +#endif /* TAP_NET_DEVICE_H */ diff --git a/src/devices/emutap/wscript b/src/devices/emutap/wscript new file mode 100644 index 000000000..11bdb3a3c --- /dev/null +++ b/src/devices/emutap/wscript @@ -0,0 +1,26 @@ +## -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*- + + +def build(bld): + obj = bld.create_suid_program('ns3-tap-manager') + obj.source = [ + 'tap-manager.cc', + ] + + module = bld.create_ns3_module('emutap', ['node']) + module.uselib = 'CAP' + module.source = [ + 'tap-net-device.cc', + 'tap-manager-client.cc', + 'tap-channel.cc', + 'host-tap-net-device.cc', + ] + headers = bld.create_obj('ns3header') + headers.module = 'emutap' + headers.source = [ + 'tap-net-device.h', + 'host-tap-net-device.h', + 'tap-channel.h', + ] + + diff --git a/src/wscript b/src/wscript index bc8c87689..5cf64f53f 100644 --- a/src/wscript +++ b/src/wscript @@ -19,6 +19,8 @@ all_modules = ( 'internet-stack', 'devices/point-to-point', 'devices/csma', + 'devices/bridge', + 'devices/emutap', 'applications/onoff', 'applications/packet-sink', 'applications/udp-echo', @@ -27,7 +29,6 @@ all_modules = ( 'mobility', 'devices/wifi', 'helper', - 'devices/bridge', 'contrib/stats', ) diff --git a/wscript b/wscript index 8eb8c50b5..b78b2e812 100644 --- a/wscript +++ b/wscript @@ -12,6 +12,7 @@ import pproc as subprocess import Params import Object import ccroot +import Task Params.g_autoconfig = 1 @@ -166,6 +167,10 @@ def set_options(opt): help=('For regression testing, only run/generate the indicated regression tests, ' 'specified as a comma separated list of test names'), dest='regression_tests', type="string") + opt.add_option('--disable-sudo', + help=('Do not attempt to use sudo to setup suid bits on ns3 executables.'), + dest='disable_sudo', action='store_true', + default=False) # options provided in a script in a subdirectory named "src" opt.sub_options('src') @@ -275,6 +280,9 @@ def configure(conf): # we cannot run regression tests without diff conf.find_program('diff', var='DIFF') + # for suid bits + conf.find_program('sudo', var='SUDO') + # we cannot pull regression traces without mercurial conf.find_program('hg', var='MERCURIAL') @@ -288,6 +296,41 @@ def configure(conf): print "%-30s: %s" % (caption, status) +class SuidBuildTask(Task.TaskBase): + """task that makes a binary Suid + """ + def __init__(self, bld, program): + self.m_display = 'build-suid' + self.prio = 1000 # build after the rest of ns-3 + self.__program = program + self.__env = bld.env () + super(SuidBuildTask, self).__init__() + + def run(self): + try: + program_obj = _find_program(self.__program.target, self.__env) + except ValueError, ex: + Params.fatal(str(ex)) + + try: + program_node = program_obj.path.find_build(ccroot.get_target_name(program_obj)) + except AttributeError: + Params.fatal("%s does not appear to be a program" % (program_name,)) + + filename = program_node.abspath(self.__env) + os.system ('sudo chown root ' + filename) + os.system ('sudo chmod u+s ' + filename) + +def create_suid_program(bld, name): + program = bld.create_obj('cpp', 'program') + program.is_ns3_program = True + program.module_deps = list() + program.name = name + program.target = name + if bld.env ()['SUDO'] and not Params.g_options.disable_sudo: + SuidBuildTask (bld, program) + return program + def create_ns3_program(bld, name, dependencies=('simulator',)): program = bld.create_obj('cpp', 'program') program.is_ns3_program = True @@ -340,6 +383,7 @@ def build(bld): Params.g_cwd_launch = Params.g_build.m_curdirnode.abspath() bld.create_ns3_program = types.MethodType(create_ns3_program, bld) + bld.create_suid_program = types.MethodType(create_suid_program, bld) variant_name = bld.env_of_name('default')['NS3_ACTIVE_VARIANT'] variant_env = bld.env_of_name(variant_name) bld.m_allenvs['default'] = variant_env # switch to the active variant From eeea109010615ec8f0a61c86c3d0d61d9339b5be Mon Sep 17 00:00:00 2001 From: Craig Dowell Date: Mon, 27 Oct 2008 22:01:24 -0700 Subject: [PATCH 02/52] give up on merging tap and emulated, break apart --- src/devices/emulated/emulated-net-device.cc | 642 ++++++++++++++++++ src/devices/emulated/emulated-net-device.h | 321 +++++++++ src/devices/emulated/emulated.h | 10 + src/devices/emulated/waf | 1 + src/devices/emulated/wscript | 14 + .../{emutap => tap}/host-tap-net-device.cc | 0 .../{emutap => tap}/host-tap-net-device.h | 0 src/devices/{emutap => tap}/tap-channel.cc | 0 src/devices/{emutap => tap}/tap-channel.h | 0 .../{emutap => tap}/tap-manager-client.cc | 0 .../{emutap => tap}/tap-manager-client.h | 0 src/devices/{emutap => tap}/tap-manager.cc | 37 +- src/devices/{emutap => tap}/tap-net-device.cc | 0 src/devices/{emutap => tap}/tap-net-device.h | 0 src/devices/{emutap => tap}/wscript | 4 +- src/node/net-device.h | 20 +- src/wscript | 3 +- 17 files changed, 1037 insertions(+), 15 deletions(-) create mode 100644 src/devices/emulated/emulated-net-device.cc create mode 100644 src/devices/emulated/emulated-net-device.h create mode 100644 src/devices/emulated/emulated.h create mode 100755 src/devices/emulated/waf create mode 100644 src/devices/emulated/wscript rename src/devices/{emutap => tap}/host-tap-net-device.cc (100%) rename src/devices/{emutap => tap}/host-tap-net-device.h (100%) rename src/devices/{emutap => tap}/tap-channel.cc (100%) rename src/devices/{emutap => tap}/tap-channel.h (100%) rename src/devices/{emutap => tap}/tap-manager-client.cc (100%) rename src/devices/{emutap => tap}/tap-manager-client.h (100%) rename src/devices/{emutap => tap}/tap-manager.cc (88%) rename src/devices/{emutap => tap}/tap-net-device.cc (100%) rename src/devices/{emutap => tap}/tap-net-device.h (100%) rename src/devices/{emutap => tap}/wscript (85%) diff --git a/src/devices/emulated/emulated-net-device.cc b/src/devices/emulated/emulated-net-device.cc new file mode 100644 index 000000000..157308a7c --- /dev/null +++ b/src/devices/emulated/emulated-net-device.cc @@ -0,0 +1,642 @@ +/* -*- 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 + */ + +#include "emulated-net-device.h" + +#include "ns3/log.h" +#include "ns3/queue.h" +#include "ns3/simulator.h" +#include "ns3/realtime-simulator-impl.h" +#include "ns3/mac48-address.h" +#include "ns3/ethernet-header.h" +#include "ns3/ethernet-trailer.h" +#include "ns3/llc-snap-header.h" +#include "ns3/trace-source-accessor.h" +#include "ns3/pointer.h" +#include "ns3/channel.h" +#include "ns3/system-thread.h" +#include "ns3/string.h" +#include "ns3/boolean.h" + +#include +#include +#include +#include +#include +#include +#include + +NS_LOG_COMPONENT_DEFINE ("EmulatedNetDevice"); + +namespace ns3 { + +NS_OBJECT_ENSURE_REGISTERED (EmulatedNetDevice); + +TypeId +EmulatedNetDevice::GetTypeId (void) +{ + static TypeId tid = TypeId ("ns3::EmulatedNetDevice") + .SetParent () + .AddConstructor () + .AddAttribute ("Address", + "The ns-3 MAC address of this (virtual) device.", + Mac48AddressValue (Mac48Address ("ff:ff:ff:ff:ff:ff")), + MakeMac48AddressAccessor (&EmulatedNetDevice::m_address), + MakeMac48AddressChecker ()) + .AddAttribute ("DeviceName", + "The name of the underlying real device (e.g. eth1).", + StringValue ("eth1"), + MakeStringAccessor (&EmulatedNetDevice::m_deviceName), + MakeStringChecker ()) + .AddAttribute ("Start", + "The simulation time at which to spin up the device thread.", + TimeValue (Seconds (0.)), + MakeTimeAccessor (&EmulatedNetDevice::m_tStart), + MakeTimeChecker ()) + .AddAttribute ("Stop", + "The simulation time at which to tear down the device thread.", + TimeValue (Seconds (0.)), + MakeTimeAccessor (&EmulatedNetDevice::m_tStop), + MakeTimeChecker ()) + .AddAttribute ("TxQueue", + "A queue to use as the transmit queue in the device.", + PointerValue (), + MakePointerAccessor (&EmulatedNetDevice::m_queue), + MakePointerChecker ()) + .AddTraceSource ("Rx", + "Trace source to fire on reception of a MAC packet.", + MakeTraceSourceAccessor (&EmulatedNetDevice::m_rxTrace)) + .AddTraceSource ("Drop", + "Trace source to fire on when a MAC packet is dropped.", + MakeTraceSourceAccessor (&EmulatedNetDevice::m_dropTrace)) + ; + return tid; +} + + +EmulatedNetDevice::EmulatedNetDevice () +: + m_startEvent (), + m_stopEvent (), + m_sock (-1), + m_readThread (0), + m_ifIndex (-1), + m_sll_ifindex (-1), + m_name ("Emulated NetDevice") +{ + NS_LOG_FUNCTION (this); + Start (m_tStart); +} + +EmulatedNetDevice::~EmulatedNetDevice () +{ +} + +void +EmulatedNetDevice::DoDispose() +{ + NS_LOG_FUNCTION_NOARGS (); + m_node = 0; + NetDevice::DoDispose (); +} + +void +EmulatedNetDevice::Start (Time tStart) +{ + NS_LOG_FUNCTION (tStart); + + // + // Cancel any pending start event and schedule a new one at some relative time in the future. + // + Simulator::Cancel (m_startEvent); + m_startEvent = Simulator::Schedule (tStart, &EmulatedNetDevice::StartDevice, this); +} + + void +EmulatedNetDevice::Stop (Time tStop) +{ + NS_LOG_FUNCTION (tStop); + // + // Cancel any pending stop event and schedule a new one at some relative time in the future. + // + Simulator::Cancel (m_stopEvent); + m_startEvent = Simulator::Schedule (tStop, &EmulatedNetDevice::StopDevice, this); +} + + void +EmulatedNetDevice::StartDevice (void) +{ + NS_LOG_FUNCTION_NOARGS (); + + // + // Spin up the emulated net device and start receiving packets. + // + NS_ASSERT_MSG (m_sock == -1, "EmulatedNetDevice::StartDevice(): Device is already started"); + + NS_LOG_LOGIC ("Creating socket"); + + m_sock = socket (PF_PACKET, SOCK_RAW, htons(ETH_P_ALL)); + // m_sock = socket (AF_INET, SOCK_PACKET, htons(ETH_P_ALL)); + NS_ASSERT_MSG (m_sock != -1, "EmulatedNetDevice::StartDevice(): Unable to open socket"); + + // + // Figure out which interface index corresponds to the device name in the corresponding attribute. + // + struct ifreq ifr; + bzero (&ifr, sizeof(ifr)); + strncpy ((char *)ifr.ifr_name, m_deviceName.c_str (), IFNAMSIZ); + + NS_LOG_LOGIC ("Getting interface index"); + int32_t rc = ioctl (m_sock, SIOCGIFINDEX, &ifr); + NS_ASSERT_MSG (rc != -1, "EmulatedNetDevice::StartDevice(): Can't get interface index"); + + // + // Save the real interface index for later calls to sendto + // + m_sll_ifindex = ifr.ifr_ifindex; + + // + // Bind the socket to the interface we just found. + // + struct sockaddr_ll ll; + bzero (&ll, sizeof(ll)); + + ll.sll_family = AF_PACKET; + ll.sll_ifindex = m_sll_ifindex; + ll.sll_protocol = htons(ETH_P_ALL); + + NS_LOG_LOGIC ("Binding socket to interface"); + + rc = bind (m_sock, (struct sockaddr *)&ll, sizeof (ll)); + NS_ASSERT_MSG (rc != -1, "EmulatedNetDevice::StartDevice(): Can't bind to specified interface"); + + // + // Now spin up a read thread to read packets. + // + NS_ASSERT_MSG (m_readThread == 0, "EmulatedNetDevice::StartDevice(): Receive thread is already running"); + + NS_LOG_LOGIC ("Spinning up read thread"); + + m_readThread = Create (MakeCallback (&EmulatedNetDevice::ReadThread, this)); + m_readThread->Start (); + + NotifyLinkUp (); +} + +void +EmulatedNetDevice::StopDevice (void) +{ + NS_LOG_FUNCTION_NOARGS (); + + close (m_sock); + m_sock = -1; + + NS_ASSERT_MSG (m_readThread != 0, "EmulatedNetDevice::StopDevice(): Receive thread is not running"); + + NS_LOG_LOGIC ("Joining read thread"); + m_readThread->Join (); + m_readThread = 0; +} + +void +EmulatedNetDevice::ForwardUp (uint8_t *buf, uint32_t len) +{ + NS_LOG_FUNCTION (buf << len); + + // + // Create a packet out of the buffer we received and free that buffer. + // + Ptr packet = Create (reinterpret_cast (buf), len); + free (buf); + buf = 0; + + // + // Trace sinks will expect complete packets, not packets without some of the + // headers. + // + Ptr originalPacket = packet->Copy (); + + // + // Checksum the packet + // + EthernetTrailer trailer; + packet->RemoveTrailer (trailer); + trailer.CheckFcs (packet); + + EthernetHeader header (false); + packet->RemoveHeader (header); + + NS_LOG_LOGIC ("Pkt source is " << header.GetSource ()); + NS_LOG_LOGIC ("Pkt destination is " << header.GetDestination ()); + + // + // An IP host group address is mapped to an Ethernet multicast address + // by placing the low-order 23-bits of the IP address into the low-order + // 23 bits of the Ethernet multicast address 01-00-5E-00-00-00 (hex). + // + // We are going to receive all packets destined to any multicast address, + // which means clearing the low-order 23 bits the header destination + // + Mac48Address mcDest; + uint8_t mcBuf[6]; + + header.GetDestination ().CopyTo (mcBuf); + mcBuf[3] &= 0x80; + mcBuf[4] = 0; + mcBuf[5] = 0; + mcDest.CopyFrom (mcBuf); + + Mac48Address multicast = Mac48Address::ConvertFrom (GetMulticast ()); + Mac48Address broadcast = Mac48Address::ConvertFrom (GetBroadcast ()); + Mac48Address destination = Mac48Address::ConvertFrom (GetAddress ()); + + LlcSnapHeader llc; + packet->RemoveHeader (llc); + uint16_t protocol = llc.GetType (); + + PacketType packetType; + + if (header.GetDestination () == broadcast) + { + NS_LOG_LOGIC ("Pkt destination is PACKET_BROADCAST"); + packetType = NS3_PACKET_BROADCAST; + } + else if (mcDest == multicast) + { + NS_LOG_LOGIC ("Pkt destination is PACKET_MULTICAST"); + packetType = NS3_PACKET_MULTICAST; + } + else if (header.GetDestination () == destination) + { + NS_LOG_LOGIC ("Pkt destination is PACKET_HOST"); + packetType = NS3_PACKET_HOST; + } + else + { + NS_LOG_LOGIC ("Pkt destination is PACKET_OTHERHOST"); + packetType = NS3_PACKET_OTHERHOST; + } + + if (!m_promiscRxCallback.IsNull ()) + { + NS_LOG_LOGIC ("calling m_promiscRxCallback"); + m_promiscRxCallback (this, packet->Copy (), protocol, header.GetSource (), header.GetDestination (), packetType); + } + + if (packetType != NS3_PACKET_OTHERHOST) + { + m_rxTrace (originalPacket); + NS_LOG_LOGIC ("calling m_rxCallback"); + m_rxCallback (this, packet, protocol, header.GetSource ()); + } +} + +void +EmulatedNetDevice::ReadThread (void) +{ + NS_LOG_FUNCTION_NOARGS (); + + // + // It's important to remember that we're in a completely different thread than the simulator is running in. We + // need to synchronize with that other thread to get the packet up into ns-3. What we will need to do is to schedule + // a method to forward up the packet using the multithreaded simulator we are most certainly running. However, I just + // said it -- we are talking about two threads here, so it is very, very dangerous to do any kind of reference couning + // on a shared object. Just don't do it. So what we're going to do is to allocate a buffer on the heap and pass that + // buffer into the ns-3 context thread where it will create the packet. + // + + int32_t len = -1; + struct sockaddr_ll addr; + socklen_t addrSize = sizeof (addr); + + for (;;) + { + uint32_t bufferSize = 65536; + uint8_t *buf = (uint8_t *)malloc (bufferSize); + NS_ASSERT_MSG (buf, "EmulatedNetDevice::ReadThread(): malloc packet buffer failed"); + NS_LOG_LOGIC ("Calling recvfrom"); + len = recvfrom (m_sock, buf, bufferSize, 0, (struct sockaddr *)&addr, &addrSize); + + if (len == -1) + { + free (buf); + buf = 0; + return; + } + + NS_LOG_INFO ("EmulatedNetDevice::ReadThread(): Received packet"); + NS_LOG_INFO ("EmulatedNetDevice::ReadThread(): Scheduling handler"); + DynamicCast (Simulator::GetImplementation ())->ScheduleRealtimeNow ( + MakeEvent (&EmulatedNetDevice::ForwardUp, this, buf, len)); + buf = 0; + } +} + +bool +EmulatedNetDevice::Send (Ptr packet, const Address &dest, uint16_t protocolNumber) +{ + NS_LOG_FUNCTION (packet << dest << protocolNumber); + // + // The immediate questions here are how are we going to encapsulate packets and what do we use as the MAC source and + // destination (hardware) addresses? + // + // If we return false from EmulatedNetDevice::NeedsArp, the ArpIpv4Interface will pass the broadcast address as the + // hardware (Ethernet) destination by default. If we return true from EmulatedNetDevice::NeedsArp, then the hardware + // destination is actually meaningful, but we'll have an ns-3 ARP running on this device. There can also be an ARP + // running on the underlying OS so we have to be very careful, both about multiple ARPs and also about TCP, UDP, etc. + // + // We are operating in promiscuous mode on the receive side (all ns-3 net devices are required to implement the + // promiscuous callback in a meaningful way), so we have an option regarding the hardware addresses. We don't actually have + // to use the real hardware addresses and IP addresses of the underlying system. We can completely use MAC-spoofing to + // fake out the OS by using the ns-3 assigned MAC address (and also the ns-3 assigned IP addresses). Ns-3 starts its + // MAC address allocation using the OUI (vendor-code) 00:00:00 which is unassigned to any organization and is a globally + // administered address, so there shouldn't be any collisions with real hardware. + // + // So what we do is we return true from EmulatedNetDevice::NeedsArp which tells ns-3 to use its own ARP. We spoof the + // MAC address of the device and use promiscuous mode to receive traffic destined to that address. + // + return SendFrom (packet, m_address, dest, protocolNumber); +} + +bool +EmulatedNetDevice::SendFrom (Ptr packet, const Address &src, const Address &dest, uint16_t protocolNumber) +{ + NS_LOG_FUNCTION (packet << src << dest << protocolNumber); + + if (IsLinkUp () == false) + { + NS_LOG_LOGIC ("Link is down, returning"); + return false; + } + + Mac48Address destination = Mac48Address::ConvertFrom (dest); + Mac48Address source = Mac48Address::ConvertFrom (src); + + NS_LOG_LOGIC ("Transmit packet with UID " << packet->GetUid ()); + NS_LOG_LOGIC ("Transmit packet from " << source); + NS_LOG_LOGIC ("Transmit packet to " << destination); + +#if 0 + { + struct ifreq ifr; + bzero (&ifr, sizeof(ifr)); + strncpy ((char *)ifr.ifr_name, m_deviceName.c_str (), IFNAMSIZ); + + NS_LOG_LOGIC ("Getting MAC address"); + int32_t rc = ioctl (m_sock, SIOCGIFHWADDR, &ifr); + NS_ASSERT_MSG (rc != -1, "EmulatedNetDevice::SendFrom(): Can't get MAC address"); + + std::ostringstream oss; + oss << std::hex << + (ifr.ifr_hwaddr.sa_data[0] & 0xff) << ":" << + (ifr.ifr_hwaddr.sa_data[1] & 0xff) << ":" << + (ifr.ifr_hwaddr.sa_data[2] & 0xff) << ":" << + (ifr.ifr_hwaddr.sa_data[3] & 0xff) << ":" << + (ifr.ifr_hwaddr.sa_data[4] & 0xff) << ":" << + (ifr.ifr_hwaddr.sa_data[5] & 0xff) << std::dec; + + NS_LOG_LOGIC ("Fixup source to HW MAC " << oss.str ()); + source = Mac48Address (oss.str ().c_str ()); + NS_LOG_LOGIC ("source now " << source); + } +#endif + + LlcSnapHeader llc; + llc.SetType (protocolNumber); + packet->AddHeader (llc); + + EthernetHeader header (false); + header.SetSource (source); + header.SetDestination (destination); + header.SetLengthType (packet->GetSize ()); + packet->AddHeader (header); + + EthernetTrailer trailer; + trailer.CalcFcs (packet); + packet->AddTrailer (trailer); + + // + // Enqueue and dequeue the packet to hit the tracing hooks. + // + m_queue->Enqueue (packet); + packet = m_queue->Dequeue (); + + struct sockaddr_ll ll; + bzero (&ll, sizeof (ll)); + + ll.sll_family = AF_PACKET; + ll.sll_ifindex = m_sll_ifindex; + ll.sll_protocol = htons(ETH_P_ALL); + + NS_LOG_LOGIC ("calling sendto"); + + int32_t rc; + rc = sendto (m_sock, packet->PeekData (), packet->GetSize (), 0, reinterpret_cast (&ll), sizeof (ll)); + + NS_LOG_LOGIC ("sendto returns " << rc); + + return rc == -1 ? false : true; +} + +void +EmulatedNetDevice::SetDataRate(DataRate bps) +{ + NS_LOG_FUNCTION (this << bps); + NS_ASSERT_MSG (false, "EmulatedNetDevice::SetDataRate(): Unable."); +} + +void +EmulatedNetDevice::SetQueue (Ptr q) +{ + NS_LOG_FUNCTION (this << q); + m_queue = q; +} + +Ptr +EmulatedNetDevice::GetQueue(void) const +{ + NS_LOG_FUNCTION_NOARGS (); + return m_queue; +} + +void +EmulatedNetDevice::NotifyLinkUp (void) +{ + m_linkUp = true; + if (!m_linkChangeCallback.IsNull ()) + { + m_linkChangeCallback (); + } +} + +void +EmulatedNetDevice::SetName(const std::string name) +{ + m_name = name; +} + +std::string +EmulatedNetDevice::GetName(void) const +{ + return m_name; +} + +void +EmulatedNetDevice::SetIfIndex(const uint32_t index) +{ + m_ifIndex = index; +} + +uint32_t +EmulatedNetDevice::GetIfIndex(void) const +{ + return m_ifIndex; +} + +Ptr +EmulatedNetDevice::GetChannel (void) const +{ + NS_ASSERT_MSG (false, "EmulatedNetDevice::GetChannel(): Unable."); + return 0; +} + +void +EmulatedNetDevice::SetAddress (Mac48Address addr) +{ + NS_LOG_FUNCTION (addr); + m_address = addr; +} + +Address +EmulatedNetDevice::GetAddress (void) const +{ + NS_LOG_FUNCTION_NOARGS (); + return m_address; +} + +bool +EmulatedNetDevice::SetMtu (const uint16_t mtu) +{ + NS_ASSERT_MSG (false, "EmulatedNetDevice::SetMtu(): Unable."); + return false; +} + +uint16_t +EmulatedNetDevice::GetMtu (void) const +{ + struct ifreq ifr; + bzero (&ifr, sizeof (ifr)); + strcpy(ifr.ifr_name, m_deviceName.c_str ()); + + int32_t fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP); + + int32_t rc = ioctl(fd, SIOCGIFMTU, &ifr); + NS_ASSERT_MSG (rc != -1, "EmulatedNetDevice::GetMtu(): Can't ioctl SIOCGIFMTU"); + + close (fd); + + return ifr.ifr_mtu; +} + +bool +EmulatedNetDevice::IsLinkUp (void) const +{ + return m_linkUp; +} + +void +EmulatedNetDevice::SetLinkChangeCallback (Callback callback) +{ + m_linkChangeCallback = callback; +} + +bool +EmulatedNetDevice::IsBroadcast (void) const +{ + return true; +} + +Address +EmulatedNetDevice::GetBroadcast (void) const +{ + return Mac48Address ("ff:ff:ff:ff:ff:ff"); +} + +bool +EmulatedNetDevice::IsMulticast (void) const +{ + return false; +} + +Address +EmulatedNetDevice::GetMulticast (void) const +{ + return Mac48Address ("01:00:5e:00:00:00"); +} + +Address +EmulatedNetDevice::MakeMulticastAddress (Ipv4Address multicastGroup) const +{ + return Mac48Address ("01:00:5e:00:00:00"); +} + +bool +EmulatedNetDevice::IsPointToPoint (void) const +{ + return false; +} + +void +EmulatedNetDevice::SetPromiscReceiveCallback (PromiscReceiveCallback cb) +{ + NS_ASSERT_MSG (false, "EmulatedNetDevice::SetPromiscReceiveCallback(): Not implemented"); +} + + bool +EmulatedNetDevice::SupportsSendFrom () const +{ + NS_LOG_FUNCTION_NOARGS (); + return true; +} + + +Ptr +EmulatedNetDevice::GetNode (void) const +{ + return m_node; +} + +void +EmulatedNetDevice::SetNode (Ptr node) +{ + m_node = node; +} + +bool +EmulatedNetDevice::NeedsArp (void) const +{ + return true; +} + +void +EmulatedNetDevice::SetReceiveCallback (NetDevice::ReceiveCallback cb) +{ + m_rxCallback = cb; +} + +} // namespace ns3 diff --git a/src/devices/emulated/emulated-net-device.h b/src/devices/emulated/emulated-net-device.h new file mode 100644 index 000000000..ef5fb66b6 --- /dev/null +++ b/src/devices/emulated/emulated-net-device.h @@ -0,0 +1,321 @@ +/* -*- 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 EMULATED_NET_DEVICE_H +#define EMULATED_NET_DEVICE_H + +#include +#include "ns3/address.h" +#include "ns3/net-device.h" +#include "ns3/node.h" +#include "ns3/callback.h" +#include "ns3/packet.h" +#include "ns3/traced-callback.h" +#include "ns3/event-id.h" +#include "ns3/nstime.h" +#include "ns3/data-rate.h" +#include "ns3/ptr.h" +#include "ns3/mac48-address.h" +#include "ns3/system-thread.h" + +namespace ns3 { + +class Queue; + +/** + * \class EmulatedNetDevice + * \brief A Device for an Emulated Network Link. + */ +class EmulatedNetDevice : public NetDevice +{ +public: + static TypeId GetTypeId (void); + + /** + * Construct a EmulatedNetDevice + * + * This is the constructor for the EmulatedNetDevice. It takes as a + */ + EmulatedNetDevice (); + + /** + * Destroy a EmulatedNetDevice + * + * This is the destructor for the EmulatedNetDevice. + */ + virtual ~EmulatedNetDevice (); + + /** + * Set the Data Rate used for transmission of packets. + * + * @see Attach () + * @param bps the data rate at which this object operates + */ + void SetDataRate (DataRate bps); + + /** + * Set the inteframe gap used to separate packets. The interframe gap + * defines the minimum space required between packets sent by this device. + * + * @param t the interframe gap time + */ + void SetInterframeGap (Time t); + + /** + * Set a start time for the device. + * + * @param tStart the start time + */ + void Start (Time tStart); + + /** + * Set a stop time for the device. + * + * @param tStop the stop time + */ + void Stop (Time tStop); + + /** + * Attach a queue to the EmulatedNetDevice. + * + * The EmulatedNetDevice "owns" a queue that implements a queueing + * method such as DropTail or RED. + * + * @see Queue + * @see DropTailQueue + * @param queue Ptr to the new queue. + */ + void SetQueue (Ptr queue); + + /** + * Receive a packet. + * + * The EmulatedNetDevice receives packets from its socket reader + * and forwards them up the protocol stack. This is the public method + * used by the reader to indicate that a packet has arrived at the device. + * + * @param p Ptr to the received packet. + */ + void Receive (Ptr p); + + /** + * Assign a MAC address to this device. + * + * @see Mac48Address + * @param addr The new address. + */ + void SetAddress (Mac48Address addr); + +// +// Pure virtual methods inherited from NetDevice we must implement. +// + virtual void SetName(const std::string name); + virtual std::string GetName(void) const; + + virtual void SetIfIndex(const uint32_t index); + virtual uint32_t GetIfIndex(void) const; + + virtual Ptr GetChannel (void) const; + virtual Address GetAddress (void) const; + + virtual bool SetMtu (const uint16_t mtu); + virtual uint16_t GetMtu (void) const; + + virtual bool IsLinkUp (void) const; + + virtual void SetLinkChangeCallback (Callback callback); + + virtual bool IsBroadcast (void) const; + virtual Address GetBroadcast (void) const; + + virtual bool IsMulticast (void) const; + virtual Address GetMulticast (void) const; + virtual Address MakeMulticastAddress (Ipv4Address multicastGroup) const; + + virtual bool IsPointToPoint (void) const; + + virtual bool Send(Ptr packet, const Address &dest, uint16_t protocolNumber); + + virtual bool SendFrom(Ptr packet, const Address& source, const Address& dest, uint16_t protocolNumber); + + virtual Ptr GetNode (void) const; + virtual void SetNode (Ptr node); + + virtual bool NeedsArp (void) const; + + virtual void SetReceiveCallback (NetDevice::ReceiveCallback cb); + virtual void SetPromiscReceiveCallback (PromiscReceiveCallback cb); + + virtual bool SupportsSendFrom (void) const; + +private: + + virtual void DoDispose (void); + + /** + * Get a copy of the attached Queue. + * + * This method is provided for any derived class that may need to get + * direct access to the underlying queue. + * + * @returns Ptr to the queue. + */ + Ptr GetQueue(void) const; + + /** + * Spin up the device + */ + void StartDevice (void); + + /** + * Tear down the device + */ + void StopDevice (void); + + /** + * Loop to read and process packets + */ + void ReadThread (void); + + /** + * Method to handle received packets. Synchronized with simulator via ScheduleNow from ReadThread. + */ + void ForwardUp (uint8_t *buf, uint32_t len); + + /** + * Adds the necessary headers and trailers to a packet of data in order to + * respect the protocol implemented by the agent. + */ + void AddHeader(Ptr p, uint16_t protocolNumber); + + /** + * Removes, from a packet of data, all headers and trailers that + * relate to the protocol implemented by the agent + * \return Returns true if the packet should be forwarded up the + * protocol stack. + */ + bool ProcessHeader(Ptr p, uint16_t& param); + + /** + * Start Sending a Packet Down the Wire. + * + * @returns true if success, false on failure + */ + bool TransmitStart (Ptr p); + + void NotifyLinkUp (void); + + /** + * The Queue which this EmulatedNetDevice uses as a packet source. + * Management of this Queue has been delegated to the EmulatedNetDevice + * and it has the responsibility for deletion. + * @see class Queue + * @see class DropTailQueue + */ + Ptr m_queue; + + /** + * The trace source for the packet reception events that the device can + * fire. + * + * @see class CallBackTraceSource + */ + TracedCallback > m_rxTrace; + + /** + * The trace source for the packet drop events that the device can + * fire. + * + * @see class CallBackTraceSource + */ + TracedCallback > m_dropTrace; + + /** + * Time to start spinning up the device + */ + Time m_tStart; + + /** + * Time to start tearing down the device + */ + Time m_tStop; + + EventId m_startEvent; + EventId m_stopEvent; + + int32_t m_sock; + + Ptr m_readThread; + + /** + * The Node to which this device is attached. + */ + Ptr m_node; + + /** + * The MAC address which has been assigned to this device. + */ + Mac48Address m_address; + + /** + * The callback used to notify higher layers that a packet has been received. + */ + NetDevice::ReceiveCallback m_rxCallback; + + /** + * The callback used to notify higher layers that a packet has been received in promiscuous mode. + */ + NetDevice::PromiscReceiveCallback m_promiscRxCallback; + + /** + * The ns-3 interface index (in the sense of net device index) that has been assigned to this network device. + */ + uint32_t m_ifIndex; + + /** + * The Unix interface index that we got from the system and which corresponds to the interface (e.g., "eth1") + * we are using to talk to the network. Valid when m_sock is valid. + */ + int32_t m_sll_ifindex; + + /** + * The human readable name of this device. + */ + std::string m_name; + + /** + * Flag indicating whether or not the link is up. In this case, + * whether or not the device is connected to a channel. + */ + bool m_linkUp; + + /** + * Callback to fire if the link changes state (up or down). + */ + Callback m_linkChangeCallback; + + /** + * The unix/linux name of the underlying device (e.g., eth0) + */ + std::string m_deviceName; +}; + +} // namespace ns3 + +#endif // EMULATED_NET_DEVICE_H + diff --git a/src/devices/emulated/emulated.h b/src/devices/emulated/emulated.h new file mode 100644 index 000000000..8b2601bc3 --- /dev/null +++ b/src/devices/emulated/emulated.h @@ -0,0 +1,10 @@ +/** + * \ingroup devices + * \defgroup Emulated Emulated Net Device Model + * + * \section Emulated Net Device Model + * + * This is a description of the emulated network device model. + * + * It is very detailed and comprehensive and answers all possible questions. + */ diff --git a/src/devices/emulated/waf b/src/devices/emulated/waf new file mode 100755 index 000000000..4283ec141 --- /dev/null +++ b/src/devices/emulated/waf @@ -0,0 +1 @@ +exec "`dirname "$0"`"/../../../waf "$@" diff --git a/src/devices/emulated/wscript b/src/devices/emulated/wscript new file mode 100644 index 000000000..75d32c750 --- /dev/null +++ b/src/devices/emulated/wscript @@ -0,0 +1,14 @@ +## -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*- + + +def build(bld): + module = bld.create_ns3_module('emulated', ['node']) + module.source = [ + 'emulated-net-device.cc', + ] + headers = bld.create_obj('ns3header') + headers.module = 'emulated' + headers.source = [ + 'emulated-net-device.h', + ] + diff --git a/src/devices/emutap/host-tap-net-device.cc b/src/devices/tap/host-tap-net-device.cc similarity index 100% rename from src/devices/emutap/host-tap-net-device.cc rename to src/devices/tap/host-tap-net-device.cc diff --git a/src/devices/emutap/host-tap-net-device.h b/src/devices/tap/host-tap-net-device.h similarity index 100% rename from src/devices/emutap/host-tap-net-device.h rename to src/devices/tap/host-tap-net-device.h diff --git a/src/devices/emutap/tap-channel.cc b/src/devices/tap/tap-channel.cc similarity index 100% rename from src/devices/emutap/tap-channel.cc rename to src/devices/tap/tap-channel.cc diff --git a/src/devices/emutap/tap-channel.h b/src/devices/tap/tap-channel.h similarity index 100% rename from src/devices/emutap/tap-channel.h rename to src/devices/tap/tap-channel.h diff --git a/src/devices/emutap/tap-manager-client.cc b/src/devices/tap/tap-manager-client.cc similarity index 100% rename from src/devices/emutap/tap-manager-client.cc rename to src/devices/tap/tap-manager-client.cc diff --git a/src/devices/emutap/tap-manager-client.h b/src/devices/tap/tap-manager-client.h similarity index 100% rename from src/devices/emutap/tap-manager-client.h rename to src/devices/tap/tap-manager-client.h diff --git a/src/devices/emutap/tap-manager.cc b/src/devices/tap/tap-manager.cc similarity index 88% rename from src/devices/emutap/tap-manager.cc rename to src/devices/tap/tap-manager.cc index a68ec9fc7..271d463ae 100644 --- a/src/devices/emutap/tap-manager.cc +++ b/src/devices/tap/tap-manager.cc @@ -1,3 +1,23 @@ +/* -*- 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 + */ + #include #include #include @@ -21,6 +41,7 @@ std::cout << __FILE__ << ":" << __LINE__ << ": Unrecoverable Error: " << x; \ std::cout << " errno=" << strerror (errno) << std::endl; \ exit (err) + #ifdef ENABLE_LOG #define LOG(x) \ std::cout << x << std::endl; @@ -30,13 +51,13 @@ #define CHECK_ARG(el,var) \ - { \ - char start[] = "--" el "="; \ - if (strncmp (*argv, start, strlen (start)) == 0) \ - { \ - var = *argv + strlen (start); \ - LOG ("--" << el << "=" << var); \ - } \ + { \ + char start[] = "--" el "="; \ + if (strncmp (*argv, start, strlen (start)) == 0) \ + { \ + var = *argv + strlen (start); \ + LOG ("--" << el << "=" << var); \ + } \ } #define ASCII_DOT (0x2e) @@ -47,6 +68,7 @@ #define ASCII_Z (0x7a) #define ASCII_COLON (0x3a) #define ASCII_ZERO (0x30) + static char AsciiToLowCase (char c) { @@ -58,6 +80,7 @@ AsciiToLowCase (char c) return c; } } + static uint32_t AsciiToIpv4 (const char *address) { diff --git a/src/devices/emutap/tap-net-device.cc b/src/devices/tap/tap-net-device.cc similarity index 100% rename from src/devices/emutap/tap-net-device.cc rename to src/devices/tap/tap-net-device.cc diff --git a/src/devices/emutap/tap-net-device.h b/src/devices/tap/tap-net-device.h similarity index 100% rename from src/devices/emutap/tap-net-device.h rename to src/devices/tap/tap-net-device.h diff --git a/src/devices/emutap/wscript b/src/devices/tap/wscript similarity index 85% rename from src/devices/emutap/wscript rename to src/devices/tap/wscript index 11bdb3a3c..bde538c0a 100644 --- a/src/devices/emutap/wscript +++ b/src/devices/tap/wscript @@ -7,7 +7,7 @@ def build(bld): 'tap-manager.cc', ] - module = bld.create_ns3_module('emutap', ['node']) + module = bld.create_ns3_module('tap', ['node']) module.uselib = 'CAP' module.source = [ 'tap-net-device.cc', @@ -16,7 +16,7 @@ def build(bld): 'host-tap-net-device.cc', ] headers = bld.create_obj('ns3header') - headers.module = 'emutap' + headers.module = 'tap' headers.source = [ 'tap-net-device.h', 'host-tap-net-device.h', diff --git a/src/node/net-device.h b/src/node/net-device.h index 35c81f4f0..a3130b2d1 100644 --- a/src/node/net-device.h +++ b/src/node/net-device.h @@ -255,13 +255,23 @@ public: virtual bool NeedsArp (void) const = 0; - /** Packet types */ + /** + * Packet types are used as they are in Linux. GCC name resolution on + * typedef enum {} PacketType is broken for the foreseeable future, so + * if you need to use ns-3 PacketType in a driver that also uses the + * Linux packet types you're hosed unless we define a shadow type, + * which we do here. + */ enum PacketType { - PACKET_HOST = 1, /* To us */ - PACKET_BROADCAST, /* To all */ - PACKET_MULTICAST, /* To group */ - PACKET_OTHERHOST, /* To someone else */ + PACKET_HOST = 1, /**< Packet addressed oo us */ + NS3_PACKET_HOST = PACKET_HOST, + PACKET_BROADCAST, /**< Packet addressed to all */ + NS3_PACKET_BROADCAST = PACKET_BROADCAST, + PACKET_MULTICAST, /**< Packet addressed to multicast group */ + NS3_PACKET_MULTICAST = PACKET_MULTICAST, + PACKET_OTHERHOST, /**< Packet addressed to someone else */ + NS3_PACKET_OTHERHOST = PACKET_OTHERHOST, }; /** diff --git a/src/wscript b/src/wscript index 5cf64f53f..a2d4731e9 100644 --- a/src/wscript +++ b/src/wscript @@ -20,7 +20,8 @@ all_modules = ( 'devices/point-to-point', 'devices/csma', 'devices/bridge', - 'devices/emutap', + 'devices/tap', + 'devices/emulated', 'applications/onoff', 'applications/packet-sink', 'applications/udp-echo', From 8cf8f180193d62eda92973c6b5d18e202741e5de Mon Sep 17 00:00:00 2001 From: Craig Dowell Date: Mon, 27 Oct 2008 23:05:57 -0700 Subject: [PATCH 03/52] add in the helpers --- src/helper/emu-helper.cc | 273 +++++++++++++++++++++++++++++++++++++++ src/helper/emu-helper.h | 181 ++++++++++++++++++++++++++ src/helper/tap-helper.cc | 109 ++++++++++++++++ src/helper/tap-helper.h | 32 +++++ src/helper/wscript | 4 + 5 files changed, 599 insertions(+) create mode 100644 src/helper/emu-helper.cc create mode 100644 src/helper/emu-helper.h create mode 100644 src/helper/tap-helper.cc create mode 100644 src/helper/tap-helper.h diff --git a/src/helper/emu-helper.cc b/src/helper/emu-helper.cc new file mode 100644 index 000000000..4edb8fb9a --- /dev/null +++ b/src/helper/emu-helper.cc @@ -0,0 +1,273 @@ +/* -*- 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 + */ + +#include + +#include "ns3/log.h" +#include "ns3/simulator.h" +#include "ns3/object-factory.h" +#include "ns3/queue.h" +#include "ns3/emulated-net-device.h" +#include "ns3/pcap-writer.h" +#include "ns3/config.h" +#include "ns3/packet.h" + +#include "emu-helper.h" + +NS_LOG_COMPONENT_DEFINE ("EmuHelper"); + +namespace ns3 { + +EmuHelper::EmuHelper () +{ + NS_LOG_FUNCTION_NOARGS (); + m_queueFactory.SetTypeId ("ns3::DropTailQueue"); + m_deviceFactory.SetTypeId ("ns3::EmulatedNetDevice"); +} + + void +EmuHelper::SetQueue ( + std::string type, + std::string n1, const AttributeValue &v1, + std::string n2, const AttributeValue &v2, + std::string n3, const AttributeValue &v3, + std::string n4, const AttributeValue &v4) +{ + NS_LOG_FUNCTION_NOARGS (); + m_queueFactory.SetTypeId (type); + m_queueFactory.Set (n1, v1); + m_queueFactory.Set (n2, v2); + m_queueFactory.Set (n3, v3); + m_queueFactory.Set (n4, v4); +} + + void +EmuHelper::SetAttribute (std::string n1, const AttributeValue &v1) +{ + NS_LOG_FUNCTION_NOARGS (); + m_deviceFactory.Set (n1, v1); +} + + void +EmuHelper::EnablePcap ( + std::string filename, + uint32_t nodeid, + uint32_t deviceid) +{ + NS_LOG_FUNCTION (filename << nodeid << deviceid); + std::ostringstream oss; + oss << filename << "-" << nodeid << "-" << deviceid << ".pcap"; + Ptr pcap = Create (); + pcap->Open (oss.str ()); + pcap->WriteEthernetHeader (); + + oss.str (""); + oss << "/NodeList/" << nodeid << "/DeviceList/" << deviceid << + "/$ns3::EmulatedNetDevice/Rx"; + Config::ConnectWithoutContext (oss.str (), + MakeBoundCallback (&EmuHelper::RxEvent, pcap)); + + oss.str (""); + oss << "/NodeList/" << nodeid << "/DeviceList/" << deviceid << + "/$ns3::EmulatedNetDevice/TxQueue/Enqueue"; + Config::ConnectWithoutContext (oss.str (), + MakeBoundCallback (&EmuHelper::EnqueueEvent, pcap)); +} + + void +EmuHelper::EnablePcap (std::string filename, NetDeviceContainer d) +{ + NS_LOG_FUNCTION (filename << &d); + for (NetDeviceContainer::Iterator i = d.Begin (); i != d.End (); ++i) + { + Ptr dev = *i; + EnablePcap (filename, dev->GetNode ()->GetId (), dev->GetIfIndex ()); + } +} + + void +EmuHelper::EnablePcap (std::string filename, NodeContainer n) +{ + NS_LOG_FUNCTION (filename << &n); + NetDeviceContainer devs; + for (NodeContainer::Iterator i = n.Begin (); i != n.End (); ++i) + { + Ptr node = *i; + for (uint32_t j = 0; j < node->GetNDevices (); ++j) + { + devs.Add (node->GetDevice (j)); + } + } + EnablePcap (filename, devs); +} + + void +EmuHelper::EnablePcapAll (std::string filename) +{ + NS_LOG_FUNCTION (filename); + EnablePcap (filename, NodeContainer::GetGlobal ()); +} + + void +EmuHelper::EnableAscii (std::ostream &os, uint32_t nodeid, uint32_t deviceid) +{ + NS_LOG_FUNCTION (&os << nodeid << deviceid); + Packet::EnablePrinting (); + std::ostringstream oss; + + oss << "/NodeList/" << nodeid << "/DeviceList/" << deviceid << + "/$ns3::EmulatedNetDevice/Rx"; + Config::Connect (oss.str (), + MakeBoundCallback (&EmuHelper::AsciiRxEvent, &os)); + + oss.str (""); + oss << "/NodeList/" << nodeid << "/DeviceList/" << deviceid << + "/$ns3::EmulatedNetDevice/TxQueue/Enqueue"; + Config::Connect (oss.str (), + MakeBoundCallback (&EmuHelper::AsciiEnqueueEvent, &os)); + + oss.str (""); + oss << "/NodeList/" << nodeid << "/DeviceList/" << deviceid << + "/$ns3::EmulatedNetDevice/TxQueue/Dequeue"; + Config::Connect (oss.str (), + MakeBoundCallback (&EmuHelper::AsciiDequeueEvent, &os)); + + oss.str (""); + oss << "/NodeList/" << nodeid << "/DeviceList/" << deviceid << + "/$ns3::EmulatedNetDevice/TxQueue/Drop"; + Config::Connect (oss.str (), + MakeBoundCallback (&EmuHelper::AsciiDropEvent, &os)); +} + + void +EmuHelper::EnableAscii (std::ostream &os, NetDeviceContainer d) +{ + NS_LOG_FUNCTION (&os << &d); + for (NetDeviceContainer::Iterator i = d.Begin (); i != d.End (); ++i) + { + Ptr dev = *i; + EnableAscii (os, dev->GetNode ()->GetId (), dev->GetIfIndex ()); + } +} + +void +EmuHelper::EnableAscii (std::ostream &os, NodeContainer n) +{ + NS_LOG_FUNCTION (&os << &n); + NetDeviceContainer devs; + for (NodeContainer::Iterator i = n.Begin (); i != n.End (); ++i) + { + Ptr node = *i; + for (uint32_t j = 0; j < node->GetNDevices (); ++j) + { + devs.Add (node->GetDevice (j)); + } + } + EnableAscii (os, devs); +} + + void +EmuHelper::EnableAsciiAll (std::ostream &os) +{ + NS_LOG_FUNCTION (&os); + EnableAscii (os, NodeContainer::GetGlobal ()); +} + + NetDeviceContainer +EmuHelper::Install (const NodeContainer &c) +{ + NS_LOG_FUNCTION (&c); + NetDeviceContainer container; + for (NodeContainer::Iterator i = c.Begin (); i != c.End (); i++) + { + Ptr node = *i; + + Ptr device = m_deviceFactory.Create (); + // + // This is a mac address used for ns-3 internal things. It cannot override the real MAC address on the NIC in + // question. + // + device->SetAddress (Mac48Address::Allocate ()); + node->AddDevice (device); + + Ptr queue = m_queueFactory.Create (); + device->SetQueue (queue); + container.Add (device); + } + return container; +} + + void +EmuHelper::EnqueueEvent (Ptr writer, Ptr packet) +{ + NS_LOG_FUNCTION (writer << packet); + writer->WritePacket (packet); +} + + void +EmuHelper::RxEvent (Ptr writer, Ptr packet) +{ + NS_LOG_FUNCTION (writer << packet); + writer->WritePacket (packet); +} + + void +EmuHelper::AsciiEnqueueEvent ( + std::ostream *os, + std::string path, + Ptr packet) +{ + NS_LOG_FUNCTION (&os << path << packet); + *os << "+ " << Simulator::Now ().GetSeconds () << " "; + *os << path << " " << *packet << std::endl; +} + + void +EmuHelper::AsciiDequeueEvent ( + std::ostream *os, + std::string path, + Ptr packet) +{ + NS_LOG_FUNCTION (&os << path << packet); + *os << "- " << Simulator::Now ().GetSeconds () << " "; + *os << path << " " << *packet << std::endl; +} + + void +EmuHelper::AsciiDropEvent ( + std::ostream *os, + std::string path, + Ptr packet) +{ + NS_LOG_FUNCTION (&os << path << packet); + *os << "d " << Simulator::Now ().GetSeconds () << " "; + *os << path << " " << *packet << std::endl; +} + + void +EmuHelper::AsciiRxEvent ( + std::ostream *os, + std::string path, + Ptr packet) +{ + NS_LOG_FUNCTION (&os << path << packet); + *os << "r " << Simulator::Now ().GetSeconds () << " "; + *os << path << " " << *packet << std::endl; +} + +} // namespace ns3 diff --git a/src/helper/emu-helper.h b/src/helper/emu-helper.h new file mode 100644 index 000000000..7d82305f6 --- /dev/null +++ b/src/helper/emu-helper.h @@ -0,0 +1,181 @@ +/* -*- 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 EMU_HELPER_H +#define EMU_HELPER_H + +#include +#include +#include "ns3/attribute.h" +#include "ns3/object-factory.h" +#include "ns3/net-device-container.h" +#include "ns3/node-container.h" +#include "ns3/emulated-net-device.h" + +namespace ns3 { + +class Packet; +class PcapWriter; + +/** + * \brief build a set of EmuNetDevice objects + */ +class EmuHelper +{ +public: + EmuHelper (); + + /** + * \param type the type of queue + * \param n1 the name of the attribute to set on the queue + * \param v1 the value of the attribute to set on the queue + * \param n2 the name of the attribute to set on the queue + * \param v2 the value of the attribute to set on the queue + * \param n3 the name of the attribute to set on the queue + * \param v3 the value of the attribute to set on the queue + * \param n4 the name of the attribute to set on the queue + * \param v4 the value of the attribute to set on the queue + * + * Set the type of queue to create and associated to each + * EmuNetDevice created through EmuHelper::Install. + */ + void SetQueue (std::string type, + std::string n1 = "", const AttributeValue &v1 = EmptyAttributeValue (), + std::string n2 = "", const AttributeValue &v2 = EmptyAttributeValue (), + std::string n3 = "", const AttributeValue &v3 = EmptyAttributeValue (), + std::string n4 = "", const AttributeValue &v4 = EmptyAttributeValue ()); + + /** + * \param n1 the name of the attribute to set + * \param v1 the value of the attribute to set + * + * Set these attributes on each ns3::EmuNetDevice created + * by EmuHelper::Install + */ + void SetAttribute (std::string n1, const AttributeValue &v1); + + /** + * \param filename filename prefix to use for pcap files. + * \param nodeid the id of the node to generate pcap output for. + * \param deviceid the id of the device to generate pcap output for. + * + * Generate a pcap file which contains the link-level data observed + * by the specified deviceid within the specified nodeid. The pcap + * data is stored in the file prefix-nodeid-deviceid.pcap. + * + * This method should be invoked after the network topology has + * been fully constructed. + */ + static void EnablePcap (std::string filename, uint32_t nodeid, + uint32_t deviceid); + + /** + * \param filename filename prefix to use for pcap files. + * \param d container of devices of type ns3::EmuNetDevice + * + * Enable pcap output on each input device which is of the + * ns3::EmuNetDevice type. + */ + static void EnablePcap (std::string filename, NetDeviceContainer d); + + /** + * \param filename filename prefix to use for pcap files. + * \param n container of nodes. + * + * Enable pcap output on each device which is of the + * ns3::EmuNetDevice type and which is located in one of the + * input nodes. + */ + static void EnablePcap (std::string filename, NodeContainer n); + + /** + * \param filename filename prefix to use for pcap files. + * + * Enable pcap output on each device which is of the + * ns3::EmuNetDevice type + */ + static void EnablePcapAll (std::string filename); + + /** + * \param os output stream + * \param nodeid the id of the node to generate ascii output for. + * \param deviceid the id of the device to generate ascii output for. + * + * Enable ascii output on the specified deviceid within the + * specified nodeid if it is of type ns3::EmuNetDevice and dump + * that to the specified stdc++ output stream. + */ + static void EnableAscii (std::ostream &os, uint32_t nodeid, + uint32_t deviceid); + + /** + * \param os output stream + * \param d device container + * + * Enable ascii output on each device which is of the + * ns3::EmuNetDevice type and which is located in the input + * device container and dump that to the specified + * stdc++ output stream. + */ + static void EnableAscii (std::ostream &os, NetDeviceContainer d); + + /** + * \param os output stream + * \param n node container + * + * Enable ascii output on each device which is of the + * ns3::EmuNetDevice type and which is located in one + * of the input node and dump that to the specified + * stdc++ output stream. + */ + static void EnableAscii (std::ostream &os, NodeContainer n); + + /** + * \param os output stream + * + * Enable ascii output on each device which is of the + * ns3::EmuNetDevice type and dump that to the specified + * stdc++ output stream. + */ + static void EnableAsciiAll (std::ostream &os); + + /** + * \param c a set of nodes + */ + NetDeviceContainer Install (const NodeContainer &c); + +private: + static void RxEvent (Ptr writer, Ptr packet); + static void EnqueueEvent (Ptr writer, Ptr packet); + static void AsciiEnqueueEvent (std::ostream *os, std::string path, + Ptr packet); + static void AsciiDequeueEvent (std::ostream *os, std::string path, + Ptr packet); + static void AsciiDropEvent (std::ostream *os, std::string path, + Ptr packet); + static void AsciiRxEvent (std::ostream *os, std::string path, + Ptr packet); + + ObjectFactory m_queueFactory; + ObjectFactory m_deviceFactory; +}; + + +} // namespace ns3 + +#endif /* EMU_HELPER_H */ diff --git a/src/helper/tap-helper.cc b/src/helper/tap-helper.cc new file mode 100644 index 000000000..b3203839b --- /dev/null +++ b/src/helper/tap-helper.cc @@ -0,0 +1,109 @@ +#include "tap-helper.h" +#include "ns3/tap-net-device.h" +#include "ns3/host-tap-net-device.h" +#include "ns3/tap-channel.h" +#include "ns3/pcap-writer.h" +#include "ns3/config.h" +#include "ns3/packet.h" +#include "ns3/callback.h" +#include "ns3/log.h" + +namespace ns3 { + +NS_LOG_COMPONENT_DEFINE ("TapHelper"); + +NetDeviceContainer +TapHelper::Install (NodeContainer hosts, NodeContainer taps) +{ + NS_ASSERT (hosts.GetN () == 1 && taps.GetN () == 1); + NetDeviceContainer devices; + + Ptr channel = CreateObject (); + + // the host. + Ptr host = hosts.Get (0); + Ptr hostDev = CreateObject (); + hostDev->SetChannel (channel); + hostDev->SetAddress (Mac48Address::Allocate ()); + host->AddDevice (hostDev); + devices.Add (hostDev); + + // the tap + Ptr tap = taps.Get (0); + Ptr tapDev = CreateObject (); + tapDev->SetChannel (channel); + tapDev->SetAddress (Mac48Address::Allocate ()); + tap->AddDevice (tapDev); + devices.Add (tapDev); + + return devices; +} + +void +TapHelper::SetupHost (NetDeviceContainer dev, Ipv4Address ad, Ipv4Mask mask, Ipv4Address gateway) +{ + NS_ASSERT (dev.GetN () == 2); + Ptr tap = dev.Get (1)->GetObject (); + tap->SetupHost (ad, mask, gateway); +} + +static void TxEvent (Ptr writer, Ptr packet, Mac48Address from, Mac48Address to) +{ + NS_LOG_FUNCTION (writer << packet << from << to); + writer->WritePacket (packet); +} +static void RxEvent (Ptr writer, Ptr packet, Mac48Address from, Mac48Address to) +{ + NS_LOG_FUNCTION (writer << packet << from << to); + writer->WritePacket (packet); +} + + +void +TapHelper::EnablePcap (std::string filename, uint32_t nodeid, uint32_t deviceid) +{ + std::ostringstream oss; + oss << filename << "-" << nodeid << "-" << deviceid << ".pcap"; + Ptr pcap = Create (); + pcap->Open (oss.str ()); + pcap->WriteEthernetHeader (); + oss.str (""); + oss << "/NodeList/" << nodeid << "/DeviceList/" << deviceid << "/$ns3::TapNetDevice/Rx"; + Config::ConnectWithoutContext (oss.str (), MakeBoundCallback (&RxEvent, pcap)); + oss.str (""); + oss << "/NodeList/" << nodeid << "/DeviceList/" << deviceid << "/$ns3::TapNetDevice/Tx"; + Config::ConnectWithoutContext (oss.str (), MakeBoundCallback (&TxEvent, pcap)); +} + +void +TapHelper::EnablePcap (std::string filename, NetDeviceContainer d) +{ + for (NetDeviceContainer::Iterator i = d.Begin (); i != d.End (); ++i) + { + Ptr dev = *i; + EnablePcap (filename, dev->GetNode ()->GetId (), dev->GetIfIndex ()); + } +} +void +TapHelper::EnablePcap (std::string filename, NodeContainer n) +{ + NetDeviceContainer devs; + for (NodeContainer::Iterator i = n.Begin (); i != n.End (); ++i) + { + Ptr node = *i; + for (uint32_t j = 0; j < node->GetNDevices (); ++j) + { + devs.Add (node->GetDevice (j)); + } + } + EnablePcap (filename, devs); +} + +void +TapHelper::EnablePcapAll (std::string filename) +{ + EnablePcap (filename, NodeContainer::GetGlobal ()); +} + + +} // namespace ns3 diff --git a/src/helper/tap-helper.h b/src/helper/tap-helper.h new file mode 100644 index 000000000..587d41570 --- /dev/null +++ b/src/helper/tap-helper.h @@ -0,0 +1,32 @@ +#ifndef TAP_HELPER_H +#define TAP_HELPER_H + +#include "ns3/ipv4-address.h" +#include "node-container.h" +#include "net-device-container.h" + +namespace ns3 { + +class PcapWriter; +class Packet; + +class TapHelper +{ +public: + /** + * \param host a node which represents the host which our tap is connected to + * \param tap the simulation node which should get a tap connected to the host. + */ + NetDeviceContainer Install (NodeContainer host, NodeContainer tap); + void SetupHost (NetDeviceContainer dev, Ipv4Address ad, Ipv4Mask mask, Ipv4Address gateway); + + static void EnablePcap (std::string filename, uint32_t nodeid, uint32_t deviceid); + static void EnablePcap (std::string filename, NetDeviceContainer d); + static void EnablePcap (std::string filename, NodeContainer n); + static void EnablePcapAll (std::string filename); +}; + + +} // namespace ns3 + +#endif /* TAP_HELPER_H */ diff --git a/src/helper/wscript b/src/helper/wscript index c638e84f0..97ce5844d 100644 --- a/src/helper/wscript +++ b/src/helper/wscript @@ -10,6 +10,8 @@ def build(bld): 'static-multicast-route-helper.cc', 'point-to-point-helper.cc', 'csma-helper.cc', + 'emu-helper.cc', + 'tap-helper.cc', 'mobility-helper.cc', 'ns2-mobility-helper.cc', 'ipv4-address-helper.cc', @@ -33,6 +35,8 @@ def build(bld): 'static-multicast-route-helper.h', 'point-to-point-helper.h', 'csma-helper.h', + 'emu-helper.h', + 'tap-helper.h', 'mobility-helper.h', 'ns2-mobility-helper.h', 'ipv4-address-helper.h', From 0df5a7183ab83f15e5f68dc485a8736909305744 Mon Sep 17 00:00:00 2001 From: Craig Dowell Date: Wed, 29 Oct 2008 11:18:39 -0700 Subject: [PATCH 04/52] apply icmp patch --- bindings/python/ns3_module_core.py | 8 +- bindings/python/ns3_module_internet_stack.py | 268 ++++++++++++ bindings/python/ns3_module_node.py | 78 ++++ src/internet-stack/arp-ipv4-interface.cc | 12 +- src/internet-stack/icmpv4-l4-protocol.cc | 223 ++++++++++ src/internet-stack/icmpv4-l4-protocol.h | 62 +++ src/internet-stack/icmpv4.cc | 387 ++++++++++++++++++ src/internet-stack/icmpv4.h | 137 +++++++ src/internet-stack/internet-stack.cc | 18 +- src/internet-stack/ipv4-end-point-demux.cc | 41 ++ src/internet-stack/ipv4-end-point-demux.h | 5 + src/internet-stack/ipv4-end-point.cc | 21 +- src/internet-stack/ipv4-end-point.h | 10 + src/internet-stack/ipv4-l3-protocol.cc | 201 +++++++-- src/internet-stack/ipv4-l3-protocol.h | 25 +- src/internet-stack/ipv4-l4-protocol.cc | 7 + src/internet-stack/ipv4-l4-protocol.h | 36 +- .../ipv4-raw-socket-factory-impl.cc | 16 + .../ipv4-raw-socket-factory-impl.h | 17 + src/internet-stack/ipv4-raw-socket-impl.cc | 269 ++++++++++++ src/internet-stack/ipv4-raw-socket-impl.h | 65 +++ src/internet-stack/nsc-tcp-l4-protocol.cc | 3 +- src/internet-stack/nsc-tcp-l4-protocol.h | 8 +- src/internet-stack/tcp-l4-protocol.cc | 7 +- src/internet-stack/tcp-l4-protocol.h | 8 +- src/internet-stack/udp-l4-protocol.cc | 34 +- src/internet-stack/udp-l4-protocol.h | 11 +- src/internet-stack/udp-socket-impl.cc | 49 ++- src/internet-stack/udp-socket-impl.h | 10 +- src/internet-stack/wscript | 5 + src/node/ipv4-raw-socket-factory.cc | 35 ++ src/node/ipv4-raw-socket-factory.h | 46 +++ src/node/socket.cc | 53 +++ src/node/socket.h | 29 +- src/node/udp-socket.cc | 6 + src/node/udp-socket.h | 3 +- src/node/wscript | 2 + 37 files changed, 2141 insertions(+), 74 deletions(-) create mode 100644 src/internet-stack/icmpv4-l4-protocol.cc create mode 100644 src/internet-stack/icmpv4-l4-protocol.h create mode 100644 src/internet-stack/icmpv4.cc create mode 100644 src/internet-stack/icmpv4.h create mode 100644 src/internet-stack/ipv4-raw-socket-factory-impl.cc create mode 100644 src/internet-stack/ipv4-raw-socket-factory-impl.h create mode 100644 src/internet-stack/ipv4-raw-socket-impl.cc create mode 100644 src/internet-stack/ipv4-raw-socket-impl.h create mode 100644 src/node/ipv4-raw-socket-factory.cc create mode 100644 src/node/ipv4-raw-socket-factory.h diff --git a/bindings/python/ns3_module_core.py b/bindings/python/ns3_module_core.py index 5f2250b16..92599fd5c 100644 --- a/bindings/python/ns3_module_core.py +++ b/bindings/python/ns3_module_core.py @@ -2025,6 +2025,10 @@ def register_functions(root_module): module.add_function('MakeStringChecker', 'ns3::Ptr< ns3::AttributeChecker const >', []) + ## type-id.h: extern ns3::Ptr ns3::MakeTypeIdChecker() [free function] + module.add_function('MakeTypeIdChecker', + 'ns3::Ptr< ns3::AttributeChecker const >', + []) ## ptr.h: extern ns3::Ptr ns3::Create() [free function] module.add_function('Create', 'ns3::Ptr< ns3::PointerValue >', @@ -2039,10 +2043,6 @@ def register_functions(root_module): module.add_function('LogComponentEnableAll', 'void', [param('ns3::LogLevel', 'level')]) - ## type-id.h: extern ns3::Ptr ns3::MakeTypeIdChecker() [free function] - module.add_function('MakeTypeIdChecker', - 'ns3::Ptr< ns3::AttributeChecker const >', - []) ## object-factory.h: extern ns3::Ptr ns3::MakeObjectFactoryChecker() [free function] module.add_function('MakeObjectFactoryChecker', 'ns3::Ptr< ns3::AttributeChecker const >', diff --git a/bindings/python/ns3_module_internet_stack.py b/bindings/python/ns3_module_internet_stack.py index 439307348..687d37841 100644 --- a/bindings/python/ns3_module_internet_stack.py +++ b/bindings/python/ns3_module_internet_stack.py @@ -3,6 +3,20 @@ from pybindgen import Module, FileCodeSink, param, retval, cppclass def register_types(module): root_module = module.get_root() + ## icmpv4.h: ns3::Icmpv4DestinationUnreachable [class] + module.add_class('Icmpv4DestinationUnreachable', parent=root_module['ns3::Header']) + ## icmpv4.h: ns3::Icmpv4DestinationUnreachable [enumeration] + module.add_enum('', ['NET_UNREACHABLE', 'HOST_UNREACHABLE', 'PROTOCOL_UNREACHABLE', 'PORT_UNREACHABLE', 'FRAG_NEEDED', 'SOURCE_ROUTE_FAILED'], outer_class=root_module['ns3::Icmpv4DestinationUnreachable']) + ## icmpv4.h: ns3::Icmpv4Echo [class] + module.add_class('Icmpv4Echo', parent=root_module['ns3::Header']) + ## icmpv4.h: ns3::Icmpv4Header [class] + module.add_class('Icmpv4Header', parent=root_module['ns3::Header']) + ## icmpv4.h: ns3::Icmpv4Header [enumeration] + module.add_enum('', ['ECHO_REPLY', 'DEST_UNREACH', 'ECHO', 'TIME_EXCEEDED'], outer_class=root_module['ns3::Icmpv4Header']) + ## icmpv4.h: ns3::Icmpv4TimeExceeded [class] + module.add_class('Icmpv4TimeExceeded', parent=root_module['ns3::Header']) + ## icmpv4.h: ns3::Icmpv4TimeExceeded [enumeration] + module.add_enum('', ['TIME_TO_LIVE', 'FRAGMENT_REASSEMBLY'], outer_class=root_module['ns3::Icmpv4TimeExceeded']) ## tcp-header.h: ns3::TcpHeader [class] module.add_class('TcpHeader', parent=root_module['ns3::Header']) ## tcp-header.h: ns3::TcpHeader::Flags_t [enumeration] @@ -57,6 +71,10 @@ def register_types_ns3_olsr(module): def register_methods(root_module): + register_Ns3Icmpv4DestinationUnreachable_methods(root_module, root_module['ns3::Icmpv4DestinationUnreachable']) + register_Ns3Icmpv4Echo_methods(root_module, root_module['ns3::Icmpv4Echo']) + register_Ns3Icmpv4Header_methods(root_module, root_module['ns3::Icmpv4Header']) + register_Ns3Icmpv4TimeExceeded_methods(root_module, root_module['ns3::Icmpv4TimeExceeded']) register_Ns3TcpHeader_methods(root_module, root_module['ns3::TcpHeader']) register_Ns3UdpHeader_methods(root_module, root_module['ns3::UdpHeader']) register_Ns3Ipv4Interface_methods(root_module, root_module['ns3::Ipv4Interface']) @@ -64,6 +82,248 @@ def register_methods(root_module): register_Ns3Ipv4StaticRouting_methods(root_module, root_module['ns3::Ipv4StaticRouting']) return +def register_Ns3Icmpv4DestinationUnreachable_methods(root_module, cls): + ## icmpv4.h: ns3::Icmpv4DestinationUnreachable::Icmpv4DestinationUnreachable(ns3::Icmpv4DestinationUnreachable const & arg0) [copy constructor] + cls.add_constructor([param('ns3::Icmpv4DestinationUnreachable const &', 'arg0')]) + ## icmpv4.h: static ns3::TypeId ns3::Icmpv4DestinationUnreachable::GetTypeId() [member function] + cls.add_method('GetTypeId', + 'ns3::TypeId', + [], + is_static=True) + ## icmpv4.h: ns3::Icmpv4DestinationUnreachable::Icmpv4DestinationUnreachable() [constructor] + cls.add_constructor([]) + ## icmpv4.h: void ns3::Icmpv4DestinationUnreachable::SetNextHopMtu(uint16_t mtu) [member function] + cls.add_method('SetNextHopMtu', + 'void', + [param('uint16_t', 'mtu')]) + ## icmpv4.h: uint16_t ns3::Icmpv4DestinationUnreachable::GetNextHopMtu() const [member function] + cls.add_method('GetNextHopMtu', + 'uint16_t', + [], + is_const=True) + ## icmpv4.h: void ns3::Icmpv4DestinationUnreachable::SetData(ns3::Ptr data) [member function] + cls.add_method('SetData', + 'void', + [param('ns3::Ptr< ns3::Packet const >', 'data')]) + ## icmpv4.h: void ns3::Icmpv4DestinationUnreachable::SetHeader(ns3::Ipv4Header header) [member function] + cls.add_method('SetHeader', + 'void', + [param('ns3::Ipv4Header', 'header')]) + ## icmpv4.h: void ns3::Icmpv4DestinationUnreachable::GetData(uint8_t * payload) const [member function] + cls.add_method('GetData', + 'void', + [param('uint8_t *', 'payload')], + is_const=True) + ## icmpv4.h: ns3::Ipv4Header ns3::Icmpv4DestinationUnreachable::GetHeader() const [member function] + cls.add_method('GetHeader', + 'ns3::Ipv4Header', + [], + is_const=True) + ## icmpv4.h: ns3::TypeId ns3::Icmpv4DestinationUnreachable::GetInstanceTypeId() const [member function] + cls.add_method('GetInstanceTypeId', + 'ns3::TypeId', + [], + is_const=True, visibility='private', is_virtual=True) + ## icmpv4.h: uint32_t ns3::Icmpv4DestinationUnreachable::GetSerializedSize() const [member function] + cls.add_method('GetSerializedSize', + 'uint32_t', + [], + is_const=True, visibility='private', is_virtual=True) + ## icmpv4.h: void ns3::Icmpv4DestinationUnreachable::Serialize(ns3::Buffer::Iterator start) const [member function] + cls.add_method('Serialize', + 'void', + [param('ns3::Buffer::Iterator', 'start')], + is_const=True, visibility='private', is_virtual=True) + ## icmpv4.h: uint32_t ns3::Icmpv4DestinationUnreachable::Deserialize(ns3::Buffer::Iterator start) [member function] + cls.add_method('Deserialize', + 'uint32_t', + [param('ns3::Buffer::Iterator', 'start')], + visibility='private', is_virtual=True) + ## icmpv4.h: void ns3::Icmpv4DestinationUnreachable::Print(std::ostream & os) const [member function] + cls.add_method('Print', + 'void', + [param('std::ostream &', 'os')], + is_const=True, visibility='private', is_virtual=True) + return + +def register_Ns3Icmpv4Echo_methods(root_module, cls): + ## icmpv4.h: ns3::Icmpv4Echo::Icmpv4Echo(ns3::Icmpv4Echo const & arg0) [copy constructor] + cls.add_constructor([param('ns3::Icmpv4Echo const &', 'arg0')]) + ## icmpv4.h: void ns3::Icmpv4Echo::SetIdentifier(uint16_t id) [member function] + cls.add_method('SetIdentifier', + 'void', + [param('uint16_t', 'id')]) + ## icmpv4.h: void ns3::Icmpv4Echo::SetSequenceNumber(uint16_t seq) [member function] + cls.add_method('SetSequenceNumber', + 'void', + [param('uint16_t', 'seq')]) + ## icmpv4.h: void ns3::Icmpv4Echo::SetData(ns3::Ptr data) [member function] + cls.add_method('SetData', + 'void', + [param('ns3::Ptr< ns3::Packet const >', 'data')]) + ## icmpv4.h: uint16_t ns3::Icmpv4Echo::GetIdentifier() const [member function] + cls.add_method('GetIdentifier', + 'uint16_t', + [], + is_const=True) + ## icmpv4.h: uint16_t ns3::Icmpv4Echo::GetSequenceNumber() const [member function] + cls.add_method('GetSequenceNumber', + 'uint16_t', + [], + is_const=True) + ## icmpv4.h: ns3::Ptr ns3::Icmpv4Echo::GetData() const [member function] + cls.add_method('GetData', + 'ns3::Ptr< ns3::Packet const >', + [], + is_const=True) + ## icmpv4.h: static ns3::TypeId ns3::Icmpv4Echo::GetTypeId() [member function] + cls.add_method('GetTypeId', + 'ns3::TypeId', + [], + is_static=True) + ## icmpv4.h: ns3::Icmpv4Echo::Icmpv4Echo() [constructor] + cls.add_constructor([]) + ## icmpv4.h: ns3::TypeId ns3::Icmpv4Echo::GetInstanceTypeId() const [member function] + cls.add_method('GetInstanceTypeId', + 'ns3::TypeId', + [], + is_const=True, is_virtual=True) + ## icmpv4.h: uint32_t ns3::Icmpv4Echo::GetSerializedSize() const [member function] + cls.add_method('GetSerializedSize', + 'uint32_t', + [], + is_const=True, is_virtual=True) + ## icmpv4.h: void ns3::Icmpv4Echo::Serialize(ns3::Buffer::Iterator start) const [member function] + cls.add_method('Serialize', + 'void', + [param('ns3::Buffer::Iterator', 'start')], + is_const=True, is_virtual=True) + ## icmpv4.h: uint32_t ns3::Icmpv4Echo::Deserialize(ns3::Buffer::Iterator start) [member function] + cls.add_method('Deserialize', + 'uint32_t', + [param('ns3::Buffer::Iterator', 'start')], + is_virtual=True) + ## icmpv4.h: void ns3::Icmpv4Echo::Print(std::ostream & os) const [member function] + cls.add_method('Print', + 'void', + [param('std::ostream &', 'os')], + is_const=True, is_virtual=True) + return + +def register_Ns3Icmpv4Header_methods(root_module, cls): + ## icmpv4.h: ns3::Icmpv4Header::Icmpv4Header(ns3::Icmpv4Header const & arg0) [copy constructor] + cls.add_constructor([param('ns3::Icmpv4Header const &', 'arg0')]) + ## icmpv4.h: void ns3::Icmpv4Header::EnableChecksum() [member function] + cls.add_method('EnableChecksum', + 'void', + []) + ## icmpv4.h: void ns3::Icmpv4Header::SetType(uint8_t type) [member function] + cls.add_method('SetType', + 'void', + [param('uint8_t', 'type')]) + ## icmpv4.h: void ns3::Icmpv4Header::SetCode(uint8_t code) [member function] + cls.add_method('SetCode', + 'void', + [param('uint8_t', 'code')]) + ## icmpv4.h: uint8_t ns3::Icmpv4Header::GetType() const [member function] + cls.add_method('GetType', + 'uint8_t', + [], + is_const=True) + ## icmpv4.h: uint8_t ns3::Icmpv4Header::GetCode() const [member function] + cls.add_method('GetCode', + 'uint8_t', + [], + is_const=True) + ## icmpv4.h: static ns3::TypeId ns3::Icmpv4Header::GetTypeId() [member function] + cls.add_method('GetTypeId', + 'ns3::TypeId', + [], + is_static=True) + ## icmpv4.h: ns3::Icmpv4Header::Icmpv4Header() [constructor] + cls.add_constructor([]) + ## icmpv4.h: ns3::TypeId ns3::Icmpv4Header::GetInstanceTypeId() const [member function] + cls.add_method('GetInstanceTypeId', + 'ns3::TypeId', + [], + is_const=True, is_virtual=True) + ## icmpv4.h: uint32_t ns3::Icmpv4Header::GetSerializedSize() const [member function] + cls.add_method('GetSerializedSize', + 'uint32_t', + [], + is_const=True, is_virtual=True) + ## icmpv4.h: void ns3::Icmpv4Header::Serialize(ns3::Buffer::Iterator start) const [member function] + cls.add_method('Serialize', + 'void', + [param('ns3::Buffer::Iterator', 'start')], + is_const=True, is_virtual=True) + ## icmpv4.h: uint32_t ns3::Icmpv4Header::Deserialize(ns3::Buffer::Iterator start) [member function] + cls.add_method('Deserialize', + 'uint32_t', + [param('ns3::Buffer::Iterator', 'start')], + is_virtual=True) + ## icmpv4.h: void ns3::Icmpv4Header::Print(std::ostream & os) const [member function] + cls.add_method('Print', + 'void', + [param('std::ostream &', 'os')], + is_const=True, is_virtual=True) + return + +def register_Ns3Icmpv4TimeExceeded_methods(root_module, cls): + ## icmpv4.h: ns3::Icmpv4TimeExceeded::Icmpv4TimeExceeded(ns3::Icmpv4TimeExceeded const & arg0) [copy constructor] + cls.add_constructor([param('ns3::Icmpv4TimeExceeded const &', 'arg0')]) + ## icmpv4.h: void ns3::Icmpv4TimeExceeded::SetData(ns3::Ptr data) [member function] + cls.add_method('SetData', + 'void', + [param('ns3::Ptr< ns3::Packet const >', 'data')]) + ## icmpv4.h: void ns3::Icmpv4TimeExceeded::SetHeader(ns3::Ipv4Header header) [member function] + cls.add_method('SetHeader', + 'void', + [param('ns3::Ipv4Header', 'header')]) + ## icmpv4.h: void ns3::Icmpv4TimeExceeded::GetData(uint8_t * payload) const [member function] + cls.add_method('GetData', + 'void', + [param('uint8_t *', 'payload')], + is_const=True) + ## icmpv4.h: ns3::Ipv4Header ns3::Icmpv4TimeExceeded::GetHeader() const [member function] + cls.add_method('GetHeader', + 'ns3::Ipv4Header', + [], + is_const=True) + ## icmpv4.h: static ns3::TypeId ns3::Icmpv4TimeExceeded::GetTypeId() [member function] + cls.add_method('GetTypeId', + 'ns3::TypeId', + [], + is_static=True) + ## icmpv4.h: ns3::Icmpv4TimeExceeded::Icmpv4TimeExceeded() [constructor] + cls.add_constructor([]) + ## icmpv4.h: ns3::TypeId ns3::Icmpv4TimeExceeded::GetInstanceTypeId() const [member function] + cls.add_method('GetInstanceTypeId', + 'ns3::TypeId', + [], + is_const=True, is_virtual=True) + ## icmpv4.h: uint32_t ns3::Icmpv4TimeExceeded::GetSerializedSize() const [member function] + cls.add_method('GetSerializedSize', + 'uint32_t', + [], + is_const=True, is_virtual=True) + ## icmpv4.h: void ns3::Icmpv4TimeExceeded::Serialize(ns3::Buffer::Iterator start) const [member function] + cls.add_method('Serialize', + 'void', + [param('ns3::Buffer::Iterator', 'start')], + is_const=True, is_virtual=True) + ## icmpv4.h: uint32_t ns3::Icmpv4TimeExceeded::Deserialize(ns3::Buffer::Iterator start) [member function] + cls.add_method('Deserialize', + 'uint32_t', + [param('ns3::Buffer::Iterator', 'start')], + is_virtual=True) + ## icmpv4.h: void ns3::Icmpv4TimeExceeded::Print(std::ostream & os) const [member function] + cls.add_method('Print', + 'void', + [param('std::ostream &', 'os')], + is_const=True, is_virtual=True) + return + def register_Ns3TcpHeader_methods(root_module, cls): ## tcp-header.h: ns3::TcpHeader::TcpHeader(ns3::TcpHeader const & arg0) [copy constructor] cls.add_constructor([param('ns3::TcpHeader const &', 'arg0')]) @@ -354,6 +614,14 @@ def register_Ns3Ipv4L3Protocol_methods(root_module, cls): cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) + ## ipv4-l3-protocol.h: ns3::Ptr ns3::Ipv4L3Protocol::CreateRawSocket() [member function] + cls.add_method('CreateRawSocket', + 'ns3::Ptr< ns3::Socket >', + []) + ## ipv4-l3-protocol.h: void ns3::Ipv4L3Protocol::DeleteRawSocket(ns3::Ptr socket) [member function] + cls.add_method('DeleteRawSocket', + 'void', + [param('ns3::Ptr< ns3::Socket >', 'socket')]) ## ipv4-l3-protocol.h: void ns3::Ipv4L3Protocol::Insert(ns3::Ptr protocol) [member function] cls.add_method('Insert', 'void', diff --git a/bindings/python/ns3_module_node.py b/bindings/python/ns3_module_node.py index 805e8747e..61c624b2d 100644 --- a/bindings/python/ns3_module_node.py +++ b/bindings/python/ns3_module_node.py @@ -67,6 +67,8 @@ def register_types(module): module.add_class('SocketFactory', parent=root_module['ns3::Object']) ## socket.h: ns3::SocketIpTtlTag [class] module.add_class('SocketIpTtlTag', parent=root_module['ns3::Tag']) + ## socket.h: ns3::SocketSetDontFragmentTag [class] + module.add_class('SocketSetDontFragmentTag', parent=root_module['ns3::Tag']) ## tcp-socket.h: ns3::TcpSocket [class] module.add_class('TcpSocket', parent=root_module['ns3::Socket']) ## tcp-socket-factory.h: ns3::TcpSocketFactory [class] @@ -91,6 +93,8 @@ def register_types(module): module.add_class('EthernetTrailer', parent=root_module['ns3::Trailer']) ## ipv4.h: ns3::Ipv4 [class] module.add_class('Ipv4', parent=root_module['ns3::Object']) + ## ipv4-raw-socket-factory.h: ns3::Ipv4RawSocketFactory [class] + module.add_class('Ipv4RawSocketFactory', parent=root_module['ns3::SocketFactory']) ## ipv4.h: ns3::Ipv4RoutingProtocol [class] module.add_class('Ipv4RoutingProtocol', parent=root_module['ns3::Object']) ## net-device.h: ns3::NetDevice [class] @@ -172,6 +176,7 @@ def register_methods(root_module): register_Ns3SocketAddressTag_methods(root_module, root_module['ns3::SocketAddressTag']) register_Ns3SocketFactory_methods(root_module, root_module['ns3::SocketFactory']) register_Ns3SocketIpTtlTag_methods(root_module, root_module['ns3::SocketIpTtlTag']) + register_Ns3SocketSetDontFragmentTag_methods(root_module, root_module['ns3::SocketSetDontFragmentTag']) register_Ns3TcpSocket_methods(root_module, root_module['ns3::TcpSocket']) register_Ns3TcpSocketFactory_methods(root_module, root_module['ns3::TcpSocketFactory']) register_Ns3UdpSocket_methods(root_module, root_module['ns3::UdpSocket']) @@ -184,6 +189,7 @@ def register_methods(root_module): register_Ns3EthernetHeader_methods(root_module, root_module['ns3::EthernetHeader']) register_Ns3EthernetTrailer_methods(root_module, root_module['ns3::EthernetTrailer']) register_Ns3Ipv4_methods(root_module, root_module['ns3::Ipv4']) + register_Ns3Ipv4RawSocketFactory_methods(root_module, root_module['ns3::Ipv4RawSocketFactory']) register_Ns3Ipv4RoutingProtocol_methods(root_module, root_module['ns3::Ipv4RoutingProtocol']) register_Ns3NetDevice_methods(root_module, root_module['ns3::NetDevice']) register_Ns3Node_methods(root_module, root_module['ns3::Node']) @@ -1507,6 +1513,56 @@ def register_Ns3SocketIpTtlTag_methods(root_module, cls): is_const=True, is_virtual=True) return +def register_Ns3SocketSetDontFragmentTag_methods(root_module, cls): + ## socket.h: ns3::SocketSetDontFragmentTag::SocketSetDontFragmentTag(ns3::SocketSetDontFragmentTag const & arg0) [copy constructor] + cls.add_constructor([param('ns3::SocketSetDontFragmentTag const &', 'arg0')]) + ## socket.h: ns3::SocketSetDontFragmentTag::SocketSetDontFragmentTag() [constructor] + cls.add_constructor([]) + ## socket.h: void ns3::SocketSetDontFragmentTag::Enable() [member function] + cls.add_method('Enable', + 'void', + []) + ## socket.h: void ns3::SocketSetDontFragmentTag::Disable() [member function] + cls.add_method('Disable', + 'void', + []) + ## socket.h: bool ns3::SocketSetDontFragmentTag::IsEnabled() const [member function] + cls.add_method('IsEnabled', + 'bool', + [], + is_const=True) + ## socket.h: static ns3::TypeId ns3::SocketSetDontFragmentTag::GetTypeId() [member function] + cls.add_method('GetTypeId', + 'ns3::TypeId', + [], + is_static=True) + ## socket.h: ns3::TypeId ns3::SocketSetDontFragmentTag::GetInstanceTypeId() const [member function] + cls.add_method('GetInstanceTypeId', + 'ns3::TypeId', + [], + is_const=True, is_virtual=True) + ## socket.h: uint32_t ns3::SocketSetDontFragmentTag::GetSerializedSize() const [member function] + cls.add_method('GetSerializedSize', + 'uint32_t', + [], + is_const=True, is_virtual=True) + ## socket.h: void ns3::SocketSetDontFragmentTag::Serialize(ns3::TagBuffer i) const [member function] + cls.add_method('Serialize', + 'void', + [param('ns3::TagBuffer', 'i')], + is_const=True, is_virtual=True) + ## socket.h: void ns3::SocketSetDontFragmentTag::Deserialize(ns3::TagBuffer i) [member function] + cls.add_method('Deserialize', + 'void', + [param('ns3::TagBuffer', 'i')], + is_virtual=True) + ## socket.h: void ns3::SocketSetDontFragmentTag::Print(std::ostream & os) const [member function] + cls.add_method('Print', + 'void', + [param('std::ostream &', 'os')], + is_const=True, is_virtual=True) + return + def register_Ns3TcpSocket_methods(root_module, cls): ## tcp-socket.h: ns3::TcpSocket::TcpSocket(ns3::TcpSocket const & arg0) [copy constructor] cls.add_constructor([param('ns3::TcpSocket const &', 'arg0')]) @@ -1661,6 +1717,16 @@ def register_Ns3UdpSocket_methods(root_module, cls): 'uint32_t', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) + ## udp-socket.h: void ns3::UdpSocket::SetMtuDiscover(bool discover) [member function] + cls.add_method('SetMtuDiscover', + 'void', + [param('bool', 'discover')], + is_pure_virtual=True, visibility='private', is_virtual=True) + ## udp-socket.h: bool ns3::UdpSocket::GetMtuDiscover() const [member function] + cls.add_method('GetMtuDiscover', + 'bool', + [], + is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) return def register_Ns3UdpSocketFactory_methods(root_module, cls): @@ -2167,6 +2233,18 @@ def register_Ns3Ipv4_methods(root_module, cls): is_virtual=True) return +def register_Ns3Ipv4RawSocketFactory_methods(root_module, cls): + ## ipv4-raw-socket-factory.h: ns3::Ipv4RawSocketFactory::Ipv4RawSocketFactory(ns3::Ipv4RawSocketFactory const & arg0) [copy constructor] + cls.add_constructor([param('ns3::Ipv4RawSocketFactory const &', 'arg0')]) + ## ipv4-raw-socket-factory.h: ns3::Ipv4RawSocketFactory::Ipv4RawSocketFactory() [constructor] + cls.add_constructor([]) + ## ipv4-raw-socket-factory.h: static ns3::TypeId ns3::Ipv4RawSocketFactory::GetTypeId() [member function] + cls.add_method('GetTypeId', + 'ns3::TypeId', + [], + is_static=True) + return + def register_Ns3Ipv4RoutingProtocol_methods(root_module, cls): ## ipv4.h: ns3::Ipv4RoutingProtocol::IF_INDEX_ANY [variable] cls.add_static_attribute('IF_INDEX_ANY', 'uint32_t const', is_const=True) diff --git a/src/internet-stack/arp-ipv4-interface.cc b/src/internet-stack/arp-ipv4-interface.cc index 457079bd4..90fc2a019 100644 --- a/src/internet-stack/arp-ipv4-interface.cc +++ b/src/internet-stack/arp-ipv4-interface.cc @@ -65,7 +65,6 @@ void ArpIpv4Interface::DoDispose (void) { NS_LOG_FUNCTION (this); - m_node = 0; m_device = 0; m_cache = 0; Ipv4Interface::DoDispose (); @@ -107,6 +106,17 @@ ArpIpv4Interface::SendTo (Ptr p, Ipv4Address dest) NS_LOG_FUNCTION (this << p << dest); NS_ASSERT (GetDevice () != 0); + if (dest == GetAddress ()) + { + Ptr ipv4 = m_node->GetObject (); + + ipv4->Receive (0, p, Ipv4L3Protocol::PROT_NUMBER, + GetDevice ()->GetBroadcast (), + GetDevice ()->GetBroadcast (), + NetDevice::PACKET_HOST // note: linux uses PACKET_LOOPBACK here + ); + return; + } if (m_device->NeedsArp ()) { NS_LOG_LOGIC ("Needs ARP"); diff --git a/src/internet-stack/icmpv4-l4-protocol.cc b/src/internet-stack/icmpv4-l4-protocol.cc new file mode 100644 index 000000000..751024695 --- /dev/null +++ b/src/internet-stack/icmpv4-l4-protocol.cc @@ -0,0 +1,223 @@ +#include "icmpv4-l4-protocol.h" +#include "ipv4-interface.h" +#include "ipv4-l3-protocol.h" +#include "ns3/assert.h" +#include "ns3/log.h" +#include "ns3/node.h" +#include "ns3/packet.h" +#include "ns3/boolean.h" + +namespace ns3 { + +NS_LOG_COMPONENT_DEFINE ("Icmpv4L4Protocol"); + +NS_OBJECT_ENSURE_REGISTERED (Icmpv4L4Protocol); + + // see rfc 792 +enum { + ICMP_PROTOCOL = 1 +}; + +TypeId +Icmpv4L4Protocol::GetTypeId (void) +{ + static TypeId tid = TypeId ("ns3::Icmpv4L4Protocol") + .SetParent () + .AddConstructor () + .AddAttribute ("CalcChecksum", + "Control whether the icmp header checksum is calculated and stored in outgoing icmpv4 headers", + BooleanValue (false), + MakeBooleanAccessor (&Icmpv4L4Protocol::m_calcChecksum), + MakeBooleanChecker ()) + ; + return tid; +} + +Icmpv4L4Protocol::Icmpv4L4Protocol () + : m_node (0) +{} +Icmpv4L4Protocol::~Icmpv4L4Protocol () +{ + NS_ASSERT (m_node == 0); +} + +void +Icmpv4L4Protocol::SetNode (Ptr node) +{ + m_node = node; +} + +uint16_t +Icmpv4L4Protocol::GetStaticProtocolNumber (void) +{ + return ICMP_PROTOCOL; +} + +int +Icmpv4L4Protocol::GetProtocolNumber (void) const +{ + return ICMP_PROTOCOL; +} +void +Icmpv4L4Protocol::SendMessage (Ptr packet, Ipv4Address dest, uint8_t type, uint8_t code) +{ + Ptr ipv4 = m_node->GetObject (); + uint32_t i; + if (!ipv4->GetIfIndexForDestination (dest, i)) + { + NS_LOG_WARN ("drop icmp message"); + return; + } + Ipv4Address source = ipv4->GetAddress (i); + SendMessage (packet, source, dest, type, code); +} + +void +Icmpv4L4Protocol::SendMessage (Ptr packet, Ipv4Address source, Ipv4Address dest, uint8_t type, uint8_t code) +{ + Ptr ipv4 = m_node->GetObject (); + Icmpv4Header icmp; + icmp.SetType (type); + icmp.SetCode (code); + if (m_calcChecksum) + { + icmp.EnableChecksum (); + } + packet->AddHeader (icmp); + ipv4->Send (packet, source, dest, ICMP_PROTOCOL); +} +void +Icmpv4L4Protocol::SendDestUnreachFragNeeded (Ipv4Header header, + Ptr orgData, + uint16_t nextHopMtu) +{ + NS_LOG_FUNCTION (this << header << *orgData << nextHopMtu); + SendDestUnreach (header, orgData, Icmpv4DestinationUnreachable::FRAG_NEEDED, nextHopMtu); +} +void +Icmpv4L4Protocol::SendDestUnreachPort (Ipv4Header header, + Ptr orgData) +{ + NS_LOG_FUNCTION (this << header << *orgData); + SendDestUnreach (header, orgData, Icmpv4DestinationUnreachable::PORT_UNREACHABLE, 0); +} +void +Icmpv4L4Protocol::SendDestUnreach (Ipv4Header header, Ptr orgData, + uint8_t code, uint16_t nextHopMtu) +{ + NS_LOG_FUNCTION (this << header << *orgData << (uint32_t) code << nextHopMtu); + Ptr p = Create (); + Icmpv4DestinationUnreachable unreach; + unreach.SetNextHopMtu (nextHopMtu); + unreach.SetHeader (header); + unreach.SetData (orgData); + p->AddHeader (unreach); + SendMessage (p, header.GetSource (), Icmpv4Header::DEST_UNREACH, code); +} + +void +Icmpv4L4Protocol::SendTimeExceededTtl (Ipv4Header header, Ptr orgData) +{ + NS_LOG_FUNCTION (this << header << *orgData); + Ptr p = Create (); + Icmpv4TimeExceeded time; + time.SetHeader (header); + time.SetData (orgData); + p->AddHeader (time); + SendMessage (p, header.GetSource (), Icmpv4Header::TIME_EXCEEDED, Icmpv4TimeExceeded::TIME_TO_LIVE); +} + +void +Icmpv4L4Protocol::HandleEcho (Ptr p, + Icmpv4Header header, + Ipv4Address source, + Ipv4Address destination) +{ + NS_LOG_FUNCTION (this << p << header << source << destination); + + Ptr reply = Create (); + Icmpv4Echo echo; + p->RemoveHeader (echo); + reply->AddHeader (echo); + SendMessage (reply, destination, source, Icmpv4Header::ECHO_REPLY, 0); +} +void +Icmpv4L4Protocol::Forward (Ipv4Address source, Icmpv4Header icmp, + uint32_t info, Ipv4Header ipHeader, + const uint8_t payload[8]) +{ + Ptr ipv4 = m_node->GetObject (); + Ptr l4 = ipv4->GetProtocol (ipHeader.GetProtocol ()); + if (l4 != 0) + { + l4->ReceiveIcmp (source, ipHeader.GetTtl (), icmp.GetType (), icmp.GetCode (), + info, ipHeader.GetSource (), ipHeader.GetDestination (), payload); + } +} +void +Icmpv4L4Protocol::HandleDestUnreach (Ptr p, + Icmpv4Header icmp, + Ipv4Address source, + Ipv4Address destination) +{ + NS_LOG_FUNCTION (this << p << icmp << source << destination); + + Icmpv4DestinationUnreachable unreach; + p->PeekHeader (unreach); + uint8_t payload[8]; + unreach.GetData (payload); + Ipv4Header ipHeader = unreach.GetHeader (); + Forward (source, icmp, unreach.GetNextHopMtu (), ipHeader, payload); +} +void +Icmpv4L4Protocol::HandleTimeExceeded (Ptr p, + Icmpv4Header icmp, + Ipv4Address source, + Ipv4Address destination) +{ + NS_LOG_FUNCTION (this << p << icmp << source << destination); + + Icmpv4TimeExceeded time; + p->PeekHeader (time); + uint8_t payload[8]; + time.GetData (payload); + Ipv4Header ipHeader = time.GetHeader (); + // info field is zero for TimeExceeded on linux + Forward (source, icmp, 0, ipHeader, payload); +} + +enum Ipv4L4Protocol::RxStatus +Icmpv4L4Protocol::Receive(Ptr p, + Ipv4Address const &source, + Ipv4Address const &destination, + Ptr incomingInterface) +{ + NS_LOG_FUNCTION (this << p << source << destination << incomingInterface); + + Icmpv4Header icmp; + p->RemoveHeader (icmp); + switch (icmp.GetType ()) { + case Icmpv4Header::ECHO: + HandleEcho (p, icmp, source, destination); + break; + case Icmpv4Header::DEST_UNREACH: + HandleDestUnreach (p, icmp, source, destination); + break; + case Icmpv4Header::TIME_EXCEEDED: + HandleTimeExceeded (p, icmp, source, destination); + break; + default: + NS_LOG_DEBUG (icmp << " " << *p); + break; + } + return Ipv4L4Protocol::RX_OK; +} +void +Icmpv4L4Protocol::DoDispose (void) +{ + NS_LOG_FUNCTION (this); + m_node = 0; + Ipv4L4Protocol::DoDispose (); +} + +} // namespace ns3 diff --git a/src/internet-stack/icmpv4-l4-protocol.h b/src/internet-stack/icmpv4-l4-protocol.h new file mode 100644 index 000000000..71310f84d --- /dev/null +++ b/src/internet-stack/icmpv4-l4-protocol.h @@ -0,0 +1,62 @@ +#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 Icmpv4L4Protocol : public Ipv4L4Protocol +{ +public: + static TypeId GetTypeId (void); + Icmpv4L4Protocol (); + virtual ~Icmpv4L4Protocol (); + + void SetNode (Ptr node); + + static uint16_t GetStaticProtocolNumber (void); + virtual int GetProtocolNumber (void) const; + virtual enum Ipv4L4Protocol::RxStatus Receive(Ptr p, + const Ipv4Address &source, + const Ipv4Address &destination, + Ptr incomingInterface); + + void SendDestUnreachFragNeeded (Ipv4Header header, Ptr orgData, uint16_t nextHopMtu); + void SendTimeExceededTtl (Ipv4Header header, Ptr orgData); + void SendDestUnreachPort (Ipv4Header header, Ptr orgData); + +private: + void HandleEcho (Ptr p, + Icmpv4Header header, + Ipv4Address source, + Ipv4Address destination); + void HandleDestUnreach (Ptr p, + Icmpv4Header header, + Ipv4Address source, + Ipv4Address destination); + void HandleTimeExceeded (Ptr p, + Icmpv4Header icmp, + Ipv4Address source, + Ipv4Address destination); + void SendDestUnreach (Ipv4Header header, Ptr orgData, + uint8_t code, uint16_t nextHopMtu); + void SendMessage (Ptr packet, Ipv4Address dest, uint8_t type, uint8_t code); + void SendMessage (Ptr packet, Ipv4Address source, Ipv4Address dest, uint8_t type, uint8_t code); + void Forward (Ipv4Address source, Icmpv4Header icmp, + uint32_t info, Ipv4Header ipHeader, + const uint8_t payload[8]); + + virtual void DoDispose (void); + + Ptr m_node; + bool m_calcChecksum; +}; + +} // namespace ns3 + +#endif /* ICMPV4_L4_PROTOCOL_H */ diff --git a/src/internet-stack/icmpv4.cc b/src/internet-stack/icmpv4.cc new file mode 100644 index 000000000..b0b2cfec9 --- /dev/null +++ b/src/internet-stack/icmpv4.cc @@ -0,0 +1,387 @@ +#include "icmpv4.h" +#include "ns3/packet.h" + +namespace ns3 { + +/******************************************************** + * Icmpv4Header + ********************************************************/ + +TypeId +Icmpv4Header::GetTypeId (void) +{ + static TypeId tid = TypeId ("ns3::Icmpv4Header") + .SetParent
() + .AddConstructor () + ; + return tid; +} +Icmpv4Header::Icmpv4Header () + : m_type (0), + m_code (0), + m_calcChecksum (false) +{} +Icmpv4Header::~Icmpv4Header () +{} +void +Icmpv4Header::EnableChecksum (void) +{ + m_calcChecksum = true; +} +TypeId +Icmpv4Header::GetInstanceTypeId (void) const +{ + return GetTypeId (); +} +uint32_t +Icmpv4Header::GetSerializedSize (void) const +{ + return 4; +} +void +Icmpv4Header::Serialize (Buffer::Iterator start) const +{ + Buffer::Iterator i = start; + i.WriteU8 (m_type); + i.WriteU8 (m_code); + i.WriteHtonU16 (0); + if (m_calcChecksum) + { + i = start; + uint16_t checksum = i.CalculateIpChecksum (i.GetSize ()); + i = start; + i.Next (2); + i.WriteU16 (checksum); + } + +} +uint32_t +Icmpv4Header::Deserialize (Buffer::Iterator start) +{ + m_type = start.ReadU8 (); + m_code = start.ReadU8 (); + uint16_t checksum; + checksum = start.ReadNtohU16 (); + return 4; +} +void +Icmpv4Header::Print (std::ostream &os) const +{ + os << "type=" << (uint32_t)m_type << ", code=" << (uint32_t)m_code; +} + +void +Icmpv4Header::SetType (uint8_t type) +{ + m_type = type; +} +void +Icmpv4Header::SetCode (uint8_t code) +{ + m_code = code; +} +uint8_t +Icmpv4Header::GetType (void) const +{ + return m_type; +} +uint8_t +Icmpv4Header::GetCode (void) const +{ + return m_code; +} + +/******************************************************** + * Icmpv4Echo + ********************************************************/ + +void +Icmpv4Echo::SetIdentifier (uint16_t id) +{ + m_identifier = id; +} +void +Icmpv4Echo::SetSequenceNumber (uint16_t seq) +{ + m_sequence = seq; +} +void +Icmpv4Echo::SetData (Ptr data) +{ + m_data = data->Copy (); +} +uint16_t +Icmpv4Echo::GetIdentifier (void) const +{ + return m_identifier; +} +uint16_t +Icmpv4Echo::GetSequenceNumber (void) const +{ + return m_sequence; +} +Ptr +Icmpv4Echo::GetData (void) const +{ + return m_data->Copy (); +} + + +TypeId +Icmpv4Echo::GetTypeId (void) +{ + static TypeId tid = TypeId ("ns3::Icmpv4Echo") + .SetParent
() + .AddConstructor () + ; + return tid; +} +Icmpv4Echo::Icmpv4Echo () + : m_identifier (0), + m_sequence (0), + m_data (0) +{} +Icmpv4Echo::~Icmpv4Echo () +{} +TypeId +Icmpv4Echo::GetInstanceTypeId (void) const +{ + return GetTypeId (); +} +uint32_t +Icmpv4Echo::GetSerializedSize (void) const +{ + return 4 + m_data->GetSize (); +} +void +Icmpv4Echo::Serialize (Buffer::Iterator start) const +{ + start.WriteHtonU16 (m_identifier); + start.WriteHtonU16 (m_sequence); + start.Write (m_data->PeekData (), m_data->GetSize ()); +} +uint32_t +Icmpv4Echo::Deserialize (Buffer::Iterator start) +{ + m_identifier = start.ReadNtohU16 (); + m_sequence = start.ReadNtohU16 (); + NS_ASSERT (start.GetSize () >= 4); + uint32_t size = start.GetSize () - 4; + uint8_t *buffer = new uint8_t[size] (); + start.Read (buffer, size); + m_data = Create (buffer, size); + delete[] buffer; + return start.GetSize (); +} +void +Icmpv4Echo::Print (std::ostream &os) const +{ + os << "identifier=" << m_identifier << ", sequence=" << m_sequence; +} + + +/******************************************************** + * Icmpv4DestinationUnreachable + ********************************************************/ + +TypeId +Icmpv4DestinationUnreachable::GetTypeId (void) +{ + static TypeId tid = TypeId ("ns3::Icmpv4DestinationUnreachable") + .SetParent
() + .AddConstructor () + ; + return tid; +} +Icmpv4DestinationUnreachable::Icmpv4DestinationUnreachable () +{ + // make sure that thing is initialized to get initialized bytes + // when the ip payload's size is smaller than 8 bytes. + for (uint8_t j = 0; j < 8; j++) + { + m_data[j] = 0; + } +} + +void +Icmpv4DestinationUnreachable::SetNextHopMtu (uint16_t mtu) +{ + m_nextHopMtu = mtu; +} +uint16_t +Icmpv4DestinationUnreachable::GetNextHopMtu (void) const +{ + return m_nextHopMtu; +} + +void +Icmpv4DestinationUnreachable::SetData (Ptr data) +{ + data->CopyData (m_data, 8); +} +void +Icmpv4DestinationUnreachable::SetHeader (Ipv4Header header) +{ + m_header = header; +} +void +Icmpv4DestinationUnreachable::GetData (uint8_t payload[8]) const +{ + memcpy (payload, m_data, 8); +} +Ipv4Header +Icmpv4DestinationUnreachable::GetHeader (void) const +{ + return m_header; +} + + +Icmpv4DestinationUnreachable::~Icmpv4DestinationUnreachable () +{} +TypeId +Icmpv4DestinationUnreachable::GetInstanceTypeId (void) const +{ + return GetTypeId (); +} +uint32_t +Icmpv4DestinationUnreachable::GetSerializedSize (void) const +{ + return 4 + m_header.GetSerializedSize () + 8; +} +void +Icmpv4DestinationUnreachable::Serialize (Buffer::Iterator start) const +{ + start.WriteU16 (0); + start.WriteHtonU16 (m_nextHopMtu); + uint32_t size = m_header.GetSerializedSize (); + m_header.Serialize (start); + start.Next (size); + start.Write (m_data, 8); +} + +uint32_t +Icmpv4DestinationUnreachable::Deserialize (Buffer::Iterator start) +{ + Buffer::Iterator i = start; + i.Next (2); + m_nextHopMtu = i.ReadNtohU16 (); + uint32_t read = m_header.Deserialize (i); + i.Next (read); + for (uint8_t j = 0; j < 8; j++) + { + m_data[j] = i.ReadU8 (); + } + return i.GetDistanceFrom (start); +} +void +Icmpv4DestinationUnreachable::Print (std::ostream &os) const +{ + m_header.Print (os); + os << " org data="; + for (uint8_t i = 0; i < 8; i++) + { + os << (uint32_t) m_data[i]; + if (i != 8) + { + os << " "; + } + } +} + +/******************************************************** + * Icmpv4TimeExceeded + ********************************************************/ + +TypeId +Icmpv4TimeExceeded::GetTypeId (void) +{ + static TypeId tid = TypeId ("ns3::Icmpv4TimeExceeded") + .SetParent
() + .AddConstructor () + ; + return tid; +} +Icmpv4TimeExceeded::Icmpv4TimeExceeded () +{ + // make sure that thing is initialized to get initialized bytes + // when the ip payload's size is smaller than 8 bytes. + for (uint8_t j = 0; j < 8; j++) + { + m_data[j] = 0; + } +} + + +void +Icmpv4TimeExceeded::SetData (Ptr data) +{ + data->CopyData (m_data, 8); +} +void +Icmpv4TimeExceeded::SetHeader (Ipv4Header header) +{ + m_header = header; +} +void +Icmpv4TimeExceeded::GetData (uint8_t payload[8]) const +{ + memcpy (payload, m_data, 8); +} +Ipv4Header +Icmpv4TimeExceeded::GetHeader (void) const +{ + return m_header; +} + + +Icmpv4TimeExceeded::~Icmpv4TimeExceeded () +{} +TypeId +Icmpv4TimeExceeded::GetInstanceTypeId (void) const +{ + return GetTypeId (); +} +uint32_t +Icmpv4TimeExceeded::GetSerializedSize (void) const +{ + return 4 + m_header.GetSerializedSize () + 8; +} +void +Icmpv4TimeExceeded::Serialize (Buffer::Iterator start) const +{ + start.WriteU32 (0); + uint32_t size = m_header.GetSerializedSize (); + m_header.Serialize (start); + start.Next (size); + start.Write (m_data, 8); +} + +uint32_t +Icmpv4TimeExceeded::Deserialize (Buffer::Iterator start) +{ + Buffer::Iterator i = start; + i.Next (4); + uint32_t read = m_header.Deserialize (i); + i.Next (read); + for (uint8_t j = 0; j < 8; j++) + { + m_data[j] = i.ReadU8 (); + } + return i.GetDistanceFrom (start); +} +void +Icmpv4TimeExceeded::Print (std::ostream &os) const +{ + m_header.Print (os); + os << " org data="; + for (uint8_t i = 0; i < 8; i++) + { + os << (uint32_t) m_data[i]; + if (i != 8) + { + os << " "; + } + } +} + +} // namespace ns3 diff --git a/src/internet-stack/icmpv4.h b/src/internet-stack/icmpv4.h new file mode 100644 index 000000000..f8d224e51 --- /dev/null +++ b/src/internet-stack/icmpv4.h @@ -0,0 +1,137 @@ +#ifndef ICMPV4_H +#define ICMPV4_H + +#include "ns3/header.h" +#include "ns3/ptr.h" +#include "ns3/ipv4-header.h" +#include + +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 data); + uint16_t GetIdentifier (void) const; + uint16_t GetSequenceNumber (void) const; + Ptr GetData (void) 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; + Ptr m_data; +}; + +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 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 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 */ diff --git a/src/internet-stack/internet-stack.cc b/src/internet-stack/internet-stack.cc index 83520a3c0..280f7bd6f 100644 --- a/src/internet-stack/internet-stack.cc +++ b/src/internet-stack/internet-stack.cc @@ -30,6 +30,8 @@ #include "udp-socket-factory-impl.h" #include "tcp-socket-factory-impl.h" #include "ipv4-impl.h" +#include "ipv4-raw-socket-factory-impl.h" +#include "icmpv4-l4-protocol.h" #ifdef NETWORK_SIMULATION_CRADLE #include "nsc-tcp-socket-factory-impl.h" #include "nsc-tcp-l4-protocol.h" @@ -57,13 +59,26 @@ AddUdpStack(Ptr node) node->AggregateObject (udpFactory); } +static void +AddIcmpStack (Ptr node) +{ + Ptr ipv4 = node->GetObject (); + Ptr icmp = CreateObject (); + icmp->SetNode (node); + ipv4->Insert (icmp); + Ptr rawFactory = CreateObject (); + node->AggregateObject (rawFactory); +} + static void AddTcpStack(Ptr node) { Ptr ipv4 = node->GetObject (); Ptr tcp = CreateObject (); tcp->SetNode (node); + ipv4->Insert (tcp); + Ptr tcpFactory = CreateObject (); tcpFactory->SetTcp (tcp); node->AggregateObject (tcpFactory); @@ -85,6 +100,7 @@ AddInternetStack (Ptr node) { AddArpStack (node); AddIpv4Stack (node); + AddIcmpStack (node); AddUdpStack (node); AddTcpStack (node); } @@ -109,7 +125,7 @@ AddNscInternetStack (Ptr node, const std::string &soname) { AddArpStack (node); AddIpv4Stack (node); - + AddIcmpStack (node); AddUdpStack (node); AddNscStack (node, soname); } diff --git a/src/internet-stack/ipv4-end-point-demux.cc b/src/internet-stack/ipv4-end-point-demux.cc index 54ed3fbbe..2c2ab838e 100644 --- a/src/internet-stack/ipv4-end-point-demux.cc +++ b/src/internet-stack/ipv4-end-point-demux.cc @@ -287,6 +287,47 @@ Ipv4EndPointDemux::Lookup (Ipv4Address daddr, uint16_t dport, return retval1; // might be empty if no matches } +Ipv4EndPoint * +Ipv4EndPointDemux::SimpleLookup (Ipv4Address daddr, + uint16_t dport, + Ipv4Address saddr, + uint16_t sport) +{ + // this code is a copy/paste version of an old BSD ip stack lookup + // function. + uint32_t genericity = 3; + Ipv4EndPoint *generic = 0; + for (EndPointsI i = m_endPoints.begin (); i != m_endPoints.end (); i++) + { + if ((*i)->GetLocalPort () != dport) + { + continue; + } + if ((*i)->GetLocalAddress () == daddr && + (*i)->GetPeerPort () == sport && + (*i)->GetPeerAddress () == saddr) + { + /* this is an exact match. */ + return *i; + } + uint32_t tmp = 0; + if ((*i)->GetLocalAddress () == Ipv4Address::GetAny ()) + { + tmp ++; + } + if ((*i)->GetPeerAddress () == Ipv4Address::GetAny ()) + { + tmp ++; + } + if (tmp < genericity) + { + generic = (*i); + genericity = tmp; + } + } + return generic; +} + uint16_t Ipv4EndPointDemux::AllocateEphemeralPort (void) { diff --git a/src/internet-stack/ipv4-end-point-demux.h b/src/internet-stack/ipv4-end-point-demux.h index 58a417264..02a225799 100644 --- a/src/internet-stack/ipv4-end-point-demux.h +++ b/src/internet-stack/ipv4-end-point-demux.h @@ -57,6 +57,11 @@ public: uint16_t sport, Ptr incomingInterface); + Ipv4EndPoint *SimpleLookup (Ipv4Address daddr, + uint16_t dport, + Ipv4Address saddr, + uint16_t sport); + Ipv4EndPoint *Allocate (void); Ipv4EndPoint *Allocate (Ipv4Address address); Ipv4EndPoint *Allocate (uint16_t port); diff --git a/src/internet-stack/ipv4-end-point.cc b/src/internet-stack/ipv4-end-point.cc index 18b7d9930..7b0649fc3 100644 --- a/src/internet-stack/ipv4-end-point.cc +++ b/src/internet-stack/ipv4-end-point.cc @@ -20,6 +20,9 @@ #include "ipv4-end-point.h" #include "ns3/packet.h" +#include "ns3/log.h" + +NS_LOG_COMPONENT_DEFINE ("Ipv4EndPoint"); namespace ns3 { @@ -76,6 +79,11 @@ Ipv4EndPoint::SetRxCallback (Callback, Ipv4Address, uint16_t> c { m_rxCallback = callback; } +void +Ipv4EndPoint::SetIcmpCallback (Callback callback) +{ + m_icmpCallback = callback; +} void Ipv4EndPoint::SetDestroyCallback (Callback callback) @@ -92,6 +100,17 @@ Ipv4EndPoint::ForwardUp (Ptr p, Ipv4Address saddr, uint16_t sport) } } - +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 ()) + { + m_icmpCallback (icmpSource,icmpTtl,icmpType,icmpCode,icmpInfo); + } +} }; // namespace ns3 diff --git a/src/internet-stack/ipv4-end-point.h b/src/internet-stack/ipv4-end-point.h index 99666f73f..f3ef159ad 100644 --- a/src/internet-stack/ipv4-end-point.h +++ b/src/internet-stack/ipv4-end-point.h @@ -54,10 +54,19 @@ public: void SetPeer (Ipv4Address address, uint16_t port); + // Called from socket implementations to get notified about important events. void SetRxCallback (Callback, Ipv4Address, uint16_t> callback); + void SetIcmpCallback (Callback callback); void SetDestroyCallback (Callback callback); + // Called from an L4Protocol implementation to notify an endpoint of a + // packet reception. void ForwardUp (Ptr p, Ipv4Address saddr, uint16_t sport); + // Called from an L4Protocol implementation to notify an endpoint of + // an icmp message reception. + void ForwardIcmp (Ipv4Address icmpSource, uint8_t icmpTtl, + uint8_t icmpType, uint8_t icmpCode, + uint32_t icmpInfo); private: Ipv4Address m_localAddr; @@ -65,6 +74,7 @@ private: Ipv4Address m_peerAddr; uint16_t m_peerPort; Callback, Ipv4Address, uint16_t> m_rxCallback; + Callback m_icmpCallback; Callback m_destroyCallback; }; diff --git a/src/internet-stack/ipv4-l3-protocol.cc b/src/internet-stack/ipv4-l3-protocol.cc index d4defa7b9..b35269128 100644 --- a/src/internet-stack/ipv4-l3-protocol.cc +++ b/src/internet-stack/ipv4-l3-protocol.cc @@ -35,9 +35,11 @@ #include "ipv4-l3-protocol.h" #include "ipv4-l4-protocol.h" +#include "icmpv4-l4-protocol.h" #include "ipv4-interface.h" #include "ipv4-loopback-interface.h" #include "arp-ipv4-interface.h" +#include "ipv4-raw-socket-impl.h" NS_LOG_COMPONENT_DEFINE ("Ipv4L3Protocol"); @@ -120,6 +122,30 @@ Ipv4L3Protocol::SetNode (Ptr node) SetupLoopback (); } +Ptr +Ipv4L3Protocol::CreateRawSocket (void) +{ + NS_LOG_FUNCTION (this); + Ptr socket = CreateObject (); + socket->SetNode (m_node); + m_sockets.push_back (socket); + return socket; +} +void +Ipv4L3Protocol::DeleteRawSocket (Ptr 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; +} + void Ipv4L3Protocol::DoDispose (void) { @@ -514,6 +540,12 @@ Ipv4L3Protocol::Receive( Ptr device, Ptr p, uint16_t pr return; } + for (SocketList::iterator i = m_sockets.begin (); i != m_sockets.end (); ++i) + { + Ptr socket = *i; + socket->ForwardUp (packet, ipHeader, device); + } + if (Forwarding (index, packet, ipHeader, device)) { return; @@ -522,6 +554,25 @@ Ipv4L3Protocol::Receive( Ptr device, Ptr p, uint16_t pr ForwardUp (packet, ipHeader, ipv4Interface); } +Ptr +Ipv4L3Protocol::GetIcmp (void) const +{ + Ptr prot = GetProtocol (Icmpv4L4Protocol::GetStaticProtocolNumber ()); + if (prot != 0) + { + return prot->GetObject (); + } + else + { + return 0; + } +} + +bool +Ipv4L3Protocol::IsUnicast (Ipv4Address ad, Ipv4Mask interfaceMask) const +{ + return !ad.IsMulticast () && !ad.IsSubnetDirectedBroadcast (interfaceMask); +} void Ipv4L3Protocol::Send (Ptr packet, @@ -542,16 +593,29 @@ Ipv4L3Protocol::Send (Ptr packet, ipHeader.SetDestination (destination); ipHeader.SetProtocol (protocol); ipHeader.SetPayloadSize (packet->GetSize ()); - ipHeader.SetTtl (m_defaultTtl); - ipHeader.SetMayFragment (); ipHeader.SetIdentification (m_identification); m_identification ++; + SocketSetDontFragmentTag dfTag; + bool found = packet->FindFirstMatchingTag (dfTag); + if (found) + { + if (dfTag.IsEnabled ()) + { + ipHeader.SetDontFragment (); + } + else + { + ipHeader.SetMayFragment (); + } + } + + // Set TTL to 1 if it is a broadcast packet of any type. Otherwise, // possibly override the default TTL if the packet is tagged SocketIpTtlTag tag; - bool found = packet->FindFirstMatchingTag (tag); + found = packet->FindFirstMatchingTag (tag); if (destination.IsBroadcast ()) { @@ -564,6 +628,7 @@ Ipv4L3Protocol::Send (Ptr packet, } else { + ipHeader.SetTtl (m_defaultTtl); uint32_t ifaceIndex = 0; for (Ipv4InterfaceList::iterator ifaceIter = m_interfaces.begin (); ifaceIter != m_interfaces.end (); ifaceIter++, ifaceIndex++) @@ -585,10 +650,28 @@ Ipv4L3Protocol::Send (Ptr packet, Ptr outInterface = *ifaceIter; Ptr packetCopy = packet->Copy (); - NS_ASSERT (packetCopy->GetSize () <= outInterface->GetMtu ()); packetCopy->AddHeader (ipHeader); - m_txTrace (packetCopy, ifaceIndex); - outInterface->Send (packetCopy, destination); + if (packetCopy->GetSize () > outInterface->GetMtu () && + ipHeader.IsDontFragment () && + IsUnicast (ipHeader.GetDestination (), outInterface->GetNetworkMask ())) + { + Ptr icmp = GetIcmp (); + NS_ASSERT (icmp != 0); + icmp->SendDestUnreachFragNeeded (ipHeader, packet, outInterface->GetMtu ()); + m_dropTrace (packetCopy); + } + else if (packet->GetSize () > outInterface->GetMtu () && + !ipHeader.IsDontFragment ()) + { + NS_LOG_LOGIC ("Too big: need fragmentation but no frag support."); + m_dropTrace (packet); + } + else + { + NS_ASSERT (packetCopy->GetSize () <= outInterface->GetMtu ()); + m_txTrace (packetCopy, ifaceIndex); + outInterface->Send (packetCopy, destination); + } } } else @@ -625,17 +708,38 @@ Ipv4L3Protocol::SendRealOut (bool found, NS_LOG_LOGIC ("Send via interface " << route.GetInterface ()); Ptr outInterface = GetInterface (route.GetInterface ()); - NS_ASSERT (packet->GetSize () <= outInterface->GetMtu ()); - m_txTrace (packet, route.GetInterface ()); - if (route.IsGateway ()) + if (packet->GetSize () > outInterface->GetMtu () && + ipHeader.IsDontFragment () && + IsUnicast (ipHeader.GetDestination (), outInterface->GetNetworkMask ())) { - NS_LOG_LOGIC ("Send to gateway " << route.GetGateway ()); - outInterface->Send (packet, route.GetGateway ()); - } - else + NS_LOG_LOGIC ("Too big: need fragmentation but not allowed"); + Ptr icmp = GetIcmp (); + NS_ASSERT (icmp != 0); + Ptr copyNoHeader = packet->Copy (); + Ipv4Header tmp; + copyNoHeader->RemoveHeader (tmp); + icmp->SendDestUnreachFragNeeded (ipHeader, copyNoHeader, outInterface->GetMtu ()); + m_dropTrace (packet); + } + else if (packet->GetSize () > outInterface->GetMtu () && + !ipHeader.IsDontFragment ()) { - NS_LOG_LOGIC ("Send to destination " << ipHeader.GetDestination ()); - outInterface->Send (packet, ipHeader.GetDestination ()); + NS_LOG_LOGIC ("Too big: need fragmentation but no frag support."); + m_dropTrace (packet); + } + else + { + m_txTrace (packet, route.GetInterface ()); + if (route.IsGateway ()) + { + NS_LOG_LOGIC ("Send to gateway " << route.GetGateway ()); + outInterface->Send (packet, route.GetGateway ()); + } + else + { + NS_LOG_LOGIC ("Send to destination " << ipHeader.GetDestination ()); + outInterface->Send (packet, ipHeader.GetDestination ()); + } } } @@ -685,17 +789,6 @@ Ipv4L3Protocol::Forwarding ( NS_LOG_LOGIC ("For me (Ipv4Addr any address)"); return false; } - - if (ipHeader.GetTtl () == 1) - { - // Should send ttl expired here - // XXX - NS_LOG_LOGIC ("Not for me (TTL expired). Drop"); - m_dropTrace (packet); - return true; - } - ipHeader.SetTtl (ipHeader.GetTtl () - 1); - // // If this is a to a multicast address and this node is a member of the // indicated group we need to return false so the multicast is forwarded up. @@ -710,18 +803,39 @@ Ipv4L3Protocol::Forwarding ( // We forward with a packet copy, since forwarding may change // the packet, affecting our local delivery NS_LOG_LOGIC ("Forwarding (multicast)."); - Lookup (ifIndex, ipHeader, packet->Copy (), - MakeCallback (&Ipv4L3Protocol::SendRealOut, this)); + DoForward (ifIndex, packet->Copy (), ipHeader); return false; } - } - NS_LOG_LOGIC ("Not for me, forwarding."); - Lookup (ifIndex, ipHeader, packet, - MakeCallback (&Ipv4L3Protocol::SendRealOut, this)); - + } + + DoForward (ifIndex, packet, ipHeader); return true; } +void +Ipv4L3Protocol::DoForward (uint32_t ifIndex, + Ptr packet, + Ipv4Header ipHeader) +{ + NS_LOG_FUNCTION (this << ifIndex << packet << ipHeader); + + ipHeader.SetTtl (ipHeader.GetTtl () - 1); + if (ipHeader.GetTtl () == 0) + { + if (IsUnicast (ipHeader.GetDestination (), GetInterface (ifIndex)->GetNetworkMask ())) + { + Ptr icmp = GetIcmp (); + icmp->SendTimeExceededTtl (ipHeader, packet); + } + m_dropTrace (packet); + return; + } + NS_LOG_LOGIC ("Not for me, forwarding."); + Lookup (ifIndex, ipHeader, packet, + MakeCallback (&Ipv4L3Protocol::SendRealOut, this)); +} + + void Ipv4L3Protocol::ForwardUp (Ptr p, Ipv4Header const&ip, Ptr incomingInterface) @@ -729,7 +843,26 @@ Ipv4L3Protocol::ForwardUp (Ptr p, Ipv4Header const&ip, NS_LOG_FUNCTION (this << p << &ip); Ptr protocol = GetProtocol (ip.GetProtocol ()); - protocol->Receive (p, ip.GetSource (), ip.GetDestination (), incomingInterface); + if (protocol != 0) + { + // we need to make a copy in the unlikely event we hit the + // RX_ENDPOINT_UNREACH codepath + Ptr copy = p->Copy (); + enum Ipv4L4Protocol::RxStatus status = + protocol->Receive (p, ip.GetSource (), ip.GetDestination (), incomingInterface); + switch (status) { + case Ipv4L4Protocol::RX_OK: + // fall through + case Ipv4L4Protocol::RX_CSUM_FAILED: + break; + case Ipv4L4Protocol::RX_ENDPOINT_UNREACH: + if (IsUnicast (ip.GetDestination (), incomingInterface->GetNetworkMask ())) + { + GetIcmp ()->SendDestUnreachPort (ip, copy); + } + break; + } + } } void diff --git a/src/internet-stack/ipv4-l3-protocol.h b/src/internet-stack/ipv4-l3-protocol.h index c5d59297d..6218eb8d4 100644 --- a/src/internet-stack/ipv4-l3-protocol.h +++ b/src/internet-stack/ipv4-l3-protocol.h @@ -40,7 +40,11 @@ class Ipv4Address; class Ipv4Header; class Ipv4Route; class Node; +class Socket; +class Ipv4RawSocketImpl; class Ipv4L4Protocol; +class Ipv4L4Protocol; +class Icmpv4L4Protocol; /** @@ -60,6 +64,9 @@ public: void SetNode (Ptr node); + Ptr CreateRawSocket (void); + void DeleteRawSocket (Ptr socket); + /** * \param protocol a template for the protocol to add to this L4 Demux. * \returns the L4Protocol effectively added. @@ -201,6 +208,8 @@ protected: virtual void DoDispose (void); private: + Ipv4L3Protocol(const Ipv4L3Protocol &); + Ipv4L3Protocol &operator = (const Ipv4L3Protocol &); void Lookup (uint32_t ifIndex, Ipv4Header const &ipHeader, Ptr packet, @@ -217,15 +226,19 @@ private: void ForwardUp (Ptr p, Ipv4Header const&ip, Ptr incomingInterface); uint32_t AddIpv4Interface (Ptr interface); void SetupLoopback (void); - Ipv4L3Protocol(const Ipv4L3Protocol &); - Ipv4L3Protocol &operator = (const Ipv4L3Protocol &); + Ptr GetIcmp (void) const; + bool IsUnicast (Ipv4Address ad, Ipv4Mask interfaceMask) const; + void DoForward (uint32_t ifIndex, + Ptr packet, + Ipv4Header ipHeader); + typedef std::list > Ipv4InterfaceList; - typedef std::list > - Ipv4MulticastGroupList; + typedef std::list > Ipv4MulticastGroupList; typedef std::list< std::pair< int, Ptr > > Ipv4RoutingProtocolList; - + typedef std::list > SocketList; typedef std::list > L4List_t; + L4List_t m_protocols; Ipv4InterfaceList m_interfaces; uint32_t m_nInterfaces; @@ -241,6 +254,8 @@ private: Ptr m_staticRouting; Ipv4MulticastGroupList m_multicastGroups; + + SocketList m_sockets; }; } // Namespace ns3 diff --git a/src/internet-stack/ipv4-l4-protocol.cc b/src/internet-stack/ipv4-l4-protocol.cc index 83e56b0f9..628f451fe 100644 --- a/src/internet-stack/ipv4-l4-protocol.cc +++ b/src/internet-stack/ipv4-l4-protocol.cc @@ -44,4 +44,11 @@ Ipv4L4Protocol::GetTypeId (void) Ipv4L4Protocol::~Ipv4L4Protocol () {} +void +Ipv4L4Protocol::ReceiveIcmp (Ipv4Address icmpSource, uint8_t icmpTtl, + uint8_t icmpType, uint8_t icmpCode, uint32_t icmpInfo, + Ipv4Address payloadSource,Ipv4Address payloadDestination, + const uint8_t payload[8]) +{} + }//namespace ns3 diff --git a/src/internet-stack/ipv4-l4-protocol.h b/src/internet-stack/ipv4-l4-protocol.h index bb348bcd9..ffdc6042e 100644 --- a/src/internet-stack/ipv4-l4-protocol.h +++ b/src/internet-stack/ipv4-l4-protocol.h @@ -25,12 +25,13 @@ #define IPV4_L4_PROTOCOL_H #include "ns3/object.h" -#include "ipv4-interface.h" +#include "ns3/ipv4-header.h" namespace ns3 { class Packet; class Ipv4Address; +class Ipv4Interface; /** * \brief L4 Protocol abstract base class @@ -41,6 +42,12 @@ class Ipv4Address; class Ipv4L4Protocol : public Object { public: + enum RxStatus { + RX_OK, + RX_CSUM_FAILED, + RX_ENDPOINT_UNREACH + }; + static TypeId GetTypeId (void); virtual ~Ipv4L4Protocol (); @@ -59,10 +66,29 @@ public: * Called from lower-level layers to send the packet up * in the stack. */ - virtual void Receive(Ptr p, - Ipv4Address const &source, - Ipv4Address const &destination, - Ptr incomingInterface) = 0; + virtual enum RxStatus Receive(Ptr p, + Ipv4Address const &source, + Ipv4Address const &destination, + Ptr incomingInterface) = 0; + + /** + * \param icmpSouce the source address of the icmp message + * \param icmpTtl the ttl of the icmp message + * \param icmpType the 'type' field of the icmp message + * \param icmpCode the 'code' field of the icmp message + * \param icmpInfo extra information dependent on the icmp message + * generated by Icmpv4L4Protocol + * \param payloadSource the source address of the packet which triggered + * the icmp message + * \param payloadDestination the destination address of the packet which + * triggered the icmp message. + * \param payload the first 8 bytes of the udp header of the packet + * which triggered the icmp message. + */ + virtual void ReceiveIcmp (Ipv4Address icmpSource, uint8_t icmpTtl, + uint8_t icmpType, uint8_t icmpCode, uint32_t icmpInfo, + Ipv4Address payloadSource, Ipv4Address payloadDestination, + const uint8_t payload[8]); }; } // Namespace ns3 diff --git a/src/internet-stack/ipv4-raw-socket-factory-impl.cc b/src/internet-stack/ipv4-raw-socket-factory-impl.cc new file mode 100644 index 000000000..244ce7ee1 --- /dev/null +++ b/src/internet-stack/ipv4-raw-socket-factory-impl.cc @@ -0,0 +1,16 @@ +#include "ipv4-raw-socket-factory-impl.h" +#include "ipv4-l3-protocol.h" +#include "ns3/socket.h" + +namespace ns3 { + + +Ptr +Ipv4RawSocketFactoryImpl::CreateSocket (void) +{ + Ptr ipv4 = GetObject (); + Ptr socket = ipv4->CreateRawSocket (); + return socket; +} + +} // namespace ns3 diff --git a/src/internet-stack/ipv4-raw-socket-factory-impl.h b/src/internet-stack/ipv4-raw-socket-factory-impl.h new file mode 100644 index 000000000..89f526258 --- /dev/null +++ b/src/internet-stack/ipv4-raw-socket-factory-impl.h @@ -0,0 +1,17 @@ +#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 CreateSocket (void); +}; + + +} // namespace ns3 + +#endif /* IPV4_RAW_SOCKET_FACTORY_IMPL_H */ diff --git a/src/internet-stack/ipv4-raw-socket-impl.cc b/src/internet-stack/ipv4-raw-socket-impl.cc new file mode 100644 index 000000000..e99f2addd --- /dev/null +++ b/src/internet-stack/ipv4-raw-socket-impl.cc @@ -0,0 +1,269 @@ +#include "ipv4-raw-socket-impl.h" +#include "ipv4-l3-protocol.h" +#include "icmpv4.h" +#include "ns3/inet-socket-address.h" +#include "ns3/node.h" +#include "ns3/packet.h" +#include "ns3/uinteger.h" +#include "ns3/log.h" + +NS_LOG_COMPONENT_DEFINE ("Ipv4RawSocketImpl"); + +namespace ns3 { + +NS_OBJECT_ENSURE_REGISTERED (Ipv4RawSocketImpl); + +TypeId +Ipv4RawSocketImpl::GetTypeId (void) +{ + static TypeId tid = TypeId ("ns3::Ipv4RawSocketImpl") + .SetParent () + .AddAttribute ("Protocol", "Protocol number to match.", + UintegerValue (0), + MakeUintegerAccessor (&Ipv4RawSocketImpl::m_protocol), + MakeUintegerChecker ()) + .AddAttribute ("IcmpFilter", + "Any icmp header whose type field matches a bit in this filter is dropped.", + UintegerValue (0), + MakeUintegerAccessor (&Ipv4RawSocketImpl::m_icmpFilter), + MakeUintegerChecker ()) + ; + return tid; +} + +Ipv4RawSocketImpl::Ipv4RawSocketImpl () +{ + NS_LOG_FUNCTION (this); + m_err = Socket::ERROR_NOTERROR; + m_node = 0; + m_src = Ipv4Address::GetAny (); + m_dst = Ipv4Address::GetAny (); + m_protocol = 0; + m_shutdownSend = false; + m_shutdownRecv = false; +} + +void +Ipv4RawSocketImpl::SetNode (Ptr node) +{ + m_node = node; +} + +void +Ipv4RawSocketImpl::DoDispose (void) +{ + NS_LOG_FUNCTION (this); + m_node = 0; + Socket::DoDispose (); +} + +enum Socket::SocketErrno +Ipv4RawSocketImpl::GetErrno (void) const +{ + NS_LOG_FUNCTION (this); + return m_err; +} +Ptr +Ipv4RawSocketImpl::GetNode (void) const +{ + NS_LOG_FUNCTION (this); + return m_node; +} +int +Ipv4RawSocketImpl::Bind (const Address &address) +{ + NS_LOG_FUNCTION (this << address); + if (!InetSocketAddress::IsMatchingType (address)) + { + m_err = Socket::ERROR_INVAL; + return -1; + } + InetSocketAddress ad = InetSocketAddress::ConvertFrom (address); + m_src = ad.GetIpv4 (); + return 0; +} +int +Ipv4RawSocketImpl::Bind (void) +{ + NS_LOG_FUNCTION (this); + m_src = Ipv4Address::GetAny (); + return 0; +} +int +Ipv4RawSocketImpl::GetSockName (Address &address) const +{ + address = InetSocketAddress (m_src, 0); + return 0; +} +int +Ipv4RawSocketImpl::Close (void) +{ + NS_LOG_FUNCTION (this); + Ptr ipv4 = m_node->GetObject (); + if (ipv4 != 0) + { + ipv4->DeleteRawSocket (this); + } + return 0; +} +int +Ipv4RawSocketImpl::ShutdownSend (void) +{ + NS_LOG_FUNCTION (this); + m_shutdownSend = true; + return 0; +} +int +Ipv4RawSocketImpl::ShutdownRecv (void) +{ + NS_LOG_FUNCTION (this); + m_shutdownRecv = true; + return 0; +} +int +Ipv4RawSocketImpl::Connect (const Address &address) +{ + NS_LOG_FUNCTION (this << address); + if (!InetSocketAddress::IsMatchingType (address)) + { + m_err = Socket::ERROR_INVAL; + return -1; + } + InetSocketAddress ad = InetSocketAddress::ConvertFrom (address); + m_dst = ad.GetIpv4 (); + return 0; +} +int +Ipv4RawSocketImpl::Listen (void) +{ + NS_LOG_FUNCTION (this); + m_err = Socket::ERROR_OPNOTSUPP; + return -1; +} +uint32_t +Ipv4RawSocketImpl::GetTxAvailable (void) const +{ + NS_LOG_FUNCTION (this); + return 0xffffffff; +} +int +Ipv4RawSocketImpl::Send (Ptr p, uint32_t flags) +{ + NS_LOG_FUNCTION (this << p << flags); + InetSocketAddress to = InetSocketAddress (m_dst, m_protocol); + return SendTo (p, flags, to); +} +int +Ipv4RawSocketImpl::SendTo (Ptr p, uint32_t flags, + const Address &toAddress) +{ + NS_LOG_FUNCTION (this << p << flags << toAddress); + if (!InetSocketAddress::IsMatchingType (toAddress)) + { + m_err = Socket::ERROR_INVAL; + return -1; + } + if (m_shutdownSend) + { + return 0; + } + InetSocketAddress ad = InetSocketAddress::ConvertFrom (toAddress); + Ptr ipv4 = m_node->GetObject (); + Ipv4Address dst = ad.GetIpv4 (); + uint32_t localIfIndex; + if (ipv4->GetIfIndexForDestination(dst, localIfIndex)) + { + ipv4->Send (p, ipv4->GetAddress (localIfIndex), dst, m_protocol); + } + else + { + NS_LOG_DEBUG ("dropped because no outgoing route."); + } + return 0; +} +uint32_t +Ipv4RawSocketImpl::GetRxAvailable (void) const +{ + NS_LOG_FUNCTION (this); + uint32_t rx = 0; + for (std::list::const_iterator i = m_recv.begin (); i != m_recv.end (); ++i) + { + rx += (i->packet)->GetSize (); + } + return rx; +} +Ptr +Ipv4RawSocketImpl::Recv (uint32_t maxSize, uint32_t flags) +{ + NS_LOG_FUNCTION (this << maxSize << flags); + Address tmp; + return RecvFrom (maxSize, flags, tmp); +} +Ptr +Ipv4RawSocketImpl::RecvFrom (uint32_t maxSize, uint32_t flags, + Address &fromAddress) +{ + NS_LOG_FUNCTION (this << maxSize << flags << fromAddress); + if (m_recv.empty ()) + { + return 0; + } + struct Data data = m_recv.front (); + m_recv.pop_front (); + if (data.packet->GetSize () > maxSize) + { + Ptr first = data.packet->CreateFragment (0, maxSize); + data.packet->RemoveAtStart (maxSize); + m_recv.push_front (data); + return first; + } + InetSocketAddress inet = InetSocketAddress (data.fromIp, data.fromProtocol); + fromAddress = inet; + return data.packet; +} + +void +Ipv4RawSocketImpl::SetProtocol (uint16_t protocol) +{ + NS_LOG_FUNCTION (this << protocol); + m_protocol = protocol; +} + +bool +Ipv4RawSocketImpl::ForwardUp (Ptr p, Ipv4Header ipHeader, Ptr device) +{ + NS_LOG_FUNCTION (this << *p << ipHeader << device); + if (m_shutdownRecv) + { + return false; + } + if ((m_src == Ipv4Address::GetAny () || ipHeader.GetDestination () == m_src) && + (m_dst == Ipv4Address::GetAny () || ipHeader.GetSource () == m_dst) && + ipHeader.GetProtocol () == m_protocol) + { + Ptr copy = p->Copy (); + if (m_protocol == 1) + { + Icmpv4Header icmpHeader; + copy->PeekHeader (icmpHeader); + uint8_t type = icmpHeader.GetType (); + if (type < 32 && + ((1 << type) & m_icmpFilter)) + { + // filter out icmp packet. + return false; + } + } + copy->AddHeader (ipHeader); + struct Data data; + data.packet = copy; + data.fromIp = ipHeader.GetSource (); + data.fromProtocol = ipHeader.GetProtocol (); + m_recv.push_back (data); + NotifyDataRecv (); + return true; + } + return false; +} + +} // namespace ns3 diff --git a/src/internet-stack/ipv4-raw-socket-impl.h b/src/internet-stack/ipv4-raw-socket-impl.h new file mode 100644 index 000000000..8e9e86af8 --- /dev/null +++ b/src/internet-stack/ipv4-raw-socket-impl.h @@ -0,0 +1,65 @@ +#ifndef IPV4_RAW_SOCKET_IMPL_H +#define IPV4_RAW_SOCKET_IMPL_H + +#include "ns3/socket.h" +#include "ns3/ipv4-header.h" +#include + +namespace ns3 { + +class NetDevice; +class Node; + +class Ipv4RawSocketImpl : public Socket +{ +public: + static TypeId GetTypeId (void); + + Ipv4RawSocketImpl (); + + void SetNode (Ptr node); + + virtual enum Socket::SocketErrno GetErrno (void) const; + virtual Ptr 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 p, uint32_t flags); + virtual int SendTo (Ptr p, uint32_t flags, + const Address &toAddress); + virtual uint32_t GetRxAvailable (void) const; + virtual Ptr Recv (uint32_t maxSize, uint32_t flags); + virtual Ptr RecvFrom (uint32_t maxSize, uint32_t flags, + Address &fromAddress); + + void SetProtocol (uint16_t protocol); + bool ForwardUp (Ptr p, Ipv4Header ipHeader, Ptr device); +private: + virtual void DoDispose (void); + + struct Data { + Ptr packet; + Ipv4Address fromIp; + uint16_t fromProtocol; + }; + + enum Socket::SocketErrno m_err; + Ptr m_node; + Ipv4Address m_src; + Ipv4Address m_dst; + uint16_t m_protocol; + std::list m_recv; + bool m_shutdownSend; + bool m_shutdownRecv; + uint32_t m_icmpFilter; +}; + +} // namespace ns3 + +#endif /* IPV4_RAW_SOCKET_IMPL_H */ diff --git a/src/internet-stack/nsc-tcp-l4-protocol.cc b/src/internet-stack/nsc-tcp-l4-protocol.cc index 401ef1e8f..5be47abaa 100644 --- a/src/internet-stack/nsc-tcp-l4-protocol.cc +++ b/src/internet-stack/nsc-tcp-l4-protocol.cc @@ -220,7 +220,7 @@ NscTcpL4Protocol::DeAllocate (Ipv4EndPoint *endPoint) // NSC m_endPoints->DeAllocate (endPoint); } -void +Ipv4L4Protocol::RxStatus NscTcpL4Protocol::Receive (Ptr packet, Ipv4Address const &source, Ipv4Address const &destination, @@ -251,6 +251,7 @@ NscTcpL4Protocol::Receive (Ptr packet, // deliver complete packet to the NSC network stack m_nscStack->if_receive_packet(0, data, packetSize); wakeup (); + return Ipv4L4Protocol::RX_OK; } void NscTcpL4Protocol::SoftInterrupt (void) diff --git a/src/internet-stack/nsc-tcp-l4-protocol.h b/src/internet-stack/nsc-tcp-l4-protocol.h index 212a62755..a9ca47345 100644 --- a/src/internet-stack/nsc-tcp-l4-protocol.h +++ b/src/internet-stack/nsc-tcp-l4-protocol.h @@ -80,10 +80,10 @@ public: * \param destination The destinations Ipv4Address * \param incomingInterface The Ipv4Interface it was received on */ - virtual void Receive (Ptr p, - Ipv4Address const &source, - Ipv4Address const &destination, - Ptr incomingInterface); + virtual Ipv4L4Protocol::RxStatus Receive (Ptr p, + Ipv4Address const &source, + Ipv4Address const &destination, + Ptr incomingInterface); // NSC callbacks. // NSC invokes these hooks to interact with the simulator. diff --git a/src/internet-stack/tcp-l4-protocol.cc b/src/internet-stack/tcp-l4-protocol.cc index 9b0d56a1f..501bb4d7d 100644 --- a/src/internet-stack/tcp-l4-protocol.cc +++ b/src/internet-stack/tcp-l4-protocol.cc @@ -431,7 +431,7 @@ TcpL4Protocol::DeAllocate (Ipv4EndPoint *endPoint) m_endPoints->DeAllocate (endPoint); } -void +enum Ipv4L4Protocol::RxStatus TcpL4Protocol::Receive (Ptr packet, Ipv4Address const &source, Ipv4Address const &destination, @@ -457,7 +457,7 @@ TcpL4Protocol::Receive (Ptr packet, if(!tcpHeader.IsChecksumOk ()) { NS_LOG_INFO("Bad checksum, dropping packet!"); - return; + return Ipv4L4Protocol::RX_CSUM_FAILED; } NS_LOG_LOGIC ("TcpL4Protocol "< packet, source.Print (oss); oss<<" source port: "<ForwardUp (packet, source, tcpHeader.GetSourcePort ()); + return Ipv4L4Protocol::RX_OK; } void diff --git a/src/internet-stack/tcp-l4-protocol.h b/src/internet-stack/tcp-l4-protocol.h index b567aaf6a..864df9d55 100644 --- a/src/internet-stack/tcp-l4-protocol.h +++ b/src/internet-stack/tcp-l4-protocol.h @@ -101,10 +101,10 @@ public: * \param destination The destinations Ipv4Address * \param incomingInterface The Ipv4Interface it was received on */ - virtual void Receive (Ptr p, - Ipv4Address const &source, - Ipv4Address const &destination, - Ptr incomingInterface); + virtual enum Ipv4L4Protocol::RxStatus Receive (Ptr p, + Ipv4Address const &source, + Ipv4Address const &destination, + Ptr incomingInterface); protected: virtual void DoDispose (void); diff --git a/src/internet-stack/udp-l4-protocol.cc b/src/internet-stack/udp-l4-protocol.cc index 080813b2c..9d5480bb9 100644 --- a/src/internet-stack/udp-l4-protocol.cc +++ b/src/internet-stack/udp-l4-protocol.cc @@ -146,6 +146,33 @@ UdpL4Protocol::DeAllocate (Ipv4EndPoint *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="<Lookup (destination, udpHeader.GetDestinationPort (), source, udpHeader.GetSourcePort (), interface); + if (endPoints.empty ()) + { + return Ipv4L4Protocol::RX_ENDPOINT_UNREACH; + } for (Ipv4EndPointDemux::EndPointsI endPoint = endPoints.begin (); endPoint != endPoints.end (); endPoint++) { (*endPoint)->ForwardUp (packet->Copy (), source, udpHeader.GetSourcePort ()); } + return Ipv4L4Protocol::RX_OK; } void diff --git a/src/internet-stack/udp-l4-protocol.h b/src/internet-stack/udp-l4-protocol.h index c92f83a61..55d967c67 100644 --- a/src/internet-stack/udp-l4-protocol.h +++ b/src/internet-stack/udp-l4-protocol.h @@ -84,10 +84,15 @@ public: * \param interface the interface from which the packet is coming. */ // inherited from Ipv4L4Protocol - virtual void Receive(Ptr p, - Ipv4Address const &source, - Ipv4Address const &destination, + virtual enum Ipv4L4Protocol::RxStatus Receive(Ptr p, + Ipv4Address const &source, + Ipv4Address const &destination, Ptr interface); + + virtual void ReceiveIcmp (Ipv4Address icmpSource, uint8_t icmpTtl, + uint8_t icmpType, uint8_t icmpCode, uint32_t icmpInfo, + Ipv4Address payloadSource,Ipv4Address payloadDestination, + const uint8_t payload[8]); protected: virtual void DoDispose (void); private: diff --git a/src/internet-stack/udp-socket-impl.cc b/src/internet-stack/udp-socket-impl.cc index 3feb6b3f5..4922e5912 100644 --- a/src/internet-stack/udp-socket-impl.cc +++ b/src/internet-stack/udp-socket-impl.cc @@ -25,8 +25,6 @@ #include "ns3/ipv4.h" #include "ns3/udp-socket-factory.h" #include "ns3/trace-source-accessor.h" -#include "ns3/uinteger.h" -#include "ns3/boolean.h" #include "udp-socket-impl.h" #include "udp-l4-protocol.h" #include "ipv4-end-point.h" @@ -47,6 +45,10 @@ UdpSocketImpl::GetTypeId (void) .AddConstructor () .AddTraceSource ("Drop", "Drop UDP packet due to receive buffer overflow", MakeTraceSourceAccessor (&UdpSocketImpl::m_dropTrace)) + .AddAttribute ("IcmpCallback", "Callback invoked whenever an icmp error is received on this socket.", + CallbackValue (), + MakeCallbackAccessor (&UdpSocketImpl::m_icmpCallback), + MakeCallbackChecker ()) ; return tid; } @@ -134,6 +136,7 @@ UdpSocketImpl::FinishBind (void) return -1; } m_endPoint->SetRxCallback (MakeCallback (&UdpSocketImpl::ForwardUp, Ptr (this))); + m_endPoint->SetIcmpCallback (MakeCallback (&UdpSocketImpl::ForwardIcmp, Ptr (this))); m_endPoint->SetDestroyCallback (MakeCallback (&UdpSocketImpl::Destroy, Ptr (this))); return 0; } @@ -328,6 +331,22 @@ UdpSocketImpl::DoSendTo (Ptr p, Ipv4Address dest, uint16_t port) tag.SetTtl (m_ipTtl); p->AddTag (tag); } + { + SocketSetDontFragmentTag tag; + bool found = p->FindFirstMatchingTag (tag); + if (!found) + { + if (m_mtuDiscover) + { + tag.Enable (); + } + else + { + tag.Disable (); + } + p->AddTag (tag); + } + } // // If dest is sent to the limited broadcast address (all ones), // convert it to send a copy of the packet out of every interface @@ -405,6 +424,7 @@ UdpSocketImpl::Recv (uint32_t maxSize, uint32_t flags) NS_LOG_FUNCTION (this << maxSize << flags); if (m_deliveryQueue.empty() ) { + m_errno = ERROR_AGAIN; return 0; } Ptr p = m_deliveryQueue.front (); @@ -483,6 +503,19 @@ UdpSocketImpl::ForwardUp (Ptr packet, Ipv4Address ipv4, uint16_t port) } } +void +UdpSocketImpl::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 ()) + { + m_icmpCallback (icmpSource, icmpTtl, icmpType, icmpCode, icmpInfo); + } +} + void UdpSocketImpl::SetRcvBufSize (uint32_t size) @@ -520,6 +553,18 @@ UdpSocketImpl::GetIpMulticastTtl (void) const return m_ipMulticastTtl; } +void +UdpSocketImpl::SetMtuDiscover (bool discover) +{ + m_mtuDiscover = discover; +} +bool +UdpSocketImpl::GetMtuDiscover (void) const +{ + return m_mtuDiscover; +} + + } //namespace ns3 diff --git a/src/internet-stack/udp-socket-impl.h b/src/internet-stack/udp-socket-impl.h index 03fae2e56..65fa0c9b3 100644 --- a/src/internet-stack/udp-socket-impl.h +++ b/src/internet-stack/udp-socket-impl.h @@ -28,6 +28,7 @@ #include "ns3/ptr.h" #include "ns3/ipv4-address.h" #include "ns3/udp-socket.h" +#include "icmpv4.h" namespace ns3 { @@ -83,6 +84,9 @@ private: virtual uint32_t GetIpTtl (void) const; virtual void SetIpMulticastTtl (uint32_t ipTtl); virtual uint32_t GetIpMulticastTtl (void) const; + virtual void SetMtuDiscover (bool discover); + virtual bool GetMtuDiscover (void) const; + friend class UdpSocketFactory; // invoked by Udp class @@ -92,6 +96,9 @@ private: int DoSend (Ptr p); int DoSendTo (Ptr p, const Address &daddr); int DoSendTo (Ptr p, Ipv4Address daddr, uint16_t dport); + void ForwardIcmp (Ipv4Address icmpSource, uint8_t icmpTtl, + uint8_t icmpType, uint8_t icmpCode, + uint32_t icmpInfo); Ipv4EndPoint *m_endPoint; Ptr m_node; @@ -114,7 +121,8 @@ private: uint32_t m_rcvBufSize; uint32_t m_ipTtl; uint32_t m_ipMulticastTtl; - + bool m_mtuDiscover; + Callback m_icmpCallback; }; }//namespace ns3 diff --git a/src/internet-stack/wscript b/src/internet-stack/wscript index 077a35859..c7f64f766 100644 --- a/src/internet-stack/wscript +++ b/src/internet-stack/wscript @@ -148,6 +148,10 @@ def build(bld): 'pending-data.cc', 'sequence-number.cc', 'rtt-estimator.cc', + 'ipv4-raw-socket-factory-impl.cc', + 'ipv4-raw-socket-impl.cc', + 'icmpv4.cc', + 'icmpv4-l4-protocol.cc', ] headers = bld.create_obj('ns3header') @@ -160,6 +164,7 @@ def build(bld): 'ipv4-interface.h', 'ipv4-l3-protocol.h', 'ipv4-static-routing.h', + 'icmpv4.h', ] if bld.env()['NSC_ENABLED']: diff --git a/src/node/ipv4-raw-socket-factory.cc b/src/node/ipv4-raw-socket-factory.cc new file mode 100644 index 000000000..433b1313c --- /dev/null +++ b/src/node/ipv4-raw-socket-factory.cc @@ -0,0 +1,35 @@ +/* -*- 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 + */ +#include "ipv4-raw-socket-factory.h" +#include "ns3/uinteger.h" + +namespace ns3 { + +NS_OBJECT_ENSURE_REGISTERED (Ipv4RawSocketFactory); + +TypeId Ipv4RawSocketFactory::GetTypeId (void) +{ + static TypeId tid = TypeId ("ns3::Ipv4RawSocketFactory") + .SetParent () + ; + return tid; +} + +} // namespace ns3 diff --git a/src/node/ipv4-raw-socket-factory.h b/src/node/ipv4-raw-socket-factory.h new file mode 100644 index 000000000..65b43aeb5 --- /dev/null +++ b/src/node/ipv4-raw-socket-factory.h @@ -0,0 +1,46 @@ +/* -*- 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 + */ +#ifndef IPV4_RAW_SOCKET_FACTORY_H +#define IPV4_RAW_SOCKET_FACTORY_H + +#include "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 */ diff --git a/src/node/socket.cc b/src/node/socket.cc index c7f9511e5..4ceac3962 100644 --- a/src/node/socket.cc +++ b/src/node/socket.cc @@ -362,4 +362,57 @@ SocketIpTtlTag::Print (std::ostream &os) const } +SocketSetDontFragmentTag::SocketSetDontFragmentTag () +{} +void +SocketSetDontFragmentTag::Enable (void) +{ + m_dontFragment = true; +} +void +SocketSetDontFragmentTag::Disable (void) +{ + m_dontFragment = false; +} +bool +SocketSetDontFragmentTag::IsEnabled (void) const +{ + return m_dontFragment; +} + +TypeId +SocketSetDontFragmentTag::GetTypeId (void) +{ + static TypeId tid = TypeId ("ns3::SocketSetDontFragmentTag") + .SetParent () + .AddConstructor () + ; + return tid; +} +TypeId +SocketSetDontFragmentTag::GetInstanceTypeId (void) const +{ + return GetTypeId (); +} +uint32_t +SocketSetDontFragmentTag::GetSerializedSize (void) const +{ + return 1; +} +void +SocketSetDontFragmentTag::Serialize (TagBuffer i) const +{ + i.WriteU8 (m_dontFragment?1:0); +} +void +SocketSetDontFragmentTag::Deserialize (TagBuffer i) +{ + m_dontFragment = (i.ReadU8 () == 1)?true:false; +} +void +SocketSetDontFragmentTag::Print (std::ostream &os) const +{ + os << (m_dontFragment?"true":"false"); +} + }//namespace ns3 diff --git a/src/node/socket.h b/src/node/socket.h index 6287895a4..22fd59e86 100644 --- a/src/node/socket.h +++ b/src/node/socket.h @@ -336,9 +336,9 @@ public: * not preserved. * * The flags argument is formed by or'ing one or more of the values: - * MSG_OOB process out-of-band data - * MSG_PEEK peek at incoming message - * These flags are _unsupported_ as of ns-3.1. + * MSG_OOB process out-of-band data + * MSG_PEEK peek at incoming message + * None of these flags are supported for now. * * Some variants of Recv() are supported as additional API, * including RecvFrom(), overloaded Recv() without arguments, @@ -555,6 +555,29 @@ private: uint8_t m_ttl; }; + +/** + * \brief indicated whether packets should be sent out with + * the DF flag set. + */ +class SocketSetDontFragmentTag : public Tag +{ +public: + SocketSetDontFragmentTag (); + void Enable (void); + void Disable (void); + bool IsEnabled (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: + bool m_dontFragment; +}; + } //namespace ns3 #endif /* SOCKET_H */ diff --git a/src/node/udp-socket.cc b/src/node/udp-socket.cc index 8fc5ea8b1..25ceacae6 100644 --- a/src/node/udp-socket.cc +++ b/src/node/udp-socket.cc @@ -21,6 +21,7 @@ #include "ns3/object.h" #include "ns3/log.h" #include "ns3/uinteger.h" +#include "ns3/boolean.h" #include "ns3/trace-source-accessor.h" #include "udp-socket.h" @@ -53,6 +54,11 @@ UdpSocket::GetTypeId (void) MakeUintegerAccessor (&UdpSocket::GetIpMulticastTtl, &UdpSocket::SetIpMulticastTtl), MakeUintegerChecker ()) + .AddAttribute ("MtuDiscover", "If enabled, every outgoing ip packet will have the DF flag set.", + BooleanValue (false), + MakeBooleanAccessor (&UdpSocket::SetMtuDiscover, + &UdpSocket::GetMtuDiscover), + MakeBooleanChecker ()) ; return tid; } diff --git a/src/node/udp-socket.h b/src/node/udp-socket.h index afe17774e..4d44549ed 100644 --- a/src/node/udp-socket.h +++ b/src/node/udp-socket.h @@ -58,7 +58,8 @@ private: virtual uint32_t GetIpTtl (void) const = 0; virtual void SetIpMulticastTtl (uint32_t ipTtl) = 0; virtual uint32_t GetIpMulticastTtl (void) const = 0; - + virtual void SetMtuDiscover (bool discover) = 0; + virtual bool GetMtuDiscover (void) const = 0; }; } //namespace ns3 diff --git a/src/node/wscript b/src/node/wscript index 1856970ff..9bb6927f7 100644 --- a/src/node/wscript +++ b/src/node/wscript @@ -34,6 +34,7 @@ def build(bld): 'application.cc', 'simple-channel.cc', 'simple-net-device.cc', + 'ipv4-raw-socket-factory.cc', ] headers = bld.create_obj('ns3header') @@ -69,4 +70,5 @@ def build(bld): 'application.h', 'simple-channel.h', 'simple-net-device.h', + 'ipv4-raw-socket-factory.h', ] From 6eeec4502a59621d4e986d438abe4fb24c61b288 Mon Sep 17 00:00:00 2001 From: Craig Dowell Date: Wed, 29 Oct 2008 11:19:01 -0700 Subject: [PATCH 05/52] Apply icmp-application patch frm lacage --- examples/csma-ping.cc | 140 ++++++++++++++++++ examples/csma-raw-ip-socket.cc | 122 +++++++++++++++ examples/wscript | 8 + regression/tests/test-csma-ping.py | 12 ++ regression/tests/test-csma-raw-ip-socket.py | 12 ++ src/applications/v4ping/v4ping.cc | 155 ++++++++++++++++++++ src/applications/v4ping/v4ping.h | 36 +++++ src/applications/v4ping/wscript | 13 ++ src/helper/v4ping-helper.cc | 33 +++++ src/helper/v4ping-helper.h | 25 ++++ src/helper/wscript | 2 + src/wscript | 1 + 12 files changed, 559 insertions(+) create mode 100644 examples/csma-ping.cc create mode 100644 examples/csma-raw-ip-socket.cc create mode 100644 regression/tests/test-csma-ping.py create mode 100644 regression/tests/test-csma-raw-ip-socket.py create mode 100644 src/applications/v4ping/v4ping.cc create mode 100644 src/applications/v4ping/v4ping.h create mode 100644 src/applications/v4ping/wscript create mode 100644 src/helper/v4ping-helper.cc create mode 100644 src/helper/v4ping-helper.h diff --git a/examples/csma-ping.cc b/examples/csma-ping.cc new file mode 100644 index 000000000..ffddd9c6f --- /dev/null +++ b/examples/csma-ping.cc @@ -0,0 +1,140 @@ +/* -*- 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 + */ + +// Port of ns-2/tcl/ex/simple.tcl to ns-3 +// +// Network topology +// +// n0 n1 n2 n3 +// | | | | +// ===================== +// +// - CBR/UDP flows from n0 to n1, and from n3 to n0 +// - UDP packet size of 210 bytes, with per-packet interval 0.00375 sec. +// (i.e., DataRate of 448,000 bps) +// - DropTail queues +// - Tracing of queues and packet receptions to file "csma-one-subnet.tr" + +#include +#include +#include +#include + +#include "ns3/core-module.h" +#include "ns3/simulator-module.h" +#include "ns3/node-module.h" +#include "ns3/helper-module.h" +#include "ns3/global-route-manager.h" + +using namespace ns3; + +NS_LOG_COMPONENT_DEFINE ("CsmaPingExample"); + +static void SinkRx (Ptr p, const Address &ad) +{ + //std::cout << *p << std::endl; +} + +static void PingRtt (std::string context, Time rtt) +{ + //std::cout << context << " " << rtt << std::endl; +} + +int +main (int argc, char *argv[]) +{ + // + // Make the random number generators generate reproducible results. + // + RandomVariable::UseGlobalSeed (1, 1, 2, 3, 5, 8); + + CommandLine cmd; + cmd.Parse (argc, argv); + + // Here, we will explicitly create four nodes. + NS_LOG_INFO ("Create nodes."); + NodeContainer c; + c.Create (4); + + // connect all our nodes to a shared channel. + NS_LOG_INFO ("Build Topology."); + CsmaHelper csma; + csma.SetChannelAttribute ("DataRate", DataRateValue (DataRate (5000000))); + csma.SetChannelAttribute ("Delay", TimeValue (MilliSeconds (2))); + csma.SetDeviceAttribute ("EncapsulationMode", StringValue ("Llc")); + NetDeviceContainer devs = csma.Install (c); + + // add an ip stack to all nodes. + NS_LOG_INFO ("Add ip stack."); + InternetStackHelper ipStack; + ipStack.Install (c); + + // assign ip addresses + NS_LOG_INFO ("Assign ip addresses."); + Ipv4AddressHelper ip; + ip.SetBase ("192.168.1.0", "255.255.255.0"); + Ipv4InterfaceContainer addresses = ip.Assign (devs); + + // setup global router + GlobalRouteManager::PopulateRoutingTables (); + NS_LOG_INFO ("Create Source"); + Config::SetDefault ("ns3::Ipv4RawSocketImpl::Protocol", StringValue ("2")); + InetSocketAddress dst = InetSocketAddress (addresses.GetAddress (3)); + OnOffHelper onoff = OnOffHelper ("ns3::Ipv4RawSocketFactory", dst); + onoff.SetAttribute ("OnTime", RandomVariableValue (ConstantVariable (1.0))); + onoff.SetAttribute ("OffTime", RandomVariableValue (ConstantVariable (0.0))); + onoff.SetAttribute ("DataRate", DataRateValue (DataRate (15000))); + onoff.SetAttribute ("PacketSize", UintegerValue (1200)); + + + ApplicationContainer apps = onoff.Install (c.Get (0)); + apps.Start (Seconds (1.0)); + apps.Stop (Seconds (10.0)); + + NS_LOG_INFO ("Create Sink."); + PacketSinkHelper sink = PacketSinkHelper ("ns3::Ipv4RawSocketFactory", dst); + apps = sink.Install (c.Get (3)); + apps.Start (Seconds (0.0)); + apps.Stop (Seconds (11.0)); + + NS_LOG_INFO ("Create pinger"); + V4PingHelper ping = V4PingHelper (addresses.GetAddress (2)); + NodeContainer pingers; + pingers.Add (c.Get (0)); + pingers.Add (c.Get (1)); + pingers.Add (c.Get (3)); + apps = ping.Install (pingers); + apps.Start (Seconds (2.0)); + apps.Stop (Seconds (5.0)); + + NS_LOG_INFO ("Configure Tracing."); + // first, pcap tracing. + csma.EnablePcapAll ("csma-ping"); + // then, print what the packet sink receives. + Config::ConnectWithoutContext ("/NodeList/3/ApplicationList/0/$ns3::PacketSink/Rx", + MakeCallback (&SinkRx)); + // finally, print the ping rtts. + Config::Connect ("/NodeList/*/ApplicationList/*/$ns3::V4Ping/Rtt", + MakeCallback (&PingRtt)); + + Packet::EnablePrinting (); + + + NS_LOG_INFO ("Run Simulation."); + Simulator::Run (); + Simulator::Destroy (); + NS_LOG_INFO ("Done."); +} diff --git a/examples/csma-raw-ip-socket.cc b/examples/csma-raw-ip-socket.cc new file mode 100644 index 000000000..37f4dab51 --- /dev/null +++ b/examples/csma-raw-ip-socket.cc @@ -0,0 +1,122 @@ +/* -*- 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 + */ + +// Port of ns-2/tcl/ex/simple.tcl to ns-3 +// +// Network topology +// +// n0 n1 n2 n3 +// | | | | +// ===================== +// +// - CBR/UDP flows from n0 to n1, and from n3 to n0 +// - UDP packet size of 210 bytes, with per-packet interval 0.00375 sec. +// (i.e., DataRate of 448,000 bps) +// - DropTail queues +// - Tracing of queues and packet receptions to file "csma-one-subnet.tr" + +#include +#include +#include +#include + +#include "ns3/core-module.h" +#include "ns3/simulator-module.h" +#include "ns3/node-module.h" +#include "ns3/helper-module.h" + +using namespace ns3; + +NS_LOG_COMPONENT_DEFINE ("CsmaPacketSocketExample"); + +static void SinkRx (Ptr p, const Address &ad) +{ + //std::cout << *p << std::endl; +} + +int +main (int argc, char *argv[]) +{ +#if 0 + LogComponentEnable ("CsmaPacketSocketExample", LOG_LEVEL_INFO); +#endif + + // + // Make the random number generators generate reproducible results. + // + RandomVariable::UseGlobalSeed (1, 1, 2, 3, 5, 8); + + CommandLine cmd; + cmd.Parse (argc, argv); + + // Here, we will explicitly create four nodes. + NS_LOG_INFO ("Create nodes."); + NodeContainer c; + c.Create (4); + + // connect all our nodes to a shared channel. + NS_LOG_INFO ("Build Topology."); + CsmaHelper csma; + csma.SetChannelAttribute ("DataRate", DataRateValue (DataRate (5000000))); + csma.SetChannelAttribute ("Delay", TimeValue (MilliSeconds (2))); + csma.SetDeviceAttribute ("EncapsulationMode", StringValue ("Llc")); + NetDeviceContainer devs = csma.Install (c); + + // add an ip stack to all nodes. + NS_LOG_INFO ("Add ip stack."); + InternetStackHelper ipStack; + ipStack.Install (c); + + // assign ip addresses + NS_LOG_INFO ("Assign ip addresses."); + Ipv4AddressHelper ip; + ip.SetBase ("192.168.1.0", "255.255.255.0"); + Ipv4InterfaceContainer addresses = ip.Assign (devs); + + NS_LOG_INFO ("Create Source"); + Config::SetDefault ("ns3::Ipv4RawSocketImpl::Protocol", StringValue ("2")); + InetSocketAddress dst = InetSocketAddress (addresses.GetAddress (3)); + OnOffHelper onoff = OnOffHelper ("ns3::Ipv4RawSocketFactory", dst); + onoff.SetAttribute ("OnTime", RandomVariableValue (ConstantVariable (1.0))); + onoff.SetAttribute ("OffTime", RandomVariableValue (ConstantVariable (0.0))); + onoff.SetAttribute ("DataRate", DataRateValue (DataRate (6000))); + onoff.SetAttribute ("PacketSize", UintegerValue (1200)); + + ApplicationContainer apps = onoff.Install (c.Get (0)); + apps.Start (Seconds (1.0)); + apps.Stop (Seconds (10.0)); + + NS_LOG_INFO ("Create Sink."); + PacketSinkHelper sink = PacketSinkHelper ("ns3::Ipv4RawSocketFactory", dst); + apps = sink.Install (c.Get (3)); + apps.Start (Seconds (0.0)); + apps.Stop (Seconds (11.0)); + + NS_LOG_INFO ("Configure Tracing."); + // first, pcap tracing. + csma.EnablePcapAll ("csma-raw-ip-socket"); + // then, print what the packet sink receives. + Config::ConnectWithoutContext ("/NodeList/3/ApplicationList/0/$ns3::PacketSink/Rx", + MakeCallback (&SinkRx)); + + Packet::EnablePrinting (); + + + NS_LOG_INFO ("Run Simulation."); + Simulator::Run (); + Simulator::Destroy (); + NS_LOG_INFO ("Done."); +} diff --git a/examples/wscript b/examples/wscript index e68afba06..4cae9dfc4 100644 --- a/examples/wscript +++ b/examples/wscript @@ -94,3 +94,11 @@ def build(bld): ['core', 'simulator', 'mobility', 'wifi', 'csma', 'helper', 'bridge']) obj.source = 'wifi-wired-bridging.cc' + + obj = bld.create_ns3_program('csma-raw-ip-socket', + ['csma', 'internet-stack']) + obj.source = 'csma-raw-ip-socket.cc' + + obj = bld.create_ns3_program('csma-ping', + ['csma', 'internet-stack', 'v4ping']) + obj.source = 'csma-ping.cc' diff --git a/regression/tests/test-csma-ping.py b/regression/tests/test-csma-ping.py new file mode 100644 index 000000000..b1fe044b1 --- /dev/null +++ b/regression/tests/test-csma-ping.py @@ -0,0 +1,12 @@ +#! /usr/bin/env python + +"""Generic trace-comparison-type regression test.""" + +import os +import shutil +import tracediff + +def run(verbose, generate, refDirName): + """Execute a test.""" + + return tracediff.run_test(verbose, generate, refDirName, "csma-ping") diff --git a/regression/tests/test-csma-raw-ip-socket.py b/regression/tests/test-csma-raw-ip-socket.py new file mode 100644 index 000000000..e6e916be6 --- /dev/null +++ b/regression/tests/test-csma-raw-ip-socket.py @@ -0,0 +1,12 @@ +#! /usr/bin/env python + +"""Generic trace-comparison-type regression test.""" + +import os +import shutil +import tracediff + +def run(verbose, generate, refDirName): + """Execute a test.""" + + return tracediff.run_test(verbose, generate, refDirName, "csma-raw-ip-socket") diff --git a/src/applications/v4ping/v4ping.cc b/src/applications/v4ping/v4ping.cc new file mode 100644 index 000000000..e70917e60 --- /dev/null +++ b/src/applications/v4ping/v4ping.cc @@ -0,0 +1,155 @@ +#include "v4ping.h" +#include "ns3/icmpv4.h" +#include "ns3/assert.h" +#include "ns3/log.h" +#include "ns3/ipv4-address.h" +#include "ns3/socket.h" +#include "ns3/uinteger.h" +#include "ns3/inet-socket-address.h" +#include "ns3/packet.h" +#include "ns3/trace-source-accessor.h" +#include "ns3/simulator.h" + +namespace ns3 { + +NS_LOG_COMPONENT_DEFINE ("V4Ping"); +NS_OBJECT_ENSURE_REGISTERED (V4Ping); + +TypeId +V4Ping::GetTypeId (void) +{ + static TypeId tid = TypeId ("ns3::V4Ping") + .SetParent () + .AddConstructor () + .AddAttribute ("Remote", + "The address of the machine we want to ping.", + Ipv4AddressValue (), + MakeIpv4AddressAccessor (&V4Ping::m_remote), + MakeIpv4AddressChecker ()) + .AddTraceSource ("Rtt", + "The rtt calculated by the ping.", + MakeTraceSourceAccessor (&V4Ping::m_traceRtt)); + ; + return tid; +} + +V4Ping::V4Ping () + : m_socket (0), + m_seq (0) +{} +V4Ping::~V4Ping () +{} + +void +V4Ping::DoDispose (void) +{ + NS_LOG_FUNCTION (this); + m_socket = 0; + Application::DoDispose (); +} + +uint32_t +V4Ping::GetApplicationId (void) const +{ + Ptr node = GetNode (); + for (uint32_t i = 0; i < node->GetNApplications (); ++i) + { + if (node->GetApplication (i) == this) + { + return i; + } + } + NS_ASSERT_MSG (false, "forgot to add application to node"); + return 0; // quiet compiler +} + +void +V4Ping::Receive (Ptr socket) +{ + NS_LOG_FUNCTION (this << socket); + while (m_socket->GetRxAvailable () > 0) + { + Address from; + Ptr p = m_socket->RecvFrom (0xffffffff, 0, from); + NS_LOG_DEBUG ("recv " << p->GetSize () << " bytes"); + NS_ASSERT (InetSocketAddress::IsMatchingType (from)); + InetSocketAddress realFrom = InetSocketAddress::ConvertFrom (from); + NS_ASSERT (realFrom.GetPort () == 1); // protocol should be icmp. + Ipv4Header ipv4; + p->RemoveHeader (ipv4); + NS_ASSERT (ipv4.GetProtocol () == 1); // protocol should be icmp. + Icmpv4Header icmp; + p->RemoveHeader (icmp); + if (icmp.GetType () == Icmpv4Header::ECHO_REPLY) + { + Icmpv4Echo echo; + p->RemoveHeader (echo); + if (echo.GetSequenceNumber () == (m_seq - 1) && + echo.GetIdentifier () == 0) + { + Ptr data = echo.GetData (); + if (data->GetSize () == 16) + { + uint32_t *buf = (uint32_t *)data->PeekData (); + if (buf[0] == GetNode ()->GetId () && + buf[1] == GetApplicationId ()) + { + int64_t ts = buf[3]; + ts <<= 32; + ts |= buf[2]; + Time sendTime = TimeStep (ts); + NS_ASSERT (Simulator::Now () > sendTime); + Time delta = Simulator::Now () - sendTime; + m_traceRtt (delta); + } + } + } + } + } +} + +void +V4Ping::StartApplication (void) +{ + NS_LOG_FUNCTION (this); + m_socket = Socket::CreateSocket (GetNode (), TypeId::LookupByName ("ns3::Ipv4RawSocketFactory")); + NS_ASSERT (m_socket != 0); + m_socket->SetAttribute ("Protocol", UintegerValue (1)); // icmp + m_socket->SetRecvCallback (MakeCallback (&V4Ping::Receive, this)); + InetSocketAddress src = InetSocketAddress (Ipv4Address::GetAny (), 0); + int status; + status = m_socket->Bind (src); + NS_ASSERT (status != -1); + InetSocketAddress dst = InetSocketAddress (m_remote, 0); + status = m_socket->Connect (dst); + NS_ASSERT (status != -1); + Ptr p = Create (); + Icmpv4Echo echo; + echo.SetSequenceNumber (m_seq); + m_seq++; + echo.SetIdentifier (0); + uint32_t data[4]; + data[0] = GetNode ()->GetId (); + data[1] = GetApplicationId (); + int64_t now = Simulator::Now ().GetTimeStep (); + data[2] = now & 0xffffffff; + now >>= 32; + data[3] = now & 0xffffffff; + Ptr dataPacket = Create ((uint8_t *) &data, 16); + echo.SetData (dataPacket); + p->AddHeader (echo); + Icmpv4Header header; + header.SetType (Icmpv4Header::ECHO); + header.SetCode (0); + p->AddHeader (header); + m_socket->Send (p, 0); + +} +void +V4Ping::StopApplication (void) +{ + NS_LOG_FUNCTION (this); +} + + +} // namespace ns3 diff --git a/src/applications/v4ping/v4ping.h b/src/applications/v4ping/v4ping.h new file mode 100644 index 000000000..800ab1fbb --- /dev/null +++ b/src/applications/v4ping/v4ping.h @@ -0,0 +1,36 @@ +#ifndef V4PING_H +#define V4PING_H + +#include "ns3/application.h" +#include "ns3/traced-callback.h" +#include "ns3/nstime.h" + +namespace ns3 { + +class Socket; + +class V4Ping : public Application +{ +public: + static TypeId GetTypeId (void); + + V4Ping (); + virtual ~V4Ping (); + +private: + // inherited from Application base class. + virtual void StartApplication (void); + virtual void StopApplication (void); + virtual void DoDispose (void); + uint32_t GetApplicationId (void) const; + void Receive (Ptr socket); + + Ipv4Address m_remote; + Ptr m_socket; + uint16_t m_seq; + TracedCallback