blob: d3db8d208a3fee507ea60a7b355553c96670e878 [file] [log] [blame]
Klement Sekeraf62ae122016-10-11 11:47:09 +02001import os
Klement Sekera778c2762016-11-08 02:00:28 +01002import time
Klement Sekeradab231a2016-12-21 08:50:14 +01003from traceback import format_exc
Klement Sekera0e3c0de2016-09-29 14:43:44 +02004from scapy.utils import wrpcap, rdpcap, PcapReader
Klement Sekeraf62ae122016-10-11 11:47:09 +02005from vpp_interface import VppInterface
6
Matej Klotton0178d522016-11-04 11:11:44 +01007from scapy.layers.l2 import Ether, ARP
Klement Sekera0e3c0de2016-09-29 14:43:44 +02008from scapy.layers.inet6 import IPv6, ICMPv6ND_NS, ICMPv6ND_NA,\
Klement Sekera65cc8c02016-12-18 15:49:54 +01009 ICMPv6NDOptSrcLLAddr, ICMPv6NDOptDstLLAddr, ICMPv6ND_RA, RouterAlert, \
10 IPv6ExtHdrHopByHop
Klement Sekera9225dee2016-12-12 08:36:58 +010011from util import ppp, ppc
Matej Klotton0178d522016-11-04 11:11:44 +010012
Klement Sekeraf62ae122016-10-11 11:47:09 +020013
Klement Sekera65cc8c02016-12-18 15:49:54 +010014def is_ipv6_misc(p):
15 """ Is packet one of uninteresting IPv6 broadcasts? """
16 if p.haslayer(ICMPv6ND_RA):
17 return True
18 if p.haslayer(IPv6ExtHdrHopByHop):
19 for o in p[IPv6ExtHdrHopByHop].options:
20 if isinstance(o, RouterAlert):
21 return True
22 return False
23
24
Klement Sekeraf62ae122016-10-11 11:47:09 +020025class VppPGInterface(VppInterface):
26 """
27 VPP packet-generator interface
28 """
29
30 @property
31 def pg_index(self):
32 """packet-generator interface index assigned by VPP"""
33 return self._pg_index
34
35 @property
36 def out_path(self):
37 """pcap file path - captured packets"""
38 return self._out_path
39
40 @property
41 def in_path(self):
42 """ pcap file path - injected packets"""
43 return self._in_path
44
45 @property
46 def capture_cli(self):
47 """CLI string to start capture on this interface"""
48 return self._capture_cli
49
50 @property
51 def cap_name(self):
52 """capture name for this interface"""
53 return self._cap_name
54
55 @property
56 def input_cli(self):
57 """CLI string to load the injected packets"""
58 return self._input_cli
59
Klement Sekera778c2762016-11-08 02:00:28 +010060 @property
61 def in_history_counter(self):
62 """Self-incrementing counter used when renaming old pcap files"""
63 v = self._in_history_counter
64 self._in_history_counter += 1
65 return v
66
67 @property
68 def out_history_counter(self):
69 """Self-incrementing counter used when renaming old pcap files"""
70 v = self._out_history_counter
71 self._out_history_counter += 1
72 return v
73
Matej Klottonc5bf07f2016-11-23 15:27:17 +010074 def __init__(self, test, pg_index):
75 """ Create VPP packet-generator interface """
76 r = test.vapi.pg_create_interface(pg_index)
77 self._sw_if_index = r.sw_if_index
78
79 super(VppPGInterface, self).__init__(test)
80
81 self._in_history_counter = 0
82 self._out_history_counter = 0
83 self._pg_index = pg_index
Klement Sekera74dcdbf2016-11-14 09:49:09 +010084 self._out_file = "pg%u_out.pcap" % self.pg_index
Klement Sekera778c2762016-11-08 02:00:28 +010085 self._out_path = self.test.tempdir + "/" + self._out_file
Klement Sekera74dcdbf2016-11-14 09:49:09 +010086 self._in_file = "pg%u_in.pcap" % self.pg_index
Klement Sekera778c2762016-11-08 02:00:28 +010087 self._in_path = self.test.tempdir + "/" + self._in_file
Klement Sekeraf62ae122016-10-11 11:47:09 +020088 self._capture_cli = "packet-generator capture pg%u pcap %s" % (
89 self.pg_index, self.out_path)
90 self._cap_name = "pcap%u" % self.sw_if_index
91 self._input_cli = "packet-generator new pcap %s source pg%u name %s" % (
92 self.in_path, self.pg_index, self.cap_name)
93
Klement Sekeraf62ae122016-10-11 11:47:09 +020094 def enable_capture(self):
95 """ Enable capture on this packet-generator interface"""
96 try:
Klement Sekera778c2762016-11-08 02:00:28 +010097 if os.path.isfile(self.out_path):
98 os.rename(self.out_path,
99 "%s/history.[timestamp:%f].[%s-counter:%04d].%s" %
100 (self.test.tempdir,
101 time.time(),
102 self.name,
103 self.out_history_counter,
104 self._out_file))
Klement Sekeraf62ae122016-10-11 11:47:09 +0200105 except:
106 pass
107 # FIXME this should be an API, but no such exists atm
108 self.test.vapi.cli(self.capture_cli)
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200109 self._pcap_reader = None
Klement Sekeraf62ae122016-10-11 11:47:09 +0200110
111 def add_stream(self, pkts):
112 """
113 Add a stream of packets to this packet-generator
114
115 :param pkts: iterable packets
116
117 """
118 try:
Klement Sekera778c2762016-11-08 02:00:28 +0100119 if os.path.isfile(self.in_path):
120 os.rename(self.in_path,
121 "%s/history.[timestamp:%f].[%s-counter:%04d].%s" %
122 (self.test.tempdir,
123 time.time(),
124 self.name,
125 self.in_history_counter,
126 self._in_file))
Klement Sekeraf62ae122016-10-11 11:47:09 +0200127 except:
128 pass
129 wrpcap(self.in_path, pkts)
Klement Sekera9225dee2016-12-12 08:36:58 +0100130 self.test.register_capture(self.cap_name)
Klement Sekeraf62ae122016-10-11 11:47:09 +0200131 # FIXME this should be an API, but no such exists atm
132 self.test.vapi.cli(self.input_cli)
Klement Sekeraf62ae122016-10-11 11:47:09 +0200133
Klement Sekeradab231a2016-12-21 08:50:14 +0100134 def _get_capture(self, timeout, filter_out_fn=is_ipv6_misc):
135 """ Helper method to get capture and filter it """
Klement Sekeraf62ae122016-10-11 11:47:09 +0200136 try:
Klement Sekeradab231a2016-12-21 08:50:14 +0100137 if not self.wait_for_capture_file(timeout):
138 return None
Klement Sekeraf62ae122016-10-11 11:47:09 +0200139 output = rdpcap(self.out_path)
Klement Sekera65cc8c02016-12-18 15:49:54 +0100140 self.test.logger.debug("Capture has %s packets" % len(output.res))
Klement Sekeradab231a2016-12-21 08:50:14 +0100141 except:
142 self.test.logger.debug("Exception in scapy.rdpcap(%s): %s" %
143 (self.out_path, format_exc()))
144 return None
Klement Sekera65cc8c02016-12-18 15:49:54 +0100145 before = len(output.res)
Klement Sekeradab231a2016-12-21 08:50:14 +0100146 if filter_out_fn:
147 output.res = [p for p in output.res if not filter_out_fn(p)]
Klement Sekera65cc8c02016-12-18 15:49:54 +0100148 removed = len(output.res) - before
149 if removed:
150 self.test.logger.debug(
151 "Filtered out %s packets from capture (returning %s)" %
152 (removed, len(output.res)))
Klement Sekeraf62ae122016-10-11 11:47:09 +0200153 return output
Matej Klotton0178d522016-11-04 11:11:44 +0100154
Klement Sekeradab231a2016-12-21 08:50:14 +0100155 def get_capture(self, expected_count=None, remark=None, timeout=1,
156 filter_out_fn=is_ipv6_misc):
157 """ Get captured packets
158
159 :param expected_count: expected number of packets to capture, if None,
160 then self.test.packet_count_for_dst_pg_idx is
161 used to lookup the expected count
162 :param remark: remark printed into debug logs
163 :param timeout: how long to wait for packets
164 :param filter_out_fn: filter applied to each packet, packets for which
165 the filter returns True are removed from capture
166 :returns: iterable packets
167 """
168 remaining_time = timeout
169 capture = None
170 name = self.name if remark is None else "%s (%s)" % (self.name, remark)
171 based_on = "based on provided argument"
172 if expected_count is None:
173 expected_count = \
174 self.test.get_packet_count_for_if_idx(self.sw_if_index)
175 based_on = "based on stored packet_infos"
Klement Sekerac86fa022017-01-02 09:03:47 +0100176 if expected_count == 0:
177 raise Exception(
178 "Internal error, expected packet count for %s is 0!" % name)
Klement Sekeradab231a2016-12-21 08:50:14 +0100179 self.test.logger.debug("Expecting to capture %s(%s) packets on %s" % (
180 expected_count, based_on, name))
Klement Sekeradab231a2016-12-21 08:50:14 +0100181 while remaining_time > 0:
182 before = time.time()
183 capture = self._get_capture(remaining_time, filter_out_fn)
184 elapsed_time = time.time() - before
185 if capture:
186 if len(capture.res) == expected_count:
187 # bingo, got the packets we expected
188 return capture
Klement Sekerac86fa022017-01-02 09:03:47 +0100189 elif expected_count == 0:
190 return None
Klement Sekeradab231a2016-12-21 08:50:14 +0100191 remaining_time -= elapsed_time
192 if capture:
193 raise Exception("Captured packets mismatch, captured %s packets, "
194 "expected %s packets on %s" %
195 (len(capture.res), expected_count, name))
196 else:
197 raise Exception("No packets captured on %s" % name)
198
199 def assert_nothing_captured(self, remark=None, filter_out_fn=is_ipv6_misc):
200 """ Assert that nothing unfiltered was captured on interface
201
202 :param remark: remark printed into debug logs
203 :param filter_out_fn: filter applied to each packet, packets for which
204 the filter returns True are removed from capture
205 """
Klement Sekera9225dee2016-12-12 08:36:58 +0100206 if os.path.isfile(self.out_path):
207 try:
Klement Sekeradab231a2016-12-21 08:50:14 +0100208 capture = self.get_capture(
209 0, remark=remark, filter_out_fn=filter_out_fn)
210 if capture:
211 if len(capture.res) == 0:
212 # junk filtered out, we're good
213 return
Klement Sekerac86fa022017-01-02 09:03:47 +0100214 self.test.logger.error(
215 ppc("Unexpected packets captured:", capture))
Klement Sekera9225dee2016-12-12 08:36:58 +0100216 except:
217 pass
218 if remark:
219 raise AssertionError(
Klement Sekeradab231a2016-12-21 08:50:14 +0100220 "Non-empty capture file present for interface %s(%s)" %
Klement Sekera9225dee2016-12-12 08:36:58 +0100221 (self.name, remark))
222 else:
Klement Sekeradab231a2016-12-21 08:50:14 +0100223 raise AssertionError(
224 "Non-empty capture file present for interface %s" %
225 self.name)
Klement Sekera9225dee2016-12-12 08:36:58 +0100226
227 def wait_for_capture_file(self, timeout=1):
228 """
229 Wait until pcap capture file appears
230
231 :param timeout: How long to wait for the packet (default 1s)
232
Klement Sekeradab231a2016-12-21 08:50:14 +0100233 :returns: True/False if the file is present or appears within timeout
Klement Sekera9225dee2016-12-12 08:36:58 +0100234 """
235 limit = time.time() + timeout
236 if not os.path.isfile(self.out_path):
Klement Sekeradab231a2016-12-21 08:50:14 +0100237 self.test.logger.debug("Waiting for capture file %s to appear, "
238 "timeout is %ss" % (self.out_path, timeout))
Klement Sekera9225dee2016-12-12 08:36:58 +0100239 else:
Klement Sekerac86fa022017-01-02 09:03:47 +0100240 self.test.logger.debug("Capture file %s already exists" %
241 self.out_path)
Klement Sekeradab231a2016-12-21 08:50:14 +0100242 return True
Klement Sekera9225dee2016-12-12 08:36:58 +0100243 while time.time() < limit:
244 if os.path.isfile(self.out_path):
245 break
246 time.sleep(0) # yield
247 if os.path.isfile(self.out_path):
248 self.test.logger.debug("Capture file appeared after %fs" %
249 (time.time() - (limit - timeout)))
250 else:
251 self.test.logger.debug("Timeout - capture file still nowhere")
Klement Sekeradab231a2016-12-21 08:50:14 +0100252 return False
253 return True
Klement Sekera9225dee2016-12-12 08:36:58 +0100254
Klement Sekeradab231a2016-12-21 08:50:14 +0100255 def wait_for_packet(self, timeout, filter_out_fn=is_ipv6_misc):
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200256 """
257 Wait for next packet captured with a timeout
258
259 :param timeout: How long to wait for the packet
260
261 :returns: Captured packet if no packet arrived within timeout
262 :raises Exception: if no packet arrives within timeout
263 """
Klement Sekeradab231a2016-12-21 08:50:14 +0100264 deadline = time.time() + timeout
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200265 if self._pcap_reader is None:
Klement Sekeradab231a2016-12-21 08:50:14 +0100266 if not self.wait_for_capture_file(timeout):
267 raise Exception("Capture file %s did not appear within "
268 "timeout" % self.out_path)
269 while time.time() < deadline:
270 try:
271 self._pcap_reader = PcapReader(self.out_path)
272 break
273 except:
274 self.test.logger.debug("Exception in scapy.PcapReader(%s): "
275 "%s" % (self.out_path, format_exc()))
276 if not self._pcap_reader:
277 raise Exception("Capture file %s did not appear within "
278 "timeout" % self.out_path)
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200279
280 self.test.logger.debug("Waiting for packet")
Klement Sekeradab231a2016-12-21 08:50:14 +0100281 while time.time() < deadline:
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200282 p = self._pcap_reader.recv()
283 if p is not None:
Klement Sekeradab231a2016-12-21 08:50:14 +0100284 if filter_out_fn is not None and filter_out_fn(p):
285 self.test.logger.debug(
286 "Packet received after %ss was filtered out" %
287 (time.time() - (deadline - timeout)))
288 else:
289 self.test.logger.debug("Packet received after %fs" %
290 (time.time() - (deadline - timeout)))
291 return p
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200292 time.sleep(0) # yield
293 self.test.logger.debug("Timeout - no packets received")
294 raise Exception("Packet didn't arrive within timeout")
295
Matej Klotton0178d522016-11-04 11:11:44 +0100296 def create_arp_req(self):
297 """Create ARP request applicable for this interface"""
298 return (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.remote_mac) /
299 ARP(op=ARP.who_has, pdst=self.local_ip4,
300 psrc=self.remote_ip4, hwsrc=self.remote_mac))
301
302 def create_ndp_req(self):
303 """Create NDP - NS applicable for this interface"""
304 return (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.remote_mac) /
Klement Sekera74dcdbf2016-11-14 09:49:09 +0100305 IPv6(src=self.remote_ip6, dst=self.local_ip6) /
306 ICMPv6ND_NS(tgt=self.local_ip6) /
307 ICMPv6NDOptSrcLLAddr(lladdr=self.remote_mac))
Matej Klotton0178d522016-11-04 11:11:44 +0100308
309 def resolve_arp(self, pg_interface=None):
310 """Resolve ARP using provided packet-generator interface
311
312 :param pg_interface: interface used to resolve, if None then this
313 interface is used
314
315 """
316 if pg_interface is None:
317 pg_interface = self
Klement Sekera7bb873a2016-11-18 07:38:42 +0100318 self.test.logger.info("Sending ARP request for %s on port %s" %
319 (self.local_ip4, pg_interface.name))
Matej Klotton0178d522016-11-04 11:11:44 +0100320 arp_req = self.create_arp_req()
321 pg_interface.add_stream(arp_req)
322 pg_interface.enable_capture()
323 self.test.pg_start()
Klement Sekera7bb873a2016-11-18 07:38:42 +0100324 self.test.logger.info(self.test.vapi.cli("show trace"))
Klement Sekera9225dee2016-12-12 08:36:58 +0100325 try:
Klement Sekeradab231a2016-12-21 08:50:14 +0100326 captured_packet = pg_interface.wait_for_packet(1)
Klement Sekera9225dee2016-12-12 08:36:58 +0100327 except:
328 self.test.logger.info("No ARP received on port %s" %
329 pg_interface.name)
Matej Klotton0178d522016-11-04 11:11:44 +0100330 return
Klement Sekeradab231a2016-12-21 08:50:14 +0100331 arp_reply = captured_packet.copy() # keep original for exception
Matej Klotton0178d522016-11-04 11:11:44 +0100332 # Make Dot1AD packet content recognizable to scapy
333 if arp_reply.type == 0x88a8:
334 arp_reply.type = 0x8100
335 arp_reply = Ether(str(arp_reply))
336 try:
337 if arp_reply[ARP].op == ARP.is_at:
Klement Sekera7bb873a2016-11-18 07:38:42 +0100338 self.test.logger.info("VPP %s MAC address is %s " %
339 (self.name, arp_reply[ARP].hwsrc))
Matej Klotton0178d522016-11-04 11:11:44 +0100340 self._local_mac = arp_reply[ARP].hwsrc
341 else:
Klement Sekeradab231a2016-12-21 08:50:14 +0100342 self.test.logger.info("No ARP received on port %s" %
343 pg_interface.name)
Matej Klotton0178d522016-11-04 11:11:44 +0100344 except:
Klement Sekera7bb873a2016-11-18 07:38:42 +0100345 self.test.logger.error(
Klement Sekeradab231a2016-12-21 08:50:14 +0100346 ppp("Unexpected response to ARP request:", captured_packet))
Matej Klotton0178d522016-11-04 11:11:44 +0100347 raise
348
Klement Sekeradab231a2016-12-21 08:50:14 +0100349 def resolve_ndp(self, pg_interface=None, timeout=1):
Matej Klotton0178d522016-11-04 11:11:44 +0100350 """Resolve NDP using provided packet-generator interface
351
352 :param pg_interface: interface used to resolve, if None then this
353 interface is used
Klement Sekeradab231a2016-12-21 08:50:14 +0100354 :param timeout: how long to wait for response before giving up
Matej Klotton0178d522016-11-04 11:11:44 +0100355
356 """
357 if pg_interface is None:
358 pg_interface = self
Klement Sekera7bb873a2016-11-18 07:38:42 +0100359 self.test.logger.info("Sending NDP request for %s on port %s" %
360 (self.local_ip6, pg_interface.name))
Matej Klotton0178d522016-11-04 11:11:44 +0100361 ndp_req = self.create_ndp_req()
362 pg_interface.add_stream(ndp_req)
363 pg_interface.enable_capture()
364 self.test.pg_start()
Klement Sekeradab231a2016-12-21 08:50:14 +0100365 now = time.time()
366 deadline = now + timeout
Neale Ranns82a06a92016-12-08 20:05:33 +0000367 # Enabling IPv6 on an interface can generate more than the
368 # ND reply we are looking for (namely MLD). So loop through
369 # the replies to look for want we want.
Klement Sekeradab231a2016-12-21 08:50:14 +0100370 while now < deadline:
371 try:
372 captured_packet = pg_interface.wait_for_packet(
373 deadline - now, filter_out_fn=None)
374 except:
375 self.test.logger.error("Timeout while waiting for NDP response")
376 raise
377 ndp_reply = captured_packet.copy() # keep original for exception
Neale Ranns82a06a92016-12-08 20:05:33 +0000378 # Make Dot1AD packet content recognizable to scapy
379 if ndp_reply.type == 0x88a8:
380 ndp_reply.type = 0x8100
381 ndp_reply = Ether(str(ndp_reply))
382 try:
383 ndp_na = ndp_reply[ICMPv6ND_NA]
384 opt = ndp_na[ICMPv6NDOptDstLLAddr]
385 self.test.logger.info("VPP %s MAC address is %s " %
386 (self.name, opt.lladdr))
387 self._local_mac = opt.lladdr
Klement Sekeradab231a2016-12-21 08:50:14 +0100388 self.test.logger.debug(self.test.vapi.cli("show trace"))
389 # we now have the MAC we've been after
390 return
Neale Ranns82a06a92016-12-08 20:05:33 +0000391 except:
392 self.test.logger.info(
Klement Sekeradab231a2016-12-21 08:50:14 +0100393 ppp("Unexpected response to NDP request:", captured_packet))
394 now = time.time()
395
396 self.test.logger.debug(self.test.vapi.cli("show trace"))
397 raise Exception("Timeout while waiting for NDP response")