tests: Modify autogo_scan to support P2P Device interface
[mech_eap.git] / tests / hwsim / test_p2p_autogo.py
1 # P2P autonomous GO test cases
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 subprocess
9 import logging
10 logger = logging.getLogger()
11
12 import hwsim_utils
13 import utils
14 from utils import HwsimSkip
15 from wlantest import Wlantest
16 from wpasupplicant import WpaSupplicant
17 from p2p_utils import *
18 from test_p2p_messages import mgmt_tx, parse_p2p_public_action
19
20 def test_autogo(dev):
21     """P2P autonomous GO and client joining group"""
22     addr0 = dev[0].p2p_dev_addr()
23     addr2 = dev[2].p2p_dev_addr()
24     res = autogo(dev[0])
25     if "p2p-wlan" in res['ifname']:
26         raise Exception("Unexpected group interface name on GO")
27     res = connect_cli(dev[0], dev[1])
28     if "p2p-wlan" in res['ifname']:
29         raise Exception("Unexpected group interface name on client")
30     bss = dev[1].get_bss("p2p_dev_addr=" + addr0, res['ifname'])
31     if not bss or bss['bssid'] != dev[0].p2p_interface_addr():
32         raise Exception("Unexpected BSSID in the BSS entry for the GO")
33     id = bss['id']
34     bss = dev[1].get_bss("ID-" + id, res['ifname'])
35     if not bss or bss['id'] != id:
36         raise Exception("Could not find BSS entry based on id")
37     res = dev[1].group_request("BSS RANGE=" + id + "- MASK=0x1")
38     if "id=" + id not in res:
39         raise Exception("Could not find BSS entry based on id range")
40
41     res = dev[1].request("SCAN_RESULTS")
42     if "[P2P]" not in res:
43         raise Exception("P2P flag missing from scan results: " + res)
44
45     # Presence request to increase testing coverage
46     if "FAIL" not in dev[1].group_request("P2P_PRESENCE_REQ 30000"):
47         raise Exception("Invald P2P_PRESENCE_REQ accepted")
48     if "FAIL" not in dev[1].group_request("P2P_PRESENCE_REQ 30000 102400 30001"):
49         raise Exception("Invald P2P_PRESENCE_REQ accepted")
50     if "FAIL" in dev[1].group_request("P2P_PRESENCE_REQ 30000 102400"):
51         raise Exception("Could not send presence request")
52     ev = dev[1].wait_group_event(["P2P-PRESENCE-RESPONSE"], 10)
53     if ev is None:
54         raise Exception("Timeout while waiting for Presence Response")
55     if "FAIL" in dev[1].group_request("P2P_PRESENCE_REQ 30000 102400 20000 102400"):
56         raise Exception("Could not send presence request")
57     ev = dev[1].wait_group_event(["P2P-PRESENCE-RESPONSE"])
58     if ev is None:
59         raise Exception("Timeout while waiting for Presence Response")
60     if "FAIL" in dev[1].group_request("P2P_PRESENCE_REQ"):
61         raise Exception("Could not send presence request")
62     ev = dev[1].wait_group_event(["P2P-PRESENCE-RESPONSE"])
63     if ev is None:
64         raise Exception("Timeout while waiting for Presence Response")
65
66     if not dev[2].discover_peer(addr0):
67         raise Exception("Could not discover GO")
68     dev[0].dump_monitor()
69     dev[2].global_request("P2P_PROV_DISC " + addr0 + " display join")
70     ev = dev[0].wait_global_event(["P2P-PROV-DISC-SHOW-PIN"], timeout=10)
71     if ev is None:
72         raise Exception("GO did not report P2P-PROV-DISC-SHOW-PIN")
73     if "p2p_dev_addr=" + addr2 not in ev:
74         raise Exception("Unexpected P2P Device Address in event: " + ev)
75     if "group=" + dev[0].group_ifname not in ev:
76         raise Exception("Unexpected group interface in event: " + ev)
77     ev = dev[2].wait_global_event(["P2P-PROV-DISC-ENTER-PIN"], timeout=10)
78     if ev is None:
79         raise Exception("P2P-PROV-DISC-ENTER-PIN not reported")
80
81     dev[0].remove_group()
82     dev[1].wait_go_ending_session()
83
84 def test_autogo2(dev):
85     """P2P autonomous GO with a separate group interface and client joining group"""
86     dev[0].request("SET p2p_no_group_iface 0")
87     res = autogo(dev[0], freq=2437)
88     if "p2p-wlan" not in res['ifname']:
89         raise Exception("Unexpected group interface name on GO")
90     if res['ifname'] not in utils.get_ifnames():
91         raise Exception("Could not find group interface netdev")
92     connect_cli(dev[0], dev[1], social=True, freq=2437)
93     dev[0].remove_group()
94     dev[1].wait_go_ending_session()
95     if res['ifname'] in utils.get_ifnames():
96         raise Exception("Group interface netdev was not removed")
97
98 def test_autogo3(dev):
99     """P2P autonomous GO and client with a separate group interface joining group"""
100     dev[1].request("SET p2p_no_group_iface 0")
101     autogo(dev[0], freq=2462)
102     res = connect_cli(dev[0], dev[1], social=True, freq=2462)
103     if "p2p-wlan" not in res['ifname']:
104         raise Exception("Unexpected group interface name on client")
105     if res['ifname'] not in utils.get_ifnames():
106         raise Exception("Could not find group interface netdev")
107     dev[0].remove_group()
108     dev[1].wait_go_ending_session()
109     dev[1].ping()
110     if res['ifname'] in utils.get_ifnames():
111         raise Exception("Group interface netdev was not removed")
112
113 def test_autogo4(dev):
114     """P2P autonomous GO and client joining group (both with a separate group interface)"""
115     dev[0].request("SET p2p_no_group_iface 0")
116     dev[1].request("SET p2p_no_group_iface 0")
117     res1 = autogo(dev[0], freq=2412)
118     res2 = connect_cli(dev[0], dev[1], social=True, freq=2412)
119     if "p2p-wlan" not in res1['ifname']:
120         raise Exception("Unexpected group interface name on GO")
121     if "p2p-wlan" not in res2['ifname']:
122         raise Exception("Unexpected group interface name on client")
123     ifnames = utils.get_ifnames()
124     if res1['ifname'] not in ifnames:
125         raise Exception("Could not find GO group interface netdev")
126     if res2['ifname'] not in ifnames:
127         raise Exception("Could not find client group interface netdev")
128     dev[0].remove_group()
129     dev[1].wait_go_ending_session()
130     dev[1].ping()
131     ifnames = utils.get_ifnames()
132     if res1['ifname'] in ifnames:
133         raise Exception("GO group interface netdev was not removed")
134     if res2['ifname'] in ifnames:
135         raise Exception("Client group interface netdev was not removed")
136
137 def test_autogo_m2d(dev):
138     """P2P autonomous GO and clients not authorized"""
139     autogo(dev[0], freq=2412)
140     go_addr = dev[0].p2p_dev_addr()
141
142     dev[1].request("SET p2p_no_group_iface 0")
143     if not dev[1].discover_peer(go_addr, social=True):
144         raise Exception("GO " + go_addr + " not found")
145     dev[1].dump_monitor()
146
147     if not dev[2].discover_peer(go_addr, social=True):
148         raise Exception("GO " + go_addr + " not found")
149     dev[2].dump_monitor()
150
151     logger.info("Trying to join the group when GO has not authorized the client")
152     pin = dev[1].wps_read_pin()
153     cmd = "P2P_CONNECT " + go_addr + " " + pin + " join"
154     if "OK" not in dev[1].global_request(cmd):
155         raise Exception("P2P_CONNECT join failed")
156
157     pin = dev[2].wps_read_pin()
158     cmd = "P2P_CONNECT " + go_addr + " " + pin + " join"
159     if "OK" not in dev[2].global_request(cmd):
160         raise Exception("P2P_CONNECT join failed")
161
162     ev = dev[1].wait_global_event(["WPS-M2D"], timeout=16)
163     if ev is None:
164         raise Exception("No global M2D event")
165     ifaces = dev[1].request("INTERFACES").splitlines()
166     iface = ifaces[0] if "p2p-wlan" in ifaces[0] else ifaces[1]
167     wpas = WpaSupplicant(ifname=iface)
168     ev = wpas.wait_event(["WPS-M2D"], timeout=10)
169     if ev is None:
170         raise Exception("No M2D event on group interface")
171
172     ev = dev[2].wait_global_event(["WPS-M2D"], timeout=10)
173     if ev is None:
174         raise Exception("No global M2D event (2)")
175     ev = dev[2].wait_event(["WPS-M2D"], timeout=10)
176     if ev is None:
177         raise Exception("No M2D event on group interface (2)")
178
179 def test_autogo_fail(dev):
180     """P2P autonomous GO and incorrect PIN"""
181     autogo(dev[0], freq=2412)
182     go_addr = dev[0].p2p_dev_addr()
183     dev[0].p2p_go_authorize_client("00000000")
184
185     dev[1].request("SET p2p_no_group_iface 0")
186     if not dev[1].discover_peer(go_addr, social=True):
187         raise Exception("GO " + go_addr + " not found")
188     dev[1].dump_monitor()
189
190     logger.info("Trying to join the group when GO has not authorized the client")
191     pin = dev[1].wps_read_pin()
192     cmd = "P2P_CONNECT " + go_addr + " " + pin + " join"
193     if "OK" not in dev[1].global_request(cmd):
194         raise Exception("P2P_CONNECT join failed")
195
196     ev = dev[1].wait_global_event(["WPS-FAIL"], timeout=10)
197     if ev is None:
198         raise Exception("No global WPS-FAIL event")
199
200 def test_autogo_2cli(dev):
201     """P2P autonomous GO and two clients joining group"""
202     autogo(dev[0], freq=2412)
203     connect_cli(dev[0], dev[1], social=True, freq=2412)
204     connect_cli(dev[0], dev[2], social=True, freq=2412)
205     hwsim_utils.test_connectivity_p2p(dev[1], dev[2])
206     dev[0].global_request("P2P_REMOVE_CLIENT " + dev[1].p2p_dev_addr())
207     dev[1].wait_go_ending_session()
208     dev[0].global_request("P2P_REMOVE_CLIENT iface=" + dev[2].p2p_interface_addr())
209     dev[2].wait_go_ending_session()
210     if "FAIL" not in dev[0].global_request("P2P_REMOVE_CLIENT foo"):
211         raise Exception("Invalid P2P_REMOVE_CLIENT command accepted")
212     dev[0].remove_group()
213
214 def test_autogo_pbc(dev):
215     """P2P autonomous GO and PBC"""
216     dev[1].global_request("SET p2p_no_group_iface 0")
217     autogo(dev[0], freq=2412)
218     if "FAIL" not in dev[0].group_request("WPS_PBC p2p_dev_addr=00:11:22:33:44"):
219         raise Exception("Invalid WPS_PBC succeeded")
220     if "OK" not in dev[0].group_request("WPS_PBC p2p_dev_addr=" + dev[1].p2p_dev_addr()):
221         raise Exception("WPS_PBC failed")
222     dev[2].p2p_connect_group(dev[0].p2p_dev_addr(), "pbc", timeout=0,
223                              social=True)
224     ev = dev[2].wait_global_event(["WPS-M2D"], timeout=15)
225     if ev is None:
226         raise Exception("WPS-M2D not reported")
227     if "config_error=12" not in ev:
228         raise Exception("Unexpected config_error: " + ev)
229     dev[1].p2p_connect_group(dev[0].p2p_dev_addr(), "pbc", timeout=15,
230                              social=True)
231
232 def test_autogo_tdls(dev):
233     """P2P autonomous GO and two clients using TDLS"""
234     wt = Wlantest()
235     go = dev[0]
236     logger.info("Start autonomous GO with fixed parameters " + go.ifname)
237     id = go.add_network()
238     go.set_network_quoted(id, "ssid", "DIRECT-tdls")
239     go.set_network_quoted(id, "psk", "12345678")
240     go.set_network(id, "mode", "3")
241     go.set_network(id, "disabled", "2")
242     res = go.p2p_start_go(persistent=id, freq="2462")
243     logger.debug("res: " + str(res))
244     wt.flush()
245     wt.add_passphrase("12345678")
246     connect_cli(go, dev[1], social=True, freq=2462)
247     connect_cli(go, dev[2], social=True, freq=2462)
248     hwsim_utils.test_connectivity_p2p(dev[1], dev[2])
249     bssid = dev[0].p2p_interface_addr()
250     addr1 = dev[1].p2p_interface_addr()
251     addr2 = dev[2].p2p_interface_addr()
252     dev[1].tdls_setup(addr2)
253     time.sleep(1)
254     hwsim_utils.test_connectivity_p2p(dev[1], dev[2])
255     conf = wt.get_tdls_counter("setup_conf_ok", bssid, addr1, addr2);
256     if conf == 0:
257         raise Exception("No TDLS Setup Confirm (success) seen")
258     dl = wt.get_tdls_counter("valid_direct_link", bssid, addr1, addr2);
259     if dl == 0:
260         raise Exception("No valid frames through direct link")
261     wt.tdls_clear(bssid, addr1, addr2);
262     dev[1].tdls_teardown(addr2)
263     time.sleep(1)
264     teardown = wt.get_tdls_counter("teardown", bssid, addr1, addr2);
265     if teardown == 0:
266         raise Exception("No TDLS Setup Teardown seen")
267     wt.tdls_clear(bssid, addr1, addr2);
268     hwsim_utils.test_connectivity_p2p(dev[1], dev[2])
269     ap_path = wt.get_tdls_counter("valid_ap_path", bssid, addr1, addr2);
270     if ap_path == 0:
271         raise Exception("No valid frames via AP path")
272     direct_link = wt.get_tdls_counter("valid_direct_link", bssid, addr1, addr2);
273     if direct_link > 0:
274         raise Exception("Unexpected frames through direct link")
275     idirect_link = wt.get_tdls_counter("invalid_direct_link", bssid, addr1,
276                                        addr2);
277     if idirect_link > 0:
278         raise Exception("Unexpected frames through direct link (invalid)")
279     dev[2].remove_group()
280     dev[1].remove_group()
281     dev[0].remove_group()
282
283 def test_autogo_legacy(dev):
284     """P2P autonomous GO and legacy clients"""
285     res = autogo(dev[0], freq=2462)
286     if dev[0].get_group_status_field("passphrase", extra="WPS") != res['passphrase']:
287         raise Exception("passphrase mismatch")
288     if dev[0].group_request("P2P_GET_PASSPHRASE") != res['passphrase']:
289         raise Exception("passphrase mismatch(2)")
290
291     logger.info("Connect P2P client")
292     connect_cli(dev[0], dev[1], social=True, freq=2462)
293
294     if "FAIL" not in dev[1].request("P2P_GET_PASSPHRASE"):
295         raise Exception("P2P_GET_PASSPHRASE succeeded on P2P Client")
296
297     logger.info("Connect legacy WPS client")
298     pin = dev[2].wps_read_pin()
299     dev[0].p2p_go_authorize_client(pin)
300     dev[2].request("P2P_SET disabled 1")
301     dev[2].dump_monitor()
302     dev[2].request("WPS_PIN any " + pin)
303     dev[2].wait_connected(timeout=30)
304     status = dev[2].get_status()
305     if status['wpa_state'] != 'COMPLETED':
306         raise Exception("Not fully connected")
307     hwsim_utils.test_connectivity_p2p_sta(dev[1], dev[2])
308     dev[2].request("DISCONNECT")
309
310     logger.info("Connect legacy non-WPS client")
311     dev[2].request("FLUSH")
312     dev[2].request("P2P_SET disabled 1")
313     dev[2].connect(ssid=res['ssid'], psk=res['passphrase'], proto='RSN',
314                    key_mgmt='WPA-PSK', pairwise='CCMP', group='CCMP',
315                    scan_freq=res['freq'])
316     hwsim_utils.test_connectivity_p2p_sta(dev[1], dev[2])
317     dev[2].request("DISCONNECT")
318
319     dev[0].remove_group()
320     dev[1].wait_go_ending_session()
321
322 def test_autogo_chan_switch(dev):
323     """P2P autonomous GO switching channels"""
324     autogo(dev[0], freq=2417)
325     connect_cli(dev[0], dev[1])
326     res = dev[0].request("CHAN_SWITCH 5 2422")
327     if "FAIL" in res:
328         # for now, skip test since mac80211_hwsim support is not yet widely
329         # deployed
330         raise HwsimSkip("Assume mac80211_hwsim did not support channel switching")
331     ev = dev[0].wait_event(["AP-CSA-FINISHED"], timeout=10)
332     if ev is None:
333         raise Exception("CSA finished event timed out")
334     if "freq=2422" not in ev:
335         raise Exception("Unexpected cahnnel in CSA finished event")
336     dev[0].dump_monitor()
337     dev[1].dump_monitor()
338     time.sleep(0.1)
339     hwsim_utils.test_connectivity_p2p(dev[0], dev[1])
340
341 def test_autogo_extra_cred(dev):
342     """P2P autonomous GO sending two WPS credentials"""
343     if "FAIL" in dev[0].request("SET wps_testing_dummy_cred 1"):
344         raise Exception("Failed to enable test mode")
345     autogo(dev[0], freq=2412)
346     connect_cli(dev[0], dev[1], social=True, freq=2412)
347     dev[0].remove_group()
348     dev[1].wait_go_ending_session()
349
350 def test_autogo_ifdown(dev):
351     """P2P autonomous GO and external ifdown"""
352     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
353     wpas.interface_add("wlan5")
354     res = autogo(wpas)
355     wpas.dump_monitor()
356     wpas.interface_remove("wlan5")
357     wpas.interface_add("wlan5")
358     res = autogo(wpas)
359     wpas.dump_monitor()
360     subprocess.call(['ifconfig', res['ifname'], 'down'])
361     ev = wpas.wait_global_event(["P2P-GROUP-REMOVED"], timeout=10)
362     if ev is None:
363         raise Exception("Group removal not reported")
364     if res['ifname'] not in ev:
365         raise Exception("Unexpected group removal event: " + ev)
366
367 def test_autogo_start_during_scan(dev):
368     """P2P autonomous GO started during ongoing manual scan"""
369     try:
370         # use autoscan to set scan_req = MANUAL_SCAN_REQ
371         if "OK" not in dev[0].request("AUTOSCAN periodic:1"):
372             raise Exception("Failed to set autoscan")
373         autogo(dev[0], freq=2462)
374         connect_cli(dev[0], dev[1], social=True, freq=2462)
375         dev[0].remove_group()
376         dev[1].wait_go_ending_session()
377     finally:
378         dev[0].request("AUTOSCAN ")
379
380 def test_autogo_passphrase_len(dev):
381     """P2P autonomous GO and longer passphrase"""
382     try:
383         if "OK" not in dev[0].request("SET p2p_passphrase_len 13"):
384             raise Exception("Failed to set passphrase length")
385         res = autogo(dev[0], freq=2412)
386         if len(res['passphrase']) != 13:
387             raise Exception("Unexpected passphrase length")
388         if dev[0].get_group_status_field("passphrase", extra="WPS") != res['passphrase']:
389             raise Exception("passphrase mismatch")
390
391         logger.info("Connect P2P client")
392         connect_cli(dev[0], dev[1], social=True, freq=2412)
393
394         logger.info("Connect legacy WPS client")
395         pin = dev[2].wps_read_pin()
396         dev[0].p2p_go_authorize_client(pin)
397         dev[2].request("P2P_SET disabled 1")
398         dev[2].dump_monitor()
399         dev[2].request("WPS_PIN any " + pin)
400         dev[2].wait_connected(timeout=30)
401         status = dev[2].get_status()
402         if status['wpa_state'] != 'COMPLETED':
403             raise Exception("Not fully connected")
404         dev[2].request("DISCONNECT")
405
406         logger.info("Connect legacy non-WPS client")
407         dev[2].request("FLUSH")
408         dev[2].request("P2P_SET disabled 1")
409         dev[2].connect(ssid=res['ssid'], psk=res['passphrase'], proto='RSN',
410                        key_mgmt='WPA-PSK', pairwise='CCMP', group='CCMP',
411                        scan_freq=res['freq'])
412         hwsim_utils.test_connectivity_p2p_sta(dev[1], dev[2])
413         dev[2].request("DISCONNECT")
414
415         dev[0].remove_group()
416         dev[1].wait_go_ending_session()
417     finally:
418         dev[0].request("SET p2p_passphrase_len 8")
419
420 def test_autogo_bridge(dev):
421     """P2P autonomous GO in a bridge"""
422     try:
423         # use autoscan to set scan_req = MANUAL_SCAN_REQ
424         if "OK" not in dev[0].request("AUTOSCAN periodic:1"):
425             raise Exception("Failed to set autoscan")
426         autogo(dev[0])
427         ifname = dev[0].get_group_ifname()
428         subprocess.call(['brctl', 'addbr', 'p2p-br0'])
429         subprocess.call(['brctl', 'setfd', 'p2p-br0', '0'])
430         subprocess.call(['brctl', 'addif', 'p2p-br0', ifname])
431         subprocess.call(['ip', 'link', 'set', 'dev', 'p2p-br0', 'up'])
432         time.sleep(0.1)
433         subprocess.call(['brctl', 'delif', 'p2p-br0', ifname])
434         time.sleep(0.1)
435         subprocess.call(['ip', 'link', 'set', 'dev', 'p2p-br0', 'down'])
436         time.sleep(0.1)
437         subprocess.call(['brctl', 'delbr', 'p2p-br0'])
438         ev = dev[0].wait_global_event(["P2P-GROUP-REMOVED"], timeout=1)
439         if ev is not None:
440             raise Exception("P2P group removed unexpectedly")
441         if dev[0].get_group_status_field('wpa_state') != "COMPLETED":
442             raise Exception("Unexpected wpa_state")
443         dev[0].remove_group()
444     finally:
445         dev[0].request("AUTOSCAN ")
446         subprocess.Popen(['brctl', 'delif', 'p2p-br0', ifname],
447                          stderr=open('/dev/null', 'w'))
448         subprocess.Popen(['ip', 'link', 'set', 'dev', 'p2p-br0', 'down'],
449                          stderr=open('/dev/null', 'w'))
450         subprocess.Popen(['brctl', 'delbr', 'p2p-br0'],
451                          stderr=open('/dev/null', 'w'))
452
453 def test_presence_req_on_group_interface(dev):
454     """P2P_PRESENCE_REQ on group interface"""
455     dev[1].request("SET p2p_no_group_iface 0")
456     res = autogo(dev[0], freq=2437)
457     res = connect_cli(dev[0], dev[1], social=True, freq=2437)
458     if "FAIL" in dev[1].group_request("P2P_PRESENCE_REQ 30000 102400"):
459         raise Exception("Could not send presence request")
460     ev = dev[1].wait_group_event(["P2P-PRESENCE-RESPONSE"])
461     if ev is None:
462         raise Exception("Timeout while waiting for Presence Response")
463     dev[0].remove_group()
464     dev[1].wait_go_ending_session()
465
466 def test_autogo_join_auto_go_not_found(dev):
467     """P2P_CONNECT-auto not finding GO"""
468     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
469     wpas.interface_add("wlan5")
470     wpas.request("P2P_SET listen_channel 1")
471     wpas.global_request("SET p2p_no_group_iface 0")
472     autogo(wpas, freq=2412)
473     addr = wpas.p2p_dev_addr()
474     bssid = wpas.p2p_interface_addr()
475     wpas.dump_monitor()
476
477     dev[1].global_request("SET p2p_no_group_iface 0")
478     dev[1].scan_for_bss(bssid, freq=2412)
479     # This makes the GO not show up in the scan iteration following the
480     # P2P_CONNECT command by stopping beaconing and handling Probe Request
481     # frames externally (but not really replying to them). P2P listen mode is
482     # needed to keep the GO listening on the operating channel for the PD
483     # exchange.
484     if "OK" not in wpas.group_request("STOP_AP"):
485         raise Exception("STOP_AP failed")
486     wpas.dump_monitor()
487     wpas.group_request("SET ext_mgmt_frame_handling 1")
488     wpas.p2p_listen()
489     wpas.dump_monitor()
490     time.sleep(0.02)
491     dev[1].global_request("P2P_CONNECT " + addr + " pbc auto")
492
493     ev = dev[1].wait_global_event(["P2P-FALLBACK-TO-GO-NEG-ENABLED"], 15)
494     wpas.dump_monitor()
495     if ev is None:
496         raise Exception("Could not trigger old-scan-only case")
497         return
498
499     ev = dev[1].wait_global_event(["P2P-FALLBACK-TO-GO-NEG"], 15)
500     wpas.remove_group()
501     if ev is None:
502         raise Exception("Fallback to GO Negotiation not seen")
503     if "reason=GO-not-found" not in ev:
504         raise Exception("Unexpected reason for fallback: " + ev)
505     wpas.dump_monitor()
506
507 def test_autogo_join_auto(dev):
508     """P2P_CONNECT-auto joining a group"""
509     autogo(dev[0])
510     addr = dev[0].p2p_dev_addr()
511     if "OK" not in dev[1].global_request("P2P_CONNECT " + addr + " pbc auto"):
512         raise Exception("P2P_CONNECT failed")
513
514     ev = dev[0].wait_global_event(["P2P-PROV-DISC-PBC-REQ"], timeout=15)
515     if ev is None:
516         raise Exception("Timeout on P2P-PROV-DISC-PBC-REQ")
517     if "group=" + dev[0].group_ifname not in ev:
518         raise Exception("Unexpected PD event contents: " + ev)
519     dev[0].group_request("WPS_PBC")
520
521     ev = dev[1].wait_global_event(["P2P-GROUP-STARTED"], timeout=15)
522     if ev is None:
523         raise Exception("Joining the group timed out")
524     dev[1].group_form_result(ev)
525
526     dev[0].remove_group()
527     dev[1].wait_go_ending_session()
528     dev[1].flush_scan_cache()
529
530 def test_autogo_join_auto_go_neg(dev):
531     """P2P_CONNECT-auto fallback to GO Neg"""
532     dev[1].flush_scan_cache()
533     dev[0].p2p_listen()
534     addr = dev[0].p2p_dev_addr()
535     if not dev[1].discover_peer(addr, social=True):
536         raise Exception("Peer not found")
537     dev[1].p2p_stop_find()
538     if "OK" not in dev[1].global_request("P2P_CONNECT " + addr + " pbc auto"):
539         raise Exception("P2P_CONNECT failed")
540
541     ev = dev[0].wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=15)
542     if ev is None:
543         raise Exception("Timeout on P2P-GO-NEG-REQUEST")
544     peer = ev.split(' ')[1]
545     dev[0].p2p_go_neg_init(peer, None, "pbc", timeout=15, go_intent=15)
546
547     ev = dev[1].wait_global_event(["P2P-FALLBACK-TO-GO-NEG"], timeout=1)
548     if ev is None:
549         raise Exception("No P2P-FALLBACK-TO-GO-NEG event seen")
550     if "P2P-FALLBACK-TO-GO-NEG-ENABLED" in ev:
551         ev = dev[1].wait_global_event(["P2P-FALLBACK-TO-GO-NEG"], timeout=1)
552         if ev is None:
553             raise Exception("No P2P-FALLBACK-TO-GO-NEG event seen")
554     if "reason=peer-not-running-GO" not in ev:
555         raise Exception("Unexpected reason: " + ev)
556
557     ev = dev[1].wait_global_event(["P2P-GROUP-STARTED"], timeout=15)
558     if ev is None:
559         raise Exception("Joining the group timed out")
560     dev[1].group_form_result(ev)
561
562     dev[0].remove_group()
563     dev[1].wait_go_ending_session()
564     dev[1].flush_scan_cache()
565
566 def test_autogo_join_auto_go_neg_after_seeing_go(dev):
567     """P2P_CONNECT-auto fallback to GO Neg after seeing GO"""
568     autogo(dev[0], freq=2412)
569     addr = dev[0].p2p_dev_addr()
570     bssid = dev[0].p2p_interface_addr()
571     dev[1].scan_for_bss(bssid, freq=2412)
572     dev[0].remove_group()
573     dev[0].p2p_listen()
574
575     if "OK" not in dev[1].global_request("P2P_CONNECT " + addr + " pbc auto"):
576         raise Exception("P2P_CONNECT failed")
577
578     ev = dev[1].wait_global_event(["P2P-FALLBACK-TO-GO-NEG-ENABLED"],
579                                   timeout=15)
580     if ev is None:
581         raise Exception("No P2P-FALLBACK-TO-GO-NEG-ENABLED event seen")
582
583     ev = dev[0].wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=15)
584     if ev is None:
585         raise Exception("Timeout on P2P-GO-NEG-REQUEST")
586     peer = ev.split(' ')[1]
587     dev[0].p2p_go_neg_init(peer, None, "pbc", timeout=15, go_intent=15)
588
589     ev = dev[1].wait_global_event(["P2P-FALLBACK-TO-GO-NEG"], timeout=1)
590     if ev is None:
591         raise Exception("No P2P-FALLBACK-TO-GO-NEG event seen")
592     if "reason=no-ACK-to-PD-Req" not in ev and "reason=PD-failed" not in ev:
593         raise Exception("Unexpected reason: " + ev)
594
595     ev = dev[1].wait_global_event(["P2P-GROUP-STARTED"], timeout=15)
596     if ev is None:
597         raise Exception("Joining the group timed out")
598     dev[1].group_form_result(ev)
599
600     dev[0].remove_group()
601     dev[1].wait_go_ending_session()
602     dev[1].flush_scan_cache()
603
604 def test_go_search_non_social(dev):
605     """P2P_FIND with freq parameter to scan a single channel"""
606     addr0 = dev[0].p2p_dev_addr()
607     autogo(dev[0], freq=2422)
608     dev[1].p2p_find(freq=2422)
609     ev = dev[1].wait_global_event(["P2P-DEVICE-FOUND"], timeout=3.5)
610     if ev is None:
611         raise Exception("Did not find GO quickly enough")
612     dev[2].p2p_listen()
613     ev = dev[1].wait_global_event(["P2P-DEVICE-FOUND"], timeout=5)
614     if ev is None:
615         raise Exception("Did not find peer")
616     dev[2].p2p_stop_find()
617     dev[1].p2p_stop_find()
618     dev[0].remove_group()
619
620 def test_autogo_many(dev):
621     """P2P autonomous GO with large number of GO instances"""
622     dev[0].request("SET p2p_no_group_iface 0")
623     for i in range(100):
624         if "OK" not in dev[0].global_request("P2P_GROUP_ADD freq=2412"):
625             logger.info("Was able to add %d groups" % i)
626             if i < 5:
627                 raise Exception("P2P_GROUP_ADD failed")
628             stop_ev = dev[0].wait_global_event(["P2P-GROUP-REMOVE"], timeout=1)
629             if stop_ev is not None:
630                 raise Exception("Unexpected P2P-GROUP-REMOVE event")
631             break
632         ev = dev[0].wait_global_event(["P2P-GROUP-STARTED"], timeout=5)
633         if ev is None:
634             raise Exception("GO start up timed out")
635         dev[0].group_form_result(ev)
636
637     for i in dev[0].global_request("INTERFACES").splitlines():
638         dev[0].request("P2P_GROUP_REMOVE " + i)
639         dev[0].dump_monitor()
640     dev[0].request("P2P_GROUP_REMOVE *")
641
642 def test_autogo_many_clients(dev):
643     """P2P autonomous GO and many clients (P2P IE fragmentation)"""
644     try:
645         _test_autogo_many_clients(dev)
646     finally:
647         dev[0].global_request("SET device_name Device A")
648         dev[1].global_request("SET device_name Device B")
649         dev[2].global_request("SET device_name Device C")
650
651 def _test_autogo_many_clients(dev):
652     # These long device names will push the P2P IE contents beyond the limit
653     # that requires fragmentation.
654     name0 = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
655     name1 = "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"
656     name2 = "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC"
657     name3 = "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD"
658     dev[0].global_request("SET device_name " + name0)
659     dev[1].global_request("SET device_name " + name1)
660     dev[2].global_request("SET device_name " + name2)
661
662     addr0 = dev[0].p2p_dev_addr()
663     res = autogo(dev[0], freq=2412)
664     bssid = dev[0].p2p_interface_addr()
665
666     connect_cli(dev[0], dev[1], social=True, freq=2412)
667     dev[0].dump_monitor()
668     connect_cli(dev[0], dev[2], social=True, freq=2412)
669     dev[0].dump_monitor()
670
671     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
672     wpas.interface_add("wlan5")
673     wpas.global_request("SET device_name " + name3)
674     wpas.global_request("SET sec_device_type 1-11111111-1")
675     wpas.global_request("SET sec_device_type 2-22222222-2")
676     wpas.global_request("SET sec_device_type 3-33333333-3")
677     wpas.global_request("SET sec_device_type 4-44444444-4")
678     wpas.global_request("SET sec_device_type 5-55555555-5")
679     connect_cli(dev[0], wpas, social=True, freq=2412)
680     dev[0].dump_monitor()
681
682     dev[1].dump_monitor()
683     dev[1].p2p_find(freq=2412)
684     ev1 = dev[1].wait_global_event(["P2P-DEVICE-FOUND"], timeout=10)
685     if ev1 is None:
686         raise Exception("Could not find peer (1)")
687     ev2 = dev[1].wait_global_event(["P2P-DEVICE-FOUND"], timeout=10)
688     if ev2 is None:
689         raise Exception("Could not find peer (2)")
690     ev3 = dev[1].wait_global_event(["P2P-DEVICE-FOUND"], timeout=10)
691     if ev3 is None:
692         raise Exception("Could not find peer (3)")
693     dev[1].p2p_stop_find()
694
695     for i in [ name0, name2, name3 ]:
696         if i not in ev1 and i not in ev2 and i not in ev3:
697             raise Exception('name "%s" not found' % i)
698
699 def rx_pd_req(dev):
700     msg = dev.mgmt_rx()
701     if msg is None:
702         raise Exception("MGMT-RX timeout")
703     p2p = parse_p2p_public_action(msg['payload'])
704     if p2p is None:
705         raise Exception("Not a P2P Public Action frame " + str(dialog_token))
706     if p2p['subtype'] != P2P_PROV_DISC_REQ:
707         raise Exception("Unexpected subtype %d" % p2p['subtype'])
708     p2p['freq'] = msg['freq']
709     return p2p
710
711 def test_autogo_scan(dev):
712     """P2P autonomous GO and no P2P IE in Probe Response scan results"""
713     addr0 = dev[0].p2p_dev_addr()
714     addr1 = dev[1].p2p_dev_addr()
715     dev[0].p2p_start_go(freq=2412, persistent=True)
716     bssid = dev[0].p2p_interface_addr()
717
718     dev[1].discover_peer(addr0)
719     dev[1].p2p_stop_find()
720     ev = dev[1].wait_global_event(["P2P-FIND-STOPPED"], timeout=2)
721     time.sleep(0.1)
722     dev[1].flush_scan_cache()
723
724     pin = dev[1].wps_read_pin()
725     dev[0].group_request("WPS_PIN any " + pin)
726
727     try:
728         dev[1].request("SET p2p_disabled 1")
729         dev[1].request("SCAN freq=2412")
730         ev = dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
731         if ev is None:
732             raise Exception("Active scan did not complete")
733     finally:
734         dev[1].request("SET p2p_disabled 0")
735
736     for i in range(2):
737         dev[1].request("SCAN freq=2412 passive=1")
738         ev = dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
739         if ev is None:
740             raise Exception("Scan did not complete")
741
742     # Disable management frame processing for a moment to skip Probe Response
743     # frame with P2P IE.
744     dev[0].group_request("SET ext_mgmt_frame_handling 1")
745
746     dev[1].global_request("P2P_CONNECT " + bssid + " " + pin + " freq=2412 join")
747
748     # Skip the first Probe Request frame
749     ev = dev[0].wait_group_event(["MGMT-RX"], timeout=10)
750     if ev is None:
751         raise Exception("No Probe Request frame seen")
752     if not ev.split(' ')[4].startswith("40"):
753         raise Exception("Not a Probe Request frame")
754
755     # If a P2P Device is not used, the PD Request will be received on the group
756     # interface (which is actually wlan0, since a separate interface is not
757     # used), which was set to external management frame handling, so need to
758     # reply to it manually.
759     res = dev[0].get_driver_status()
760     if not (int(res['capa.flags'], 0) & 0x20000000):
761         # Reply to PD Request while still filtering Probe Request frames
762         msg = rx_pd_req(dev[0])
763         mgmt_tx(dev[0], "MGMT_TX {} {} freq={} wait_time=10 no_cck=1 action={}".format(addr1, addr0, 2412, "0409506f9a0908%02xdd0a0050f204100800020008" % msg['dialog_token']))
764
765     # Skip Probe Request frames until something else is received
766     for i in range(10):
767         ev = dev[0].wait_group_event(["MGMT-RX"], timeout=10)
768         if ev is None:
769             raise Exception("No frame seen")
770         if not ev.split(' ')[4].startswith("40"):
771             break
772
773     # Allow wpa_supplicant to process authentication and association
774     dev[0].group_request("SET ext_mgmt_frame_handling 0")
775
776     # Joining the group should succeed and indicate persistent group based on
777     # Beacon frame P2P IE.
778     ev = dev[1].wait_global_event(["P2P-GROUP-STARTED"], timeout=10)
779     if ev is None:
780         raise Exception("Failed to join group")
781     if "[PERSISTENT]" not in ev:
782         raise Exception("Did not recognize group as persistent")
783     dev[0].remove_group()
784     dev[1].wait_go_ending_session()
785
786 def test_autogo_join_before_found(dev):
787     """P2P client joining a group before having found GO Device Address"""
788     dev[0].request("SET p2p_no_group_iface 0")
789     res = autogo(dev[0], freq=2412)
790     if "p2p-wlan" not in res['ifname']:
791         raise Exception("Unexpected group interface name on GO")
792     status = dev[0].get_group_status()
793     bssid = status['bssid']
794
795     pin = dev[1].wps_read_pin()
796     dev[0].p2p_go_authorize_client(pin)
797     cmd = "P2P_CONNECT " + bssid + " " + pin + " join freq=2412"
798     if "OK" not in dev[1].global_request(cmd):
799         raise Exception("P2P_CONNECT join failed")
800     ev = dev[1].wait_global_event(["P2P-GROUP-STARTED"], timeout=15)
801     if ev is None:
802         raise Exception("Joining the group timed out")
803     dev[0].remove_group()
804     dev[1].wait_go_ending_session()