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