A Discrete-Event Network Simulator
API
openflow-switch-net-device.cc
Go to the documentation of this file.
1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2 /*
3  * This program is free software; you can redistribute it and/or modify
4  * it under the terms of the GNU General Public License version 2 as
5  * published by the Free Software Foundation;
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software
14  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
15  *
16  * Author: Blake Hurd <naimorai@gmail.com>
17  */
18 #ifdef NS3_OPENFLOW
19 
21 #include "ns3/udp-l4-protocol.h"
22 #include "ns3/tcp-l4-protocol.h"
23 
24 namespace ns3 {
25 
26 NS_LOG_COMPONENT_DEFINE ("OpenFlowSwitchNetDevice");
27 
28 NS_OBJECT_ENSURE_REGISTERED (OpenFlowSwitchNetDevice);
29 
30 const char *
32 {
33  return "The ns-3 team";
34 }
35 
36 const char *
38 {
39  return "N/A";
40 }
41 
42 const char *
44 {
45  return "Simulated OpenFlow Switch";
46 }
47 
48 const char *
50 {
51  return "N/A";
52 }
53 
54 static uint64_t
55 GenerateId ()
56 {
57  uint8_t ea[ETH_ADDR_LEN];
58  eth_addr_random (ea);
59  return eth_addr_to_uint64 (ea);
60 }
61 
62 TypeId
64 {
65  static TypeId tid = TypeId ("ns3::OpenFlowSwitchNetDevice")
66  .SetParent<NetDevice> ()
67  .SetGroupName ("Openflow")
69  .AddAttribute ("ID",
70  "The identification of the OpenFlowSwitchNetDevice/Datapath, needed for OpenFlow compatibility.",
71  UintegerValue (GenerateId ()),
73  MakeUintegerChecker<uint64_t> ())
74  .AddAttribute ("FlowTableLookupDelay",
75  "A real switch will have an overhead for looking up in the flow table. For the default, we simulate a standard TCAM on an FPGA.",
76  TimeValue (NanoSeconds (30)),
78  MakeTimeChecker ())
79  .AddAttribute ("Flags", // Note: The Controller can configure this value, overriding the user's setting.
80  "Flags to turn different functionality on/off, such as whether to inform the controller when a flow expires, or how to handle fragments.",
81  UintegerValue (0), // Look at the ofp_config_flags enum in openflow/include/openflow.h for options.
83  MakeUintegerChecker<uint16_t> ())
84  .AddAttribute ("FlowTableMissSendLength", // Note: The Controller can configure this value, overriding the user's setting.
85  "When forwarding a packet the switch didn't match up to the controller, it can be more efficient to forward only the first x bytes.",
86  UintegerValue (OFP_DEFAULT_MISS_SEND_LEN), // 128 bytes
88  MakeUintegerChecker<uint16_t> ())
89  ;
90  return tid;
91 }
92 
94  : m_node (0),
95  m_ifIndex (0),
96  m_mtu (0xffff)
97 {
99 
100  m_channel = CreateObject<BridgeChannel> ();
101 
102  time_init (); // OFSI's clock; needed to use the buffer storage system.
103  // m_lastTimeout = time_now ();
104 
105  m_controller = 0;
106  // m_listenPVConn = 0;
107 
108  m_chain = chain_create ();
109  if (m_chain == 0)
110  {
111  NS_LOG_ERROR ("Not enough memory to create the flow table.");
112  }
113 
114  m_ports.reserve (DP_MAX_PORTS);
115  vport_table_init (&m_vportTable);
116 }
117 
118 OpenFlowSwitchNetDevice::~OpenFlowSwitchNetDevice ()
119 {
121 }
122 
123 void
124 OpenFlowSwitchNetDevice::DoDispose ()
125 {
127 
128  for (Ports_t::iterator b = m_ports.begin (), e = m_ports.end (); b != e; b++)
129  {
130  SendPortStatus (*b, OFPPR_DELETE);
131  b->netdev = 0;
132  }
133  m_ports.clear ();
134 
135  m_controller = 0;
136 
137  chain_destroy (m_chain);
138  RBTreeDestroy (m_vportTable.table);
139  m_channel = 0;
140  m_node = 0;
141  NetDevice::DoDispose ();
142 }
143 
144 void
145 OpenFlowSwitchNetDevice::SetController (Ptr<ofi::Controller> c)
146 {
147  if (m_controller != 0)
148  {
149  NS_LOG_ERROR ("Controller already set.");
150  return;
151  }
152 
153  m_controller = c;
154  m_controller->AddSwitch (this);
155 }
156 
157 int
158 OpenFlowSwitchNetDevice::AddSwitchPort (Ptr<NetDevice> switchPort)
159 {
161  NS_ASSERT (switchPort != this);
162  if (!Mac48Address::IsMatchingType (switchPort->GetAddress ()))
163  {
164  NS_FATAL_ERROR ("Device does not support eui 48 addresses: cannot be added to switch.");
165  }
166  if (!switchPort->SupportsSendFrom ())
167  {
168  NS_FATAL_ERROR ("Device does not support SendFrom: cannot be added to switch.");
169  }
170  if (m_address == Mac48Address ())
171  {
172  m_address = Mac48Address::ConvertFrom (switchPort->GetAddress ());
173  }
174 
175  if (m_ports.size () < DP_MAX_PORTS)
176  {
177  ofi::Port p;
178  p.config = 0;
179  p.netdev = switchPort;
180  m_ports.push_back (p);
181 
182  // Notify the controller that this port has been added
183  SendPortStatus (p, OFPPR_ADD);
184 
185  NS_LOG_DEBUG ("RegisterProtocolHandler for " << switchPort->GetInstanceTypeId ().GetName ());
186  m_node->RegisterProtocolHandler (MakeCallback (&OpenFlowSwitchNetDevice::ReceiveFromDevice, this),
187  0, switchPort, true);
188  m_channel->AddChannel (switchPort->GetChannel ());
189  }
190  else
191  {
192  return EXFULL;
193  }
194 
195  return 0;
196 }
197 
198 void
199 OpenFlowSwitchNetDevice::SetIfIndex (const uint32_t index)
200 {
202  m_ifIndex = index;
203 }
204 
205 uint32_t
206 OpenFlowSwitchNetDevice::GetIfIndex (void) const
207 {
209  return m_ifIndex;
210 }
211 
212 Ptr<Channel>
213 OpenFlowSwitchNetDevice::GetChannel (void) const
214 {
216  return m_channel;
217 }
218 
219 void
220 OpenFlowSwitchNetDevice::SetAddress (Address address)
221 {
223  m_address = Mac48Address::ConvertFrom (address);
224 }
225 
226 Address
227 OpenFlowSwitchNetDevice::GetAddress (void) const
228 {
230  return m_address;
231 }
232 
233 bool
234 OpenFlowSwitchNetDevice::SetMtu (const uint16_t mtu)
235 {
237  m_mtu = mtu;
238  return true;
239 }
240 
241 uint16_t
242 OpenFlowSwitchNetDevice::GetMtu (void) const
243 {
245  return m_mtu;
246 }
247 
248 
249 bool
250 OpenFlowSwitchNetDevice::IsLinkUp (void) const
251 {
253  return true;
254 }
255 
256 
257 void
258 OpenFlowSwitchNetDevice::AddLinkChangeCallback (Callback<void> callback)
259 {
260 }
261 
262 bool
263 OpenFlowSwitchNetDevice::IsBroadcast (void) const
264 {
266  return true;
267 }
268 
269 Address
270 OpenFlowSwitchNetDevice::GetBroadcast (void) const
271 {
273  return Mac48Address ("ff:ff:ff:ff:ff:ff");
274 }
275 
276 bool
278 {
280  return true;
281 }
282 
283 Address
284 OpenFlowSwitchNetDevice::GetMulticast (Ipv4Address multicastGroup) const
285 {
286  NS_LOG_FUNCTION (this << multicastGroup);
287  Mac48Address multicast = Mac48Address::GetMulticast (multicastGroup);
288  return multicast;
289 }
290 
291 
292 bool
293 OpenFlowSwitchNetDevice::IsPointToPoint (void) const
294 {
296  return false;
297 }
298 
299 bool
300 OpenFlowSwitchNetDevice::IsBridge (void) const
301 {
303  return true;
304 }
305 
306 void
307 OpenFlowSwitchNetDevice::DoOutput (uint32_t packet_uid, int in_port, size_t max_len, int out_port, bool ignore_no_fwd)
308 {
309  if (out_port != OFPP_CONTROLLER)
310  {
311  OutputPort (packet_uid, in_port, out_port, ignore_no_fwd);
312  }
313  else
314  {
315  OutputControl (packet_uid, in_port, max_len, OFPR_ACTION);
316  }
317 }
318 
319 bool
320 OpenFlowSwitchNetDevice::Send (Ptr<Packet> packet, const Address& dest, uint16_t protocolNumber)
321 {
323  return SendFrom (packet, m_address, dest, protocolNumber);
324 }
325 
326 bool
327 OpenFlowSwitchNetDevice::SendFrom (Ptr<Packet> packet, const Address& src, const Address& dest, uint16_t protocolNumber)
328 {
330 
331  ofpbuf *buffer = BufferFromPacket (packet,src,dest,GetMtu (),protocolNumber);
332 
333  uint32_t packet_uid = save_buffer (buffer);
334  ofi::SwitchPacketMetadata data;
335  data.packet = packet;
336  data.buffer = buffer;
337  data.protocolNumber = protocolNumber;
338  data.src = Address (src);
339  data.dst = Address (dest);
340  m_packetData.insert (std::make_pair (packet_uid, data));
341 
342  RunThroughFlowTable (packet_uid, -1);
343 
344  return true;
345 }
346 
347 
348 Ptr<Node>
349 OpenFlowSwitchNetDevice::GetNode (void) const
350 {
352  return m_node;
353 }
354 
355 void
356 OpenFlowSwitchNetDevice::SetNode (Ptr<Node> node)
357 {
359  m_node = node;
360 }
361 
362 bool
363 OpenFlowSwitchNetDevice::NeedsArp (void) const
364 {
366  return true;
367 }
368 
369 void
370 OpenFlowSwitchNetDevice::SetReceiveCallback (NetDevice::ReceiveCallback cb)
371 {
373  m_rxCallback = cb;
374 }
375 
376 void
377 OpenFlowSwitchNetDevice::SetPromiscReceiveCallback (NetDevice::PromiscReceiveCallback cb)
378 {
380  m_promiscRxCallback = cb;
381 }
382 
383 bool
384 OpenFlowSwitchNetDevice::SupportsSendFrom () const
385 {
387  return true;
388 }
389 
390 Address
391 OpenFlowSwitchNetDevice::GetMulticast (Ipv6Address addr) const
392 {
393  NS_LOG_FUNCTION (this << addr);
394  return Mac48Address::GetMulticast (addr);
395 }
396 
397 // Add a virtual port table entry.
398 int
399 OpenFlowSwitchNetDevice::AddVPort (const ofp_vport_mod *ovpm)
400 {
401  size_t actions_len = ntohs (ovpm->header.length) - sizeof *ovpm;
402  unsigned int vport = ntohl (ovpm->vport);
403  unsigned int parent_port = ntohl (ovpm->parent_port);
404 
405  // check whether port table entry exists for specified port number
406  vport_table_entry *vpe = vport_table_lookup (&m_vportTable, vport);
407  if (vpe != 0)
408  {
409  NS_LOG_ERROR ("vport " << vport << " already exists!");
410  SendErrorMsg (OFPET_BAD_ACTION, OFPET_VPORT_MOD_FAILED, ovpm, ntohs (ovpm->header.length));
411  return EINVAL;
412  }
413 
414  // check whether actions are valid
415  uint16_t v_code = ofi::ValidateVPortActions (ovpm->actions, actions_len);
416  if (v_code != ACT_VALIDATION_OK)
417  {
418  SendErrorMsg (OFPET_BAD_ACTION, v_code, ovpm, ntohs (ovpm->header.length));
419  return EINVAL;
420  }
421 
422  vpe = vport_table_entry_alloc (actions_len);
423 
424  vpe->vport = vport;
425  vpe->parent_port = parent_port;
426  if (vport < OFPP_VP_START || vport > OFPP_VP_END)
427  {
428  NS_LOG_ERROR ("port " << vport << " is not in the virtual port range (" << OFPP_VP_START << "-" << OFPP_VP_END << ")");
429  SendErrorMsg (OFPET_BAD_ACTION, OFPET_VPORT_MOD_FAILED, ovpm, ntohs (ovpm->header.length));
430  free_vport_table_entry (vpe); // free allocated entry
431  return EINVAL;
432  }
433 
434  vpe->port_acts->actions_len = actions_len;
435  memcpy (vpe->port_acts->actions, ovpm->actions, actions_len);
436 
437  int error = insert_vport_table_entry (&m_vportTable, vpe);
438  if (error)
439  {
440  NS_LOG_ERROR ("could not insert port table entry for port " << vport);
441  }
442 
443  return error;
444 }
445 
446 ofpbuf *
447 OpenFlowSwitchNetDevice::BufferFromPacket (Ptr<Packet> packet, Address src, Address dst, int mtu, uint16_t protocol)
448 {
449  NS_LOG_INFO ("Creating Openflow buffer from packet.");
450 
451  /*
452  * Allocate buffer with some headroom to add headers in forwarding
453  * to the controller or adding a vlan tag, plus an extra 2 bytes to
454  * allow IP headers to be aligned on a 4-byte boundary.
455  */
456  const int headroom = 128 + 2;
457  const int hard_header = VLAN_ETH_HEADER_LEN;
458  ofpbuf *buffer = ofpbuf_new (headroom + hard_header + mtu);
459  buffer->data = (char*)buffer->data + headroom + hard_header;
460 
461  int l2_length = 0, l3_length = 0, l4_length = 0;
462 
463  // Load headers
464  EthernetHeader eth_hd;
465  if (packet->PeekHeader (eth_hd))
466  {
467  buffer->l2 = new eth_header;
468  eth_header* eth_h = (eth_header*)buffer->l2;
469  dst.CopyTo (eth_h->eth_dst); // Destination Mac Address
470  src.CopyTo (eth_h->eth_src); // Source Mac Address
471  eth_h->eth_type = htons (ETH_TYPE_IP); // Ether Type
472  NS_LOG_INFO ("Parsed EthernetHeader");
473 
474  l2_length = ETH_HEADER_LEN;
475  }
476 
477  // We have to wrap this because PeekHeader has an assert fail if we check for an Ipv4Header that isn't there.
478  if (protocol == Ipv4L3Protocol::PROT_NUMBER)
479  {
480  Ipv4Header ip_hd;
481  if (packet->PeekHeader (ip_hd))
482  {
483  buffer->l3 = new ip_header;
484  ip_header* ip_h = (ip_header*)buffer->l3;
485  ip_h->ip_ihl_ver = IP_IHL_VER (5, IP_VERSION); // Version
486  ip_h->ip_tos = ip_hd.GetTos (); // Type of Service/Differentiated Services
487  ip_h->ip_tot_len = packet->GetSize (); // Total Length
488  ip_h->ip_id = ip_hd.GetIdentification (); // Identification
489  ip_h->ip_frag_off = ip_hd.GetFragmentOffset (); // Fragment Offset
490  ip_h->ip_ttl = ip_hd.GetTtl (); // Time to Live
491  ip_h->ip_proto = ip_hd.GetProtocol (); // Protocol
492  ip_h->ip_src = htonl (ip_hd.GetSource ().Get ()); // Source Address
493  ip_h->ip_dst = htonl (ip_hd.GetDestination ().Get ()); // Destination Address
494  ip_h->ip_csum = csum (&ip_h, sizeof ip_h); // Header Checksum
495  NS_LOG_INFO ("Parsed Ipv4Header");
496 
497  l3_length = IP_HEADER_LEN;
498  }
499  }
500  else
501  {
502  // ARP Packet; the underlying OpenFlow header isn't used to match, so this is probably superfluous.
503  ArpHeader arp_hd;
504  if (packet->PeekHeader (arp_hd))
505  {
506  buffer->l3 = new arp_eth_header;
507  arp_eth_header* arp_h = (arp_eth_header*)buffer->l3;
508  arp_h->ar_hrd = ARP_HRD_ETHERNET; // Hardware type.
509  arp_h->ar_pro = ARP_PRO_IP; // Protocol type.
510  arp_h->ar_op = arp_hd.m_type; // Opcode.
511  arp_hd.GetDestinationHardwareAddress ().CopyTo (arp_h->ar_tha); // Target hardware address.
512  arp_hd.GetSourceHardwareAddress ().CopyTo (arp_h->ar_sha); // Sender hardware address.
513  arp_h->ar_tpa = arp_hd.GetDestinationIpv4Address ().Get (); // Target protocol address.
514  arp_h->ar_spa = arp_hd.GetSourceIpv4Address ().Get (); // Sender protocol address.
515  arp_h->ar_hln = sizeof arp_h->ar_tha; // Hardware address length.
516  arp_h->ar_pln = sizeof arp_h->ar_tpa; // Protocol address length.
517  NS_LOG_INFO ("Parsed ArpHeader");
518 
519  l3_length = ARP_ETH_HEADER_LEN;
520  }
521  }
522 
523  if (protocol == Ipv4L3Protocol::PROT_NUMBER)
524  {
525  ip_header* ip_h = (ip_header*)buffer->l3;
526  if (ip_h->ip_proto == TcpL4Protocol::PROT_NUMBER)
527  {
528  TcpHeader tcp_hd;
529  if (packet->PeekHeader (tcp_hd))
530  {
531  buffer->l4 = new tcp_header;
532  tcp_header* tcp_h = (tcp_header*)buffer->l4;
533  tcp_h->tcp_src = htons (tcp_hd.GetSourcePort ()); // Source Port
534  tcp_h->tcp_dst = htons (tcp_hd.GetDestinationPort ()); // Destination Port
535  tcp_h->tcp_seq = tcp_hd.GetSequenceNumber ().GetValue (); // Sequence Number
536  tcp_h->tcp_ack = tcp_hd.GetAckNumber ().GetValue (); // ACK Number
537  tcp_h->tcp_ctl = TCP_FLAGS (tcp_hd.GetFlags ()); // Data Offset + Reserved + Flags
538  tcp_h->tcp_winsz = tcp_hd.GetWindowSize (); // Window Size
539  tcp_h->tcp_urg = tcp_hd.GetUrgentPointer (); // Urgent Pointer
540  tcp_h->tcp_csum = csum (&tcp_h, sizeof tcp_h); // Header Checksum
541  NS_LOG_INFO ("Parsed TcpHeader");
542 
543  l4_length = TCP_HEADER_LEN;
544  }
545  }
546  else if (ip_h->ip_proto == UdpL4Protocol::PROT_NUMBER)
547  {
548  UdpHeader udp_hd;
549  if (packet->PeekHeader (udp_hd))
550  {
551  buffer->l4 = new udp_header;
552  udp_header* udp_h = (udp_header*)buffer->l4;
553  udp_h->udp_src = htons (udp_hd.GetSourcePort ()); // Source Port
554  udp_h->udp_dst = htons (udp_hd.GetDestinationPort ()); // Destination Port
555  udp_h->udp_len = htons (UDP_HEADER_LEN + packet->GetSize ());
556 
557  ip_header* ip_h = (ip_header*)buffer->l3;
558  uint32_t udp_csum = csum_add32 (0, ip_h->ip_src);
559  udp_csum = csum_add32 (udp_csum, ip_h->ip_dst);
560  udp_csum = csum_add16 (udp_csum, IP_TYPE_UDP << 8);
561  udp_csum = csum_add16 (udp_csum, udp_h->udp_len);
562  udp_csum = csum_continue (udp_csum, udp_h, sizeof udp_h);
563  udp_h->udp_csum = csum_finish (csum_continue (udp_csum, buffer->data, buffer->size)); // Header Checksum
564  NS_LOG_INFO ("Parsed UdpHeader");
565 
566  l4_length = UDP_HEADER_LEN;
567  }
568  }
569  }
570 
571  // Load Packet data into buffer data
572  packet->CopyData ((uint8_t*)buffer->data, packet->GetSize ());
573 
574  if (buffer->l4)
575  {
576  ofpbuf_push (buffer, buffer->l4, l4_length);
577  delete (tcp_header*)buffer->l4;
578  }
579  if (buffer->l3)
580  {
581  ofpbuf_push (buffer, buffer->l3, l3_length);
582  delete (ip_header*)buffer->l3;
583  }
584  if (buffer->l2)
585  {
586  ofpbuf_push (buffer, buffer->l2, l2_length);
587  delete (eth_header*)buffer->l2;
588  }
589 
590  return buffer;
591 }
592 
593 void
594 OpenFlowSwitchNetDevice::ReceiveFromDevice (Ptr<NetDevice> netdev, Ptr<const Packet> packet, uint16_t protocol,
595  const Address& src, const Address& dst, PacketType packetType)
596 {
598  NS_LOG_INFO ("--------------------------------------------");
599  NS_LOG_DEBUG ("UID is " << packet->GetUid ());
600 
601  if (!m_promiscRxCallback.IsNull ())
602  {
603  m_promiscRxCallback (this, packet, protocol, src, dst, packetType);
604  }
605 
606  Mac48Address dst48 = Mac48Address::ConvertFrom (dst);
607  NS_LOG_INFO ("Received packet from " << Mac48Address::ConvertFrom (src) << " looking for " << dst48);
608 
609  for (size_t i = 0; i < m_ports.size (); i++)
610  {
611  if (m_ports[i].netdev == netdev)
612  {
613  if (packetType == PACKET_HOST && dst48 == m_address)
614  {
615  m_rxCallback (this, packet, protocol, src);
616  }
617  else if (packetType == PACKET_BROADCAST || packetType == PACKET_MULTICAST || packetType == PACKET_OTHERHOST)
618  {
619  if (packetType == PACKET_OTHERHOST && dst48 == m_address)
620  {
621  m_rxCallback (this, packet, protocol, src);
622  }
623  else
624  {
625  if (packetType != PACKET_OTHERHOST)
626  {
627  m_rxCallback (this, packet, protocol, src);
628  }
629 
630  ofi::SwitchPacketMetadata data;
631  data.packet = packet->Copy ();
632 
633  ofpbuf *buffer = BufferFromPacket (data.packet,src,dst,netdev->GetMtu (),protocol);
634  m_ports[i].rx_packets++;
635  m_ports[i].rx_bytes += buffer->size;
636  data.buffer = buffer;
637  uint32_t packet_uid = save_buffer (buffer);
638 
639  data.protocolNumber = protocol;
640  data.src = Address (src);
641  data.dst = Address (dst);
642  m_packetData.insert (std::make_pair (packet_uid, data));
643 
644  RunThroughFlowTable (packet_uid, i);
645  }
646  }
647 
648  break;
649  }
650  }
651 
652  // Run periodic execution.
653  Time now = Simulator::Now ();
654  if (now >= Seconds (m_lastExecute.GetSeconds () + 1)) // If a second or more has passed from the simulation time, execute.
655  {
656  // If port status is modified in any way, notify the controller.
657  for (size_t i = 0; i < m_ports.size (); i++)
658  {
659  if (UpdatePortStatus (m_ports[i]))
660  {
661  SendPortStatus (m_ports[i], OFPPR_MODIFY);
662  }
663  }
664 
665  // If any flows have expired, delete them and notify the controller.
666  List deleted = LIST_INITIALIZER (&deleted);
667  sw_flow *f, *n;
668  chain_timeout (m_chain, &deleted);
669  LIST_FOR_EACH_SAFE (f, n, sw_flow, node, &deleted)
670  {
671  std::ostringstream str;
672  str << "Flow [";
673  for (int i = 0; i < 6; i++)
674  str << (i!=0 ? ":" : "") << std::hex << f->key.flow.dl_src[i]/16 << f->key.flow.dl_src[i]%16;
675  str << " -> ";
676  for (int i = 0; i < 6; i++)
677  str << (i!=0 ? ":" : "") << std::hex << f->key.flow.dl_dst[i]/16 << f->key.flow.dl_dst[i]%16;
678  str << "] expired.";
679 
680  NS_LOG_INFO (str.str ());
681  SendFlowExpired (f, (ofp_flow_expired_reason)f->reason);
682  list_remove (&f->node);
683  flow_free (f);
684  }
685 
686  m_lastExecute = now;
687  }
688 }
689 
690 int
691 OpenFlowSwitchNetDevice::OutputAll (uint32_t packet_uid, int in_port, bool flood)
692 {
694  NS_LOG_INFO ("Flooding over ports.");
695 
696  int prev_port = -1;
697  for (size_t i = 0; i < m_ports.size (); i++)
698  {
699  if (i == (unsigned)in_port) // Originating port
700  {
701  continue;
702  }
703  if (flood && m_ports[i].config & OFPPC_NO_FLOOD) // Port configured to not allow flooding
704  {
705  continue;
706  }
707  if (prev_port != -1)
708  {
709  OutputPort (packet_uid, in_port, prev_port, false);
710  }
711  prev_port = i;
712  }
713  if (prev_port != -1)
714  {
715  OutputPort (packet_uid, in_port, prev_port, false);
716  }
717 
718  return 0;
719 }
720 
721 void
722 OpenFlowSwitchNetDevice::OutputPacket (uint32_t packet_uid, int out_port)
723 {
724  if (out_port >= 0 && out_port < DP_MAX_PORTS)
725  {
726  ofi::Port& p = m_ports[out_port];
727  if (p.netdev != 0 && !(p.config & OFPPC_PORT_DOWN))
728  {
729  ofi::SwitchPacketMetadata data = m_packetData.find (packet_uid)->second;
730  size_t bufsize = data.buffer->size;
731  NS_LOG_INFO ("Sending packet " << data.packet->GetUid () << " over port " << out_port);
732  if (p.netdev->SendFrom (data.packet->Copy (), data.src, data.dst, data.protocolNumber))
733  {
734  p.tx_packets++;
735  p.tx_bytes += bufsize;
736  }
737  else
738  {
739  p.tx_dropped++;
740  }
741  return;
742  }
743  }
744 
745  NS_LOG_DEBUG ("can't forward to bad port " << out_port);
746 }
747 
748 void
749 OpenFlowSwitchNetDevice::OutputPort (uint32_t packet_uid, int in_port, int out_port, bool ignore_no_fwd)
750 {
752 
753  if (out_port == OFPP_FLOOD)
754  {
755  OutputAll (packet_uid, in_port, true);
756  }
757  else if (out_port == OFPP_ALL)
758  {
759  OutputAll (packet_uid, in_port, false);
760  }
761  else if (out_port == OFPP_CONTROLLER)
762  {
763  OutputControl (packet_uid, in_port, 0, OFPR_ACTION);
764  }
765  else if (out_port == OFPP_IN_PORT)
766  {
767  OutputPacket (packet_uid, in_port);
768  }
769  else if (out_port == OFPP_TABLE)
770  {
771  RunThroughFlowTable (packet_uid, in_port < DP_MAX_PORTS ? in_port : -1, false);
772  }
773  else if (out_port >= OFPP_VP_START && out_port <= OFPP_VP_END)
774  {
775  // port is a virtual port
776  NS_LOG_INFO ("packet sent to virtual port " << out_port);
777  if (in_port < DP_MAX_PORTS)
778  {
779  RunThroughVPortTable (packet_uid, in_port, out_port);
780  }
781  else
782  {
783  RunThroughVPortTable (packet_uid, -1, out_port);
784  }
785  }
786  else if (in_port == out_port)
787  {
788  NS_LOG_DEBUG ("can't directly forward to input port");
789  }
790  else
791  {
792  OutputPacket (packet_uid, out_port);
793  }
794 }
795 
796 void*
797 OpenFlowSwitchNetDevice::MakeOpenflowReply (size_t openflow_len, uint8_t type, ofpbuf **bufferp)
798 {
799  return make_openflow_xid (openflow_len, type, 0, bufferp);
800 }
801 
802 int
803 OpenFlowSwitchNetDevice::SendOpenflowBuffer (ofpbuf *buffer)
804 {
805  if (m_controller != 0)
806  {
807  update_openflow_length (buffer);
808  m_controller->ReceiveFromSwitch (this, buffer);
809  }
810 
811  return 0;
812 }
813 
814 void
815 OpenFlowSwitchNetDevice::OutputControl (uint32_t packet_uid, int in_port, size_t max_len, int reason)
816 {
817  NS_LOG_INFO ("Sending packet to controller");
818 
819  ofpbuf* buffer = m_packetData.find (packet_uid)->second.buffer;
820  size_t total_len = buffer->size;
821  if (packet_uid != std::numeric_limits<uint32_t>::max () && max_len != 0 && buffer->size > max_len)
822  {
823  buffer->size = max_len;
824  }
825 
826  ofp_packet_in *opi = (ofp_packet_in*)ofpbuf_push_uninit (buffer, offsetof (ofp_packet_in, data));
827  opi->header.version = OFP_VERSION;
828  opi->header.type = OFPT_PACKET_IN;
829  opi->header.length = htons (buffer->size);
830  opi->header.xid = htonl (0);
831  opi->buffer_id = htonl (packet_uid);
832  opi->total_len = htons (total_len);
833  opi->in_port = htons (in_port);
834  opi->reason = reason;
835  opi->pad = 0;
836  SendOpenflowBuffer (buffer);
837 }
838 
839 void
840 OpenFlowSwitchNetDevice::FillPortDesc (ofi::Port p, ofp_phy_port *desc)
841 {
842  desc->port_no = htons (GetSwitchPortIndex (p));
843 
844  std::ostringstream nm;
845  nm << "eth" << GetSwitchPortIndex (p);
846  strncpy ((char *)desc->name, nm.str ().c_str (), sizeof desc->name);
847 
848  p.netdev->GetAddress ().CopyTo (desc->hw_addr);
849  desc->config = htonl (p.config);
850  desc->state = htonl (p.state);
851 
853  desc->curr = 0; // htonl(netdev_get_features(p->netdev, NETDEV_FEAT_CURRENT));
854  desc->supported = 0; // htonl(netdev_get_features(p->netdev, NETDEV_FEAT_SUPPORTED));
855  desc->advertised = 0; // htonl(netdev_get_features(p->netdev, NETDEV_FEAT_ADVERTISED));
856  desc->peer = 0; // htonl(netdev_get_features(p->netdev, NETDEV_FEAT_PEER));
857 }
858 
859 void
860 OpenFlowSwitchNetDevice::SendFeaturesReply ()
861 {
862  ofpbuf *buffer;
863  ofp_switch_features *ofr = (ofp_switch_features*)MakeOpenflowReply (sizeof *ofr, OFPT_FEATURES_REPLY, &buffer);
864  ofr->datapath_id = htonll (m_id);
865  ofr->n_tables = m_chain->n_tables;
866  ofr->n_buffers = htonl (N_PKT_BUFFERS);
867  ofr->capabilities = htonl (OFP_SUPPORTED_CAPABILITIES);
868  ofr->actions = htonl (OFP_SUPPORTED_ACTIONS);
869 
870  for (size_t i = 0; i < m_ports.size (); i++)
871  {
872  ofp_phy_port* opp = (ofp_phy_port*)ofpbuf_put_zeros (buffer, sizeof *opp);
873  FillPortDesc (m_ports[i], opp);
874  }
875 
876  SendOpenflowBuffer (buffer);
877 }
878 
879 void
880 OpenFlowSwitchNetDevice::SendVPortTableFeatures ()
881 {
882  ofpbuf *buffer;
883  ofp_vport_table_features *ovtfr = (ofp_vport_table_features*)MakeOpenflowReply (sizeof *ovtfr, OFPT_VPORT_TABLE_FEATURES_REPLY, &buffer);
884  ovtfr->actions = htonl (OFP_SUPPORTED_VPORT_TABLE_ACTIONS);
885  ovtfr->max_vports = htonl (m_vportTable.max_vports);
886  ovtfr->max_chain_depth = htons (-1); // support a chain depth of 2^16
887  ovtfr->mixed_chaining = true;
888  SendOpenflowBuffer (buffer);
889 }
890 
891 int
892 OpenFlowSwitchNetDevice::UpdatePortStatus (ofi::Port& p)
893 {
894  uint32_t orig_config = p.config;
895  uint32_t orig_state = p.state;
896 
897  // Port is always enabled because the Net Device is always enabled.
898  p.config &= ~OFPPC_PORT_DOWN;
899 
900  if (p.netdev->IsLinkUp ())
901  {
902  p.state &= ~OFPPS_LINK_DOWN;
903  }
904  else
905  {
906  p.state |= OFPPS_LINK_DOWN;
907  }
908 
909  return ((orig_config != p.config) || (orig_state != p.state));
910 }
911 
912 void
913 OpenFlowSwitchNetDevice::SendPortStatus (ofi::Port p, uint8_t status)
914 {
915  ofpbuf *buffer;
916  ofp_port_status *ops = (ofp_port_status*)MakeOpenflowReply (sizeof *ops, OFPT_PORT_STATUS, &buffer);
917  ops->reason = status;
918  memset (ops->pad, 0, sizeof ops->pad);
919  FillPortDesc (p, &ops->desc);
920 
921  SendOpenflowBuffer (buffer);
922  ofpbuf_delete (buffer);
923 }
924 
925 void
926 OpenFlowSwitchNetDevice::SendFlowExpired (sw_flow *flow, enum ofp_flow_expired_reason reason)
927 {
928  ofpbuf *buffer;
929  ofp_flow_expired *ofe = (ofp_flow_expired*)MakeOpenflowReply (sizeof *ofe, OFPT_FLOW_EXPIRED, &buffer);
930  flow_fill_match (&ofe->match, &flow->key);
931 
932  ofe->priority = htons (flow->priority);
933  ofe->reason = reason;
934  memset (ofe->pad, 0, sizeof ofe->pad);
935 
936  ofe->duration = htonl (time_now () - flow->created);
937  memset (ofe->pad2, 0, sizeof ofe->pad2);
938  ofe->packet_count = htonll (flow->packet_count);
939  ofe->byte_count = htonll (flow->byte_count);
940  SendOpenflowBuffer (buffer);
941 }
942 
943 void
944 OpenFlowSwitchNetDevice::SendErrorMsg (uint16_t type, uint16_t code, const void *data, size_t len)
945 {
946  ofpbuf *buffer;
947  ofp_error_msg *oem = (ofp_error_msg*)MakeOpenflowReply (sizeof(*oem) + len, OFPT_ERROR, &buffer);
948  oem->type = htons (type);
949  oem->code = htons (code);
950  memcpy (oem->data, data, len);
951  SendOpenflowBuffer (buffer);
952 }
953 
954 void
955 OpenFlowSwitchNetDevice::FlowTableLookup (sw_flow_key key, ofpbuf* buffer, uint32_t packet_uid, int port, bool send_to_controller)
956 {
957  sw_flow *flow = chain_lookup (m_chain, &key);
958  if (flow != 0)
959  {
960  NS_LOG_INFO ("Flow matched");
961  flow_used (flow, buffer);
962  ofi::ExecuteActions (this, packet_uid, buffer, &key, flow->sf_acts->actions, flow->sf_acts->actions_len, false);
963  }
964  else
965  {
966  NS_LOG_INFO ("Flow not matched.");
967 
968  if (send_to_controller)
969  {
970  OutputControl (packet_uid, port, m_missSendLen, OFPR_NO_MATCH);
971  }
972  }
973 
974  // Clean up; at this point we're done with the packet.
975  m_packetData.erase (packet_uid);
976  discard_buffer (packet_uid);
977  ofpbuf_delete (buffer);
978 }
979 
980 void
981 OpenFlowSwitchNetDevice::RunThroughFlowTable (uint32_t packet_uid, int port, bool send_to_controller)
982 {
983  ofi::SwitchPacketMetadata data = m_packetData.find (packet_uid)->second;
984  ofpbuf* buffer = data.buffer;
985 
986  sw_flow_key key;
987  key.wildcards = 0; // Lookup cannot take wildcards.
988  // Extract the matching key's flow data from the packet's headers; if the policy is to drop fragments and the message is a fragment, drop it.
989  if (flow_extract (buffer, port != -1 ? port : OFPP_NONE, &key.flow) && (m_flags & OFPC_FRAG_MASK) == OFPC_FRAG_DROP)
990  {
991  ofpbuf_delete (buffer);
992  return;
993  }
994 
995  // drop MPLS packets with TTL 1
996  if (buffer->l2_5)
997  {
998  mpls_header mpls_h;
999  mpls_h.value = ntohl (*((uint32_t*)buffer->l2_5));
1000  if (mpls_h.ttl == 1)
1001  {
1002  // increment mpls drop counter
1003  if (port != -1)
1004  {
1005  m_ports[port].mpls_ttl0_dropped++;
1006  }
1007  return;
1008  }
1009  }
1010 
1011  // If we received the packet on a port, and opted not to receive any messages from it...
1012  if (port != -1)
1013  {
1014  uint32_t config = m_ports[port].config;
1015  if (config & (OFPPC_NO_RECV | OFPPC_NO_RECV_STP)
1016  && config & (!eth_addr_equals (key.flow.dl_dst, stp_eth_addr) ? OFPPC_NO_RECV : OFPPC_NO_RECV_STP))
1017  {
1018  return;
1019  }
1020  }
1021 
1022  NS_LOG_INFO ("Matching against the flow table.");
1023  Simulator::Schedule (m_lookupDelay, &OpenFlowSwitchNetDevice::FlowTableLookup, this, key, buffer, packet_uid, port, send_to_controller);
1024 }
1025 
1026 int
1027 OpenFlowSwitchNetDevice::RunThroughVPortTable (uint32_t packet_uid, int port, uint32_t vport)
1028 {
1029  ofpbuf* buffer = m_packetData.find (packet_uid)->second.buffer;
1030 
1031  // extract the flow again since we need it
1032  // and the layer pointers may changed
1033  sw_flow_key key;
1034  key.wildcards = 0;
1035  if (flow_extract (buffer, port != -1 ? port : OFPP_NONE, &key.flow)
1036  && (m_flags & OFPC_FRAG_MASK) == OFPC_FRAG_DROP)
1037  {
1038  return 0;
1039  }
1040 
1041  // run through the chain of port table entries
1042  vport_table_entry *vpe = vport_table_lookup (&m_vportTable, vport);
1043  m_vportTable.lookup_count++;
1044  if (vpe)
1045  {
1046  m_vportTable.port_match_count++;
1047  }
1048  while (vpe != 0)
1049  {
1050  ofi::ExecuteVPortActions (this, packet_uid, m_packetData.find (packet_uid)->second.buffer, &key, vpe->port_acts->actions, vpe->port_acts->actions_len);
1051  vport_used (vpe, buffer); // update counters for virtual port
1052  if (vpe->parent_port_ptr == 0)
1053  {
1054  // if a port table's parent_port_ptr is 0 then
1055  // the parent_port should be a physical port
1056  if (vpe->parent_port <= OFPP_VP_START) // done traversing port chain, send packet to output port
1057  {
1058  OutputPort (packet_uid, port != -1 ? port : OFPP_NONE, vpe->parent_port, false);
1059  }
1060  else
1061  {
1062  NS_LOG_ERROR ("virtual port points to parent port\n");
1063  }
1064  }
1065  else // increment the number of port entries accessed by chaining
1066  {
1067  m_vportTable.chain_match_count++;
1068  }
1069  // move to the parent port entry
1070  vpe = vpe->parent_port_ptr;
1071  }
1072 
1073  return 0;
1074 }
1075 
1076 int
1077 OpenFlowSwitchNetDevice::ReceiveFeaturesRequest (const void *msg)
1078 {
1079  SendFeaturesReply ();
1080  return 0;
1081 }
1082 
1083 int
1084 OpenFlowSwitchNetDevice::ReceiveVPortTableFeaturesRequest (const void *msg)
1085 {
1086  SendVPortTableFeatures ();
1087  return 0;
1088 }
1089 
1090 int
1091 OpenFlowSwitchNetDevice::ReceiveGetConfigRequest (const void *msg)
1092 {
1093  ofpbuf *buffer;
1094  ofp_switch_config *osc = (ofp_switch_config*)MakeOpenflowReply (sizeof *osc, OFPT_GET_CONFIG_REPLY, &buffer);
1095  osc->flags = htons (m_flags);
1096  osc->miss_send_len = htons (m_missSendLen);
1097 
1098  return SendOpenflowBuffer (buffer);
1099 }
1100 
1101 int
1102 OpenFlowSwitchNetDevice::ReceiveSetConfig (const void *msg)
1103 {
1104  const ofp_switch_config *osc = (ofp_switch_config*)msg;
1105 
1106  int n_flags = ntohs (osc->flags) & (OFPC_SEND_FLOW_EXP | OFPC_FRAG_MASK);
1107  if ((n_flags & OFPC_FRAG_MASK) != OFPC_FRAG_NORMAL && (n_flags & OFPC_FRAG_MASK) != OFPC_FRAG_DROP)
1108  {
1109  n_flags = (n_flags & ~OFPC_FRAG_MASK) | OFPC_FRAG_DROP;
1110  }
1111 
1112  m_flags = n_flags;
1113  m_missSendLen = ntohs (osc->miss_send_len);
1114  return 0;
1115 }
1116 
1117 int
1118 OpenFlowSwitchNetDevice::ReceivePacketOut (const void *msg)
1119 {
1120  const ofp_packet_out *opo = (ofp_packet_out*)msg;
1121  ofpbuf *buffer;
1122  size_t actions_len = ntohs (opo->actions_len);
1123 
1124  if (actions_len > (ntohs (opo->header.length) - sizeof *opo))
1125  {
1126  NS_LOG_DEBUG ("message too short for number of actions");
1127  return -EINVAL;
1128  }
1129 
1130  if (ntohl (opo->buffer_id) == (uint32_t) -1)
1131  {
1132  // FIXME: can we avoid copying data here?
1133  int data_len = ntohs (opo->header.length) - sizeof *opo - actions_len;
1134  buffer = ofpbuf_new (data_len);
1135  ofpbuf_put (buffer, (uint8_t *)opo->actions + actions_len, data_len);
1136  }
1137  else
1138  {
1139  buffer = retrieve_buffer (ntohl (opo->buffer_id));
1140  if (buffer == 0)
1141  {
1142  return -ESRCH;
1143  }
1144  }
1145 
1146  sw_flow_key key;
1147  flow_extract (buffer, opo->in_port, &key.flow); // ntohs(opo->in_port)
1148 
1149  uint16_t v_code = ofi::ValidateActions (&key, opo->actions, actions_len);
1150  if (v_code != ACT_VALIDATION_OK)
1151  {
1152  SendErrorMsg (OFPET_BAD_ACTION, v_code, msg, ntohs (opo->header.length));
1153  ofpbuf_delete (buffer);
1154  return -EINVAL;
1155  }
1156 
1157  ofi::ExecuteActions (this, opo->buffer_id, buffer, &key, opo->actions, actions_len, true);
1158  return 0;
1159 }
1160 
1161 int
1162 OpenFlowSwitchNetDevice::ReceivePortMod (const void *msg)
1163 {
1164  ofp_port_mod* opm = (ofp_port_mod*)msg;
1165 
1166  int port = opm->port_no; // ntohs(opm->port_no);
1167  if (port < DP_MAX_PORTS)
1168  {
1169  ofi::Port& p = m_ports[port];
1170 
1171  // Make sure the port id hasn't changed since this was sent
1172  Mac48Address hw_addr = Mac48Address ();
1173  hw_addr.CopyFrom (opm->hw_addr);
1174  if (p.netdev->GetAddress () != hw_addr)
1175  {
1176  return 0;
1177  }
1178 
1179  if (opm->mask)
1180  {
1181  uint32_t config_mask = ntohl (opm->mask);
1182  p.config &= ~config_mask;
1183  p.config |= ntohl (opm->config) & config_mask;
1184  }
1185 
1186  if (opm->mask & htonl (OFPPC_PORT_DOWN))
1187  {
1188  if ((opm->config & htonl (OFPPC_PORT_DOWN)) && (p.config & OFPPC_PORT_DOWN) == 0)
1189  {
1190  p.config |= OFPPC_PORT_DOWN;
1192  }
1193  else if ((opm->config & htonl (OFPPC_PORT_DOWN)) == 0 && (p.config & OFPPC_PORT_DOWN))
1194  {
1195  p.config &= ~OFPPC_PORT_DOWN;
1197  }
1198  }
1199  }
1200 
1201  return 0;
1202 }
1203 
1204 // add or remove a virtual port table entry
1205 int
1206 OpenFlowSwitchNetDevice::ReceiveVPortMod (const void *msg)
1207 {
1208  const ofp_vport_mod *ovpm = (ofp_vport_mod*)msg;
1209 
1210  uint16_t command = ntohs (ovpm->command);
1211  if (command == OFPVP_ADD)
1212  {
1213  return AddVPort (ovpm);
1214  }
1215  else if (command == OFPVP_DELETE)
1216  {
1217  if (remove_vport_table_entry (&m_vportTable, ntohl (ovpm->vport)))
1218  {
1219  SendErrorMsg (OFPET_BAD_ACTION, OFPET_VPORT_MOD_FAILED, ovpm, ntohs (ovpm->header.length));
1220  }
1221  }
1222 
1223  return 0;
1224 }
1225 
1226 int
1227 OpenFlowSwitchNetDevice::AddFlow (const ofp_flow_mod *ofm)
1228 {
1229  size_t actions_len = ntohs (ofm->header.length) - sizeof *ofm;
1230 
1231  // Allocate memory.
1232  sw_flow *flow = flow_alloc (actions_len);
1233  if (flow == 0)
1234  {
1235  if (ntohl (ofm->buffer_id) != (uint32_t) -1)
1236  {
1237  discard_buffer (ntohl (ofm->buffer_id));
1238  }
1239  return -ENOMEM;
1240  }
1241 
1242  flow_extract_match (&flow->key, &ofm->match);
1243 
1244  uint16_t v_code = ofi::ValidateActions (&flow->key, ofm->actions, actions_len);
1245  if (v_code != ACT_VALIDATION_OK)
1246  {
1247  SendErrorMsg (OFPET_BAD_ACTION, v_code, ofm, ntohs (ofm->header.length));
1248  flow_free (flow);
1249  if (ntohl (ofm->buffer_id) != (uint32_t) -1)
1250  {
1251  discard_buffer (ntohl (ofm->buffer_id));
1252  }
1253  return -ENOMEM;
1254  }
1255 
1256  // Fill out flow.
1257  flow->priority = flow->key.wildcards ? ntohs (ofm->priority) : -1;
1258  flow->idle_timeout = ntohs (ofm->idle_timeout);
1259  flow->hard_timeout = ntohs (ofm->hard_timeout);
1260  flow->used = flow->created = time_now ();
1261  flow->sf_acts->actions_len = actions_len;
1262  flow->byte_count = 0;
1263  flow->packet_count = 0;
1264  memcpy (flow->sf_acts->actions, ofm->actions, actions_len);
1265 
1266  // Act.
1267  int error = chain_insert (m_chain, flow);
1268  if (error)
1269  {
1270  if (error == -ENOBUFS)
1271  {
1272  SendErrorMsg (OFPET_FLOW_MOD_FAILED, OFPFMFC_ALL_TABLES_FULL, ofm, ntohs (ofm->header.length));
1273  }
1274  flow_free (flow);
1275  if (ntohl (ofm->buffer_id) != (uint32_t) -1)
1276  {
1277  discard_buffer (ntohl (ofm->buffer_id));
1278  }
1279  return error;
1280  }
1281 
1282  NS_LOG_INFO ("Added new flow.");
1283  if (ntohl (ofm->buffer_id) != std::numeric_limits<uint32_t>::max ())
1284  {
1285  ofpbuf *buffer = retrieve_buffer (ofm->buffer_id); // ntohl(ofm->buffer_id)
1286  if (buffer)
1287  {
1288  sw_flow_key key;
1289  flow_used (flow, buffer);
1290  flow_extract (buffer, ofm->match.in_port, &key.flow); // ntohs(ofm->match.in_port);
1291  ofi::ExecuteActions (this, ofm->buffer_id, buffer, &key, ofm->actions, actions_len, false);
1292  ofpbuf_delete (buffer);
1293  }
1294  else
1295  {
1296  return -ESRCH;
1297  }
1298  }
1299  return 0;
1300 }
1301 
1302 int
1303 OpenFlowSwitchNetDevice::ModFlow (const ofp_flow_mod *ofm)
1304 {
1305  sw_flow_key key;
1306  flow_extract_match (&key, &ofm->match);
1307 
1308  size_t actions_len = ntohs (ofm->header.length) - sizeof *ofm;
1309 
1310  uint16_t v_code = ofi::ValidateActions (&key, ofm->actions, actions_len);
1311  if (v_code != ACT_VALIDATION_OK)
1312  {
1313  SendErrorMsg ((ofp_error_type)OFPET_BAD_ACTION, v_code, ofm, ntohs (ofm->header.length));
1314  if (ntohl (ofm->buffer_id) != (uint32_t) -1)
1315  {
1316  discard_buffer (ntohl (ofm->buffer_id));
1317  }
1318  return -ENOMEM;
1319  }
1320 
1321  uint16_t priority = key.wildcards ? ntohs (ofm->priority) : -1;
1322  int strict = (ofm->command == htons (OFPFC_MODIFY_STRICT)) ? 1 : 0;
1323  chain_modify (m_chain, &key, priority, strict, ofm->actions, actions_len);
1324 
1325  if (ntohl (ofm->buffer_id) != std::numeric_limits<uint32_t>::max ())
1326  {
1327  ofpbuf *buffer = retrieve_buffer (ofm->buffer_id); // ntohl (ofm->buffer_id)
1328  if (buffer)
1329  {
1330  sw_flow_key skb_key;
1331  flow_extract (buffer, ofm->match.in_port, &skb_key.flow); // ntohs(ofm->match.in_port);
1332  ofi::ExecuteActions (this, ofm->buffer_id, buffer, &skb_key, ofm->actions, actions_len, false);
1333  ofpbuf_delete (buffer);
1334  }
1335  else
1336  {
1337  return -ESRCH;
1338  }
1339  }
1340  return 0;
1341 }
1342 
1343 int
1344 OpenFlowSwitchNetDevice::ReceiveFlow (const void *msg)
1345 {
1347  const ofp_flow_mod *ofm = (ofp_flow_mod*)msg;
1348  uint16_t command = ntohs (ofm->command);
1349 
1350  if (command == OFPFC_ADD)
1351  {
1352  return AddFlow (ofm);
1353  }
1354  else if ((command == OFPFC_MODIFY) || (command == OFPFC_MODIFY_STRICT))
1355  {
1356  return ModFlow (ofm);
1357  }
1358  else if (command == OFPFC_DELETE)
1359  {
1360  sw_flow_key key;
1361  flow_extract_match (&key, &ofm->match);
1362  return chain_delete (m_chain, &key, ofm->out_port, 0, 0) ? 0 : -ESRCH;
1363  }
1364  else if (command == OFPFC_DELETE_STRICT)
1365  {
1366  sw_flow_key key;
1367  uint16_t priority;
1368  flow_extract_match (&key, &ofm->match);
1369  priority = key.wildcards ? ntohs (ofm->priority) : -1;
1370  return chain_delete (m_chain, &key, ofm->out_port, priority, 1) ? 0 : -ESRCH;
1371  }
1372  else
1373  {
1374  return -ENODEV;
1375  }
1376 }
1377 
1378 int
1379 OpenFlowSwitchNetDevice::StatsDump (ofi::StatsDumpCallback *cb)
1380 {
1381  ofp_stats_reply *osr;
1382  ofpbuf *buffer;
1383  int err;
1384 
1385  if (cb->done)
1386  {
1387  return 0;
1388  }
1389 
1390  osr = (ofp_stats_reply*)MakeOpenflowReply (sizeof *osr, OFPT_STATS_REPLY, &buffer);
1391  osr->type = htons (cb->s->type);
1392  osr->flags = 0;
1393 
1394  err = cb->s->DoDump (this, cb->state, buffer);
1395  if (err >= 0)
1396  {
1397  if (err == 0)
1398  {
1399  cb->done = true;
1400  }
1401  else
1402  {
1403  // Buffer might have been reallocated, so find our data again.
1404  osr = (ofp_stats_reply*)ofpbuf_at_assert (buffer, 0, sizeof *osr);
1405  osr->flags = ntohs (OFPSF_REPLY_MORE);
1406  }
1407 
1408  int err2 = SendOpenflowBuffer (buffer);
1409  if (err2)
1410  {
1411  err = err2;
1412  }
1413  }
1414 
1415  return err;
1416 }
1417 
1418 void
1419 OpenFlowSwitchNetDevice::StatsDone (ofi::StatsDumpCallback *cb)
1420 {
1421  if (cb)
1422  {
1423  cb->s->DoCleanup (cb->state);
1424  free (cb->s);
1425  free (cb);
1426  }
1427 }
1428 
1429 int
1430 OpenFlowSwitchNetDevice::ReceiveStatsRequest (const void *oh)
1431 {
1432  const ofp_stats_request *rq = (ofp_stats_request*)oh;
1433  size_t rq_len = ntohs (rq->header.length);
1434  int type = ntohs (rq->type);
1435  int body_len = rq_len - offsetof (ofp_stats_request, body);
1436  ofi::Stats* st = new ofi::Stats ((ofp_stats_types)type, (unsigned)body_len);
1437 
1438  if (st == 0)
1439  {
1440  return -EINVAL;
1441  }
1442 
1443  ofi::StatsDumpCallback cb;
1444  cb.done = false;
1445  cb.rq = (ofp_stats_request*)xmemdup (rq, rq_len);
1446  cb.s = st;
1447  cb.state = 0;
1448  cb.swtch = this;
1449 
1450  if (cb.s)
1451  {
1452  int err = cb.s->DoInit (rq->body, body_len, &cb.state);
1453  if (err)
1454  {
1455  NS_LOG_WARN ("failed initialization of stats request type " << type << ": " << strerror (-err));
1456  free (cb.rq);
1457  return err;
1458  }
1459  }
1460 
1461  if (m_controller != 0)
1462  {
1463  m_controller->StartDump (&cb);
1464  }
1465  else
1466  {
1467  NS_LOG_ERROR ("Switch needs to be registered to a controller in order to start the stats reply.");
1468  }
1469 
1470  return 0;
1471 }
1472 
1473 int
1474 OpenFlowSwitchNetDevice::ReceiveEchoRequest (const void *oh)
1475 {
1476  return SendOpenflowBuffer (make_echo_reply ((ofp_header*)oh));
1477 }
1478 
1479 int
1480 OpenFlowSwitchNetDevice::ReceiveEchoReply (const void *oh)
1481 {
1482  return 0;
1483 }
1484 
1485 int
1486 OpenFlowSwitchNetDevice::ForwardControlInput (const void *msg, size_t length)
1487 {
1488  // Check encapsulated length.
1489  ofp_header *oh = (ofp_header*) msg;
1490  if (ntohs (oh->length) > length)
1491  {
1492  return -EINVAL;
1493  }
1494  assert (oh->version == OFP_VERSION);
1495 
1496  int error = 0;
1497 
1498  // Figure out how to handle it.
1499  switch (oh->type)
1500  {
1501  case OFPT_FEATURES_REQUEST:
1502  error = length < sizeof(ofp_header) ? -EFAULT : ReceiveFeaturesRequest (msg);
1503  break;
1504  case OFPT_GET_CONFIG_REQUEST:
1505  error = length < sizeof(ofp_header) ? -EFAULT : ReceiveGetConfigRequest (msg);
1506  break;
1507  case OFPT_SET_CONFIG:
1508  error = length < sizeof(ofp_switch_config) ? -EFAULT : ReceiveSetConfig (msg);
1509  break;
1510  case OFPT_PACKET_OUT:
1511  error = length < sizeof(ofp_packet_out) ? -EFAULT : ReceivePacketOut (msg);
1512  break;
1513  case OFPT_FLOW_MOD:
1514  error = length < sizeof(ofp_flow_mod) ? -EFAULT : ReceiveFlow (msg);
1515  break;
1516  case OFPT_PORT_MOD:
1517  error = length < sizeof(ofp_port_mod) ? -EFAULT : ReceivePortMod (msg);
1518  break;
1519  case OFPT_STATS_REQUEST:
1520  error = length < sizeof(ofp_stats_request) ? -EFAULT : ReceiveStatsRequest (msg);
1521  break;
1522  case OFPT_ECHO_REQUEST:
1523  error = length < sizeof(ofp_header) ? -EFAULT : ReceiveEchoRequest (msg);
1524  break;
1525  case OFPT_ECHO_REPLY:
1526  error = length < sizeof(ofp_header) ? -EFAULT : ReceiveEchoReply (msg);
1527  break;
1528  case OFPT_VPORT_MOD:
1529  error = length < sizeof(ofp_vport_mod) ? -EFAULT : ReceiveVPortMod (msg);
1530  break;
1531  case OFPT_VPORT_TABLE_FEATURES_REQUEST:
1532  error = length < sizeof(ofp_header) ? -EFAULT : ReceiveVPortTableFeaturesRequest (msg);
1533  break;
1534  default:
1535  SendErrorMsg ((ofp_error_type)OFPET_BAD_REQUEST, (ofp_bad_request_code)OFPBRC_BAD_TYPE, msg, length);
1536  error = -EINVAL;
1537  }
1538 
1539  if (msg != 0)
1540  {
1541  free ((ofpbuf*)msg);
1542  }
1543  return error;
1544 }
1545 
1546 sw_chain*
1547 OpenFlowSwitchNetDevice::GetChain ()
1548 {
1549  return m_chain;
1550 }
1551 
1552 uint32_t
1553 OpenFlowSwitchNetDevice::GetNSwitchPorts (void) const
1554 {
1556  return m_ports.size ();
1557 }
1558 
1559 ofi::Port
1560 OpenFlowSwitchNetDevice::GetSwitchPort (uint32_t n) const
1561 {
1563  return m_ports[n];
1564 }
1565 
1566 int
1567 OpenFlowSwitchNetDevice::GetSwitchPortIndex (ofi::Port p)
1568 {
1569  for (size_t i = 0; i < m_ports.size (); i++)
1570  {
1571  if (m_ports[i].netdev == p.netdev)
1572  {
1573  return i;
1574  }
1575  }
1576  return -1;
1577 }
1578 
1579 vport_table_t
1580 OpenFlowSwitchNetDevice::GetVPortTable ()
1581 {
1582  return m_vportTable;
1583 }
1584 
1585 } // namespace ns3
1586 
1587 #endif // NS3_OPENFLOW
void discard_buffer(uint32_t id)
#define N_PKT_BUFFERS
#define NS_LOG_FUNCTION(parameters)
If log level LOG_FUNCTION is enabled, this macro will output all input parameters separated by "...
TypeId AddConstructor(void)
Definition: type-id.h:460
void ExecuteActions(Ptr< OpenFlowSwitchNetDevice > swtch, uint64_t packet_uid, ofpbuf *buffer, sw_flow_key *key, const ofp_action_header *actions, size_t actions_len, int ignore_no_fwd)
Executes a list of flow table actions.
#define NS_OBJECT_ENSURE_REGISTERED(type)
Register an Object subclass with the TypeId system.
Definition: object-base.h:44
static const char * GetSerialNumber()
uint16_t m_flags
Flags; configurable by the controller.
bool IsMulticast(const Address &ad)
Address family-independent test for a multicast address.
#define NS_ASSERT(condition)
At runtime, in debugging builds, if this condition is not true, the program prints the source file...
Definition: assert.h:67
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition: log.h:201
static const char * GetHardwareDescription()
#define NS_LOG_INFO(msg)
Use NS_LOG to output a message of level LOG_INFO.
Definition: log.h:244
#define NS_FATAL_ERROR(msg)
Fatal error handling.
Definition: fatal-error.h:100
#define NS_LOG_FUNCTION_NOARGS()
Output the name of the function.
ofpbuf * retrieve_buffer(uint32_t id)
uint16_t port
Definition: dsdv-manet.cc:44
Ptr< const AttributeChecker > MakeTimeChecker(const Time min, const Time max)
Helper to make a Time checker with bounded range.
Definition: time.cc:446
static TypeId GetTypeId(void)
Time NanoSeconds(uint64_t value)
Construct a Time in the indicated unit.
Definition: nstime.h:890
static const char * GetManufacturerDescription()
void ExecuteVPortActions(Ptr< OpenFlowSwitchNetDevice > swtch, uint64_t packet_uid, ofpbuf *buffer, sw_flow_key *key, const ofp_action_header *actions, size_t actions_len)
Executes a list of virtual port table entry actions.
uint8_t data[writeSize]
uint64_t m_id
Unique identifier for this switch, needed for OpenFlow.
#define OFP_SUPPORTED_ACTIONS
Callback< R > MakeCallback(R(T::*memPtr)(void), OBJ objPtr)
Definition: callback.h:1296
uint32_t save_buffer(ofpbuf *)
static const char * GetSoftwareDescription()
#define OFP_SUPPORTED_VPORT_TABLE_ACTIONS
Every class exported by the ns3 library is enclosed in the ns3 namespace.
Ptr< const AttributeAccessor > MakeTimeAccessor(T1 a1)
Create an AttributeAccessor for a class data member, or a lone class get functor or set method...
Definition: nstime.h:929
uint16_t ValidateActions(const sw_flow_key *key, const ofp_action_header *actions, size_t actions_len)
Validates a list of flow table actions.
#define NS_LOG_WARN(msg)
Use NS_LOG to output a message of level LOG_WARN.
Definition: log.h:228
#define NS_LOG_DEBUG(msg)
Use NS_LOG to output a message of level LOG_DEBUG.
Definition: log.h:236
Time Seconds(double value)
Construct a Time in the indicated unit.
Definition: nstime.h:866
Time Now(void)
create an ns3::Time instance which contains the current simulation time.
Definition: simulator.cc:330
#define NS_LOG_ERROR(msg)
Use NS_LOG to output a message of level LOG_ERROR.
Definition: log.h:220
tuple address
Definition: first.py:37
uint16_t ValidateVPortActions(const ofp_action_header *actions, size_t actions_len)
Validates a list of virtual port table entry actions.
Ptr< const AttributeAccessor > MakeUintegerAccessor(T1 a1)
Create an AttributeAccessor for a class data member, or a lone class get functor or set method...
Definition: uinteger.h:45
uint16_t m_missSendLen
Flow Table Miss Send Length; configurable by the controller.
TypeId SetParent(TypeId tid)
Definition: type-id.cc:638
#define OFP_SUPPORTED_CAPABILITIES
Time m_lookupDelay
Flow Table Lookup Delay [overhead].