tests: P2P autonomous GO and no P2P IE in Probe Response scan results
[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 "OK" not in dev[1].global_request("P2P_CONNECT " + addr + " pbc auto"):
536         raise Exception("P2P_CONNECT failed")
537
538     ev = dev[0].wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=15)
539     if ev is None:
540         raise Exception("Timeout on P2P-GO-NEG-REQUEST")
541     peer = ev.split(' ')[1]
542     dev[0].p2p_go_neg_init(peer, None, "pbc", timeout=15, go_intent=15)
543
544     ev = dev[1].wait_global_event(["P2P-FALLBACK-TO-GO-NEG"], timeout=1)
545     if ev is None:
546         raise Exception("No P2P-FALLBACK-TO-GO-NEG event seen")
547     if "P2P-FALLBACK-TO-GO-NEG-ENABLED" in ev:
548         ev = dev[1].wait_global_event(["P2P-FALLBACK-TO-GO-NEG"], timeout=1)
549         if ev is None:
550             raise Exception("No P2P-FALLBACK-TO-GO-NEG event seen")
551     if "reason=peer-not-running-GO" not in ev:
552         raise Exception("Unexpected reason: " + ev)
553
554     ev = dev[1].wait_global_event(["P2P-GROUP-STARTED"], timeout=15)
555     if ev is None:
556         raise Exception("Joining the group timed out")
557     dev[1].group_form_result(ev)
558
559     dev[0].remove_group()
560     dev[1].wait_go_ending_session()
561     dev[1].flush_scan_cache()
562
563 def test_autogo_join_auto_go_neg_after_seeing_go(dev):
564     """P2P_CONNECT-auto fallback to GO Neg after seeing GO"""
565     autogo(dev[0], freq=2412)
566     addr = dev[0].p2p_dev_addr()
567     bssid = dev[0].p2p_interface_addr()
568     dev[1].scan_for_bss(bssid, freq=2412)
569     dev[0].remove_group()
570     dev[0].p2p_listen()
571
572     if "OK" not in dev[1].global_request("P2P_CONNECT " + addr + " pbc auto"):
573         raise Exception("P2P_CONNECT failed")
574
575     ev = dev[1].wait_global_event(["P2P-FALLBACK-TO-GO-NEG-ENABLED"],
576                                   timeout=15)
577     if ev is None:
578         raise Exception("No P2P-FALLBACK-TO-GO-NEG-ENABLED event seen")
579
580     ev = dev[0].wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=15)
581     if ev is None:
582         raise Exception("Timeout on P2P-GO-NEG-REQUEST")
583     peer = ev.split(' ')[1]
584     dev[0].p2p_go_neg_init(peer, None, "pbc", timeout=15, go_intent=15)
585
586     ev = dev[1].wait_global_event(["P2P-FALLBACK-TO-GO-NEG"], timeout=1)
587     if ev is None:
588         raise Exception("No P2P-FALLBACK-TO-GO-NEG event seen")
589     if "reason=no-ACK-to-PD-Req" not in ev and "reason=PD-failed" not in ev:
590         raise Exception("Unexpected reason: " + ev)
591
592     ev = dev[1].wait_global_event(["P2P-GROUP-STARTED"], timeout=15)
593     if ev is None:
594         raise Exception("Joining the group timed out")
595     dev[1].group_form_result(ev)
596
597     dev[0].remove_group()
598     dev[1].wait_go_ending_session()
599     dev[1].flush_scan_cache()
600
601 def test_go_search_non_social(dev):
602     """P2P_FIND with freq parameter to scan a single channel"""
603     addr0 = dev[0].p2p_dev_addr()
604     autogo(dev[0], freq=2422)
605     dev[1].p2p_find(freq=2422)
606     ev = dev[1].wait_global_event(["P2P-DEVICE-FOUND"], timeout=3.5)
607     if ev is None:
608         raise Exception("Did not find GO quickly enough")
609     dev[2].p2p_listen()
610     ev = dev[1].wait_global_event(["P2P-DEVICE-FOUND"], timeout=5)
611     if ev is None:
612         raise Exception("Did not find peer")
613     dev[2].p2p_stop_find()
614     dev[1].p2p_stop_find()
615     dev[0].remove_group()
616
617 def test_autogo_many(dev):
618     """P2P autonomous GO with large number of GO instances"""
619     dev[0].request("SET p2p_no_group_iface 0")
620     for i in range(100):
621         if "OK" not in dev[0].global_request("P2P_GROUP_ADD freq=2412"):
622             logger.info("Was able to add %d groups" % i)
623             if i < 5:
624                 raise Exception("P2P_GROUP_ADD failed")
625             stop_ev = dev[0].wait_global_event(["P2P-GROUP-REMOVE"], timeout=1)
626             if stop_ev is not None:
627                 raise Exception("Unexpected P2P-GROUP-REMOVE event")
628             break
629         ev = dev[0].wait_global_event(["P2P-GROUP-STARTED"], timeout=5)
630         if ev is None:
631             raise Exception("GO start up timed out")
632         dev[0].group_form_result(ev)
633
634     for i in dev[0].global_request("INTERFACES").splitlines():
635         dev[0].request("P2P_GROUP_REMOVE " + i)
636         dev[0].dump_monitor()
637     dev[0].request("P2P_GROUP_REMOVE *")
638
639 def test_autogo_many_clients(dev):
640     """P2P autonomous GO and many clients (P2P IE fragmentation)"""
641     try:
642         _test_autogo_many_clients(dev)
643     finally:
644         dev[0].global_request("SET device_name Device A")
645         dev[1].global_request("SET device_name Device B")
646         dev[2].global_request("SET device_name Device C")
647
648 def _test_autogo_many_clients(dev):
649     # These long device names will push the P2P IE contents beyond the limit
650     # that requires fragmentation.
651     name0 = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
652     name1 = "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"
653     name2 = "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC"
654     name3 = "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD"
655     dev[0].global_request("SET device_name " + name0)
656     dev[1].global_request("SET device_name " + name1)
657     dev[2].global_request("SET device_name " + name2)
658
659     addr0 = dev[0].p2p_dev_addr()
660     res = autogo(dev[0], freq=2412)
661     bssid = dev[0].p2p_interface_addr()
662
663     connect_cli(dev[0], dev[1], social=True, freq=2412)
664     dev[0].dump_monitor()
665     connect_cli(dev[0], dev[2], social=True, freq=2412)
666     dev[0].dump_monitor()
667
668     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
669     wpas.interface_add("wlan5")
670     wpas.global_request("SET device_name " + name3)
671     wpas.global_request("SET sec_device_type 1-11111111-1")
672     wpas.global_request("SET sec_device_type 2-22222222-2")
673     wpas.global_request("SET sec_device_type 3-33333333-3")
674     wpas.global_request("SET sec_device_type 4-44444444-4")
675     wpas.global_request("SET sec_device_type 5-55555555-5")
676     connect_cli(dev[0], wpas, social=True, freq=2412)
677     dev[0].dump_monitor()
678
679     dev[1].dump_monitor()
680     dev[1].p2p_find(freq=2412)
681     ev1 = dev[1].wait_global_event(["P2P-DEVICE-FOUND"], timeout=10)
682     if ev1 is None:
683         raise Exception("Could not find peer (1)")
684     ev2 = dev[1].wait_global_event(["P2P-DEVICE-FOUND"], timeout=10)
685     if ev2 is None:
686         raise Exception("Could not find peer (2)")
687     ev3 = dev[1].wait_global_event(["P2P-DEVICE-FOUND"], timeout=10)
688     if ev3 is None:
689         raise Exception("Could not find peer (3)")
690     dev[1].p2p_stop_find()
691
692     for i in [ name0, name2, name3 ]:
693         if i not in ev1 and i not in ev2 and i not in ev3:
694             raise Exception('name "%s" not found' % i)
695
696 def rx_pd_req(dev):
697     msg = dev.mgmt_rx()
698     if msg is None:
699         raise Exception("MGMT-RX timeout")
700     p2p = parse_p2p_public_action(msg['payload'])
701     if p2p is None:
702         raise Exception("Not a P2P Public Action frame " + str(dialog_token))
703     if p2p['subtype'] != P2P_PROV_DISC_REQ:
704         raise Exception("Unexpected subtype %d" % p2p['subtype'])
705     p2p['freq'] = msg['freq']
706     return p2p
707
708 def test_autogo_scan(dev):
709     """P2P autonomous GO and no P2P IE in Probe Response scan results"""
710     addr0 = dev[0].p2p_dev_addr()
711     addr1 = dev[1].p2p_dev_addr()
712     dev[0].p2p_start_go(freq=2412, persistent=True)
713     bssid = dev[0].p2p_interface_addr()
714
715     dev[1].discover_peer(addr0)
716     dev[1].p2p_stop_find()
717     ev = dev[1].wait_global_event(["P2P-FIND-STOPPED"], timeout=2)
718     time.sleep(0.1)
719     dev[1].flush_scan_cache()
720
721     pin = dev[1].wps_read_pin()
722     dev[0].group_request("WPS_PIN any " + pin)
723
724     try:
725         dev[1].request("SET p2p_disabled 1")
726         dev[1].request("SCAN freq=2412")
727         ev = dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
728         if ev is None:
729             raise Exception("Active scan did not complete")
730     finally:
731         dev[1].request("SET p2p_disabled 0")
732
733     for i in range(2):
734         dev[1].request("SCAN freq=2412 passive=1")
735         ev = dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
736         if ev is None:
737             raise Exception("Scan did not complete")
738
739     # Disable management frame processing for a moment to skip Probe Response
740     # frame with P2P IE.
741     dev[0].group_request("SET ext_mgmt_frame_handling 1")
742
743     dev[1].request("P2P_CONNECT " + bssid + " " + pin + " freq=2412 join")
744
745     # Skip the first Probe Request frame
746     ev = dev[0].wait_group_event(["MGMT-RX"], timeout=10)
747     if ev is None:
748         raise Exception("No Probe Request frame seen")
749     if not ev.split(' ')[4].startswith("40"):
750         raise Exception("Not a Probe Request frame")
751
752     # Reply to PD Request while still filtering Probe Request frames
753     msg = rx_pd_req(dev[0])
754     mgmt_tx(dev[0], "MGMT_TX {} {} freq={} wait_time=10 no_cck=1 action={}".format(addr1, addr0, 2412, "0409506f9a0908%02xdd0a0050f204100800020008" % msg['dialog_token']))
755
756     # Skip Probe Request frames until something else is received
757     for i in range(10):
758         ev = dev[0].wait_group_event(["MGMT-RX"], timeout=10)
759         if ev is None:
760             raise Exception("No frame seen")
761         if not ev.split(' ')[4].startswith("40"):
762             break
763
764     # Allow wpa_supplicant to process authentication and association
765     dev[0].group_request("SET ext_mgmt_frame_handling 0")
766
767     # Joining the group should succeed and indicate persistent group based on
768     # Beacon frame P2P IE.
769     ev = dev[1].wait_global_event(["P2P-GROUP-STARTED"], timeout=10)
770     if ev is None:
771         raise Exception("Failed to join group")
772     if "[PERSISTENT]" not in ev:
773         raise Exception("Did not recognize group as persistent")
774     dev[0].remove_group()
775     dev[1].wait_go_ending_session()