tests: P2P group formation using PBC multiple times in a row
[mech_eap.git] / tests / hwsim / test_p2p_grpform.py
1 # P2P group formation test cases
2 # Copyright (c) 2013-2014, Jouni Malinen <j@w1.fi>
3 #
4 # This software may be distributed under the terms of the BSD license.
5 # See README for more details.
6
7 import logging
8 logger = logging.getLogger()
9 import time
10 import threading
11 import Queue
12 import os
13
14 import hostapd
15 import hwsim_utils
16 import utils
17 from utils import HwsimSkip
18 from wpasupplicant import WpaSupplicant
19
20 def check_grpform_results(i_res, r_res):
21     if i_res['result'] != 'success' or r_res['result'] != 'success':
22         raise Exception("Failed group formation")
23     if i_res['ssid'] != r_res['ssid']:
24         raise Exception("SSID mismatch")
25     if i_res['freq'] != r_res['freq']:
26         raise Exception("freq mismatch")
27     if 'go_neg_freq' in r_res and i_res['go_neg_freq'] != r_res['go_neg_freq']:
28         raise Exception("go_neg_freq mismatch")
29     if i_res['freq'] != i_res['go_neg_freq']:
30         raise Exception("freq/go_neg_freq mismatch")
31     if i_res['role'] != i_res['go_neg_role']:
32         raise Exception("role/go_neg_role mismatch")
33     if 'go_neg_role' in r_res and r_res['role'] != r_res['go_neg_role']:
34         raise Exception("role/go_neg_role mismatch")
35     if i_res['go_dev_addr'] != r_res['go_dev_addr']:
36         raise Exception("GO Device Address mismatch")
37
38 def go_neg_init(i_dev, r_dev, pin, i_method, i_intent, res):
39     logger.debug("Initiate GO Negotiation from i_dev")
40     try:
41         i_res = i_dev.p2p_go_neg_init(r_dev.p2p_dev_addr(), pin, i_method, timeout=20, go_intent=i_intent)
42         logger.debug("i_res: " + str(i_res))
43     except Exception, e:
44         i_res = None
45         logger.info("go_neg_init thread caught an exception from p2p_go_neg_init: " + str(e))
46     res.put(i_res)
47
48 def go_neg_pin(i_dev, r_dev, i_intent=None, r_intent=None, i_method='enter', r_method='display'):
49     r_dev.p2p_listen()
50     i_dev.p2p_listen()
51     pin = r_dev.wps_read_pin()
52     logger.info("Start GO negotiation " + i_dev.ifname + " -> " + r_dev.ifname)
53     r_dev.dump_monitor()
54     res = Queue.Queue()
55     t = threading.Thread(target=go_neg_init, args=(i_dev, r_dev, pin, i_method, i_intent, res))
56     t.start()
57     logger.debug("Wait for GO Negotiation Request on r_dev")
58     ev = r_dev.wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=15)
59     if ev is None:
60         raise Exception("GO Negotiation timed out")
61     r_dev.dump_monitor()
62     logger.debug("Re-initiate GO Negotiation from r_dev")
63     r_res = r_dev.p2p_go_neg_init(i_dev.p2p_dev_addr(), pin, r_method, go_intent=r_intent, timeout=20)
64     logger.debug("r_res: " + str(r_res))
65     r_dev.dump_monitor()
66     t.join()
67     i_res = res.get()
68     if i_res is None:
69         raise Exception("go_neg_init thread failed")
70     logger.debug("i_res: " + str(i_res))
71     logger.info("Group formed")
72     hwsim_utils.test_connectivity_p2p(r_dev, i_dev)
73     i_dev.dump_monitor()
74     return [i_res, r_res]
75
76 def go_neg_pin_authorized(i_dev, r_dev, i_intent=None, r_intent=None, expect_failure=False, i_go_neg_status=None, i_method='enter', r_method='display', test_data=True, i_freq=None, r_freq=None):
77     i_dev.p2p_listen()
78     pin = r_dev.wps_read_pin()
79     logger.info("Start GO negotiation " + i_dev.ifname + " -> " + r_dev.ifname)
80     r_dev.p2p_go_neg_auth(i_dev.p2p_dev_addr(), pin, r_method, go_intent=r_intent, freq=r_freq)
81     r_dev.p2p_listen()
82     i_res = i_dev.p2p_go_neg_init(r_dev.p2p_dev_addr(), pin, i_method, timeout=20, go_intent=i_intent, expect_failure=expect_failure, freq=i_freq)
83     r_res = r_dev.p2p_go_neg_auth_result(expect_failure=expect_failure)
84     logger.debug("i_res: " + str(i_res))
85     logger.debug("r_res: " + str(r_res))
86     r_dev.dump_monitor()
87     i_dev.dump_monitor()
88     if i_go_neg_status:
89         if i_res['result'] != 'go-neg-failed':
90             raise Exception("Expected GO Negotiation failure not reported")
91         if i_res['status'] != i_go_neg_status:
92             raise Exception("Expected GO Negotiation status not seen")
93     if expect_failure:
94         return
95     logger.info("Group formed")
96     if test_data:
97         hwsim_utils.test_connectivity_p2p(r_dev, i_dev)
98     return [i_res, r_res]
99
100 def go_neg_init_pbc(i_dev, r_dev, i_intent, res, freq, provdisc):
101     logger.debug("Initiate GO Negotiation from i_dev")
102     try:
103         i_res = i_dev.p2p_go_neg_init(r_dev.p2p_dev_addr(), None, "pbc",
104                                       timeout=20, go_intent=i_intent, freq=freq,
105                                       provdisc=provdisc)
106         logger.debug("i_res: " + str(i_res))
107     except Exception, e:
108         i_res = None
109         logger.info("go_neg_init_pbc thread caught an exception from p2p_go_neg_init: " + str(e))
110     res.put(i_res)
111
112 def go_neg_pbc(i_dev, r_dev, i_intent=None, r_intent=None, i_freq=None, r_freq=None, provdisc=False, r_listen=False):
113     if r_listen:
114         r_dev.p2p_listen()
115     else:
116         r_dev.p2p_find(social=True)
117     i_dev.p2p_find(social=True)
118     logger.info("Start GO negotiation " + i_dev.ifname + " -> " + r_dev.ifname)
119     r_dev.dump_monitor()
120     res = Queue.Queue()
121     t = threading.Thread(target=go_neg_init_pbc, args=(i_dev, r_dev, i_intent, res, i_freq, provdisc))
122     t.start()
123     logger.debug("Wait for GO Negotiation Request on r_dev")
124     ev = r_dev.wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=15)
125     if ev is None:
126         raise Exception("GO Negotiation timed out")
127     r_dev.dump_monitor()
128     # Allow some time for the GO Neg Resp to go out before initializing new
129     # GO Negotiation.
130     time.sleep(0.2)
131     logger.debug("Re-initiate GO Negotiation from r_dev")
132     r_res = r_dev.p2p_go_neg_init(i_dev.p2p_dev_addr(), None, "pbc",
133                                   go_intent=r_intent, timeout=20, freq=r_freq)
134     logger.debug("r_res: " + str(r_res))
135     r_dev.dump_monitor()
136     t.join()
137     i_res = res.get()
138     if i_res is None:
139         raise Exception("go_neg_init_pbc thread failed")
140     logger.debug("i_res: " + str(i_res))
141     logger.info("Group formed")
142     hwsim_utils.test_connectivity_p2p(r_dev, i_dev)
143     i_dev.dump_monitor()
144     return [i_res, r_res]
145
146 def go_neg_pbc_authorized(i_dev, r_dev, i_intent=None, r_intent=None,
147                           expect_failure=False, i_freq=None, r_freq=None):
148     i_dev.p2p_listen()
149     logger.info("Start GO negotiation " + i_dev.ifname + " -> " + r_dev.ifname)
150     r_dev.p2p_go_neg_auth(i_dev.p2p_dev_addr(), None, "pbc",
151                           go_intent=r_intent, freq=r_freq)
152     r_dev.p2p_listen()
153     i_res = i_dev.p2p_go_neg_init(r_dev.p2p_dev_addr(), None, "pbc", timeout=20,
154                                   go_intent=i_intent,
155                                   expect_failure=expect_failure, freq=i_freq)
156     r_res = r_dev.p2p_go_neg_auth_result(expect_failure=expect_failure)
157     logger.debug("i_res: " + str(i_res))
158     logger.debug("r_res: " + str(r_res))
159     r_dev.dump_monitor()
160     i_dev.dump_monitor()
161     if expect_failure:
162         return
163     logger.info("Group formed")
164     return [i_res, r_res]
165
166 def remove_group(dev1, dev2):
167     dev1.remove_group()
168     try:
169         dev2.remove_group()
170     except:
171         pass
172
173 def test_grpform(dev):
174     """P2P group formation using PIN and authorized connection (init -> GO)"""
175     try:
176         dev[0].request("SET p2p_group_idle 2")
177         [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
178                                                r_dev=dev[1], r_intent=0)
179         check_grpform_results(i_res, r_res)
180         dev[1].remove_group()
181         ev = dev[0].wait_global_event(["P2P-GROUP-REMOVED"], timeout=10)
182         if ev is None:
183             raise Exception("GO did not remove group on idle timeout")
184         if "GO reason=IDLE" not in ev:
185             raise Exception("Unexpected group removal event: " + ev)
186     finally:
187         dev[0].request("SET p2p_group_idle 0")
188
189 def test_grpform_a(dev):
190     """P2P group formation using PIN and authorized connection (init -> GO) (init: group iface)"""
191     dev[0].request("SET p2p_no_group_iface 0")
192     [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
193                                            r_dev=dev[1], r_intent=0)
194     if "p2p-wlan" not in i_res['ifname']:
195         raise Exception("Unexpected group interface name")
196     check_grpform_results(i_res, r_res)
197     remove_group(dev[0], dev[1])
198     if i_res['ifname'] in utils.get_ifnames():
199         raise Exception("Group interface netdev was not removed")
200
201 def test_grpform_b(dev):
202     """P2P group formation using PIN and authorized connection (init -> GO) (resp: group iface)"""
203     dev[1].request("SET p2p_no_group_iface 0")
204     [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
205                                            r_dev=dev[1], r_intent=0)
206     if "p2p-wlan" not in r_res['ifname']:
207         raise Exception("Unexpected group interface name")
208     check_grpform_results(i_res, r_res)
209     remove_group(dev[0], dev[1])
210     if r_res['ifname'] in utils.get_ifnames():
211         raise Exception("Group interface netdev was not removed")
212
213 def test_grpform_c(dev):
214     """P2P group formation using PIN and authorized connection (init -> GO) (group iface)"""
215     dev[0].request("SET p2p_no_group_iface 0")
216     dev[1].request("SET p2p_no_group_iface 0")
217     [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
218                                            r_dev=dev[1], r_intent=0)
219     if "p2p-wlan" not in i_res['ifname']:
220         raise Exception("Unexpected group interface name")
221     if "p2p-wlan" not in r_res['ifname']:
222         raise Exception("Unexpected group interface name")
223     check_grpform_results(i_res, r_res)
224     remove_group(dev[0], dev[1])
225     if i_res['ifname'] in utils.get_ifnames():
226         raise Exception("Group interface netdev was not removed")
227     if r_res['ifname'] in utils.get_ifnames():
228         raise Exception("Group interface netdev was not removed")
229
230 def test_grpform2(dev):
231     """P2P group formation using PIN and authorized connection (resp -> GO)"""
232     go_neg_pin_authorized(i_dev=dev[0], i_intent=0, r_dev=dev[1], r_intent=15)
233     remove_group(dev[0], dev[1])
234
235 def test_grpform2_c(dev):
236     """P2P group formation using PIN and authorized connection (resp -> GO) (group iface)"""
237     dev[0].request("SET p2p_no_group_iface 0")
238     dev[1].request("SET p2p_no_group_iface 0")
239     [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=0, r_dev=dev[1], r_intent=15)
240     remove_group(dev[0], dev[1])
241     if i_res['ifname'] in utils.get_ifnames():
242         raise Exception("Group interface netdev was not removed")
243     if r_res['ifname'] in utils.get_ifnames():
244         raise Exception("Group interface netdev was not removed")
245
246 def test_grpform3(dev):
247     """P2P group formation using PIN and re-init GO Negotiation"""
248     go_neg_pin(i_dev=dev[0], i_intent=15, r_dev=dev[1], r_intent=0)
249     remove_group(dev[0], dev[1])
250
251 def test_grpform3_c(dev):
252     """P2P group formation using PIN and re-init GO Negotiation (group iface)"""
253     dev[0].request("SET p2p_no_group_iface 0")
254     dev[1].request("SET p2p_no_group_iface 0")
255     [i_res, r_res] = go_neg_pin(i_dev=dev[0], i_intent=15, r_dev=dev[1], r_intent=0)
256     remove_group(dev[0], dev[1])
257     if i_res['ifname'] in utils.get_ifnames():
258         raise Exception("Group interface netdev was not removed")
259     if r_res['ifname'] in utils.get_ifnames():
260         raise Exception("Group interface netdev was not removed")
261
262 def test_grpform_pbc(dev):
263     """P2P group formation using PBC and re-init GO Negotiation"""
264     [i_res, r_res] = go_neg_pbc(i_dev=dev[0], i_intent=15, r_dev=dev[1], r_intent=0)
265     check_grpform_results(i_res, r_res)
266     if i_res['role'] != 'GO' or r_res['role'] != 'client':
267         raise Exception("Unexpected device roles")
268     remove_group(dev[0], dev[1])
269
270 def test_grpform_pd(dev):
271     """P2P group formation with PD-before-GO-Neg workaround"""
272     [i_res, r_res] = go_neg_pbc(i_dev=dev[0], provdisc=True, r_dev=dev[1], r_listen=True)
273     check_grpform_results(i_res, r_res)
274     remove_group(dev[0], dev[1])
275
276 def test_grpform_ext_listen(dev):
277     """P2P group formation with extended listen timing enabled"""
278     try:
279         if "FAIL" not in dev[0].global_request("P2P_EXT_LISTEN 100"):
280             raise Exception("Invalid P2P_EXT_LISTEN accepted")
281         if "OK" not in dev[0].global_request("P2P_EXT_LISTEN 100 50000"):
282             raise Exception("Failed to set extended listen timing")
283         if "OK" not in dev[1].global_request("P2P_EXT_LISTEN 200 40000"):
284             raise Exception("Failed to set extended listen timing")
285         [i_res, r_res] = go_neg_pbc(i_dev=dev[0], provdisc=True, r_dev=dev[1], r_listen=True)
286         check_grpform_results(i_res, r_res)
287         peer1 = dev[0].get_peer(dev[1].p2p_dev_addr())
288         if peer1['ext_listen_interval'] != "40000":
289             raise Exception("Extended listen interval not discovered correctly")
290         if peer1['ext_listen_period'] != "200":
291             raise Exception("Extended listen period not discovered correctly")
292         peer0 = dev[1].get_peer(dev[0].p2p_dev_addr())
293         if peer0['ext_listen_interval'] != "50000":
294             raise Exception("Extended listen interval not discovered correctly")
295         if peer0['ext_listen_period'] != "100":
296             raise Exception("Extended listen period not discovered correctly")
297         remove_group(dev[0], dev[1])
298     finally:
299         if "OK" not in dev[0].global_request("P2P_EXT_LISTEN"):
300             raise Exception("Failed to clear extended listen timing")
301         if "OK" not in dev[1].global_request("P2P_EXT_LISTEN"):
302             raise Exception("Failed to clear extended listen timing")
303
304 def test_both_go_intent_15(dev):
305     """P2P GO Negotiation with both devices using GO intent 15"""
306     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)
307
308 def test_both_go_neg_display(dev):
309     """P2P GO Negotiation with both devices trying to display PIN"""
310     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')
311
312 def test_both_go_neg_enter(dev):
313     """P2P GO Negotiation with both devices trying to enter PIN"""
314     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')
315
316 def test_go_neg_pbc_vs_pin(dev):
317     """P2P GO Negotiation with one device using PBC and the other PIN"""
318     addr0 = dev[0].p2p_dev_addr()
319     addr1 = dev[1].p2p_dev_addr()
320     dev[1].p2p_listen()
321     if not dev[0].discover_peer(addr1):
322         raise Exception("Could not discover peer")
323     dev[0].p2p_listen()
324     if "OK" not in dev[0].request("P2P_CONNECT " + addr1 + " pbc auth"):
325         raise Exception("Failed to authorize GO Neg")
326     if not dev[1].discover_peer(addr0):
327         raise Exception("Could not discover peer")
328     if "OK" not in dev[1].request("P2P_CONNECT " + addr0 + " 12345670 display"):
329         raise Exception("Failed to initiate GO Neg")
330     ev = dev[1].wait_global_event(["P2P-GO-NEG-FAILURE"], timeout=10)
331     if ev is None:
332         raise Exception("GO Negotiation failure timed out")
333     if "status=10" not in ev:
334         raise Exception("Unexpected failure reason: " + ev)
335
336 def test_go_neg_pin_vs_pbc(dev):
337     """P2P GO Negotiation with one device using PIN and the other PBC"""
338     addr0 = dev[0].p2p_dev_addr()
339     addr1 = dev[1].p2p_dev_addr()
340     dev[1].p2p_listen()
341     if not dev[0].discover_peer(addr1):
342         raise Exception("Could not discover peer")
343     dev[0].p2p_listen()
344     if "OK" not in dev[0].request("P2P_CONNECT " + addr1 + " 12345670 display auth"):
345         raise Exception("Failed to authorize GO Neg")
346     if not dev[1].discover_peer(addr0):
347         raise Exception("Could not discover peer")
348     if "OK" not in dev[1].request("P2P_CONNECT " + addr0 + " pbc"):
349         raise Exception("Failed to initiate GO Neg")
350     ev = dev[1].wait_global_event(["P2P-GO-NEG-FAILURE"], timeout=10)
351     if ev is None:
352         raise Exception("GO Negotiation failure timed out")
353     if "status=10" not in ev:
354         raise Exception("Unexpected failure reason: " + ev)
355
356 def test_grpform_per_sta_psk(dev):
357     """P2P group formation with per-STA PSKs"""
358     dev[0].request("P2P_SET per_sta_psk 1")
359     [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15, r_dev=dev[1], r_intent=0)
360     check_grpform_results(i_res, r_res)
361
362     pin = dev[2].wps_read_pin()
363     dev[0].p2p_go_authorize_client(pin)
364     c_res = dev[2].p2p_connect_group(dev[0].p2p_dev_addr(), pin, timeout=60)
365     check_grpform_results(i_res, c_res)
366
367     if r_res['psk'] == c_res['psk']:
368         raise Exception("Same PSK assigned for both clients")
369
370     hwsim_utils.test_connectivity_p2p(dev[1], dev[2])
371
372     dev[0].remove_group()
373     dev[1].wait_go_ending_session()
374     dev[2].wait_go_ending_session()
375
376 def test_grpform_per_sta_psk_wps(dev):
377     """P2P group formation with per-STA PSKs with non-P2P WPS STA"""
378     dev[0].request("P2P_SET per_sta_psk 1")
379     [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15, r_dev=dev[1], r_intent=0)
380     check_grpform_results(i_res, r_res)
381
382     dev[0].p2p_go_authorize_client_pbc()
383     dev[2].request("WPS_PBC")
384     dev[2].wait_connected(timeout=30)
385
386     hwsim_utils.test_connectivity_p2p_sta(dev[1], dev[2])
387
388     dev[0].remove_group()
389     dev[2].request("DISCONNECT")
390     dev[1].wait_go_ending_session()
391
392 def test_grpform_force_chan_go(dev):
393     """P2P group formation forced channel selection by GO"""
394     [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
395                                            i_freq=2432,
396                                            r_dev=dev[1], r_intent=0,
397                                            test_data=False)
398     check_grpform_results(i_res, r_res)
399     if i_res['freq'] != "2432":
400         raise Exception("Unexpected channel - did not follow GO's forced channel")
401     remove_group(dev[0], dev[1])
402
403 def test_grpform_force_chan_cli(dev):
404     """P2P group formation forced channel selection by client"""
405     [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=0,
406                                            i_freq=2417,
407                                            r_dev=dev[1], r_intent=15,
408                                            test_data=False)
409     check_grpform_results(i_res, r_res)
410     if i_res['freq'] != "2417":
411         raise Exception("Unexpected channel - did not follow GO's forced channel")
412     remove_group(dev[0], dev[1])
413
414 def test_grpform_force_chan_conflict(dev):
415     """P2P group formation fails due to forced channel mismatch"""
416     go_neg_pin_authorized(i_dev=dev[0], i_intent=0, i_freq=2422,
417                           r_dev=dev[1], r_intent=15, r_freq=2427,
418                           expect_failure=True, i_go_neg_status=7)
419
420 def test_grpform_pref_chan_go(dev):
421     """P2P group formation preferred channel selection by GO"""
422     dev[0].request("SET p2p_pref_chan 81:7")
423     [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
424                                            r_dev=dev[1], r_intent=0,
425                                            test_data=False)
426     check_grpform_results(i_res, r_res)
427     if i_res['freq'] != "2442":
428         raise Exception("Unexpected channel - did not follow GO's p2p_pref_chan")
429     remove_group(dev[0], dev[1])
430
431 def test_grpform_pref_chan_go_overridden(dev):
432     """P2P group formation preferred channel selection by GO overridden by client"""
433     dev[1].request("SET p2p_pref_chan 81:7")
434     [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=0,
435                                            i_freq=2422,
436                                            r_dev=dev[1], r_intent=15,
437                                            test_data=False)
438     check_grpform_results(i_res, r_res)
439     if i_res['freq'] != "2422":
440         raise Exception("Unexpected channel - did not follow client's forced channel")
441     remove_group(dev[0], dev[1])
442
443 def test_grpform_no_go_freq_forcing_chan(dev):
444     """P2P group formation with no-GO freq forcing channel"""
445     dev[1].request("SET p2p_no_go_freq 100-200,300,4000-6000")
446     [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=0,
447                                            r_dev=dev[1], r_intent=15,
448                                            test_data=False)
449     check_grpform_results(i_res, r_res)
450     if int(i_res['freq']) > 4000:
451         raise Exception("Unexpected channel - did not follow no-GO freq")
452     remove_group(dev[0], dev[1])
453
454 def test_grpform_no_go_freq_conflict(dev):
455     """P2P group formation fails due to no-GO range forced by client"""
456     dev[1].request("SET p2p_no_go_freq 2000-3000")
457     go_neg_pin_authorized(i_dev=dev[0], i_intent=0, i_freq=2422,
458                           r_dev=dev[1], r_intent=15,
459                           expect_failure=True, i_go_neg_status=7)
460
461 def test_grpform_no_5ghz_world_roaming(dev):
462     """P2P group formation with world roaming regulatory"""
463     [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=0,
464                                            r_dev=dev[1], r_intent=15,
465                                            test_data=False)
466     check_grpform_results(i_res, r_res)
467     if int(i_res['freq']) > 4000:
468         raise Exception("Unexpected channel - did not follow world roaming rules")
469     remove_group(dev[0], dev[1])
470
471 def test_grpform_no_5ghz_add_cli(dev):
472     """P2P group formation with passive scan 5 GHz and p2p_add_cli_chan=1"""
473     dev[0].request("SET p2p_add_cli_chan 1")
474     dev[1].request("SET p2p_add_cli_chan 1")
475     [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=0,
476                                            r_dev=dev[1], r_intent=14,
477                                            test_data=False)
478     check_grpform_results(i_res, r_res)
479     if int(i_res['freq']) > 4000:
480         raise Exception("Unexpected channel - did not follow world roaming rules")
481     remove_group(dev[0], dev[1])
482
483 def test_grpform_no_5ghz_add_cli2(dev):
484     """P2P group formation with passive scan 5 GHz and p2p_add_cli_chan=1 (reverse)"""
485     dev[0].request("SET p2p_add_cli_chan 1")
486     dev[1].request("SET p2p_add_cli_chan 1")
487     [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=14,
488                                            r_dev=dev[1], r_intent=0,
489                                            test_data=False)
490     check_grpform_results(i_res, r_res)
491     if int(i_res['freq']) > 4000:
492         raise Exception("Unexpected channel - did not follow world roaming rules")
493     remove_group(dev[0], dev[1])
494
495 def test_grpform_no_5ghz_add_cli3(dev):
496     """P2P group formation with passive scan 5 GHz and p2p_add_cli_chan=1 (intent 15)"""
497     dev[0].request("SET p2p_add_cli_chan 1")
498     dev[1].request("SET p2p_add_cli_chan 1")
499     [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=0,
500                                            r_dev=dev[1], r_intent=15,
501                                            test_data=False)
502     check_grpform_results(i_res, r_res)
503     if int(i_res['freq']) > 4000:
504         raise Exception("Unexpected channel - did not follow world roaming rules")
505     remove_group(dev[0], dev[1])
506
507 def test_grpform_no_5ghz_add_cli4(dev):
508     """P2P group formation with passive scan 5 GHz and p2p_add_cli_chan=1 (reverse; intent 15)"""
509     dev[0].request("SET p2p_add_cli_chan 1")
510     dev[1].request("SET p2p_add_cli_chan 1")
511     [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
512                                            r_dev=dev[1], r_intent=0,
513                                            test_data=False)
514     check_grpform_results(i_res, r_res)
515     if int(i_res['freq']) > 4000:
516         raise Exception("Unexpected channel - did not follow world roaming rules")
517     remove_group(dev[0], dev[1])
518
519 def test_grpform_incorrect_pin(dev):
520     """P2P GO Negotiation with incorrect PIN"""
521     dev[1].p2p_listen()
522     addr1 = dev[1].p2p_dev_addr()
523     if not dev[0].discover_peer(addr1):
524         raise Exception("Peer not found")
525     res = dev[1].request("P2P_CONNECT " + dev[0].p2p_dev_addr() + " pin auth go_intent=0")
526     if "FAIL" in res:
527         raise Exception("P2P_CONNECT failed to generate PIN")
528     logger.info("PIN from P2P_CONNECT: " + res)
529     dev[0].request("P2P_CONNECT " + addr1 + " 00000000 enter go_intent=15")
530     ev = dev[0].wait_global_event(["P2P-GO-NEG-SUCCESS"], timeout=15)
531     if ev is None:
532         raise Exception("GO Negotiation did not complete successfully(0)")
533     ev = dev[1].wait_global_event(["P2P-GO-NEG-SUCCESS"], timeout=15)
534     if ev is None:
535         raise Exception("GO Negotiation did not complete successfully(1)")
536     ev = dev[1].wait_event(["WPS-FAIL"], timeout=15)
537     if ev is None:
538         raise Exception("WPS failure not reported(1)")
539     if "msg=8 config_error=18" not in ev:
540         raise Exception("Unexpected WPS failure(1): " + ev)
541     ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
542     if ev is None:
543         raise Exception("WPS failure not reported")
544     if "msg=8 config_error=18" not in ev:
545         raise Exception("Unexpected WPS failure: " + ev)
546     ev = dev[1].wait_event(["P2P-GROUP-FORMATION-FAILURE"], timeout=10)
547     if ev is None:
548         raise Exception("Group formation failure timed out")
549     ev = dev[0].wait_event(["P2P-GROUP-FORMATION-FAILURE"], timeout=5)
550     if ev is None:
551         raise Exception("Group formation failure timed out")
552
553 def test_grpform_reject(dev):
554     """User rejecting group formation attempt by a P2P peer"""
555     addr0 = dev[0].p2p_dev_addr()
556     dev[0].p2p_listen()
557     dev[1].p2p_go_neg_init(addr0, None, "pbc")
558     ev = dev[0].wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=15)
559     if ev is None:
560         raise Exception("GO Negotiation timed out")
561     if "OK" in dev[0].global_request("P2P_REJECT foo"):
562         raise Exception("Invalid P2P_REJECT accepted")
563     if "FAIL" in dev[0].global_request("P2P_REJECT " + ev.split(' ')[1]):
564         raise Exception("P2P_REJECT failed")
565     dev[1].request("P2P_STOP_FIND")
566     dev[1].p2p_go_neg_init(addr0, None, "pbc")
567     ev = dev[1].wait_global_event(["GO-NEG-FAILURE"], timeout=10)
568     if ev is None:
569         raise Exception("Rejection not reported")
570     if "status=11" not in ev:
571         raise Exception("Unexpected status code in rejection")
572
573 def test_grpform_pd_no_probe_resp(dev):
574     """GO Negotiation after PD, but no Probe Response"""
575     addr0 = dev[0].p2p_dev_addr()
576     addr1 = dev[1].p2p_dev_addr()
577     dev[0].p2p_listen()
578     if not dev[1].discover_peer(addr0):
579         raise Exception("Peer not found")
580     dev[1].p2p_stop_find()
581     dev[0].p2p_stop_find()
582     peer = dev[0].get_peer(addr1)
583     if peer['listen_freq'] == '0':
584         raise Exception("Peer listen frequency not learned from Probe Request")
585     time.sleep(0.3)
586     dev[0].request("P2P_FLUSH")
587     dev[0].p2p_listen()
588     dev[1].global_request("P2P_PROV_DISC " + addr0 + " display")
589     ev = dev[0].wait_global_event(["P2P-PROV-DISC-SHOW-PIN"], timeout=5)
590     if ev is None:
591         raise Exception("PD Request timed out")
592     ev = dev[1].wait_global_event(["P2P-PROV-DISC-ENTER-PIN"], timeout=5)
593     if ev is None:
594         raise Exception("PD Response timed out")
595     peer = dev[0].get_peer(addr1)
596     if peer['listen_freq'] != '0':
597         raise Exception("Peer listen frequency learned unexpectedly from PD Request")
598
599     pin = dev[0].wps_read_pin()
600     if "FAIL" in dev[1].request("P2P_CONNECT " + addr0 + " " + pin + " enter"):
601         raise Exception("P2P_CONNECT on initiator failed")
602     ev = dev[0].wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=5)
603     if ev is None:
604         raise Exception("GO Negotiation start timed out")
605     peer = dev[0].get_peer(addr1)
606     if peer['listen_freq'] == '0':
607         raise Exception("Peer listen frequency not learned from PD followed by GO Neg Req")
608     if "FAIL" in dev[0].request("P2P_CONNECT " + addr1 + " " + pin + " display"):
609         raise Exception("P2P_CONNECT on responder failed")
610     ev = dev[0].wait_global_event(["P2P-GROUP-STARTED"], timeout=15)
611     if ev is None:
612         raise Exception("Group formation timed out")
613     ev = dev[1].wait_global_event(["P2P-GROUP-STARTED"], timeout=15)
614     if ev is None:
615         raise Exception("Group formation timed out")
616
617 def test_go_neg_two_peers(dev):
618     """P2P GO Negotiation rejected due to already started negotiation with another peer"""
619     addr0 = dev[0].p2p_dev_addr()
620     addr1 = dev[1].p2p_dev_addr()
621     addr2 = dev[2].p2p_dev_addr()
622     dev[1].p2p_listen()
623     dev[2].p2p_listen()
624     if not dev[0].discover_peer(addr1):
625         raise Exception("Could not discover peer")
626     if not dev[0].discover_peer(addr2):
627         raise Exception("Could not discover peer")
628     if "OK" not in dev[0].request("P2P_CONNECT " + addr2 + " pbc auth"):
629         raise Exception("Failed to authorize GO Neg")
630     dev[0].p2p_listen()
631     if not dev[2].discover_peer(addr0):
632         raise Exception("Could not discover peer")
633     if "OK" not in dev[0].request("P2P_CONNECT " + addr1 + " pbc"):
634         raise Exception("Failed to initiate GO Neg")
635     ev = dev[1].wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=5)
636     if ev is None:
637         raise Exception("timeout on GO Neg RX event")
638     dev[2].request("P2P_CONNECT " + addr0 + " pbc")
639     ev = dev[2].wait_global_event(["GO-NEG-FAILURE"], timeout=10)
640     if ev is None:
641         raise Exception("Rejection not reported")
642     if "status=5" not in ev:
643         raise Exception("Unexpected status code in rejection: " + ev)
644
645 def clear_pbc_overlap(dev, ifname):
646     hapd_global = hostapd.HostapdGlobal()
647     hapd_global.remove(ifname)
648     dev[0].request("P2P_CANCEL")
649     dev[1].request("P2P_CANCEL")
650     dev[0].p2p_stop_find()
651     dev[1].p2p_stop_find()
652     dev[0].dump_monitor()
653     dev[1].dump_monitor()
654     time.sleep(0.1)
655     dev[0].flush_scan_cache()
656     dev[1].flush_scan_cache()
657     time.sleep(0.1)
658
659 def test_grpform_pbc_overlap(dev, apdev):
660     """P2P group formation during PBC overlap"""
661     params = { "ssid": "wps", "eap_server": "1", "wps_state": "1" }
662     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
663     hapd.request("WPS_PBC")
664     time.sleep(0.1)
665
666     # Since P2P Client scan case is now optimzied to use a specific SSID, the
667     # WPS AP will not reply to that and the scan after GO Negotiation can quite
668     # likely miss the AP due to dwell time being short enoguh to miss the Beacon
669     # frame. This has made the test case somewhat pointless, but keep it here
670     # for now with an additional scan to confirm that PBC detection works if
671     # there is a BSS entry for a overlapping AP.
672     for i in range(0, 5):
673         dev[0].scan(freq="2412")
674         if dev[0].get_bss(apdev[0]['bssid']) is not None:
675             break
676
677     addr0 = dev[0].p2p_dev_addr()
678     addr1 = dev[1].p2p_dev_addr()
679     dev[0].p2p_listen()
680     if not dev[1].discover_peer(addr0):
681         raise Exception("Could not discover peer")
682     dev[1].p2p_listen()
683     if not dev[0].discover_peer(addr1):
684         raise Exception("Could not discover peer")
685     dev[0].p2p_listen()
686     if "OK" not in dev[0].request("P2P_CONNECT " + addr1 + " pbc auth go_intent=0"):
687         raise Exception("Failed to authorize GO Neg")
688     if "OK" not in dev[1].request("P2P_CONNECT " + addr0 + " pbc go_intent=15 freq=2412"):
689         raise Exception("Failed to initiate GO Neg")
690     ev = dev[0].wait_global_event(["WPS-OVERLAP-DETECTED"], timeout=15)
691     if ev is None:
692         raise Exception("PBC overlap not reported")
693
694     clear_pbc_overlap(dev, apdev[0]['ifname'])
695
696 def test_grpform_pbc_overlap_group_iface(dev, apdev):
697     """P2P group formation during PBC overlap using group interfaces"""
698     # Note: Need to include P2P IE from the AP to get the P2P interface BSS
699     # update use this information.
700     params = { "ssid": "wps", "eap_server": "1", "wps_state": "1",
701                "beacon_int": "15", 'manage_p2p': '1' }
702     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
703     hapd.request("WPS_PBC")
704
705     dev[0].request("SET p2p_no_group_iface 0")
706     dev[1].request("SET p2p_no_group_iface 0")
707
708     addr0 = dev[0].p2p_dev_addr()
709     addr1 = dev[1].p2p_dev_addr()
710     dev[0].p2p_listen()
711     if not dev[1].discover_peer(addr0):
712         raise Exception("Could not discover peer")
713     dev[1].p2p_listen()
714     if not dev[0].discover_peer(addr1):
715         raise Exception("Could not discover peer")
716     dev[0].p2p_stop_find()
717     dev[0].scan(freq="2412")
718     dev[0].p2p_listen()
719     if "OK" not in dev[0].request("P2P_CONNECT " + addr1 + " pbc auth go_intent=0"):
720         raise Exception("Failed to authorize GO Neg")
721     if "OK" not in dev[1].request("P2P_CONNECT " + addr0 + " pbc go_intent=15 freq=2412"):
722         raise Exception("Failed to initiate GO Neg")
723     ev = dev[0].wait_global_event(["WPS-OVERLAP-DETECTED",
724                                    "P2P-GROUP-FORMATION-SUCCESS"], timeout=15)
725     if ev is None or "WPS-OVERLAP-DETECTED" not in ev:
726         # Do not report this as failure since the P2P group formation case
727         # using a separate group interface has limited chances of "seeing" the
728         # overlapping AP due to a per-SSID scan and no prior scan operations on
729         # the group interface.
730         logger.info("PBC overlap not reported")
731
732     clear_pbc_overlap(dev, apdev[0]['ifname'])
733
734 def test_grpform_goneg_fail_with_group_iface(dev):
735     """P2P group formation fails while using group interface"""
736     dev[0].request("SET p2p_no_group_iface 0")
737     dev[1].p2p_listen()
738     peer = dev[1].p2p_dev_addr()
739     if not dev[0].discover_peer(peer):
740         raise Exception("Peer " + peer + " not found")
741     if "OK" not in dev[1].request("P2P_REJECT " + dev[0].p2p_dev_addr()):
742         raise Exception("P2P_REJECT failed")
743     if "OK" not in dev[0].request("P2P_CONNECT " + peer + " pbc"):
744         raise Exception("P2P_CONNECT failed")
745     ev = dev[0].wait_global_event(["P2P-GO-NEG-FAILURE"], timeout=10)
746     if ev is None:
747         raise Exception("GO Negotiation failure timed out")
748
749 def test_grpform_cred_ready_timeout(dev, apdev, params):
750     """P2P GO Negotiation wait for credentials to become ready [long]"""
751     if not params['long']:
752         raise HwsimSkip("Skip test case with long duration due to --long not specified")
753
754     dev[1].p2p_listen()
755     addr1 = dev[1].p2p_dev_addr()
756     if not dev[0].discover_peer(addr1):
757         raise Exception("Peer " + addr1 + " not found")
758     if not dev[2].discover_peer(addr1):
759         raise Exception("Peer " + addr1 + " not found(2)")
760
761     start = os.times()[4]
762
763     cmd = "P2P_CONNECT " + addr1 + " 12345670 display"
764     if "OK" not in dev[0].global_request(cmd):
765         raise Exception("Failed to initiate GO Neg")
766
767     if "OK" not in dev[2].global_request(cmd):
768         raise Exception("Failed to initiate GO Neg(2)")
769
770     # First, check with p2p_find
771     ev = dev[2].wait_global_event(["P2P-GO-NEG-FAILURE"], timeout=30)
772     if ev is not None:
773         raise Exception("Too early GO Negotiation timeout reported(2)")
774     dev[2].dump_monitor()
775     logger.info("Starting p2p_find to change state")
776     dev[2].p2p_find()
777     ev = dev[2].wait_global_event(["P2P-GO-NEG-FAILURE"], timeout=100)
778     if ev is None:
779         raise Exception("GO Negotiation failure timed out(2)")
780     dev[2].dump_monitor()
781     end = os.times()[4]
782     logger.info("GO Negotiation wait time: {} seconds(2)".format(end - start))
783     if end - start < 120:
784         raise Exception("Too short GO Negotiation wait time(2): {}".format(end - start))
785
786     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
787     wpas.interface_add("wlan5")
788
789     wpas.p2p_listen()
790     ev = dev[2].wait_global_event(["P2P-DEVICE-FOUND"], timeout=10)
791     if ev is None:
792         raise Exception("Did not discover new device after GO Negotiation failure")
793     if wpas.p2p_dev_addr() not in ev:
794         raise Exception("Unexpected device found: " + ev)
795     dev[2].p2p_stop_find()
796     wpas.p2p_stop_find()
797
798     # Finally, verify without p2p_find
799     ev = dev[0].wait_global_event(["P2P-GO-NEG-FAILURE"], timeout=120)
800     if ev is None:
801         raise Exception("GO Negotiation failure timed out")
802     end = os.times()[4]
803     logger.info("GO Negotiation wait time: {} seconds".format(end - start))
804     if end - start < 120:
805         raise Exception("Too short GO Negotiation wait time: {}".format(end - start))
806
807 def test_grpform_no_wsc_done(dev):
808     """P2P group formation with WSC-Done not sent"""
809     addr0 = dev[0].p2p_dev_addr()
810     addr1 = dev[1].p2p_dev_addr()
811
812     for i in range(0, 2):
813         dev[0].request("SET ext_eapol_frame_io 1")
814         dev[1].request("SET ext_eapol_frame_io 1")
815         dev[0].p2p_listen()
816         dev[1].p2p_go_neg_auth(addr0, "12345670", "display", 0)
817         dev[1].p2p_listen()
818         dev[0].p2p_go_neg_init(addr1, "12345670", "enter", timeout=20,
819                                go_intent=15, wait_group=False)
820
821         mode = None
822         while True:
823             ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
824             if ev is None:
825                 raise Exception("Timeout on EAPOL-TX from GO")
826             if not mode:
827                 mode = dev[0].get_status_field("mode")
828             res = dev[1].request("EAPOL_RX " + addr0 + " " + ev.split(' ')[2])
829             if "OK" not in res:
830                 raise Exception("EAPOL_RX failed")
831             ev = dev[1].wait_event(["EAPOL-TX"], timeout=15)
832             if ev is None:
833                 raise Exception("Timeout on EAPOL-TX from P2P Client")
834             msg = ev.split(' ')[2]
835             if msg[46:56] == "102200010f":
836                 logger.info("Drop WSC_Done")
837                 dev[0].request("SET ext_eapol_frame_io 0")
838                 dev[1].request("SET ext_eapol_frame_io 0")
839                 # Fake EAP-Failure to complete session on the client
840                 id = msg[10:12]
841                 dev[1].request("EAPOL_RX " + addr0 + " 0300000404" + id + "0004")
842                 break
843             res = dev[0].request("EAPOL_RX " + addr1 + " " + msg)
844             if "OK" not in res:
845                 raise Exception("EAPOL_RX failed")
846
847         ev = dev[0].wait_global_event(["P2P-GROUP-STARTED"], timeout=15)
848         if ev is None:
849             raise Exception("Group formation timed out on GO")
850         ev = dev[1].wait_global_event(["P2P-GROUP-STARTED"], timeout=15)
851         if ev is None:
852             raise Exception("Group formation timed out on P2P Client")
853         dev[0].remove_group()
854
855         if mode != "P2P GO - group formation":
856             raise Exception("Unexpected mode on GO during group formation: " + mode)
857
858 def test_grpform_wait_peer(dev):
859     """P2P group formation wait for peer to become ready"""
860     addr0 = dev[0].p2p_dev_addr()
861     addr1 = dev[1].p2p_dev_addr()
862     dev[1].p2p_listen()
863     if not dev[0].discover_peer(addr1):
864         raise Exception("Peer " + addr1 + " not found")
865     dev[0].request("SET extra_roc_dur 500")
866     if "OK" not in dev[0].request("P2P_CONNECT " + addr1 + " 12345670 display go_intent=15"):
867         raise Exception("Failed to initiate GO Neg")
868     time.sleep(3)
869     dev[1].request("P2P_CONNECT " + addr0 + " 12345670 enter go_intent=0")
870
871     ev = dev[0].wait_global_event(["P2P-GROUP-STARTED"], timeout=15)
872     if ev is None:
873         raise Exception("Group formation timed out")
874     dev[0].request("SET extra_roc_dur 0")
875     ev = dev[1].wait_global_event(["P2P-GROUP-STARTED"], timeout=15)
876     if ev is None:
877         raise Exception("Group formation timed out")
878     dev[0].remove_group()
879
880 def test_invalid_p2p_connect_command(dev):
881     """P2P_CONNECT error cases"""
882     id = dev[0].add_network()
883     for cmd in [ "foo",
884                  "00:11:22:33:44:55",
885                  "00:11:22:33:44:55 pbc persistent=123",
886                  "00:11:22:33:44:55 pbc persistent=%d" % id,
887                  "00:11:22:33:44:55 pbc go_intent=-1",
888                  "00:11:22:33:44:55 pbc go_intent=16",
889                  "00:11:22:33:44:55 pin",
890                  "00:11:22:33:44:55 pbc freq=0" ]:
891         if "FAIL" not in dev[0].request("P2P_CONNECT " + cmd):
892             raise Exception("Invalid P2P_CONNECT command accepted: " + cmd)
893
894     if "FAIL-INVALID-PIN" not in dev[0].request("P2P_CONNECT 00:11:22:33:44:55 1234567"):
895         raise Exception("Invalid PIN was not rejected")
896
897     if "FAIL-CHANNEL-UNSUPPORTED" not in dev[0].request("P2P_CONNECT 00:11:22:33:44:55 pin freq=3000"):
898         raise Exception("Unsupported channel not reported")
899
900 def 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 def test_grpform_pbc_multiple(dev):
921     """P2P group formation using PBC multiple times in a row"""
922     try:
923         dev[1].request("SET passive_scan 1")
924         for i in range(5):
925             [i_res, r_res] = go_neg_pbc_authorized(i_dev=dev[0], i_intent=15,
926                                                    r_dev=dev[1], r_intent=0)
927             remove_group(dev[0], dev[1])
928     finally:
929         dev[1].request("SET passive_scan 0")
930         dev[1].flush_scan_cache()