Updated through tag hostap_2_5 from git://w1.fi/hostap.git
[mech_eap.git] / libeap / 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
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]['ifname'], { "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]['ifname'], { "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]['ifname'], { "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]['ifname'], { "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]['ifname'], { "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]['ifname'], { "ssid": "test-scan" })
171         bssid = apdev[0]['bssid']
172         dev[0].scan(freq="2412")
173         if bssid not in dev[0].request("SCAN_RESULTS"):
174             raise Exception("BSS not found in initial scan")
175         hapd.request("DISABLE")
176         logger.info("Waiting for BSS entry to expire")
177         time.sleep(7)
178         if bssid not in dev[0].request("SCAN_RESULTS"):
179             raise Exception("BSS expired too quickly")
180         ev = dev[0].wait_event(["CTRL-EVENT-BSS-REMOVED"], timeout=15)
181         if ev is None:
182             raise Exception("BSS entry expiration timed out")
183         if bssid in dev[0].request("SCAN_RESULTS"):
184             raise Exception("BSS not removed after expiration time")
185     finally:
186         dev[0].request("BSS_EXPIRE_AGE 180")
187
188 def test_scan_filter(dev, apdev):
189     """Filter scan results based on SSID"""
190     try:
191         if "OK" not in dev[0].request("SET filter_ssids 1"):
192             raise Exception("SET failed")
193         id = dev[0].connect("test-scan", key_mgmt="NONE", only_add_network=True)
194         hostapd.add_ap(apdev[0]['ifname'], { "ssid": "test-scan" })
195         bssid = apdev[0]['bssid']
196         hostapd.add_ap(apdev[1]['ifname'], { "ssid": "test-scan2" })
197         bssid2 = apdev[1]['bssid']
198         dev[0].scan(freq="2412", only_new=True)
199         if bssid not in dev[0].request("SCAN_RESULTS"):
200             raise Exception("BSS not found in scan results")
201         if bssid2 in dev[0].request("SCAN_RESULTS"):
202             raise Exception("Unexpected BSS found in scan results")
203         dev[0].set_network_quoted(id, "ssid", "")
204         dev[0].scan(freq="2412")
205         id2 = dev[0].connect("test", key_mgmt="NONE", only_add_network=True)
206         dev[0].scan(freq="2412")
207     finally:
208         dev[0].request("SET filter_ssids 0")
209
210 def test_scan_int(dev, apdev):
211     """scan interval configuration"""
212     try:
213         if "FAIL" not in dev[0].request("SCAN_INTERVAL -1"):
214             raise Exception("Accepted invalid scan interval")
215         if "OK" not in dev[0].request("SCAN_INTERVAL 1"):
216             raise Exception("Failed to set scan interval")
217         dev[0].connect("not-used", key_mgmt="NONE", scan_freq="2412",
218                        wait_connect=False)
219         times = {}
220         for i in range(0, 3):
221             logger.info("Waiting for scan to start")
222             start = os.times()[4]
223             ev = dev[0].wait_event(["CTRL-EVENT-SCAN-STARTED"], timeout=5)
224             if ev is None:
225                 raise Exception("did not start a scan")
226             stop = os.times()[4]
227             times[i] = stop - start
228             logger.info("Waiting for scan to complete")
229             ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 10)
230             if ev is None:
231                 raise Exception("did not complete a scan")
232         logger.info("times=" + str(times))
233         if times[0] > 1 or times[1] < 0.5 or times[1] > 1.5 or times[2] < 0.5 or times[2] > 1.5:
234             raise Exception("Unexpected scan timing: " + str(times))
235     finally:
236         dev[0].request("SCAN_INTERVAL 5")
237
238 def test_scan_bss_operations(dev, apdev):
239     """Control interface behavior on BSS parameters"""
240     hostapd.add_ap(apdev[0]['ifname'], { "ssid": "test-scan" })
241     bssid = apdev[0]['bssid']
242     hostapd.add_ap(apdev[1]['ifname'], { "ssid": "test2-scan" })
243     bssid2 = apdev[1]['bssid']
244
245     dev[0].scan(freq="2412")
246     dev[0].scan(freq="2412")
247     dev[0].scan(freq="2412")
248
249     id1 = dev[0].request("BSS FIRST MASK=0x1").splitlines()[0].split('=')[1]
250     id2 = dev[0].request("BSS LAST MASK=0x1").splitlines()[0].split('=')[1]
251
252     res = dev[0].request("BSS RANGE=ALL MASK=0x20001")
253     if "id=" + id1 not in res:
254         raise Exception("Missing BSS " + id1)
255     if "id=" + id2 not in res:
256         raise Exception("Missing BSS " + id2)
257     if "====" not in res:
258         raise Exception("Missing delim")
259     if "####" not in res:
260         raise Exception("Missing end")
261
262     res = dev[0].request("BSS RANGE=ALL MASK=0")
263     if "id=" + id1 not in res:
264         raise Exception("Missing BSS " + id1)
265     if "id=" + id2 not in res:
266         raise Exception("Missing BSS " + id2)
267     if "====" in res:
268         raise Exception("Unexpected delim")
269     if "####" in res:
270         raise Exception("Unexpected end delim")
271
272     res = dev[0].request("BSS RANGE=ALL MASK=0x1").splitlines()
273     if len(res) != 2:
274         raise Exception("Unexpected result: " + str(res))
275     res = dev[0].request("BSS FIRST MASK=0x1")
276     if "id=" + id1 not in res:
277         raise Exception("Unexpected result: " + res)
278     res = dev[0].request("BSS LAST MASK=0x1")
279     if "id=" + id2 not in res:
280         raise Exception("Unexpected result: " + res)
281     res = dev[0].request("BSS ID-" + id1 + " MASK=0x1")
282     if "id=" + id1 not in res:
283         raise Exception("Unexpected result: " + res)
284     res = dev[0].request("BSS NEXT-" + id1 + " MASK=0x1")
285     if "id=" + id2 not in res:
286         raise Exception("Unexpected result: " + res)
287     res = dev[0].request("BSS NEXT-" + id2 + " MASK=0x1")
288     if "id=" in res:
289         raise Exception("Unexpected result: " + res)
290
291     if len(dev[0].request("BSS RANGE=" + id2 + " MASK=0x1").splitlines()) != 0:
292         raise Exception("Unexpected RANGE=1 result")
293     if len(dev[0].request("BSS RANGE=" + id1 + "- MASK=0x1").splitlines()) != 2:
294         raise Exception("Unexpected RANGE=0- result")
295     if len(dev[0].request("BSS RANGE=-" + id2 + " MASK=0x1").splitlines()) != 2:
296         raise Exception("Unexpected RANGE=-1 result")
297     if len(dev[0].request("BSS RANGE=" + id1 + "-" + id2 + " MASK=0x1").splitlines()) != 2:
298         raise Exception("Unexpected RANGE=0-1 result")
299     if len(dev[0].request("BSS RANGE=" + id2 + "-" + id2 + " MASK=0x1").splitlines()) != 1:
300         raise Exception("Unexpected RANGE=1-1 result")
301     if len(dev[0].request("BSS RANGE=" + str(int(id2) + 1) + "-" + str(int(id2) + 10) + " MASK=0x1").splitlines()) != 0:
302         raise Exception("Unexpected RANGE=2-10 result")
303     if len(dev[0].request("BSS RANGE=0-" + str(int(id2) + 10) + " MASK=0x1").splitlines()) != 2:
304         raise Exception("Unexpected RANGE=0-10 result")
305     if len(dev[0].request("BSS RANGE=" + id1 + "-" + id1 + " MASK=0x1").splitlines()) != 1:
306         raise Exception("Unexpected RANGE=0-0 result")
307
308     res = dev[0].request("BSS p2p_dev_addr=FOO")
309     if "FAIL" in res or "id=" in res:
310         raise Exception("Unexpected result: " + res)
311     res = dev[0].request("BSS p2p_dev_addr=00:11:22:33:44:55")
312     if "FAIL" in res or "id=" in res:
313         raise Exception("Unexpected result: " + res)
314
315     dev[0].request("BSS_FLUSH 1000")
316     res = dev[0].request("BSS RANGE=ALL MASK=0x1").splitlines()
317     if len(res) != 2:
318         raise Exception("Unexpected result after BSS_FLUSH 1000")
319     dev[0].request("BSS_FLUSH 0")
320     res = dev[0].request("BSS RANGE=ALL MASK=0x1").splitlines()
321     if len(res) != 0:
322         raise Exception("Unexpected result after BSS_FLUSH 0")
323
324 def test_scan_and_interface_disabled(dev, apdev):
325     """Scan operation when interface gets disabled"""
326     try:
327         dev[0].request("SCAN")
328         ev = dev[0].wait_event(["CTRL-EVENT-SCAN-STARTED"])
329         if ev is None:
330             raise Exception("Scan did not start")
331         dev[0].request("DRIVER_EVENT INTERFACE_DISABLED")
332         ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=7)
333         if ev is not None:
334             raise Exception("Scan completed unexpectedly")
335
336         # verify that scan is rejected
337         if "FAIL" not in dev[0].request("SCAN"):
338             raise Exception("New scan request was accepted unexpectedly")
339
340         dev[0].request("DRIVER_EVENT INTERFACE_ENABLED")
341         dev[0].scan(freq="2412")
342     finally:
343         dev[0].request("DRIVER_EVENT INTERFACE_ENABLED")
344
345 def test_scan_for_auth(dev, apdev):
346     """cfg80211 workaround with scan-for-auth"""
347     hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid": "open" })
348     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
349     # Block sme-connect radio work with an external radio work item, so that
350     # SELECT_NETWORK can decide to use fast associate without a new scan while
351     # cfg80211 still has the matching BSS entry, but the actual connection is
352     # not yet started.
353     id = dev[0].request("RADIO_WORK add block-work")
354     ev = dev[0].wait_event(["EXT-RADIO-WORK-START"])
355     if ev is None:
356         raise Exception("Timeout while waiting radio work to start")
357     dev[0].connect("open", key_mgmt="NONE", scan_freq="2412",
358                    wait_connect=False)
359     dev[0].dump_monitor()
360     # Clear cfg80211 BSS table.
361     try:
362         subprocess.check_call(['iw', dev[0].ifname, 'scan', 'trigger',
363                                'freq', '2457', 'flush'])
364     except subprocess.CalledProcessError, e:
365         raise HwsimSkip("iw scan trigger flush not supported")
366     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
367     if ev is None:
368         raise Exception("External flush scan timed out")
369     # Release blocking radio work to allow connection to go through with the
370     # cfg80211 BSS entry missing.
371     dev[0].request("RADIO_WORK done " + id)
372
373     dev[0].wait_connected(timeout=15)
374
375 def test_scan_for_auth_fail(dev, apdev):
376     """cfg80211 workaround with scan-for-auth failing"""
377     hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid": "open" })
378     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
379     # Block sme-connect radio work with an external radio work item, so that
380     # SELECT_NETWORK can decide to use fast associate without a new scan while
381     # cfg80211 still has the matching BSS entry, but the actual connection is
382     # not yet started.
383     id = dev[0].request("RADIO_WORK add block-work")
384     ev = dev[0].wait_event(["EXT-RADIO-WORK-START"])
385     if ev is None:
386         raise Exception("Timeout while waiting radio work to start")
387     dev[0].connect("open", key_mgmt="NONE", scan_freq="2412",
388                    wait_connect=False)
389     dev[0].dump_monitor()
390     hapd.disable()
391     # Clear cfg80211 BSS table.
392     try:
393         subprocess.check_call(['iw', dev[0].ifname, 'scan', 'trigger',
394                                'freq', '2457', 'flush'])
395     except subprocess.CalledProcessError, e:
396         raise HwsimSkip("iw scan trigger flush not supported")
397     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
398     if ev is None:
399         raise Exception("External flush scan timed out")
400     # Release blocking radio work to allow connection to go through with the
401     # cfg80211 BSS entry missing.
402     dev[0].request("RADIO_WORK done " + id)
403
404     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS",
405                             "CTRL-EVENT-CONNECTED"], 15)
406     if ev is None:
407         raise Exception("Scan event missing")
408     if "CTRL-EVENT-CONNECTED" in ev:
409         raise Exception("Unexpected connection")
410     dev[0].request("DISCONNECT")
411
412 def test_scan_for_auth_wep(dev, apdev):
413     """cfg80211 scan-for-auth workaround with WEP keys"""
414     dev[0].flush_scan_cache()
415     hapd = hostapd.add_ap(apdev[0]['ifname'],
416                           { "ssid": "wep", "wep_key0": '"abcde"',
417                             "auth_algs": "2" })
418     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
419     # Block sme-connect radio work with an external radio work item, so that
420     # SELECT_NETWORK can decide to use fast associate without a new scan while
421     # cfg80211 still has the matching BSS entry, but the actual connection is
422     # not yet started.
423     id = dev[0].request("RADIO_WORK add block-work")
424     ev = dev[0].wait_event(["EXT-RADIO-WORK-START"])
425     if ev is None:
426         raise Exception("Timeout while waiting radio work to start")
427     dev[0].connect("wep", key_mgmt="NONE", wep_key0='"abcde"',
428                    auth_alg="SHARED", scan_freq="2412", wait_connect=False)
429     dev[0].dump_monitor()
430     # Clear cfg80211 BSS table.
431     try:
432         subprocess.check_call(['iw', dev[0].ifname, 'scan', 'trigger',
433                                'freq', '2457', 'flush'])
434     except subprocess.CalledProcessError, e:
435         raise HwsimSkip("iw scan trigger flush not supported")
436     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
437     if ev is None:
438         raise Exception("External flush scan timed out")
439     # Release blocking radio work to allow connection to go through with the
440     # cfg80211 BSS entry missing.
441     dev[0].request("RADIO_WORK done " + id)
442
443     dev[0].wait_connected(timeout=15)
444
445 def test_scan_hidden(dev, apdev):
446     """Control interface behavior on scan parameters"""
447     hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid": "test-scan",
448                                                 "ignore_broadcast_ssid": "1" })
449     bssid = apdev[0]['bssid']
450
451     check_scan(dev[0], "freq=2412 use_id=1")
452     if "test-scan" in dev[0].request("SCAN_RESULTS"):
453         raise Exception("BSS unexpectedly found in initial scan")
454
455     id1 = dev[0].connect("foo", key_mgmt="NONE", scan_ssid="1",
456                          only_add_network=True)
457     id2 = dev[0].connect("test-scan", key_mgmt="NONE", scan_ssid="1",
458                          only_add_network=True)
459     id3 = dev[0].connect("bar", key_mgmt="NONE", only_add_network=True)
460
461     check_scan(dev[0], "freq=2412 use_id=1")
462     if "test-scan" in dev[0].request("SCAN_RESULTS"):
463         raise Exception("BSS unexpectedly found in scan")
464
465     # Allow multiple attempts to be more robust under heavy CPU load that can
466     # result in Probe Response frames getting sent only after the station has
467     # already stopped waiting for the response on the channel.
468     found = False
469     for i in range(10):
470         check_scan(dev[0], "scan_id=%d,%d,%d freq=2412 use_id=1" % (id1, id2, id3))
471         if "test-scan" in dev[0].request("SCAN_RESULTS"):
472             found = True
473             break
474     if not found:
475         raise Exception("BSS not found in scan")
476
477     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"):
478         raise Exception("Too many scan_id values accepted")
479
480     dev[0].request("REMOVE_NETWORK all")
481     hapd.disable()
482     dev[0].flush_scan_cache(freq=2432)
483     dev[0].flush_scan_cache()
484
485 def test_scan_and_bss_entry_removed(dev, apdev):
486     """Last scan result and connect work processing on BSS entry update"""
487     hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid": "open",
488                                                 "eap_server": "1",
489                                                 "wps_state": "2" })
490     bssid = apdev[0]['bssid']
491
492     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
493     wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
494
495     # Add a BSS entry
496     dev[0].scan_for_bss(bssid, freq="2412")
497     wpas.scan_for_bss(bssid, freq="2412")
498
499     # Start a connect radio work with a blocking entry preventing this from
500     # proceeding; this stores a pointer to the selected BSS entry.
501     id = dev[0].request("RADIO_WORK add block-work")
502     w_id = wpas.request("RADIO_WORK add block-work")
503     dev[0].wait_event(["EXT-RADIO-WORK-START"], timeout=1)
504     wpas.wait_event(["EXT-RADIO-WORK-START"], timeout=1)
505     nid = dev[0].connect("open", key_mgmt="NONE", scan_freq="2412",
506                          wait_connect=False)
507     w_nid = wpas.connect("open", key_mgmt="NONE", scan_freq="2412",
508                          wait_connect=False)
509     time.sleep(0.1)
510
511     # Remove the BSS entry
512     dev[0].request("BSS_FLUSH 0")
513     wpas.request("BSS_FLUSH 0")
514
515     # Allow the connect radio work to continue. The bss entry stored in the
516     # pending connect work is now stale. This will result in the connection
517     # attempt failing since the BSS entry does not exist.
518     dev[0].request("RADIO_WORK done " + id)
519     wpas.request("RADIO_WORK done " + w_id)
520
521     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
522     if ev is not None:
523         raise Exception("Unexpected connection")
524     dev[0].remove_network(nid)
525     ev = wpas.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
526     if ev is not None:
527         raise Exception("Unexpected connection")
528     wpas.remove_network(w_nid)
529     time.sleep(0.5)
530     dev[0].request("BSS_FLUSH 0")
531     wpas.request("BSS_FLUSH 0")
532
533     # Add a BSS entry
534     dev[0].scan_for_bss(bssid, freq="2412")
535     wpas.scan_for_bss(bssid, freq="2412")
536
537     # Start a connect radio work with a blocking entry preventing this from
538     # proceeding; this stores a pointer to the selected BSS entry.
539     id = dev[0].request("RADIO_WORK add block-work")
540     w_id = wpas.request("RADIO_WORK add block-work")
541     dev[0].wait_event(["EXT-RADIO-WORK-START"], timeout=1)
542     wpas.wait_event(["EXT-RADIO-WORK-START"], timeout=1)
543
544     # Schedule a connection based on the current BSS entry.
545     dev[0].connect("open", key_mgmt="NONE", scan_freq="2412",
546                    wait_connect=False)
547     wpas.connect("open", key_mgmt="NONE", scan_freq="2412",
548                  wait_connect=False)
549
550     # Update scan results with results that have longer set of IEs so that new
551     # memory needs to be allocated for the BSS entry.
552     hapd.request("WPS_PBC")
553     time.sleep(0.1)
554     subprocess.call(['iw', dev[0].ifname, 'scan', 'trigger', 'freq', '2412'])
555     subprocess.call(['iw', wpas.ifname, 'scan', 'trigger', 'freq', '2412'])
556     time.sleep(0.1)
557
558     # Allow the connect radio work to continue. The bss entry stored in the
559     # pending connect work becomes stale during the scan and it must have been
560     # updated for the connection to work.
561     dev[0].request("RADIO_WORK done " + id)
562     wpas.request("RADIO_WORK done " + w_id)
563
564     dev[0].wait_connected(timeout=15, error="No connection (sme-connect)")
565     wpas.wait_connected(timeout=15, error="No connection (connect)")
566     dev[0].request("DISCONNECT")
567     wpas.request("DISCONNECT")
568     dev[0].flush_scan_cache()
569     wpas.flush_scan_cache()
570
571 def test_scan_reqs_with_non_scan_radio_work(dev, apdev):
572     """SCAN commands while non-scan radio_work is in progress"""
573     id = dev[0].request("RADIO_WORK add test-work-a")
574     ev = dev[0].wait_event(["EXT-RADIO-WORK-START"])
575     if ev is None:
576         raise Exception("Timeout while waiting radio work to start")
577
578     if "OK" not in dev[0].request("SCAN"):
579         raise Exception("SCAN failed")
580     if "FAIL-BUSY" not in dev[0].request("SCAN"):
581         raise Exception("SCAN accepted while one is already pending")
582     if "FAIL-BUSY" not in dev[0].request("SCAN"):
583         raise Exception("SCAN accepted while one is already pending")
584
585     res = dev[0].request("RADIO_WORK show").splitlines()
586     count = 0
587     for l in res:
588         if "scan" in l:
589             count += 1
590     if count != 1:
591         logger.info(res)
592         raise Exception("Unexpected number of scan radio work items")
593
594     dev[0].dump_monitor()
595     dev[0].request("RADIO_WORK done " + id)
596     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-STARTED"], timeout=5)
597     if ev is None:
598         raise Exception("Scan did not start")
599     if "FAIL-BUSY" not in dev[0].request("SCAN"):
600         raise Exception("SCAN accepted while one is already in progress")
601
602     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
603     if ev is None:
604         print "Scan did not complete"
605     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-STARTED"], timeout=0.2)
606     if ev is not None:
607         raise Exception("Unexpected scan started")
608
609 def test_scan_setband(dev, apdev):
610     """Band selection for scan operations"""
611     try:
612         hapd = None
613         hapd2 = None
614         params = { "ssid": "test-setband",
615                    "hw_mode": "a",
616                    "channel": "36",
617                    "country_code": "US" }
618         hapd = hostapd.add_ap(apdev[0]['ifname'], params)
619         bssid = apdev[0]['bssid']
620
621         params = { "ssid": "test-setband",
622                    "hw_mode": "g",
623                    "channel": "1" }
624         hapd2 = hostapd.add_ap(apdev[1]['ifname'], params)
625         bssid2 = apdev[1]['bssid']
626
627         if "FAIL" not in dev[0].request("SET setband FOO"):
628             raise Exception("Invalid set setband accepted")
629         if "OK" not in dev[0].request("SET setband AUTO"):
630             raise Exception("Failed to set setband")
631         if "OK" not in dev[1].request("SET setband 5G"):
632             raise Exception("Failed to set setband")
633         if "OK" not in dev[2].request("SET setband 2G"):
634             raise Exception("Failed to set setband")
635
636         for i in range(3):
637             dev[i].request("SCAN only_new=1")
638
639         for i in range(3):
640             ev = dev[i].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
641             if ev is None:
642                 raise Exception("Scan timed out")
643
644         res = dev[0].request("SCAN_RESULTS")
645         if bssid not in res or bssid2 not in res:
646             raise Exception("Missing scan result(0)")
647
648         res = dev[1].request("SCAN_RESULTS")
649         if bssid not in res:
650             raise Exception("Missing scan result(1)")
651         if bssid2 in res:
652             raise Exception("Unexpected scan result(1)")
653
654         res = dev[2].request("SCAN_RESULTS")
655         if bssid2 not in res:
656             raise Exception("Missing scan result(2)")
657         if bssid in res:
658             raise Exception("Unexpected scan result(2)")
659     finally:
660         if hapd:
661             hapd.request("DISABLE")
662         if hapd2:
663             hapd2.request("DISABLE")
664         subprocess.call(['iw', 'reg', 'set', '00'])
665         for i in range(3):
666             dev[i].request("SET setband AUTO")
667             dev[i].flush_scan_cache()
668
669 def test_scan_hidden_many(dev, apdev):
670     """scan_ssid=1 with large number of profile with hidden SSID"""
671     try:
672         _test_scan_hidden_many(dev, apdev)
673     finally:
674         dev[0].flush_scan_cache(freq=2432)
675         dev[0].flush_scan_cache()
676         dev[0].request("SCAN_INTERVAL 5")
677
678 def _test_scan_hidden_many(dev, apdev):
679     hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid": "test-scan-ssid",
680                                                 "ignore_broadcast_ssid": "1" })
681     bssid = apdev[0]['bssid']
682
683     dev[0].request("SCAN_INTERVAL 1")
684
685     for i in range(5):
686         id = dev[0].add_network()
687         dev[0].set_network_quoted(id, "ssid", "foo")
688         dev[0].set_network(id, "key_mgmt", "NONE")
689         dev[0].set_network(id, "disabled", "0")
690         dev[0].set_network(id, "scan_freq", "2412")
691         dev[0].set_network(id, "scan_ssid", "1")
692
693     dev[0].set_network_quoted(id, "ssid", "test-scan-ssid")
694     dev[0].set_network(id, "key_mgmt", "NONE")
695     dev[0].set_network(id, "disabled", "0")
696     dev[0].set_network(id, "scan_freq", "2412")
697     dev[0].set_network(id, "scan_ssid", "1")
698
699     for i in range(5):
700         id = dev[0].add_network()
701         dev[0].set_network_quoted(id, "ssid", "foo")
702         dev[0].set_network(id, "key_mgmt", "NONE")
703         dev[0].set_network(id, "disabled", "0")
704         dev[0].set_network(id, "scan_freq", "2412")
705         dev[0].set_network(id, "scan_ssid", "1")
706
707     dev[0].request("REASSOCIATE")
708     dev[0].wait_connected(timeout=30)
709     dev[0].request("REMOVE_NETWORK all")
710     hapd.disable()
711
712 def test_scan_random_mac(dev, apdev, params):
713     """Random MAC address in scans"""
714     try:
715         _test_scan_random_mac(dev, apdev, params)
716     finally:
717         dev[0].request("MAC_RAND_SCAN all enable=0")
718
719 def _test_scan_random_mac(dev, apdev, params):
720     hostapd.add_ap(apdev[0]['ifname'], { "ssid": "test-scan" })
721     bssid = apdev[0]['bssid']
722
723     tests = [ "",
724               "addr=foo",
725               "mask=foo",
726               "enable=1",
727               "all enable=1 mask=00:11:22:33:44:55",
728               "all enable=1 addr=00:11:22:33:44:55",
729               "all enable=1 addr=01:11:22:33:44:55 mask=ff:ff:ff:ff:ff:ff",
730               "all enable=1 addr=00:11:22:33:44:55 mask=fe:ff:ff:ff:ff:ff",
731               "enable=2 scan sched pno all",
732               "pno enable=1",
733               "all enable=2",
734               "foo" ]
735     for args in tests:
736         if "FAIL" not in dev[0].request("MAC_RAND_SCAN " + args):
737             raise Exception("Invalid MAC_RAND_SCAN accepted: " + args)
738
739     if dev[0].get_driver_status_field('capa.mac_addr_rand_scan_supported') != '1':
740         raise HwsimSkip("Driver does not support random MAC address for scanning")
741
742     tests = [ "all enable=1",
743               "all enable=1 addr=f2:11:22:33:44:55 mask=ff:ff:ff:ff:ff:ff",
744               "all enable=1 addr=f2:11:33:00:00:00 mask=ff:ff:ff:00:00:00" ]
745     for args in tests:
746         dev[0].request("MAC_RAND_SCAN " + args)
747         dev[0].scan_for_bss(bssid, freq=2412, force_scan=True)
748
749     out = run_tshark(os.path.join(params['logdir'], "hwsim0.pcapng"),
750                      "wlan.fc.type_subtype == 4", ["wlan.ta" ])
751     if out is not None:
752         addr = out.splitlines()
753         logger.info("Probe Request frames seen from: " + str(addr))
754         if dev[0].own_addr() in addr:
755             raise Exception("Real address used to transmit Probe Request frame")
756         if "f2:11:22:33:44:55" not in addr:
757             raise Exception("Fully configured random address not seen")
758         found = False
759         for a in addr:
760             if a.startswith('f2:11:33'):
761                 found = True
762                 break
763         if not found:
764             raise Exception("Fixed OUI random address not seen")
765
766 def test_scan_trigger_failure(dev, apdev):
767     """Scan trigger to the driver failing"""
768     hostapd.add_ap(apdev[0]['ifname'], { "ssid": "test-scan" })
769     bssid = apdev[0]['bssid']
770
771     if "OK" not in dev[0].request("SET test_failure 1"):
772         raise Exception("Failed to set test_failure")
773
774     if "OK" not in dev[0].request("SCAN"):
775         raise Exception("SCAN command failed")
776     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-FAILED"], timeout=10)
777     if ev is None:
778         raise Exception("Did not receive CTRL-EVENT-SCAN-FAILED event")
779     if "retry=1" in ev:
780         raise Exception("Unexpected scan retry indicated")
781     if dev[0].get_status_field('wpa_state') == "SCANNING":
782         raise Exception("wpa_state SCANNING not cleared")
783
784     id = dev[0].connect("test-scan", key_mgmt="NONE", scan_freq="2412",
785                         only_add_network=True)
786     dev[0].select_network(id)
787     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-FAILED"], timeout=10)
788     if ev is None:
789         raise Exception("Did not receive CTRL-EVENT-SCAN-FAILED event")
790     if "retry=1" not in ev:
791         raise Exception("No scan retry indicated for connection")
792     if dev[0].get_status_field('wpa_state') == "SCANNING":
793         raise Exception("wpa_state SCANNING not cleared")
794     dev[0].request("SET test_failure 0")
795     dev[0].wait_connected()
796
797     dev[0].request("SET test_failure 1")
798     if "OK" not in dev[0].request("SCAN"):
799         raise Exception("SCAN command failed")
800     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-FAILED"], timeout=10)
801     if ev is None:
802         raise Exception("Did not receive CTRL-EVENT-SCAN-FAILED event")
803     if "retry=1" in ev:
804         raise Exception("Unexpected scan retry indicated")
805     if dev[0].get_status_field('wpa_state') != "COMPLETED":
806         raise Exception("wpa_state COMPLETED not restored")
807     dev[0].request("SET test_failure 0")
808
809 def test_scan_specify_ssid(dev, apdev):
810     """Control interface behavior on scan SSID parameter"""
811     dev[0].flush_scan_cache()
812     hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid": "test-hidden",
813                                                 "ignore_broadcast_ssid": "1" })
814     bssid = apdev[0]['bssid']
815     check_scan(dev[0], "freq=2412 use_id=1 ssid 414243")
816     bss = dev[0].get_bss(bssid)
817     if bss is not None and bss['ssid'] == 'test-hidden':
818         raise Exception("BSS entry for hidden AP present unexpectedly")
819     check_scan(dev[0], "freq=2412 ssid 414243 ssid 746573742d68696464656e ssid 616263313233 use_id=1")
820     bss = dev[0].get_bss(bssid)
821     if bss is None:
822         raise Exception("BSS entry for hidden AP not found")
823     if 'test-hidden' not in dev[0].request("SCAN_RESULTS"):
824         raise Exception("Expected SSID not included in the scan results");
825
826     hapd.disable()
827     dev[0].flush_scan_cache(freq=2432)
828     dev[0].flush_scan_cache()
829
830     if "FAIL" not in dev[0].request("SCAN ssid foo"):
831         raise Exception("Invalid SCAN command accepted")
832
833 def test_scan_ap_scan_2_ap_mode(dev, apdev):
834     """AP_SCAN 2 AP mode and scan()"""
835     try:
836         _test_scan_ap_scan_2_ap_mode(dev, apdev)
837     finally:
838         dev[0].request("AP_SCAN 1")
839
840 def _test_scan_ap_scan_2_ap_mode(dev, apdev):
841     if "OK" not in dev[0].request("AP_SCAN 2"):
842         raise Exception("Failed to set AP_SCAN 2")
843
844     id = dev[0].add_network()
845     dev[0].set_network(id, "mode", "2")
846     dev[0].set_network_quoted(id, "ssid", "wpas-ap-open")
847     dev[0].set_network(id, "key_mgmt", "NONE")
848     dev[0].set_network(id, "frequency", "2412")
849     dev[0].set_network(id, "scan_freq", "2412")
850     dev[0].set_network(id, "disabled", "0")
851     dev[0].select_network(id)
852     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=5)
853     if ev is None:
854         raise Exception("AP failed to start")
855
856     with fail_test(dev[0], 1, "wpa_driver_nl80211_scan"):
857         if "OK" not in dev[0].request("SCAN freq=2412"):
858             raise Exception("SCAN command failed unexpectedly")
859         ev = dev[0].wait_event(["CTRL-EVENT-SCAN-FAILED",
860                                 "AP-DISABLED"], timeout=5)
861         if ev is None:
862             raise Exception("CTRL-EVENT-SCAN-FAILED not seen")
863         if "AP-DISABLED" in ev:
864             raise Exception("Unexpected AP-DISABLED event")
865         if "retry=1" in ev:
866             # Wait for the retry to scan happen
867             ev = dev[0].wait_event(["CTRL-EVENT-SCAN-FAILED",
868                                     "AP-DISABLED"], timeout=5)
869             if ev is None:
870                 raise Exception("CTRL-EVENT-SCAN-FAILED not seen - retry")
871             if "AP-DISABLED" in ev:
872                 raise Exception("Unexpected AP-DISABLED event - retry")
873
874     dev[1].connect("wpas-ap-open", key_mgmt="NONE", scan_freq="2412")
875     dev[1].request("DISCONNECT")
876     dev[1].wait_disconnected()
877     dev[0].request("DISCONNECT")
878     dev[0].wait_disconnected()
879
880 def test_scan_bss_expiration_on_ssid_change(dev, apdev):
881     """BSS entry expiration when AP changes SSID"""
882     dev[0].flush_scan_cache()
883     hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid": "test-scan" })
884     bssid = apdev[0]['bssid']
885     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
886
887     hapd.request("DISABLE")
888     hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid": "open" })
889     if "OK" not in dev[0].request("BSS_EXPIRE_COUNT 3"):
890         raise Exception("BSS_EXPIRE_COUNT failed")
891     dev[0].scan(freq="2412")
892     dev[0].scan(freq="2412")
893     if "OK" not in dev[0].request("BSS_EXPIRE_COUNT 2"):
894         raise Exception("BSS_EXPIRE_COUNT failed")
895     res = dev[0].request("SCAN_RESULTS")
896     if "test-scan" not in res:
897         raise Exception("The first SSID not in scan results")
898     if "open" not in res:
899         raise Exception("The second SSID not in scan results")
900     dev[0].connect("open", key_mgmt="NONE")
901
902     dev[0].request("BSS_FLUSH 0")
903     res = dev[0].request("SCAN_RESULTS")
904     if "test-scan" in res:
905         raise Exception("The BSS entry with the old SSID was not removed")
906     dev[0].request("DISCONNECT")
907     dev[0].wait_disconnected()