1# P2P group formation test cases
2# Copyright (c) 2013-2019, 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 binascii
9import logging
10logger = logging.getLogger()
11import struct
12import time
13import os
14
15import hostapd
16import hwsim_utils
17from utils import *
18from wpasupplicant import WpaSupplicant
19from p2p_utils import *
20from test_p2p_messages import parse_p2p_public_action, p2p_hdr, p2p_attr_capability, p2p_attr_go_intent, p2p_attr_config_timeout, p2p_attr_listen_channel, p2p_attr_intended_interface_addr, p2p_attr_channel_list, p2p_attr_device_info, p2p_attr_operating_channel, ie_p2p, ie_wsc, mgmt_tx, P2P_GO_NEG_REQ
21
22@remote_compatible
23def test_grpform(dev):
24    """P2P group formation using PIN and authorized connection (init -> GO)"""
25    try:
26        dev[0].global_request("SET p2p_group_idle 2")
27        [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
28                                               r_dev=dev[1], r_intent=0)
29        check_grpform_results(i_res, r_res)
30        dev[1].remove_group()
31        ev = dev[0].wait_global_event(["P2P-GROUP-REMOVED"], timeout=10)
32        if ev is None:
33            raise Exception("GO did not remove group on idle timeout")
34        if "GO reason=IDLE" not in ev:
35            raise Exception("Unexpected group removal event: " + ev)
36    finally:
37        dev[0].global_request("SET p2p_group_idle 0")
38
39def test_grpform_a(dev):
40    """P2P group formation using PIN and authorized connection (init -> GO) (init: group iface)"""
41    dev[0].global_request("SET p2p_no_group_iface 0")
42    [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
43                                           r_dev=dev[1], r_intent=0)
44    if "p2p-wlan" not in i_res['ifname']:
45        raise Exception("Unexpected group interface name")
46    check_grpform_results(i_res, r_res)
47    remove_group(dev[0], dev[1])
48    if i_res['ifname'] in get_ifnames():
49        raise Exception("Group interface netdev was not removed")
50
51def test_grpform_b(dev):
52    """P2P group formation using PIN and authorized connection (init -> GO) (resp: group iface)"""
53    dev[1].global_request("SET p2p_no_group_iface 0")
54    [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
55                                           r_dev=dev[1], r_intent=0)
56    if "p2p-wlan" not in r_res['ifname']:
57        raise Exception("Unexpected group interface name")
58    check_grpform_results(i_res, r_res)
59    addr = dev[0].group_request("P2P_GROUP_MEMBER " + dev[1].p2p_dev_addr())
60    if "FAIL" in addr:
61        raise Exception("P2P_GROUP_MEMBER failed")
62    if addr != dev[1].p2p_interface_addr():
63        raise Exception("Unexpected P2P_GROUP_MEMBER result: " + addr)
64    if "FAIL" not in dev[0].group_request("P2P_GROUP_MEMBER a"):
65        raise Exception("Invalid P2P_GROUP_MEMBER command accepted")
66    if "FAIL" not in dev[0].group_request("P2P_GROUP_MEMBER 00:11:22:33:44:55"):
67        raise Exception("P2P_GROUP_MEMBER for non-member accepted")
68    remove_group(dev[0], dev[1])
69    if r_res['ifname'] in get_ifnames():
70        raise Exception("Group interface netdev was not removed")
71
72def test_grpform_c(dev):
73    """P2P group formation using PIN and authorized connection (init -> GO) (group iface)"""
74    dev[0].global_request("SET p2p_no_group_iface 0")
75    dev[1].global_request("SET p2p_no_group_iface 0")
76    [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
77                                           r_dev=dev[1], r_intent=0)
78    if "p2p-wlan" not in i_res['ifname']:
79        raise Exception("Unexpected group interface name")
80    if "p2p-wlan" not in r_res['ifname']:
81        raise Exception("Unexpected group interface name")
82    check_grpform_results(i_res, r_res)
83    remove_group(dev[0], dev[1])
84    if i_res['ifname'] in get_ifnames():
85        raise Exception("Group interface netdev was not removed")
86    if r_res['ifname'] in get_ifnames():
87        raise Exception("Group interface netdev was not removed")
88
89@remote_compatible
90def test_grpform2(dev):
91    """P2P group formation using PIN and authorized connection (resp -> GO)"""
92    go_neg_pin_authorized(i_dev=dev[0], i_intent=0, r_dev=dev[1], r_intent=15)
93    remove_group(dev[0], dev[1])
94
95def test_grpform2_c(dev):
96    """P2P group formation using PIN and authorized connection (resp -> GO) (group iface)"""
97    dev[0].global_request("SET p2p_no_group_iface 0")
98    dev[1].global_request("SET p2p_no_group_iface 0")
99    [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=0, r_dev=dev[1], r_intent=15)
100    remove_group(dev[0], dev[1])
101    if i_res['ifname'] in get_ifnames():
102        raise Exception("Group interface netdev was not removed")
103    if r_res['ifname'] in get_ifnames():
104        raise Exception("Group interface netdev was not removed")
105
106@remote_compatible
107def test_grpform3(dev):
108    """P2P group formation using PIN and re-init GO Negotiation"""
109    go_neg_pin(i_dev=dev[0], i_intent=15, r_dev=dev[1], r_intent=0)
110    remove_group(dev[0], dev[1])
111
112def test_grpform3_c(dev):
113    """P2P group formation using PIN and re-init GO Negotiation (group iface)"""
114    dev[0].global_request("SET p2p_no_group_iface 0")
115    dev[1].global_request("SET p2p_no_group_iface 0")
116    [i_res, r_res] = go_neg_pin(i_dev=dev[0], i_intent=15, r_dev=dev[1], r_intent=0)
117    remove_group(dev[0], dev[1])
118    if i_res['ifname'] in get_ifnames():
119        raise Exception("Group interface netdev was not removed")
120    if r_res['ifname'] in get_ifnames():
121        raise Exception("Group interface netdev was not removed")
122
123@remote_compatible
124def test_grpform4(dev):
125    """P2P group formation response during p2p_find"""
126    addr1 = dev[1].p2p_dev_addr()
127    dev[1].p2p_listen()
128    dev[0].discover_peer(addr1)
129    dev[1].p2p_find(social=True)
130    time.sleep(0.4)
131    dev[0].global_request("P2P_CONNECT " + addr1 + " 12345670 display")
132    ev = dev[1].wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=15)
133    if ev is None:
134        raise Exception("GO Negotiation RX timed out")
135    time.sleep(0.5)
136    dev[1].p2p_stop_find()
137    dev[0].p2p_stop_find()
138
139@remote_compatible
140def test_grpform_pbc(dev):
141    """P2P group formation using PBC and re-init GO Negotiation"""
142    [i_res, r_res] = go_neg_pbc(i_dev=dev[0], i_intent=15, r_dev=dev[1], r_intent=0)
143    check_grpform_results(i_res, r_res)
144    if i_res['role'] != 'GO' or r_res['role'] != 'client':
145        raise Exception("Unexpected device roles")
146    remove_group(dev[0], dev[1])
147
148@remote_compatible
149def test_grpform_pd(dev):
150    """P2P group formation with PD-before-GO-Neg workaround"""
151    [i_res, r_res] = go_neg_pbc(i_dev=dev[0], provdisc=True, r_dev=dev[1], r_listen=True)
152    check_grpform_results(i_res, r_res)
153    remove_group(dev[0], dev[1])
154
155def test_grpform_ext_listen(dev):
156    """P2P group formation with extended listen timing enabled"""
157    addr0 = dev[0].p2p_dev_addr()
158    try:
159        if "FAIL" not in dev[0].global_request("P2P_EXT_LISTEN 100"):
160            raise Exception("Invalid P2P_EXT_LISTEN accepted")
161        if "OK" not in dev[0].global_request("P2P_EXT_LISTEN 300 1000"):
162            raise Exception("Failed to set extended listen timing")
163        if "OK" not in dev[1].global_request("P2P_EXT_LISTEN 200 40000"):
164            raise Exception("Failed to set extended listen timing")
165        [i_res, r_res] = go_neg_pbc(i_dev=dev[0], provdisc=True, r_dev=dev[1],
166                                    r_listen=True, i_freq="2417", r_freq="2417",
167                                    i_intent=1, r_intent=15)
168        check_grpform_results(i_res, r_res)
169        peer1 = dev[0].get_peer(dev[1].p2p_dev_addr())
170        if peer1['ext_listen_interval'] != "40000":
171            raise Exception("Extended listen interval not discovered correctly")
172        if peer1['ext_listen_period'] != "200":
173            raise Exception("Extended listen period not discovered correctly")
174        peer0 = dev[1].get_peer(dev[0].p2p_dev_addr())
175        if peer0['ext_listen_interval'] != "1000":
176            raise Exception("Extended listen interval not discovered correctly")
177        if peer0['ext_listen_period'] != "300":
178            raise Exception("Extended listen period not discovered correctly")
179        if not dev[2].discover_peer(addr0):
180            raise Exception("Could not discover peer during ext listen")
181        remove_group(dev[0], dev[1])
182    finally:
183        if "OK" not in dev[0].global_request("P2P_EXT_LISTEN"):
184            raise Exception("Failed to clear extended listen timing")
185        if "OK" not in dev[1].global_request("P2P_EXT_LISTEN"):
186            raise Exception("Failed to clear extended listen timing")
187
188def test_grpform_ext_listen_oper(dev):
189    """P2P extended listen timing operations"""
190    try:
191        _test_grpform_ext_listen_oper(dev)
192    finally:
193        dev[0].global_request("P2P_EXT_LISTEN")
194
195def _test_grpform_ext_listen_oper(dev):
196    addr0 = dev[0].p2p_dev_addr()
197    dev[0].global_request("SET p2p_no_group_iface 0")
198    wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
199    wpas.interface_add("wlan5")
200    addr1 = wpas.p2p_dev_addr()
201    wpas.request("P2P_SET listen_channel 1")
202    wpas.global_request("SET p2p_no_group_iface 0")
203    wpas.request("P2P_LISTEN")
204    if not dev[0].discover_peer(addr1):
205        raise Exception("Could not discover peer")
206    dev[0].request("P2P_LISTEN")
207    if not wpas.discover_peer(addr0):
208        raise Exception("Could not discover peer (2)")
209
210    dev[0].global_request("P2P_EXT_LISTEN 300 500")
211    dev[0].global_request("P2P_CONNECT " + addr1 + " 12345670 display auth go_intent=0 freq=2417")
212    wpas.global_request("P2P_CONNECT " + addr0 + " 12345670 enter go_intent=15 freq=2417")
213    ev = dev[0].wait_global_event(["P2P-GO-NEG-SUCCESS"], timeout=15)
214    if ev is None:
215        raise Exception("GO Negotiation failed")
216    ifaces = wpas.request("INTERFACES").splitlines()
217    iface = ifaces[0] if "p2p-wlan" in ifaces[0] else ifaces[1]
218    wpas.group_ifname = iface
219    if "OK" not in wpas.group_request("STOP_AP"):
220        raise Exception("STOP_AP failed")
221    wpas.group_request("SET ext_mgmt_frame_handling 1")
222    dev[1].p2p_find(social=True)
223    time.sleep(1)
224    if dev[1].peer_known(addr0):
225        raise Exception("Unexpected peer discovery")
226    ifaces = dev[0].request("INTERFACES").splitlines()
227    iface = ifaces[0] if "p2p-wlan" in ifaces[0] else ifaces[1]
228    if "OK" not in dev[0].global_request("P2P_GROUP_REMOVE " + iface):
229        raise Exception("Failed to request group removal")
230    wpas.remove_group()
231
232    count = 0
233    timeout = 15
234    found = False
235    while count < timeout * 4:
236        time.sleep(0.25)
237        count = count + 1
238        if dev[1].peer_known(addr0):
239            found = True
240            break
241    dev[1].p2p_stop_find()
242    if not found:
243        raise Exception("Could not discover peer that was supposed to use extended listen")
244
245@remote_compatible
246def test_both_go_intent_15(dev):
247    """P2P GO Negotiation with both devices using GO intent 15"""
248    go_neg_pin_authorized(i_dev=dev[0], i_intent=15, r_dev=dev[1], r_intent=15, expect_failure=True, i_go_neg_status=9)
249
250@remote_compatible
251def test_both_go_neg_display(dev):
252    """P2P GO Negotiation with both devices trying to display PIN"""
253    go_neg_pin_authorized(i_dev=dev[0], r_dev=dev[1], expect_failure=True, i_go_neg_status=10, i_method='display', r_method='display')
254
255@remote_compatible
256def test_both_go_neg_enter(dev):
257    """P2P GO Negotiation with both devices trying to enter PIN"""
258    go_neg_pin_authorized(i_dev=dev[0], r_dev=dev[1], expect_failure=True, i_go_neg_status=10, i_method='enter', r_method='enter')
259
260@remote_compatible
261def test_go_neg_pbc_vs_pin(dev):
262    """P2P GO Negotiation with one device using PBC and the other PIN"""
263    addr0 = dev[0].p2p_dev_addr()
264    addr1 = dev[1].p2p_dev_addr()
265    dev[1].p2p_listen()
266    if not dev[0].discover_peer(addr1):
267        raise Exception("Could not discover peer")
268    dev[0].p2p_listen()
269    if "OK" not in dev[0].request("P2P_CONNECT " + addr1 + " pbc auth"):
270        raise Exception("Failed to authorize GO Neg")
271    if not dev[1].discover_peer(addr0):
272        raise Exception("Could not discover peer")
273    if "OK" not in dev[1].request("P2P_CONNECT " + addr0 + " 12345670 display"):
274        raise Exception("Failed to initiate GO Neg")
275    ev = dev[1].wait_global_event(["P2P-GO-NEG-FAILURE"], timeout=10)
276    if ev is None:
277        raise Exception("GO Negotiation failure timed out")
278    if "status=10" not in ev:
279        raise Exception("Unexpected failure reason: " + ev)
280
281@remote_compatible
282def test_go_neg_pin_vs_pbc(dev):
283    """P2P GO Negotiation with one device using PIN and the other PBC"""
284    addr0 = dev[0].p2p_dev_addr()
285    addr1 = dev[1].p2p_dev_addr()
286    dev[1].p2p_listen()
287    if not dev[0].discover_peer(addr1):
288        raise Exception("Could not discover peer")
289    dev[0].p2p_listen()
290    if "OK" not in dev[0].request("P2P_CONNECT " + addr1 + " 12345670 display auth"):
291        raise Exception("Failed to authorize GO Neg")
292    if not dev[1].discover_peer(addr0):
293        raise Exception("Could not discover peer")
294    if "OK" not in dev[1].request("P2P_CONNECT " + addr0 + " pbc"):
295        raise Exception("Failed to initiate GO Neg")
296    ev = dev[1].wait_global_event(["P2P-GO-NEG-FAILURE"], timeout=10)
297    if ev is None:
298        raise Exception("GO Negotiation failure timed out")
299    if "status=10" not in ev:
300        raise Exception("Unexpected failure reason: " + ev)
301
302def test_grpform_per_sta_psk(dev):
303    """P2P group formation with per-STA PSKs"""
304    dev[0].global_request("P2P_SET per_sta_psk 1")
305    [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15, r_dev=dev[1], r_intent=0)
306    check_grpform_results(i_res, r_res)
307
308    pin = dev[2].wps_read_pin()
309    dev[0].p2p_go_authorize_client(pin)
310    c_res = dev[2].p2p_connect_group(dev[0].p2p_dev_addr(), pin, timeout=60)
311    dev[0].wait_sta(dev[2].p2p_interface_addr())
312    check_grpform_results(i_res, c_res)
313
314    if r_res['psk'] == c_res['psk']:
315        raise Exception("Same PSK assigned for both clients")
316
317    hwsim_utils.test_connectivity_p2p(dev[1], dev[2])
318
319    dev[0].remove_group()
320    dev[1].wait_go_ending_session()
321    dev[2].wait_go_ending_session()
322
323def test_grpform_per_sta_psk_wps(dev):
324    """P2P group formation with per-STA PSKs with non-P2P WPS STA"""
325    dev[0].global_request("P2P_SET per_sta_psk 1")
326    [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15, r_dev=dev[1], r_intent=0)
327    check_grpform_results(i_res, r_res)
328
329    dev[0].p2p_go_authorize_client_pbc()
330    dev[2].request("WPS_PBC")
331    dev[2].wait_connected(timeout=30)
332
333    dev[0].wait_sta(dev[2].p2p_interface_addr())
334    hwsim_utils.test_connectivity_p2p_sta(dev[1], dev[2])
335
336    dev[0].remove_group()
337    dev[2].request("DISCONNECT")
338    dev[1].wait_go_ending_session()
339
340@remote_compatible
341def test_grpform_force_chan_go(dev):
342    """P2P group formation forced channel selection by GO"""
343    [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
344                                           i_freq=2432,
345                                           r_dev=dev[1], r_intent=0,
346                                           test_data=False)
347    check_grpform_results(i_res, r_res)
348    if i_res['freq'] != "2432":
349        raise Exception("Unexpected channel - did not follow GO's forced channel")
350    remove_group(dev[0], dev[1])
351
352@remote_compatible
353def test_grpform_force_chan_cli(dev):
354    """P2P group formation forced channel selection by client"""
355    [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=0,
356                                           i_freq=2417,
357                                           r_dev=dev[1], r_intent=15,
358                                           test_data=False)
359    check_grpform_results(i_res, r_res)
360    if i_res['freq'] != "2417":
361        raise Exception("Unexpected channel - did not follow GO's forced channel")
362    remove_group(dev[0], dev[1])
363
364@remote_compatible
365def test_grpform_force_chan_conflict(dev):
366    """P2P group formation fails due to forced channel mismatch"""
367    go_neg_pin_authorized(i_dev=dev[0], i_intent=0, i_freq=2422,
368                          r_dev=dev[1], r_intent=15, r_freq=2427,
369                          expect_failure=True, i_go_neg_status=7)
370
371@remote_compatible
372def test_grpform_pref_chan_go(dev):
373    """P2P group formation preferred channel selection by GO"""
374    try:
375        dev[0].request("SET p2p_pref_chan 81:7")
376        [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
377                                               r_dev=dev[1], r_intent=0,
378                                               test_data=False)
379        check_grpform_results(i_res, r_res)
380        if i_res['freq'] != "2442":
381            raise Exception("Unexpected channel - did not follow GO's p2p_pref_chan")
382        remove_group(dev[0], dev[1])
383    finally:
384        dev[0].request("SET p2p_pref_chan ")
385
386@remote_compatible
387def test_grpform_pref_chan_go_overridden(dev):
388    """P2P group formation preferred channel selection by GO overridden by client"""
389    try:
390        dev[1].request("SET p2p_pref_chan 81:7")
391        [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=0,
392                                               i_freq=2422,
393                                               r_dev=dev[1], r_intent=15,
394                                               test_data=False)
395        check_grpform_results(i_res, r_res)
396        if i_res['freq'] != "2422":
397            raise Exception("Unexpected channel - did not follow client's forced channel")
398        remove_group(dev[0], dev[1])
399    finally:
400        dev[1].request("SET p2p_pref_chan ")
401
402@remote_compatible
403def test_grpform_no_go_freq_forcing_chan(dev):
404    """P2P group formation with no-GO freq forcing channel"""
405    try:
406        dev[1].request("SET p2p_no_go_freq 100-200,300,4000-6000")
407        [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=0,
408                                               r_dev=dev[1], r_intent=15,
409                                               test_data=False)
410        check_grpform_results(i_res, r_res)
411        if int(i_res['freq']) > 4000:
412            raise Exception("Unexpected channel - did not follow no-GO freq")
413        remove_group(dev[0], dev[1])
414    finally:
415        dev[1].request("SET p2p_no_go_freq ")
416
417@remote_compatible
418def test_grpform_no_go_freq_conflict(dev):
419    """P2P group formation fails due to no-GO range forced by client"""
420    try:
421        dev[1].request("SET p2p_no_go_freq 2000-3000")
422        go_neg_pin_authorized(i_dev=dev[0], i_intent=0, i_freq=2422,
423                              r_dev=dev[1], r_intent=15,
424                              expect_failure=True, i_go_neg_status=7)
425    finally:
426        dev[1].request("SET p2p_no_go_freq ")
427
428@remote_compatible
429def test_grpform_no_5ghz_world_roaming(dev):
430    """P2P group formation with world roaming regulatory"""
431    [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=0,
432                                           r_dev=dev[1], r_intent=15,
433                                           test_data=False)
434    check_grpform_results(i_res, r_res)
435    if int(i_res['freq']) > 4000:
436        raise Exception("Unexpected channel - did not follow world roaming rules")
437    remove_group(dev[0], dev[1])
438
439@remote_compatible
440def test_grpform_no_5ghz_add_cli(dev):
441    """P2P group formation with passive scan 5 GHz and p2p_add_cli_chan=1"""
442    try:
443        dev[0].request("SET p2p_add_cli_chan 1")
444        dev[1].request("SET p2p_add_cli_chan 1")
445        [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=0,
446                                               r_dev=dev[1], r_intent=14,
447                                               test_data=False)
448        check_grpform_results(i_res, r_res)
449        if int(i_res['freq']) > 4000:
450            raise Exception("Unexpected channel - did not follow world roaming rules")
451        remove_group(dev[0], dev[1])
452    finally:
453        dev[0].request("SET p2p_add_cli_chan 0")
454        dev[1].request("SET p2p_add_cli_chan 0")
455
456@remote_compatible
457def test_grpform_no_5ghz_add_cli2(dev):
458    """P2P group formation with passive scan 5 GHz and p2p_add_cli_chan=1 (reverse)"""
459    try:
460        dev[0].request("SET p2p_add_cli_chan 1")
461        dev[1].request("SET p2p_add_cli_chan 1")
462        [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=14,
463                                               r_dev=dev[1], r_intent=0,
464                                               test_data=False)
465        check_grpform_results(i_res, r_res)
466        if int(i_res['freq']) > 4000:
467            raise Exception("Unexpected channel - did not follow world roaming rules")
468        remove_group(dev[0], dev[1])
469    finally:
470        dev[0].request("SET p2p_add_cli_chan 0")
471        dev[1].request("SET p2p_add_cli_chan 0")
472
473@remote_compatible
474def test_grpform_no_5ghz_add_cli3(dev):
475    """P2P group formation with passive scan 5 GHz and p2p_add_cli_chan=1 (intent 15)"""
476    try:
477        dev[0].request("SET p2p_add_cli_chan 1")
478        dev[1].request("SET p2p_add_cli_chan 1")
479        [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=0,
480                                               r_dev=dev[1], r_intent=15,
481                                               test_data=False)
482        check_grpform_results(i_res, r_res)
483        if int(i_res['freq']) > 4000:
484            raise Exception("Unexpected channel - did not follow world roaming rules")
485        remove_group(dev[0], dev[1])
486    finally:
487        dev[0].request("SET p2p_add_cli_chan 0")
488        dev[1].request("SET p2p_add_cli_chan 0")
489
490@remote_compatible
491def test_grpform_no_5ghz_add_cli4(dev):
492    """P2P group formation with passive scan 5 GHz and p2p_add_cli_chan=1 (reverse; intent 15)"""
493    try:
494        dev[0].request("SET p2p_add_cli_chan 1")
495        dev[1].request("SET p2p_add_cli_chan 1")
496        [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
497                                               r_dev=dev[1], r_intent=0,
498                                               test_data=False)
499        check_grpform_results(i_res, r_res)
500        if int(i_res['freq']) > 4000:
501            raise Exception("Unexpected channel - did not follow world roaming rules")
502        remove_group(dev[0], dev[1])
503    finally:
504        dev[0].request("SET p2p_add_cli_chan 0")
505        dev[1].request("SET p2p_add_cli_chan 0")
506
507@remote_compatible
508def test_grpform_incorrect_pin(dev):
509    """P2P GO Negotiation with incorrect PIN"""
510    dev[1].p2p_listen()
511    addr1 = dev[1].p2p_dev_addr()
512    if not dev[0].discover_peer(addr1):
513        raise Exception("Peer not found")
514    res = dev[1].global_request("P2P_CONNECT " + dev[0].p2p_dev_addr() + " pin auth go_intent=0")
515    if "FAIL" in res:
516        raise Exception("P2P_CONNECT failed to generate PIN")
517    logger.info("PIN from P2P_CONNECT: " + res)
518    dev[0].global_request("P2P_CONNECT " + addr1 + " 00000000 enter go_intent=15")
519    ev = dev[0].wait_global_event(["P2P-GO-NEG-SUCCESS"], timeout=15)
520    if ev is None:
521        raise Exception("GO Negotiation did not complete successfully(0)")
522    ev = dev[1].wait_global_event(["P2P-GO-NEG-SUCCESS"], timeout=15)
523    if ev is None:
524        raise Exception("GO Negotiation did not complete successfully(1)")
525    ev = dev[1].wait_global_event(["WPS-FAIL"], timeout=15)
526    if ev is None:
527        raise Exception("WPS failure not reported(1)")
528    if "msg=8 config_error=18" not in ev:
529        raise Exception("Unexpected WPS failure(1): " + ev)
530    ev = dev[0].wait_global_event(["WPS-FAIL"], timeout=15)
531    if ev is None:
532        raise Exception("WPS failure not reported")
533    if "msg=8 config_error=18" not in ev:
534        raise Exception("Unexpected WPS failure: " + ev)
535    ev = dev[1].wait_global_event(["P2P-GROUP-FORMATION-FAILURE"], timeout=10)
536    if ev is None:
537        raise Exception("Group formation failure timed out")
538    ev = dev[0].wait_global_event(["P2P-GROUP-FORMATION-FAILURE"], timeout=5)
539    if ev is None:
540        raise Exception("Group formation failure timed out")
541
542@remote_compatible
543def test_grpform_reject(dev):
544    """User rejecting group formation attempt by a P2P peer"""
545    addr0 = dev[0].p2p_dev_addr()
546    dev[0].p2p_listen()
547    dev[1].p2p_go_neg_init(addr0, None, "pbc")
548    ev = dev[0].wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=15)
549    if ev is None:
550        raise Exception("GO Negotiation timed out")
551    if "OK" in dev[0].global_request("P2P_REJECT foo"):
552        raise Exception("Invalid P2P_REJECT accepted")
553    if "FAIL" in dev[0].global_request("P2P_REJECT " + ev.split(' ')[1]):
554        raise Exception("P2P_REJECT failed")
555    dev[1].request("P2P_STOP_FIND")
556    dev[1].p2p_go_neg_init(addr0, None, "pbc")
557    ev = dev[1].wait_global_event(["P2P-GO-NEG-FAILURE"], timeout=10)
558    if ev is None:
559        raise Exception("Rejection not reported")
560    if "status=11" not in ev:
561        raise Exception("Unexpected status code in rejection")
562
563@remote_compatible
564def test_grpform_pd_no_probe_resp(dev):
565    """GO Negotiation after PD, but no Probe Response"""
566    addr0 = dev[0].p2p_dev_addr()
567    addr1 = dev[1].p2p_dev_addr()
568    dev[0].p2p_listen()
569    if not dev[1].discover_peer(addr0):
570        raise Exception("Peer not found")
571    dev[1].p2p_stop_find()
572    dev[0].p2p_stop_find()
573    peer = dev[0].get_peer(addr1)
574    if peer['listen_freq'] == '0':
575        raise Exception("Peer listen frequency not learned from Probe Request")
576    time.sleep(0.3)
577    dev[0].request("P2P_FLUSH")
578    dev[0].p2p_listen()
579    dev[1].global_request("P2P_PROV_DISC " + addr0 + " display")
580    ev = dev[0].wait_global_event(["P2P-PROV-DISC-SHOW-PIN"], timeout=5)
581    if ev is None:
582        raise Exception("PD Request timed out")
583    ev = dev[1].wait_global_event(["P2P-PROV-DISC-ENTER-PIN"], timeout=5)
584    if ev is None:
585        raise Exception("PD Response timed out")
586    peer = dev[0].get_peer(addr1)
587    if peer['listen_freq'] != '0':
588        raise Exception("Peer listen frequency learned unexpectedly from PD Request")
589
590    pin = dev[0].wps_read_pin()
591    if "FAIL" in dev[1].global_request("P2P_CONNECT " + addr0 + " " + pin + " enter"):
592        raise Exception("P2P_CONNECT on initiator failed")
593    ev = dev[0].wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=5)
594    if ev is None:
595        raise Exception("GO Negotiation start timed out")
596    peer = dev[0].get_peer(addr1)
597    if peer['listen_freq'] == '0':
598        raise Exception("Peer listen frequency not learned from PD followed by GO Neg Req")
599    if "FAIL" in dev[0].global_request("P2P_CONNECT " + addr1 + " " + pin + " display"):
600        raise Exception("P2P_CONNECT on responder failed")
601    ev = dev[0].wait_global_event(["P2P-GROUP-STARTED"], timeout=15)
602    if ev is None:
603        raise Exception("Group formation timed out")
604    ev = dev[1].wait_global_event(["P2P-GROUP-STARTED"], timeout=15)
605    if ev is None:
606        raise Exception("Group formation timed out")
607
608def test_go_neg_two_peers(dev):
609    """P2P GO Negotiation rejected due to already started negotiation with another peer"""
610    addr0 = dev[0].p2p_dev_addr()
611    addr1 = dev[1].p2p_dev_addr()
612    addr2 = dev[2].p2p_dev_addr()
613    dev[1].p2p_listen()
614    dev[2].p2p_listen()
615    if not dev[0].discover_peer(addr1):
616        raise Exception("Could not discover peer")
617    if not dev[0].discover_peer(addr2):
618        raise Exception("Could not discover peer")
619    if "OK" not in dev[0].request("P2P_CONNECT " + addr2 + " pbc auth"):
620        raise Exception("Failed to authorize GO Neg")
621    dev[0].p2p_listen()
622    if not dev[2].discover_peer(addr0):
623        raise Exception("Could not discover peer")
624    if "OK" not in dev[0].request("P2P_CONNECT " + addr1 + " pbc"):
625        raise Exception("Failed to initiate GO Neg")
626    ev = dev[1].wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=5)
627    if ev is None:
628        raise Exception("timeout on GO Neg RX event")
629    dev[2].request("P2P_CONNECT " + addr0 + " pbc")
630    ev = dev[2].wait_global_event(["P2P-GO-NEG-FAILURE"], timeout=10)
631    if ev is None:
632        raise Exception("Rejection not reported")
633    if "status=5" not in ev:
634        raise Exception("Unexpected status code in rejection: " + ev)
635
636def clear_pbc_overlap(dev, ap):
637    hostapd.remove_bss(ap)
638    dev[0].request("P2P_CANCEL")
639    dev[1].request("P2P_CANCEL")
640    dev[0].p2p_stop_find()
641    dev[1].p2p_stop_find()
642    remove_group(dev[0], dev[1], allow_failure=True)
643    dev[0].dump_monitor()
644    dev[1].dump_monitor()
645    time.sleep(0.1)
646    dev[0].flush_scan_cache()
647    dev[1].flush_scan_cache()
648    time.sleep(0.1)
649
650@remote_compatible
651def test_grpform_pbc_overlap(dev, apdev):
652    """P2P group formation during PBC overlap"""
653    params = {"ssid": "wps", "eap_server": "1", "wps_state": "1"}
654    hapd = hostapd.add_ap(apdev[0], params)
655    hapd.request("WPS_PBC")
656    time.sleep(0.1)
657
658    # Since P2P Client scan case is now optimized to use a specific SSID, the
659    # WPS AP will not reply to that and the scan after GO Negotiation can quite
660    # likely miss the AP due to dwell time being short enough to miss the Beacon
661    # frame. This has made the test case somewhat pointless, but keep it here
662    # for now with an additional scan to confirm that PBC detection works if
663    # there is a BSS entry for a overlapping AP.
664    for i in range(0, 5):
665        dev[0].scan(freq="2412")
666        if dev[0].get_bss(apdev[0]['bssid']) is not None:
667            break
668
669    addr0 = dev[0].p2p_dev_addr()
670    addr1 = dev[1].p2p_dev_addr()
671    dev[0].p2p_listen()
672    if not dev[1].discover_peer(addr0):
673        raise Exception("Could not discover peer")
674    dev[1].p2p_listen()
675    if not dev[0].discover_peer(addr1):
676        raise Exception("Could not discover peer")
677    dev[0].p2p_listen()
678    if "OK" not in dev[0].global_request("P2P_CONNECT " + addr1 + " pbc auth go_intent=0"):
679        raise Exception("Failed to authorize GO Neg")
680    if "OK" not in dev[1].global_request("P2P_CONNECT " + addr0 + " pbc go_intent=15 freq=2412"):
681        raise Exception("Failed to initiate GO Neg")
682    ev = dev[0].wait_global_event(["WPS-OVERLAP-DETECTED",
683                                   "P2P-GROUP-FORMATION-SUCCESS"], timeout=15)
684    clear_pbc_overlap(dev, apdev[0])
685    if ev is None or "P2P-GROUP-FORMATION-SUCCESS" not in ev:
686        raise Exception("P2P group formation did not complete")
687
688@remote_compatible
689def test_grpform_pbc_overlap_group_iface(dev, apdev):
690    """P2P group formation during PBC overlap using group interfaces"""
691    # Note: Need to include P2P IE from the AP to get the P2P interface BSS
692    # update use this information.
693    params = {"ssid": "wps", "eap_server": "1", "wps_state": "1",
694              "beacon_int": "15", 'manage_p2p': '1'}
695    hapd = hostapd.add_ap(apdev[0], params)
696    hapd.request("WPS_PBC")
697
698    dev[0].request("SET p2p_no_group_iface 0")
699    dev[1].request("SET p2p_no_group_iface 0")
700
701    addr0 = dev[0].p2p_dev_addr()
702    addr1 = dev[1].p2p_dev_addr()
703    dev[0].p2p_listen()
704    if not dev[1].discover_peer(addr0):
705        raise Exception("Could not discover peer")
706    dev[1].p2p_listen()
707    if not dev[0].discover_peer(addr1):
708        raise Exception("Could not discover peer")
709    dev[0].p2p_stop_find()
710    dev[0].scan(freq="2412")
711    dev[0].p2p_listen()
712    if "OK" not in dev[0].global_request("P2P_CONNECT " + addr1 + " pbc auth go_intent=0"):
713        raise Exception("Failed to authorize GO Neg")
714    if "OK" not in dev[1].global_request("P2P_CONNECT " + addr0 + " pbc go_intent=15 freq=2412"):
715        raise Exception("Failed to initiate GO Neg")
716    ev = dev[0].wait_global_event(["WPS-OVERLAP-DETECTED",
717                                   "P2P-GROUP-FORMATION-SUCCESS"], timeout=15)
718    clear_pbc_overlap(dev, apdev[0])
719    if ev is None or "P2P-GROUP-FORMATION-SUCCESS" not in ev:
720        raise Exception("P2P group formation did not complete")
721
722@remote_compatible
723def test_grpform_goneg_fail_with_group_iface(dev):
724    """P2P group formation fails while using group interface"""
725    dev[0].request("SET p2p_no_group_iface 0")
726    dev[1].p2p_listen()
727    peer = dev[1].p2p_dev_addr()
728    if not dev[0].discover_peer(peer):
729        raise Exception("Peer " + peer + " not found")
730    if "OK" not in dev[1].request("P2P_REJECT " + dev[0].p2p_dev_addr()):
731        raise Exception("P2P_REJECT failed")
732    if "OK" not in dev[0].request("P2P_CONNECT " + peer + " pbc"):
733        raise Exception("P2P_CONNECT failed")
734    ev = dev[0].wait_global_event(["P2P-GO-NEG-FAILURE"], timeout=10)
735    if ev is None:
736        raise Exception("GO Negotiation failure timed out")
737
738@long_duration_test
739def test_grpform_cred_ready_timeout(dev):
740    """P2P GO Negotiation wait for credentials to become ready"""
741    dev[1].p2p_listen()
742    addr1 = dev[1].p2p_dev_addr()
743    if not dev[0].discover_peer(addr1):
744        raise Exception("Peer " + addr1 + " not found")
745    if not dev[2].discover_peer(addr1):
746        raise Exception("Peer " + addr1 + " not found(2)")
747
748    start = os.times()[4]
749
750    cmd = "P2P_CONNECT " + addr1 + " 12345670 display"
751    if "OK" not in dev[0].global_request(cmd):
752        raise Exception("Failed to initiate GO Neg")
753
754    if "OK" not in dev[2].global_request(cmd):
755        raise Exception("Failed to initiate GO Neg(2)")
756
757    # First, check with p2p_find
758    ev = dev[2].wait_global_event(["P2P-GO-NEG-FAILURE"], timeout=30)
759    if ev is not None:
760        raise Exception("Too early GO Negotiation timeout reported(2)")
761    dev[2].dump_monitor()
762    logger.info("Starting p2p_find to change state")
763    dev[2].p2p_find()
764    for i in range(10):
765        ev = dev[2].wait_global_event(["P2P-GO-NEG-FAILURE"], timeout=10)
766        if ev:
767            break
768        dev[2].dump_monitor(global_mon=False)
769    if ev is None:
770        raise Exception("GO Negotiation failure timed out(2)")
771    dev[2].dump_monitor()
772    end = os.times()[4]
773    logger.info("GO Negotiation wait time: {} seconds(2)".format(end - start))
774    if end - start < 120:
775        raise Exception("Too short GO Negotiation wait time(2): {}".format(end - start))
776
777    wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
778    wpas.interface_add("wlan5")
779
780    wpas.p2p_listen()
781    ev = dev[2].wait_global_event(["P2P-DEVICE-FOUND"], timeout=10)
782    if ev is None:
783        raise Exception("Did not discover new device after GO Negotiation failure")
784    if wpas.p2p_dev_addr() not in ev:
785        raise Exception("Unexpected device found: " + ev)
786    dev[2].p2p_stop_find()
787    dev[2].dump_monitor()
788    wpas.p2p_stop_find()
789    wpas.close_monitor()
790    del wpas
791
792    # Finally, verify without p2p_find
793    ev = dev[0].wait_global_event(["P2P-GO-NEG-FAILURE"], timeout=120)
794    if ev is None:
795        raise Exception("GO Negotiation failure timed out")
796    end = os.times()[4]
797    logger.info("GO Negotiation wait time: {} seconds".format(end - start))
798    if end - start < 120:
799        raise Exception("Too short GO Negotiation wait time: {}".format(end - start))
800
801def test_grpform_no_wsc_done(dev):
802    """P2P group formation with WSC-Done not sent"""
803    addr0 = dev[0].p2p_dev_addr()
804    addr1 = dev[1].p2p_dev_addr()
805
806    for i in range(0, 2):
807        dev[0].request("SET ext_eapol_frame_io 1")
808        dev[1].request("SET ext_eapol_frame_io 1")
809        dev[0].p2p_listen()
810        dev[1].p2p_go_neg_auth(addr0, "12345670", "display", 0)
811        dev[1].p2p_listen()
812        dev[0].p2p_go_neg_init(addr1, "12345670", "enter", timeout=20,
813                               go_intent=15, wait_group=False)
814
815        mode = None
816        while True:
817            ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
818            if ev is None:
819                raise Exception("Timeout on EAPOL-TX from GO")
820            if not mode:
821                mode = dev[0].get_status_field("mode")
822            res = dev[1].request("EAPOL_RX " + addr0 + " " + ev.split(' ')[2])
823            if "OK" not in res:
824                raise Exception("EAPOL_RX failed")
825            ev = dev[1].wait_event(["EAPOL-TX"], timeout=15)
826            if ev is None:
827                raise Exception("Timeout on EAPOL-TX from P2P Client")
828            msg = ev.split(' ')[2]
829            if msg[46:56] == "102200010f":
830                logger.info("Drop WSC_Done")
831                dev[0].request("SET ext_eapol_frame_io 0")
832                dev[1].request("SET ext_eapol_frame_io 0")
833                # Fake EAP-Failure to complete session on the client
834                id = msg[10:12]
835                dev[1].request("EAPOL_RX " + addr0 + " 0300000404" + id + "0004")
836                break
837            res = dev[0].request("EAPOL_RX " + addr1 + " " + msg)
838            if "OK" not in res:
839                raise Exception("EAPOL_RX failed")
840
841        ev = dev[0].wait_global_event(["P2P-GROUP-STARTED"], timeout=15)
842        if ev is None:
843            raise Exception("Group formation timed out on GO")
844        ev = dev[1].wait_global_event(["P2P-GROUP-STARTED"], timeout=15)
845        if ev is None:
846            raise Exception("Group formation timed out on P2P Client")
847        dev[0].remove_group()
848        dev[1].wait_go_ending_session()
849
850        if mode != "P2P GO - group formation":
851            raise Exception("Unexpected mode on GO during group formation: " + mode)
852
853@remote_compatible
854def test_grpform_wait_peer(dev):
855    """P2P group formation wait for peer to become ready"""
856    addr0 = dev[0].p2p_dev_addr()
857    addr1 = dev[1].p2p_dev_addr()
858    dev[1].p2p_listen()
859    if not dev[0].discover_peer(addr1):
860        raise Exception("Peer " + addr1 + " not found")
861    dev[0].request("SET extra_roc_dur 500")
862    if "OK" not in dev[0].request("P2P_CONNECT " + addr1 + " 12345670 display go_intent=15"):
863        raise Exception("Failed to initiate GO Neg")
864    time.sleep(3)
865    dev[1].request("P2P_CONNECT " + addr0 + " 12345670 enter go_intent=0")
866
867    ev = dev[0].wait_global_event(["P2P-GROUP-STARTED"], timeout=15)
868    if ev is None:
869        raise Exception("Group formation timed out")
870    dev[0].group_form_result(ev)
871
872    dev[0].request("SET extra_roc_dur 0")
873    ev = dev[1].wait_global_event(["P2P-GROUP-STARTED"], timeout=15)
874    if ev is None:
875        raise Exception("Group formation timed out")
876    dev[0].remove_group()
877
878@remote_compatible
879def test_invalid_p2p_connect_command(dev):
880    """P2P_CONNECT error cases"""
881    id = dev[0].add_network()
882    for cmd in ["foo",
883                "00:11:22:33:44:55",
884                "00:11:22:33:44:55 pbc persistent=123",
885                "00:11:22:33:44:55 pbc persistent=%d" % id,
886                "00:11:22:33:44:55 pbc go_intent=-1",
887                "00:11:22:33:44:55 pbc go_intent=16",
888                "00:11:22:33:44:55 pin",
889                "00:11:22:33:44:55 pbc freq=0"]:
890        if "FAIL" not in dev[0].request("P2P_CONNECT " + cmd):
891            raise Exception("Invalid P2P_CONNECT command accepted: " + cmd)
892
893    if "FAIL-INVALID-PIN" not in dev[0].request("P2P_CONNECT 00:11:22:33:44:55 1234567"):
894        raise Exception("Invalid PIN was not rejected")
895    if "FAIL-INVALID-PIN" not in dev[0].request("P2P_CONNECT 00:11:22:33:44:55 12345678a"):
896        raise Exception("Invalid PIN was not rejected")
897
898    if "FAIL-CHANNEL-UNSUPPORTED" not in dev[0].request("P2P_CONNECT 00:11:22:33:44:55 pin freq=3000"):
899        raise Exception("Unsupported channel not reported")
900
901@remote_compatible
902def test_p2p_unauthorize(dev):
903    """P2P_UNAUTHORIZE to unauthorize a peer"""
904    if "FAIL" not in dev[0].request("P2P_UNAUTHORIZE foo"):
905        raise Exception("Invalid P2P_UNAUTHORIZE accepted")
906    if "FAIL" not in dev[0].request("P2P_UNAUTHORIZE 00:11:22:33:44:55"):
907        raise Exception("P2P_UNAUTHORIZE for unknown peer accepted")
908
909    addr0 = dev[0].p2p_dev_addr()
910    addr1 = dev[1].p2p_dev_addr()
911    dev[1].p2p_listen()
912    pin = dev[0].wps_read_pin()
913    dev[0].p2p_go_neg_auth(addr1, pin, "display")
914    dev[0].p2p_listen()
915    if "OK" not in dev[0].request("P2P_UNAUTHORIZE " + addr1):
916        raise Exception("P2P_UNAUTHORIZE failed")
917    dev[1].p2p_go_neg_init(addr0, pin, "keypad", timeout=0)
918    ev = dev[0].wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=10)
919    if ev is None:
920        raise Exception("No GO Negotiation Request RX reported")
921
922@remote_compatible
923def test_grpform_pbc_multiple(dev):
924    """P2P group formation using PBC multiple times in a row"""
925    try:
926        dev[1].request("SET passive_scan 1")
927        for i in range(5):
928            [i_res, r_res] = go_neg_pbc_authorized(i_dev=dev[0], i_intent=15,
929                                                   r_dev=dev[1], r_intent=0)
930            remove_group(dev[0], dev[1])
931    finally:
932        dev[1].request("SET passive_scan 0")
933        dev[1].flush_scan_cache()
934
935def test_grpform_not_ready(dev):
936    """Not ready for GO Negotiation (listen)"""
937    addr0 = dev[0].p2p_dev_addr()
938    addr2 = dev[2].p2p_dev_addr()
939    dev[0].p2p_listen()
940    if not dev[1].discover_peer(addr0):
941        raise Exception("Could not discover peer")
942    dev[1].global_request("P2P_CONNECT " + addr0 + " pbc")
943    ev = dev[0].wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=5)
944    if ev is None:
945        raise Exception("No P2P-GO-NEG-REQUEST event")
946    dev[0].dump_monitor()
947    time.sleep(5)
948    if not dev[2].discover_peer(addr0):
949        raise Exception("Could not discover peer(2)")
950    for i in range(3):
951        dev[i].p2p_stop_find()
952
953def test_grpform_not_ready2(dev):
954    """Not ready for GO Negotiation (search)"""
955    addr0 = dev[0].p2p_dev_addr()
956    addr2 = dev[2].p2p_dev_addr()
957    dev[0].p2p_find(social=True)
958    if not dev[1].discover_peer(addr0):
959        raise Exception("Could not discover peer")
960    dev[1].global_request("P2P_CONNECT " + addr0 + " pbc")
961    ev = dev[0].wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=5)
962    if ev is None:
963        raise Exception("No P2P-GO-NEG-REQUEST event")
964    dev[0].dump_monitor()
965    time.sleep(1)
966    dev[2].p2p_listen()
967    ev = dev[0].wait_global_event(["P2P-DEVICE-FOUND"], timeout=10)
968    if ev is None:
969        raise Exception("Peer not discovered after GO Neg Resp(status=1) TX")
970    if addr2 not in ev:
971        raise Exception("Unexpected peer discovered: " + ev)
972    for i in range(3):
973        dev[i].p2p_stop_find()
974
975@remote_compatible
976def test_grpform_and_scan(dev):
977    """GO Negotiation and scan operations"""
978    addr0 = dev[0].p2p_dev_addr()
979    addr1 = dev[1].p2p_dev_addr()
980    dev[1].p2p_listen()
981    if not dev[0].discover_peer(addr1):
982        raise Exception("Could not discover peer")
983    dev[0].p2p_stop_find()
984    dev[1].p2p_stop_find()
985
986    if "OK" not in dev[0].request("SCAN TYPE=ONLY freq=2412-2472"):
987        raise Exception("Could not start scan")
988    ev = dev[0].wait_event(["CTRL-EVENT-SCAN-STARTED"], timeout=5)
989    if ev is None:
990        raise Exception("Scan did not start")
991    time.sleep(0.1)
992    # Request PD while the previously started scan is still in progress
993    if "OK" not in dev[0].request("P2P_PROV_DISC %s pbc" % addr1):
994        raise Exception("Could not request PD")
995    ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
996    if ev is None:
997        raise Exception("Scan did not complete")
998    time.sleep(0.3)
999
1000    dev[1].p2p_listen()
1001    ev = dev[0].wait_global_event(["P2P-PROV-DISC-PBC-RESP"], timeout=5)
1002    if ev is None:
1003        raise Exception("PD Response not received")
1004
1005    if "OK" not in dev[0].request("SCAN TYPE=ONLY freq=2412-2472"):
1006        raise Exception("Could not start scan")
1007    ev = dev[0].wait_event(["CTRL-EVENT-SCAN-STARTED"], timeout=5)
1008    if ev is None:
1009        raise Exception("Scan did not start")
1010    time.sleep(0.1)
1011    # Request GO Neg while the previously started scan is still in progress
1012    if "OK" not in dev[0].request("P2P_CONNECT %s pbc" % addr1):
1013        raise Exception("Could not request GO Negotiation")
1014    ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
1015    if ev is None:
1016        raise Exception("Scan did not complete")
1017
1018    ev = dev[1].wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=10)
1019    if ev is None:
1020        raise Exception("GO Neg Req RX not reported")
1021
1022    dev[1].p2p_stop_find()
1023
1024    if "OK" not in dev[1].request("SCAN TYPE=ONLY freq=2412-2472"):
1025        raise Exception("Could not start scan")
1026    ev = dev[1].wait_event(["CTRL-EVENT-SCAN-STARTED"], timeout=5)
1027    if ev is None:
1028        raise Exception("Scan did not start")
1029    time.sleep(0.1)
1030    dev[1].global_request("P2P_CONNECT " + addr0 + " pbc")
1031    ev = dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
1032    if ev is None:
1033        raise Exception("Scan did not complete")
1034
1035    ev0 = dev[0].wait_global_event(["P2P-GROUP-STARTED"], timeout=15)
1036    if ev0 is None:
1037        raise Exception("Group formation timed out on dev0")
1038    dev[0].group_form_result(ev0)
1039
1040    ev1 = dev[1].wait_global_event(["P2P-GROUP-STARTED"], timeout=15)
1041    if ev1 is None:
1042        raise Exception("Group formation timed out on dev1")
1043    dev[1].group_form_result(ev1)
1044
1045    dev[0].dump_monitor()
1046    dev[1].dump_monitor()
1047
1048    remove_group(dev[0], dev[1])
1049
1050    dev[0].dump_monitor()
1051    dev[1].dump_monitor()
1052
1053def test_grpform_go_neg_dup_on_restart(dev):
1054    """Duplicated GO Negotiation Request after GO Neg restart"""
1055    if dev[0].p2p_dev_addr() > dev[1].p2p_dev_addr():
1056        higher = dev[0]
1057        lower = dev[1]
1058    else:
1059        higher = dev[1]
1060        lower = dev[0]
1061    addr_low = lower.p2p_dev_addr()
1062    addr_high = higher.p2p_dev_addr()
1063    higher.p2p_listen()
1064    if not lower.discover_peer(addr_high):
1065        raise Exception("Could not discover peer")
1066    lower.p2p_stop_find()
1067
1068    if "OK" not in lower.request("P2P_CONNECT %s pbc" % addr_high):
1069        raise Exception("Could not request GO Negotiation")
1070    ev = higher.wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=10)
1071    if ev is None:
1072        raise Exception("GO Neg Req RX not reported")
1073
1074    # Wait for GO Negotiation Response (Status=1) to go through
1075    time.sleep(0.2)
1076
1077    if "FAIL" in lower.request("SET ext_mgmt_frame_handling 1"):
1078        raise Exception("Failed to enable external management frame handling")
1079
1080    higher.p2p_stop_find()
1081    higher.global_request("P2P_CONNECT " + addr_low + " pbc")
1082
1083    # Wait for the GO Negotiation Request frame of the restarted GO Negotiation
1084    rx_msg = lower.mgmt_rx()
1085    if rx_msg is None:
1086        raise Exception("MGMT-RX timeout")
1087    p2p = parse_p2p_public_action(rx_msg['payload'])
1088    if p2p is None:
1089        raise Exception("Not a P2P Public Action frame")
1090    if p2p['subtype'] != 0:
1091        raise Exception("Unexpected P2P Public Action subtype %d" % p2p['subtype'])
1092
1093    # Send duplicate GO Negotiation Request from the prior instance of GO
1094    # Negotiation
1095    lower.p2p_stop_find()
1096    peer = higher.get_peer(addr_low)
1097
1098    msg = p2p_hdr(addr_high, addr_low, type=P2P_GO_NEG_REQ, dialog_token=123)
1099    attrs = p2p_attr_capability(dev_capab=0x25, group_capab=0x08)
1100    attrs += p2p_attr_go_intent(go_intent=7, tie_breaker=1)
1101    attrs += p2p_attr_config_timeout()
1102    attrs += p2p_attr_listen_channel(chan=(int(peer['listen_freq']) - 2407) // 5)
1103    attrs += p2p_attr_intended_interface_addr(lower.p2p_dev_addr())
1104    attrs += p2p_attr_channel_list()
1105    attrs += p2p_attr_device_info(addr_low, config_methods=0x80, name="Device A")
1106    attrs += p2p_attr_operating_channel()
1107    wsc_attrs = struct.pack(">HHH", 0x1012, 2, 4)
1108    msg['payload'] += ie_p2p(attrs) + ie_wsc(wsc_attrs)
1109    mgmt_tx(lower, "MGMT_TX {} {} freq={} wait_time=200 no_cck=1 action={}".format(addr_high, addr_high, peer['listen_freq'], binascii.hexlify(msg['payload']).decode()))
1110
1111    # Wait for the GO Negotiation Response frame which would have been sent in
1112    # this case previously, but not anymore after the check for
1113    # dev->go_neg_req_sent and dev->flags & P2P_DEV_PEER_WAITING_RESPONSE.
1114    rx_msg = lower.mgmt_rx(timeout=0.2)
1115    if rx_msg is not None:
1116        raise Exception("Unexpected management frame")
1117
1118    if "FAIL" in lower.request("SET ext_mgmt_frame_handling 0"):
1119        raise Exception("Failed to disable external management frame handling")
1120    lower.p2p_listen()
1121
1122    ev = lower.wait_global_event(["P2P-GO-NEG-SUCCESS"], timeout=10)
1123    if ev is None:
1124        raise Exception("GO Negotiation did not succeed on dev0")
1125
1126    ev = higher.wait_global_event(["P2P-GO-NEG-SUCCESS"], timeout=10)
1127    if ev is None:
1128        raise Exception("GO Negotiation did not succeed on dev1")
1129
1130    ev0 = lower.wait_global_event(["P2P-GROUP-STARTED"], timeout=15)
1131    if ev0 is None:
1132        raise Exception("Group formation timed out on dev0")
1133    lower.group_form_result(ev0)
1134
1135    ev1 = higher.wait_global_event(["P2P-GROUP-STARTED"], timeout=15)
1136    if ev1 is None:
1137        raise Exception("Group formation timed out on dev1")
1138    higher.group_form_result(ev1)
1139
1140    lower.dump_monitor()
1141    higher.dump_monitor()
1142
1143    remove_group(lower, higher)
1144
1145    lower.dump_monitor()
1146    higher.dump_monitor()
1147
1148@remote_compatible
1149def test_grpform_go_neg_stopped(dev):
1150    """GO Negotiation stopped after TX start"""
1151    addr0 = dev[0].p2p_dev_addr()
1152    dev[0].p2p_listen()
1153    if not dev[1].discover_peer(addr0):
1154        raise Exception("Could not discover peer")
1155    dev[0].p2p_stop_find()
1156    if "OK" not in dev[1].request("P2P_CONNECT %s pbc" % addr0):
1157        raise Exception("Could not request GO Negotiation")
1158    dev[1].p2p_stop_find()
1159    dev[1].p2p_listen()
1160    dev[0].p2p_find(social=True)
1161    ev = dev[0].wait_global_event(["P2P-DEVICE-FOUND"], timeout=1.2)
1162    dev[0].p2p_stop_find()
1163    dev[1].p2p_stop_find()
1164    if ev is None:
1165        raise Exception("Did not find peer quickly enough after stopped P2P_CONNECT")
1166
1167def test_grpform_random_addr(dev):
1168    """P2P group formation with random interface addresses"""
1169    dev[0].global_request("SET p2p_no_group_iface 0")
1170    dev[1].global_request("SET p2p_no_group_iface 0")
1171    try:
1172        if "OK" not in dev[0].global_request("SET p2p_interface_random_mac_addr 1"):
1173            raise Exception("Failed to set p2p_interface_random_mac_addr")
1174        if "OK" not in dev[1].global_request("SET p2p_interface_random_mac_addr 1"):
1175            raise Exception("Failed to set p2p_interface_random_mac_addr")
1176        [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
1177                                               r_dev=dev[1], r_intent=0)
1178        if "p2p-wlan" not in i_res['ifname']:
1179            raise Exception("Unexpected group interface name")
1180        check_grpform_results(i_res, r_res)
1181        hwsim_utils.test_connectivity_p2p(dev[0], dev[1])
1182        remove_group(dev[0], dev[1])
1183        if i_res['ifname'] in get_ifnames():
1184            raise Exception("Group interface netdev was not removed")
1185    finally:
1186        dev[0].global_request("SET p2p_interface_random_mac_addr 0")
1187        dev[1].global_request("SET p2p_interface_random_mac_addr 0")
1188