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