PUNT socket: External control plane processes connected via UNIX domain sockets.
[vpp.git] / test / vpp_pg_interface.py
1 import os
2 import time
3 import socket
4 import struct
5 from traceback import format_exc, format_stack
6 from scapy.utils import wrpcap, rdpcap, PcapReader
7 from scapy.plist import PacketList
8 from vpp_interface import VppInterface
9
10 from scapy.layers.l2 import Ether, ARP
11 from scapy.layers.inet6 import IPv6, ICMPv6ND_NS, ICMPv6ND_NA,\
12     ICMPv6NDOptSrcLLAddr, ICMPv6NDOptDstLLAddr, ICMPv6ND_RA, RouterAlert, \
13     IPv6ExtHdrHopByHop
14 from util import ppp, ppc
15 from scapy.utils6 import in6_getnsma, in6_getnsmac, in6_ismaddr
16 from scapy.utils import inet_pton, inet_ntop
17
18
19 class CaptureTimeoutError(Exception):
20     """ Exception raised if capture or packet doesn't appear within timeout """
21     pass
22
23
24 def is_ipv6_misc(p):
25     """ Is packet one of uninteresting IPv6 broadcasts? """
26     if p.haslayer(ICMPv6ND_RA):
27         if in6_ismaddr(p[IPv6].dst):
28             return True
29     if p.haslayer(IPv6ExtHdrHopByHop):
30         for o in p[IPv6ExtHdrHopByHop].options:
31             if isinstance(o, RouterAlert):
32                 return True
33     return False
34
35
36 class VppPGInterface(VppInterface):
37     """
38     VPP packet-generator interface
39     """
40
41     @property
42     def pg_index(self):
43         """packet-generator interface index assigned by VPP"""
44         return self._pg_index
45
46     @property
47     def out_path(self):
48         """pcap file path - captured packets"""
49         return self._out_path
50
51     @property
52     def in_path(self):
53         """ pcap file path - injected packets"""
54         return self._in_path
55
56     @property
57     def capture_cli(self):
58         """CLI string to start capture on this interface"""
59         return self._capture_cli
60
61     @property
62     def cap_name(self):
63         """capture name for this interface"""
64         return self._cap_name
65
66     @property
67     def input_cli(self):
68         """CLI string to load the injected packets"""
69         return self._input_cli
70
71     @property
72     def in_history_counter(self):
73         """Self-incrementing counter used when renaming old pcap files"""
74         v = self._in_history_counter
75         self._in_history_counter += 1
76         return v
77
78     @property
79     def out_history_counter(self):
80         """Self-incrementing counter used when renaming old pcap files"""
81         v = self._out_history_counter
82         self._out_history_counter += 1
83         return v
84
85     def __init__(self, test, pg_index):
86         """ Create VPP packet-generator interface """
87         r = test.vapi.pg_create_interface(pg_index)
88         self._sw_if_index = r.sw_if_index
89
90         super(VppPGInterface, self).__init__(test)
91
92         self._in_history_counter = 0
93         self._out_history_counter = 0
94         self._out_assert_counter = 0
95         self._pg_index = pg_index
96         self._out_file = "pg%u_out.pcap" % self.pg_index
97         self._out_path = self.test.tempdir + "/" + self._out_file
98         self._in_file = "pg%u_in.pcap" % self.pg_index
99         self._in_path = self.test.tempdir + "/" + self._in_file
100         self._capture_cli = "packet-generator capture pg%u pcap %s" % (
101             self.pg_index, self.out_path)
102         self._cap_name = "pcap%u" % self.sw_if_index
103         self._input_cli = \
104             "packet-generator new pcap %s source pg%u name %s" % (
105                 self.in_path, self.pg_index, self.cap_name)
106
107     def enable_capture(self):
108         """ Enable capture on this packet-generator interface"""
109         try:
110             if os.path.isfile(self.out_path):
111                 name = "%s/history.[timestamp:%f].[%s-counter:%04d].%s" % \
112                     (self.test.tempdir,
113                      time.time(),
114                      self.name,
115                      self.out_history_counter,
116                      self._out_file)
117                 self.test.logger.debug("Renaming %s->%s" %
118                                        (self.out_path, name))
119                 os.rename(self.out_path, name)
120         except:
121             pass
122         # FIXME this should be an API, but no such exists atm
123         self.test.vapi.cli(self.capture_cli)
124         self._pcap_reader = None
125
126     def add_stream(self, pkts):
127         """
128         Add a stream of packets to this packet-generator
129
130         :param pkts: iterable packets
131
132         """
133         try:
134             if os.path.isfile(self.in_path):
135                 name = "%s/history.[timestamp:%f].[%s-counter:%04d].%s" %\
136                     (self.test.tempdir,
137                      time.time(),
138                      self.name,
139                      self.in_history_counter,
140                      self._in_file)
141                 self.test.logger.debug("Renaming %s->%s" %
142                                        (self.in_path, name))
143                 os.rename(self.in_path, name)
144         except:
145             pass
146         wrpcap(self.in_path, pkts)
147         self.test.register_capture(self.cap_name)
148         # FIXME this should be an API, but no such exists atm
149         self.test.vapi.cli(self.input_cli)
150
151     def generate_debug_aid(self, kind):
152         """ Create a hardlink to the out file with a counter and a file
153         containing stack trace to ease debugging in case of multiple capture
154         files present. """
155         self.test.logger.debug("Generating debug aid for %s on %s" %
156                                (kind, self._name))
157         link_path, stack_path = ["%s/debug_%s_%s_%s.%s" %
158                                  (self.test.tempdir, self._name,
159                                   self._out_assert_counter, kind, suffix)
160                                  for suffix in ["pcap", "stack"]
161                                  ]
162         os.link(self.out_path, link_path)
163         with open(stack_path, "w") as f:
164             f.writelines(format_stack())
165         self._out_assert_counter += 1
166
167     def _get_capture(self, timeout, filter_out_fn=is_ipv6_misc):
168         """ Helper method to get capture and filter it """
169         try:
170             if not self.wait_for_capture_file(timeout):
171                 return None
172             output = rdpcap(self.out_path)
173             self.test.logger.debug("Capture has %s packets" % len(output.res))
174         except:
175             self.test.logger.debug("Exception in scapy.rdpcap (%s): %s" %
176                                    (self.out_path, format_exc()))
177             return None
178         before = len(output.res)
179         if filter_out_fn:
180             output.res = [p for p in output.res if not filter_out_fn(p)]
181         removed = before - len(output.res)
182         if removed:
183             self.test.logger.debug(
184                 "Filtered out %s packets from capture (returning %s)" %
185                 (removed, len(output.res)))
186         return output
187
188     def get_capture(self, expected_count=None, remark=None, timeout=1,
189                     filter_out_fn=is_ipv6_misc):
190         """ Get captured packets
191
192         :param expected_count: expected number of packets to capture, if None,
193                                then self.test.packet_count_for_dst_pg_idx is
194                                used to lookup the expected count
195         :param remark: remark printed into debug logs
196         :param timeout: how long to wait for packets
197         :param filter_out_fn: filter applied to each packet, packets for which
198                               the filter returns True are removed from capture
199         :returns: iterable packets
200         """
201         remaining_time = timeout
202         capture = None
203         name = self.name if remark is None else "%s (%s)" % (self.name, remark)
204         based_on = "based on provided argument"
205         if expected_count is None:
206             expected_count = \
207                 self.test.get_packet_count_for_if_idx(self.sw_if_index)
208             based_on = "based on stored packet_infos"
209             if expected_count == 0:
210                 raise Exception(
211                     "Internal error, expected packet count for %s is 0!" %
212                     name)
213         self.test.logger.debug("Expecting to capture %s (%s) packets on %s" % (
214             expected_count, based_on, name))
215         while remaining_time > 0:
216             before = time.time()
217             capture = self._get_capture(remaining_time, filter_out_fn)
218             elapsed_time = time.time() - before
219             if capture:
220                 if len(capture.res) == expected_count:
221                     # bingo, got the packets we expected
222                     return capture
223                 elif len(capture.res) > expected_count:
224                     self.test.logger.error(
225                         ppc("Unexpected packets captured:", capture))
226                     break
227                 else:
228                     self.test.logger.debug("Partial capture containing %s "
229                                            "packets doesn't match expected "
230                                            "count %s (yet?)" %
231                                            (len(capture.res), expected_count))
232             elif expected_count == 0:
233                 # bingo, got None as we expected - return empty capture
234                 return PacketList()
235             remaining_time -= elapsed_time
236         if capture:
237             self.generate_debug_aid("count-mismatch")
238             raise Exception("Captured packets mismatch, captured %s packets, "
239                             "expected %s packets on %s" %
240                             (len(capture.res), expected_count, name))
241         else:
242             raise Exception("No packets captured on %s" % name)
243
244     def assert_nothing_captured(self, remark=None, filter_out_fn=is_ipv6_misc):
245         """ Assert that nothing unfiltered was captured on interface
246
247         :param remark: remark printed into debug logs
248         :param filter_out_fn: filter applied to each packet, packets for which
249                               the filter returns True are removed from capture
250         """
251         if os.path.isfile(self.out_path):
252             try:
253                 capture = self.get_capture(
254                     0, remark=remark, filter_out_fn=filter_out_fn)
255                 if not capture or len(capture.res) == 0:
256                     # junk filtered out, we're good
257                     return
258             except:
259                 pass
260             self.generate_debug_aid("empty-assert")
261             if remark:
262                 raise AssertionError(
263                     "Non-empty capture file present for interface %s (%s)" %
264                     (self.name, remark))
265             else:
266                 raise AssertionError("Capture file present for interface %s" %
267                                      self.name)
268
269     def wait_for_capture_file(self, timeout=1):
270         """
271         Wait until pcap capture file appears
272
273         :param timeout: How long to wait for the packet (default 1s)
274
275         :returns: True/False if the file is present or appears within timeout
276         """
277         deadline = time.time() + timeout
278         if not os.path.isfile(self.out_path):
279             self.test.logger.debug("Waiting for capture file %s to appear, "
280                                    "timeout is %ss" % (self.out_path, timeout))
281         else:
282             self.test.logger.debug("Capture file %s already exists" %
283                                    self.out_path)
284             return True
285         while time.time() < deadline:
286             if os.path.isfile(self.out_path):
287                 break
288             time.sleep(0)  # yield
289         if os.path.isfile(self.out_path):
290             self.test.logger.debug("Capture file appeared after %fs" %
291                                    (time.time() - (deadline - timeout)))
292         else:
293             self.test.logger.debug("Timeout - capture file still nowhere")
294             return False
295         return True
296
297     def verify_enough_packet_data_in_pcap(self):
298         """
299         Check if enough data is available in file handled by internal pcap
300         reader so that a whole packet can be read.
301
302         :returns: True if enough data present, else False
303         """
304         orig_pos = self._pcap_reader.f.tell()  # save file position
305         enough_data = False
306         # read packet header from pcap
307         packet_header_size = 16
308         caplen = None
309         end_pos = None
310         hdr = self._pcap_reader.f.read(packet_header_size)
311         if len(hdr) == packet_header_size:
312             # parse the capture length - caplen
313             sec, usec, caplen, wirelen = struct.unpack(
314                 self._pcap_reader.endian + "IIII", hdr)
315             self._pcap_reader.f.seek(0, 2)  # seek to end of file
316             end_pos = self._pcap_reader.f.tell()  # get position at end
317             if end_pos >= orig_pos + len(hdr) + caplen:
318                 enough_data = True  # yay, we have enough data
319         self._pcap_reader.f.seek(orig_pos, 0)  # restore original position
320         return enough_data
321
322     def wait_for_packet(self, timeout, filter_out_fn=is_ipv6_misc):
323         """
324         Wait for next packet captured with a timeout
325
326         :param timeout: How long to wait for the packet
327
328         :returns: Captured packet if no packet arrived within timeout
329         :raises Exception: if no packet arrives within timeout
330         """
331         deadline = time.time() + timeout
332         if self._pcap_reader is None:
333             if not self.wait_for_capture_file(timeout):
334                 raise CaptureTimeoutError("Capture file %s did not appear "
335                                           "within timeout" % self.out_path)
336             while time.time() < deadline:
337                 try:
338                     self._pcap_reader = PcapReader(self.out_path)
339                     break
340                 except:
341                     self.test.logger.debug(
342                         "Exception in scapy.PcapReader(%s): %s" %
343                         (self.out_path, format_exc()))
344         if not self._pcap_reader:
345             raise CaptureTimeoutError("Capture file %s did not appear within "
346                                       "timeout" % self.out_path)
347
348         poll = False
349         if timeout > 0:
350             self.test.logger.debug("Waiting for packet")
351         else:
352             poll = True
353             self.test.logger.debug("Polling for packet")
354         while time.time() < deadline or poll:
355             if not self.verify_enough_packet_data_in_pcap():
356                 time.sleep(0)  # yield
357                 poll = False
358                 continue
359             p = self._pcap_reader.recv()
360             if p is not None:
361                 if filter_out_fn is not None and filter_out_fn(p):
362                     self.test.logger.debug(
363                         "Packet received after %ss was filtered out" %
364                         (time.time() - (deadline - timeout)))
365                 else:
366                     self.test.logger.debug(
367                         "Packet received after %fs" %
368                         (time.time() - (deadline - timeout)))
369                     return p
370             time.sleep(0)  # yield
371             poll = False
372         self.test.logger.debug("Timeout - no packets received")
373         raise CaptureTimeoutError("Packet didn't arrive within timeout")
374
375     def create_arp_req(self):
376         """Create ARP request applicable for this interface"""
377         return (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.remote_mac) /
378                 ARP(op=ARP.who_has, pdst=self.local_ip4,
379                     psrc=self.remote_ip4, hwsrc=self.remote_mac))
380
381     def create_ndp_req(self):
382         """Create NDP - NS applicable for this interface"""
383         nsma = in6_getnsma(inet_pton(socket.AF_INET6, self.local_ip6))
384         d = inet_ntop(socket.AF_INET6, nsma)
385
386         return (Ether(dst=in6_getnsmac(nsma)) /
387                 IPv6(dst=d, src=self.remote_ip6) /
388                 ICMPv6ND_NS(tgt=self.local_ip6) /
389                 ICMPv6NDOptSrcLLAddr(lladdr=self.remote_mac))
390
391     def resolve_arp(self, pg_interface=None):
392         """Resolve ARP using provided packet-generator interface
393
394         :param pg_interface: interface used to resolve, if None then this
395             interface is used
396
397         """
398         if pg_interface is None:
399             pg_interface = self
400         self.test.logger.info("Sending ARP request for %s on port %s" %
401                               (self.local_ip4, pg_interface.name))
402         arp_req = self.create_arp_req()
403         pg_interface.add_stream(arp_req)
404         pg_interface.enable_capture()
405         self.test.pg_start()
406         self.test.logger.info(self.test.vapi.cli("show trace"))
407         try:
408             captured_packet = pg_interface.wait_for_packet(1)
409         except:
410             self.test.logger.info("No ARP received on port %s" %
411                                   pg_interface.name)
412             return
413         arp_reply = captured_packet.copy()  # keep original for exception
414         # Make Dot1AD packet content recognizable to scapy
415         if arp_reply.type == 0x88a8:
416             arp_reply.type = 0x8100
417             arp_reply = Ether(str(arp_reply))
418         try:
419             if arp_reply[ARP].op == ARP.is_at:
420                 self.test.logger.info("VPP %s MAC address is %s " %
421                                       (self.name, arp_reply[ARP].hwsrc))
422                 self._local_mac = arp_reply[ARP].hwsrc
423             else:
424                 self.test.logger.info("No ARP received on port %s" %
425                                       pg_interface.name)
426         except:
427             self.test.logger.error(
428                 ppp("Unexpected response to ARP request:", captured_packet))
429             raise
430
431     def resolve_ndp(self, pg_interface=None, timeout=1):
432         """Resolve NDP using provided packet-generator interface
433
434         :param pg_interface: interface used to resolve, if None then this
435             interface is used
436         :param timeout: how long to wait for response before giving up
437
438         """
439         if pg_interface is None:
440             pg_interface = self
441         self.test.logger.info("Sending NDP request for %s on port %s" %
442                               (self.local_ip6, pg_interface.name))
443         ndp_req = self.create_ndp_req()
444         pg_interface.add_stream(ndp_req)
445         pg_interface.enable_capture()
446         self.test.pg_start()
447         now = time.time()
448         deadline = now + timeout
449         # Enabling IPv6 on an interface can generate more than the
450         # ND reply we are looking for (namely MLD). So loop through
451         # the replies to look for want we want.
452         while now < deadline:
453             try:
454                 captured_packet = pg_interface.wait_for_packet(
455                     deadline - now, filter_out_fn=None)
456             except:
457                 self.test.logger.error(
458                     "Timeout while waiting for NDP response")
459                 raise
460             ndp_reply = captured_packet.copy()  # keep original for exception
461             # Make Dot1AD packet content recognizable to scapy
462             if ndp_reply.type == 0x88a8:
463                 ndp_reply.type = 0x8100
464                 ndp_reply = Ether(str(ndp_reply))
465             try:
466                 ndp_na = ndp_reply[ICMPv6ND_NA]
467                 opt = ndp_na[ICMPv6NDOptDstLLAddr]
468                 self.test.logger.info("VPP %s MAC address is %s " %
469                                       (self.name, opt.lladdr))
470                 self._local_mac = opt.lladdr
471                 self.test.logger.debug(self.test.vapi.cli("show trace"))
472                 # we now have the MAC we've been after
473                 return
474             except:
475                 self.test.logger.info(
476                     ppp("Unexpected response to NDP request:",
477                         captured_packet))
478             now = time.time()
479
480         self.test.logger.debug(self.test.vapi.cli("show trace"))
481         raise Exception("Timeout while waiting for NDP response")