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