00064c8d1dc6b649c7a56803ae26b6731f1cdee7
[mech_eap.git] / tests / hwsim / test_scan.py
1 # Scanning tests
2 # Copyright (c) 2013-2015, Jouni Malinen <j@w1.fi>
3 #
4 # This software may be distributed under the terms of the BSD license.
5 # See README for more details.
6
7 import time
8 import logging
9 logger = logging.getLogger()
10 import os
11 import subprocess
12
13 import hostapd
14 from wpasupplicant import WpaSupplicant
15 from utils import HwsimSkip, fail_test, alloc_fail, wait_fail_trigger
16 from tshark import run_tshark
17
18 def check_scan(dev, params, other_started=False, test_busy=False):
19     if not other_started:
20         dev.dump_monitor()
21     id = dev.request("SCAN " + params)
22     if "FAIL" in id:
23         raise Exception("Failed to start scan")
24     id = int(id)
25
26     if test_busy:
27         if "FAIL-BUSY" not in dev.request("SCAN"):
28             raise Exception("SCAN command while already scanning not rejected")
29
30     if other_started:
31         ev = dev.wait_event(["CTRL-EVENT-SCAN-STARTED"])
32         if ev is None:
33             raise Exception("Other scan did not start")
34         if "id=" + str(id) in ev:
35             raise Exception("Own scan id unexpectedly included in start event")
36
37         ev = dev.wait_event(["CTRL-EVENT-SCAN-RESULTS"])
38         if ev is None:
39             raise Exception("Other scan did not complete")
40         if "id=" + str(id) in ev:
41             raise Exception("Own scan id unexpectedly included in completed event")
42
43     ev = dev.wait_event(["CTRL-EVENT-SCAN-STARTED"])
44     if ev is None:
45         raise Exception("Scan did not start")
46     if "id=" + str(id) not in ev:
47         raise Exception("Scan id not included in start event")
48     if test_busy:
49         if "FAIL-BUSY" not in dev.request("SCAN"):
50             raise Exception("SCAN command while already scanning not rejected")
51
52     ev = dev.wait_event(["CTRL-EVENT-SCAN-RESULTS"])
53     if ev is None:
54         raise Exception("Scan did not complete")
55     if "id=" + str(id) not in ev:
56         raise Exception("Scan id not included in completed event")
57
58 def check_scan_retry(dev, params, bssid):
59     for i in range(0, 5):
60         check_scan(dev, "freq=2412-2462,5180 use_id=1")
61         if int(dev.get_bss(bssid)['age']) <= 1:
62             return
63     raise Exception("Unexpectedly old BSS entry")
64
65 def test_scan(dev, apdev):
66     """Control interface behavior on scan parameters"""
67     hostapd.add_ap(apdev[0], { "ssid": "test-scan" })
68     bssid = apdev[0]['bssid']
69
70     logger.info("Full scan")
71     check_scan(dev[0], "use_id=1", test_busy=True)
72
73     logger.info("Limited channel scan")
74     check_scan_retry(dev[0], "freq=2412-2462,5180 use_id=1", bssid)
75
76     # wait long enough to allow next scans to be verified not to find the AP
77     time.sleep(2)
78
79     logger.info("Passive single-channel scan")
80     check_scan(dev[0], "freq=2457 passive=1 use_id=1")
81     logger.info("Active single-channel scan")
82     check_scan(dev[0], "freq=2452 passive=0 use_id=1")
83     if int(dev[0].get_bss(bssid)['age']) < 2:
84         raise Exception("Unexpectedly updated BSS entry")
85
86     logger.info("Active single-channel scan on AP's operating channel")
87     check_scan_retry(dev[0], "freq=2412 passive=0 use_id=1", bssid)
88
89 def test_scan_tsf(dev, apdev):
90     """Scan and TSF updates from Beacon/Probe Response frames"""
91     hostapd.add_ap(apdev[0], { "ssid": "test-scan",
92                                'beacon_int': "100" })
93     bssid = apdev[0]['bssid']
94
95     tsf = []
96     for passive in [ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1 ]:
97         check_scan(dev[0], "freq=2412 passive=%d use_id=1" % passive)
98         bss = dev[0].get_bss(bssid)
99         if bss:
100             tsf.append(int(bss['tsf']))
101             logger.info("TSF: " + bss['tsf'])
102     if tsf[-3] <= tsf[-4]:
103         # For now, only write this in the log without failing the test case
104         # since mac80211_hwsim does not yet update the Timestamp field in
105         # Probe Response frames.
106         logger.info("Probe Response did not update TSF")
107         #raise Exception("Probe Response did not update TSF")
108     if tsf[-1] <= tsf[-3]:
109         raise Exception("Beacon did not update TSF")
110     if 0 in tsf:
111         raise Exception("0 TSF reported")
112
113 def test_scan_only(dev, apdev):
114     """Control interface behavior on scan parameters with type=only"""
115     hostapd.add_ap(apdev[0], { "ssid": "test-scan" })
116     bssid = apdev[0]['bssid']
117
118     logger.info("Full scan")
119     check_scan(dev[0], "type=only use_id=1")
120
121     logger.info("Limited channel scan")
122     check_scan_retry(dev[0], "type=only freq=2412-2462,5180 use_id=1", bssid)
123
124     # wait long enough to allow next scans to be verified not to find the AP
125     time.sleep(2)
126
127     logger.info("Passive single-channel scan")
128     check_scan(dev[0], "type=only freq=2457 passive=1 use_id=1")
129     logger.info("Active single-channel scan")
130     check_scan(dev[0], "type=only freq=2452 passive=0 use_id=1")
131     if int(dev[0].get_bss(bssid)['age']) < 2:
132         raise Exception("Unexpectedly updated BSS entry")
133
134     logger.info("Active single-channel scan on AP's operating channel")
135     check_scan_retry(dev[0], "type=only freq=2412 passive=0 use_id=1", bssid)
136
137 def test_scan_external_trigger(dev, apdev):
138     """Avoid operations during externally triggered scan"""
139     hostapd.add_ap(apdev[0], { "ssid": "test-scan" })
140     bssid = apdev[0]['bssid']
141     subprocess.call(['iw', dev[0].ifname, 'scan', 'trigger'])
142     check_scan(dev[0], "use_id=1", other_started=True)
143
144 def test_scan_bss_expiration_count(dev, apdev):
145     """BSS entry expiration based on scan results without match"""
146     if "FAIL" not in dev[0].request("BSS_EXPIRE_COUNT 0"):
147         raise Exception("Invalid BSS_EXPIRE_COUNT accepted")
148     if "OK" not in dev[0].request("BSS_EXPIRE_COUNT 2"):
149         raise Exception("BSS_EXPIRE_COUNT failed")
150     hapd = hostapd.add_ap(apdev[0], { "ssid": "test-scan" })
151     bssid = apdev[0]['bssid']
152     dev[0].scan(freq="2412", only_new=True)
153     if bssid not in dev[0].request("SCAN_RESULTS"):
154         raise Exception("BSS not found in initial scan")
155     hapd.request("DISABLE")
156     dev[0].scan(freq="2412", only_new=True)
157     if bssid not in dev[0].request("SCAN_RESULTS"):
158         raise Exception("BSS not found in first scan without match")
159     dev[0].scan(freq="2412", only_new=True)
160     if bssid in dev[0].request("SCAN_RESULTS"):
161         raise Exception("BSS found after two scans without match")
162
163 def test_scan_bss_expiration_age(dev, apdev):
164     """BSS entry expiration based on age"""
165     try:
166         if "FAIL" not in dev[0].request("BSS_EXPIRE_AGE COUNT 9"):
167             raise Exception("Invalid BSS_EXPIRE_AGE accepted")
168         if "OK" not in dev[0].request("BSS_EXPIRE_AGE 10"):
169             raise Exception("BSS_EXPIRE_AGE failed")
170         hapd = hostapd.add_ap(apdev[0], { "ssid": "test-scan" })
171         bssid = apdev[0]['bssid']
172         # Allow couple more retries to avoid reporting errors during heavy load
173         for i in range(5):
174             dev[0].scan(freq="2412")
175             if bssid in dev[0].request("SCAN_RESULTS"):
176                 break
177         if bssid not in dev[0].request("SCAN_RESULTS"):
178             raise Exception("BSS not found in initial scan")
179         hapd.request("DISABLE")
180         logger.info("Waiting for BSS entry to expire")
181         time.sleep(7)
182         if bssid not in dev[0].request("SCAN_RESULTS"):
183             raise Exception("BSS expired too quickly")
184         ev = dev[0].wait_event(["CTRL-EVENT-BSS-REMOVED"], timeout=15)
185         if ev is None:
186             raise Exception("BSS entry expiration timed out")
187         if bssid in dev[0].request("SCAN_RESULTS"):
188             raise Exception("BSS not removed after expiration time")
189     finally:
190         dev[0].request("BSS_EXPIRE_AGE 180")
191
192 def test_scan_filter(dev, apdev):
193     """Filter scan results based on SSID"""
194     try:
195         if "OK" not in dev[0].request("SET filter_ssids 1"):
196             raise Exception("SET failed")
197         id = dev[0].connect("test-scan", key_mgmt="NONE", only_add_network=True)
198         hostapd.add_ap(apdev[0], { "ssid": "test-scan" })
199         bssid = apdev[0]['bssid']
200         hostapd.add_ap(apdev[1], { "ssid": "test-scan2" })
201         bssid2 = apdev[1]['bssid']
202         dev[0].scan(freq="2412", only_new=True)
203         if bssid not in dev[0].request("SCAN_RESULTS"):
204             raise Exception("BSS not found in scan results")
205         if bssid2 in dev[0].request("SCAN_RESULTS"):
206             raise Exception("Unexpected BSS found in scan results")
207         dev[0].set_network_quoted(id, "ssid", "")
208         dev[0].scan(freq="2412")
209         id2 = dev[0].connect("test", key_mgmt="NONE", only_add_network=True)
210         dev[0].scan(freq="2412")
211     finally:
212         dev[0].request("SET filter_ssids 0")
213
214 def test_scan_int(dev, apdev):
215     """scan interval configuration"""
216     try:
217         if "FAIL" not in dev[0].request("SCAN_INTERVAL -1"):
218             raise Exception("Accepted invalid scan interval")
219         if "OK" not in dev[0].request("SCAN_INTERVAL 1"):
220             raise Exception("Failed to set scan interval")
221         dev[0].connect("not-used", key_mgmt="NONE", scan_freq="2412",
222                        wait_connect=False)
223         times = {}
224         for i in range(0, 3):
225             logger.info("Waiting for scan to start")
226             start = os.times()[4]
227             ev = dev[0].wait_event(["CTRL-EVENT-SCAN-STARTED"], timeout=5)
228             if ev is None:
229                 raise Exception("did not start a scan")
230             stop = os.times()[4]
231             times[i] = stop - start
232             logger.info("Waiting for scan to complete")
233             ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 10)
234             if ev is None:
235                 raise Exception("did not complete a scan")
236         logger.info("times=" + str(times))
237         if times[0] > 1 or times[1] < 0.5 or times[1] > 1.5 or times[2] < 0.5 or times[2] > 1.5:
238             raise Exception("Unexpected scan timing: " + str(times))
239     finally:
240         dev[0].request("SCAN_INTERVAL 5")
241
242 def test_scan_bss_operations(dev, apdev):
243     """Control interface behavior on BSS parameters"""
244     hostapd.add_ap(apdev[0], { "ssid": "test-scan" })
245     bssid = apdev[0]['bssid']
246     hostapd.add_ap(apdev[1], { "ssid": "test2-scan" })
247     bssid2 = apdev[1]['bssid']
248
249     dev[0].scan(freq="2412")
250     dev[0].scan(freq="2412")
251     dev[0].scan(freq="2412")
252
253     id1 = dev[0].request("BSS FIRST MASK=0x1").splitlines()[0].split('=')[1]
254     id2 = dev[0].request("BSS LAST MASK=0x1").splitlines()[0].split('=')[1]
255
256     res = dev[0].request("BSS RANGE=ALL MASK=0x20001")
257     if "id=" + id1 not in res:
258         raise Exception("Missing BSS " + id1)
259     if "id=" + id2 not in res:
260         raise Exception("Missing BSS " + id2)
261     if "====" not in res:
262         raise Exception("Missing delim")
263     if "####" not in res:
264         raise Exception("Missing end")
265
266     res = dev[0].request("BSS RANGE=ALL MASK=0")
267     if "id=" + id1 not in res:
268         raise Exception("Missing BSS " + id1)
269     if "id=" + id2 not in res:
270         raise Exception("Missing BSS " + id2)
271     if "====" in res:
272         raise Exception("Unexpected delim")
273     if "####" in res:
274         raise Exception("Unexpected end delim")
275
276     res = dev[0].request("BSS RANGE=ALL MASK=0x1").splitlines()
277     if len(res) != 2:
278         raise Exception("Unexpected result: " + str(res))
279     res = dev[0].request("BSS FIRST MASK=0x1")
280     if "id=" + id1 not in res:
281         raise Exception("Unexpected result: " + res)
282     res = dev[0].request("BSS LAST MASK=0x1")
283     if "id=" + id2 not in res:
284         raise Exception("Unexpected result: " + res)
285     res = dev[0].request("BSS ID-" + id1 + " MASK=0x1")
286     if "id=" + id1 not in res:
287         raise Exception("Unexpected result: " + res)
288     res = dev[0].request("BSS NEXT-" + id1 + " MASK=0x1")
289     if "id=" + id2 not in res:
290         raise Exception("Unexpected result: " + res)
291     res = dev[0].request("BSS NEXT-" + id2 + " MASK=0x1")
292     if "id=" in res:
293         raise Exception("Unexpected result: " + res)
294
295     if len(dev[0].request("BSS RANGE=" + id2 + " MASK=0x1").splitlines()) != 0:
296         raise Exception("Unexpected RANGE=1 result")
297     if len(dev[0].request("BSS RANGE=" + id1 + "- MASK=0x1").splitlines()) != 2:
298         raise Exception("Unexpected RANGE=0- result")
299     if len(dev[0].request("BSS RANGE=-" + id2 + " MASK=0x1").splitlines()) != 2:
300         raise Exception("Unexpected RANGE=-1 result")
301     if len(dev[0].request("BSS RANGE=" + id1 + "-" + id2 + " MASK=0x1").splitlines()) != 2:
302         raise Exception("Unexpected RANGE=0-1 result")
303     if len(dev[0].request("BSS RANGE=" + id2 + "-" + id2 + " MASK=0x1").splitlines()) != 1:
304         raise Exception("Unexpected RANGE=1-1 result")
305     if len(dev[0].request("BSS RANGE=" + str(int(id2) + 1) + "-" + str(int(id2) + 10) + " MASK=0x1").splitlines()) != 0:
306         raise Exception("Unexpected RANGE=2-10 result")
307     if len(dev[0].request("BSS RANGE=0-" + str(int(id2) + 10) + " MASK=0x1").splitlines()) != 2:
308         raise Exception("Unexpected RANGE=0-10 result")
309     if len(dev[0].request("BSS RANGE=" + id1 + "-" + id1 + " MASK=0x1").splitlines()) != 1:
310         raise Exception("Unexpected RANGE=0-0 result")
311
312     res = dev[0].request("BSS p2p_dev_addr=FOO")
313     if "FAIL" in res or "id=" in res:
314         raise Exception("Unexpected result: " + res)
315     res = dev[0].request("BSS p2p_dev_addr=00:11:22:33:44:55")
316     if "FAIL" in res or "id=" in res:
317         raise Exception("Unexpected result: " + res)
318
319     dev[0].request("BSS_FLUSH 1000")
320     res = dev[0].request("BSS RANGE=ALL MASK=0x1").splitlines()
321     if len(res) != 2:
322         raise Exception("Unexpected result after BSS_FLUSH 1000")
323     dev[0].request("BSS_FLUSH 0")
324     res = dev[0].request("BSS RANGE=ALL MASK=0x1").splitlines()
325     if len(res) != 0:
326         raise Exception("Unexpected result after BSS_FLUSH 0")
327
328 def test_scan_and_interface_disabled(dev, apdev):
329     """Scan operation when interface gets disabled"""
330     try:
331         dev[0].request("SCAN")
332         ev = dev[0].wait_event(["CTRL-EVENT-SCAN-STARTED"])
333         if ev is None:
334             raise Exception("Scan did not start")
335         dev[0].request("DRIVER_EVENT INTERFACE_DISABLED")
336         ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=7)
337         if ev is not None:
338             raise Exception("Scan completed unexpectedly")
339
340         # verify that scan is rejected
341         if "FAIL" not in dev[0].request("SCAN"):
342             raise Exception("New scan request was accepted unexpectedly")
343
344         dev[0].request("DRIVER_EVENT INTERFACE_ENABLED")
345         dev[0].scan(freq="2412")
346     finally:
347         dev[0].request("DRIVER_EVENT INTERFACE_ENABLED")
348
349 def test_scan_for_auth(dev, apdev):
350     """cfg80211 workaround with scan-for-auth"""
351     hapd = hostapd.add_ap(apdev[0], { "ssid": "open" })
352     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
353     # Block sme-connect radio work with an external radio work item, so that
354     # SELECT_NETWORK can decide to use fast associate without a new scan while
355     # cfg80211 still has the matching BSS entry, but the actual connection is
356     # not yet started.
357     id = dev[0].request("RADIO_WORK add block-work")
358     ev = dev[0].wait_event(["EXT-RADIO-WORK-START"])
359     if ev is None:
360         raise Exception("Timeout while waiting radio work to start")
361     dev[0].connect("open", key_mgmt="NONE", scan_freq="2412",
362                    wait_connect=False)
363     dev[0].dump_monitor()
364     # Clear cfg80211 BSS table.
365     try:
366         subprocess.check_call(['iw', dev[0].ifname, 'scan', 'trigger',
367                                'freq', '2457', 'flush'])
368     except subprocess.CalledProcessError, e:
369         raise HwsimSkip("iw scan trigger flush not supported")
370     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
371     if ev is None:
372         raise Exception("External flush scan timed out")
373     # Release blocking radio work to allow connection to go through with the
374     # cfg80211 BSS entry missing.
375     dev[0].request("RADIO_WORK done " + id)
376
377     dev[0].wait_connected(timeout=15)
378
379 def test_scan_for_auth_fail(dev, apdev):
380     """cfg80211 workaround with scan-for-auth failing"""
381     hapd = hostapd.add_ap(apdev[0], { "ssid": "open" })
382     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
383     # Block sme-connect radio work with an external radio work item, so that
384     # SELECT_NETWORK can decide to use fast associate without a new scan while
385     # cfg80211 still has the matching BSS entry, but the actual connection is
386     # not yet started.
387     id = dev[0].request("RADIO_WORK add block-work")
388     ev = dev[0].wait_event(["EXT-RADIO-WORK-START"])
389     if ev is None:
390         raise Exception("Timeout while waiting radio work to start")
391     dev[0].connect("open", key_mgmt="NONE", scan_freq="2412",
392                    wait_connect=False)
393     dev[0].dump_monitor()
394     hapd.disable()
395     # Clear cfg80211 BSS table.
396     try:
397         subprocess.check_call(['iw', dev[0].ifname, 'scan', 'trigger',
398                                'freq', '2457', 'flush'])
399     except subprocess.CalledProcessError, e:
400         raise HwsimSkip("iw scan trigger flush not supported")
401     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
402     if ev is None:
403         raise Exception("External flush scan timed out")
404     # Release blocking radio work to allow connection to go through with the
405     # cfg80211 BSS entry missing.
406     dev[0].request("RADIO_WORK done " + id)
407
408     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS",
409                             "CTRL-EVENT-CONNECTED"], 15)
410     if ev is None:
411         raise Exception("Scan event missing")
412     if "CTRL-EVENT-CONNECTED" in ev:
413         raise Exception("Unexpected connection")
414     dev[0].request("DISCONNECT")
415
416 def test_scan_for_auth_wep(dev, apdev):
417     """cfg80211 scan-for-auth workaround with WEP keys"""
418     dev[0].flush_scan_cache()
419     hapd = hostapd.add_ap(apdev[0],
420                           { "ssid": "wep", "wep_key0": '"abcde"',
421                             "auth_algs": "2" })
422     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
423     # Block sme-connect radio work with an external radio work item, so that
424     # SELECT_NETWORK can decide to use fast associate without a new scan while
425     # cfg80211 still has the matching BSS entry, but the actual connection is
426     # not yet started.
427     id = dev[0].request("RADIO_WORK add block-work")
428     ev = dev[0].wait_event(["EXT-RADIO-WORK-START"])
429     if ev is None:
430         raise Exception("Timeout while waiting radio work to start")
431     dev[0].connect("wep", key_mgmt="NONE", wep_key0='"abcde"',
432                    auth_alg="SHARED", scan_freq="2412", wait_connect=False)
433     dev[0].dump_monitor()
434     # Clear cfg80211 BSS table.
435     try:
436         subprocess.check_call(['iw', dev[0].ifname, 'scan', 'trigger',
437                                'freq', '2457', 'flush'])
438     except subprocess.CalledProcessError, e:
439         raise HwsimSkip("iw scan trigger flush not supported")
440     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
441     if ev is None:
442         raise Exception("External flush scan timed out")
443     # Release blocking radio work to allow connection to go through with the
444     # cfg80211 BSS entry missing.
445     dev[0].request("RADIO_WORK done " + id)
446
447     dev[0].wait_connected(timeout=15)
448
449 def test_scan_hidden(dev, apdev):
450     """Control interface behavior on scan parameters"""
451     hapd = hostapd.add_ap(apdev[0], { "ssid": "test-scan",
452                                       "ignore_broadcast_ssid": "1" })
453     bssid = apdev[0]['bssid']
454
455     check_scan(dev[0], "freq=2412 use_id=1")
456     if "test-scan" in dev[0].request("SCAN_RESULTS"):
457         raise Exception("BSS unexpectedly found in initial scan")
458
459     id1 = dev[0].connect("foo", key_mgmt="NONE", scan_ssid="1",
460                          only_add_network=True)
461     id2 = dev[0].connect("test-scan", key_mgmt="NONE", scan_ssid="1",
462                          only_add_network=True)
463     id3 = dev[0].connect("bar", key_mgmt="NONE", only_add_network=True)
464
465     check_scan(dev[0], "freq=2412 use_id=1")
466     if "test-scan" in dev[0].request("SCAN_RESULTS"):
467         raise Exception("BSS unexpectedly found in scan")
468
469     # Allow multiple attempts to be more robust under heavy CPU load that can
470     # result in Probe Response frames getting sent only after the station has
471     # already stopped waiting for the response on the channel.
472     found = False
473     for i in range(10):
474         check_scan(dev[0], "scan_id=%d,%d,%d freq=2412 use_id=1" % (id1, id2, id3))
475         if "test-scan" in dev[0].request("SCAN_RESULTS"):
476             found = True
477             break
478     if not found:
479         raise Exception("BSS not found in scan")
480
481     if "FAIL" not in dev[0].request("SCAN scan_id=1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17"):
482         raise Exception("Too many scan_id values accepted")
483
484     # Duplicate SSID removal
485     check_scan(dev[0], "scan_id=%d,%d,%d freq=2412 use_id=1" % (id1, id1, id2))
486
487     dev[0].request("REMOVE_NETWORK all")
488     hapd.disable()
489     dev[0].flush_scan_cache(freq=2432)
490     dev[0].flush_scan_cache()
491
492 def test_scan_and_bss_entry_removed(dev, apdev):
493     """Last scan result and connect work processing on BSS entry update"""
494     hapd = hostapd.add_ap(apdev[0], { "ssid": "open",
495                                       "eap_server": "1",
496                                       "wps_state": "2" })
497     bssid = apdev[0]['bssid']
498
499     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
500     wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
501
502     # Add a BSS entry
503     dev[0].scan_for_bss(bssid, freq="2412")
504     wpas.scan_for_bss(bssid, freq="2412")
505
506     # Start a connect radio work with a blocking entry preventing this from
507     # proceeding; this stores a pointer to the selected BSS entry.
508     id = dev[0].request("RADIO_WORK add block-work")
509     w_id = wpas.request("RADIO_WORK add block-work")
510     dev[0].wait_event(["EXT-RADIO-WORK-START"], timeout=1)
511     wpas.wait_event(["EXT-RADIO-WORK-START"], timeout=1)
512     nid = dev[0].connect("open", key_mgmt="NONE", scan_freq="2412",
513                          wait_connect=False)
514     w_nid = wpas.connect("open", key_mgmt="NONE", scan_freq="2412",
515                          wait_connect=False)
516     time.sleep(0.1)
517
518     # Remove the BSS entry
519     dev[0].request("BSS_FLUSH 0")
520     wpas.request("BSS_FLUSH 0")
521
522     # Allow the connect radio work to continue. The bss entry stored in the
523     # pending connect work is now stale. This will result in the connection
524     # attempt failing since the BSS entry does not exist.
525     dev[0].request("RADIO_WORK done " + id)
526     wpas.request("RADIO_WORK done " + w_id)
527
528     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
529     if ev is not None:
530         raise Exception("Unexpected connection")
531     dev[0].remove_network(nid)
532     ev = wpas.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
533     if ev is not None:
534         raise Exception("Unexpected connection")
535     wpas.remove_network(w_nid)
536     time.sleep(0.5)
537     dev[0].request("BSS_FLUSH 0")
538     wpas.request("BSS_FLUSH 0")
539
540     # Add a BSS entry
541     dev[0].scan_for_bss(bssid, freq="2412")
542     wpas.scan_for_bss(bssid, freq="2412")
543
544     # Start a connect radio work with a blocking entry preventing this from
545     # proceeding; this stores a pointer to the selected BSS entry.
546     id = dev[0].request("RADIO_WORK add block-work")
547     w_id = wpas.request("RADIO_WORK add block-work")
548     dev[0].wait_event(["EXT-RADIO-WORK-START"], timeout=1)
549     wpas.wait_event(["EXT-RADIO-WORK-START"], timeout=1)
550
551     # Schedule a connection based on the current BSS entry.
552     dev[0].connect("open", key_mgmt="NONE", scan_freq="2412",
553                    wait_connect=False)
554     wpas.connect("open", key_mgmt="NONE", scan_freq="2412",
555                  wait_connect=False)
556
557     # Update scan results with results that have longer set of IEs so that new
558     # memory needs to be allocated for the BSS entry.
559     hapd.request("WPS_PBC")
560     time.sleep(0.1)
561     subprocess.call(['iw', dev[0].ifname, 'scan', 'trigger', 'freq', '2412'])
562     subprocess.call(['iw', wpas.ifname, 'scan', 'trigger', 'freq', '2412'])
563     time.sleep(0.1)
564
565     # Allow the connect radio work to continue. The bss entry stored in the
566     # pending connect work becomes stale during the scan and it must have been
567     # updated for the connection to work.
568     dev[0].request("RADIO_WORK done " + id)
569     wpas.request("RADIO_WORK done " + w_id)
570
571     dev[0].wait_connected(timeout=15, error="No connection (sme-connect)")
572     wpas.wait_connected(timeout=15, error="No connection (connect)")
573     dev[0].request("DISCONNECT")
574     wpas.request("DISCONNECT")
575     dev[0].flush_scan_cache()
576     wpas.flush_scan_cache()
577
578 def test_scan_reqs_with_non_scan_radio_work(dev, apdev):
579     """SCAN commands while non-scan radio_work is in progress"""
580     id = dev[0].request("RADIO_WORK add test-work-a")
581     ev = dev[0].wait_event(["EXT-RADIO-WORK-START"])
582     if ev is None:
583         raise Exception("Timeout while waiting radio work to start")
584
585     if "OK" not in dev[0].request("SCAN"):
586         raise Exception("SCAN failed")
587     if "FAIL-BUSY" not in dev[0].request("SCAN"):
588         raise Exception("SCAN accepted while one is already pending")
589     if "FAIL-BUSY" not in dev[0].request("SCAN"):
590         raise Exception("SCAN accepted while one is already pending")
591
592     res = dev[0].request("RADIO_WORK show").splitlines()
593     count = 0
594     for l in res:
595         if "scan" in l:
596             count += 1
597     if count != 1:
598         logger.info(res)
599         raise Exception("Unexpected number of scan radio work items")
600
601     dev[0].dump_monitor()
602     dev[0].request("RADIO_WORK done " + id)
603     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-STARTED"], timeout=5)
604     if ev is None:
605         raise Exception("Scan did not start")
606     if "FAIL-BUSY" not in dev[0].request("SCAN"):
607         raise Exception("SCAN accepted while one is already in progress")
608
609     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
610     if ev is None:
611         print "Scan did not complete"
612     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-STARTED"], timeout=0.2)
613     if ev is not None:
614         raise Exception("Unexpected scan started")
615
616 def test_scan_setband(dev, apdev):
617     """Band selection for scan operations"""
618     try:
619         hapd = None
620         hapd2 = None
621         params = { "ssid": "test-setband",
622                    "hw_mode": "a",
623                    "channel": "36",
624                    "country_code": "US" }
625         hapd = hostapd.add_ap(apdev[0], params)
626         bssid = apdev[0]['bssid']
627
628         params = { "ssid": "test-setband",
629                    "hw_mode": "g",
630                    "channel": "1" }
631         hapd2 = hostapd.add_ap(apdev[1], params)
632         bssid2 = apdev[1]['bssid']
633
634         if "FAIL" not in dev[0].request("SET setband FOO"):
635             raise Exception("Invalid set setband accepted")
636         if "OK" not in dev[0].request("SET setband AUTO"):
637             raise Exception("Failed to set setband")
638         if "OK" not in dev[1].request("SET setband 5G"):
639             raise Exception("Failed to set setband")
640         if "OK" not in dev[2].request("SET setband 2G"):
641             raise Exception("Failed to set setband")
642
643         # Allow a retry to avoid reporting errors during heavy load
644         for j in range(5):
645             for i in range(3):
646                 dev[i].request("SCAN only_new=1")
647
648             for i in range(3):
649                 ev = dev[i].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
650                 if ev is None:
651                     raise Exception("Scan timed out")
652
653             res0 = dev[0].request("SCAN_RESULTS")
654             res1 = dev[1].request("SCAN_RESULTS")
655             res2 = dev[2].request("SCAN_RESULTS")
656             if bssid in res0 and bssid2 in res0 and bssid in res1 and bssid2 in res2:
657                 break
658
659         res = dev[0].request("SCAN_RESULTS")
660         if bssid not in res or bssid2 not in res:
661             raise Exception("Missing scan result(0)")
662
663         res = dev[1].request("SCAN_RESULTS")
664         if bssid not in res:
665             raise Exception("Missing scan result(1)")
666         if bssid2 in res:
667             raise Exception("Unexpected scan result(1)")
668
669         res = dev[2].request("SCAN_RESULTS")
670         if bssid2 not in res:
671             raise Exception("Missing scan result(2)")
672         if bssid in res:
673             raise Exception("Unexpected scan result(2)")
674     finally:
675         if hapd:
676             hapd.request("DISABLE")
677         if hapd2:
678             hapd2.request("DISABLE")
679         subprocess.call(['iw', 'reg', 'set', '00'])
680         for i in range(3):
681             dev[i].request("SET setband AUTO")
682             dev[i].flush_scan_cache()
683
684 def test_scan_hidden_many(dev, apdev):
685     """scan_ssid=1 with large number of profile with hidden SSID"""
686     try:
687         _test_scan_hidden_many(dev, apdev)
688     finally:
689         dev[0].flush_scan_cache(freq=2432)
690         dev[0].flush_scan_cache()
691         dev[0].request("SCAN_INTERVAL 5")
692
693 def _test_scan_hidden_many(dev, apdev):
694     hapd = hostapd.add_ap(apdev[0], { "ssid": "test-scan-ssid",
695                                       "ignore_broadcast_ssid": "1" })
696     bssid = apdev[0]['bssid']
697
698     dev[0].request("SCAN_INTERVAL 1")
699
700     for i in range(5):
701         id = dev[0].add_network()
702         dev[0].set_network_quoted(id, "ssid", "foo")
703         dev[0].set_network(id, "key_mgmt", "NONE")
704         dev[0].set_network(id, "disabled", "0")
705         dev[0].set_network(id, "scan_freq", "2412")
706         dev[0].set_network(id, "scan_ssid", "1")
707
708     dev[0].set_network_quoted(id, "ssid", "test-scan-ssid")
709     dev[0].set_network(id, "key_mgmt", "NONE")
710     dev[0].set_network(id, "disabled", "0")
711     dev[0].set_network(id, "scan_freq", "2412")
712     dev[0].set_network(id, "scan_ssid", "1")
713
714     for i in range(5):
715         id = dev[0].add_network()
716         dev[0].set_network_quoted(id, "ssid", "foo")
717         dev[0].set_network(id, "key_mgmt", "NONE")
718         dev[0].set_network(id, "disabled", "0")
719         dev[0].set_network(id, "scan_freq", "2412")
720         dev[0].set_network(id, "scan_ssid", "1")
721
722     dev[0].request("REASSOCIATE")
723     dev[0].wait_connected(timeout=30)
724     dev[0].request("REMOVE_NETWORK all")
725     hapd.disable()
726
727 def test_scan_random_mac(dev, apdev, params):
728     """Random MAC address in scans"""
729     try:
730         _test_scan_random_mac(dev, apdev, params)
731     finally:
732         dev[0].request("MAC_RAND_SCAN all enable=0")
733
734 def _test_scan_random_mac(dev, apdev, params):
735     hostapd.add_ap(apdev[0], { "ssid": "test-scan" })
736     bssid = apdev[0]['bssid']
737
738     tests = [ "",
739               "addr=foo",
740               "mask=foo",
741               "enable=1",
742               "all enable=1 mask=00:11:22:33:44:55",
743               "all enable=1 addr=00:11:22:33:44:55",
744               "all enable=1 addr=01:11:22:33:44:55 mask=ff:ff:ff:ff:ff:ff",
745               "all enable=1 addr=00:11:22:33:44:55 mask=fe:ff:ff:ff:ff:ff",
746               "enable=2 scan sched pno all",
747               "pno enable=1",
748               "all enable=2",
749               "foo" ]
750     for args in tests:
751         if "FAIL" not in dev[0].request("MAC_RAND_SCAN " + args):
752             raise Exception("Invalid MAC_RAND_SCAN accepted: " + args)
753
754     if dev[0].get_driver_status_field('capa.mac_addr_rand_scan_supported') != '1':
755         raise HwsimSkip("Driver does not support random MAC address for scanning")
756
757     tests = [ "all enable=1",
758               "all enable=1 addr=f2:11:22:33:44:55 mask=ff:ff:ff:ff:ff:ff",
759               "all enable=1 addr=f2:11:33:00:00:00 mask=ff:ff:ff:00:00:00" ]
760     for args in tests:
761         dev[0].request("MAC_RAND_SCAN " + args)
762         dev[0].scan_for_bss(bssid, freq=2412, force_scan=True)
763
764     out = run_tshark(os.path.join(params['logdir'], "hwsim0.pcapng"),
765                      "wlan.fc.type_subtype == 4", ["wlan.ta" ])
766     if out is not None:
767         addr = out.splitlines()
768         logger.info("Probe Request frames seen from: " + str(addr))
769         if dev[0].own_addr() in addr:
770             raise Exception("Real address used to transmit Probe Request frame")
771         if "f2:11:22:33:44:55" not in addr:
772             raise Exception("Fully configured random address not seen")
773         found = False
774         for a in addr:
775             if a.startswith('f2:11:33'):
776                 found = True
777                 break
778         if not found:
779             raise Exception("Fixed OUI random address not seen")
780
781 def test_scan_trigger_failure(dev, apdev):
782     """Scan trigger to the driver failing"""
783     hostapd.add_ap(apdev[0], { "ssid": "test-scan" })
784     bssid = apdev[0]['bssid']
785
786     if "OK" not in dev[0].request("SET test_failure 1"):
787         raise Exception("Failed to set test_failure")
788
789     if "OK" not in dev[0].request("SCAN"):
790         raise Exception("SCAN command failed")
791     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-FAILED"], timeout=10)
792     if ev is None:
793         raise Exception("Did not receive CTRL-EVENT-SCAN-FAILED event")
794     if "retry=1" in ev:
795         raise Exception("Unexpected scan retry indicated")
796     if dev[0].get_status_field('wpa_state') == "SCANNING":
797         raise Exception("wpa_state SCANNING not cleared")
798
799     id = dev[0].connect("test-scan", key_mgmt="NONE", scan_freq="2412",
800                         only_add_network=True)
801     dev[0].select_network(id)
802     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-FAILED"], timeout=10)
803     if ev is None:
804         raise Exception("Did not receive CTRL-EVENT-SCAN-FAILED event")
805     if "retry=1" not in ev:
806         raise Exception("No scan retry indicated for connection")
807     if dev[0].get_status_field('wpa_state') == "SCANNING":
808         raise Exception("wpa_state SCANNING not cleared")
809     dev[0].request("SET test_failure 0")
810     dev[0].wait_connected()
811
812     dev[0].request("SET test_failure 1")
813     if "OK" not in dev[0].request("SCAN"):
814         raise Exception("SCAN command failed")
815     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-FAILED"], timeout=10)
816     if ev is None:
817         raise Exception("Did not receive CTRL-EVENT-SCAN-FAILED event")
818     if "retry=1" in ev:
819         raise Exception("Unexpected scan retry indicated")
820     if dev[0].get_status_field('wpa_state') != "COMPLETED":
821         raise Exception("wpa_state COMPLETED not restored")
822     dev[0].request("SET test_failure 0")
823
824 def test_scan_specify_ssid(dev, apdev):
825     """Control interface behavior on scan SSID parameter"""
826     dev[0].flush_scan_cache()
827     hapd = hostapd.add_ap(apdev[0], { "ssid": "test-hidden",
828                                       "ignore_broadcast_ssid": "1" })
829     bssid = apdev[0]['bssid']
830     check_scan(dev[0], "freq=2412 use_id=1 ssid 414243")
831     bss = dev[0].get_bss(bssid)
832     if bss is not None and bss['ssid'] == 'test-hidden':
833         raise Exception("BSS entry for hidden AP present unexpectedly")
834     # Allow couple more retries to avoid reporting errors during heavy load
835     for i in range(5):
836         check_scan(dev[0], "freq=2412 ssid 414243 ssid 746573742d68696464656e ssid 616263313233 use_id=1")
837         bss = dev[0].get_bss(bssid)
838         if bss and 'test-hidden' in dev[0].request("SCAN_RESULTS"):
839             break
840     if bss is None:
841         raise Exception("BSS entry for hidden AP not found")
842     if 'test-hidden' not in dev[0].request("SCAN_RESULTS"):
843         raise Exception("Expected SSID not included in the scan results");
844
845     hapd.disable()
846     dev[0].flush_scan_cache(freq=2432)
847     dev[0].flush_scan_cache()
848
849     if "FAIL" not in dev[0].request("SCAN ssid foo"):
850         raise Exception("Invalid SCAN command accepted")
851
852 def test_scan_ap_scan_2_ap_mode(dev, apdev):
853     """AP_SCAN 2 AP mode and scan()"""
854     try:
855         _test_scan_ap_scan_2_ap_mode(dev, apdev)
856     finally:
857         dev[0].request("AP_SCAN 1")
858
859 def _test_scan_ap_scan_2_ap_mode(dev, apdev):
860     if "OK" not in dev[0].request("AP_SCAN 2"):
861         raise Exception("Failed to set AP_SCAN 2")
862
863     id = dev[0].add_network()
864     dev[0].set_network(id, "mode", "2")
865     dev[0].set_network_quoted(id, "ssid", "wpas-ap-open")
866     dev[0].set_network(id, "key_mgmt", "NONE")
867     dev[0].set_network(id, "frequency", "2412")
868     dev[0].set_network(id, "scan_freq", "2412")
869     dev[0].set_network(id, "disabled", "0")
870     dev[0].select_network(id)
871     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=5)
872     if ev is None:
873         raise Exception("AP failed to start")
874
875     with fail_test(dev[0], 1, "wpa_driver_nl80211_scan"):
876         if "OK" not in dev[0].request("SCAN freq=2412"):
877             raise Exception("SCAN command failed unexpectedly")
878         ev = dev[0].wait_event(["CTRL-EVENT-SCAN-FAILED",
879                                 "AP-DISABLED"], timeout=5)
880         if ev is None:
881             raise Exception("CTRL-EVENT-SCAN-FAILED not seen")
882         if "AP-DISABLED" in ev:
883             raise Exception("Unexpected AP-DISABLED event")
884         if "retry=1" in ev:
885             # Wait for the retry to scan happen
886             ev = dev[0].wait_event(["CTRL-EVENT-SCAN-FAILED",
887                                     "AP-DISABLED"], timeout=5)
888             if ev is None:
889                 raise Exception("CTRL-EVENT-SCAN-FAILED not seen - retry")
890             if "AP-DISABLED" in ev:
891                 raise Exception("Unexpected AP-DISABLED event - retry")
892
893     dev[1].connect("wpas-ap-open", key_mgmt="NONE", scan_freq="2412")
894     dev[1].request("DISCONNECT")
895     dev[1].wait_disconnected()
896     dev[0].request("DISCONNECT")
897     dev[0].wait_disconnected()
898
899 def test_scan_bss_expiration_on_ssid_change(dev, apdev):
900     """BSS entry expiration when AP changes SSID"""
901     dev[0].flush_scan_cache()
902     hapd = hostapd.add_ap(apdev[0], { "ssid": "test-scan" })
903     bssid = apdev[0]['bssid']
904     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
905
906     hapd.request("DISABLE")
907     hapd = hostapd.add_ap(apdev[0], { "ssid": "open" })
908     if "OK" not in dev[0].request("BSS_EXPIRE_COUNT 3"):
909         raise Exception("BSS_EXPIRE_COUNT failed")
910     dev[0].scan(freq="2412")
911     dev[0].scan(freq="2412")
912     if "OK" not in dev[0].request("BSS_EXPIRE_COUNT 2"):
913         raise Exception("BSS_EXPIRE_COUNT failed")
914     res = dev[0].request("SCAN_RESULTS")
915     if "test-scan" not in res:
916         raise Exception("The first SSID not in scan results")
917     if "open" not in res:
918         raise Exception("The second SSID not in scan results")
919     dev[0].connect("open", key_mgmt="NONE")
920
921     dev[0].request("BSS_FLUSH 0")
922     res = dev[0].request("SCAN_RESULTS")
923     if "test-scan" in res:
924         raise Exception("The BSS entry with the old SSID was not removed")
925     dev[0].request("DISCONNECT")
926     dev[0].wait_disconnected()
927
928 def test_scan_dfs(dev, apdev, params):
929     """Scan on DFS channels"""
930     try:
931         _test_scan_dfs(dev, apdev, params)
932     finally:
933         subprocess.call(['iw', 'reg', 'set', '00'])
934
935 def _test_scan_dfs(dev, apdev, params):
936     subprocess.call(['iw', 'reg', 'set', 'US'])
937     for i in range(2):
938         for j in range(5):
939             ev = dev[i].wait_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=5)
940             if ev is None:
941                 raise Exception("No regdom change event")
942             if "alpha2=US" in ev:
943                 break
944         dev[i].dump_monitor()
945
946     if "OK" not in dev[0].request("SCAN"):
947         raise Exception("SCAN command failed")
948     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
949     if ev is None:
950         raise Exception("Scan did not complete")
951
952     if "OK" not in dev[0].request("SCAN freq=2412,5180,5260,5500,5600,5745"):
953         raise Exception("SCAN command failed")
954     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
955     if ev is None:
956         raise Exception("Scan did not complete")
957
958     out = run_tshark(os.path.join(params['logdir'], "hwsim0.pcapng"),
959                      "wlan.fc.type_subtype == 4", [ "radiotap.channel.freq" ])
960     if out is not None:
961         freq = out.splitlines()
962         freq = [int(f) for f in freq]
963         freq = list(set(freq))
964         freq.sort()
965         logger.info("Active scan seen on channels: " + str(freq))
966         for f in freq:
967             if (f >= 5260 and f <= 5320) or (f >= 5500 and f <= 5700):
968                 raise Exception("Active scan on DFS channel: %d" % f)
969             if f in [ 2467, 2472 ]:
970                 raise Exception("Active scan on US-disallowed channel: %d" % f)
971
972 def test_scan_abort(dev, apdev):
973     """Aborting a full scan"""
974     dev[0].request("SCAN")
975     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-STARTED"])
976     if ev is None:
977         raise Exception("Scan did not start")
978     if "OK" not in dev[0].request("ABORT_SCAN"):
979         raise Exception("ABORT_SCAN command failed")
980     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=2)
981     if ev is None:
982         raise Exception("Scan did not terminate")
983
984 def test_scan_abort_on_connect(dev, apdev):
985     """Aborting a full scan on connection request"""
986     hostapd.add_ap(apdev[0], { "ssid": "test-scan" })
987     bssid = apdev[0]['bssid']
988
989     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
990     dev[0].dump_monitor()
991     dev[0].request("SCAN")
992     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-STARTED"])
993     if ev is None:
994         raise Exception("Scan did not start")
995     dev[0].connect("test-scan", key_mgmt="NONE")
996
997 def test_scan_ext(dev, apdev):
998     """Custom IE in Probe Request frame"""
999     hostapd.add_ap(apdev[0], { "ssid": "test-scan" })
1000     bssid = apdev[0]['bssid']
1001
1002     try:
1003         if "OK" not in dev[0].request("VENDOR_ELEM_ADD 14 dd050011223300"):
1004             raise Exception("VENDOR_ELEM_ADD failed")
1005         check_scan(dev[0], "freq=2412 use_id=1")
1006     finally:
1007         dev[0].request("VENDOR_ELEM_REMOVE 14 *")
1008
1009 def test_scan_fail(dev, apdev):
1010     """Scan failures"""
1011     with fail_test(dev[0], 1, "wpa_driver_nl80211_scan"):
1012         dev[0].request("DISCONNECT")
1013         if "OK" not in dev[0].request("SCAN freq=2412"):
1014             raise Exception("SCAN failed")
1015         ev = dev[0].wait_event(["CTRL-EVENT-SCAN-FAILED"], timeout=5)
1016         if ev is None:
1017             raise Exception("Did not see scan failure event")
1018     dev[0].dump_monitor()
1019
1020     for i in range(1, 5):
1021         with alloc_fail(dev[0], i,
1022                         "wpa_scan_clone_params;wpa_supplicant_trigger_scan"):
1023             if "OK" not in dev[0].request("SCAN ssid 112233 freq=2412"):
1024                 raise Exception("SCAN failed")
1025             ev = dev[0].wait_event(["CTRL-EVENT-SCAN-FAILED"], timeout=5)
1026             if ev is None:
1027                 raise Exception("Did not see scan failure event")
1028         dev[0].dump_monitor()
1029
1030     with alloc_fail(dev[0], 1, "radio_add_work;wpa_supplicant_trigger_scan"):
1031         if "OK" not in dev[0].request("SCAN freq=2412"):
1032             raise Exception("SCAN failed")
1033         ev = dev[0].wait_event(["CTRL-EVENT-SCAN-FAILED"], timeout=5)
1034         if ev is None:
1035             raise Exception("Did not see scan failure event")
1036     dev[0].dump_monitor()
1037
1038     try:
1039         if "OK" not in dev[0].request("SET filter_ssids 1"):
1040             raise Exception("SET failed")
1041         id = dev[0].connect("test-scan", key_mgmt="NONE", only_add_network=True)
1042         with alloc_fail(dev[0], 1, "wpa_supplicant_build_filter_ssids"):
1043             # While the filter list cannot be created due to memory allocation
1044             # failure, this scan is expected to be completed without SSID
1045             # filtering.
1046             if "OK" not in dev[0].request("SCAN freq=2412"):
1047                 raise Exception("SCAN failed")
1048             ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
1049             if ev is None:
1050                 raise Exception("Scan did not complete")
1051         dev[0].remove_network(id)
1052     finally:
1053         dev[0].request("SET filter_ssids 0")
1054     dev[0].dump_monitor()
1055
1056     with alloc_fail(dev[0], 1, "nl80211_get_scan_results"):
1057         if "OK" not in dev[0].request("SCAN freq=2412"):
1058             raise Exception("SCAN failed")
1059         ev = dev[0].wait_event(["CTRL-EVENT-SCAN-STARTED"], timeout=5)
1060         if ev is None:
1061             raise Exception("Did not see scan started event")
1062         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
1063     dev[0].dump_monitor()
1064
1065     try:
1066         if "OK" not in dev[0].request("SET setband 2G"):
1067             raise Exception("SET setband failed")
1068         with alloc_fail(dev[0], 1, "=wpa_setband_scan_freqs_list"):
1069             # While the frequency list cannot be created due to memory
1070             # allocation failure, this scan is expected to be completed without
1071             # frequency filtering.
1072             if "OK" not in dev[0].request("SCAN"):
1073                 raise Exception("SCAN failed")
1074             wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
1075             dev[0].request("ABORT_SCAN")
1076             ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
1077             if ev is None:
1078                 raise Exception("Scan did not complete")
1079     finally:
1080         dev[0].request("SET setband AUTO")
1081     dev[0].dump_monitor()
1082
1083     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
1084     wpas.interface_add("wlan5")
1085     wpas.request("SET preassoc_mac_addr 1")
1086     with fail_test(wpas, 1, "nl80211_set_mac_addr;wpas_trigger_scan_cb"):
1087         if "OK" not in wpas.request("SCAN freq=2412"):
1088             raise Exception("SCAN failed")
1089         ev = wpas.wait_event(["CTRL-EVENT-SCAN-FAILED"], timeout=5)
1090         if ev is None:
1091             raise Exception("Did not see scan failure event")
1092     wpas.request("SET preassoc_mac_addr 0")
1093     wpas.dump_monitor()