tests: Add support for wlantest for remote hwsim tests
[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].global_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].global_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].global_request("SET p2p_no_group_iface 0")
116     dev[1].global_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].global_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     go = dev[0]
235     logger.info("Start autonomous GO with fixed parameters " + go.ifname)
236     id = go.add_network()
237     go.set_network_quoted(id, "ssid", "DIRECT-tdls")
238     go.set_network_quoted(id, "psk", "12345678")
239     go.set_network(id, "mode", "3")
240     go.set_network(id, "disabled", "2")
241     res = go.p2p_start_go(persistent=id, freq="2462")
242     logger.debug("res: " + str(res))
243     Wlantest.setup(go, True)
244     wt = Wlantest()
245     wt.flush()
246     wt.add_passphrase("12345678")
247     connect_cli(go, dev[1], social=True, freq=2462)
248     connect_cli(go, dev[2], social=True, freq=2462)
249     hwsim_utils.test_connectivity_p2p(dev[1], dev[2])
250     bssid = dev[0].p2p_interface_addr()
251     addr1 = dev[1].p2p_interface_addr()
252     addr2 = dev[2].p2p_interface_addr()
253     dev[1].tdls_setup(addr2)
254     time.sleep(1)
255     hwsim_utils.test_connectivity_p2p(dev[1], dev[2])
256     conf = wt.get_tdls_counter("setup_conf_ok", bssid, addr1, addr2);
257     if conf == 0:
258         raise Exception("No TDLS Setup Confirm (success) seen")
259     dl = wt.get_tdls_counter("valid_direct_link", bssid, addr1, addr2);
260     if dl == 0:
261         raise Exception("No valid frames through direct link")
262     wt.tdls_clear(bssid, addr1, addr2);
263     dev[1].tdls_teardown(addr2)
264     time.sleep(1)
265     teardown = wt.get_tdls_counter("teardown", bssid, addr1, addr2);
266     if teardown == 0:
267         raise Exception("No TDLS Setup Teardown seen")
268     wt.tdls_clear(bssid, addr1, addr2);
269     hwsim_utils.test_connectivity_p2p(dev[1], dev[2])
270     ap_path = wt.get_tdls_counter("valid_ap_path", bssid, addr1, addr2);
271     if ap_path == 0:
272         raise Exception("No valid frames via AP path")
273     direct_link = wt.get_tdls_counter("valid_direct_link", bssid, addr1, addr2);
274     if direct_link > 0:
275         raise Exception("Unexpected frames through direct link")
276     idirect_link = wt.get_tdls_counter("invalid_direct_link", bssid, addr1,
277                                        addr2);
278     if idirect_link > 0:
279         raise Exception("Unexpected frames through direct link (invalid)")
280     dev[2].remove_group()
281     dev[1].remove_group()
282     dev[0].remove_group()
283
284 def test_autogo_legacy(dev):
285     """P2P autonomous GO and legacy clients"""
286     res = autogo(dev[0], freq=2462)
287     if dev[0].get_group_status_field("passphrase", extra="WPS") != res['passphrase']:
288         raise Exception("passphrase mismatch")
289     if dev[0].group_request("P2P_GET_PASSPHRASE") != res['passphrase']:
290         raise Exception("passphrase mismatch(2)")
291
292     logger.info("Connect P2P client")
293     connect_cli(dev[0], dev[1], social=True, freq=2462)
294
295     if "FAIL" not in dev[1].request("P2P_GET_PASSPHRASE"):
296         raise Exception("P2P_GET_PASSPHRASE succeeded on P2P Client")
297
298     logger.info("Connect legacy WPS client")
299     pin = dev[2].wps_read_pin()
300     dev[0].p2p_go_authorize_client(pin)
301     dev[2].request("P2P_SET disabled 1")
302     dev[2].dump_monitor()
303     dev[2].request("WPS_PIN any " + pin)
304     dev[2].wait_connected(timeout=30)
305     status = dev[2].get_status()
306     if status['wpa_state'] != 'COMPLETED':
307         raise Exception("Not fully connected")
308     hwsim_utils.test_connectivity_p2p_sta(dev[1], dev[2])
309     dev[2].request("DISCONNECT")
310
311     logger.info("Connect legacy non-WPS client")
312     dev[2].request("FLUSH")
313     dev[2].request("P2P_SET disabled 1")
314     dev[2].connect(ssid=res['ssid'], psk=res['passphrase'], proto='RSN',
315                    key_mgmt='WPA-PSK', pairwise='CCMP', group='CCMP',
316                    scan_freq=res['freq'])
317     hwsim_utils.test_connectivity_p2p_sta(dev[1], dev[2])
318     dev[2].request("DISCONNECT")
319
320     dev[0].remove_group()
321     dev[1].wait_go_ending_session()
322
323 def test_autogo_chan_switch(dev):
324     """P2P autonomous GO switching channels"""
325     autogo(dev[0], freq=2417)
326     connect_cli(dev[0], dev[1])
327     res = dev[0].request("CHAN_SWITCH 5 2422")
328     if "FAIL" in res:
329         # for now, skip test since mac80211_hwsim support is not yet widely
330         # deployed
331         raise HwsimSkip("Assume mac80211_hwsim did not support channel switching")
332     ev = dev[0].wait_event(["AP-CSA-FINISHED"], timeout=10)
333     if ev is None:
334         raise Exception("CSA finished event timed out")
335     if "freq=2422" not in ev:
336         raise Exception("Unexpected cahnnel in CSA finished event")
337     dev[0].dump_monitor()
338     dev[1].dump_monitor()
339     time.sleep(0.1)
340     hwsim_utils.test_connectivity_p2p(dev[0], dev[1])
341
342 def test_autogo_extra_cred(dev):
343     """P2P autonomous GO sending two WPS credentials"""
344     if "FAIL" in dev[0].request("SET wps_testing_dummy_cred 1"):
345         raise Exception("Failed to enable test mode")
346     autogo(dev[0], freq=2412)
347     connect_cli(dev[0], dev[1], social=True, freq=2412)
348     dev[0].remove_group()
349     dev[1].wait_go_ending_session()
350
351 def test_autogo_ifdown(dev):
352     """P2P autonomous GO and external ifdown"""
353     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
354     wpas.interface_add("wlan5")
355     res = autogo(wpas)
356     wpas.dump_monitor()
357     wpas.interface_remove("wlan5")
358     wpas.interface_add("wlan5")
359     res = autogo(wpas)
360     wpas.dump_monitor()
361     subprocess.call(['ifconfig', res['ifname'], 'down'])
362     ev = wpas.wait_global_event(["P2P-GROUP-REMOVED"], timeout=10)
363     if ev is None:
364         raise Exception("Group removal not reported")
365     if res['ifname'] not in ev:
366         raise Exception("Unexpected group removal event: " + ev)
367
368 def test_autogo_start_during_scan(dev):
369     """P2P autonomous GO started during ongoing manual scan"""
370     try:
371         # use autoscan to set scan_req = MANUAL_SCAN_REQ
372         if "OK" not in dev[0].request("AUTOSCAN periodic:1"):
373             raise Exception("Failed to set autoscan")
374         autogo(dev[0], freq=2462)
375         connect_cli(dev[0], dev[1], social=True, freq=2462)
376         dev[0].remove_group()
377         dev[1].wait_go_ending_session()
378     finally:
379         dev[0].request("AUTOSCAN ")
380
381 def test_autogo_passphrase_len(dev):
382     """P2P autonomous GO and longer passphrase"""
383     try:
384         if "OK" not in dev[0].request("SET p2p_passphrase_len 13"):
385             raise Exception("Failed to set passphrase length")
386         res = autogo(dev[0], freq=2412)
387         if len(res['passphrase']) != 13:
388             raise Exception("Unexpected passphrase length")
389         if dev[0].get_group_status_field("passphrase", extra="WPS") != res['passphrase']:
390             raise Exception("passphrase mismatch")
391
392         logger.info("Connect P2P client")
393         connect_cli(dev[0], dev[1], social=True, freq=2412)
394
395         logger.info("Connect legacy WPS client")
396         pin = dev[2].wps_read_pin()
397         dev[0].p2p_go_authorize_client(pin)
398         dev[2].request("P2P_SET disabled 1")
399         dev[2].dump_monitor()
400         dev[2].request("WPS_PIN any " + pin)
401         dev[2].wait_connected(timeout=30)
402         status = dev[2].get_status()
403         if status['wpa_state'] != 'COMPLETED':
404             raise Exception("Not fully connected")
405         dev[2].request("DISCONNECT")
406
407         logger.info("Connect legacy non-WPS client")
408         dev[2].request("FLUSH")
409         dev[2].request("P2P_SET disabled 1")
410         dev[2].connect(ssid=res['ssid'], psk=res['passphrase'], proto='RSN',
411                        key_mgmt='WPA-PSK', pairwise='CCMP', group='CCMP',
412                        scan_freq=res['freq'])
413         hwsim_utils.test_connectivity_p2p_sta(dev[1], dev[2])
414         dev[2].request("DISCONNECT")
415
416         dev[0].remove_group()
417         dev[1].wait_go_ending_session()
418     finally:
419         dev[0].request("SET p2p_passphrase_len 8")
420
421 def test_autogo_bridge(dev):
422     """P2P autonomous GO in a bridge"""
423     try:
424         # use autoscan to set scan_req = MANUAL_SCAN_REQ
425         if "OK" not in dev[0].request("AUTOSCAN periodic:1"):
426             raise Exception("Failed to set autoscan")
427         autogo(dev[0])
428         ifname = dev[0].get_group_ifname()
429         subprocess.call(['brctl', 'addbr', 'p2p-br0'])
430         subprocess.call(['brctl', 'setfd', 'p2p-br0', '0'])
431         subprocess.call(['brctl', 'addif', 'p2p-br0', ifname])
432         subprocess.call(['ip', 'link', 'set', 'dev', 'p2p-br0', 'up'])
433         time.sleep(0.1)
434         subprocess.call(['brctl', 'delif', 'p2p-br0', ifname])
435         time.sleep(0.1)
436         subprocess.call(['ip', 'link', 'set', 'dev', 'p2p-br0', 'down'])
437         time.sleep(0.1)
438         subprocess.call(['brctl', 'delbr', 'p2p-br0'])
439         ev = dev[0].wait_global_event(["P2P-GROUP-REMOVED"], timeout=1)
440         if ev is not None:
441             raise Exception("P2P group removed unexpectedly")
442         if dev[0].get_group_status_field('wpa_state') != "COMPLETED":
443             raise Exception("Unexpected wpa_state")
444         dev[0].remove_group()
445     finally:
446         dev[0].request("AUTOSCAN ")
447         subprocess.Popen(['brctl', 'delif', 'p2p-br0', ifname],
448                          stderr=open('/dev/null', 'w'))
449         subprocess.Popen(['ip', 'link', 'set', 'dev', 'p2p-br0', 'down'],
450                          stderr=open('/dev/null', 'w'))
451         subprocess.Popen(['brctl', 'delbr', 'p2p-br0'],
452                          stderr=open('/dev/null', 'w'))
453
454 def test_presence_req_on_group_interface(dev):
455     """P2P_PRESENCE_REQ on group interface"""
456     dev[1].global_request("SET p2p_no_group_iface 0")
457     res = autogo(dev[0], freq=2437)
458     res = connect_cli(dev[0], dev[1], social=True, freq=2437)
459     if "FAIL" in dev[1].group_request("P2P_PRESENCE_REQ 30000 102400"):
460         raise Exception("Could not send presence request")
461     ev = dev[1].wait_group_event(["P2P-PRESENCE-RESPONSE"])
462     if ev is None:
463         raise Exception("Timeout while waiting for Presence Response")
464     dev[0].remove_group()
465     dev[1].wait_go_ending_session()
466
467 def test_autogo_join_auto_go_not_found(dev):
468     """P2P_CONNECT-auto not finding GO"""
469     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
470     wpas.interface_add("wlan5")
471     wpas.request("P2P_SET listen_channel 1")
472     wpas.global_request("SET p2p_no_group_iface 0")
473     autogo(wpas, freq=2412)
474     addr = wpas.p2p_dev_addr()
475     bssid = wpas.p2p_interface_addr()
476     wpas.dump_monitor()
477
478     dev[1].global_request("SET p2p_no_group_iface 0")
479     dev[1].scan_for_bss(bssid, freq=2412)
480     # This makes the GO not show up in the scan iteration following the
481     # P2P_CONNECT command by stopping beaconing and handling Probe Request
482     # frames externally (but not really replying to them). P2P listen mode is
483     # needed to keep the GO listening on the operating channel for the PD
484     # exchange.
485     if "OK" not in wpas.group_request("STOP_AP"):
486         raise Exception("STOP_AP failed")
487     wpas.dump_monitor()
488     wpas.group_request("SET ext_mgmt_frame_handling 1")
489     wpas.p2p_listen()
490     wpas.dump_monitor()
491     time.sleep(0.02)
492     dev[1].global_request("P2P_CONNECT " + addr + " pbc auto")
493
494     ev = dev[1].wait_global_event(["P2P-FALLBACK-TO-GO-NEG-ENABLED"], 15)
495     wpas.dump_monitor()
496     if ev is None:
497         raise Exception("Could not trigger old-scan-only case")
498         return
499
500     ev = dev[1].wait_global_event(["P2P-FALLBACK-TO-GO-NEG"], 15)
501     wpas.remove_group()
502     if ev is None:
503         raise Exception("Fallback to GO Negotiation not seen")
504     if "reason=GO-not-found" not in ev:
505         raise Exception("Unexpected reason for fallback: " + ev)
506     wpas.dump_monitor()
507
508 def test_autogo_join_auto(dev):
509     """P2P_CONNECT-auto joining a group"""
510     autogo(dev[0])
511     addr = dev[0].p2p_dev_addr()
512     if "OK" not in dev[1].global_request("P2P_CONNECT " + addr + " pbc auto"):
513         raise Exception("P2P_CONNECT failed")
514
515     ev = dev[0].wait_global_event(["P2P-PROV-DISC-PBC-REQ"], timeout=15)
516     if ev is None:
517         raise Exception("Timeout on P2P-PROV-DISC-PBC-REQ")
518     if "group=" + dev[0].group_ifname not in ev:
519         raise Exception("Unexpected PD event contents: " + ev)
520     dev[0].group_request("WPS_PBC")
521
522     ev = dev[1].wait_global_event(["P2P-GROUP-STARTED"], timeout=15)
523     if ev is None:
524         raise Exception("Joining the group timed out")
525     dev[1].group_form_result(ev)
526
527     dev[0].remove_group()
528     dev[1].wait_go_ending_session()
529     dev[1].flush_scan_cache()
530
531 def test_autogo_join_auto_go_neg(dev):
532     """P2P_CONNECT-auto fallback to GO Neg"""
533     dev[1].flush_scan_cache()
534     dev[0].p2p_listen()
535     addr = dev[0].p2p_dev_addr()
536     if not dev[1].discover_peer(addr, social=True):
537         raise Exception("Peer not found")
538     dev[1].p2p_stop_find()
539     if "OK" not in dev[1].global_request("P2P_CONNECT " + addr + " pbc auto"):
540         raise Exception("P2P_CONNECT failed")
541
542     ev = dev[0].wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=15)
543     if ev is None:
544         raise Exception("Timeout on P2P-GO-NEG-REQUEST")
545     peer = ev.split(' ')[1]
546     dev[0].p2p_go_neg_init(peer, None, "pbc", timeout=15, go_intent=15)
547
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 "P2P-FALLBACK-TO-GO-NEG-ENABLED" in ev:
552         ev = dev[1].wait_global_event(["P2P-FALLBACK-TO-GO-NEG"], timeout=1)
553         if ev is None:
554             raise Exception("No P2P-FALLBACK-TO-GO-NEG event seen")
555     if "reason=peer-not-running-GO" not in ev:
556         raise Exception("Unexpected reason: " + ev)
557
558     ev = dev[1].wait_global_event(["P2P-GROUP-STARTED"], timeout=15)
559     if ev is None:
560         raise Exception("Joining the group timed out")
561     dev[1].group_form_result(ev)
562
563     dev[0].remove_group()
564     dev[1].wait_go_ending_session()
565     dev[1].flush_scan_cache()
566
567 def test_autogo_join_auto_go_neg_after_seeing_go(dev):
568     """P2P_CONNECT-auto fallback to GO Neg after seeing GO"""
569     autogo(dev[0], freq=2412)
570     addr = dev[0].p2p_dev_addr()
571     bssid = dev[0].p2p_interface_addr()
572     dev[1].scan_for_bss(bssid, freq=2412)
573     dev[0].remove_group()
574     dev[0].p2p_listen()
575
576     if "OK" not in dev[1].global_request("P2P_CONNECT " + addr + " pbc auto"):
577         raise Exception("P2P_CONNECT failed")
578
579     ev = dev[1].wait_global_event(["P2P-FALLBACK-TO-GO-NEG-ENABLED"],
580                                   timeout=15)
581     if ev is None:
582         raise Exception("No P2P-FALLBACK-TO-GO-NEG-ENABLED event seen")
583
584     ev = dev[0].wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=15)
585     if ev is None:
586         raise Exception("Timeout on P2P-GO-NEG-REQUEST")
587     peer = ev.split(' ')[1]
588     dev[0].p2p_go_neg_init(peer, None, "pbc", timeout=15, go_intent=15)
589
590     ev = dev[1].wait_global_event(["P2P-FALLBACK-TO-GO-NEG"], timeout=1)
591     if ev is None:
592         raise Exception("No P2P-FALLBACK-TO-GO-NEG event seen")
593     if "reason=no-ACK-to-PD-Req" not in ev and "reason=PD-failed" not in ev:
594         raise Exception("Unexpected reason: " + ev)
595
596     ev = dev[1].wait_global_event(["P2P-GROUP-STARTED"], timeout=15)
597     if ev is None:
598         raise Exception("Joining the group timed out")
599     dev[1].group_form_result(ev)
600
601     dev[0].remove_group()
602     dev[1].wait_go_ending_session()
603     dev[1].flush_scan_cache()
604
605 def test_go_search_non_social(dev):
606     """P2P_FIND with freq parameter to scan a single channel"""
607     addr0 = dev[0].p2p_dev_addr()
608     autogo(dev[0], freq=2422)
609     dev[1].p2p_find(freq=2422)
610     ev = dev[1].wait_global_event(["P2P-DEVICE-FOUND"], timeout=3.5)
611     if ev is None:
612         raise Exception("Did not find GO quickly enough")
613     dev[2].p2p_listen()
614     ev = dev[1].wait_global_event(["P2P-DEVICE-FOUND"], timeout=5)
615     if ev is None:
616         raise Exception("Did not find peer")
617     dev[2].p2p_stop_find()
618     dev[1].p2p_stop_find()
619     dev[0].remove_group()
620
621 def test_autogo_many(dev):
622     """P2P autonomous GO with large number of GO instances"""
623     dev[0].global_request("SET p2p_no_group_iface 0")
624     for i in range(100):
625         if "OK" not in dev[0].global_request("P2P_GROUP_ADD freq=2412"):
626             logger.info("Was able to add %d groups" % i)
627             if i < 5:
628                 raise Exception("P2P_GROUP_ADD failed")
629             stop_ev = dev[0].wait_global_event(["P2P-GROUP-REMOVE"], timeout=1)
630             if stop_ev is not None:
631                 raise Exception("Unexpected P2P-GROUP-REMOVE event")
632             break
633         ev = dev[0].wait_global_event(["P2P-GROUP-STARTED"], timeout=5)
634         if ev is None:
635             raise Exception("GO start up timed out")
636         dev[0].group_form_result(ev)
637
638     for i in dev[0].global_request("INTERFACES").splitlines():
639         dev[0].request("P2P_GROUP_REMOVE " + i)
640         dev[0].dump_monitor()
641     dev[0].request("P2P_GROUP_REMOVE *")
642
643 def test_autogo_many_clients(dev):
644     """P2P autonomous GO and many clients (P2P IE fragmentation)"""
645     try:
646         _test_autogo_many_clients(dev)
647     finally:
648         dev[0].global_request("SET device_name Device A")
649         dev[1].global_request("SET device_name Device B")
650         dev[2].global_request("SET device_name Device C")
651
652 def _test_autogo_many_clients(dev):
653     # These long device names will push the P2P IE contents beyond the limit
654     # that requires fragmentation.
655     name0 = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
656     name1 = "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"
657     name2 = "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC"
658     name3 = "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD"
659     dev[0].global_request("SET device_name " + name0)
660     dev[1].global_request("SET device_name " + name1)
661     dev[2].global_request("SET device_name " + name2)
662
663     addr0 = dev[0].p2p_dev_addr()
664     res = autogo(dev[0], freq=2412)
665     bssid = dev[0].p2p_interface_addr()
666
667     connect_cli(dev[0], dev[1], social=True, freq=2412)
668     dev[0].dump_monitor()
669     connect_cli(dev[0], dev[2], social=True, freq=2412)
670     dev[0].dump_monitor()
671
672     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
673     wpas.interface_add("wlan5")
674     wpas.global_request("SET device_name " + name3)
675     wpas.global_request("SET sec_device_type 1-11111111-1")
676     wpas.global_request("SET sec_device_type 2-22222222-2")
677     wpas.global_request("SET sec_device_type 3-33333333-3")
678     wpas.global_request("SET sec_device_type 4-44444444-4")
679     wpas.global_request("SET sec_device_type 5-55555555-5")
680     connect_cli(dev[0], wpas, social=True, freq=2412)
681     dev[0].dump_monitor()
682
683     dev[1].dump_monitor()
684     dev[1].p2p_find(freq=2412)
685     ev1 = dev[1].wait_global_event(["P2P-DEVICE-FOUND"], timeout=10)
686     if ev1 is None:
687         raise Exception("Could not find peer (1)")
688     ev2 = dev[1].wait_global_event(["P2P-DEVICE-FOUND"], timeout=10)
689     if ev2 is None:
690         raise Exception("Could not find peer (2)")
691     ev3 = dev[1].wait_global_event(["P2P-DEVICE-FOUND"], timeout=10)
692     if ev3 is None:
693         raise Exception("Could not find peer (3)")
694     dev[1].p2p_stop_find()
695
696     for i in [ name0, name2, name3 ]:
697         if i not in ev1 and i not in ev2 and i not in ev3:
698             raise Exception('name "%s" not found' % i)
699
700 def rx_pd_req(dev):
701     msg = dev.mgmt_rx()
702     if msg is None:
703         raise Exception("MGMT-RX timeout")
704     p2p = parse_p2p_public_action(msg['payload'])
705     if p2p is None:
706         raise Exception("Not a P2P Public Action frame " + str(dialog_token))
707     if p2p['subtype'] != P2P_PROV_DISC_REQ:
708         raise Exception("Unexpected subtype %d" % p2p['subtype'])
709     p2p['freq'] = msg['freq']
710     return p2p
711
712 def test_autogo_scan(dev):
713     """P2P autonomous GO and no P2P IE in Probe Response scan results"""
714     addr0 = dev[0].p2p_dev_addr()
715     addr1 = dev[1].p2p_dev_addr()
716     dev[0].p2p_start_go(freq=2412, persistent=True)
717     bssid = dev[0].p2p_interface_addr()
718
719     dev[1].discover_peer(addr0)
720     dev[1].p2p_stop_find()
721     ev = dev[1].wait_global_event(["P2P-FIND-STOPPED"], timeout=2)
722     time.sleep(0.1)
723     dev[1].flush_scan_cache()
724
725     pin = dev[1].wps_read_pin()
726     dev[0].group_request("WPS_PIN any " + pin)
727
728     try:
729         dev[1].request("SET p2p_disabled 1")
730         dev[1].request("SCAN freq=2412")
731         ev = dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
732         if ev is None:
733             raise Exception("Active scan did not complete")
734     finally:
735         dev[1].request("SET p2p_disabled 0")
736
737     for i in range(2):
738         dev[1].request("SCAN freq=2412 passive=1")
739         ev = dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
740         if ev is None:
741             raise Exception("Scan did not complete")
742
743     # Disable management frame processing for a moment to skip Probe Response
744     # frame with P2P IE.
745     dev[0].group_request("SET ext_mgmt_frame_handling 1")
746
747     dev[1].global_request("P2P_CONNECT " + bssid + " " + pin + " freq=2412 join")
748
749     # Skip the first Probe Request frame
750     ev = dev[0].wait_group_event(["MGMT-RX"], timeout=10)
751     if ev is None:
752         raise Exception("No Probe Request frame seen")
753     if not ev.split(' ')[4].startswith("40"):
754         raise Exception("Not a Probe Request frame")
755
756     # If a P2P Device is not used, the PD Request will be received on the group
757     # interface (which is actually wlan0, since a separate interface is not
758     # used), which was set to external management frame handling, so need to
759     # reply to it manually.
760     res = dev[0].get_driver_status()
761     if not (int(res['capa.flags'], 0) & 0x20000000):
762         # Reply to PD Request while still filtering Probe Request frames
763         msg = rx_pd_req(dev[0])
764         mgmt_tx(dev[0], "MGMT_TX {} {} freq={} wait_time=10 no_cck=1 action={}".format(addr1, addr0, 2412, "0409506f9a0908%02xdd0a0050f204100800020008" % msg['dialog_token']))
765
766     # Skip Probe Request frames until something else is received
767     for i in range(10):
768         ev = dev[0].wait_group_event(["MGMT-RX"], timeout=10)
769         if ev is None:
770             raise Exception("No frame seen")
771         if not ev.split(' ')[4].startswith("40"):
772             break
773
774     # Allow wpa_supplicant to process authentication and association
775     dev[0].group_request("SET ext_mgmt_frame_handling 0")
776
777     # Joining the group should succeed and indicate persistent group based on
778     # Beacon frame P2P IE.
779     ev = dev[1].wait_global_event(["P2P-GROUP-STARTED"], timeout=10)
780     if ev is None:
781         raise Exception("Failed to join group")
782     if "[PERSISTENT]" not in ev:
783         raise Exception("Did not recognize group as persistent")
784     dev[0].remove_group()
785     dev[1].wait_go_ending_session()
786
787 def test_autogo_join_before_found(dev):
788     """P2P client joining a group before having found GO Device Address"""
789     dev[0].global_request("SET p2p_no_group_iface 0")
790     res = autogo(dev[0], freq=2412)
791     if "p2p-wlan" not in res['ifname']:
792         raise Exception("Unexpected group interface name on GO")
793     status = dev[0].get_group_status()
794     bssid = status['bssid']
795
796     pin = dev[1].wps_read_pin()
797     dev[0].p2p_go_authorize_client(pin)
798     cmd = "P2P_CONNECT " + bssid + " " + pin + " join freq=2412"
799     if "OK" not in dev[1].global_request(cmd):
800         raise Exception("P2P_CONNECT join failed")
801     ev = dev[1].wait_global_event(["P2P-GROUP-STARTED"], timeout=15)
802     if ev is None:
803         raise Exception("Joining the group timed out")
804     dev[0].remove_group()
805     dev[1].wait_go_ending_session()