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