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    check_grpform_results(i_res, c_res)
312
313    if r_res['psk'] == c_res['psk']:
314        raise Exception("Same PSK assigned for both clients")
315
316    hwsim_utils.test_connectivity_p2p(dev[1], dev[2])
317
318    dev[0].remove_group()
319    dev[1].wait_go_ending_session()
320    dev[2].wait_go_ending_session()
321
322def test_grpform_per_sta_psk_wps(dev):
323    """P2P group formation with per-STA PSKs with non-P2P WPS STA"""
324    dev[0].global_request("P2P_SET per_sta_psk 1")
325    [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15, r_dev=dev[1], r_intent=0)
326    check_grpform_results(i_res, r_res)
327
328    dev[0].p2p_go_authorize_client_pbc()
329    dev[2].request("WPS_PBC")
330    dev[2].wait_connected(timeout=30)
331
332    hwsim_utils.test_connectivity_p2p_sta(dev[1], dev[2])
333
334    dev[0].remove_group()
335    dev[2].request("DISCONNECT")
336    dev[1].wait_go_ending_session()
337
338@remote_compatible
339def test_grpform_force_chan_go(dev):
340    """P2P group formation forced channel selection by GO"""
341    [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
342                                           i_freq=2432,
343                                           r_dev=dev[1], r_intent=0,
344                                           test_data=False)
345    check_grpform_results(i_res, r_res)
346    if i_res['freq'] != "2432":
347        raise Exception("Unexpected channel - did not follow GO's forced channel")
348    remove_group(dev[0], dev[1])
349
350@remote_compatible
351def test_grpform_force_chan_cli(dev):
352    """P2P group formation forced channel selection by client"""
353    [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=0,
354                                           i_freq=2417,
355                                           r_dev=dev[1], r_intent=15,
356                                           test_data=False)
357    check_grpform_results(i_res, r_res)
358    if i_res['freq'] != "2417":
359        raise Exception("Unexpected channel - did not follow GO's forced channel")
360    remove_group(dev[0], dev[1])
361
362@remote_compatible
363def test_grpform_force_chan_conflict(dev):
364    """P2P group formation fails due to forced channel mismatch"""
365    go_neg_pin_authorized(i_dev=dev[0], i_intent=0, i_freq=2422,
366                          r_dev=dev[1], r_intent=15, r_freq=2427,
367                          expect_failure=True, i_go_neg_status=7)
368
369@remote_compatible
370def test_grpform_pref_chan_go(dev):
371    """P2P group formation preferred channel selection by GO"""
372    try:
373        dev[0].request("SET p2p_pref_chan 81:7")
374        [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
375                                               r_dev=dev[1], r_intent=0,
376                                               test_data=False)
377        check_grpform_results(i_res, r_res)
378        if i_res['freq'] != "2442":
379            raise Exception("Unexpected channel - did not follow GO's p2p_pref_chan")
380        remove_group(dev[0], dev[1])
381    finally:
382        dev[0].request("SET p2p_pref_chan ")
383
384@remote_compatible
385def test_grpform_pref_chan_go_overridden(dev):
386    """P2P group formation preferred channel selection by GO overridden by client"""
387    try:
388        dev[1].request("SET p2p_pref_chan 81:7")
389        [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=0,
390                                               i_freq=2422,
391                                               r_dev=dev[1], r_intent=15,
392                                               test_data=False)
393        check_grpform_results(i_res, r_res)
394        if i_res['freq'] != "2422":
395            raise Exception("Unexpected channel - did not follow client's forced channel")
396        remove_group(dev[0], dev[1])
397    finally:
398        dev[1].request("SET p2p_pref_chan ")
399
400@remote_compatible
401def test_grpform_no_go_freq_forcing_chan(dev):
402    """P2P group formation with no-GO freq forcing channel"""
403    try:
404        dev[1].request("SET p2p_no_go_freq 100-200,300,4000-6000")
405        [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=0,
406                                               r_dev=dev[1], r_intent=15,
407                                               test_data=False)
408        check_grpform_results(i_res, r_res)
409        if int(i_res['freq']) > 4000:
410            raise Exception("Unexpected channel - did not follow no-GO freq")
411        remove_group(dev[0], dev[1])
412    finally:
413        dev[1].request("SET p2p_no_go_freq ")
414
415@remote_compatible
416def test_grpform_no_go_freq_conflict(dev):
417    """P2P group formation fails due to no-GO range forced by client"""
418    try:
419        dev[1].request("SET p2p_no_go_freq 2000-3000")
420        go_neg_pin_authorized(i_dev=dev[0], i_intent=0, i_freq=2422,
421                              r_dev=dev[1], r_intent=15,
422                              expect_failure=True, i_go_neg_status=7)
423    finally:
424        dev[1].request("SET p2p_no_go_freq ")
425
426@remote_compatible
427def test_grpform_no_5ghz_world_roaming(dev):
428    """P2P group formation with world roaming regulatory"""
429    [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=0,
430                                           r_dev=dev[1], r_intent=15,
431                                           test_data=False)
432    check_grpform_results(i_res, r_res)
433    if int(i_res['freq']) > 4000:
434        raise Exception("Unexpected channel - did not follow world roaming rules")
435    remove_group(dev[0], dev[1])
436
437@remote_compatible
438def test_grpform_no_5ghz_add_cli(dev):
439    """P2P group formation with passive scan 5 GHz and p2p_add_cli_chan=1"""
440    try:
441        dev[0].request("SET p2p_add_cli_chan 1")
442        dev[1].request("SET p2p_add_cli_chan 1")
443        [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=0,
444                                               r_dev=dev[1], r_intent=14,
445                                               test_data=False)
446        check_grpform_results(i_res, r_res)
447        if int(i_res['freq']) > 4000:
448            raise Exception("Unexpected channel - did not follow world roaming rules")
449        remove_group(dev[0], dev[1])
450    finally:
451        dev[0].request("SET p2p_add_cli_chan 0")
452        dev[1].request("SET p2p_add_cli_chan 0")
453
454@remote_compatible
455def test_grpform_no_5ghz_add_cli2(dev):
456    """P2P group formation with passive scan 5 GHz and p2p_add_cli_chan=1 (reverse)"""
457    try:
458        dev[0].request("SET p2p_add_cli_chan 1")
459        dev[1].request("SET p2p_add_cli_chan 1")
460        [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=14,
461                                               r_dev=dev[1], r_intent=0,
462                                               test_data=False)
463        check_grpform_results(i_res, r_res)
464        if int(i_res['freq']) > 4000:
465            raise Exception("Unexpected channel - did not follow world roaming rules")
466        remove_group(dev[0], dev[1])
467    finally:
468        dev[0].request("SET p2p_add_cli_chan 0")
469        dev[1].request("SET p2p_add_cli_chan 0")
470
471@remote_compatible
472def test_grpform_no_5ghz_add_cli3(dev):
473    """P2P group formation with passive scan 5 GHz and p2p_add_cli_chan=1 (intent 15)"""
474    try:
475        dev[0].request("SET p2p_add_cli_chan 1")
476        dev[1].request("SET p2p_add_cli_chan 1")
477        [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=0,
478                                               r_dev=dev[1], r_intent=15,
479                                               test_data=False)
480        check_grpform_results(i_res, r_res)
481        if int(i_res['freq']) > 4000:
482            raise Exception("Unexpected channel - did not follow world roaming rules")
483        remove_group(dev[0], dev[1])
484    finally:
485        dev[0].request("SET p2p_add_cli_chan 0")
486        dev[1].request("SET p2p_add_cli_chan 0")
487
488@remote_compatible
489def test_grpform_no_5ghz_add_cli4(dev):
490    """P2P group formation with passive scan 5 GHz and p2p_add_cli_chan=1 (reverse; intent 15)"""
491    try:
492        dev[0].request("SET p2p_add_cli_chan 1")
493        dev[1].request("SET p2p_add_cli_chan 1")
494        [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
495                                               r_dev=dev[1], r_intent=0,
496                                               test_data=False)
497        check_grpform_results(i_res, r_res)
498        if int(i_res['freq']) > 4000:
499            raise Exception("Unexpected channel - did not follow world roaming rules")
500        remove_group(dev[0], dev[1])
501    finally:
502        dev[0].request("SET p2p_add_cli_chan 0")
503        dev[1].request("SET p2p_add_cli_chan 0")
504
505@remote_compatible
506def test_grpform_incorrect_pin(dev):
507    """P2P GO Negotiation with incorrect PIN"""
508    dev[1].p2p_listen()
509    addr1 = dev[1].p2p_dev_addr()
510    if not dev[0].discover_peer(addr1):
511        raise Exception("Peer not found")
512    res = dev[1].global_request("P2P_CONNECT " + dev[0].p2p_dev_addr() + " pin auth go_intent=0")
513    if "FAIL" in res:
514        raise Exception("P2P_CONNECT failed to generate PIN")
515    logger.info("PIN from P2P_CONNECT: " + res)
516    dev[0].global_request("P2P_CONNECT " + addr1 + " 00000000 enter go_intent=15")
517    ev = dev[0].wait_global_event(["P2P-GO-NEG-SUCCESS"], timeout=15)
518    if ev is None:
519        raise Exception("GO Negotiation did not complete successfully(0)")
520    ev = dev[1].wait_global_event(["P2P-GO-NEG-SUCCESS"], timeout=15)
521    if ev is None:
522        raise Exception("GO Negotiation did not complete successfully(1)")
523    ev = dev[1].wait_global_event(["WPS-FAIL"], timeout=15)
524    if ev is None:
525        raise Exception("WPS failure not reported(1)")
526    if "msg=8 config_error=18" not in ev:
527        raise Exception("Unexpected WPS failure(1): " + ev)
528    ev = dev[0].wait_global_event(["WPS-FAIL"], timeout=15)
529    if ev is None:
530        raise Exception("WPS failure not reported")
531    if "msg=8 config_error=18" not in ev:
532        raise Exception("Unexpected WPS failure: " + ev)
533    ev = dev[1].wait_global_event(["P2P-GROUP-FORMATION-FAILURE"], timeout=10)
534    if ev is None:
535        raise Exception("Group formation failure timed out")
536    ev = dev[0].wait_global_event(["P2P-GROUP-FORMATION-FAILURE"], timeout=5)
537    if ev is None:
538        raise Exception("Group formation failure timed out")
539
540@remote_compatible
541def test_grpform_reject(dev):
542    """User rejecting group formation attempt by a P2P peer"""
543    addr0 = dev[0].p2p_dev_addr()
544    dev[0].p2p_listen()
545    dev[1].p2p_go_neg_init(addr0, None, "pbc")
546    ev = dev[0].wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=15)
547    if ev is None:
548        raise Exception("GO Negotiation timed out")
549    if "OK" in dev[0].global_request("P2P_REJECT foo"):
550        raise Exception("Invalid P2P_REJECT accepted")
551    if "FAIL" in dev[0].global_request("P2P_REJECT " + ev.split(' ')[1]):
552        raise Exception("P2P_REJECT failed")
553    dev[1].request("P2P_STOP_FIND")
554    dev[1].p2p_go_neg_init(addr0, None, "pbc")
555    ev = dev[1].wait_global_event(["P2P-GO-NEG-FAILURE"], timeout=10)
556    if ev is None:
557        raise Exception("Rejection not reported")
558    if "status=11" not in ev:
559        raise Exception("Unexpected status code in rejection")
560
561@remote_compatible
562def test_grpform_pd_no_probe_resp(dev):
563    """GO Negotiation after PD, but no Probe Response"""
564    addr0 = dev[0].p2p_dev_addr()
565    addr1 = dev[1].p2p_dev_addr()
566    dev[0].p2p_listen()
567    if not dev[1].discover_peer(addr0):
568        raise Exception("Peer not found")
569    dev[1].p2p_stop_find()
570    dev[0].p2p_stop_find()
571    peer = dev[0].get_peer(addr1)
572    if peer['listen_freq'] == '0':
573        raise Exception("Peer listen frequency not learned from Probe Request")
574    time.sleep(0.3)
575    dev[0].request("P2P_FLUSH")
576    dev[0].p2p_listen()
577    dev[1].global_request("P2P_PROV_DISC " + addr0 + " display")
578    ev = dev[0].wait_global_event(["P2P-PROV-DISC-SHOW-PIN"], timeout=5)
579    if ev is None:
580        raise Exception("PD Request timed out")
581    ev = dev[1].wait_global_event(["P2P-PROV-DISC-ENTER-PIN"], timeout=5)
582    if ev is None:
583        raise Exception("PD Response timed out")
584    peer = dev[0].get_peer(addr1)
585    if peer['listen_freq'] != '0':
586        raise Exception("Peer listen frequency learned unexpectedly from PD Request")
587
588    pin = dev[0].wps_read_pin()
589    if "FAIL" in dev[1].global_request("P2P_CONNECT " + addr0 + " " + pin + " enter"):
590        raise Exception("P2P_CONNECT on initiator failed")
591    ev = dev[0].wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=5)
592    if ev is None:
593        raise Exception("GO Negotiation start timed out")
594    peer = dev[0].get_peer(addr1)
595    if peer['listen_freq'] == '0':
596        raise Exception("Peer listen frequency not learned from PD followed by GO Neg Req")
597    if "FAIL" in dev[0].global_request("P2P_CONNECT " + addr1 + " " + pin + " display"):
598        raise Exception("P2P_CONNECT on responder failed")
599    ev = dev[0].wait_global_event(["P2P-GROUP-STARTED"], timeout=15)
600    if ev is None:
601        raise Exception("Group formation timed out")
602    ev = dev[1].wait_global_event(["P2P-GROUP-STARTED"], timeout=15)
603    if ev is None:
604        raise Exception("Group formation timed out")
605
606def test_go_neg_two_peers(dev):
607    """P2P GO Negotiation rejected due to already started negotiation with another peer"""
608    addr0 = dev[0].p2p_dev_addr()
609    addr1 = dev[1].p2p_dev_addr()
610    addr2 = dev[2].p2p_dev_addr()
611    dev[1].p2p_listen()
612    dev[2].p2p_listen()
613    if not dev[0].discover_peer(addr1):
614        raise Exception("Could not discover peer")
615    if not dev[0].discover_peer(addr2):
616        raise Exception("Could not discover peer")
617    if "OK" not in dev[0].request("P2P_CONNECT " + addr2 + " pbc auth"):
618        raise Exception("Failed to authorize GO Neg")
619    dev[0].p2p_listen()
620    if not dev[2].discover_peer(addr0):
621        raise Exception("Could not discover peer")
622    if "OK" not in dev[0].request("P2P_CONNECT " + addr1 + " pbc"):
623        raise Exception("Failed to initiate GO Neg")
624    ev = dev[1].wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=5)
625    if ev is None:
626        raise Exception("timeout on GO Neg RX event")
627    dev[2].request("P2P_CONNECT " + addr0 + " pbc")
628    ev = dev[2].wait_global_event(["P2P-GO-NEG-FAILURE"], timeout=10)
629    if ev is None:
630        raise Exception("Rejection not reported")
631    if "status=5" not in ev:
632        raise Exception("Unexpected status code in rejection: " + ev)
633
634def clear_pbc_overlap(dev, ap):
635    hostapd.remove_bss(ap)
636    dev[0].request("P2P_CANCEL")
637    dev[1].request("P2P_CANCEL")
638    dev[0].p2p_stop_find()
639    dev[1].p2p_stop_find()
640    remove_group(dev[0], dev[1], allow_failure=True)
641    dev[0].dump_monitor()
642    dev[1].dump_monitor()
643    time.sleep(0.1)
644    dev[0].flush_scan_cache()
645    dev[1].flush_scan_cache()
646    time.sleep(0.1)
647
648@remote_compatible
649def test_grpform_pbc_overlap(dev, apdev):
650    """P2P group formation during PBC overlap"""
651    params = {"ssid": "wps", "eap_server": "1", "wps_state": "1"}
652    hapd = hostapd.add_ap(apdev[0], params)
653    hapd.request("WPS_PBC")
654    time.sleep(0.1)
655
656    # Since P2P Client scan case is now optimized to use a specific SSID, the
657    # WPS AP will not reply to that and the scan after GO Negotiation can quite
658    # likely miss the AP due to dwell time being short enough to miss the Beacon
659    # frame. This has made the test case somewhat pointless, but keep it here
660    # for now with an additional scan to confirm that PBC detection works if
661    # there is a BSS entry for a overlapping AP.
662    for i in range(0, 5):
663        dev[0].scan(freq="2412")
664        if dev[0].get_bss(apdev[0]['bssid']) is not None:
665            break
666
667    addr0 = dev[0].p2p_dev_addr()
668    addr1 = dev[1].p2p_dev_addr()
669    dev[0].p2p_listen()
670    if not dev[1].discover_peer(addr0):
671        raise Exception("Could not discover peer")
672    dev[1].p2p_listen()
673    if not dev[0].discover_peer(addr1):
674        raise Exception("Could not discover peer")
675    dev[0].p2p_listen()
676    if "OK" not in dev[0].global_request("P2P_CONNECT " + addr1 + " pbc auth go_intent=0"):
677        raise Exception("Failed to authorize GO Neg")
678    if "OK" not in dev[1].global_request("P2P_CONNECT " + addr0 + " pbc go_intent=15 freq=2412"):
679        raise Exception("Failed to initiate GO Neg")
680    ev = dev[0].wait_global_event(["WPS-OVERLAP-DETECTED",
681                                   "P2P-GROUP-FORMATION-SUCCESS"], timeout=15)
682    clear_pbc_overlap(dev, apdev[0])
683    if ev is None or "P2P-GROUP-FORMATION-SUCCESS" not in ev:
684        raise Exception("P2P group formation did not complete")
685
686@remote_compatible
687def test_grpform_pbc_overlap_group_iface(dev, apdev):
688    """P2P group formation during PBC overlap using group interfaces"""
689    # Note: Need to include P2P IE from the AP to get the P2P interface BSS
690    # update use this information.
691    params = {"ssid": "wps", "eap_server": "1", "wps_state": "1",
692              "beacon_int": "15", 'manage_p2p': '1'}
693    hapd = hostapd.add_ap(apdev[0], params)
694    hapd.request("WPS_PBC")
695
696    dev[0].request("SET p2p_no_group_iface 0")
697    dev[1].request("SET p2p_no_group_iface 0")
698
699    addr0 = dev[0].p2p_dev_addr()
700    addr1 = dev[1].p2p_dev_addr()
701    dev[0].p2p_listen()
702    if not dev[1].discover_peer(addr0):
703        raise Exception("Could not discover peer")
704    dev[1].p2p_listen()
705    if not dev[0].discover_peer(addr1):
706        raise Exception("Could not discover peer")
707    dev[0].p2p_stop_find()
708    dev[0].scan(freq="2412")
709    dev[0].p2p_listen()
710    if "OK" not in dev[0].global_request("P2P_CONNECT " + addr1 + " pbc auth go_intent=0"):
711        raise Exception("Failed to authorize GO Neg")
712    if "OK" not in dev[1].global_request("P2P_CONNECT " + addr0 + " pbc go_intent=15 freq=2412"):
713        raise Exception("Failed to initiate GO Neg")
714    ev = dev[0].wait_global_event(["WPS-OVERLAP-DETECTED",
715                                   "P2P-GROUP-FORMATION-SUCCESS"], timeout=15)
716    clear_pbc_overlap(dev, apdev[0])
717    if ev is None or "P2P-GROUP-FORMATION-SUCCESS" not in ev:
718        raise Exception("P2P group formation did not complete")
719
720@remote_compatible
721def test_grpform_goneg_fail_with_group_iface(dev):
722    """P2P group formation fails while using group interface"""
723    dev[0].request("SET p2p_no_group_iface 0")
724    dev[1].p2p_listen()
725    peer = dev[1].p2p_dev_addr()
726    if not dev[0].discover_peer(peer):
727        raise Exception("Peer " + peer + " not found")
728    if "OK" not in dev[1].request("P2P_REJECT " + dev[0].p2p_dev_addr()):
729        raise Exception("P2P_REJECT failed")
730    if "OK" not in dev[0].request("P2P_CONNECT " + peer + " pbc"):
731        raise Exception("P2P_CONNECT failed")
732    ev = dev[0].wait_global_event(["P2P-GO-NEG-FAILURE"], timeout=10)
733    if ev is None:
734        raise Exception("GO Negotiation failure timed out")
735
736@long_duration_test
737def test_grpform_cred_ready_timeout(dev):
738    """P2P GO Negotiation wait for credentials to become ready"""
739    dev[1].p2p_listen()
740    addr1 = dev[1].p2p_dev_addr()
741    if not dev[0].discover_peer(addr1):
742        raise Exception("Peer " + addr1 + " not found")
743    if not dev[2].discover_peer(addr1):
744        raise Exception("Peer " + addr1 + " not found(2)")
745
746    start = os.times()[4]
747
748    cmd = "P2P_CONNECT " + addr1 + " 12345670 display"
749    if "OK" not in dev[0].global_request(cmd):
750        raise Exception("Failed to initiate GO Neg")
751
752    if "OK" not in dev[2].global_request(cmd):
753        raise Exception("Failed to initiate GO Neg(2)")
754
755    # First, check with p2p_find
756    ev = dev[2].wait_global_event(["P2P-GO-NEG-FAILURE"], timeout=30)
757    if ev is not None:
758        raise Exception("Too early GO Negotiation timeout reported(2)")
759    dev[2].dump_monitor()
760    logger.info("Starting p2p_find to change state")
761    dev[2].p2p_find()
762    for i in range(10):
763        ev = dev[2].wait_global_event(["P2P-GO-NEG-FAILURE"], timeout=10)
764        if ev:
765            break
766        dev[2].dump_monitor(global_mon=False)
767    if ev is None:
768        raise Exception("GO Negotiation failure timed out(2)")
769    dev[2].dump_monitor()
770    end = os.times()[4]
771    logger.info("GO Negotiation wait time: {} seconds(2)".format(end - start))
772    if end - start < 120:
773        raise Exception("Too short GO Negotiation wait time(2): {}".format(end - start))
774
775    wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
776    wpas.interface_add("wlan5")
777
778    wpas.p2p_listen()
779    ev = dev[2].wait_global_event(["P2P-DEVICE-FOUND"], timeout=10)
780    if ev is None:
781        raise Exception("Did not discover new device after GO Negotiation failure")
782    if wpas.p2p_dev_addr() not in ev:
783        raise Exception("Unexpected device found: " + ev)
784    dev[2].p2p_stop_find()
785    dev[2].dump_monitor()
786    wpas.p2p_stop_find()
787    wpas.close_monitor()
788    del wpas
789
790    # Finally, verify without p2p_find
791    ev = dev[0].wait_global_event(["P2P-GO-NEG-FAILURE"], timeout=120)
792    if ev is None:
793        raise Exception("GO Negotiation failure timed out")
794    end = os.times()[4]
795    logger.info("GO Negotiation wait time: {} seconds".format(end - start))
796    if end - start < 120:
797        raise Exception("Too short GO Negotiation wait time: {}".format(end - start))
798
799def test_grpform_no_wsc_done(dev):
800    """P2P group formation with WSC-Done not sent"""
801    addr0 = dev[0].p2p_dev_addr()
802    addr1 = dev[1].p2p_dev_addr()
803
804    for i in range(0, 2):
805        dev[0].request("SET ext_eapol_frame_io 1")
806        dev[1].request("SET ext_eapol_frame_io 1")
807        dev[0].p2p_listen()
808        dev[1].p2p_go_neg_auth(addr0, "12345670", "display", 0)
809        dev[1].p2p_listen()
810        dev[0].p2p_go_neg_init(addr1, "12345670", "enter", timeout=20,
811                               go_intent=15, wait_group=False)
812
813        mode = None
814        while True:
815            ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
816            if ev is None:
817                raise Exception("Timeout on EAPOL-TX from GO")
818            if not mode:
819                mode = dev[0].get_status_field("mode")
820            res = dev[1].request("EAPOL_RX " + addr0 + " " + ev.split(' ')[2])
821            if "OK" not in res:
822                raise Exception("EAPOL_RX failed")
823            ev = dev[1].wait_event(["EAPOL-TX"], timeout=15)
824            if ev is None:
825                raise Exception("Timeout on EAPOL-TX from P2P Client")
826            msg = ev.split(' ')[2]
827            if msg[46:56] == "102200010f":
828                logger.info("Drop WSC_Done")
829                dev[0].request("SET ext_eapol_frame_io 0")
830                dev[1].request("SET ext_eapol_frame_io 0")
831                # Fake EAP-Failure to complete session on the client
832                id = msg[10:12]
833                dev[1].request("EAPOL_RX " + addr0 + " 0300000404" + id + "0004")
834                break
835            res = dev[0].request("EAPOL_RX " + addr1 + " " + msg)
836            if "OK" not in res:
837                raise Exception("EAPOL_RX failed")
838
839        ev = dev[0].wait_global_event(["P2P-GROUP-STARTED"], timeout=15)
840        if ev is None:
841            raise Exception("Group formation timed out on GO")
842        ev = dev[1].wait_global_event(["P2P-GROUP-STARTED"], timeout=15)
843        if ev is None:
844            raise Exception("Group formation timed out on P2P Client")
845        dev[0].remove_group()
846        dev[1].wait_go_ending_session()
847
848        if mode != "P2P GO - group formation":
849            raise Exception("Unexpected mode on GO during group formation: " + mode)
850
851@remote_compatible
852def test_grpform_wait_peer(dev):
853    """P2P group formation wait for peer to become ready"""
854    addr0 = dev[0].p2p_dev_addr()
855    addr1 = dev[1].p2p_dev_addr()
856    dev[1].p2p_listen()
857    if not dev[0].discover_peer(addr1):
858        raise Exception("Peer " + addr1 + " not found")
859    dev[0].request("SET extra_roc_dur 500")
860    if "OK" not in dev[0].request("P2P_CONNECT " + addr1 + " 12345670 display go_intent=15"):
861        raise Exception("Failed to initiate GO Neg")
862    time.sleep(3)
863    dev[1].request("P2P_CONNECT " + addr0 + " 12345670 enter go_intent=0")
864
865    ev = dev[0].wait_global_event(["P2P-GROUP-STARTED"], timeout=15)
866    if ev is None:
867        raise Exception("Group formation timed out")
868    dev[0].group_form_result(ev)
869
870    dev[0].request("SET extra_roc_dur 0")
871    ev = dev[1].wait_global_event(["P2P-GROUP-STARTED"], timeout=15)
872    if ev is None:
873        raise Exception("Group formation timed out")
874    dev[0].remove_group()
875
876@remote_compatible
877def test_invalid_p2p_connect_command(dev):
878    """P2P_CONNECT error cases"""
879    id = dev[0].add_network()
880    for cmd in ["foo",
881                "00:11:22:33:44:55",
882                "00:11:22:33:44:55 pbc persistent=123",
883                "00:11:22:33:44:55 pbc persistent=%d" % id,
884                "00:11:22:33:44:55 pbc go_intent=-1",
885                "00:11:22:33:44:55 pbc go_intent=16",
886                "00:11:22:33:44:55 pin",
887                "00:11:22:33:44:55 pbc freq=0"]:
888        if "FAIL" not in dev[0].request("P2P_CONNECT " + cmd):
889            raise Exception("Invalid P2P_CONNECT command accepted: " + cmd)
890
891    if "FAIL-INVALID-PIN" not in dev[0].request("P2P_CONNECT 00:11:22:33:44:55 1234567"):
892        raise Exception("Invalid PIN was not rejected")
893    if "FAIL-INVALID-PIN" not in dev[0].request("P2P_CONNECT 00:11:22:33:44:55 12345678a"):
894        raise Exception("Invalid PIN was not rejected")
895
896    if "FAIL-CHANNEL-UNSUPPORTED" not in dev[0].request("P2P_CONNECT 00:11:22:33:44:55 pin freq=3000"):
897        raise Exception("Unsupported channel not reported")
898
899@remote_compatible
900def test_p2p_unauthorize(dev):
901    """P2P_UNAUTHORIZE to unauthorize a peer"""
902    if "FAIL" not in dev[0].request("P2P_UNAUTHORIZE foo"):
903        raise Exception("Invalid P2P_UNAUTHORIZE accepted")
904    if "FAIL" not in dev[0].request("P2P_UNAUTHORIZE 00:11:22:33:44:55"):
905        raise Exception("P2P_UNAUTHORIZE for unknown peer accepted")
906
907    addr0 = dev[0].p2p_dev_addr()
908    addr1 = dev[1].p2p_dev_addr()
909    dev[1].p2p_listen()
910    pin = dev[0].wps_read_pin()
911    dev[0].p2p_go_neg_auth(addr1, pin, "display")
912    dev[0].p2p_listen()
913    if "OK" not in dev[0].request("P2P_UNAUTHORIZE " + addr1):
914        raise Exception("P2P_UNAUTHORIZE failed")
915    dev[1].p2p_go_neg_init(addr0, pin, "keypad", timeout=0)
916    ev = dev[0].wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=10)
917    if ev is None:
918        raise Exception("No GO Negotiation Request RX reported")
919
920@remote_compatible
921def test_grpform_pbc_multiple(dev):
922    """P2P group formation using PBC multiple times in a row"""
923    try:
924        dev[1].request("SET passive_scan 1")
925        for i in range(5):
926            [i_res, r_res] = go_neg_pbc_authorized(i_dev=dev[0], i_intent=15,
927                                                   r_dev=dev[1], r_intent=0)
928            remove_group(dev[0], dev[1])
929    finally:
930        dev[1].request("SET passive_scan 0")
931        dev[1].flush_scan_cache()
932
933def test_grpform_not_ready(dev):
934    """Not ready for GO Negotiation (listen)"""
935    addr0 = dev[0].p2p_dev_addr()
936    addr2 = dev[2].p2p_dev_addr()
937    dev[0].p2p_listen()
938    if not dev[1].discover_peer(addr0):
939        raise Exception("Could not discover peer")
940    dev[1].global_request("P2P_CONNECT " + addr0 + " pbc")
941    ev = dev[0].wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=5)
942    if ev is None:
943        raise Exception("No P2P-GO-NEG-REQUEST event")
944    dev[0].dump_monitor()
945    time.sleep(5)
946    if not dev[2].discover_peer(addr0):
947        raise Exception("Could not discover peer(2)")
948    for i in range(3):
949        dev[i].p2p_stop_find()
950
951def test_grpform_not_ready2(dev):
952    """Not ready for GO Negotiation (search)"""
953    addr0 = dev[0].p2p_dev_addr()
954    addr2 = dev[2].p2p_dev_addr()
955    dev[0].p2p_find(social=True)
956    if not dev[1].discover_peer(addr0):
957        raise Exception("Could not discover peer")
958    dev[1].global_request("P2P_CONNECT " + addr0 + " pbc")
959    ev = dev[0].wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=5)
960    if ev is None:
961        raise Exception("No P2P-GO-NEG-REQUEST event")
962    dev[0].dump_monitor()
963    time.sleep(1)
964    dev[2].p2p_listen()
965    ev = dev[0].wait_global_event(["P2P-DEVICE-FOUND"], timeout=10)
966    if ev is None:
967        raise Exception("Peer not discovered after GO Neg Resp(status=1) TX")
968    if addr2 not in ev:
969        raise Exception("Unexpected peer discovered: " + ev)
970    for i in range(3):
971        dev[i].p2p_stop_find()
972
973@remote_compatible
974def test_grpform_and_scan(dev):
975    """GO Negotiation and scan operations"""
976    addr0 = dev[0].p2p_dev_addr()
977    addr1 = dev[1].p2p_dev_addr()
978    dev[1].p2p_listen()
979    if not dev[0].discover_peer(addr1):
980        raise Exception("Could not discover peer")
981    dev[0].p2p_stop_find()
982    dev[1].p2p_stop_find()
983
984    if "OK" not in dev[0].request("SCAN TYPE=ONLY freq=2412-2472"):
985        raise Exception("Could not start scan")
986    ev = dev[0].wait_event(["CTRL-EVENT-SCAN-STARTED"], timeout=5)
987    if ev is None:
988        raise Exception("Scan did not start")
989    time.sleep(0.1)
990    # Request PD while the previously started scan is still in progress
991    if "OK" not in dev[0].request("P2P_PROV_DISC %s pbc" % addr1):
992        raise Exception("Could not request PD")
993    ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
994    if ev is None:
995        raise Exception("Scan did not complete")
996    time.sleep(0.3)
997
998    dev[1].p2p_listen()
999    ev = dev[0].wait_global_event(["P2P-PROV-DISC-PBC-RESP"], timeout=5)
1000    if ev is None:
1001        raise Exception("PD Response not received")
1002
1003    if "OK" not in dev[0].request("SCAN TYPE=ONLY freq=2412-2472"):
1004        raise Exception("Could not start scan")
1005    ev = dev[0].wait_event(["CTRL-EVENT-SCAN-STARTED"], timeout=5)
1006    if ev is None:
1007        raise Exception("Scan did not start")
1008    time.sleep(0.1)
1009    # Request GO Neg while the previously started scan is still in progress
1010    if "OK" not in dev[0].request("P2P_CONNECT %s pbc" % addr1):
1011        raise Exception("Could not request GO Negotiation")
1012    ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
1013    if ev is None:
1014        raise Exception("Scan did not complete")
1015
1016    ev = dev[1].wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=10)
1017    if ev is None:
1018        raise Exception("GO Neg Req RX not reported")
1019
1020    dev[1].p2p_stop_find()
1021
1022    if "OK" not in dev[1].request("SCAN TYPE=ONLY freq=2412-2472"):
1023        raise Exception("Could not start scan")
1024    ev = dev[1].wait_event(["CTRL-EVENT-SCAN-STARTED"], timeout=5)
1025    if ev is None:
1026        raise Exception("Scan did not start")
1027    time.sleep(0.1)
1028    dev[1].global_request("P2P_CONNECT " + addr0 + " pbc")
1029    ev = dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
1030    if ev is None:
1031        raise Exception("Scan did not complete")
1032
1033    ev0 = dev[0].wait_global_event(["P2P-GROUP-STARTED"], timeout=15)
1034    if ev0 is None:
1035        raise Exception("Group formation timed out on dev0")
1036    dev[0].group_form_result(ev0)
1037
1038    ev1 = dev[1].wait_global_event(["P2P-GROUP-STARTED"], timeout=15)
1039    if ev1 is None:
1040        raise Exception("Group formation timed out on dev1")
1041    dev[1].group_form_result(ev1)
1042
1043    dev[0].dump_monitor()
1044    dev[1].dump_monitor()
1045
1046    remove_group(dev[0], dev[1])
1047
1048    dev[0].dump_monitor()
1049    dev[1].dump_monitor()
1050
1051def test_grpform_go_neg_dup_on_restart(dev):
1052    """Duplicated GO Negotiation Request after GO Neg restart"""
1053    if dev[0].p2p_dev_addr() > dev[1].p2p_dev_addr():
1054        higher = dev[0]
1055        lower = dev[1]
1056    else:
1057        higher = dev[1]
1058        lower = dev[0]
1059    addr_low = lower.p2p_dev_addr()
1060    addr_high = higher.p2p_dev_addr()
1061    higher.p2p_listen()
1062    if not lower.discover_peer(addr_high):
1063        raise Exception("Could not discover peer")
1064    lower.p2p_stop_find()
1065
1066    if "OK" not in lower.request("P2P_CONNECT %s pbc" % addr_high):
1067        raise Exception("Could not request GO Negotiation")
1068    ev = higher.wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=10)
1069    if ev is None:
1070        raise Exception("GO Neg Req RX not reported")
1071
1072    # Wait for GO Negotiation Response (Status=1) to go through
1073    time.sleep(0.2)
1074
1075    if "FAIL" in lower.request("SET ext_mgmt_frame_handling 1"):
1076        raise Exception("Failed to enable external management frame handling")
1077
1078    higher.p2p_stop_find()
1079    higher.global_request("P2P_CONNECT " + addr_low + " pbc")
1080
1081    # Wait for the GO Negotiation Request frame of the restarted GO Negotiation
1082    rx_msg = lower.mgmt_rx()
1083    if rx_msg is None:
1084        raise Exception("MGMT-RX timeout")
1085    p2p = parse_p2p_public_action(rx_msg['payload'])
1086    if p2p is None:
1087        raise Exception("Not a P2P Public Action frame")
1088    if p2p['subtype'] != 0:
1089        raise Exception("Unexpected P2P Public Action subtype %d" % p2p['subtype'])
1090
1091    # Send duplicate GO Negotiation Request from the prior instance of GO
1092    # Negotiation
1093    lower.p2p_stop_find()
1094    peer = higher.get_peer(addr_low)
1095
1096    msg = p2p_hdr(addr_high, addr_low, type=P2P_GO_NEG_REQ, dialog_token=123)
1097    attrs = p2p_attr_capability(dev_capab=0x25, group_capab=0x08)
1098    attrs += p2p_attr_go_intent(go_intent=7, tie_breaker=1)
1099    attrs += p2p_attr_config_timeout()
1100    attrs += p2p_attr_listen_channel(chan=(int(peer['listen_freq']) - 2407) // 5)
1101    attrs += p2p_attr_intended_interface_addr(lower.p2p_dev_addr())
1102    attrs += p2p_attr_channel_list()
1103    attrs += p2p_attr_device_info(addr_low, config_methods=0x80, name="Device A")
1104    attrs += p2p_attr_operating_channel()
1105    wsc_attrs = struct.pack(">HHH", 0x1012, 2, 4)
1106    msg['payload'] += ie_p2p(attrs) + ie_wsc(wsc_attrs)
1107    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()))
1108
1109    # Wait for the GO Negotiation Response frame which would have been sent in
1110    # this case previously, but not anymore after the check for
1111    # dev->go_neg_req_sent and dev->flags & P2P_DEV_PEER_WAITING_RESPONSE.
1112    rx_msg = lower.mgmt_rx(timeout=0.2)
1113    if rx_msg is not None:
1114        raise Exception("Unexpected management frame")
1115
1116    if "FAIL" in lower.request("SET ext_mgmt_frame_handling 0"):
1117        raise Exception("Failed to disable external management frame handling")
1118    lower.p2p_listen()
1119
1120    ev = lower.wait_global_event(["P2P-GO-NEG-SUCCESS"], timeout=10)
1121    if ev is None:
1122        raise Exception("GO Negotiation did not succeed on dev0")
1123
1124    ev = higher.wait_global_event(["P2P-GO-NEG-SUCCESS"], timeout=10)
1125    if ev is None:
1126        raise Exception("GO Negotiation did not succeed on dev1")
1127
1128    ev0 = lower.wait_global_event(["P2P-GROUP-STARTED"], timeout=15)
1129    if ev0 is None:
1130        raise Exception("Group formation timed out on dev0")
1131    lower.group_form_result(ev0)
1132
1133    ev1 = higher.wait_global_event(["P2P-GROUP-STARTED"], timeout=15)
1134    if ev1 is None:
1135        raise Exception("Group formation timed out on dev1")
1136    higher.group_form_result(ev1)
1137
1138    lower.dump_monitor()
1139    higher.dump_monitor()
1140
1141    remove_group(lower, higher)
1142
1143    lower.dump_monitor()
1144    higher.dump_monitor()
1145
1146@remote_compatible
1147def test_grpform_go_neg_stopped(dev):
1148    """GO Negotiation stopped after TX start"""
1149    addr0 = dev[0].p2p_dev_addr()
1150    dev[0].p2p_listen()
1151    if not dev[1].discover_peer(addr0):
1152        raise Exception("Could not discover peer")
1153    dev[0].p2p_stop_find()
1154    if "OK" not in dev[1].request("P2P_CONNECT %s pbc" % addr0):
1155        raise Exception("Could not request GO Negotiation")
1156    dev[1].p2p_stop_find()
1157    dev[1].p2p_listen()
1158    dev[0].p2p_find(social=True)
1159    ev = dev[0].wait_global_event(["P2P-DEVICE-FOUND"], timeout=1.2)
1160    dev[0].p2p_stop_find()
1161    dev[1].p2p_stop_find()
1162    if ev is None:
1163        raise Exception("Did not find peer quickly enough after stopped P2P_CONNECT")
1164
1165def test_grpform_random_addr(dev):
1166    """P2P group formation with random interface addresses"""
1167    dev[0].global_request("SET p2p_no_group_iface 0")
1168    dev[1].global_request("SET p2p_no_group_iface 0")
1169    try:
1170        if "OK" not in dev[0].global_request("SET p2p_interface_random_mac_addr 1"):
1171            raise Exception("Failed to set p2p_interface_random_mac_addr")
1172        if "OK" not in dev[1].global_request("SET p2p_interface_random_mac_addr 1"):
1173            raise Exception("Failed to set p2p_interface_random_mac_addr")
1174        [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
1175                                               r_dev=dev[1], r_intent=0)
1176        if "p2p-wlan" not in i_res['ifname']:
1177            raise Exception("Unexpected group interface name")
1178        check_grpform_results(i_res, r_res)
1179        hwsim_utils.test_connectivity_p2p(dev[0], dev[1])
1180        remove_group(dev[0], dev[1])
1181        if i_res['ifname'] in get_ifnames():
1182            raise Exception("Group interface netdev was not removed")
1183    finally:
1184        dev[0].global_request("SET p2p_interface_random_mac_addr 0")
1185        dev[1].global_request("SET p2p_interface_random_mac_addr 0")
1186