tests: Move P2P helper functions to a separate file
[mech_eap.git] / tests / hwsim / test_p2p_channel.py
1 # P2P channel selection test cases
2 # Copyright (c) 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 os
10 import subprocess
11 import time
12
13 import hostapd
14 import hwsim_utils
15 from utils import HwsimSkip
16 from tshark import run_tshark
17 from wpasupplicant import WpaSupplicant
18 from hwsim import HWSimRadio
19 from p2p_utils import *
20
21 def set_country(country, dev=None):
22     subprocess.call(['iw', 'reg', 'set', country])
23     time.sleep(0.1)
24     if dev:
25         for i in range(10):
26             ev = dev.wait_global_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=15)
27             if ev is None:
28                 raise Exception("No regdom change event seen")
29             if "type=COUNTRY alpha2=" + country in ev:
30                 return
31         raise Exception("No matching regdom event seen for set_country(%s)" % country)
32
33 def test_p2p_channel_5ghz(dev):
34     """P2P group formation with 5 GHz preference"""
35     try:
36         set_country("US", dev[0])
37         [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
38                                                r_dev=dev[1], r_intent=0,
39                                                test_data=False)
40         check_grpform_results(i_res, r_res)
41         freq = int(i_res['freq'])
42         if freq < 5000:
43             raise Exception("Unexpected channel %d MHz - did not follow 5 GHz preference" % freq)
44         remove_group(dev[0], dev[1])
45     finally:
46         set_country("00")
47         dev[1].flush_scan_cache()
48
49 def test_p2p_channel_5ghz_no_vht(dev):
50     """P2P group formation with 5 GHz preference when VHT channels are disallowed"""
51     try:
52         set_country("US", dev[0])
53         dev[0].request("P2P_SET disallow_freq 5180-5240")
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                                                test_data=False)
57         check_grpform_results(i_res, r_res)
58         freq = int(i_res['freq'])
59         if freq < 5000:
60             raise Exception("Unexpected channel %d MHz - did not follow 5 GHz preference" % freq)
61         remove_group(dev[0], dev[1])
62     finally:
63         set_country("00")
64         dev[0].request("P2P_SET disallow_freq ")
65         dev[1].flush_scan_cache()
66
67 def test_p2p_channel_random_social(dev):
68     """P2P group formation with 5 GHz preference but all 5 GHz channels disabled"""
69     try:
70         set_country("US", dev[0])
71         dev[0].request("SET p2p_oper_channel 11")
72         dev[0].request("P2P_SET disallow_freq 5000-6000,2462")
73         [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
74                                                r_dev=dev[1], r_intent=0,
75                                                test_data=False)
76         check_grpform_results(i_res, r_res)
77         freq = int(i_res['freq'])
78         if freq not in [ 2412, 2437, 2462 ]:
79             raise Exception("Unexpected channel %d MHz - did not pick random social channel" % freq)
80         remove_group(dev[0], dev[1])
81     finally:
82         set_country("00")
83         dev[0].request("P2P_SET disallow_freq ")
84         dev[1].flush_scan_cache()
85
86 def test_p2p_channel_random(dev):
87     """P2P group formation with 5 GHz preference but all 5 GHz channels and all social channels disabled"""
88     try:
89         set_country("US", dev[0])
90         dev[0].request("SET p2p_oper_channel 11")
91         dev[0].request("P2P_SET disallow_freq 5000-6000,2412,2437,2462")
92         [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
93                                                r_dev=dev[1], r_intent=0,
94                                                test_data=False)
95         check_grpform_results(i_res, r_res)
96         freq = int(i_res['freq'])
97         if freq > 2500 or freq in [ 2412, 2437, 2462 ]:
98             raise Exception("Unexpected channel %d MHz" % freq)
99         remove_group(dev[0], dev[1])
100     finally:
101         set_country("00")
102         dev[0].request("P2P_SET disallow_freq ")
103         dev[1].flush_scan_cache()
104
105 def test_p2p_channel_random_social_with_op_class_change(dev, apdev, params):
106     """P2P group formation using random social channel with oper class change needed"""
107     try:
108         set_country("US", dev[0])
109         logger.info("Start group on 5 GHz")
110         [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
111                                                r_dev=dev[1], r_intent=0,
112                                                test_data=False)
113         check_grpform_results(i_res, r_res)
114         freq = int(i_res['freq'])
115         if freq < 5000:
116             raise Exception("Unexpected channel %d MHz - did not pick 5 GHz preference" % freq)
117         remove_group(dev[0], dev[1])
118
119         logger.info("Disable 5 GHz and try to re-start group based on 5 GHz preference")
120         dev[0].request("SET p2p_oper_reg_class 115")
121         dev[0].request("SET p2p_oper_channel 36")
122         dev[0].request("P2P_SET disallow_freq 5000-6000")
123         [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
124                                                r_dev=dev[1], r_intent=0,
125                                                test_data=False)
126         check_grpform_results(i_res, r_res)
127         freq = int(i_res['freq'])
128         if freq not in [ 2412, 2437, 2462 ]:
129             raise Exception("Unexpected channel %d MHz - did not pick random social channel" % freq)
130         remove_group(dev[0], dev[1])
131
132         out = run_tshark(os.path.join(params['logdir'], "hwsim0.pcapng"),
133                          "wifi_p2p.public_action.subtype == 0")
134         if out is not None:
135             last = None
136             for l in out.splitlines():
137                 if "Operating Channel:" not in l:
138                     continue
139                 last = l
140             if last is None:
141                 raise Exception("Could not find GO Negotiation Request")
142             if "Operating Class 81" not in last:
143                 raise Exception("Unexpected operating class: " + last.strip())
144     finally:
145         set_country("00")
146         dev[0].request("P2P_SET disallow_freq ")
147         dev[0].request("SET p2p_oper_reg_class 0")
148         dev[0].request("SET p2p_oper_channel 0")
149         dev[1].flush_scan_cache()
150
151 def test_p2p_channel_avoid(dev):
152     """P2P and avoid frequencies driver event"""
153     try:
154         set_country("US", dev[0])
155         if "OK" not in dev[0].request("DRIVER_EVENT AVOID_FREQUENCIES 5000-6000,2412,2437,2462"):
156             raise Exception("Could not simulate driver event")
157         ev = dev[0].wait_event(["CTRL-EVENT-AVOID-FREQ"], timeout=10)
158         if ev is None:
159             raise Exception("No CTRL-EVENT-AVOID-FREQ event")
160         [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
161                                                r_dev=dev[1], r_intent=0,
162                                                test_data=False)
163         check_grpform_results(i_res, r_res)
164         freq = int(i_res['freq'])
165         if freq > 2500 or freq in [ 2412, 2437, 2462 ]:
166             raise Exception("Unexpected channel %d MHz" % freq)
167
168         if "OK" not in dev[0].request("DRIVER_EVENT AVOID_FREQUENCIES"):
169             raise Exception("Could not simulate driver event(2)")
170         ev = dev[0].wait_event(["CTRL-EVENT-AVOID-FREQ"], timeout=10)
171         if ev is None:
172             raise Exception("No CTRL-EVENT-AVOID-FREQ event")
173         ev = dev[0].wait_group_event(["P2P-REMOVE-AND-REFORM-GROUP",
174                                       "AP-CSA-FINISHED"], timeout=1)
175         if ev is not None:
176             raise Exception("Unexpected + " + ev + " event")
177
178         if "OK" not in dev[0].request("DRIVER_EVENT AVOID_FREQUENCIES " + str(freq)):
179             raise Exception("Could not simulate driver event(3)")
180         ev = dev[0].wait_event(["CTRL-EVENT-AVOID-FREQ"], timeout=10)
181         if ev is None:
182             raise Exception("No CTRL-EVENT-AVOID-FREQ event")
183         ev = dev[0].wait_group_event(["P2P-REMOVE-AND-REFORM-GROUP",
184                                       "AP-CSA-FINISHED"],
185                                      timeout=10)
186         if ev is None:
187             raise Exception("No P2P-REMOVE-AND-REFORM-GROUP or AP-CSA-FINISHED event")
188     finally:
189         set_country("00")
190         dev[0].request("DRIVER_EVENT AVOID_FREQUENCIES")
191         dev[1].flush_scan_cache()
192
193 def test_autogo_following_bss(dev, apdev):
194     """P2P autonomous GO operate on the same channel as station interface"""
195     if dev[0].get_mcc() > 1:
196         logger.info("test mode: MCC")
197
198     dev[0].request("SET p2p_no_group_iface 0")
199
200     channels = { 3 : "2422", 5 : "2432", 9 : "2452" }
201     for key in channels:
202         hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid" : 'ap-test',
203                                                     "channel" : str(key) })
204         dev[0].connect("ap-test", key_mgmt="NONE",
205                        scan_freq=str(channels[key]))
206         res_go = autogo(dev[0])
207         if res_go['freq'] != channels[key]:
208             raise Exception("Group operation channel is not the same as on connected station interface")
209         hwsim_utils.test_connectivity(dev[0], hapd)
210         dev[0].remove_group(res_go['ifname'])
211
212 def test_go_neg_with_bss_connected(dev, apdev):
213     """P2P channel selection: GO negotiation when station interface is connected"""
214
215     dev[0].flush_scan_cache()
216     dev[1].flush_scan_cache()
217     dev[0].request("SET p2p_no_group_iface 0")
218
219     hapd = hostapd.add_ap(apdev[0]['ifname'],
220                           { "ssid": 'bss-2.4ghz', "channel": '5' })
221     dev[0].connect("bss-2.4ghz", key_mgmt="NONE", scan_freq="2432")
222     #dev[0] as GO
223     [i_res, r_res] = go_neg_pbc(i_dev=dev[0], i_intent=10, r_dev=dev[1],
224                                 r_intent=1)
225     check_grpform_results(i_res, r_res)
226     if i_res['role'] != "GO":
227        raise Exception("GO not selected according to go_intent")
228     if i_res['freq'] != "2432":
229        raise Exception("Group formed on a different frequency than BSS")
230     hwsim_utils.test_connectivity(dev[0], hapd)
231     dev[0].remove_group(i_res['ifname'])
232     dev[1].wait_go_ending_session()
233
234     if dev[0].get_mcc() > 1:
235         logger.info("Skip as-client case due to MCC being enabled")
236         return;
237
238     #dev[0] as client
239     [i_res2, r_res2] = go_neg_pbc(i_dev=dev[0], i_intent=1, r_dev=dev[1],
240                                   r_intent=10)
241     check_grpform_results(i_res2, r_res2)
242     if i_res2['role'] != "client":
243        raise Exception("GO not selected according to go_intent")
244     if i_res2['freq'] != "2432":
245        raise Exception("Group formed on a different frequency than BSS")
246     hwsim_utils.test_connectivity(dev[0], hapd)
247     dev[1].remove_group(r_res2['ifname'])
248     dev[0].wait_go_ending_session()
249     dev[0].request("DISCONNECT")
250     hapd.disable()
251     dev[0].flush_scan_cache()
252     dev[1].flush_scan_cache()
253
254 def test_autogo_with_bss_on_disallowed_chan(dev, apdev):
255     """P2P channel selection: Autonomous GO with BSS on a disallowed channel"""
256
257     with HWSimRadio(n_channels=2) as (radio, iface):
258         wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
259         wpas.interface_add(iface)
260
261         wpas.request("SET p2p_no_group_iface 0")
262
263         if wpas.get_mcc() < 2:
264            raise Exception("New radio does not support MCC")
265
266         try:
267             hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid": 'bss-2.4ghz',
268                                                         "channel": '1' })
269             wpas.request("P2P_SET disallow_freq 2412")
270             wpas.connect("bss-2.4ghz", key_mgmt="NONE", scan_freq="2412")
271             res = autogo(wpas)
272             if res['freq'] == "2412":
273                raise Exception("GO set on a disallowed channel")
274             hwsim_utils.test_connectivity(wpas, hapd)
275         finally:
276             wpas.request("P2P_SET disallow_freq ")
277
278 def test_go_neg_with_bss_on_disallowed_chan(dev, apdev):
279     """P2P channel selection: GO negotiation with station interface on a disallowed channel"""
280
281     with HWSimRadio(n_channels=2) as (radio, iface):
282         wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
283         wpas.interface_add(iface)
284
285         wpas.request("SET p2p_no_group_iface 0")
286
287         if wpas.get_mcc() < 2:
288            raise Exception("New radio does not support MCC")
289
290         try:
291             hapd = hostapd.add_ap(apdev[0]['ifname'],
292                                   { "ssid": 'bss-2.4ghz', "channel": '1' })
293             # make sure PBC overlap from old test cases is not maintained
294             dev[1].flush_scan_cache()
295             wpas.connect("bss-2.4ghz", key_mgmt="NONE", scan_freq="2412")
296             wpas.request("P2P_SET disallow_freq 2412")
297
298             #wpas as GO
299             [i_res, r_res] = go_neg_pbc(i_dev=wpas, i_intent=10, r_dev=dev[1],
300                                         r_intent=1)
301             check_grpform_results(i_res, r_res)
302             if i_res['role'] != "GO":
303                raise Exception("GO not selected according to go_intent")
304             if i_res['freq'] == "2412":
305                raise Exception("Group formed on a disallowed channel")
306             hwsim_utils.test_connectivity(wpas, hapd)
307             wpas.remove_group(i_res['ifname'])
308             dev[1].wait_go_ending_session()
309             dev[1].flush_scan_cache()
310
311             wpas.dump_monitor()
312             dev[1].dump_monitor()
313
314             #wpas as client
315             [i_res2, r_res2] = go_neg_pbc(i_dev=wpas, i_intent=1, r_dev=dev[1],
316                                           r_intent=10)
317             check_grpform_results(i_res2, r_res2)
318             if i_res2['role'] != "client":
319                raise Exception("GO not selected according to go_intent")
320             if i_res2['freq'] == "2412":
321                raise Exception("Group formed on a disallowed channel")
322             hwsim_utils.test_connectivity(wpas, hapd)
323             dev[1].remove_group(r_res2['ifname'])
324             wpas.wait_go_ending_session()
325             ev = dev[1].wait_global_event(["P2P-GROUP-REMOVED"], timeout=5)
326             if ev is None:
327                 raise Exception("Group removal not indicated")
328             wpas.request("DISCONNECT")
329             hapd.disable()
330         finally:
331             wpas.request("P2P_SET disallow_freq ")
332
333 def test_autogo_force_diff_channel(dev, apdev):
334     """P2P autonomous GO and station interface operate on different channels"""
335     with HWSimRadio(n_channels=2) as (radio, iface):
336         wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
337         wpas.interface_add(iface)
338
339         if wpas.get_mcc() < 2:
340            raise Exception("New radio does not support MCC")
341
342         wpas.request("SET p2p_no_group_iface 0")
343
344         hapd = hostapd.add_ap(apdev[0]['ifname'],
345                               {"ssid" : 'ap-test', "channel" : '1'})
346         wpas.connect("ap-test", key_mgmt = "NONE", scan_freq = "2412")
347         wpas.dump_monitor()
348         channels = { 2 : 2417, 5 : 2432, 9 : 2452 }
349         for key in channels:
350             res_go = autogo(wpas, channels[key])
351             wpas.dump_monitor()
352             hwsim_utils.test_connectivity(wpas, hapd)
353             if int(res_go['freq']) == 2412:
354                 raise Exception("Group operation channel is: 2412 excepted: " + res_go['freq'])
355             wpas.remove_group(res_go['ifname'])
356             wpas.dump_monitor()
357
358 def test_go_neg_forced_freq_diff_than_bss_freq(dev, apdev):
359     """P2P channel selection: GO negotiation with forced freq different than station interface"""
360     with HWSimRadio(n_channels=2) as (radio, iface):
361         wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
362         wpas.interface_add(iface)
363
364         if wpas.get_mcc() < 2:
365            raise Exception("New radio does not support MCC")
366
367         # Clear possible PBC session overlap from previous test case
368         dev[1].flush_scan_cache()
369
370         wpas.request("SET p2p_no_group_iface 0")
371
372         hapd = hostapd.add_ap(apdev[0]['ifname'],
373                               { "country_code": 'US',
374                                 "ssid": 'bss-5ghz', "hw_mode": 'a',
375                                 "channel": '40' })
376         wpas.connect("bss-5ghz", key_mgmt="NONE", scan_freq="5200")
377
378         # GO and peer force the same freq, different than BSS freq,
379         # wpas to become GO
380         [i_res, r_res] = go_neg_pbc(i_dev=dev[1], i_intent=1, i_freq=5180,
381                                     r_dev=wpas, r_intent=14, r_freq=5180)
382         check_grpform_results(i_res, r_res)
383         if i_res['freq'] != "5180":
384            raise Exception("P2P group formed on unexpected frequency: " + i_res['freq'])
385         if r_res['role'] != "GO":
386            raise Exception("GO not selected according to go_intent")
387         hwsim_utils.test_connectivity(wpas, hapd)
388         wpas.remove_group(r_res['ifname'])
389         dev[1].wait_go_ending_session()
390         dev[1].flush_scan_cache()
391
392         # GO and peer force the same freq, different than BSS freq, wpas to
393         # become client
394         [i_res2, r_res2] = go_neg_pbc(i_dev=dev[1], i_intent=14, i_freq=2422,
395                                       r_dev=wpas, r_intent=1, r_freq=2422)
396         check_grpform_results(i_res2, r_res2)
397         if i_res2['freq'] != "2422":
398            raise Exception("P2P group formed on unexpected frequency: " + i_res2['freq'])
399         if r_res2['role'] != "client":
400            raise Exception("GO not selected according to go_intent")
401         hwsim_utils.test_connectivity(wpas, hapd)
402
403         wpas.request("DISCONNECT")
404         hapd.request("DISABLE")
405         subprocess.call(['iw', 'reg', 'set', '00'])
406         wpas.flush_scan_cache()
407
408 def test_go_pref_chan_bss_on_diff_chan(dev, apdev):
409     """P2P channel selection: Station on different channel than GO configured pref channel"""
410
411     dev[0].request("SET p2p_no_group_iface 0")
412
413     try:
414         hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid": 'bss-2.4ghz',
415                                                     "channel": '1' })
416         dev[0].request("SET p2p_pref_chan 81:2")
417         dev[0].connect("bss-2.4ghz", key_mgmt="NONE", scan_freq="2412")
418         res = autogo(dev[0])
419         if res['freq'] != "2412":
420            raise Exception("GO channel did not follow BSS")
421         hwsim_utils.test_connectivity(dev[0], hapd)
422     finally:
423         dev[0].request("SET p2p_pref_chan ")
424
425 def test_go_pref_chan_bss_on_disallowed_chan(dev, apdev):
426     """P2P channel selection: Station interface on different channel than GO configured pref channel, and station channel is disallowed"""
427     with HWSimRadio(n_channels=2) as (radio, iface):
428         wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
429         wpas.interface_add(iface)
430
431         if wpas.get_mcc() < 2:
432            raise Exception("New radio does not support MCC")
433
434         wpas.request("SET p2p_no_group_iface 0")
435
436         try:
437             hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid": 'bss-2.4ghz',
438                                                         "channel": '1' })
439             wpas.request("P2P_SET disallow_freq 2412")
440             wpas.request("SET p2p_pref_chan 81:2")
441             wpas.connect("bss-2.4ghz", key_mgmt="NONE", scan_freq="2412")
442             res2 = autogo(wpas)
443             if res2['freq'] != "2417":
444                raise Exception("GO channel did not follow pref_chan configuration")
445             hwsim_utils.test_connectivity(wpas, hapd)
446         finally:
447             wpas.request("P2P_SET disallow_freq ")
448             wpas.request("SET p2p_pref_chan ")
449
450 def test_no_go_freq(dev, apdev):
451     """P2P channel selection: no GO freq"""
452     try:
453        dev[0].request("SET p2p_no_go_freq 2412")
454        # dev[0] as client, channel 1 is ok
455        [i_res, r_res] = go_neg_pbc(i_dev=dev[0], i_intent=1,
456                                    r_dev=dev[1], r_intent=14, r_freq=2412)
457        check_grpform_results(i_res, r_res)
458        if i_res['freq'] != "2412":
459           raise Exception("P2P group not formed on forced freq")
460
461        dev[1].remove_group(r_res['ifname'])
462        dev[0].wait_go_ending_session()
463        dev[0].flush_scan_cache()
464
465        fail = False
466        # dev[0] as GO, channel 1 is not allowed
467        try:
468           dev[0].request("SET p2p_no_go_freq 2412")
469           [i_res2, r_res2] = go_neg_pbc(i_dev=dev[0], i_intent=14,
470                                         r_dev=dev[1], r_intent=1, r_freq=2412)
471           check_grpform_results(i_res2, r_res2)
472           fail = True
473        except:
474            pass
475        if fail:
476            raise Exception("GO set on a disallowed freq")
477     finally:
478        dev[0].request("SET p2p_no_go_freq ")
479
480 def test_go_neg_peers_force_diff_freq(dev, apdev):
481     """P2P channel selection when peers for different frequency"""
482     try:
483        [i_res2, r_res2] = go_neg_pbc(i_dev=dev[0], i_intent=14, i_freq=5180,
484                                      r_dev=dev[1], r_intent=0, r_freq=5200)
485     except Exception, e:
486         return
487     raise Exception("Unexpected group formation success")
488
489 def test_autogo_random_channel(dev, apdev):
490     """P2P channel selection: GO instantiated on random channel 1, 6, 11"""
491     freqs = []
492     go_freqs = ["2412", "2437", "2462"]
493     for i in range(0, 20):
494         result = autogo(dev[0])
495         if result['freq'] not in go_freqs:
496            raise Exception("Unexpected frequency selected: " + result['freq'])
497         if result['freq'] not in freqs:
498             freqs.append(result['freq'])
499         if len(freqs) == 3:
500             break
501         dev[0].remove_group(result['ifname'])
502     if i == 20:
503        raise Exception("GO created 20 times and not all social channels were selected. freqs not selected: " + str(list(set(go_freqs) - set(freqs))))
504
505 def test_p2p_autogo_pref_chan_disallowed(dev, apdev):
506     """P2P channel selection: GO preferred channels are disallowed"""
507     try:
508        dev[0].request("SET p2p_pref_chan 81:1,81:3,81:6,81:9,81:11")
509        dev[0].request("P2P_SET disallow_freq 2412,2422,2437,2452,2462")
510        for i in range(0, 5):
511            res = autogo(dev[0])
512            if res['freq'] in [ "2412", "2422", "2437", "2452", "2462" ]:
513                raise Exception("GO channel is disallowed")
514            dev[0].remove_group(res['ifname'])
515     finally:
516        dev[0].request("P2P_SET disallow_freq ")
517        dev[0].request("SET p2p_pref_chan ")
518
519 def test_p2p_autogo_pref_chan_not_in_regulatory(dev, apdev):
520     """P2P channel selection: GO preferred channel not allowed in the regulatory rules"""
521     try:
522         set_country("US", dev[0])
523         dev[0].request("SET p2p_pref_chan 124:149")
524         res = autogo(dev[0], persistent=True)
525         if res['freq'] != "5745":
526             raise Exception("Unexpected channel selected: " + res['freq'])
527         dev[0].remove_group(res['ifname'])
528
529         netw = dev[0].list_networks(p2p=True)
530         if len(netw) != 1:
531             raise Exception("Unexpected number of network blocks: " + str(netw))
532         id = netw[0]['id']
533
534         set_country("DE", dev[0])
535         res = autogo(dev[0], persistent=id)
536         if res['freq'] == "5745":
537             raise Exception("Unexpected channel selected(2): " + res['freq'])
538         dev[0].remove_group(res['ifname'])
539     finally:
540         dev[0].request("SET p2p_pref_chan ")
541         set_country("00")
542
543 def run_autogo(dev, param):
544     if "OK" not in dev.global_request("P2P_GROUP_ADD " + param):
545         raise Exception("P2P_GROUP_ADD failed: " + param)
546     ev = dev.wait_global_event(["P2P-GROUP-STARTED"], timeout=10)
547     if ev is None:
548         raise Exception("GO start up timed out")
549     res = dev.group_form_result(ev)
550     dev.remove_group()
551     return res
552
553 def _test_autogo_ht_vht(dev):
554     res = run_autogo(dev[0], "ht40")
555
556     res = run_autogo(dev[0], "vht")
557
558     res = run_autogo(dev[0], "freq=2")
559     freq = int(res['freq'])
560     if freq < 2412 or freq > 2462:
561         raise Exception("Unexpected freq=2 channel: " + str(freq))
562
563     res = run_autogo(dev[0], "freq=5")
564     freq = int(res['freq'])
565     if freq < 5000 or freq >= 6000:
566         raise Exception("Unexpected freq=5 channel: " + str(freq))
567
568     res = run_autogo(dev[0], "freq=5 ht40 vht")
569     logger.info(str(res))
570     freq = int(res['freq'])
571     if freq < 5000 or freq >= 6000:
572         raise Exception("Unexpected freq=5 ht40 vht channel: " + str(freq))
573
574 def test_autogo_ht_vht(dev):
575     """P2P autonomous GO with HT/VHT parameters"""
576     try:
577         set_country("US", dev[0])
578         _test_autogo_ht_vht(dev)
579     finally:
580         set_country("00")
581
582 def test_p2p_listen_chan_optimize(dev, apdev):
583     """P2P listen channel optimization"""
584     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
585     wpas.interface_add("wlan5")
586     addr5 = wpas.p2p_dev_addr()
587     try:
588         if "OK" not in wpas.request("SET p2p_optimize_listen_chan 1"):
589             raise Exception("Failed to set p2p_optimize_listen_chan")
590         wpas.p2p_listen()
591         if not dev[0].discover_peer(addr5):
592             raise Exception("Could not discover peer")
593         peer = dev[0].get_peer(addr5)
594         lfreq = peer['listen_freq']
595         wpas.p2p_stop_find()
596         dev[0].p2p_stop_find()
597
598         channel = "1" if lfreq != '2412' else "6"
599         freq = "2412" if lfreq != '2412' else "2437"
600         params = { "ssid": "test-open", "channel": channel }
601         hapd = hostapd.add_ap(apdev[0]['ifname'], params)
602
603         id = wpas.connect("test-open", key_mgmt="NONE", scan_freq=freq)
604         wpas.p2p_listen()
605
606         if "OK" not in dev[0].request("P2P_FLUSH"):
607             raise Exception("P2P_FLUSH failed")
608         if not dev[0].discover_peer(addr5):
609             raise Exception("Could not discover peer")
610         peer = dev[0].get_peer(addr5)
611         lfreq2 = peer['listen_freq']
612         if lfreq == lfreq2:
613             raise Exception("Listen channel did not change")
614         if lfreq2 != freq:
615             raise Exception("Listen channel not on AP's operating channel")
616         wpas.p2p_stop_find()
617         dev[0].p2p_stop_find()
618
619         wpas.request("DISCONNECT")
620         wpas.wait_disconnected()
621
622         # for larger coverage, cover case of current channel matching
623         wpas.select_network(id)
624         wpas.wait_connected()
625         wpas.request("DISCONNECT")
626         wpas.wait_disconnected()
627
628         lchannel = "1" if channel != "1" else "6"
629         lfreq3 = "2412" if channel != "1" else "2437"
630         if "OK" not in wpas.request("P2P_SET listen_channel " + lchannel):
631             raise Exception("Failed to set listen channel")
632
633         wpas.select_network(id)
634         wpas.wait_connected()
635         wpas.p2p_listen()
636
637         if "OK" not in dev[0].request("P2P_FLUSH"):
638             raise Exception("P2P_FLUSH failed")
639         if not dev[0].discover_peer(addr5):
640             raise Exception("Could not discover peer")
641         peer = dev[0].get_peer(addr5)
642         lfreq4 = peer['listen_freq']
643         if lfreq4 != lfreq3:
644             raise Exception("Unexpected Listen channel after configuration")
645         wpas.p2p_stop_find()
646         dev[0].p2p_stop_find()
647     finally:
648         wpas.request("SET p2p_optimize_listen_chan 0")
649
650 def test_p2p_channel_5ghz_only(dev):
651     """P2P GO start with only 5 GHz band allowed"""
652     try:
653         set_country("US", dev[0])
654         dev[0].request("P2P_SET disallow_freq 2400-2500")
655         res = autogo(dev[0])
656         freq = int(res['freq'])
657         if freq < 5000:
658             raise Exception("Unexpected channel %d MHz" % freq)
659         dev[0].remove_group()
660     finally:
661         set_country("00")
662         dev[0].request("P2P_SET disallow_freq ")
663
664 def test_p2p_channel_5ghz_165_169_us(dev):
665     """P2P GO and 5 GHz channels 165 (allowed) and 169 (disallowed) in US"""
666     try:
667         set_country("US", dev[0])
668         res = dev[0].p2p_start_go(freq=5825)
669         if res['freq'] != "5825":
670             raise Exception("Unexpected frequency: " + res['freq'])
671         dev[0].remove_group()
672
673         res = dev[0].global_request("P2P_GROUP_ADD freq=5845")
674         if "FAIL" not in res:
675             raise Exception("GO on channel 169 allowed unexpectedly")
676     finally:
677         set_country("00")
678
679 def test_p2p_go_move_reg_change(dev, apdev, params):
680     """P2P GO move due to regulatory change [long]"""
681     if not params['long']:
682         raise HwsimSkip("Skip test case with long duration due to --long not specified")
683
684     try:
685         set_country("US")
686         dev[0].global_request("P2P_SET disallow_freq 2400-5000")
687         res = autogo(dev[0])
688         freq1 = int(res['freq'])
689         if freq1 < 5000:
690             raise Exception("Unexpected channel %d MHz" % freq1)
691
692         dev[0].global_request("P2P_SET disallow_freq ")
693
694         # GO move is not allowed while waiting for initial client connection
695         time.sleep(20)
696         set_country("00")
697         ev = dev[0].wait_group_event(["P2P-REMOVE-AND-REFORM-GROUP",
698                                       "AP-CSA-FINISHED"],
699                                      timeout=10)
700         if ev is None:
701             raise Exception("P2P-REMOVE-AND-REFORM-GROUP or AP-CSA-FINISHED not seen")
702
703         freq2 = dev[0].get_group_status_field('freq')
704         if freq1 == freq2:
705             raise Exception("Unexpected freq after group reform=" + freq2)
706
707         dev[0].remove_group()
708     finally:
709         dev[0].global_request("P2P_SET disallow_freq ")
710         set_country("00")
711
712 def test_p2p_go_move_active(dev, apdev, params):
713     """P2P GO stays in freq although SCM is possible [long]"""
714     if dev[0].get_mcc() <= 1:
715         raise HwsimSkip("Skip due to MCC not being enabled")
716
717     if not params['long']:
718         raise HwsimSkip("Skip test case with long duration due to --long not specified")
719
720     dev[0].request("SET p2p_no_group_iface 0")
721     try:
722         dev[0].global_request("P2P_SET disallow_freq 2430-6000")
723         hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid" : 'ap-test',
724                                                     "channel" : '11' })
725         dev[0].connect("ap-test", key_mgmt="NONE",
726                        scan_freq="2462")
727
728         res = autogo(dev[0])
729         freq = int(res['freq'])
730         if freq > 2430:
731             raise Exception("Unexpected channel %d MHz" % freq)
732
733         # GO move is not allowed while waiting for initial client connection
734         time.sleep(20)
735         dev[0].global_request("P2P_SET disallow_freq ")
736
737         ev = dev[0].wait_group_event(["P2P-REMOVE-AND-REFORM-GROUP",
738                                       "AP-CSA-FINISHED"],
739                                      timeout=10)
740         if ev is not None:
741             raise Exception("Unexpected P2P-REMOVE-AND-REFORM-GROUP or AP-CSA-FINISHED seen")
742
743         dev[0].remove_group()
744     finally:
745         dev[0].global_request("P2P_SET disallow_freq ")
746
747 def test_p2p_go_move_scm(dev, apdev, params):
748     """P2P GO move due to SCM operation preference [long]"""
749     if dev[0].get_mcc() <= 1:
750         raise HwsimSkip("Skip due to MCC not being enabled")
751
752     if not params['long']:
753         raise HwsimSkip("Skip test case with long duration due to --long not specified")
754
755     dev[0].request("SET p2p_no_group_iface 0")
756     try:
757         dev[0].global_request("P2P_SET disallow_freq 2430-6000")
758         hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid" : 'ap-test',
759                                                     "channel" : '11' })
760         dev[0].connect("ap-test", key_mgmt="NONE",
761                        scan_freq="2462")
762
763         dev[0].global_request("SET p2p_go_freq_change_policy 0")
764         res = autogo(dev[0])
765         freq = int(res['freq'])
766         if freq > 2430:
767             raise Exception("Unexpected channel %d MHz" % freq)
768
769         # GO move is not allowed while waiting for initial client connection
770         time.sleep(20)
771         dev[0].global_request("P2P_SET disallow_freq ")
772
773         ev = dev[0].wait_group_event(["P2P-REMOVE-AND-REFORM-GROUP",
774                                       "AP-CSA-FINISHED"], timeout=3)
775         if ev is None:
776             raise Exception("P2P-REMOVE-AND-REFORM-GROUP or AP-CSA-FINISHED not seen")
777
778         freq = dev[0].get_group_status_field('freq')
779         if freq != '2462':
780             raise Exception("Unexpected freq after group reform=" + freq)
781
782         dev[0].remove_group()
783     finally:
784         dev[0].global_request("P2P_SET disallow_freq ")
785         dev[0].global_request("SET p2p_go_freq_change_policy 2")
786
787 def test_p2p_go_move_scm_peer_supports(dev, apdev, params):
788     """P2P GO move due to SCM operation preference (peer supports) [long]"""
789     if dev[0].get_mcc() <= 1:
790         raise HwsimSkip("Skip due to MCC not being enabled")
791
792     if not params['long']:
793         raise HwsimSkip("Skip test case with long duration due to --long not specified")
794
795     try:
796         dev[0].global_request("SET p2p_go_freq_change_policy 1")
797         set_country("US", dev[0])
798
799         dev[0].request("SET p2p_no_group_iface 0")
800         [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
801                                                r_dev=dev[1], r_intent=0,
802                                                test_data=False)
803         check_grpform_results(i_res, r_res)
804         freq = int(i_res['freq'])
805         if freq < 5000:
806             raise Exception("Unexpected channel %d MHz - did not follow 5 GHz preference" % freq)
807
808         hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid" : 'ap-test',
809                                                     "channel" : '11' })
810         logger.info('Connecting client to to an AP on channel 11');
811         dev[0].connect("ap-test", key_mgmt="NONE",
812                        scan_freq="2462")
813
814         ev = dev[0].wait_group_event(["P2P-REMOVE-AND-REFORM-GROUP",
815                                       "AP-CSA-FINISHED"], timeout=3)
816         if ev is None:
817             raise Exception("P2P-REMOVE-AND-REFORM-GROUP or AP-CSA-FINISHED not seen")
818
819         freq = dev[0].get_group_status_field('freq')
820         if freq != '2462':
821             raise Exception("Unexpected freq after group reform=" + freq)
822
823         dev[0].remove_group()
824     finally:
825         dev[0].global_request("SET p2p_go_freq_change_policy 2")
826         set_country("00")
827
828 def test_p2p_go_move_scm_peer_does_not_support(dev, apdev, params):
829     """No P2P GO move due to SCM operation (peer does not supports) [long]"""
830     if dev[0].get_mcc() <= 1:
831         raise HwsimSkip("Skip due to MCC not being enabled")
832
833     if not params['long']:
834         raise HwsimSkip("Skip test case with long duration due to --long not specified")
835
836     try:
837         dev[0].global_request("SET p2p_go_freq_change_policy 1")
838         set_country("US", dev[0])
839
840         dev[0].request("SET p2p_no_group_iface 0")
841         if "OK" not in dev[1].request("DRIVER_EVENT AVOID_FREQUENCIES 2400-2500"):
842             raise Exception("Could not simulate driver event")
843         [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
844                                                r_dev=dev[1], r_intent=0,
845                                                test_data=False)
846         check_grpform_results(i_res, r_res)
847         freq = int(i_res['freq'])
848         if freq < 5000:
849             raise Exception("Unexpected channel %d MHz - did not follow 5 GHz preference" % freq)
850
851         hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid" : 'ap-test',
852                                                     "channel" : '11' })
853         logger.info('Connecting client to to an AP on channel 11');
854         dev[0].connect("ap-test", key_mgmt="NONE",
855                        scan_freq="2462")
856
857         ev = dev[0].wait_group_event(["P2P-REMOVE-AND-REFORM-GROUP",
858                                       "AP-CSA-FINISHED"],
859                                      timeout=10)
860         if ev is not None:
861             raise Exception("Unexpected P2P-REMOVE-AND-REFORM-GROUP or AP-CSA-FINISHED seen")
862
863         dev[0].remove_group()
864     finally:
865         dev[0].global_request("SET p2p_go_freq_change_policy 2")
866         set_country("00")
867
868 def test_p2p_go_move_scm_multi(dev, apdev, params):
869     """P2P GO move due to SCM operation preference multiple times [long]"""
870     if dev[0].get_mcc() <= 1:
871         raise HwsimSkip("Skip due to MCC not being enabled")
872
873     if not params['long']:
874         raise HwsimSkip("Skip test case with long duration due to --long not specified")
875
876     dev[0].request("SET p2p_no_group_iface 0")
877     try:
878         dev[0].global_request("P2P_SET disallow_freq 2430-6000")
879         hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid" : 'ap-test-1',
880                                                     "channel" : '11' })
881         dev[0].connect("ap-test-1", key_mgmt="NONE",
882                        scan_freq="2462")
883
884         dev[0].global_request("SET p2p_go_freq_change_policy 0")
885         res = autogo(dev[0])
886         freq = int(res['freq'])
887         if freq > 2430:
888             raise Exception("Unexpected channel %d MHz" % freq)
889
890         # GO move is not allowed while waiting for initial client connection
891         time.sleep(20)
892         dev[0].global_request("P2P_SET disallow_freq ")
893
894         ev = dev[0].wait_group_event(["P2P-REMOVE-AND-REFORM-GROUP",
895                                       "AP-CSA-FINISHED"], timeout=3)
896         if ev is None:
897             raise Exception("P2P-REMOVE-AND-REFORM-GROUP or AP-CSA-FINISHED not seen")
898
899         freq = dev[0].get_group_status_field('freq')
900         if freq != '2462':
901             raise Exception("Unexpected freq after group reform=" + freq)
902
903         hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid" : 'ap-test-2',
904                                                     "channel" : '6' })
905         dev[0].connect("ap-test-2", key_mgmt="NONE",
906                        scan_freq="2437")
907
908         ev = dev[0].wait_group_event(["P2P-REMOVE-AND-REFORM-GROUP",
909                                       "AP-CSA-FINISHED"], timeout=5)
910         if ev is None:
911             raise Exception("(2) P2P-REMOVE-AND-REFORM-GROUP or AP-CSA-FINISHED not seen")
912
913         freq = dev[0].get_group_status_field('freq')
914         if freq != '2437':
915             raise Exception("(2) Unexpected freq after group reform=" + freq)
916
917         dev[0].remove_group()
918     finally:
919         dev[0].global_request("P2P_SET disallow_freq ")
920         dev[0].global_request("SET p2p_go_freq_change_policy 2")